Elffuss BraidHub

utopia-ia/elffuss-braid public

Merge workspaces: status, commit, land, update and change create

# Conflicts:
#	Cargo.toml
Changesetf548cd6eec4f671bbeefe257750ea1d363b8ca71367e235f9af89e7830e1efe7
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:09 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:09 +02:00
Parents2d05b66297dd, f42277d3e849

Browse the files at this changeset

32 files changed

modified Cargo.lock +375 −8
@@ -2,12 +2,27 @@
22 # It is not intended for manual editing.
33 version = 4
44
5+[[package]]
6+name = "aho-corasick"
7+version = "1.1.5"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
10+dependencies = [
11+ "memchr",
12+]
13+
514 [[package]]
615 name = "allocator-api2"
716 version = "0.2.21"
817 source = "registry+https://github.com/rust-lang/crates.io-index"
918 checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
1019
20+[[package]]
21+name = "ambient-authority"
22+version = "0.0.2"
23+source = "registry+https://github.com/rust-lang/crates.io-index"
24+checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
25+
1126 [[package]]
1227 name = "anstream"
1328 version = "1.0.0"
@@ -44,7 +59,7 @@
4459 source = "registry+https://github.com/rust-lang/crates.io-index"
4560 checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
4661 dependencies = [
47- "windows-sys",
62+ "windows-sys 0.61.2",
4863 ]
4964
5065 [[package]]
@@ -55,7 +70,7 @@
5570 dependencies = [
5671 "anstyle",
5772 "once_cell_polyfill",
58- "windows-sys",
73+ "windows-sys 0.61.2",
5974 ]
6075
6176 [[package]]
@@ -185,6 +200,48 @@
185200 source = "registry+https://github.com/rust-lang/crates.io-index"
186201 checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
187202
203+[[package]]
204+name = "cap-fs-ext"
205+version = "4.0.3"
206+source = "registry+https://github.com/rust-lang/crates.io-index"
207+checksum = "56ff379b70af8e08307a8f65e7040c7301cb4a572538ade16b4984f0da77847f"
208+dependencies = [
209+ "cap-primitives",
210+ "cap-std",
211+ "io-lifetimes 3.0.1",
212+ "windows-sys 0.61.2",
213+]
214+
215+[[package]]
216+name = "cap-primitives"
217+version = "4.0.3"
218+source = "registry+https://github.com/rust-lang/crates.io-index"
219+checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
220+dependencies = [
221+ "ambient-authority",
222+ "fs-set-times",
223+ "io-extras",
224+ "io-lifetimes 3.0.1",
225+ "ipnet",
226+ "maybe-owned",
227+ "rustix",
228+ "rustix-linux-procfs",
229+ "windows-sys 0.61.2",
230+ "winx",
231+]
232+
233+[[package]]
234+name = "cap-std"
235+version = "4.0.3"
236+source = "registry+https://github.com/rust-lang/crates.io-index"
237+checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
238+dependencies = [
239+ "cap-primitives",
240+ "io-extras",
241+ "io-lifetimes 3.0.1",
242+ "rustix",
243+]
244+
188245 [[package]]
189246 name = "cc"
190247 version = "1.8.0"
@@ -323,6 +380,25 @@
323380 "crossbeam-utils",
324381 ]
325382
383+[[package]]
384+name = "crossbeam-deque"
385+version = "0.8.8"
386+source = "registry+https://github.com/rust-lang/crates.io-index"
387+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
388+dependencies = [
389+ "crossbeam-epoch",
390+ "crossbeam-utils",
391+]
392+
393+[[package]]
394+name = "crossbeam-epoch"
395+version = "0.9.21"
396+source = "registry+https://github.com/rust-lang/crates.io-index"
397+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
398+dependencies = [
399+ "crossbeam-utils",
400+]
401+
326402 [[package]]
327403 name = "crossbeam-utils"
328404 version = "0.8.23"
@@ -394,16 +470,24 @@
394470 source = "registry+https://github.com/rust-lang/crates.io-index"
395471 checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
396472
473+[[package]]
474+name = "either"
475+version = "1.19.0"
476+source = "registry+https://github.com/rust-lang/crates.io-index"
477+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
478+
397479 [[package]]
398480 name = "elffuss-braid-cli"
399481 version = "0.0.1"
400482 dependencies = [
401483 "anyhow",
402484 "clap",
485+ "elffuss-braid-engine",
403486 "elffuss-braid-format",
404487 "elffuss-braid-git",
405488 "elffuss-braid-repo",
406489 "elffuss-braid-store",
490+ "elffuss-braid-wc",
407491 "serde_json",
408492 "tempfile",
409493 ]
@@ -475,6 +559,23 @@
475559 "zstd",
476560 ]
477561
562+[[package]]
563+name = "elffuss-braid-wc"
564+version = "0.0.1"
565+dependencies = [
566+ "cap-fs-ext",
567+ "cap-std",
568+ "elffuss-braid-engine",
569+ "elffuss-braid-format",
570+ "elffuss-braid-repo",
571+ "elffuss-braid-store",
572+ "ignore",
573+ "rayon",
574+ "tempfile",
575+ "thiserror",
576+ "unicode-normalization",
577+]
578+
478579 [[package]]
479580 name = "encoding_rs"
480581 version = "0.8.42"
@@ -502,7 +603,7 @@
502603 checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
503604 dependencies = [
504605 "libc",
505- "windows-sys",
606+ "windows-sys 0.61.2",
506607 ]
507608
508609 [[package]]
@@ -547,6 +648,17 @@
547648 source = "registry+https://github.com/rust-lang/crates.io-index"
548649 checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
549650
651+[[package]]
652+name = "fs-set-times"
653+version = "0.20.3"
654+source = "registry+https://github.com/rust-lang/crates.io-index"
655+checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
656+dependencies = [
657+ "io-lifetimes 2.0.4",
658+ "rustix",
659+ "windows-sys 0.59.0",
660+]
661+
550662 [[package]]
551663 name = "getrandom"
552664 version = "0.4.3"
@@ -1060,7 +1172,7 @@
10601172 "bitflags 2.13.2",
10611173 "gix-path",
10621174 "libc",
1063- "windows-sys",
1175+ "windows-sys 0.61.2",
10641176 ]
10651177
10661178 [[package]]
@@ -1086,7 +1198,7 @@
10861198 "libc",
10871199 "parking_lot",
10881200 "tempfile",
1089- "windows-sys",
1201+ "windows-sys 0.61.2",
10901202 ]
10911203
10921204 [[package]]
@@ -1198,6 +1310,19 @@
11981310 "zlib-rs",
11991311 ]
12001312
1313+[[package]]
1314+name = "globset"
1315+version = "0.4.20"
1316+source = "registry+https://github.com/rust-lang/crates.io-index"
1317+checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988"
1318+dependencies = [
1319+ "aho-corasick",
1320+ "bstr",
1321+ "log",
1322+ "regex-automata",
1323+ "regex-syntax",
1324+]
1325+
12011326 [[package]]
12021327 name = "hash32"
12031328 version = "0.3.1"
@@ -1258,6 +1383,22 @@
12581383 "typenum",
12591384 ]
12601385
1386+[[package]]
1387+name = "ignore"
1388+version = "0.4.33"
1389+source = "registry+https://github.com/rust-lang/crates.io-index"
1390+checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f"
1391+dependencies = [
1392+ "crossbeam-deque",
1393+ "globset",
1394+ "log",
1395+ "memchr",
1396+ "regex-automata",
1397+ "same-file",
1398+ "walkdir",
1399+ "winapi-util",
1400+]
1401+
12611402 [[package]]
12621403 name = "imara-diff"
12631404 version = "0.2.0"
@@ -1278,6 +1419,34 @@
12781419 "hashbrown 0.17.1",
12791420 ]
12801421
1422+[[package]]
1423+name = "io-extras"
1424+version = "0.19.0"
1425+source = "registry+https://github.com/rust-lang/crates.io-index"
1426+checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
1427+dependencies = [
1428+ "io-lifetimes 3.0.1",
1429+ "windows-sys 0.60.2",
1430+]
1431+
1432+[[package]]
1433+name = "io-lifetimes"
1434+version = "2.0.4"
1435+source = "registry+https://github.com/rust-lang/crates.io-index"
1436+checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
1437+
1438+[[package]]
1439+name = "io-lifetimes"
1440+version = "3.0.1"
1441+source = "registry+https://github.com/rust-lang/crates.io-index"
1442+checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
1443+
1444+[[package]]
1445+name = "ipnet"
1446+version = "2.12.2"
1447+source = "registry+https://github.com/rust-lang/crates.io-index"
1448+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
1449+
12811450 [[package]]
12821451 name = "is_terminal_polyfill"
12831452 version = "1.70.2"
@@ -1381,6 +1550,12 @@
13811550 source = "registry+https://github.com/rust-lang/crates.io-index"
13821551 checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
13831552
1553+[[package]]
1554+name = "maybe-owned"
1555+version = "0.3.4"
1556+source = "registry+https://github.com/rust-lang/crates.io-index"
1557+checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
1558+
13841559 [[package]]
13851560 name = "memchr"
13861561 version = "2.8.3"
@@ -1572,6 +1747,26 @@
15721747 "rand_core",
15731748 ]
15741749
1750+[[package]]
1751+name = "rayon"
1752+version = "1.12.0"
1753+source = "registry+https://github.com/rust-lang/crates.io-index"
1754+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
1755+dependencies = [
1756+ "either",
1757+ "rayon-core",
1758+]
1759+
1760+[[package]]
1761+name = "rayon-core"
1762+version = "1.13.0"
1763+source = "registry+https://github.com/rust-lang/crates.io-index"
1764+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
1765+dependencies = [
1766+ "crossbeam-deque",
1767+ "crossbeam-utils",
1768+]
1769+
15751770 [[package]]
15761771 name = "redox_syscall"
15771772 version = "0.5.18"
@@ -1586,6 +1781,11 @@
15861781 version = "0.4.18"
15871782 source = "registry+https://github.com/rust-lang/crates.io-index"
15881783 checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
1784+dependencies = [
1785+ "aho-corasick",
1786+ "memchr",
1787+ "regex-syntax",
1788+]
15891789
15901790 [[package]]
15911791 name = "regex-syntax"
@@ -1612,7 +1812,17 @@
16121812 "errno",
16131813 "libc",
16141814 "linux-raw-sys",
1615- "windows-sys",
1815+ "windows-sys 0.61.2",
1816+]
1817+
1818+[[package]]
1819+name = "rustix-linux-procfs"
1820+version = "0.1.1"
1821+source = "registry+https://github.com/rust-lang/crates.io-index"
1822+checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
1823+dependencies = [
1824+ "once_cell",
1825+ "rustix",
16161826 ]
16171827
16181828 [[package]]
@@ -1776,7 +1986,7 @@
17761986 "getrandom",
17771987 "once_cell",
17781988 "rustix",
1779- "windows-sys",
1989+ "windows-sys 0.61.2",
17801990 ]
17811991
17821992 [[package]]
@@ -1899,7 +2109,7 @@
18992109 source = "registry+https://github.com/rust-lang/crates.io-index"
19002110 checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
19012111 dependencies = [
1902- "windows-sys",
2112+ "windows-sys 0.61.2",
19032113 ]
19042114
19052115 [[package]]
@@ -1908,6 +2118,24 @@
19082118 source = "registry+https://github.com/rust-lang/crates.io-index"
19092119 checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
19102120
2121+[[package]]
2122+name = "windows-sys"
2123+version = "0.59.0"
2124+source = "registry+https://github.com/rust-lang/crates.io-index"
2125+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
2126+dependencies = [
2127+ "windows-targets 0.52.6",
2128+]
2129+
2130+[[package]]
2131+name = "windows-sys"
2132+version = "0.60.2"
2133+source = "registry+https://github.com/rust-lang/crates.io-index"
2134+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
2135+dependencies = [
2136+ "windows-targets 0.53.5",
2137+]
2138+
19112139 [[package]]
19122140 name = "windows-sys"
19132141 version = "0.61.2"
@@ -1917,6 +2145,135 @@
19172145 "windows-link",
19182146 ]
19192147
2148+[[package]]
2149+name = "windows-targets"
2150+version = "0.52.6"
2151+source = "registry+https://github.com/rust-lang/crates.io-index"
2152+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
2153+dependencies = [
2154+ "windows_aarch64_gnullvm 0.52.6",
2155+ "windows_aarch64_msvc 0.52.6",
2156+ "windows_i686_gnu 0.52.6",
2157+ "windows_i686_gnullvm 0.52.6",
2158+ "windows_i686_msvc 0.52.6",
2159+ "windows_x86_64_gnu 0.52.6",
2160+ "windows_x86_64_gnullvm 0.52.6",
2161+ "windows_x86_64_msvc 0.52.6",
2162+]
2163+
2164+[[package]]
2165+name = "windows-targets"
2166+version = "0.53.5"
2167+source = "registry+https://github.com/rust-lang/crates.io-index"
2168+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
2169+dependencies = [
2170+ "windows-link",
2171+ "windows_aarch64_gnullvm 0.53.1",
2172+ "windows_aarch64_msvc 0.53.1",
2173+ "windows_i686_gnu 0.53.1",
2174+ "windows_i686_gnullvm 0.53.1",
2175+ "windows_i686_msvc 0.53.1",
2176+ "windows_x86_64_gnu 0.53.1",
2177+ "windows_x86_64_gnullvm 0.53.1",
2178+ "windows_x86_64_msvc 0.53.1",
2179+]
2180+
2181+[[package]]
2182+name = "windows_aarch64_gnullvm"
2183+version = "0.52.6"
2184+source = "registry+https://github.com/rust-lang/crates.io-index"
2185+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
2186+
2187+[[package]]
2188+name = "windows_aarch64_gnullvm"
2189+version = "0.53.1"
2190+source = "registry+https://github.com/rust-lang/crates.io-index"
2191+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
2192+
2193+[[package]]
2194+name = "windows_aarch64_msvc"
2195+version = "0.52.6"
2196+source = "registry+https://github.com/rust-lang/crates.io-index"
2197+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
2198+
2199+[[package]]
2200+name = "windows_aarch64_msvc"
2201+version = "0.53.1"
2202+source = "registry+https://github.com/rust-lang/crates.io-index"
2203+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
2204+
2205+[[package]]
2206+name = "windows_i686_gnu"
2207+version = "0.52.6"
2208+source = "registry+https://github.com/rust-lang/crates.io-index"
2209+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
2210+
2211+[[package]]
2212+name = "windows_i686_gnu"
2213+version = "0.53.1"
2214+source = "registry+https://github.com/rust-lang/crates.io-index"
2215+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
2216+
2217+[[package]]
2218+name = "windows_i686_gnullvm"
2219+version = "0.52.6"
2220+source = "registry+https://github.com/rust-lang/crates.io-index"
2221+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
2222+
2223+[[package]]
2224+name = "windows_i686_gnullvm"
2225+version = "0.53.1"
2226+source = "registry+https://github.com/rust-lang/crates.io-index"
2227+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
2228+
2229+[[package]]
2230+name = "windows_i686_msvc"
2231+version = "0.52.6"
2232+source = "registry+https://github.com/rust-lang/crates.io-index"
2233+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
2234+
2235+[[package]]
2236+name = "windows_i686_msvc"
2237+version = "0.53.1"
2238+source = "registry+https://github.com/rust-lang/crates.io-index"
2239+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
2240+
2241+[[package]]
2242+name = "windows_x86_64_gnu"
2243+version = "0.52.6"
2244+source = "registry+https://github.com/rust-lang/crates.io-index"
2245+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
2246+
2247+[[package]]
2248+name = "windows_x86_64_gnu"
2249+version = "0.53.1"
2250+source = "registry+https://github.com/rust-lang/crates.io-index"
2251+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
2252+
2253+[[package]]
2254+name = "windows_x86_64_gnullvm"
2255+version = "0.52.6"
2256+source = "registry+https://github.com/rust-lang/crates.io-index"
2257+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
2258+
2259+[[package]]
2260+name = "windows_x86_64_gnullvm"
2261+version = "0.53.1"
2262+source = "registry+https://github.com/rust-lang/crates.io-index"
2263+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
2264+
2265+[[package]]
2266+name = "windows_x86_64_msvc"
2267+version = "0.52.6"
2268+source = "registry+https://github.com/rust-lang/crates.io-index"
2269+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
2270+
2271+[[package]]
2272+name = "windows_x86_64_msvc"
2273+version = "0.53.1"
2274+source = "registry+https://github.com/rust-lang/crates.io-index"
2275+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
2276+
19202277 [[package]]
19212278 name = "winnow"
19222279 version = "1.0.4"
@@ -1926,6 +2283,16 @@
19262283 "memchr",
19272284 ]
19282285
2286+[[package]]
2287+name = "winx"
2288+version = "0.36.4"
2289+source = "registry+https://github.com/rust-lang/crates.io-index"
2290+checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
2291+dependencies = [
2292+ "bitflags 2.13.2",
2293+ "windows-sys 0.59.0",
2294+]
2295+
19292296 [[package]]
19302297 name = "zlib-rs"
19312298 version = "0.6.8"
modified Cargo.toml +1 −0
@@ -18,6 +18,7 @@
1818 braid-store = { package = "elffuss-braid-store", path = "crates/store" }
1919 braid-repo = { package = "elffuss-braid-repo", path = "crates/repo" }
2020 braid-git = { package = "elffuss-braid-git", path = "crates/git" }
21+braid-wc = { package = "elffuss-braid-wc", path = "crates/wc" }
2122 anyhow = "1.0"
2223 blake3 = "1.8"
2324 clap = { version = "4.6", features = ["derive", "env"] }
modified README.md +42 −8
@@ -91,8 +91,8 @@
9191
9292 ## Quick start
9393
94-Today braid stores history and moves it in and out of git bit for bit.
95-Workspaces and landing for many agents arrive with milestone 4.
94+Braid stores history, moves it in and out of git bit for bit, and gives each
95+agent a workspace that lands on `main` without waiting for the others.
9696
9797 ```bash
9898 git clone https://github.com/KikoCis/elffuss-braid
@@ -129,6 +129,38 @@
129129 b3sum --derive-key "elffuss-braid 2026 blob v1" README.md
130130 ```
131131
132+### Many agents, one repository
133+
134+Each agent gets its own workspace. There is no staging area and no shared
135+index: an agent commits what it changed and lands it, and braid rebases it
136+onto whatever the others landed first.
137+
138+```bash
139+export BRAID_AUTHOR="Ada Lovelace <ada@example.org>"
140+braid workspace add agent-1 # ./agent-1, tracking main
141+cd agent-1
142+echo 'fn main() {}' > main.rs
143+braid status
144+braid commit -m "Add main.rs"
145+braid land # fast-forward, or a rebase onto main
146+```
147+
148+When two agents change the same lines, the second `land` exits with status 2,
149+prints the conflicts as data (`--json` for agents) and leaves `main` where it
150+was. `braid update` then rebases the change and writes git-style conflict
151+markers; fix the file, `braid commit`, `braid land`.
152+
153+An agent that knows exactly what it changes needs no checkout at all, and can
154+check that nobody changed the file under it:
155+
156+```bash
157+braid change create --base main --set src/lib.rs=@new-lib.rs \
158+ --expect src/lib.rs=<blob id it read> -m "Fix the parser" --land main
159+```
160+
161+New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger than
162+1 MiB are not committed until `braid track <path>` says so.
163+
132164 ## Working with git
133165
134166 Repositories come in with their whole history and keep a git mirror.
@@ -177,9 +209,10 @@
177209
178210 ## What is honest about this
179211
180-- **It is pre-alpha.** Today it stores history and round-trips git
181- repositories, but it has no workspaces yet. Keep your git repository as the
182- source of truth, and do not keep anything only in braid.
212+- **It is pre-alpha.** Today it stores history, round-trips git
213+ repositories, and runs workspaces for many agents on one machine. Keep your
214+ git repository as the source of truth, and do not keep anything only in
215+ braid.
183216 - **No performance claims yet.** When benchmarks land they will be ratios
184217 against git on the same machine, with the script that reproduces them, never
185218 numbers nobody can check.
@@ -240,6 +273,7 @@
240273 Es una implementación independiente, sin código de Anthropic y sin relación con
241274 la empresa.
242275
243-Hoy está en pre-alfa: guarda historia y la mete y saca de git bit a bit, pero aún
244-no tiene espacios de trabajo para agentes. Las [fases](#status-and-roadmap)
245-dicen qué llega después y qué pruebas tiene que pasar cada una.
276+Hoy está en pre-alfa: guarda historia, la mete y saca de git bit a bit, y cada
277+agente tiene su espacio de trabajo y aterriza en `main` sin esperar a los demás.
278+Las [fases](#status-and-roadmap) dicen qué llega después y qué pruebas tiene que
279+pasar cada una.
modified crates/cli/Cargo.toml +2 −0
@@ -14,10 +14,12 @@
1414 path = "src/main.rs"
1515
1616 [dependencies]
17+braid-engine.workspace = true
1718 braid-format.workspace = true
1819 braid-git.workspace = true
1920 braid-repo.workspace = true
2021 braid-store.workspace = true
22+braid-wc.workspace = true
2123 anyhow.workspace = true
2224 clap.workspace = true
2325 serde_json.workspace = true
modified crates/cli/src/main.rs +46 −0
@@ -4,6 +4,7 @@
44 //! `braid`, the command-line tool.
55
66 mod sync;
7+mod work;
78
89 use std::fs::File;
910 use std::io::{self, Read, Write};
@@ -37,6 +38,11 @@
3738 #[arg(long, global = true, env = "BRAID_AGENT", default_value = "cli")]
3839 agent: String,
3940
41+ /// Workspace to act on (default: the one containing the current
42+ /// directory).
43+ #[arg(long, global = true, value_name = "NAME")]
44+ workspace: Option<String>,
45+
4046 #[command(subcommand)]
4147 command: Command,
4248 }
@@ -98,6 +104,38 @@
98104 },
99105 /// Check every record, index, op log entry and ref of the store.
100106 Fsck,
107+ /// Create, list and remove workspaces.
108+ Workspace {
109+ #[command(subcommand)]
110+ action: work::WorkspaceAction,
111+ },
112+ /// Show how the workspace differs from its base and its branch.
113+ Status,
114+ /// Record the workspace's changes as a changeset on its base.
115+ Commit(work::CommitArgs),
116+ /// Land the workspace's changesets on its branch (exit status 2 on
117+ /// conflicts).
118+ Land(work::LandArgs),
119+ /// Bring the workspace onto its branch's head, rebasing its own
120+ /// changesets (exit status 2 on conflicts).
121+ Update(work::IdentityArgs),
122+ /// Mark conflicts of a rebase in progress resolved.
123+ Resolve {
124+ /// Paths whose conflicts are settled.
125+ #[arg(required = true)]
126+ paths: Vec<PathBuf>,
127+ },
128+ /// Let new files that look like secrets or are large be committed.
129+ Track {
130+ /// Files, or directories whose new files may be committed.
131+ #[arg(required = true)]
132+ paths: Vec<PathBuf>,
133+ },
134+ /// Make changesets without a working copy.
135+ Change {
136+ #[command(subcommand)]
137+ action: work::ChangeAction,
138+ },
101139 }
102140
103141 #[derive(Debug, Subcommand)]
@@ -207,6 +245,14 @@
207245 },
208246 } => sync::git_sync(cli, remote, branch, remote_branch.as_deref(), *dry_run),
209247 Command::Fsck => fsck(cli),
248+ Command::Workspace { action } => work::workspace(cli, action),
249+ Command::Status => work::status(cli),
250+ Command::Commit(args) => work::commit(cli, args),
251+ Command::Land(args) => work::land(cli, args),
252+ Command::Update(args) => work::update(cli, args),
253+ Command::Resolve { paths } => work::resolve(cli, paths),
254+ Command::Track { paths } => work::track(cli, paths),
255+ Command::Change { action } => work::change(cli, action),
210256 }
211257 }
212258
added crates/cli/src/work.rs +855 −0
@@ -0,0 +1,855 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Workspace commands: `workspace`, `status`, `commit`, `land`, `update`,
5+//! `resolve`, `track` and `change create`.
6+//!
7+//! Commands that report conflicts exit with status 2, so that an agent can
8+//! tell them from failures (status 1) without parsing anything.
9+
10+use std::ffi::{OsStr, OsString};
11+use std::io::{self, Read, Write};
12+use std::path::{Path, PathBuf};
13+use std::process::ExitCode;
14+
15+use anyhow::{Context, Result, bail};
16+use braid_engine::{Conflict, ConflictKind, HunkSide};
17+use braid_format::{ChangeOp, EntryKind, Kind, ObjectId, Objects};
18+use braid_repo::{Location, Repo};
19+use braid_wc::{
20+ ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, RebaseProgress, Updated,
21+ Workspace,
22+};
23+use clap::{Args, Subcommand};
24+use serde_json::{Value, json};
25+
26+use crate::{Cli, change_json, open_repo, print_json};
27+
28+/// Exit status of a command that stopped on conflicts.
29+const CONFLICTS: u8 = 2;
30+
31+#[derive(Debug, Subcommand)]
32+pub(crate) enum WorkspaceAction {
33+ /// Create a workspace and write its files.
34+ Add {
35+ /// The workspace's name: letters, digits, '.', '_' or '-'.
36+ name: String,
37+ /// Its directory, which must not exist or be empty (default:
38+ /// ./<name>).
39+ path: Option<PathBuf>,
40+ /// The changeset to start at: a ref or a full id (default: the head
41+ /// of the tracked branch, or nothing if it does not exist yet).
42+ #[arg(long, value_name = "REV")]
43+ at: Option<String>,
44+ /// The branch the workspace lands on and updates from.
45+ #[arg(long, value_name = "BRANCH", default_value = "main")]
46+ track: String,
47+ },
48+ /// List the repository's workspaces.
49+ List,
50+ /// Remove a workspace: its directory and its state.
51+ Remove {
52+ /// The workspace's name.
53+ name: String,
54+ /// Remove it even with uncommitted changes, unlanded changesets or
55+ /// a rebase in progress.
56+ #[arg(long)]
57+ force: bool,
58+ },
59+}
60+
61+#[derive(Debug, Args)]
62+pub(crate) struct IdentityArgs {
63+ /// Who records changesets, as "Name <email>" (default: BRAID_AUTHOR,
64+ /// then name and email in .braid/config).
65+ #[arg(long, env = "BRAID_AUTHOR", value_name = "IDENTITY")]
66+ author: Option<String>,
67+}
68+
69+#[derive(Debug, Args)]
70+pub(crate) struct CommitArgs {
71+ /// The message (while a rebase is in progress, the rebased changeset's
72+ /// message by default).
73+ #[arg(short, long)]
74+ message: Option<String>,
75+ /// Commit even if conflict markers remain or conflicts are not marked
76+ /// resolved.
77+ #[arg(long)]
78+ force: bool,
79+ #[command(flatten)]
80+ identity: IdentityArgs,
81+ /// Commit only these files and directories (default: everything).
82+ paths: Vec<PathBuf>,
83+}
84+
85+#[derive(Debug, Args)]
86+pub(crate) struct LandArgs {
87+ /// The branch to land on (default: the workspace's branch).
88+ #[arg(long, value_name = "BRANCH")]
89+ onto: Option<String>,
90+ #[command(flatten)]
91+ identity: IdentityArgs,
92+}
93+
94+#[derive(Debug, Subcommand)]
95+pub(crate) enum ChangeAction {
96+ /// Make a changeset on a base without a working copy, and optionally
97+ /// land it (exit status 2 on conflicts). Prints the ids as JSON.
98+ Create(CreateArgs),
99+}
100+
101+#[derive(Debug, Args)]
102+pub(crate) struct CreateArgs {
103+ /// The changeset to build on: a ref, a full id, or "none" for a first
104+ /// changeset.
105+ #[arg(long, value_name = "REV")]
106+ base: String,
107+ /// Set a file: PATH=@FILE takes the content of FILE, PATH=@- reads
108+ /// standard input. Repeat for several.
109+ #[arg(long = "set", value_name = "PATH=@FILE")]
110+ sets: Vec<OsString>,
111+ /// Delete a file. Repeat for several.
112+ #[arg(long = "delete", value_name = "PATH")]
113+ deletes: Vec<OsString>,
114+ /// Require the base to hold this blob at PATH, or nothing ("absent"),
115+ /// before anything is made. Repeat for several.
116+ #[arg(long = "expect", value_name = "PATH=ID|absent")]
117+ expects: Vec<OsString>,
118+ /// The message.
119+ #[arg(short, long)]
120+ message: String,
121+ /// Land the changeset on this branch.
122+ #[arg(long, value_name = "BRANCH")]
123+ land: Option<String>,
124+ #[command(flatten)]
125+ identity: IdentityArgs,
126+}
127+
128+/// The repository and the workspace a command acts on.
129+struct Target {
130+ repo: Repo,
131+ name: String,
132+ /// Where its `.braid` file was found, when it was found by looking.
133+ dir: Option<PathBuf>,
134+}
135+
136+impl Target {
137+ /// The workspace named by `--workspace`, or the one containing the
138+ /// current directory.
139+ fn find(cli: &Cli) -> Result<Target> {
140+ if let Some(name) = &cli.workspace {
141+ return Ok(Target {
142+ repo: open_repo(cli)?,
143+ name: name.clone(),
144+ dir: None,
145+ });
146+ }
147+ let cwd = std::env::current_dir()?;
148+ match braid_repo::locate(&cwd)? {
149+ Location::Workspace { dir, link } => {
150+ let repo = match &cli.repo {
151+ Some(root) => Repo::open(root)?,
152+ None => Repo::open(&link.repository)?,
153+ };
154+ Ok(Target {
155+ repo,
156+ name: link.name,
157+ dir: Some(dir),
158+ })
159+ }
160+ Location::Root(_) => Err(braid_wc::Error::NotAWorkspace.into()),
161+ }
162+ }
163+
164+ fn open(&self) -> Result<Workspace<'_>> {
165+ Ok(match &self.dir {
166+ Some(dir) => Workspace::at(&self.repo, &self.name, dir)?,
167+ None => Workspace::open(&self.repo, &self.name)?,
168+ })
169+ }
170+}
171+
172+fn identity(args: &IdentityArgs, repo: &Repo) -> Result<Identity> {
173+ Ok(Identity::resolve(args.author.as_deref(), repo)?)
174+}
175+
176+/// Paths given on the command line, as paths of the workspace.
177+fn workspace_paths(workspace: &Workspace<'_>, given: &[PathBuf]) -> Result<Vec<Vec<u8>>> {
178+ let root = std::fs::canonicalize(workspace.dir())
179+ .with_context(|| format!("cannot open {}", workspace.dir().display()))?;
180+ let cwd = std::fs::canonicalize(std::env::current_dir()?)?;
181+ given
182+ .iter()
183+ .map(|path| Ok(braid_wc::workspace_path(&root, &cwd, path)?))
184+ .collect()
185+}
186+
187+fn show(path: &[u8]) -> String {
188+ String::from_utf8_lossy(path).into_owned()
189+}
190+
191+/// `1 path`, `3 paths`.
192+fn count(n: usize, noun: &str) -> String {
193+ if n == 1 {
194+ format!("1 {noun}")
195+ } else {
196+ format!("{n} {noun}s")
197+ }
198+}
199+
200+fn hex(id: Option<ObjectId>) -> Value {
201+ id.map_or(Value::Null, |id| Value::String(id.to_hex()))
202+}
203+
204+fn short(id: Option<ObjectId>) -> String {
205+ id.map_or_else(|| "(none)".to_owned(), |id| id.short())
206+}
207+
208+/// A changeset named by a ref or a full id.
209+fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> {
210+ let id = repo.resolve(revision)?;
211+ match repo.store().stat(&id)? {
212+ Some((Kind::Changeset, _)) => Ok(id),
213+ _ => bail!("{revision} is not a changeset"),
214+ }
215+}
216+
217+pub(crate) fn workspace(cli: &Cli, action: &WorkspaceAction) -> Result<ExitCode> {
218+ match action {
219+ WorkspaceAction::Add {
220+ name,
221+ path,
222+ at,
223+ track,
224+ } => {
225+ let repo = open_repo(cli)?;
226+ let at = match at {
227+ Some(revision) => Some(resolve_changeset(&repo, revision)?),
228+ None => repo.store().refs()?.get(track),
229+ };
230+ let dir = match path {
231+ Some(path) => path.clone(),
232+ None => std::env::current_dir()?.join(name),
233+ };
234+ let (workspace, files) = Workspace::create(&repo, name, &dir, at, track)?;
235+ if cli.json {
236+ print_json(&json!({
237+ "name": workspace.name(),
238+ "path": workspace.dir().to_string_lossy(),
239+ "branch": track,
240+ "base": hex(at),
241+ "files": files,
242+ }))?;
243+ } else {
244+ println!(
245+ "Created workspace {} in {} on {track} at {}, {}",
246+ workspace.name(),
247+ workspace.dir().display(),
248+ short(at),
249+ count(files, "file")
250+ );
251+ }
252+ }
253+ WorkspaceAction::List => {
254+ let repo = open_repo(cli)?;
255+ let all = Workspace::list(&repo)?;
256+ if cli.json {
257+ let items: Vec<Value> = all
258+ .iter()
259+ .map(|(name, state)| {
260+ json!({
261+ "name": name,
262+ "path": state.path.to_string_lossy(),
263+ "branch": state.branch,
264+ "base": hex(state.base),
265+ "rebase": state.rebase.is_some(),
266+ "present": state.path.join(braid_repo::DIR).is_file(),
267+ })
268+ })
269+ .collect();
270+ print_json(&Value::Array(items))?;
271+ } else {
272+ for (name, state) in &all {
273+ println!(
274+ "{name} {} {} {}{}",
275+ state.branch,
276+ short(state.base),
277+ state.path.display(),
278+ if state.rebase.is_some() {
279+ " (rebase in progress)"
280+ } else {
281+ ""
282+ }
283+ );
284+ }
285+ }
286+ }
287+ WorkspaceAction::Remove { name, force } => {
288+ let repo = open_repo(cli)?;
289+ Workspace::remove(&repo, name, *force)?;
290+ if cli.json {
291+ print_json(&json!({ "name": name, "removed": true }))?;
292+ } else {
293+ println!("Removed workspace {name}");
294+ }
295+ }
296+ }
297+ Ok(ExitCode::SUCCESS)
298+}
299+
300+pub(crate) fn status(cli: &Cli) -> Result<ExitCode> {
301+ let target = Target::find(cli)?;
302+ let workspace = target.open()?;
303+ let report = workspace.status()?;
304+ let state = &report.state;
305+ let status = &report.status;
306+ if cli.json {
307+ let by_kind = |kind: braid_wc::ChangeKind| -> Vec<String> {
308+ status
309+ .changes
310+ .iter()
311+ .filter(|change| change.kind == kind)
312+ .map(|change| show(&change.path))
313+ .collect()
314+ };
315+ let rebase = state.rebase.as_ref().map(|rebase| {
316+ json!({
317+ "change": rebase.change.to_hex(),
318+ "onto": rebase.onto.to_hex(),
319+ "pending": rebase.pending.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
320+ "conflicts": report.conflicts.iter().map(|(conflict, remain)| json!({
321+ "path": show(&conflict.path),
322+ "kind": conflict.code,
323+ "markers": conflict.markers,
324+ "markers_remain": remain,
325+ "resolved": conflict.resolved,
326+ })).collect::<Vec<_>>(),
327+ })
328+ });
329+ print_json(&json!({
330+ "workspace": workspace.name(),
331+ "path": workspace.dir().to_string_lossy(),
332+ "branch": state.branch,
333+ "base": hex(state.base),
334+ "head": hex(report.head),
335+ "clean": status.is_clean(),
336+ "unlanded": report.unlanded.iter().map(ObjectId::to_hex).collect::<Vec<_>>(),
337+ "changes": status.changes.iter().map(|change| {
338+ let mut value = change_json(&braid_format::Change {
339+ path: change.path.clone(),
340+ op: change.op.clone(),
341+ });
342+ value["kind"] = Value::String(change.kind.name().to_owned());
343+ value
344+ }).collect::<Vec<_>>(),
345+ "added": by_kind(braid_wc::ChangeKind::Added),
346+ "modified": by_kind(braid_wc::ChangeKind::Modified),
347+ "deleted": by_kind(braid_wc::ChangeKind::Deleted),
348+ "typechanged": by_kind(braid_wc::ChangeKind::TypeChanged),
349+ "needs_track": status.needs_track.iter().map(|p| show(p)).collect::<Vec<_>>(),
350+ "rebase": rebase,
351+ }))?;
352+ return Ok(ExitCode::SUCCESS);
353+ }
354+ let mut out = io::stdout().lock();
355+ writeln!(
356+ out,
357+ "Workspace {} on {}, at {}",
358+ workspace.name(),
359+ state.branch,
360+ short(state.base)
361+ )?;
362+ if !report.unlanded.is_empty() {
363+ writeln!(
364+ out,
365+ "{} not landed on {}",
366+ count(report.unlanded.len(), "changeset"),
367+ state.branch
368+ )?;
369+ } else if report.head.is_some() && report.head != state.base {
370+ writeln!(
371+ out,
372+ "{} has moved on to {}: run `braid update`",
373+ state.branch,
374+ short(report.head)
375+ )?;
376+ }
377+ if let Some(rebase) = &state.rebase {
378+ writeln!(
379+ out,
380+ "Rebase of {} in progress onto {}; resolve, then `braid commit`",
381+ rebase.change.short(),
382+ rebase.onto.short()
383+ )?;
384+ for (conflict, remain) in &report.conflicts {
385+ let note = if conflict.markers {
386+ if *remain { "markers remain" } else { "edited" }
387+ } else if conflict.resolved {
388+ "resolved"
389+ } else {
390+ "run `braid resolve` once settled"
391+ };
392+ writeln!(
393+ out,
394+ " {:<13} {} ({note})",
395+ conflict.code,
396+ show(&conflict.path)
397+ )?;
398+ }
399+ }
400+ if status.is_clean() {
401+ writeln!(out, "Nothing to commit.")?;
402+ } else {
403+ writeln!(out, "Changes:")?;
404+ for change in &status.changes {
405+ writeln!(out, " {:<11} {}", change.kind.name(), show(&change.path))?;
406+ }
407+ }
408+ if !status.needs_track.is_empty() {
409+ writeln!(out, "New files not committed until `braid track <path>`:")?;
410+ for path in &status.needs_track {
411+ writeln!(out, " {}", show(path))?;
412+ }
413+ }
414+ Ok(ExitCode::SUCCESS)
415+}
416+
417+fn progress_json(progress: &RebaseProgress) -> Value {
418+ match progress {
419+ RebaseProgress::None => Value::Null,
420+ RebaseProgress::Finished { tip } => json!({ "outcome": "finished", "tip": tip.to_hex() }),
421+ RebaseProgress::Stopped { change, conflicts } => json!({
422+ "outcome": "conflicts",
423+ "change": change.to_hex(),
424+ "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
425+ }),
426+ }
427+}
428+
429+pub(crate) fn commit(cli: &Cli, args: &CommitArgs) -> Result<ExitCode> {
430+ let target = Target::find(cli)?;
431+ let workspace = target.open()?;
432+ let request = CommitRequest {
433+ message: args.message.as_ref().map(|m| m.as_bytes().to_vec()),
434+ paths: workspace_paths(&workspace, &args.paths)?,
435+ author: None,
436+ committer: identity(&args.identity, &target.repo)?,
437+ force: args.force,
438+ };
439+ let outcome = workspace.commit(&request)?;
440+ let stopped = matches!(outcome.rebase, RebaseProgress::Stopped { .. });
441+ if cli.json {
442+ print_json(&json!({
443+ "changeset": hex(outcome.changeset),
444+ "changes": outcome.changes,
445+ "rebase": progress_json(&outcome.rebase),
446+ }))?;
447+ } else {
448+ match outcome.changeset {
449+ Some(id) => println!(
450+ "Committed {} ({})",
451+ id.short(),
452+ count(outcome.changes, "path")
453+ ),
454+ None => println!("Nothing left to record for this changeset"),
455+ }
456+ match &outcome.rebase {
457+ RebaseProgress::None => {}
458+ RebaseProgress::Finished { tip } => {
459+ println!(
460+ "Rebase finished at {}; `braid land` when ready",
461+ tip.short()
462+ );
463+ }
464+ RebaseProgress::Stopped { change, conflicts } => {
465+ println!("The next changeset, {}, conflicts too:", change.short());
466+ print_conflicts(conflicts);
467+ }
468+ }
469+ }
470+ Ok(if stopped {
471+ ExitCode::from(CONFLICTS)
472+ } else {
473+ ExitCode::SUCCESS
474+ })
475+}
476+
477+/// Prints a landing's report and returns the exit status it calls for.
478+fn report_landing(cli: &Cli, report: &LandReport) -> Result<ExitCode> {
479+ let (outcome, changeset) = match &report.landed {
480+ Landed::Nothing => ("nothing", None),
481+ Landed::FastForward(id) => ("fast-forward", Some(*id)),
482+ Landed::Rebased(id) => ("rebased", Some(*id)),
483+ Landed::AlreadyApplied => ("already-applied", None),
484+ Landed::Conflicts { change, .. } => ("conflicts", Some(*change)),
485+ };
486+ let conflicts: &[Conflict] = match &report.landed {
487+ Landed::Conflicts { conflicts, .. } => conflicts,
488+ _ => &[],
489+ };
490+ if cli.json {
491+ print_json(&json!({
492+ "branch": report.branch,
493+ "outcome": outcome,
494+ "previous": hex(report.previous),
495+ "head": hex(report.head()),
496+ "changeset": hex(changeset),
497+ "operation": report.operation,
498+ "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
499+ }))?;
500+ } else {
501+ match &report.landed {
502+ Landed::Nothing => println!("Nothing to land on {}", report.branch),
503+ Landed::FastForward(id) => {
504+ println!("Landed {} on {} (fast-forward)", id.short(), report.branch);
505+ }
506+ Landed::Rebased(id) => println!(
507+ "Landed on {} as {}, rebased onto {}",
508+ report.branch,
509+ id.short(),
510+ short(report.previous)
511+ ),
512+ Landed::AlreadyApplied => println!("{} already has these changes", report.branch),
513+ Landed::Conflicts { change, conflicts } => {
514+ println!(
515+ "{} conflicts with {} at {}; {} did not move:",
516+ change.short(),
517+ report.branch,
518+ short(report.previous),
519+ report.branch
520+ );
521+ print_conflicts(conflicts);
522+ }
523+ }
524+ }
525+ Ok(if conflicts.is_empty() {
526+ ExitCode::SUCCESS
527+ } else {
528+ ExitCode::from(CONFLICTS)
529+ })
530+}
531+
532+pub(crate) fn land(cli: &Cli, args: &LandArgs) -> Result<ExitCode> {
533+ let target = Target::find(cli)?;
534+ let workspace = target.open()?;
535+ let committer = identity(&args.identity, &target.repo)?;
536+ let report = workspace.land(args.onto.as_deref(), &cli.agent, &committer)?;
537+ report_landing(cli, &report)
538+}
539+
540+pub(crate) fn update(cli: &Cli, args: &IdentityArgs) -> Result<ExitCode> {
541+ let target = Target::find(cli)?;
542+ let workspace = target.open()?;
543+ let committer = identity(args, &target.repo)?;
544+ let updated = workspace.update(&committer)?;
545+ let (outcome, head, base, conflicts): (&str, Option<ObjectId>, Option<ObjectId>, &[Conflict]) =
546+ match &updated {
547+ Updated::UpToDate => ("up-to-date", None, None, &[]),
548+ Updated::Moved { head } => ("moved", Some(*head), Some(*head), &[]),
549+ Updated::Rebased { head, tip } => ("rebased", Some(*head), Some(*tip), &[]),
550+ Updated::Conflicts {
551+ head, conflicts, ..
552+ } => ("conflicts", Some(*head), Some(*head), conflicts),
553+ };
554+ if cli.json {
555+ let change = match &updated {
556+ Updated::Conflicts { change, .. } => Some(*change),
557+ _ => None,
558+ };
559+ print_json(&json!({
560+ "outcome": outcome,
561+ "head": hex(head),
562+ "base": hex(base.or(workspace.state()?.base)),
563+ "change": hex(change),
564+ "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
565+ }))?;
566+ } else {
567+ match &updated {
568+ Updated::UpToDate => println!("Up to date"),
569+ Updated::Moved { head } => println!("Moved to {}", head.short()),
570+ Updated::Rebased { head, tip } => {
571+ println!("Rebased onto {}; now at {}", head.short(), tip.short());
572+ }
573+ Updated::Conflicts {
574+ head,
575+ change,
576+ conflicts,
577+ } => {
578+ println!(
579+ "{} conflicts with {}; the working copy has the merge so far:",
580+ change.short(),
581+ head.short()
582+ );
583+ print_conflicts(conflicts);
584+ println!(
585+ "Fix the files, `braid resolve` the other conflicts, then `braid commit`."
586+ );
587+ }
588+ }
589+ }
590+ Ok(if conflicts.is_empty() {
591+ ExitCode::SUCCESS
592+ } else {
593+ ExitCode::from(CONFLICTS)
594+ })
595+}
596+
597+pub(crate) fn resolve(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> {
598+ let target = Target::find(cli)?;
599+ let workspace = target.open()?;
600+ let paths = workspace_paths(&workspace, paths)?;
601+ let remaining = workspace.resolve(&paths)?;
602+ if cli.json {
603+ print_json(&json!({
604+ "resolved": paths.iter().map(|p| show(p)).collect::<Vec<_>>(),
605+ "remaining": remaining.iter().map(|c| show(&c.path)).collect::<Vec<_>>(),
606+ }))?;
607+ } else if remaining.is_empty() {
608+ println!("Every conflict needing `braid resolve` is resolved");
609+ } else {
610+ println!("Still unresolved:");
611+ for conflict in &remaining {
612+ println!(" {:<13} {}", conflict.code, show(&conflict.path));
613+ }
614+ }
615+ Ok(ExitCode::SUCCESS)
616+}
617+
618+pub(crate) fn track(cli: &Cli, paths: &[PathBuf]) -> Result<ExitCode> {
619+ let target = Target::find(cli)?;
620+ let workspace = target.open()?;
621+ let paths = workspace_paths(&workspace, paths)?;
622+ if paths.iter().any(Vec::is_empty) {
623+ bail!("give files or directories inside the workspace, not its root");
624+ }
625+ let marks = workspace.track(&paths)?;
626+ if cli.json {
627+ print_json(&json!({ "tracked": marks.iter().map(|p| show(p)).collect::<Vec<_>>() }))?;
628+ } else {
629+ for path in &paths {
630+ println!("New files at {} will be committed", show(path));
631+ }
632+ }
633+ Ok(ExitCode::SUCCESS)
634+}
635+
636+/// The bytes of a command-line argument.
637+fn arg_bytes(arg: &OsStr) -> Result<Vec<u8>> {
638+ braid_repo::text::path_bytes(Path::new(arg))
639+ .with_context(|| format!("{} is not valid here", arg.to_string_lossy()))
640+}
641+
642+pub(crate) fn change(cli: &Cli, action: &ChangeAction) -> Result<ExitCode> {
643+ // The output is JSON whether or not `--json` is given.
644+ let ChangeAction::Create(args) = action;
645+ let repo = open_repo(cli)?;
646+ let base = match args.base.as_str() {
647+ "none" => None,
648+ revision => Some(resolve_changeset(&repo, revision)?),
649+ };
650+ let mut stdin_used = false;
651+ let mut sets = Vec::with_capacity(args.sets.len());
652+ for set in &args.sets {
653+ let bytes = arg_bytes(set)?;
654+ let at = bytes
655+ .windows(2)
656+ .position(|pair| pair == b"=@")
657+ .with_context(|| {
658+ format!(
659+ "--set takes PATH=@FILE or PATH=@-, not {}",
660+ set.to_string_lossy()
661+ )
662+ })?;
663+ let (path, source) = (bytes[..at].to_vec(), &bytes[at + 2..]);
664+ let content = if source == b"-" {
665+ if stdin_used {
666+ bail!("only one --set can read standard input");
667+ }
668+ stdin_used = true;
669+ let mut content = Vec::new();
670+ io::stdin()
671+ .lock()
672+ .read_to_end(&mut content)
673+ .context("cannot read standard input")?;
674+ content
675+ } else {
676+ let file = braid_repo::text::path_from_bytes(source).context("invalid file name")?;
677+ std::fs::read(&file).with_context(|| format!("cannot read {}", file.display()))?
678+ };
679+ sets.push((path, content));
680+ }
681+ let deletes = args
682+ .deletes
683+ .iter()
684+ .map(|path| arg_bytes(path))
685+ .collect::<Result<Vec<_>>>()?;
686+ let mut expects = Vec::with_capacity(args.expects.len());
687+ for expect in &args.expects {
688+ let bytes = arg_bytes(expect)?;
689+ let at = bytes
690+ .iter()
691+ .rposition(|byte| *byte == b'=')
692+ .with_context(|| {
693+ format!(
694+ "--expect takes PATH=ID or PATH=absent, not {}",
695+ expect.to_string_lossy()
696+ )
697+ })?;
698+ let value = std::str::from_utf8(&bytes[at + 1..]).unwrap_or("");
699+ let expected = match value {
700+ "absent" => Expect::Absent,
701+ id => Expect::Blob(id.parse().with_context(|| {
702+ format!("--expect needs a full blob id or \"absent\", not {id:?}")
703+ })?),
704+ };
705+ expects.push((bytes[..at].to_vec(), expected));
706+ }
707+ let author = identity(&args.identity, &repo)?;
708+ let request = ChangeRequest {
709+ base,
710+ sets,
711+ deletes,
712+ expects,
713+ message: args.message.as_bytes().to_vec(),
714+ author: author.clone(),
715+ };
716+ let change = braid_wc::create_change(repo.store(), &request)?;
717+ let landing = match &args.land {
718+ Some(branch) => Some(braid_wc::land_change(
719+ repo.store(),
720+ branch,
721+ change,
722+ &cli.agent,
723+ &author,
724+ )?),
725+ None => None,
726+ };
727+ let conflicted = matches!(
728+ landing.as_ref().map(|report| &report.landed),
729+ Some(Landed::Conflicts { .. })
730+ );
731+ // Always JSON: this command is for agents, which want the ids.
732+ let land = match &landing {
733+ Some(report) => landing_json(report),
734+ None => Value::Null,
735+ };
736+ print_json(&json!({
737+ "change": change.to_hex(),
738+ "base": hex(base),
739+ "land": land,
740+ }))?;
741+ Ok(if conflicted {
742+ ExitCode::from(CONFLICTS)
743+ } else {
744+ ExitCode::SUCCESS
745+ })
746+}
747+
748+fn landing_json(report: &LandReport) -> Value {
749+ let outcome = match &report.landed {
750+ Landed::Nothing => "nothing",
751+ Landed::FastForward(_) => "fast-forward",
752+ Landed::Rebased(_) => "rebased",
753+ Landed::AlreadyApplied => "already-applied",
754+ Landed::Conflicts { .. } => "conflicts",
755+ };
756+ let conflicts: &[Conflict] = match &report.landed {
757+ Landed::Conflicts { conflicts, .. } => conflicts,
758+ _ => &[],
759+ };
760+ json!({
761+ "branch": report.branch,
762+ "outcome": outcome,
763+ "previous": hex(report.previous),
764+ "head": hex(report.head()),
765+ "operation": report.operation,
766+ "conflicts": conflicts.iter().map(conflict_json).collect::<Vec<_>>(),
767+ })
768+}
769+
770+fn entry_json(entry: &Option<EntryKind>) -> Value {
771+ match entry {
772+ None => Value::Null,
773+ Some(EntryKind::Tree { tree }) => json!({ "kind": "tree", "tree": tree.to_hex() }),
774+ Some(kind) => match ChangeOp::from_entry(kind) {
775+ Some(op) => {
776+ let mut value = change_json(&braid_format::Change {
777+ path: Vec::new(),
778+ op,
779+ });
780+ if let Some(object) = value.as_object_mut() {
781+ object.remove("path");
782+ if let Some(op) = object.remove("op") {
783+ object.insert("kind".to_owned(), op);
784+ }
785+ }
786+ value
787+ }
788+ None => Value::Null,
789+ },
790+ }
791+}
792+
793+fn side_json(side: &HunkSide) -> Value {
794+ json!({
795+ "start": side.lines.start,
796+ "end": side.lines.end,
797+ "text": String::from_utf8_lossy(&side.text),
798+ })
799+}
800+
801+/// A conflict as data: the path, the kind's code, the entries of the base,
802+/// ours (the branch head) and theirs (the change), and for content
803+/// conflicts the hunks.
804+pub(crate) fn conflict_json(conflict: &Conflict) -> Value {
805+ let mut value = json!({
806+ "path": show(&conflict.path),
807+ "kind": conflict.kind.code(),
808+ "base": entry_json(&conflict.base),
809+ "ours": entry_json(&conflict.ours),
810+ "theirs": entry_json(&conflict.theirs),
811+ "hunks": [],
812+ });
813+ match &conflict.kind {
814+ ConflictKind::Content { hunks } => {
815+ value["hunks"] = hunks
816+ .iter()
817+ .map(|hunk| {
818+ json!({
819+ "base": side_json(&hunk.base),
820+ "ours": side_json(&hunk.ours),
821+ "theirs": side_json(&hunk.theirs),
822+ })
823+ })
824+ .collect();
825+ }
826+ ConflictKind::DirectoryRemoved { directory } => {
827+ value["directory"] = Value::String(show(directory));
828+ }
829+ ConflictKind::Case { existing } => {
830+ value["existing"] = Value::String(show(existing));
831+ }
832+ _ => {}
833+ }
834+ value
835+}
836+
837+fn print_conflicts(conflicts: &[Conflict]) {
838+ for conflict in conflicts {
839+ let detail = match &conflict.kind {
840+ ConflictKind::Content { hunks } if !hunks.is_empty() => {
841+ format!(" ({})", count(hunks.len(), "region"))
842+ }
843+ ConflictKind::DirectoryRemoved { directory } => {
844+ format!(" (directory {} removed)", show(directory))
845+ }
846+ ConflictKind::Case { existing } => format!(" (collides with {})", show(existing)),
847+ _ => String::new(),
848+ };
849+ println!(
850+ " {:<13} {}{detail}",
851+ conflict.kind.code(),
852+ show(&conflict.path)
853+ );
854+ }
855+}
added crates/cli/tests/workspaces.rs +709 −0
@@ -0,0 +1,709 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! End-to-end tests of workspaces: several of them on one repository,
5+//! committing and landing in any order, conflicts, the secrets guard,
6+//! changesets made without a working copy, and many processes at once.
7+
8+use std::collections::{HashMap, HashSet};
9+use std::path::{Path, PathBuf};
10+use std::process::{Command, Output, Stdio};
11+
12+use serde_json::Value;
13+
14+const AUTHOR: &str = "Ada <ada@example.org>";
15+
16+/// A repository in a temporary directory, driven through the binary.
17+struct Repo {
18+ _temp: tempfile::TempDir,
19+ root: PathBuf,
20+}
21+
22+impl Repo {
23+ fn new() -> Repo {
24+ let temp = tempfile::tempdir().unwrap();
25+ // Canonical, so paths compare equal to what braid records.
26+ let base = std::fs::canonicalize(temp.path()).unwrap();
27+ let root = base.join("repo");
28+ let out = braid(&base, &["init", root.to_str().unwrap()]);
29+ assert!(out.status.success(), "{}", stderr(&out));
30+ Repo { _temp: temp, root }
31+ }
32+
33+ /// Creates a workspace next to the repository's own directory.
34+ fn workspace(&self, name: &str) -> PathBuf {
35+ let dir = self.root.parent().unwrap().join(name);
36+ json(
37+ &self.root,
38+ &["workspace", "add", name, dir.to_str().unwrap()],
39+ );
40+ dir
41+ }
42+
43+ fn main(&self) -> Option<String> {
44+ json(&self.root, &["refs"])["refs"]["main"]
45+ .as_str()
46+ .map(str::to_owned)
47+ }
48+
49+ fn fsck_is_clean(&self) -> bool {
50+ json(&self.root, &["fsck"])["clean"] == true
51+ }
52+}
53+
54+/// Runs braid in `dir` with a fixed author and agent.
55+fn braid(dir: &Path, args: &[&str]) -> Output {
56+ Command::new(env!("CARGO_BIN_EXE_braid"))
57+ .current_dir(dir)
58+ .args(args)
59+ .env("BRAID_AUTHOR", AUTHOR)
60+ .env("BRAID_AGENT", "tester")
61+ .output()
62+ .unwrap()
63+}
64+
65+fn stderr(out: &Output) -> String {
66+ String::from_utf8_lossy(&out.stderr).into_owned()
67+}
68+
69+/// Runs braid with `--json`, expecting exit status `code`.
70+fn json_status(dir: &Path, args: &[&str], code: i32) -> Value {
71+ let mut all = args.to_vec();
72+ all.push("--json");
73+ let out = braid(dir, &all);
74+ assert_eq!(
75+ out.status.code(),
76+ Some(code),
77+ "braid {args:?}: {}{}",
78+ String::from_utf8_lossy(&out.stdout),
79+ stderr(&out)
80+ );
81+ serde_json::from_slice(&out.stdout).unwrap()
82+}
83+
84+fn json(dir: &Path, args: &[&str]) -> Value {
85+ json_status(dir, args, 0)
86+}
87+
88+/// Runs braid expecting failure, and returns its error message.
89+fn fails(dir: &Path, args: &[&str]) -> String {
90+ let out = braid(dir, args);
91+ assert_eq!(out.status.code(), Some(1), "braid {args:?} should fail");
92+ stderr(&out)
93+}
94+
95+fn write(dir: &Path, name: &str, content: &str) {
96+ let path = dir.join(name);
97+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
98+ std::fs::write(path, content).unwrap();
99+}
100+
101+fn read(dir: &Path, name: &str) -> String {
102+ std::fs::read_to_string(dir.join(name)).unwrap()
103+}
104+
105+/// Seeds `main` with these files, through `change create`.
106+fn seed(repo: &Repo, files: &[(&str, &str)]) -> String {
107+ let mut args = vec![
108+ "change".to_owned(),
109+ "create".to_owned(),
110+ "--base".to_owned(),
111+ "none".to_owned(),
112+ ];
113+ for (name, content) in files {
114+ let source = repo
115+ .root
116+ .parent()
117+ .unwrap()
118+ .join(format!("seed-{}", name.replace('/', "-")));
119+ std::fs::write(&source, content).unwrap();
120+ args.push("--set".to_owned());
121+ args.push(format!("{name}=@{}", source.display()));
122+ }
123+ args.extend(["-m", "seed", "--land", "main"].map(str::to_owned));
124+ let args: Vec<&str> = args.iter().map(String::as_str).collect();
125+ let out = json(&repo.root, &args);
126+ out["change"].as_str().unwrap().to_owned()
127+}
128+
129+fn status(dir: &Path) -> Value {
130+ json(dir, &["status"])
131+}
132+
133+/// Every changeset on `main`'s first-parent chain, newest first.
134+fn history(repo: &Repo) -> Vec<Value> {
135+ json(&repo.root, &["log", "main", "-n", "100000"])
136+ .as_array()
137+ .unwrap()
138+ .clone()
139+}
140+
141+fn rebased_from(changeset: &Value) -> Option<String> {
142+ changeset["extras"]
143+ .as_array()
144+ .unwrap()
145+ .iter()
146+ .find_map(|pair| (pair[0] == "rebased-from").then(|| pair[1].as_str().unwrap().to_owned()))
147+}
148+
149+#[test]
150+fn disjoint_workspaces_land_in_either_order() {
151+ for a_first in [true, false] {
152+ let repo = Repo::new();
153+ seed(&repo, &[("README.md", "hello\n")]);
154+ let a = repo.workspace("a");
155+ let b = repo.workspace("b");
156+ assert_eq!(read(&a, "README.md"), "hello\n");
157+
158+ write(&a, "src/a.rs", "pub fn a() {}\n");
159+ write(&b, "docs/b.md", "# b\n");
160+ let a_commit = json(&a, &["commit", "-m", "add a"]);
161+ let b_commit = json(&b, &["commit", "-m", "add b"]);
162+ assert_eq!(a_commit["changes"], 1);
163+
164+ let (first, second) = if a_first { (&a, &b) } else { (&b, &a) };
165+ let landed = json(first, &["land"]);
166+ assert_eq!(landed["outcome"], "fast-forward");
167+ let landed = json(second, &["land"]);
168+ assert_eq!(landed["outcome"], "rebased");
169+ assert_eq!(landed["previous"], json(first, &["status"])["base"]);
170+
171+ // Both changes are on main, once each, on a linear history.
172+ let log = history(&repo);
173+ assert_eq!(log.len(), 3);
174+ assert!(
175+ log.iter()
176+ .all(|c| c["parents"].as_array().unwrap().len() <= 1)
177+ );
178+ let originals: HashSet<String> = log[..2]
179+ .iter()
180+ .map(|c| rebased_from(c).unwrap_or_else(|| c["id"].as_str().unwrap().to_owned()))
181+ .collect();
182+ let made: HashSet<String> = [&a_commit, &b_commit]
183+ .iter()
184+ .map(|c| c["changeset"].as_str().unwrap().to_owned())
185+ .collect();
186+ assert_eq!(originals, made);
187+
188+ // The second workspace has both files; the first catches up.
189+ assert_eq!(read(second, "src/a.rs"), "pub fn a() {}\n");
190+ assert_eq!(read(second, "docs/b.md"), "# b\n");
191+ assert_eq!(json(first, &["update"])["outcome"], "moved");
192+ assert_eq!(read(first, "docs/b.md"), "# b\n");
193+ assert_eq!(read(first, "src/a.rs"), "pub fn a() {}\n");
194+ for dir in [&a, &b] {
195+ let now = status(dir);
196+ assert_eq!(now["clean"], true);
197+ assert_eq!(now["base"].as_str(), repo.main().as_deref());
198+ }
199+ assert!(repo.fsck_is_clean());
200+ }
201+}
202+
203+#[test]
204+fn same_lines_conflict_then_resolve() {
205+ let repo = Repo::new();
206+ seed(&repo, &[("shared.txt", "one\ntwo\nthree\n")]);
207+ let a = repo.workspace("a");
208+ let b = repo.workspace("b");
209+ write(&a, "shared.txt", "one\nTWO from a\nthree\n");
210+ write(&b, "shared.txt", "one\nTWO from b\nthree\n");
211+ json(&a, &["commit", "-m", "a's two"]);
212+ json(&b, &["commit", "-m", "b's two"]);
213+ json(&a, &["land"]);
214+ let main_before = repo.main();
215+
216+ // The second landing conflicts: exit status 2, and main does not move.
217+ let landed = json_status(&b, &["land"], 2);
218+ assert_eq!(landed["outcome"], "conflicts");
219+ let conflict = &landed["conflicts"][0];
220+ assert_eq!(conflict["path"], "shared.txt");
221+ assert_eq!(conflict["kind"], "CONTENT");
222+ assert_eq!(conflict["hunks"][0]["ours"]["text"], "TWO from a\n");
223+ assert_eq!(conflict["hunks"][0]["theirs"]["text"], "TWO from b\n");
224+ assert_eq!(conflict["base"]["kind"], "file");
225+ assert_eq!(repo.main(), main_before);
226+
227+ // Update writes the conflict with markers, and a rebase is in progress.
228+ let updated = json_status(&b, &["update"], 2);
229+ assert_eq!(updated["outcome"], "conflicts");
230+ let merged = read(&b, "shared.txt");
231+ assert!(merged.contains("<<<<<<< main"), "{merged}");
232+ assert!(
233+ merged.contains("TWO from a\n=======\nTWO from b\n"),
234+ "{merged}"
235+ );
236+ let now = status(&b);
237+ assert_eq!(now["rebase"]["conflicts"][0]["markers_remain"], true);
238+ assert_eq!(now["base"].as_str(), main_before.as_deref());
239+ // Landing waits for the rebase.
240+ assert!(fails(&b, &["land"]).contains("rebase is in progress"));
241+
242+ // Committing with the markers still there is refused.
243+ let refused = fails(&b, &["commit", "-m", "resolved"]);
244+ assert!(refused.contains("conflict markers remain"), "{refused}");
245+
246+ write(&b, "shared.txt", "one\nTWO from a and b\nthree\n");
247+ let committed = json(&b, &["commit", "-m", "both twos"]);
248+ assert_eq!(committed["rebase"]["outcome"], "finished");
249+ let landed = json(&b, &["land"]);
250+ assert_eq!(landed["outcome"], "fast-forward");
251+ assert_eq!(repo.main().as_deref(), committed["changeset"].as_str());
252+ // The resolution's first parent is a's change, and it names the change
253+ // it resolves.
254+ let log = history(&repo);
255+ assert_eq!(log[0]["parents"][0].as_str(), main_before.as_deref());
256+ assert!(rebased_from(&log[0]).is_some());
257+ assert_eq!(read(&b, "shared.txt"), "one\nTWO from a and b\nthree\n");
258+ assert!(repo.fsck_is_clean());
259+}
260+
261+#[test]
262+fn landing_after_main_moved_rebases_and_follows_the_tree() {
263+ let repo = Repo::new();
264+ seed(&repo, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
265+ let ws = repo.workspace("ws");
266+ // Main moves without this workspace: a disjoint change, made without a
267+ // working copy.
268+ let main = repo.main().unwrap();
269+ let elsewhere = repo.root.parent().unwrap().join("other.txt");
270+ std::fs::write(&elsewhere, "from elsewhere\n").unwrap();
271+ json(
272+ &repo.root,
273+ &[
274+ "change",
275+ "create",
276+ "--base",
277+ &main,
278+ "--set",
279+ &format!("dir/other.txt=@{}", elsewhere.display()),
280+ "--delete",
281+ "b.txt",
282+ "-m",
283+ "elsewhere",
284+ "--land",
285+ "main",
286+ ],
287+ );
288+ write(&ws, "a.txt", "a, edited\n");
289+ let committed = json(&ws, &["commit", "-m", "edit a"]);
290+ let landed = json(&ws, &["land"]);
291+ assert_eq!(landed["outcome"], "rebased");
292+ let head = landed["head"].as_str().unwrap().to_owned();
293+ assert_eq!(repo.main().as_deref(), Some(head.as_str()));
294+ assert_ne!(Some(head.as_str()), committed["changeset"].as_str());
295+
296+ // The working copy is the landed tree: main's change came in, the
297+ // deleted file went away, and nothing is left to commit.
298+ assert_eq!(read(&ws, "dir/other.txt"), "from elsewhere\n");
299+ assert!(!ws.join("b.txt").exists());
300+ assert_eq!(read(&ws, "a.txt"), "a, edited\n");
301+ let now = status(&ws);
302+ assert_eq!(now["clean"], true);
303+ assert_eq!(now["base"].as_str(), Some(head.as_str()));
304+ let show = json(&repo.root, &["show", &head]);
305+ let paths: Vec<&str> = show["changes"]
306+ .as_array()
307+ .unwrap()
308+ .iter()
309+ .map(|c| c["path"].as_str().unwrap())
310+ .collect();
311+ assert_eq!(paths, ["a.txt"]);
312+ assert!(repo.fsck_is_clean());
313+}
314+
315+#[test]
316+fn the_secrets_guard() {
317+ let repo = Repo::new();
318+ seed(&repo, &[("README.md", "hello\n")]);
319+ let ws = repo.workspace("ws");
320+ write(&ws, ".env", "TOKEN=secret\n");
321+ write(&ws, "keys/server.pem", "-----BEGIN-----\n");
322+ write(&ws, "keys/id_ed25519", "private\n");
323+ std::fs::write(ws.join("big.bin"), vec![7u8; (1 << 20) + 1]).unwrap();
324+ write(&ws, "notes.txt", "fine\n");
325+
326+ let now = status(&ws);
327+ assert_eq!(now["added"], serde_json::json!(["notes.txt"]));
328+ assert_eq!(
329+ now["needs_track"],
330+ serde_json::json!([".env", "big.bin", "keys/id_ed25519", "keys/server.pem"])
331+ );
332+ // Only the ordinary file is committed.
333+ let committed = json(&ws, &["commit", "-m", "notes"]);
334+ assert_eq!(committed["changes"], 1);
335+ let show = json(
336+ &repo.root,
337+ &["show", committed["changeset"].as_str().unwrap()],
338+ );
339+ assert_eq!(show["changes"].as_array().unwrap().len(), 1);
340+ // Guarded files are not uncommitted changes: landing goes ahead.
341+ json(&ws, &["land"]);
342+
343+ // Marked, they are committed.
344+ json(&ws, &["track", ".env", "keys"]);
345+ let now = status(&ws);
346+ assert_eq!(now["needs_track"], serde_json::json!(["big.bin"]));
347+ assert_eq!(
348+ now["added"],
349+ serde_json::json!([".env", "keys/id_ed25519", "keys/server.pem"])
350+ );
351+ let committed = json(&ws, &["commit", "-m", "keys"]);
352+ assert_eq!(committed["changes"], 3);
353+ assert_eq!(status(&ws)["needs_track"], serde_json::json!(["big.bin"]));
354+ // Nothing else to commit while only guarded files remain.
355+ assert!(fails(&ws, &["commit", "-m", "nothing"]).contains("nothing to commit"));
356+}
357+
358+#[test]
359+fn change_create_with_expectations() {
360+ let repo = Repo::new();
361+ let seeded = seed(&repo, &[("config.toml", "a = 1\n")]);
362+ let show = json(&repo.root, &["show", &seeded]);
363+ let blob = show["changes"][0]["blob"].as_str().unwrap().to_owned();
364+ let new = repo.root.parent().unwrap().join("new.toml");
365+ std::fs::write(&new, "a = 2\n").unwrap();
366+ let set = format!("config.toml=@{}", new.display());
367+
368+ // The expectation matches: made and landed.
369+ let made = json(
370+ &repo.root,
371+ &[
372+ "change",
373+ "create",
374+ "--base",
375+ "main",
376+ "--set",
377+ &set,
378+ "--expect",
379+ &format!("config.toml={blob}"),
380+ "--expect",
381+ "other.toml=absent",
382+ "-m",
383+ "a is 2",
384+ "--land",
385+ "main",
386+ ],
387+ );
388+ assert_eq!(made["land"]["outcome"], "fast-forward");
389+ assert_eq!(repo.main().as_deref(), made["change"].as_str());
390+
391+ // Another agent, still believing the old content, is stopped before
392+ // anything is made: its base holds another blob now.
393+ let ops = json(&repo.root, &["op", "log"]).as_array().unwrap().len();
394+ let refused = fails(
395+ &repo.root,
396+ &[
397+ "change",
398+ "create",
399+ "--base",
400+ "main",
401+ "--set",
402+ &set,
403+ "--expect",
404+ &format!("config.toml={blob}"),
405+ "-m",
406+ "stale",
407+ "--land",
408+ "main",
409+ ],
410+ );
411+ assert!(refused.contains("expected"), "{refused}");
412+ let refused = fails(
413+ &repo.root,
414+ &[
415+ "change",
416+ "create",
417+ "--base",
418+ "main",
419+ "--set",
420+ &set,
421+ "--expect",
422+ "config.toml=absent",
423+ "-m",
424+ "stale",
425+ ],
426+ );
427+ assert!(refused.contains("absent"), "{refused}");
428+ assert_eq!(repo.main().as_deref(), made["change"].as_str());
429+ assert_eq!(
430+ json(&repo.root, &["op", "log"]).as_array().unwrap().len(),
431+ ops
432+ );
433+
434+ // Built on the old base and landed now, the stale edit conflicts: exit
435+ // status 2, and main stays.
436+ let stale = repo.root.parent().unwrap().join("stale.toml");
437+ std::fs::write(&stale, "a = 3\n").unwrap();
438+ let conflicted = json_status(
439+ &repo.root,
440+ &[
441+ "change",
442+ "create",
443+ "--base",
444+ &seeded,
445+ "--set",
446+ &format!("config.toml=@{}", stale.display()),
447+ "-m",
448+ "a is 3",
449+ "--land",
450+ "main",
451+ ],
452+ 2,
453+ );
454+ assert_eq!(conflicted["land"]["outcome"], "conflicts");
455+ assert_eq!(conflicted["land"]["conflicts"][0]["kind"], "CONTENT");
456+ assert_eq!(repo.main().as_deref(), made["change"].as_str());
457+
458+ // Content from standard input.
459+ let mut child = Command::new(env!("CARGO_BIN_EXE_braid"))
460+ .current_dir(&repo.root)
461+ .args([
462+ "change",
463+ "create",
464+ "--base",
465+ "main",
466+ "--set",
467+ "piped.txt=@-",
468+ "-m",
469+ "piped",
470+ "--json",
471+ ])
472+ .env("BRAID_AUTHOR", AUTHOR)
473+ .stdin(Stdio::piped())
474+ .stdout(Stdio::piped())
475+ .spawn()
476+ .unwrap();
477+ std::io::Write::write_all(&mut child.stdin.take().unwrap(), b"from a pipe\n").unwrap();
478+ let out = child.wait_with_output().unwrap();
479+ assert!(out.status.success());
480+ let piped: Value = serde_json::from_slice(&out.stdout).unwrap();
481+ let shown = json(&repo.root, &["show", piped["change"].as_str().unwrap()]);
482+ assert_eq!(shown["changes"][0]["path"], "piped.txt");
483+ assert_eq!(shown["changes"][0]["size"], 12);
484+ assert!(repo.fsck_is_clean());
485+}
486+
487+#[test]
488+fn removing_a_workspace() {
489+ let repo = Repo::new();
490+ seed(&repo, &[("README.md", "hello\n")]);
491+ let ws = repo.workspace("ws");
492+ write(&ws, "draft.txt", "not committed\n");
493+ let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
494+ assert!(refused.contains("uncommitted changes"), "{refused}");
495+ assert!(ws.join("draft.txt").exists());
496+
497+ // Committed but not landed: still refused.
498+ json(&ws, &["commit", "-m", "draft"]);
499+ let refused = fails(&repo.root, &["workspace", "remove", "ws"]);
500+ assert!(refused.contains("does not have"), "{refused}");
501+
502+ // Landed: removed, directory and all.
503+ json(&ws, &["land"]);
504+ json(&repo.root, &["workspace", "remove", "ws"]);
505+ assert!(!ws.exists());
506+ assert!(
507+ json(&repo.root, &["workspace", "list"])
508+ .as_array()
509+ .unwrap()
510+ .is_empty()
511+ );
512+
513+ // --force removes a dirty one.
514+ let other = repo.workspace("other");
515+ write(&other, "scratch.txt", "x\n");
516+ json(&repo.root, &["workspace", "remove", "other", "--force"]);
517+ assert!(!other.exists());
518+}
519+
520+#[test]
521+fn workspaces_are_found_from_anywhere_inside() {
522+ let repo = Repo::new();
523+ seed(&repo, &[("src/lib.rs", "pub fn f() {}\n")]);
524+ let ws = repo.workspace("ws");
525+ let inside = ws.join("src");
526+ write(&ws, "src/lib.rs", "pub fn g() {}\n");
527+ let now = status(&inside);
528+ assert_eq!(now["workspace"], "ws");
529+ assert_eq!(now["modified"], serde_json::json!(["src/lib.rs"]));
530+ // Paths are relative to the current directory.
531+ write(&ws, "src/new.rs", "x\n");
532+ write(&ws, "top.txt", "y\n");
533+ let committed = json(&inside, &["commit", "-m", "only src", "new.rs", "lib.rs"]);
534+ assert_eq!(committed["changes"], 2);
535+ assert_eq!(status(&ws)["added"], serde_json::json!(["top.txt"]));
536+ // The repository root is not a workspace.
537+ assert!(fails(&repo.root, &["status"]).contains("not inside a workspace"));
538+ // --workspace names one from anywhere in the repository.
539+ assert_eq!(
540+ json(&repo.root, &["status", "--workspace", "ws"])["workspace"],
541+ "ws"
542+ );
543+}
544+
545+#[test]
546+fn stacked_changesets_land_in_order() {
547+ let repo = Repo::new();
548+ seed(&repo, &[("a.txt", "1\n"), ("b.txt", "1\n")]);
549+ let ws = repo.workspace("ws");
550+ let other = repo.workspace("other");
551+ write(&ws, "a.txt", "2\n");
552+ let first = json(&ws, &["commit", "-m", "first"]);
553+ write(&ws, "a.txt", "3\n");
554+ let second = json(&ws, &["commit", "-m", "second"]);
555+ assert_eq!(status(&ws)["unlanded"].as_array().unwrap().len(), 2);
556+ write(&other, "b.txt", "other\n");
557+ json(&other, &["commit", "-m", "other"]);
558+ json(&other, &["land"]);
559+
560+ // Both are rebased onto the other workspace's change, in order.
561+ let landed = json(&ws, &["land"]);
562+ assert_eq!(landed["outcome"], "rebased");
563+ let log = history(&repo);
564+ let messages: Vec<&str> = log.iter().map(|c| c["message"].as_str().unwrap()).collect();
565+ assert_eq!(messages, ["second", "first", "other", "seed"]);
566+ assert_eq!(
567+ rebased_from(&log[0]).as_deref(),
568+ second["changeset"].as_str()
569+ );
570+ assert_eq!(
571+ rebased_from(&log[1]).as_deref(),
572+ first["changeset"].as_str()
573+ );
574+ assert_eq!(read(&ws, "a.txt"), "3\n");
575+ assert_eq!(read(&ws, "b.txt"), "other\n");
576+ assert!(repo.fsck_is_clean());
577+}
578+
579+#[test]
580+fn a_conflict_that_is_not_about_content_needs_resolve() {
581+ let repo = Repo::new();
582+ seed(&repo, &[("gone.txt", "1\n"), ("keep.txt", "k\n")]);
583+ let a = repo.workspace("a");
584+ let b = repo.workspace("b");
585+ std::fs::remove_file(a.join("gone.txt")).unwrap();
586+ json(&a, &["commit", "-m", "delete it"]);
587+ json(&a, &["land"]);
588+ write(&b, "gone.txt", "2\n");
589+ json(&b, &["commit", "-m", "edit it"]);
590+ let updated = json_status(&b, &["update"], 2);
591+ assert_eq!(updated["conflicts"][0]["kind"], "MODIFY_DELETE");
592+ // The head's version stays: deleted.
593+ assert!(!b.join("gone.txt").exists());
594+ let refused = fails(&b, &["commit", "-m", "x"]);
595+ assert!(refused.contains("braid resolve"), "{refused}");
596+ let resolved = json(&b, &["resolve", "gone.txt"]);
597+ assert!(resolved["remaining"].as_array().unwrap().is_empty());
598+ // Keeping the deletion leaves nothing of the change: the rebase ends
599+ // without a changeset.
600+ let committed = json(&b, &["commit"]);
601+ assert!(committed["changeset"].is_null());
602+ assert_eq!(committed["rebase"]["outcome"], "finished");
603+ assert_eq!(status(&b)["base"].as_str(), repo.main().as_deref());
604+ assert_eq!(json(&b, &["land"])["outcome"], "nothing");
605+}
606+
607+/// Eight processes, each with its own workspace, edit their own file and
608+/// their own line of a shared file, commit and land, round after round,
609+/// all at once. Afterwards every change is on main exactly once, main's
610+/// history is linear, and the store is clean.
611+#[test]
612+fn eight_agents_land_at_once() {
613+ const AGENTS: usize = 8;
614+ const ROUNDS: usize = 4;
615+ let repo = Repo::new();
616+ // One line per agent, with two untouched lines between them, so that
617+ // edits to different agents' lines merge.
618+ let shared: String = (0..AGENTS)
619+ .map(|i| format!("agent {i}: start\n--\n--\n"))
620+ .collect();
621+ seed(&repo, &[("shared.txt", &shared)]);
622+ let dirs: Vec<PathBuf> = (0..AGENTS)
623+ .map(|i| repo.workspace(&format!("agent-{i}")))
624+ .collect();
625+
626+ let made: Vec<Vec<String>> = std::thread::scope(|scope| {
627+ let handles: Vec<_> = dirs
628+ .iter()
629+ .enumerate()
630+ .map(|(i, dir)| {
631+ scope.spawn(move || {
632+ let mut commits = Vec::new();
633+ for round in 0..ROUNDS {
634+ write(
635+ dir,
636+ &format!("own-{i}.txt"),
637+ &format!("agent {i} round {round}\n"),
638+ );
639+ let text = read(dir, "shared.txt");
640+ let lines: Vec<String> = text
641+ .lines()
642+ .enumerate()
643+ .map(|(n, line)| {
644+ if n == i * 3 {
645+ format!("agent {i}: round {round}")
646+ } else {
647+ line.to_owned()
648+ }
649+ })
650+ .collect();
651+ write(dir, "shared.txt", &(lines.join("\n") + "\n"));
652+ let committed =
653+ json(dir, &["commit", "-m", &format!("agent {i} round {round}")]);
654+ commits.push(committed["changeset"].as_str().unwrap().to_owned());
655+ loop {
656+ let out = braid(dir, &["land", "--json"]);
657+ match out.status.code() {
658+ Some(0) => break,
659+ Some(2) => {
660+ // Someone else's change got in the way:
661+ // rebase onto it and try again.
662+ json(dir, &["update"]);
663+ }
664+ _ => panic!("land failed: {}", stderr(&out)),
665+ }
666+ }
667+ }
668+ commits
669+ })
670+ })
671+ .collect();
672+ handles.into_iter().map(|h| h.join().unwrap()).collect()
673+ });
674+
675+ // Every changeset on main maps back to one of the changesets made,
676+ // through the rebases it went through.
677+ let log = history(&repo);
678+ assert_eq!(log.len(), AGENTS * ROUNDS + 1);
679+ let mut seen = HashMap::new();
680+ for changeset in &log[..log.len() - 1] {
681+ assert_eq!(changeset["parents"].as_array().unwrap().len(), 1, "a merge");
682+ let mut id = changeset["id"].as_str().unwrap().to_owned();
683+ let mut current = changeset.clone();
684+ while let Some(from) = rebased_from(&current) {
685+ current = json(&repo.root, &["show", &from]);
686+ id = from;
687+ }
688+ *seen.entry(id).or_insert(0) += 1;
689+ }
690+ let all: HashSet<String> = made.iter().flatten().cloned().collect();
691+ assert_eq!(all.len(), AGENTS * ROUNDS);
692+ assert_eq!(seen.keys().cloned().collect::<HashSet<_>>(), all);
693+ assert!(seen.values().all(|count| *count == 1), "{seen:?}");
694+
695+ // A fresh workspace has every agent's last round.
696+ let check = repo.workspace("check");
697+ let text = read(&check, "shared.txt");
698+ for i in 0..AGENTS {
699+ assert_eq!(
700+ read(&check, &format!("own-{i}.txt")),
701+ format!("agent {i} round {}\n", ROUNDS - 1)
702+ );
703+ assert!(
704+ text.contains(&format!("agent {i}: round {}\n", ROUNDS - 1)),
705+ "{text}"
706+ );
707+ }
708+ assert!(repo.fsck_is_clean());
709+}
modified crates/repo/src/lib.rs +53 −7
@@ -9,13 +9,19 @@
99 //! workspace of the repository, `git/` holds the mirrors of the git remotes
1010 //! that [`Repo::git_sync`] keeps in step with, and the optional `config` file
1111 //! holds settings (see [`Config`]).
12+//!
13+//! A workspace is any directory holding a `.braid` *file* instead: a
14+//! [`WorkspaceLink`] naming the repository and the workspace. [`locate`] and
15+//! [`Repo::discover`] find the repository from inside either.
1216
1317 #![forbid(unsafe_code)]
1418
1519 mod config;
1620 mod git;
21+mod link;
1722 mod remote;
1823 mod sync;
24+pub mod text;
1925
2026 use std::fs;
2127 use std::io;
@@ -30,6 +36,7 @@
3036 GIT_EXPORT_AGENT, GitImport, MAP_REF, REMOTE_PREFIX, braid_ref_for_git, git_ref_for_braid,
3137 remote_ref,
3238 };
39+pub use link::{Location, WORKSPACES_DIR, WorkspaceLink, locate};
3340 pub use remote::Remote;
3441 pub use sync::{MIRRORS_DIR, SyncOptions, SyncOutcome, SyncReport};
3542
@@ -43,9 +50,18 @@
4350 #[derive(Debug, thiserror::Error)]
4451 #[non_exhaustive]
4552 pub enum Error {
46- /// No `.braid` directory in the starting directory or any parent.
53+ /// No `.braid` directory or workspace file in the starting directory or
54+ /// any parent.
4755 #[error("not inside a braid repository")]
4856 NotFound,
57+ /// A workspace's `.braid` file cannot be read.
58+ #[error("{}: not a valid workspace file: {detail}", .path.display())]
59+ BadWorkspaceFile {
60+ /// The file.
61+ path: PathBuf,
62+ /// What is wrong with it.
63+ detail: String,
64+ },
4965 /// `init` on a directory that already holds a repository.
5066 #[error("a braid repository already exists here")]
5167 AlreadyExists,
@@ -177,14 +193,13 @@
177193 }
178194
179195 /// Opens the repository that contains `start`: `start` itself or the
180- /// nearest parent with a `.braid` directory.
196+ /// nearest parent with a `.braid` directory, or the repository named by
197+ /// the `.braid` file of the workspace that contains `start`.
181198 pub fn discover(start: &Path) -> Result<Repo, Error> {
182- for dir in start.ancestors() {
183- if dir.join(DIR).join(STORE_DIR).is_dir() {
184- return Repo::open(dir);
185- }
199+ match locate(start)? {
200+ Location::Root(dir) => Repo::open(&dir),
201+ Location::Workspace { link, .. } => Repo::open(&link.repository),
186202 }
187- Err(Error::NotFound)
188203 }
189204
190205 /// The directory that holds `.braid`.
@@ -252,4 +267,35 @@
252267 Err(Error::NotFound)
253268 ));
254269 }
270+
271+ #[test]
272+ fn discover_through_a_workspace_file() {
273+ let repo_dir = tempfile::tempdir().unwrap();
274+ Repo::init(repo_dir.path()).unwrap();
275+ let elsewhere = tempfile::tempdir().unwrap();
276+ let workspace = elsewhere.path().join("agent-1");
277+ fs::create_dir_all(workspace.join("src/deep")).unwrap();
278+ let link = WorkspaceLink {
279+ repository: repo_dir.path().to_path_buf(),
280+ name: "agent-1".to_owned(),
281+ };
282+ fs::write(workspace.join(DIR), link.encode()).unwrap();
283+
284+ let found = Repo::discover(&workspace.join("src/deep")).unwrap();
285+ assert_eq!(found.root(), repo_dir.path());
286+ match locate(&workspace.join("src")).unwrap() {
287+ Location::Workspace { dir, link: read } => {
288+ assert_eq!(dir, workspace);
289+ assert_eq!(read, link);
290+ }
291+ other => panic!("expected a workspace, got {other:?}"),
292+ }
293+
294+ // A damaged file is an error, not a reason to keep looking.
295+ fs::write(workspace.join(DIR), b"something else\n").unwrap();
296+ assert!(matches!(
297+ Repo::discover(&workspace),
298+ Err(Error::BadWorkspaceFile { .. })
299+ ));
300+ }
255301 }
added crates/repo/src/link.rs +194 −0
@@ -0,0 +1,194 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Finding the repository from a repository root or from a workspace.
5+//!
6+//! A workspace directory holds a `.braid` file, never tracked, that names its
7+//! repository and the workspace:
8+//!
9+//! ```text
10+//! braid-workspace 1
11+//! name agent-1
12+//! repository /absolute/path/of/the/repository
13+//! ```
14+//!
15+//! Values are written with [`escape`](crate::text::escape), so any path fits.
16+//! The workspace's own state lives in the repository, under
17+//! `.braid/ws/<name>/`.
18+
19+use std::fs;
20+use std::io;
21+use std::path::{Path, PathBuf};
22+
23+use crate::text::{escape, path_bytes, path_from_bytes, unescape};
24+use crate::{DIR, Error, STORE_DIR};
25+
26+/// Directory inside `.braid` that holds one directory of state per
27+/// workspace.
28+pub const WORKSPACES_DIR: &str = "ws";
29+
30+/// The first line of a workspace file.
31+const HEADER: &str = "braid-workspace 1";
32+
33+/// What a workspace's `.braid` file records.
34+#[derive(Clone, Debug, PartialEq, Eq)]
35+pub struct WorkspaceLink {
36+ /// The repository's root directory: absolute, so that the workspace can
37+ /// be anywhere.
38+ pub repository: PathBuf,
39+ /// The workspace's name; see [`WorkspaceLink::is_valid_name`].
40+ pub name: String,
41+}
42+
43+impl WorkspaceLink {
44+ /// Whether `name` can name a workspace: 1 to 64 ASCII letters, digits,
45+ /// `.`, `_` or `-`, starting with a letter or a digit. Names are used as
46+ /// directory names inside the repository, so nothing else is accepted.
47+ pub fn is_valid_name(name: &str) -> bool {
48+ let bytes = name.as_bytes();
49+ !bytes.is_empty()
50+ && bytes.len() <= 64
51+ && bytes[0].is_ascii_alphanumeric()
52+ && bytes
53+ .iter()
54+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
55+ }
56+
57+ /// The file's contents.
58+ pub fn encode(&self) -> Vec<u8> {
59+ let repository = path_bytes(&self.repository).unwrap_or_default();
60+ format!(
61+ "{HEADER}\nname {}\nrepository {}\n",
62+ escape(self.name.as_bytes()),
63+ escape(&repository)
64+ )
65+ .into_bytes()
66+ }
67+
68+ /// Reads the contents of a workspace file.
69+ pub fn decode(bytes: &[u8]) -> Result<Self, String> {
70+ let text = std::str::from_utf8(bytes).map_err(|_| "not UTF-8".to_owned())?;
71+ let mut lines = text.lines();
72+ if lines.next() != Some(HEADER) {
73+ return Err(format!("the first line is not {HEADER:?}"));
74+ }
75+ let mut name = None;
76+ let mut repository = None;
77+ for line in lines {
78+ let (key, value) = line.split_once(' ').unwrap_or((line, ""));
79+ let value = unescape(value).ok_or_else(|| format!("bad escape in {key:?}"))?;
80+ match key {
81+ "name" => name = Some(value),
82+ "repository" => repository = Some(value),
83+ // Later versions may add lines; this one ignores them.
84+ _ => {}
85+ }
86+ }
87+ let name = name
88+ .and_then(|name| String::from_utf8(name).ok())
89+ .filter(|name| Self::is_valid_name(name))
90+ .ok_or("no valid workspace name")?;
91+ let repository = repository
92+ .and_then(|bytes| path_from_bytes(&bytes))
93+ .filter(|path| path.is_absolute())
94+ .ok_or("no absolute repository path")?;
95+ Ok(WorkspaceLink { repository, name })
96+ }
97+
98+ /// Reads the workspace file at `path`.
99+ pub fn read(path: &Path) -> Result<Self, Error> {
100+ let bytes = fs::read(path)?;
101+ Self::decode(&bytes).map_err(|detail| Error::BadWorkspaceFile {
102+ path: path.to_path_buf(),
103+ detail,
104+ })
105+ }
106+}
107+
108+/// Where a search for a repository stopped.
109+#[derive(Clone, Debug, PartialEq, Eq)]
110+pub enum Location {
111+ /// A repository root: a directory holding a `.braid` directory.
112+ Root(PathBuf),
113+ /// A workspace: a directory holding a `.braid` file.
114+ Workspace {
115+ /// The workspace directory.
116+ dir: PathBuf,
117+ /// What its `.braid` file says.
118+ link: WorkspaceLink,
119+ },
120+}
121+
122+/// Finds the nearest directory, `start` or one of its parents, that is a
123+/// repository root or a workspace.
124+///
125+/// A `.braid` directory counts only when it holds a store. A `.braid` file
126+/// must be a regular file, not a symlink, and must be valid: a damaged one
127+/// is an error rather than a reason to keep looking further up.
128+pub fn locate(start: &Path) -> Result<Location, Error> {
129+ for dir in start.ancestors() {
130+ let marker = dir.join(DIR);
131+ if marker.join(STORE_DIR).is_dir() {
132+ return Ok(Location::Root(dir.to_path_buf()));
133+ }
134+ match fs::symlink_metadata(&marker) {
135+ Ok(meta) if meta.is_file() => {
136+ let link = WorkspaceLink::read(&marker)?;
137+ return Ok(Location::Workspace {
138+ dir: dir.to_path_buf(),
139+ link,
140+ });
141+ }
142+ Ok(_) => {}
143+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}
144+ Err(err) => return Err(err.into()),
145+ }
146+ }
147+ Err(Error::NotFound)
148+}
149+
150+#[cfg(test)]
151+mod tests {
152+ use super::*;
153+
154+ #[test]
155+ fn names() {
156+ for good in ["a", "agent-1", "A.b_c", "0"] {
157+ assert!(WorkspaceLink::is_valid_name(good), "{good}");
158+ }
159+ for bad in [
160+ "",
161+ ".",
162+ "..",
163+ ".hidden",
164+ "-x",
165+ "a/b",
166+ "a b",
167+ "é",
168+ &"x".repeat(65),
169+ ] {
170+ assert!(!WorkspaceLink::is_valid_name(bad), "{bad}");
171+ }
172+ }
173+
174+ #[test]
175+ fn links_round_trip() {
176+ let link = WorkspaceLink {
177+ repository: PathBuf::from("/srv/repos/with space/and%percent"),
178+ name: "agent-7".to_owned(),
179+ };
180+ let bytes = link.encode();
181+ assert!(bytes.starts_with(HEADER.as_bytes()));
182+ assert_eq!(WorkspaceLink::decode(&bytes).unwrap(), link);
183+
184+ for bad in [
185+ &b""[..],
186+ b"braid-workspace 2\nname a\nrepository /r\n",
187+ b"braid-workspace 1\nname ../x\nrepository /r\n",
188+ b"braid-workspace 1\nname a\nrepository relative\n",
189+ b"braid-workspace 1\nname a\n",
190+ ] {
191+ assert!(WorkspaceLink::decode(bad).is_err(), "{bad:?}");
192+ }
193+ }
194+}
added crates/repo/src/text.rs +117 −0
@@ -0,0 +1,117 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Byte strings in braid's small text files.
5+//!
6+//! Paths are bytes, not text, but the files that record a workspace are
7+//! meant to be read by people too. A value is written with every byte
8+//! outside printable ASCII, and `%` itself, as `%` and two uppercase hex
9+//! digits, so any byte string fits on one line and reads back exactly.
10+
11+use std::path::{Path, PathBuf};
12+
13+/// The text form of `bytes`: printable ASCII as it is, any other byte and
14+/// `%` as `%XX`.
15+pub fn escape(bytes: &[u8]) -> String {
16+ let mut text = String::with_capacity(bytes.len());
17+ for &byte in bytes {
18+ if (0x20..0x7f).contains(&byte) && byte != b'%' {
19+ text.push(char::from(byte));
20+ } else {
21+ text.push('%');
22+ text.push(char::from(b"0123456789ABCDEF"[usize::from(byte >> 4)]));
23+ text.push(char::from(b"0123456789ABCDEF"[usize::from(byte & 0x0f)]));
24+ }
25+ }
26+ text
27+}
28+
29+/// The bytes that [`escape`] wrote as `text`, or `None` if `text` is not
30+/// such a form: a `%` not followed by two hex digits, or a byte that should
31+/// have been escaped.
32+pub fn unescape(text: &str) -> Option<Vec<u8>> {
33+ let bytes = text.as_bytes();
34+ let mut out = Vec::with_capacity(bytes.len());
35+ let mut i = 0;
36+ while i < bytes.len() {
37+ let byte = bytes[i];
38+ if byte == b'%' {
39+ let high = hex_value(*bytes.get(i + 1)?)?;
40+ let low = hex_value(*bytes.get(i + 2)?)?;
41+ out.push((high << 4) | low);
42+ i += 3;
43+ } else if (0x20..0x7f).contains(&byte) {
44+ out.push(byte);
45+ i += 1;
46+ } else {
47+ return None;
48+ }
49+ }
50+ Some(out)
51+}
52+
53+fn hex_value(digit: u8) -> Option<u8> {
54+ match digit {
55+ b'0'..=b'9' => Some(digit - b'0'),
56+ b'A'..=b'F' => Some(digit - b'A' + 10),
57+ b'a'..=b'f' => Some(digit - b'a' + 10),
58+ _ => None,
59+ }
60+}
61+
62+/// The bytes of a path as the operating system stores it. On systems where
63+/// paths are not byte strings, only paths that are valid Unicode have bytes.
64+pub fn path_bytes(path: &Path) -> Option<Vec<u8>> {
65+ #[cfg(unix)]
66+ {
67+ use std::os::unix::ffi::OsStrExt;
68+ Some(path.as_os_str().as_bytes().to_vec())
69+ }
70+ #[cfg(not(unix))]
71+ {
72+ path.to_str().map(|text| text.as_bytes().to_vec())
73+ }
74+}
75+
76+/// The path whose bytes are `bytes`, the inverse of [`path_bytes`].
77+pub fn path_from_bytes(bytes: &[u8]) -> Option<PathBuf> {
78+ #[cfg(unix)]
79+ {
80+ use std::os::unix::ffi::OsStrExt;
81+ Some(PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
82+ }
83+ #[cfg(not(unix))]
84+ {
85+ std::str::from_utf8(bytes).ok().map(PathBuf::from)
86+ }
87+}
88+
89+#[cfg(test)]
90+mod tests {
91+ use super::*;
92+
93+ #[test]
94+ fn escaping_round_trips_every_byte() {
95+ let all: Vec<u8> = (0..=255).collect();
96+ let text = escape(&all);
97+ assert!(text.bytes().all(|byte| (0x20..0x7f).contains(&byte)));
98+ assert_eq!(unescape(&text).unwrap(), all);
99+ assert_eq!(escape(b"a b/c.txt"), "a b/c.txt");
100+ assert_eq!(escape(b"100%\n"), "100%25%0A");
101+ assert_eq!(unescape("caf%C3%a9").unwrap(), "caf\u{e9}".as_bytes());
102+ }
103+
104+ #[test]
105+ fn malformed_escapes_are_refused() {
106+ for bad in ["%", "%4", "%zz", "tab\there", "caf\u{e9}"] {
107+ assert_eq!(unescape(bad), None, "{bad:?}");
108+ }
109+ }
110+
111+ #[test]
112+ fn paths_round_trip() {
113+ let path = Path::new("dir/sub dir/file.txt");
114+ let bytes = path_bytes(path).unwrap();
115+ assert_eq!(path_from_bytes(&bytes).unwrap(), path);
116+ }
117+}
added crates/wc/Cargo.toml +31 −0
@@ -0,0 +1,31 @@
1+[package]
2+name = "elffuss-braid-wc"
3+description = "Workspaces of elffuss-braid: safe checkouts, status, commit, land and update."
4+version.workspace = true
5+edition.workspace = true
6+rust-version.workspace = true
7+license.workspace = true
8+repository.workspace = true
9+homepage.workspace = true
10+publish.workspace = true
11+
12+[lib]
13+name = "braid_wc"
14+
15+[dependencies]
16+braid-engine.workspace = true
17+braid-format.workspace = true
18+braid-repo.workspace = true
19+braid-store.workspace = true
20+cap-std = "4.0.3"
21+cap-fs-ext = "4.0.3"
22+ignore = "0.4.33"
23+rayon = "1.12.0"
24+thiserror = "2.0"
25+unicode-normalization = "0.1.25"
26+
27+[dev-dependencies]
28+tempfile = "3"
29+
30+[lints]
31+workspace = true
added crates/wc/src/cache.rs +251 −0
@@ -0,0 +1,251 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! The stat cache: what each file of the working copy hashed to, and the
5+//! metadata it had then, so that unchanged files are not read again.
6+//!
7+//! An entry is used only when the file's modification time, size, inode
8+//! number and type are all still the same, and its modification time is
9+//! strictly older than the time the cache's scan started, read from the
10+//! workspace's own file system. A file written in the same instant as the
11+//! scan, or later, may have changed without its metadata showing it, so it
12+//! is hashed again.
13+//!
14+//! ```text
15+//! [8] "braidwsc" | u32 version = 1 | u32 0
16+//! sv seconds | uv nanoseconds when the scan started
17+//! uv n | n × entry, paths strictly ascending
18+//! [32] BLAKE3 (the derived-object context) of everything before it
19+//!
20+//! entry: bytes path | sv mtime seconds | uv mtime nanoseconds | uv size
21+//! uv inode | u8 kind (0 file, 1 executable, 2 symlink) | [32] blob
22+//! ```
23+//!
24+//! The cache is only a cache: if it is missing or damaged, everything is
25+//! hashed again.
26+
27+use std::collections::HashMap;
28+use std::fs;
29+use std::io::Write;
30+use std::path::Path;
31+
32+use braid_format::codec::{Reader, put_bytes, put_id, put_sv, put_uv};
33+use braid_format::{DecodeError, Kind, ObjectId};
34+
35+use crate::error::Error;
36+use crate::fsprobe::random_hex;
37+use crate::safe::{Stat, StatKind};
38+
39+const MAGIC: &[u8; 8] = b"braidwsc";
40+const VERSION: u32 = 1;
41+
42+/// The file the cache lives in, inside the workspace's state directory.
43+pub(crate) const FILE: &str = "stat";
44+
45+/// What a file was when it was hashed.
46+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47+pub(crate) struct Entry {
48+ pub mtime: (i64, u32),
49+ pub size: u64,
50+ pub ino: u64,
51+ /// 0 regular file, 1 executable, 2 symlink.
52+ pub kind: u8,
53+ pub blob: ObjectId,
54+}
55+
56+impl Entry {
57+ /// The entry for a file with this metadata and blob, or `None` for
58+ /// something that is not a file or a symlink.
59+ pub(crate) fn new(stat: &Stat, blob: ObjectId) -> Option<Entry> {
60+ Some(Entry {
61+ mtime: stat.mtime,
62+ size: stat.size,
63+ ino: stat.ino,
64+ kind: kind_code(stat)?,
65+ blob,
66+ })
67+ }
68+}
69+
70+fn kind_code(stat: &Stat) -> Option<u8> {
71+ match stat.kind {
72+ StatKind::File if stat.executable => Some(1),
73+ StatKind::File => Some(0),
74+ StatKind::Symlink => Some(2),
75+ StatKind::Dir | StatKind::Other => None,
76+ }
77+}
78+
79+/// The cache of one workspace.
80+#[derive(Clone, Debug, Default, PartialEq, Eq)]
81+pub(crate) struct Cache {
82+ /// When the scan that wrote it started, by the file system's clock.
83+ pub time: (i64, u32),
84+ pub entries: HashMap<Vec<u8>, Entry>,
85+}
86+
87+impl Cache {
88+ /// The cache in `state_dir`, or an empty one if there is none or it is
89+ /// damaged.
90+ pub(crate) fn load(state_dir: &Path) -> Cache {
91+ fs::read(state_dir.join(FILE))
92+ .ok()
93+ .and_then(|bytes| decode(&bytes).ok())
94+ .unwrap_or_default()
95+ }
96+
97+ /// The blob of the file at `path`, if the cache may be trusted for a
98+ /// file that now has the metadata `stat`.
99+ pub(crate) fn lookup(&self, path: &[u8], stat: &Stat) -> Option<ObjectId> {
100+ let entry = self.entries.get(path)?;
101+ let same = entry.mtime == stat.mtime
102+ && entry.size == stat.size
103+ && entry.ino == stat.ino
104+ && Some(entry.kind) == kind_code(stat);
105+ (same && entry.mtime < self.time).then_some(entry.blob)
106+ }
107+
108+ /// Writes the cache into `state_dir`, through a scratch file and a
109+ /// rename.
110+ pub(crate) fn save(&self, state_dir: &Path) -> Result<(), Error> {
111+ let bytes = self.encode();
112+ let scratch = state_dir.join(format!("{FILE}.tmp-{}", random_hex()));
113+ let target = state_dir.join(FILE);
114+ let written = fs::File::create_new(&scratch)
115+ .and_then(|mut file| file.write_all(&bytes))
116+ .and_then(|()| fs::rename(&scratch, &target));
117+ if written.is_err() {
118+ let _ = fs::remove_file(&scratch);
119+ }
120+ written.map_err(Error::io("write", &target))
121+ }
122+
123+ fn encode(&self) -> Vec<u8> {
124+ let mut out = Vec::with_capacity(64 + self.entries.len() * 64);
125+ out.extend_from_slice(MAGIC);
126+ out.extend_from_slice(&VERSION.to_le_bytes());
127+ out.extend_from_slice(&0u32.to_le_bytes());
128+ put_sv(&mut out, self.time.0);
129+ put_uv(&mut out, u64::from(self.time.1));
130+ let mut paths: Vec<&Vec<u8>> = self.entries.keys().collect();
131+ paths.sort();
132+ put_uv(&mut out, paths.len() as u64);
133+ for path in paths {
134+ let entry = &self.entries[path];
135+ put_bytes(&mut out, path);
136+ put_sv(&mut out, entry.mtime.0);
137+ put_uv(&mut out, u64::from(entry.mtime.1));
138+ put_uv(&mut out, entry.size);
139+ put_uv(&mut out, entry.ino);
140+ out.push(entry.kind);
141+ put_id(&mut out, &entry.blob);
142+ }
143+ let check = ObjectId::hash(Kind::Derived, &out);
144+ put_id(&mut out, &check);
145+ out
146+ }
147+}
148+
149+fn decode(bytes: &[u8]) -> Result<Cache, DecodeError> {
150+ let invalid = |at, what| DecodeError::Invalid { at, what };
151+ if bytes.len() < 16 + ObjectId::LEN {
152+ return Err(invalid(0, "stat cache length"));
153+ }
154+ let (body, check) = bytes.split_at(bytes.len() - ObjectId::LEN);
155+ if ObjectId::hash(Kind::Derived, body).as_bytes()[..] != *check {
156+ return Err(invalid(body.len(), "stat cache checksum"));
157+ }
158+ let mut reader = Reader::new(body);
159+ if reader.take(8)? != MAGIC || reader.array::<4>()? != VERSION.to_le_bytes() {
160+ return Err(invalid(0, "stat cache header"));
161+ }
162+ reader.array::<4>()?;
163+ let seconds = reader.sv()?;
164+ let nanos = u32::try_from(reader.uv()?).map_err(|_| invalid(12, "nanoseconds"))?;
165+ let count = reader.count(1 + 1 + 1 + 1 + 1 + 1 + 32)?;
166+ let mut entries = HashMap::with_capacity(count);
167+ for _ in 0..count {
168+ let path = reader.bytes()?.to_vec();
169+ let at = reader.position();
170+ let mtime = (
171+ reader.sv()?,
172+ u32::try_from(reader.uv()?).map_err(|_| invalid(at, "nanoseconds"))?,
173+ );
174+ let entry = Entry {
175+ mtime,
176+ size: reader.uv()?,
177+ ino: reader.uv()?,
178+ kind: reader.u8()?,
179+ blob: reader.id()?,
180+ };
181+ entries.insert(path, entry);
182+ }
183+ reader.finish()?;
184+ Ok(Cache {
185+ time: (seconds, nanos),
186+ entries,
187+ })
188+}
189+
190+#[cfg(test)]
191+mod tests {
192+ use super::*;
193+
194+ fn stat(mtime: i64) -> Stat {
195+ Stat {
196+ kind: StatKind::File,
197+ executable: false,
198+ size: 5,
199+ mtime: (mtime, 7),
200+ ino: 42,
201+ }
202+ }
203+
204+ #[test]
205+ fn round_trip_and_damage() {
206+ let dir = tempfile::tempdir().unwrap();
207+ assert_eq!(Cache::load(dir.path()), Cache::default());
208+ let blob = ObjectId::hash(Kind::Blob, b"hello");
209+ let mut cache = Cache {
210+ time: (100, 0),
211+ entries: HashMap::new(),
212+ };
213+ cache
214+ .entries
215+ .insert(b"a/b".to_vec(), Entry::new(&stat(50), blob).unwrap());
216+ cache.save(dir.path()).unwrap();
217+ assert_eq!(Cache::load(dir.path()), cache);
218+
219+ let mut bytes = fs::read(dir.path().join(FILE)).unwrap();
220+ bytes[20] ^= 1;
221+ fs::write(dir.path().join(FILE), &bytes).unwrap();
222+ assert_eq!(Cache::load(dir.path()), Cache::default());
223+ }
224+
225+ #[test]
226+ fn the_guard() {
227+ let blob = ObjectId::hash(Kind::Blob, b"hello");
228+ let mut cache = Cache {
229+ time: (100, 0),
230+ entries: HashMap::new(),
231+ };
232+ cache
233+ .entries
234+ .insert(b"old".to_vec(), Entry::new(&stat(50), blob).unwrap());
235+ cache
236+ .entries
237+ .insert(b"racy".to_vec(), Entry::new(&stat(100), blob).unwrap());
238+ assert_eq!(cache.lookup(b"old", &stat(50)), Some(blob));
239+ // Modified since, or written in the same instant as the scan.
240+ assert_eq!(cache.lookup(b"old", &stat(51)), None);
241+ assert_eq!(cache.lookup(b"racy", &stat(100)), None);
242+ // Another inode, size or kind.
243+ let mut moved = stat(50);
244+ moved.ino = 43;
245+ assert_eq!(cache.lookup(b"old", &moved), None);
246+ let mut exec = stat(50);
247+ exec.executable = true;
248+ assert_eq!(cache.lookup(b"old", &exec), None);
249+ assert_eq!(cache.lookup(b"absent", &stat(50)), None);
250+ }
251+}
added crates/wc/src/change.rs +206 −0
@@ -0,0 +1,206 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Making a changeset without a working copy, and landing one.
5+//!
6+//! An agent that knows which files it wants to change does not need a
7+//! checkout: it names the base, the new contents and the deletions, and can
8+//! state what it expects the base to hold at each path, so that it never
9+//! overwrites an edit it did not see.
10+
11+use braid_engine::{EMPTY_TREE, LandOutcome, entry_at, land, read_changeset};
12+use braid_format::{Change, ChangeOp, EntryKind, Kind, ObjectId, Objects, validate_path};
13+use braid_store::{RefUpdate, Store, TransactError};
14+
15+use crate::error::Error;
16+use crate::identity::Identity;
17+use crate::workspace::{LandReport, Landed};
18+
19+/// What the base must hold at a path.
20+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21+pub enum Expect {
22+ /// A file, executable or symlink with this blob.
23+ Blob(ObjectId),
24+ /// Nothing: no file and no directory.
25+ Absent,
26+}
27+
28+/// A changeset to make.
29+#[derive(Clone, Debug)]
30+pub struct ChangeRequest {
31+ /// The changeset to build on; `None` for a first changeset.
32+ pub base: Option<ObjectId>,
33+ /// Paths to set, with their new contents. A path that is an executable
34+ /// in the base stays executable.
35+ pub sets: Vec<(Vec<u8>, Vec<u8>)>,
36+ /// Paths to delete.
37+ pub deletes: Vec<Vec<u8>>,
38+ /// What the base must hold, checked before anything is stored.
39+ pub expects: Vec<(Vec<u8>, Expect)>,
40+ /// The message.
41+ pub message: Vec<u8>,
42+ /// The author, who also commits it.
43+ pub author: Identity,
44+}
45+
46+/// Checks the expectations against the base, stores the contents and the
47+/// changeset, makes it durable, and returns its id.
48+pub fn create_change(store: &Store, request: &ChangeRequest) -> Result<ObjectId, Error> {
49+ let base_root = match request.base {
50+ Some(base) => read_changeset(store, base)?.root,
51+ None => EMPTY_TREE,
52+ };
53+ for path in request
54+ .sets
55+ .iter()
56+ .map(|(path, _)| path)
57+ .chain(&request.deletes)
58+ .chain(request.expects.iter().map(|(path, _)| path))
59+ {
60+ validate_path(path).map_err(|error| Error::InvalidPath {
61+ path: path.clone(),
62+ error,
63+ })?;
64+ }
65+ for (path, expect) in &request.expects {
66+ let found = entry_at(store, base_root, path)?;
67+ let matches = match (expect, &found) {
68+ (Expect::Absent, None) => true,
69+ (
70+ Expect::Blob(want),
71+ Some(
72+ EntryKind::File { blob, .. }
73+ | EntryKind::Executable { blob, .. }
74+ | EntryKind::Symlink { blob, .. },
75+ ),
76+ ) => want == blob,
77+ _ => false,
78+ };
79+ if !matches {
80+ return Err(Error::ExpectationFailed {
81+ path: path.clone(),
82+ expected: match expect {
83+ Expect::Blob(id) => id.to_hex(),
84+ Expect::Absent => "absent".to_owned(),
85+ },
86+ found: describe(found.as_ref()),
87+ });
88+ }
89+ }
90+ let mut changes = Vec::with_capacity(request.sets.len() + request.deletes.len());
91+ for (path, content) in &request.sets {
92+ let blob = store.put(Kind::Blob, content)?;
93+ let size = content.len() as u64;
94+ let executable = matches!(
95+ entry_at(store, base_root, path)?,
96+ Some(EntryKind::Executable { .. })
97+ );
98+ changes.push(Change {
99+ path: path.clone(),
100+ op: if executable {
101+ ChangeOp::Executable { blob, size }
102+ } else {
103+ ChangeOp::File { blob, size }
104+ },
105+ });
106+ }
107+ for path in &request.deletes {
108+ changes.push(Change {
109+ path: path.clone(),
110+ op: ChangeOp::Delete,
111+ });
112+ }
113+ let signature = request.author.now();
114+ let id = braid_engine::commit(
115+ store,
116+ request.base.into_iter().collect(),
117+ changes,
118+ signature.clone(),
119+ signature,
120+ request.message.clone(),
121+ Vec::new(),
122+ )?;
123+ store.sync()?;
124+ Ok(id)
125+}
126+
127+fn describe(entry: Option<&EntryKind>) -> String {
128+ match entry {
129+ None => "absent".to_owned(),
130+ Some(EntryKind::Tree { .. }) => "a directory".to_owned(),
131+ Some(EntryKind::Gitlink { .. }) => "a gitlink".to_owned(),
132+ Some(
133+ EntryKind::File { blob, .. }
134+ | EntryKind::Executable { blob, .. }
135+ | EntryKind::Symlink { blob, .. },
136+ ) => blob.to_hex(),
137+ }
138+}
139+
140+/// Lands `change` on `branch` in one op log transaction: the engine
141+/// fast-forwards or rebases it onto the head, and the branch moves with a
142+/// compare-and-swap. With conflicts, or when the branch already has it, the
143+/// branch does not move and no operation is recorded.
144+pub fn land_change(
145+ store: &Store,
146+ branch: &str,
147+ change: ObjectId,
148+ agent: &str,
149+ committer: &Identity,
150+) -> Result<LandReport, Error> {
151+ let signature = committer.now();
152+ let mut previous = None;
153+ let mut landed = Landed::Nothing;
154+ let description = format!("land {} on {branch}", change.short());
155+ let result = store.transact(agent, &description, |refs| {
156+ let head = refs.get(branch);
157+ previous = head;
158+ let new = match land(store, head, change, signature).map_err(|err| Some(err.into()))? {
159+ LandOutcome::FastForward(id) => {
160+ landed = Landed::FastForward(id);
161+ id
162+ }
163+ LandOutcome::Rebased { changeset, .. } => {
164+ landed = Landed::Rebased(changeset);
165+ changeset
166+ }
167+ LandOutcome::AlreadyApplied => {
168+ landed = Landed::AlreadyApplied;
169+ return Err(None);
170+ }
171+ LandOutcome::Conflicts(conflicts) => {
172+ landed = Landed::Conflicts { change, conflicts };
173+ return Err(None);
174+ }
175+ };
176+ Ok(vec![RefUpdate::new(branch, head, Some(new))])
177+ });
178+ let operation = match result {
179+ Ok(op) => Some(op.seq),
180+ // The branch stays where it is.
181+ Err(TransactError::Aborted(None)) => None,
182+ Err(TransactError::Aborted(Some(err))) => return Err(err),
183+ Err(TransactError::Store(err)) => return Err(err.into()),
184+ };
185+ Ok(LandReport {
186+ branch: branch.to_owned(),
187+ previous,
188+ landed,
189+ operation,
190+ })
191+}
192+
193+#[cfg(test)]
194+mod tests {
195+ use super::*;
196+
197+ #[test]
198+ fn describing_entries() {
199+ assert_eq!(describe(None), "absent");
200+ let blob = ObjectId::hash(Kind::Blob, b"x");
201+ assert_eq!(
202+ describe(Some(&EntryKind::File { blob, size: 1 })),
203+ blob.to_hex()
204+ );
205+ }
206+}
added crates/wc/src/checkout.rs +515 −0
@@ -0,0 +1,515 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Bringing a working copy from one tree to another, writing only what
5+//! differs.
6+//!
7+//! A checkout is planned first and written second. Planning reads the two
8+//! trees and the working copy and refuses, before anything is written:
9+//!
10+//! - a name this platform cannot represent;
11+//! - two names of one directory that this file system would take for the
12+//! same file (letter case, Unicode normalisation): neither is written;
13+//! - in checked mode, anything in the way that braid did not put there: an
14+//! untracked file where a new file goes, or a file or symlink where a new
15+//! directory goes.
16+//!
17+//! Writing then removes before it creates. Files that go away are removed
18+//! first, then the directories left empty, then new content is written:
19+//! each regular file into a scratch file in its directory, with mode 0644 or
20+//! 0755, renamed over its name; each symlink created with its target stored
21+//! as data and renamed into place; each gitlink as an empty directory. Every
22+//! step goes through directory handles that never follow a symlink (see
23+//! [`safe`](crate::safe)), and nothing found in the repository is ever run.
24+
25+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
26+use std::io;
27+
28+use braid_engine::{EMPTY_TREE, diff, entry_at, read_blob, read_tree};
29+use braid_format::{ChangeOp, EntryKind, ObjectId, Objects};
30+
31+use crate::error::Error;
32+use crate::fsprobe::FileSystem;
33+use crate::paths::{ancestors, names, os_name, platform_problem, split_last};
34+use crate::safe::{Found, Root, StatKind, remove_entry, write_file, write_symlink};
35+
36+/// Whether a checkout may overwrite what it finds.
37+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38+pub(crate) enum Mode {
39+ /// Refuse when untracked data is in the way.
40+ Checked,
41+ /// Finish a checkout that was interrupted: the paths it covers are
42+ /// braid's to overwrite.
43+ Forced,
44+}
45+
46+/// A checkout, validated and ready to write.
47+#[derive(Debug, Default)]
48+pub(crate) struct Plan {
49+ /// Files, symlinks and gitlinks to remove, with what they were.
50+ removes: Vec<(Vec<u8>, ChangeOp)>,
51+ /// Directories that the target tree does not have, deepest first.
52+ empty_dirs: Vec<Vec<u8>>,
53+ /// What to write, by path in order.
54+ writes: Vec<(Vec<u8>, ChangeOp)>,
55+}
56+
57+impl Plan {
58+ /// How many paths the checkout writes or removes.
59+ pub(crate) fn len(&self) -> usize {
60+ self.removes.len() + self.writes.len()
61+ }
62+}
63+
64+/// Plans the checkout that turns the working copy of tree `from` into tree
65+/// `to`.
66+pub(crate) fn plan<O: Objects>(
67+ objects: &O,
68+ root: &Root,
69+ fs: FileSystem,
70+ from: ObjectId,
71+ to: ObjectId,
72+ mode: Mode,
73+) -> Result<Plan, Error> {
74+ let mut plan = Plan::default();
75+ if from == to {
76+ return Ok(plan);
77+ }
78+ // The diff the other way lists the same paths with what `from` has
79+ // there: one walk over the difference instead of a lookup per path.
80+ let olds: HashMap<Vec<u8>, ChangeOp> = if from == EMPTY_TREE {
81+ HashMap::new()
82+ } else {
83+ diff(objects, to, from)?
84+ .into_iter()
85+ .filter(|change| !matches!(change.op, ChangeOp::Delete))
86+ .map(|change| (change.path, change.op))
87+ .collect()
88+ };
89+ for change in diff(objects, from, to)? {
90+ match change.op {
91+ ChangeOp::Delete => {
92+ if let Some(old) = olds.get(&change.path) {
93+ plan.removes.push((change.path, old.clone()));
94+ }
95+ }
96+ op => plan.writes.push((change.path, op)),
97+ }
98+ }
99+
100+ // Directories the removals may leave behind, deepest first.
101+ let mut is_dir: HashMap<&[u8], bool> = HashMap::new();
102+ let mut gone = BTreeSet::new();
103+ for (path, _) in &plan.removes {
104+ for dir in ancestors(path) {
105+ let stays = match is_dir.get(dir) {
106+ Some(stays) => *stays,
107+ None => {
108+ let stays = is_dir_in(objects, to, dir)?;
109+ is_dir.insert(dir, stays);
110+ stays
111+ }
112+ };
113+ if !stays {
114+ gone.insert(dir.to_vec());
115+ }
116+ }
117+ }
118+ plan.empty_dirs = gone.into_iter().collect();
119+ plan.empty_dirs.sort_by(|a, b| {
120+ let depth = |p: &[u8]| p.iter().filter(|byte| **byte == b'/').count();
121+ depth(b).cmp(&depth(a)).then_with(|| a.cmp(b))
122+ });
123+
124+ for (path, _) in &plan.writes {
125+ for name in names(path) {
126+ if let Some(reason) = platform_problem(name) {
127+ return Err(Error::Unsafe {
128+ path: path.clone(),
129+ reason: reason.to_owned(),
130+ });
131+ }
132+ }
133+ }
134+ if fs.ignores_case || fs.ignores_normalization {
135+ check_collisions(objects, fs, to, &plan.writes)?;
136+ }
137+ if mode == Mode::Checked {
138+ check_obstacles(root, fs, &plan, &olds)?;
139+ }
140+ Ok(plan)
141+}
142+
143+/// Whether `dir` is a directory of the tree `root`.
144+fn is_dir_in<O: Objects>(objects: &O, root: ObjectId, dir: &[u8]) -> Result<bool, Error> {
145+ Ok(matches!(
146+ entry_at(objects, root, dir)?,
147+ Some(EntryKind::Tree { .. })
148+ ))
149+}
150+
151+/// Refuses two names of one directory of `to` that fold to the same name,
152+/// in every directory a write goes through.
153+fn check_collisions<O: Objects>(
154+ objects: &O,
155+ fs: FileSystem,
156+ to: ObjectId,
157+ writes: &[(Vec<u8>, ChangeOp)],
158+) -> Result<(), Error> {
159+ let mut checked: HashSet<Vec<u8>> = HashSet::new();
160+ for (path, _) in writes {
161+ let dirs = std::iter::once(&path[..0]).chain(ancestors(path));
162+ for dir in dirs {
163+ if !checked.insert(dir.to_vec()) {
164+ continue;
165+ }
166+ let tree = if dir.is_empty() {
167+ to
168+ } else {
169+ match entry_at(objects, to, dir)? {
170+ Some(EntryKind::Tree { tree }) => tree,
171+ _ => continue,
172+ }
173+ };
174+ let mut seen: HashMap<Vec<u8>, Vec<u8>> = HashMap::new();
175+ for entry in read_tree(objects, tree)? {
176+ let folded = fs.fold(&entry.name).into_owned();
177+ if let Some(first) = seen.insert(folded, entry.name.clone()) {
178+ let at = |name: &[u8]| crate::paths::join(dir, name);
179+ return Err(Error::Collision {
180+ first: at(&first),
181+ second: at(&entry.name),
182+ });
183+ }
184+ }
185+ }
186+ }
187+ Ok(())
188+}
189+
190+/// What the working copy has at a directory on the way to a write.
191+#[derive(Clone, Copy, PartialEq, Eq)]
192+enum DirState {
193+ Present,
194+ Missing,
195+}
196+
197+/// Refuses writes that would overwrite or go through something the old
198+/// tree did not have there.
199+fn check_obstacles(
200+ root: &Root,
201+ fs: FileSystem,
202+ plan: &Plan,
203+ olds: &HashMap<Vec<u8>, ChangeOp>,
204+) -> Result<(), Error> {
205+ let fold_path = |path: &[u8]| -> Vec<u8> {
206+ let mut out = Vec::with_capacity(path.len());
207+ for name in names(path) {
208+ if !out.is_empty() {
209+ out.push(b'/');
210+ }
211+ out.extend_from_slice(&fs.fold(name));
212+ }
213+ out
214+ };
215+ // What the plan removes, as this file system finds it.
216+ let removed: HashSet<Vec<u8>> = plan
217+ .removes
218+ .iter()
219+ .map(|(path, _)| fold_path(path))
220+ .collect();
221+ let emptied: HashSet<Vec<u8>> = plan.empty_dirs.iter().map(|path| fold_path(path)).collect();
222+ let mut dirs: HashMap<Vec<u8>, DirState> = HashMap::new();
223+ dirs.insert(Vec::new(), DirState::Present);
224+
225+ for (path, op) in &plan.writes {
226+ let mut parent_state = DirState::Present;
227+ for dir in ancestors(path) {
228+ if let Some(state) = dirs.get(dir) {
229+ parent_state = *state;
230+ continue;
231+ }
232+ let state = if parent_state == DirState::Missing {
233+ DirState::Missing
234+ } else {
235+ match root.stat(dir)? {
236+ Found::Here(stat) if stat.kind == StatKind::Dir => DirState::Present,
237+ Found::Here(_) if removed.contains(&fold_path(dir)) => DirState::Missing,
238+ Found::Here(_) => {
239+ return Err(Error::Unsafe {
240+ path: dir.to_vec(),
241+ reason: "a file or symlink that braid does not track is where a directory goes"
242+ .to_owned(),
243+ });
244+ }
245+ Found::Missing | Found::Blocked(_) => DirState::Missing,
246+ }
247+ };
248+ dirs.insert(dir.to_vec(), state);
249+ parent_state = state;
250+ }
251+ if parent_state == DirState::Missing || olds.contains_key(path) {
252+ continue;
253+ }
254+ let Found::Here(stat) = root.stat(path)? else {
255+ continue;
256+ };
257+ let folded = fold_path(path);
258+ if removed.contains(&folded) {
259+ // A file or symlink the checkout removes first.
260+ continue;
261+ }
262+ let is_dir = stat.kind == StatKind::Dir;
263+ if is_dir && matches!(op, ChangeOp::Gitlink { .. }) {
264+ continue;
265+ }
266+ if is_dir && emptied.contains(&folded) {
267+ // A directory that this file replaces: it must hold nothing
268+ // but what the checkout removes.
269+ if let Some(untracked) = untracked_inside(root, path, &removed, &fold_path)? {
270+ return Err(Error::Unsafe {
271+ path: untracked,
272+ reason: format!(
273+ "a file replaces the directory {:?}, and this untracked file in it would be lost",
274+ crate::paths::show(path)
275+ ),
276+ });
277+ }
278+ continue;
279+ }
280+ return Err(Error::Unsafe {
281+ path: path.clone(),
282+ reason: "an untracked file or directory is in the way; move it or remove it".to_owned(),
283+ });
284+ }
285+ Ok(())
286+}
287+
288+/// The first entry under the directory `dir` of the working copy that is
289+/// not a directory and that the checkout does not remove, if there is one.
290+fn untracked_inside(
291+ root: &Root,
292+ dir: &[u8],
293+ removed: &HashSet<Vec<u8>>,
294+ fold_path: &dyn Fn(&[u8]) -> Vec<u8>,
295+) -> Result<Option<Vec<u8>>, Error> {
296+ let mut pending = vec![dir.to_vec()];
297+ while let Some(current) = pending.pop() {
298+ let Found::Here(handle) = root.open_dir(&current)? else {
299+ continue;
300+ };
301+ let entries = handle
302+ .entries()
303+ .map_err(|err| root.error("read", &current, err))?;
304+ for entry in entries {
305+ let entry = entry.map_err(|err| root.error("read", &current, err))?;
306+ let name = entry.file_name();
307+ let Some(bytes) = crate::paths::name_bytes(&name) else {
308+ return Ok(Some(current));
309+ };
310+ let path = crate::paths::join(&current, bytes);
311+ let meta = handle
312+ .symlink_metadata(&name)
313+ .map_err(|err| root.error("read", &path, err))?;
314+ if meta.is_dir() {
315+ pending.push(path);
316+ } else if !removed.contains(&fold_path(&path)) {
317+ return Ok(Some(path));
318+ }
319+ }
320+ }
321+ Ok(None)
322+}
323+
324+/// Writes a planned checkout. Returns how many paths it wrote or removed.
325+pub(crate) fn apply<O: Objects>(objects: &O, root: &Root, plan: &Plan) -> Result<usize, Error> {
326+ for (path, old) in &plan.removes {
327+ let (parent, name) = split_last(path);
328+ let Found::Here(dir) = root.open_dir(parent)? else {
329+ continue;
330+ };
331+ let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
332+ let removed = match old {
333+ // A submodule's directory goes only if it is empty.
334+ ChangeOp::Gitlink { .. } => match dir.remove_dir(os) {
335+ Err(err) if is_not_empty(&err) || err.kind() == io::ErrorKind::NotFound => Ok(()),
336+ other => other,
337+ },
338+ _ => remove_entry(&dir, os),
339+ };
340+ removed.map_err(|err| root.error("remove", path, err))?;
341+ }
342+ for path in &plan.empty_dirs {
343+ let (parent, name) = split_last(path);
344+ let Found::Here(dir) = root.open_dir(parent)? else {
345+ continue;
346+ };
347+ let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
348+ match dir.remove_dir(os) {
349+ Ok(()) => {}
350+ // Untracked files keep it, or it is gone already, or it is not a
351+ // directory any more.
352+ Err(err)
353+ if is_not_empty(&err)
354+ || err.kind() == io::ErrorKind::NotFound
355+ || err.kind() == io::ErrorKind::NotADirectory => {}
356+ Err(err) => return Err(root.error("remove", path, err)),
357+ }
358+ }
359+
360+ // Writes in path order, so a directory's files go out together.
361+ let mut by_dir: BTreeMap<&[u8], Vec<Write<'_>>> = BTreeMap::new();
362+ for (path, op) in &plan.writes {
363+ let (parent, name) = split_last(path);
364+ by_dir.entry(parent).or_default().push((path, name, op));
365+ }
366+ for (parent, files) in by_dir {
367+ let dir = root.create_dirs(parent)?;
368+ for (path, name, op) in files {
369+ let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
370+ let written = match op {
371+ ChangeOp::File { blob, .. } | ChangeOp::Executable { blob, .. } => {
372+ let content = read_blob(objects, *blob)?;
373+ let executable = matches!(op, ChangeOp::Executable { .. });
374+ write_file(&dir, os, &content, executable)
375+ }
376+ ChangeOp::Symlink { blob, .. } => {
377+ let target = read_blob(objects, *blob)?;
378+ write_symlink(&dir, os, &target)
379+ }
380+ ChangeOp::Gitlink { .. } => match dir.symlink_metadata(os) {
381+ Ok(meta) if meta.is_dir() => Ok(()),
382+ _ => remove_entry(&dir, os).and_then(|()| dir.create_dir(os)),
383+ },
384+ ChangeOp::Delete => Ok(()),
385+ };
386+ written.map_err(|err| match err.kind() {
387+ _ if is_not_empty(&err) => Error::Unsafe {
388+ path: path.to_vec(),
389+ reason: "a directory that still holds untracked files is where a file goes"
390+ .to_owned(),
391+ },
392+ _ => root.error("write", path, err),
393+ })?;
394+ }
395+ }
396+ Ok(plan.len())
397+}
398+
399+/// One write of a directory: the full path, the name in the directory, and
400+/// what to write.
401+type Write<'p> = (&'p [u8], &'p [u8], &'p ChangeOp);
402+
403+fn is_not_empty(err: &io::Error) -> bool {
404+ // Some systems report a directory that is not empty as "exists".
405+ err.kind() == io::ErrorKind::DirectoryNotEmpty || err.kind() == io::ErrorKind::AlreadyExists
406+}
407+
408+fn unrepresentable(path: &[u8]) -> Error {
409+ Error::Unsafe {
410+ path: path.to_vec(),
411+ reason: "this platform cannot represent the name".to_owned(),
412+ }
413+}
414+
415+#[cfg(test)]
416+mod tests {
417+ use super::*;
418+ use braid_engine::write_tree;
419+ use braid_format::{Entry, Kind, MemoryObjects};
420+
421+ fn file(objects: &MemoryObjects, name: &str, content: &str) -> Entry {
422+ Entry {
423+ name: name.as_bytes().to_vec(),
424+ kind: EntryKind::File {
425+ blob: objects.put(Kind::Blob, content.as_bytes()).unwrap(),
426+ size: content.len() as u64,
427+ },
428+ }
429+ }
430+
431+ fn planned(
432+ objects: &MemoryObjects,
433+ fs: FileSystem,
434+ to: ObjectId,
435+ ) -> (tempfile::TempDir, Result<Plan, Error>) {
436+ let dir = tempfile::tempdir().unwrap();
437+ let root = Root::open(dir.path()).unwrap();
438+ let plan = plan(objects, &root, fs, EMPTY_TREE, to, Mode::Checked);
439+ (dir, plan)
440+ }
441+
442+ #[test]
443+ fn case_twins_collide_where_case_is_ignored() {
444+ let objects = MemoryObjects::new();
445+ let tree = write_tree(
446+ &objects,
447+ vec![file(&objects, "README", "a"), file(&objects, "readme", "b")],
448+ )
449+ .unwrap();
450+ let (_dir, plan) = planned(&objects, FileSystem::FORGIVING, tree);
451+ assert!(
452+ matches!(&plan, Err(Error::Collision { first, second })
453+ if first == b"README" && second == b"readme"),
454+ "{plan:?}"
455+ );
456+ // Where names are exact, both are fine.
457+ let (_dir, plan) = planned(&objects, FileSystem::default(), tree);
458+ assert_eq!(plan.unwrap().len(), 2);
459+ }
460+
461+ #[test]
462+ fn normalisation_twins_collide_in_subdirectories() {
463+ let objects = MemoryObjects::new();
464+ let inner = write_tree(
465+ &objects,
466+ vec![
467+ file(&objects, "caf\u{e9}", "a"),
468+ file(&objects, "cafe\u{301}", "b"),
469+ ],
470+ )
471+ .unwrap();
472+ let tree = write_tree(
473+ &objects,
474+ vec![Entry {
475+ name: b"docs".to_vec(),
476+ kind: EntryKind::Tree { tree: inner },
477+ }],
478+ )
479+ .unwrap();
480+ let only_normalisation = FileSystem {
481+ ignores_case: false,
482+ ignores_normalization: true,
483+ };
484+ let (_dir, plan) = planned(&objects, only_normalisation, tree);
485+ assert!(matches!(plan, Err(Error::Collision { .. })), "{plan:?}");
486+ }
487+
488+ #[test]
489+ fn a_symlink_and_a_directory_that_fold_together_are_refused() {
490+ // `dir` is a symlink and `DIR/x` a file: on a file system that
491+ // ignores case, writing `DIR/x` would go through the symlink.
492+ let objects = MemoryObjects::new();
493+ let x = file(&objects, "x", "pwned");
494+ let inner = write_tree(&objects, vec![x]).unwrap();
495+ let tree = write_tree(
496+ &objects,
497+ vec![
498+ Entry {
499+ name: b"DIR".to_vec(),
500+ kind: EntryKind::Tree { tree: inner },
501+ },
502+ Entry {
503+ name: b"dir".to_vec(),
504+ kind: EntryKind::Symlink {
505+ blob: objects.put(Kind::Blob, b"/tmp").unwrap(),
506+ size: 4,
507+ },
508+ },
509+ ],
510+ )
511+ .unwrap();
512+ let (_dir, plan) = planned(&objects, FileSystem::FORGIVING, tree);
513+ assert!(matches!(plan, Err(Error::Collision { .. })), "{plan:?}");
514+ }
515+}
added crates/wc/src/error.rs +237 −0
@@ -0,0 +1,237 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Why a workspace operation failed.
5+
6+use std::io;
7+use std::path::{Path, PathBuf};
8+
9+use braid_format::ObjectId;
10+
11+use crate::paths::show;
12+
13+/// Why a workspace operation failed.
14+///
15+/// Conflicts are not errors: landing, updating and committing report them as
16+/// outcomes. These are the failures, after which the branch has not moved
17+/// and the workspace is as it was, except where a variant says otherwise.
18+#[derive(Debug, thiserror::Error)]
19+#[non_exhaustive]
20+pub enum Error {
21+ /// A file system call failed.
22+ #[error("cannot {action} {}: {source}", .path.display())]
23+ Io {
24+ /// What was being done, as a verb.
25+ action: &'static str,
26+ /// The file or directory involved.
27+ path: PathBuf,
28+ /// The error from the operating system.
29+ #[source]
30+ source: io::Error,
31+ },
32+
33+ /// The object store failed.
34+ #[error(transparent)]
35+ Store(#[from] braid_store::Error),
36+
37+ /// The repository could not be opened or read.
38+ #[error(transparent)]
39+ Repo(#[from] braid_repo::Error),
40+
41+ /// The engine refused an operation or found invalid data.
42+ #[error(transparent)]
43+ Engine(#[from] braid_engine::Error),
44+
45+ /// A changeset could not be assembled.
46+ #[error("cannot assemble a changeset: {0}")]
47+ Assemble(#[from] braid_format::ChangesetError),
48+
49+ /// The current directory is not inside a workspace.
50+ #[error("not inside a workspace; create one with `braid workspace add <name>`")]
51+ NotAWorkspace,
52+
53+ /// A workspace name that is not allowed.
54+ #[error(
55+ "invalid workspace name {0:?}: use 1 to 64 letters, digits, '.', '_' or '-', starting with a letter or digit"
56+ )]
57+ InvalidName(String),
58+
59+ /// A workspace with this name exists already.
60+ #[error("workspace {0:?} exists already")]
61+ WorkspaceExists(String),
62+
63+ /// No workspace has this name.
64+ #[error("no workspace named {0:?}")]
65+ NoSuchWorkspace(String),
66+
67+ /// The directory for a new workspace exists and is not empty.
68+ #[error("{} exists and is not empty", .0.display())]
69+ DirectoryNotEmpty(PathBuf),
70+
71+ /// A file of the workspace's state is damaged.
72+ #[error("{}: {detail}", .path.display())]
73+ BadState {
74+ /// The file.
75+ path: PathBuf,
76+ /// What is wrong with it.
77+ detail: String,
78+ },
79+
80+ /// A checkout would be unsafe or impossible: a name this platform or
81+ /// file system cannot hold, a symlink in the way, untracked data that
82+ /// would be overwritten. Nothing was written.
83+ #[error("cannot write {:?}: {reason}", show(.path))]
84+ Unsafe {
85+ /// The path in the repository.
86+ path: Vec<u8>,
87+ /// Why.
88+ reason: String,
89+ },
90+
91+ /// Two paths of a tree would be the same file on this file system,
92+ /// which ignores letter case or Unicode normalisation. Neither was
93+ /// written.
94+ #[error("{:?} and {:?} would be the same file on this file system", show(.first), show(.second))]
95+ Collision {
96+ /// One path.
97+ first: Vec<u8>,
98+ /// The other.
99+ second: Vec<u8>,
100+ },
101+
102+ /// The workspace has changes that are not committed.
103+ #[error("the workspace has uncommitted changes ({count} paths, starting with {:?}); commit them first", show(.first))]
104+ Uncommitted {
105+ /// How many paths changed.
106+ count: usize,
107+ /// The first of them.
108+ first: Vec<u8>,
109+ },
110+
111+ /// The command needs the rebase in progress to be finished first.
112+ #[error("a rebase is in progress: resolve the conflicts and run `braid commit` first")]
113+ RebaseInProgress,
114+
115+ /// `commit` was given paths while a rebase is in progress: the
116+ /// resolution is recorded whole.
117+ #[error("while a rebase is in progress, commit records the whole working copy: give no paths")]
118+ PathsDuringRebase,
119+
120+ /// The workspace has changesets that its branch does not have.
121+ #[error(
122+ "the workspace has {count} changesets that {branch} does not have; land them, or pass --force"
123+ )]
124+ Unlanded {
125+ /// How many.
126+ count: usize,
127+ /// The branch.
128+ branch: String,
129+ },
130+
131+ /// `resolve` was used with no rebase in progress.
132+ #[error("no rebase is in progress")]
133+ NoRebase,
134+
135+ /// `resolve` named a path without a conflict, or a content conflict.
136+ #[error("{:?}: {reason}", show(.path))]
137+ NotResolvable {
138+ /// The path.
139+ path: Vec<u8>,
140+ /// Why it cannot be marked resolved.
141+ reason: &'static str,
142+ },
143+
144+ /// Conflict markers remain in files with content conflicts.
145+ #[error("conflict markers remain in {}; edit them out, or commit with --force", show_list(.0))]
146+ MarkersRemain(Vec<Vec<u8>>),
147+
148+ /// Conflicts that are not about content are not marked resolved.
149+ #[error("unresolved conflicts at {}; run `braid resolve <path>` once each is settled, or commit with --force", show_list(.0))]
150+ Unresolved(Vec<Vec<u8>>),
151+
152+ /// There is nothing to commit.
153+ #[error("nothing to commit")]
154+ NothingToCommit,
155+
156+ /// A commit needs a message.
157+ #[error("a commit needs a message: pass -m")]
158+ NoMessage,
159+
160+ /// No author is configured.
161+ #[error(
162+ "no author: pass --author \"Name <email>\", set BRAID_AUTHOR, or set name and email in .braid/config"
163+ )]
164+ NoAuthor,
165+
166+ /// An author that cannot be used.
167+ #[error("invalid author {text:?}: {reason}")]
168+ InvalidAuthor {
169+ /// What was given.
170+ text: String,
171+ /// Why it was refused.
172+ reason: &'static str,
173+ },
174+
175+ /// A path given on the command line is outside the workspace.
176+ #[error("{} is outside the workspace", .0.display())]
177+ OutsideWorkspace(PathBuf),
178+
179+ /// A path in the repository that is not valid.
180+ #[error("invalid path {:?}: {error}", show(.path))]
181+ InvalidPath {
182+ /// The path.
183+ path: Vec<u8>,
184+ /// What is wrong with it.
185+ error: braid_format::PathError,
186+ },
187+
188+ /// `change create --expect` did not match the base.
189+ #[error("expected {:?} to be {expected} in the base, it is {found}", show(.path))]
190+ ExpectationFailed {
191+ /// The path.
192+ path: Vec<u8>,
193+ /// What was expected: a blob id or `absent`.
194+ expected: String,
195+ /// What the base has.
196+ found: String,
197+ },
198+
199+ /// The workspace's base is not on the branch, so its changes cannot be
200+ /// landed as they are.
201+ #[error("the workspace's changes are not based on {branch}; run `braid update` first")]
202+ NotOnBranch {
203+ /// The branch.
204+ branch: String,
205+ },
206+
207+ /// An object of the wrong kind where a changeset was expected.
208+ #[error("{0} is not a changeset")]
209+ NotAChangeset(ObjectId),
210+}
211+
212+impl Error {
213+ /// Wraps an I/O error with the action and the path it happened on.
214+ pub(crate) fn io(
215+ action: &'static str,
216+ path: impl AsRef<Path>,
217+ ) -> impl FnOnce(io::Error) -> Self {
218+ let path = path.as_ref().to_path_buf();
219+ move |source| Error::Io {
220+ action,
221+ path,
222+ source,
223+ }
224+ }
225+}
226+
227+fn show_list(paths: &[Vec<u8>]) -> String {
228+ let mut shown: Vec<String> = paths
229+ .iter()
230+ .take(5)
231+ .map(|p| format!("{:?}", show(p)))
232+ .collect();
233+ if paths.len() > 5 {
234+ shown.push(format!("and {} more", paths.len() - 5));
235+ }
236+ shown.join(", ")
237+}
added crates/wc/src/fsprobe.rs +133 −0
@@ -0,0 +1,133 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! What a workspace's file system considers the same name.
5+//!
6+//! Many file systems ignore letter case (the defaults on macOS and Windows),
7+//! and some ignore Unicode normalisation too (macOS). A tree that holds
8+//! `README` and `readme`, or `café` written two ways, is valid, but on such
9+//! a file system the two names are one file: writing both would let the
10+//! second overwrite the first, or write through a symlink the first one
11+//! made. Each workspace finds out once, when it is created, by creating a
12+//! file and looking it up under other spellings.
13+
14+use std::borrow::Cow;
15+use std::hash::{BuildHasher, Hasher};
16+use std::io;
17+use std::time::{SystemTime, UNIX_EPOCH};
18+
19+use cap_std::fs::{Dir, OpenOptions};
20+use unicode_normalization::UnicodeNormalization;
21+
22+/// Prefix of the names braid gives its scratch files inside a workspace.
23+/// Status skips them.
24+pub(crate) const SCRATCH_PREFIX: &str = ".braid-";
25+
26+/// Which differences between names a file system ignores.
27+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28+pub struct FileSystem {
29+ /// `README` and `readme` are one file.
30+ pub ignores_case: bool,
31+ /// `café` precomposed and decomposed are one file.
32+ pub ignores_normalization: bool,
33+}
34+
35+impl FileSystem {
36+ /// The most forgiving file system: one that ignores both.
37+ pub const FORGIVING: FileSystem = FileSystem {
38+ ignores_case: true,
39+ ignores_normalization: true,
40+ };
41+
42+ /// Finds out by creating a scratch file in `dir` and looking it up under
43+ /// another case and another normalisation. If the probe itself fails,
44+ /// the answer is the most forgiving file system, which refuses the most.
45+ pub fn probe(dir: &Dir) -> FileSystem {
46+ probe_names(dir).unwrap_or(FileSystem::FORGIVING)
47+ }
48+
49+ /// The form of `name` under which this file system finds it: lowercased
50+ /// if case is ignored, in Unicode NFC if normalisation is. A name that
51+ /// is not UTF-8 is lowercased as ASCII.
52+ pub fn fold<'a>(&self, name: &'a [u8]) -> Cow<'a, [u8]> {
53+ if !self.ignores_case && !self.ignores_normalization {
54+ return Cow::Borrowed(name);
55+ }
56+ match std::str::from_utf8(name) {
57+ Ok(text) => {
58+ let folded: String = match (self.ignores_case, self.ignores_normalization) {
59+ (true, true) => text.nfc().flat_map(char::to_lowercase).nfc().collect(),
60+ (true, false) => text.chars().flat_map(char::to_lowercase).collect(),
61+ _ => text.nfc().collect(),
62+ };
63+ Cow::Owned(folded.into_bytes())
64+ }
65+ Err(_) if self.ignores_case => Cow::Owned(name.to_ascii_lowercase()),
66+ Err(_) => Cow::Borrowed(name),
67+ }
68+ }
69+}
70+
71+fn probe_names(dir: &Dir) -> io::Result<FileSystem> {
72+ let stem = format!("{SCRATCH_PREFIX}probe-{}-", random_hex());
73+ let created = format!("{stem}X\u{e9}");
74+ let other_case = format!("{stem}x\u{e9}");
75+ let other_form = format!("{stem}Xe\u{301}");
76+ dir.open_with(&created, OpenOptions::new().write(true).create_new(true))?;
77+ let found = |name: &str| dir.symlink_metadata(name).is_ok();
78+ let probed = FileSystem {
79+ ignores_case: found(&other_case),
80+ ignores_normalization: found(&other_form),
81+ };
82+ dir.remove_file(&created)?;
83+ Ok(probed)
84+}
85+
86+/// Sixteen hex digits that differ between calls and processes, for scratch
87+/// file names. Not for secrets: names are always created exclusively.
88+pub(crate) fn random_hex() -> String {
89+ let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
90+ let nanos = SystemTime::now()
91+ .duration_since(UNIX_EPOCH)
92+ .map_or(0, |since| since.as_nanos());
93+ hasher.write_u128(nanos);
94+ hasher.write_u32(std::process::id());
95+ format!("{:016x}", hasher.finish())
96+}
97+
98+#[cfg(test)]
99+mod tests {
100+ use super::*;
101+
102+ #[test]
103+ fn folding() {
104+ let exact = FileSystem::default();
105+ assert_eq!(exact.fold(b"README"), &b"README"[..]);
106+ let case = FileSystem {
107+ ignores_case: true,
108+ ignores_normalization: false,
109+ };
110+ assert_eq!(case.fold(b"ReadMe"), &b"readme"[..]);
111+ assert_ne!(
112+ case.fold("caf\u{e9}".as_bytes()),
113+ case.fold("cafe\u{301}".as_bytes())
114+ );
115+ let both = FileSystem::FORGIVING;
116+ assert_eq!(
117+ both.fold("CAF\u{c9}".as_bytes()),
118+ both.fold("cafe\u{301}".as_bytes())
119+ );
120+ assert_eq!(both.fold(b"\xffA"), &b"\xffa"[..]);
121+ }
122+
123+ #[test]
124+ fn probing_leaves_nothing_behind() {
125+ let temp = tempfile::tempdir().unwrap();
126+ let dir = Dir::open_ambient_dir(temp.path(), cap_std::ambient_authority()).unwrap();
127+ let probed = FileSystem::probe(&dir);
128+ assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 0);
129+ // Whatever the answer, it is the same the second time.
130+ assert_eq!(FileSystem::probe(&dir), probed);
131+ assert_ne!(random_hex(), random_hex());
132+ }
133+}
added crates/wc/src/identity.rs +154 −0
@@ -0,0 +1,154 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Who makes a change: from `--author`, then `BRAID_AUTHOR`, then the
5+//! `name` and `email` of the repository's `.braid/config` (see
6+//! [`braid_repo::Config`]).
7+//!
8+//! Signatures record the current time with an offset of zero: braid does
9+//! not work out the local time zone yet, so times read as UTC.
10+
11+use std::time::{SystemTime, UNIX_EPOCH};
12+
13+use braid_format::Signature;
14+use braid_repo::Repo;
15+
16+use crate::error::Error;
17+
18+/// A name and an e-mail address.
19+#[derive(Clone, Debug, PartialEq, Eq)]
20+pub struct Identity {
21+ /// The name.
22+ pub name: String,
23+ /// The e-mail address.
24+ pub email: String,
25+}
26+
27+impl Identity {
28+ /// Reads `Name <email>`.
29+ pub fn parse(text: &str) -> Result<Identity, Error> {
30+ let invalid = |reason| Error::InvalidAuthor {
31+ text: text.to_owned(),
32+ reason,
33+ };
34+ let (name, rest) = text
35+ .split_once('<')
36+ .ok_or_else(|| invalid("expected \"Name <email>\""))?;
37+ let (email, after) = rest
38+ .split_once('>')
39+ .ok_or_else(|| invalid("expected \"Name <email>\""))?;
40+ if !after.trim().is_empty() {
41+ return Err(invalid("nothing may follow the e-mail address"));
42+ }
43+ Identity::new(name.trim(), email.trim()).map_err(invalid)
44+ }
45+
46+ /// An identity from its parts, which must not hold `<`, `>`, a newline
47+ /// or NUL, so that it can be written as a git signature too.
48+ pub fn new(name: &str, email: &str) -> Result<Identity, &'static str> {
49+ let bad = |text: &str| text.contains(['<', '>', '\n', '\r', '\0']);
50+ if name.is_empty() {
51+ return Err("the name is empty");
52+ }
53+ if bad(name) || bad(email) {
54+ return Err("a signature cannot hold '<', '>', a newline or NUL");
55+ }
56+ Ok(Identity {
57+ name: name.to_owned(),
58+ email: email.to_owned(),
59+ })
60+ }
61+
62+ /// The identity that the repository's `.braid/config` sets, if it sets
63+ /// a name. It must set an email address too.
64+ pub fn from_config(repo: &Repo) -> Result<Option<Identity>, Error> {
65+ let config = repo.config()?;
66+ let Some(name) = config.name else {
67+ return Ok(None);
68+ };
69+ let invalid = |reason| Error::InvalidAuthor {
70+ text: format!("name = {name} in .braid/config"),
71+ reason,
72+ };
73+ let email = config
74+ .email
75+ .ok_or_else(|| invalid("the config sets a name but no email"))?;
76+ Identity::new(&name, &email).map(Some).map_err(invalid)
77+ }
78+
79+ /// The identity given (by `--author` or `BRAID_AUTHOR`), or else the
80+ /// one in the repository's config.
81+ pub fn resolve(given: Option<&str>, repo: &Repo) -> Result<Identity, Error> {
82+ match given {
83+ Some(text) => Identity::parse(text),
84+ None => Identity::from_config(repo)?.ok_or(Error::NoAuthor),
85+ }
86+ }
87+
88+ /// A signature by this identity, now, with an offset of zero.
89+ pub fn now(&self) -> Signature {
90+ let seconds = SystemTime::now()
91+ .duration_since(UNIX_EPOCH)
92+ .map_or(0, |since| since.as_secs() as i64);
93+ Signature {
94+ name: self.name.as_bytes().to_vec(),
95+ email: self.email.as_bytes().to_vec(),
96+ seconds,
97+ offset_minutes: 0,
98+ }
99+ }
100+}
101+
102+#[cfg(test)]
103+mod tests {
104+ use super::*;
105+
106+ #[test]
107+ fn parsing() {
108+ let ada = Identity::parse("Ada Lovelace <ada@example.org>").unwrap();
109+ assert_eq!(ada.name, "Ada Lovelace");
110+ assert_eq!(ada.email, "ada@example.org");
111+ for bad in [
112+ "Ada",
113+ "<ada@example.org>",
114+ "Ada <a>b>",
115+ "Ada <ada> extra",
116+ "A\nB <x>",
117+ ] {
118+ assert!(Identity::parse(bad).is_err(), "{bad:?}");
119+ }
120+ let signature = ada.now();
121+ assert_eq!(signature.offset_minutes, 0);
122+ assert!(signature.seconds > 1_700_000_000);
123+ }
124+
125+ #[test]
126+ fn config() {
127+ let dir = tempfile::tempdir().unwrap();
128+ let repo = Repo::init(dir.path()).unwrap();
129+ assert_eq!(Identity::from_config(&repo).unwrap(), None);
130+ assert!(matches!(
131+ Identity::resolve(None, &repo),
132+ Err(Error::NoAuthor)
133+ ));
134+ let config = dir
135+ .path()
136+ .join(braid_repo::DIR)
137+ .join(braid_repo::CONFIG_FILE);
138+ std::fs::write(&config, "# who commits\nname = Grace Hopper\n").unwrap();
139+ assert!(matches!(
140+ Identity::resolve(None, &repo),
141+ Err(Error::InvalidAuthor { .. })
142+ ));
143+ std::fs::write(
144+ &config,
145+ "# who commits\nname = Grace Hopper\nemail = grace@example.org\n",
146+ )
147+ .unwrap();
148+ let grace = Identity::resolve(None, &repo).unwrap();
149+ assert_eq!(grace.name, "Grace Hopper");
150+ assert_eq!(grace.email, "grace@example.org");
151+ let given = Identity::resolve(Some("Ada <ada@example.org>"), &repo).unwrap();
152+ assert_eq!(given.name, "Ada");
153+ }
154+}
added crates/wc/src/ignores.rs +144 −0
@@ -0,0 +1,144 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! `.gitignore` and `.braidignore` rules, as the walk over a working copy
5+//! meets them.
6+//!
7+//! Each directory may hold either file, with git's pattern syntax. Rules in a
8+//! deeper directory win over rules above it, and within one directory
9+//! `.braidignore` wins over `.gitignore`. As in git, a file under an ignored
10+//! directory cannot be brought back by a later `!` rule, since the walk does
11+//! not go into ignored directories. Tracked files are never ignored: the
12+//! walk checks them whatever the rules say.
13+
14+use std::io::Read;
15+use std::rc::Rc;
16+
17+use cap_std::fs::Dir;
18+use ignore::Match;
19+use ignore::gitignore::{Gitignore, GitignoreBuilder};
20+
21+use crate::paths::os_name;
22+use crate::safe::open_file;
23+
24+/// Ignore files read in each directory, highest precedence first.
25+const FILES: [&str; 2] = [".braidignore", ".gitignore"];
26+
27+/// The rules of one directory, and those of the directories above it.
28+#[derive(Debug)]
29+pub(crate) struct Rules {
30+ /// The directory's path in the working copy; empty for the root.
31+ dir: Vec<u8>,
32+ /// Its matchers, highest precedence first.
33+ matchers: Vec<Gitignore>,
34+ parent: Option<Rc<Rules>>,
35+}
36+
37+/// The rules in force in a directory.
38+pub(crate) type Chain = Option<Rc<Rules>>;
39+
40+/// The rules in force inside `dir`, whose path is `path`: those of its own
41+/// ignore files, if it has any, on top of `parent`. Ignore files that are
42+/// symlinks, unreadable, or not UTF-8 lines are skipped.
43+pub(crate) fn enter(dir: &Dir, path: &[u8], parent: &Chain) -> Chain {
44+ let mut matchers = Vec::new();
45+ for name in FILES {
46+ let Ok(mut file) = open_file(dir, name.as_ref()) else {
47+ continue;
48+ };
49+ let mut text = Vec::new();
50+ if file.read_to_end(&mut text).is_err() {
51+ continue;
52+ }
53+ let mut builder = GitignoreBuilder::new(".");
54+ for line in text.split(|byte| *byte == b'\n') {
55+ if let Ok(line) = std::str::from_utf8(line) {
56+ // A pattern that does not parse is left out, as git does.
57+ let _ = builder.add_line(None, line.trim_end_matches('\r'));
58+ }
59+ }
60+ if let Ok(matcher) = builder.build()
61+ && !matcher.is_empty()
62+ {
63+ matchers.push(matcher);
64+ }
65+ }
66+ if matchers.is_empty() {
67+ return parent.clone();
68+ }
69+ Some(Rc::new(Rules {
70+ dir: path.to_vec(),
71+ matchers,
72+ parent: parent.clone(),
73+ }))
74+}
75+
76+/// Whether the rules ignore `path`, a directory if `is_dir`.
77+pub(crate) fn is_ignored(chain: &Chain, path: &[u8], is_dir: bool) -> bool {
78+ let mut rules = chain.as_deref();
79+ while let Some(current) = rules {
80+ let skip = if current.dir.is_empty() {
81+ 0
82+ } else {
83+ current.dir.len() + 1
84+ };
85+ if let Some(relative) = path.get(skip..).and_then(os_name) {
86+ for matcher in &current.matchers {
87+ match matcher.matched(relative, is_dir) {
88+ Match::Ignore(_) => return true,
89+ Match::Whitelist(_) => return false,
90+ Match::None => {}
91+ }
92+ }
93+ }
94+ rules = current.parent.as_deref();
95+ }
96+ false
97+}
98+
99+#[cfg(test)]
100+mod tests {
101+ use super::*;
102+
103+ fn dir(path: &std::path::Path) -> Dir {
104+ Dir::open_ambient_dir(path, cap_std::ambient_authority()).unwrap()
105+ }
106+
107+ #[test]
108+ fn rules_nest_and_negate() {
109+ let temp = tempfile::tempdir().unwrap();
110+ std::fs::write(temp.path().join(".gitignore"), "*.log\nbuild/\n/top.txt\n").unwrap();
111+ std::fs::create_dir(temp.path().join("sub")).unwrap();
112+ std::fs::write(temp.path().join("sub/.gitignore"), "!keep.log\n").unwrap();
113+ std::fs::write(temp.path().join("sub/.braidignore"), "secret\n").unwrap();
114+
115+ let root = enter(&dir(temp.path()), b"", &None);
116+ assert!(is_ignored(&root, b"a.log", false));
117+ assert!(is_ignored(&root, b"build", true));
118+ assert!(!is_ignored(&root, b"build", false));
119+ assert!(is_ignored(&root, b"top.txt", false));
120+ assert!(!is_ignored(&root, b"sub/top.txt", false));
121+ assert!(!is_ignored(&root, b"a.txt", false));
122+
123+ let sub = enter(&dir(&temp.path().join("sub")), b"sub", &root);
124+ assert!(is_ignored(&sub, b"sub/x.log", false));
125+ assert!(!is_ignored(&sub, b"sub/keep.log", false));
126+ assert!(is_ignored(&sub, b"sub/secret", false));
127+ // Directories without ignore files share their parent's rules.
128+ std::fs::create_dir(temp.path().join("plain")).unwrap();
129+ let plain = enter(&dir(&temp.path().join("plain")), b"plain", &root);
130+ assert!(Rc::ptr_eq(plain.as_ref().unwrap(), root.as_ref().unwrap()));
131+ }
132+
133+ #[cfg(unix)]
134+ #[test]
135+ fn symlinked_ignore_files_are_not_read() {
136+ let temp = tempfile::tempdir().unwrap();
137+ let outside = tempfile::tempdir().unwrap();
138+ std::fs::write(outside.path().join("rules"), "*\n").unwrap();
139+ std::os::unix::fs::symlink(outside.path().join("rules"), temp.path().join(".gitignore"))
140+ .unwrap();
141+ let root = enter(&dir(temp.path()), b"", &None);
142+ assert!(!is_ignored(&root, b"anything", false));
143+ }
144+}
added crates/wc/src/lib.rs +79 −0
@@ -0,0 +1,79 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Workspaces of elffuss-braid: working copies that many agents use at once
5+//! on one repository, each landing on a branch without waiting for the
6+//! others.
7+//!
8+//! # Layout
9+//!
10+//! A workspace is any directory holding a `.braid` file. The file is local
11+//! and never tracked; it names the repository and the workspace (see
12+//! [`braid_repo::WorkspaceLink`]). The workspace's state lives in the
13+//! repository, in `.braid/ws/<name>/`:
14+//!
15+//! ```text
16+//! state the base changeset, the branch, the directory, the file system's
17+//! name rules, marks made by `braid track`, a rebase in progress
18+//! stat the stat cache
19+//! lock locked while a command changes the workspace
20+//! ```
21+//!
22+//! # Operations
23+//!
24+//! - [`Workspace::create`] writes a tree into a new directory.
25+//! - [`Workspace::status`] compares the working copy with the base, using
26+//! the stat cache so that unchanged files are not read again.
27+//! - [`Workspace::commit`] records the working copy as a changeset on the
28+//! base. There is no staging area.
29+//! - [`Workspace::land`] puts the workspace's changesets on its branch in
30+//! one short op log transaction, fast-forwarding or rebasing them with the
31+//! engine; conflicts come back as data and the branch does not move.
32+//! - [`Workspace::update`] brings the workspace onto the branch's head,
33+//! rebasing its own changesets; conflicts are written with markers.
34+//! - [`create_change`] and [`land_change`] make and land a changeset
35+//! without any working copy.
36+//!
37+//! # Safety of checkouts
38+//!
39+//! Every write into a working copy goes through directory handles that
40+//! never follow a symlink (see the `safe` module), through a scratch file
41+//! and a rename, with modes 0644 or 0755 only. Names this platform cannot
42+//! hold, and names that would collide on the workspace's file system, are
43+//! refused before anything is written. Nothing found in the repository is
44+//! ever run: there are no hooks, filters or attributes.
45+//!
46+//! New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are
47+//! larger than 1 MiB are not committed until [`Workspace::track`] marks
48+//! them.
49+
50+#![forbid(unsafe_code)]
51+
52+mod cache;
53+mod change;
54+mod checkout;
55+mod error;
56+mod fsprobe;
57+mod identity;
58+mod ignores;
59+mod markers;
60+mod paths;
61+mod rebase;
62+mod safe;
63+mod scan;
64+mod state;
65+mod status;
66+mod tree;
67+mod workspace;
68+
69+pub use change::{ChangeRequest, Expect, create_change, land_change};
70+pub use error::Error;
71+pub use fsprobe::FileSystem;
72+pub use identity::Identity;
73+pub use paths::workspace_path;
74+pub use state::{Checkout, Rebase, RecordedConflict, State};
75+pub use status::{ChangeKind, GUARD_SIZE, PathChange, Status, is_guarded};
76+pub use workspace::{
77+ CommitOutcome, CommitRequest, LandReport, Landed, RebaseProgress, StatusReport, Updated,
78+ Workspace,
79+};
added crates/wc/src/markers.rs +200 −0
@@ -0,0 +1,200 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Conflict markers, in the style git writes them:
5+//!
6+//! ```text
7+//! <<<<<<< ours label
8+//! the lines of ours
9+//! =======
10+//! the lines of theirs
11+//! >>>>>>> theirs label
12+//! ```
13+//!
14+//! The regions come from the engine's three-way merge, so they are exactly
15+//! the hunks a conflict reports. The parts between them are merged again on
16+//! their own, which gives the clean result the whole merge would have had.
17+
18+use braid_engine::{ConflictHunk, MergeResult, merge3};
19+
20+/// The first line of a conflict region starts with this.
21+const OURS: &[u8] = b"<<<<<<<";
22+/// The line between the two sides.
23+const SEPARATOR: &[u8] = b"=======";
24+/// The last line of a conflict region starts with this.
25+const THEIRS: &[u8] = b">>>>>>>";
26+
27+/// `ours` and `theirs` merged against `base`, with each conflicting region
28+/// written between markers, or `None` when the content cannot be merged line
29+/// by line (binary content) or merges cleanly.
30+pub(crate) fn render(
31+ base: &[u8],
32+ ours: &[u8],
33+ theirs: &[u8],
34+ ours_label: &str,
35+ theirs_label: &str,
36+) -> Option<Vec<u8>> {
37+ let MergeResult::Conflict { hunks } = merge3(base, ours, theirs) else {
38+ return None;
39+ };
40+ if hunks.is_empty() {
41+ return None;
42+ }
43+ let base_lines = lines(base);
44+ let ours_lines = lines(ours);
45+ let theirs_lines = lines(theirs);
46+ let mut out = Vec::with_capacity(ours.len() + theirs.len());
47+ let (mut b, mut o, mut t) = (0, 0, 0);
48+ for hunk in &hunks {
49+ let ConflictHunk {
50+ base: hb,
51+ ours: ho,
52+ theirs: ht,
53+ } = hunk;
54+ merge_between(
55+ &mut out,
56+ &base_lines[b..hb.lines.start],
57+ &ours_lines[o..ho.lines.start],
58+ &theirs_lines[t..ht.lines.start],
59+ ours_label,
60+ theirs_label,
61+ );
62+ region(&mut out, &ho.text, &ht.text, ours_label, theirs_label);
63+ (b, o, t) = (hb.lines.end, ho.lines.end, ht.lines.end);
64+ }
65+ merge_between(
66+ &mut out,
67+ &base_lines[b..],
68+ &ours_lines[o..],
69+ &theirs_lines[t..],
70+ ours_label,
71+ theirs_label,
72+ );
73+ Some(out)
74+}
75+
76+/// Whether `content` still holds a line that starts a conflict region,
77+/// separates its sides or ends it.
78+pub(crate) fn has_markers(content: &[u8]) -> bool {
79+ lines(content).iter().any(|line| {
80+ let line = line.strip_suffix(b"\n").unwrap_or(line);
81+ let line = line.strip_suffix(b"\r").unwrap_or(line);
82+ line == SEPARATOR
83+ || [OURS, THEIRS].iter().any(|marker| {
84+ line.starts_with(marker)
85+ && (line.len() == marker.len() || line[marker.len()] == b' ')
86+ })
87+ })
88+}
89+
90+/// Lines, each with its `\n`; a last line without one is a line too.
91+fn lines(content: &[u8]) -> Vec<&[u8]> {
92+ content.split_inclusive(|byte| *byte == b'\n').collect()
93+}
94+
95+/// The lines between two conflict regions, which merged cleanly as part of
96+/// the whole; merged again on their own. Should that disagree, the stretch
97+/// is shown as a conflict too, rather than guessed.
98+fn merge_between(
99+ out: &mut Vec<u8>,
100+ base: &[&[u8]],
101+ ours: &[&[u8]],
102+ theirs: &[&[u8]],
103+ ours_label: &str,
104+ theirs_label: &str,
105+) {
106+ let (base, ours, theirs) = (base.concat(), ours.concat(), theirs.concat());
107+ match merge3(&base, &ours, &theirs) {
108+ MergeResult::Clean(merged) => out.extend_from_slice(&merged),
109+ MergeResult::Conflict { .. } => region(out, &ours, &theirs, ours_label, theirs_label),
110+ }
111+}
112+
113+fn region(out: &mut Vec<u8>, ours: &[u8], theirs: &[u8], ours_label: &str, theirs_label: &str) {
114+ marker_line(out, OURS, ours_label);
115+ side(out, ours);
116+ out.extend_from_slice(SEPARATOR);
117+ out.push(b'\n');
118+ side(out, theirs);
119+ marker_line(out, THEIRS, theirs_label);
120+}
121+
122+fn marker_line(out: &mut Vec<u8>, marker: &[u8], label: &str) {
123+ out.extend_from_slice(marker);
124+ if !label.is_empty() {
125+ out.push(b' ');
126+ out.extend_from_slice(label.replace('\n', " ").as_bytes());
127+ }
128+ out.push(b'\n');
129+}
130+
131+/// One side of a region, ending with a newline so the next marker starts a
132+/// line.
133+fn side(out: &mut Vec<u8>, text: &[u8]) {
134+ out.extend_from_slice(text);
135+ if !text.is_empty() && !text.ends_with(b"\n") {
136+ out.push(b'\n');
137+ }
138+}
139+
140+#[cfg(test)]
141+mod tests {
142+ use super::*;
143+
144+ fn text(bytes: Option<Vec<u8>>) -> String {
145+ String::from_utf8(bytes.expect("a conflict")).unwrap()
146+ }
147+
148+ #[test]
149+ fn one_region_between_clean_parts() {
150+ let base = "1\n2\n3\n4\n5\n6\n7\n";
151+ let ours = "ONE\n2\n3\nours\n5\n6\n7\n";
152+ let theirs = "1\n2\n3\ntheirs\n5\n6\nSEVEN\n";
153+ let merged = text(render(
154+ base.as_bytes(),
155+ ours.as_bytes(),
156+ theirs.as_bytes(),
157+ "main",
158+ "mine",
159+ ));
160+ assert_eq!(
161+ merged,
162+ "ONE\n2\n3\n<<<<<<< main\nours\n=======\ntheirs\n>>>>>>> mine\n5\n6\nSEVEN\n"
163+ );
164+ assert!(has_markers(merged.as_bytes()));
165+ }
166+
167+ #[test]
168+ fn several_regions_and_a_last_line_without_newline() {
169+ let base = "a\nb\nc\nd\ne\nf";
170+ let ours = "A\nb\nc\nd\ne\nF";
171+ let theirs = "a2\nb\nc\nd\ne\nf2";
172+ let merged = text(render(
173+ base.as_bytes(),
174+ ours.as_bytes(),
175+ theirs.as_bytes(),
176+ "o",
177+ "t",
178+ ));
179+ assert_eq!(
180+ merged,
181+ "<<<<<<< o\nA\n=======\na2\n>>>>>>> t\nb\nc\nd\ne\n<<<<<<< o\nF\n=======\nf2\n>>>>>>> t\n"
182+ );
183+ }
184+
185+ #[test]
186+ fn nothing_to_mark() {
187+ assert_eq!(render(b"a\n", b"b\n", b"a\n", "o", "t"), None);
188+ assert_eq!(render(b"\0a", b"\0b", b"\0c", "o", "t"), None);
189+ }
190+
191+ #[test]
192+ fn marker_detection() {
193+ assert!(!has_markers(b"plain\ntext\n"));
194+ assert!(!has_markers(b"<<<<<<<< eight\n========\n"));
195+ assert!(!has_markers(b"a <<<<<<< b\n"));
196+ assert!(has_markers(b"x\n=======\r\ny\n"));
197+ assert!(has_markers(b">>>>>>> theirs"));
198+ assert!(has_markers(b"<<<<<<<\n"));
199+ }
200+}
added crates/wc/src/paths.rs +213 −0
@@ -0,0 +1,213 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Paths of the repository, which are bytes, and the file system names they
5+//! become.
6+
7+use std::borrow::Cow;
8+use std::ffi::OsStr;
9+use std::path::{Component, Path, PathBuf};
10+
11+use crate::error::Error;
12+
13+/// How many bytes of a path messages show.
14+const SHOWN_BYTES: usize = 256;
15+
16+/// A path for messages: lossy UTF-8, cut short if it is long.
17+pub(crate) fn show(path: &[u8]) -> Cow<'_, str> {
18+ if path.len() <= SHOWN_BYTES {
19+ return String::from_utf8_lossy(path);
20+ }
21+ let mut shown = String::from_utf8_lossy(&path[..SHOWN_BYTES]).into_owned();
22+ shown.push('…');
23+ Cow::Owned(shown)
24+}
25+
26+/// `dir/name`, or `name` when `dir` is the root (empty).
27+pub(crate) fn join(dir: &[u8], name: &[u8]) -> Vec<u8> {
28+ let mut path = Vec::with_capacity(dir.len() + 1 + name.len());
29+ if !dir.is_empty() {
30+ path.extend_from_slice(dir);
31+ path.push(b'/');
32+ }
33+ path.extend_from_slice(name);
34+ path
35+}
36+
37+/// The directory part and the last name of a path; the directory of a path
38+/// with one name is the root, empty.
39+pub(crate) fn split_last(path: &[u8]) -> (&[u8], &[u8]) {
40+ match path.iter().rposition(|byte| *byte == b'/') {
41+ Some(slash) => (&path[..slash], &path[slash + 1..]),
42+ None => (&[], path),
43+ }
44+}
45+
46+/// The names of a path.
47+pub(crate) fn names(path: &[u8]) -> impl Iterator<Item = &[u8]> {
48+ path.split(|byte| *byte == b'/')
49+ .filter(|name| !name.is_empty())
50+}
51+
52+/// Every proper prefix of `path` that names a directory, shortest first:
53+/// `a`, `a/b` for `a/b/c`.
54+pub(crate) fn ancestors(path: &[u8]) -> impl Iterator<Item = &[u8]> {
55+ path.iter()
56+ .enumerate()
57+ .filter(|(_, byte)| **byte == b'/')
58+ .map(|(at, _)| &path[..at])
59+}
60+
61+/// Whether `path` is `prefix` or lies below it. The empty prefix is the
62+/// root, which holds everything.
63+pub(crate) fn is_within(path: &[u8], prefix: &[u8]) -> bool {
64+ prefix.is_empty()
65+ || path == prefix
66+ || (path.len() > prefix.len() && path.starts_with(prefix) && path[prefix.len()] == b'/')
67+}
68+
69+/// The file system name for one name of a repository path, if this platform
70+/// can represent it at all.
71+pub(crate) fn os_name(name: &[u8]) -> Option<&OsStr> {
72+ #[cfg(unix)]
73+ {
74+ use std::os::unix::ffi::OsStrExt;
75+ Some(OsStr::from_bytes(name))
76+ }
77+ #[cfg(not(unix))]
78+ {
79+ std::str::from_utf8(name).ok().map(OsStr::new)
80+ }
81+}
82+
83+/// The repository bytes of a file system name, if it has any.
84+pub(crate) fn name_bytes(name: &OsStr) -> Option<&[u8]> {
85+ #[cfg(unix)]
86+ {
87+ use std::os::unix::ffi::OsStrExt;
88+ Some(name.as_bytes())
89+ }
90+ #[cfg(not(unix))]
91+ {
92+ name.to_str().map(str::as_bytes)
93+ }
94+}
95+
96+/// Why this platform cannot hold `name` as a file name, if it cannot.
97+///
98+/// The store accepts names that some systems cannot write: Apple file
99+/// systems store names as UTF-8 and Windows forbids a set of characters and
100+/// device names. Such a name is refused before anything is written.
101+pub(crate) fn platform_problem(name: &[u8]) -> Option<&'static str> {
102+ if os_name(name).is_none() {
103+ return Some("the name is not valid UTF-8, which this platform needs");
104+ }
105+ if cfg!(target_vendor = "apple") && std::str::from_utf8(name).is_err() {
106+ return Some("the name is not valid UTF-8, which this file system needs");
107+ }
108+ if cfg!(windows) {
109+ if name
110+ .iter()
111+ .any(|byte| *byte < 0x20 || br#"<>:"\|?*"#.contains(byte))
112+ {
113+ return Some("the name holds a character Windows does not allow");
114+ }
115+ if matches!(name.last(), Some(b'.' | b' ')) {
116+ return Some("Windows drops a final dot or space");
117+ }
118+ let stem = name.split(|byte| *byte == b'.').next().unwrap_or(name);
119+ let stem = stem.to_ascii_uppercase();
120+ let device = matches!(stem.as_slice(), b"CON" | b"PRN" | b"AUX" | b"NUL")
121+ || (stem.len() == 4
122+ && (stem.starts_with(b"COM") || stem.starts_with(b"LPT"))
123+ && stem[3].is_ascii_digit());
124+ if device {
125+ return Some("the name is a Windows device name");
126+ }
127+ }
128+ None
129+}
130+
131+/// Resolves a path given on the command line, relative to `cwd`, into a
132+/// path of the workspace whose root is `root`. Both must be absolute and
133+/// free of symlinks. `.` and `..` are resolved by name, without looking at
134+/// the file system. The workspace root itself is the empty path.
135+pub fn workspace_path(root: &Path, cwd: &Path, given: &Path) -> Result<Vec<u8>, Error> {
136+ let joined = cwd.join(given);
137+ let mut normal = PathBuf::new();
138+ for component in joined.components() {
139+ match component {
140+ Component::CurDir => {}
141+ Component::ParentDir => {
142+ normal.pop();
143+ }
144+ other => normal.push(other.as_os_str()),
145+ }
146+ }
147+ let relative = normal
148+ .strip_prefix(root)
149+ .map_err(|_| Error::OutsideWorkspace(given.to_path_buf()))?;
150+ let mut bytes = Vec::new();
151+ for component in relative.components() {
152+ let name = name_bytes(component.as_os_str())
153+ .ok_or_else(|| Error::OutsideWorkspace(given.to_path_buf()))?;
154+ if !bytes.is_empty() {
155+ bytes.push(b'/');
156+ }
157+ bytes.extend_from_slice(name);
158+ }
159+ Ok(bytes)
160+}
161+
162+#[cfg(test)]
163+mod tests {
164+ use super::*;
165+
166+ #[test]
167+ fn helpers() {
168+ assert_eq!(join(b"", b"a"), b"a");
169+ assert_eq!(join(b"a/b", b"c"), b"a/b/c");
170+ assert_eq!(split_last(b"a/b/c"), (&b"a/b"[..], &b"c"[..]));
171+ assert_eq!(split_last(b"c"), (&b""[..], &b"c"[..]));
172+ assert_eq!(ancestors(b"a/b/c").collect::<Vec<_>>(), [&b"a"[..], b"a/b"]);
173+ assert_eq!(ancestors(b"c").count(), 0);
174+ assert_eq!(names(b"a/b").collect::<Vec<_>>(), [&b"a"[..], b"b"]);
175+ assert!(is_within(b"a/b", b"a"));
176+ assert!(is_within(b"a", b"a"));
177+ assert!(is_within(b"anything", b""));
178+ assert!(!is_within(b"ab", b"a"));
179+ assert!(!is_within(b"a", b"a/b"));
180+ }
181+
182+ #[test]
183+ fn command_line_paths() {
184+ let root = Path::new("/w/ws");
185+ let cwd = Path::new("/w/ws/src");
186+ assert_eq!(
187+ workspace_path(root, cwd, Path::new("a.rs")).unwrap(),
188+ b"src/a.rs"
189+ );
190+ assert_eq!(workspace_path(root, cwd, Path::new("../b")).unwrap(), b"b");
191+ assert_eq!(
192+ workspace_path(root, cwd, Path::new("./x/../y")).unwrap(),
193+ b"src/y"
194+ );
195+ assert_eq!(workspace_path(root, cwd, Path::new("..")).unwrap(), b"");
196+ assert_eq!(
197+ workspace_path(root, cwd, Path::new("/w/ws/c")).unwrap(),
198+ b"c"
199+ );
200+ assert!(matches!(
201+ workspace_path(root, cwd, Path::new("../../other")),
202+ Err(Error::OutsideWorkspace(_))
203+ ));
204+ }
205+
206+ #[test]
207+ fn platform_names() {
208+ assert_eq!(platform_problem(b"README.md"), None);
209+ if cfg!(target_vendor = "apple") {
210+ assert!(platform_problem(b"\xff").is_some());
211+ }
212+ }
213+}
added crates/wc/src/rebase.rs +379 −0
@@ -0,0 +1,379 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Putting a workspace's own changesets on top of a branch head.
5+//!
6+//! A workspace's unlanded changesets form a stack: each one's first parent
7+//! is the one before, and the first one's is on the branch. The first is
8+//! landed with [`braid_engine::land`], which needs its base on the head's
9+//! first-parent chain. The ones after it are based on a changeset that the
10+//! landing may have just rewritten, so each is rebased with the changeset it
11+//! was built on as the merge base, onto the rewritten one: the engine is
12+//! asked to land it on a temporary changeset whose first parent is its
13+//! original base and whose tree is the rewritten one's, and the result is
14+//! given the rewritten one as its parent. The temporary changesets stay in
15+//! the store, unreferenced.
16+
17+use braid_engine::{
18+ Conflict, LandOutcome, REBASED_FROM, commit, diff, entry_at, land, read_blob, read_changes,
19+ read_changeset,
20+};
21+use braid_format::{
22+ Change, ChangeOp, ChangesetParts, EntryKind, Kind, ObjectId, Objects, Signature,
23+};
24+
25+use crate::error::Error;
26+use crate::markers;
27+use crate::paths::is_within;
28+use crate::state::RecordedConflict;
29+use crate::tree::root_of;
30+
31+/// The extra field a temporary base carries, so that it can be told apart.
32+pub const TEMPORARY: &[u8] = b"braid-temporary-base";
33+
34+/// How a replay ended.
35+#[derive(Clone, Debug, PartialEq, Eq)]
36+pub(crate) enum Replayed {
37+ /// Every changeset is on top of the head; `tip` is the last of them, or
38+ /// the head itself when it had all of them already.
39+ Done { tip: ObjectId, rebased: bool },
40+ /// The changeset at `index` of the stack conflicts with `onto`, the head
41+ /// or the last changeset replayed before it.
42+ Stopped {
43+ index: usize,
44+ onto: ObjectId,
45+ conflicts: Vec<Conflict>,
46+ },
47+}
48+
49+/// How the first changeset of a stack goes onto the head.
50+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51+pub(crate) enum First {
52+ /// Landed: its base must be on the head's first-parent chain.
53+ MustBeOnBranch,
54+ /// Landed if its base is on the chain, and otherwise rebased from its
55+ /// own base wherever that is, as an update allows.
56+ Anywhere,
57+ /// Rebased from its own base, which is known not to be on the chain:
58+ /// what continuing a rebase after a resolution does.
59+ Pick,
60+}
61+
62+/// Replays `stack`, oldest first, onto `head` (`None` for an empty
63+/// branch). Fails with [`Error::NotOnBranch`] when the first changeset's
64+/// base is not on the branch and `first` requires it.
65+pub(crate) fn replay<O: Objects>(
66+ objects: &O,
67+ branch: &str,
68+ head: Option<ObjectId>,
69+ stack: &[ObjectId],
70+ committer: &Signature,
71+ first: First,
72+) -> Result<Replayed, Error> {
73+ let mut tip = head;
74+ let mut rebased = false;
75+ for (index, &change) in stack.iter().enumerate() {
76+ let outcome = match tip {
77+ Some(onto) if index > 0 || first == First::Pick => {
78+ replay_one(objects, onto, change, committer)?
79+ }
80+ _ => match land(objects, tip, change, committer.clone()) {
81+ Err(braid_engine::Error::BaseNotOnBranch { .. }) => match (first, tip) {
82+ (First::Anywhere, Some(onto)) => replay_one(objects, onto, change, committer)?,
83+ _ => {
84+ return Err(Error::NotOnBranch {
85+ branch: branch.to_owned(),
86+ });
87+ }
88+ },
89+ other => other?,
90+ },
91+ };
92+ match outcome {
93+ LandOutcome::FastForward(id) => tip = Some(id),
94+ LandOutcome::Rebased { changeset, .. } => {
95+ tip = Some(changeset);
96+ rebased = true;
97+ }
98+ LandOutcome::AlreadyApplied => {}
99+ LandOutcome::Conflicts(conflicts) => {
100+ let onto = tip.ok_or(Error::NotOnBranch {
101+ branch: branch.to_owned(),
102+ })?;
103+ return Ok(Replayed::Stopped {
104+ index,
105+ onto,
106+ conflicts,
107+ });
108+ }
109+ }
110+ }
111+ match tip {
112+ Some(tip) => Ok(Replayed::Done { tip, rebased }),
113+ None => Err(Error::NotOnBranch {
114+ branch: branch.to_owned(),
115+ }),
116+ }
117+}
118+
119+/// Rebases `change` onto `onto`, with `change`'s first parent as the merge
120+/// base, whatever history connects them. A first changeset, which has no
121+/// parent, is rebased from the empty tree.
122+pub(crate) fn replay_one<O: Objects>(
123+ objects: &O,
124+ onto: ObjectId,
125+ change: ObjectId,
126+ committer: &Signature,
127+) -> Result<LandOutcome, Error> {
128+ let theirs = read_changeset(objects, change)?;
129+ let (stand_in, base) = match theirs.parents.first() {
130+ Some(&base) if base == onto => return Ok(LandOutcome::FastForward(change)),
131+ Some(&base) => (change, base),
132+ None => {
133+ // The same change on an empty first changeset: its tree and
134+ // its change list stay what they are.
135+ let empty = commit(
136+ objects,
137+ Vec::new(),
138+ Vec::new(),
139+ committer.clone(),
140+ committer.clone(),
141+ b"braid: empty base of a rebase\n".to_vec(),
142+ vec![(TEMPORARY.to_vec(), Vec::new())],
143+ )?;
144+ let changes = read_changes(objects, change, &theirs)?.into_owned();
145+ let copy = store_parts(
146+ objects,
147+ ChangesetParts {
148+ parents: vec![empty],
149+ root: theirs.root,
150+ changes,
151+ author: theirs.author.clone(),
152+ committer: theirs.committer.clone(),
153+ message: theirs.message.clone(),
154+ extras: theirs.extras.clone(),
155+ git_origin: None,
156+ },
157+ )?;
158+ (copy, empty)
159+ }
160+ };
161+ let onto_root = read_changeset(objects, onto)?.root;
162+ let base_root = read_changeset(objects, base)?.root;
163+ let temporary = commit(
164+ objects,
165+ vec![base],
166+ diff(objects, base_root, onto_root)?,
167+ committer.clone(),
168+ committer.clone(),
169+ b"braid: temporary base of a rebase\n".to_vec(),
170+ vec![(TEMPORARY.to_vec(), onto.to_hex().into_bytes())],
171+ )?;
172+ let outcome = land(objects, Some(temporary), stand_in, committer.clone())?;
173+ let LandOutcome::Rebased {
174+ changeset,
175+ merged_paths,
176+ } = outcome
177+ else {
178+ return Ok(outcome);
179+ };
180+ // The same tree and change list, with `onto` as the first parent (the
181+ // temporary base has `onto`'s tree), naming the original change.
182+ let landed = read_changeset(objects, changeset)?;
183+ let changes = read_changes(objects, changeset, &landed)?.into_owned();
184+ let parents = std::iter::once(onto)
185+ .chain(landed.parents.iter().skip(1).copied())
186+ .collect();
187+ let mut extras: Vec<(Vec<u8>, Vec<u8>)> = landed
188+ .extras
189+ .into_iter()
190+ .filter(|(key, _)| key.as_slice() != REBASED_FROM)
191+ .collect();
192+ extras.extend(rebased_extras(change));
193+ let rebased = store_parts(
194+ objects,
195+ ChangesetParts {
196+ parents,
197+ root: landed.root,
198+ changes,
199+ author: landed.author,
200+ committer: landed.committer,
201+ message: landed.message,
202+ extras,
203+ git_origin: None,
204+ },
205+ )?;
206+ Ok(LandOutcome::Rebased {
207+ changeset: rebased,
208+ merged_paths,
209+ })
210+}
211+
212+/// Assembles and stores a changeset whose tree is stored already.
213+fn store_parts<O: Objects>(objects: &O, parts: ChangesetParts) -> Result<ObjectId, Error> {
214+ let assembled = parts.assemble()?;
215+ if let Some((_, list)) = &assembled.external_list {
216+ objects.put(Kind::Blob, list).map_err(store_error)?;
217+ }
218+ objects
219+ .put(Kind::Changeset, &assembled.encoded)
220+ .map_err(store_error)?;
221+ Ok(assembled.id)
222+}
223+
224+fn store_error<E: std::error::Error + Send + Sync + 'static>(error: E) -> Error {
225+ Error::Engine(braid_engine::Error::Store(Box::new(error)))
226+}
227+
228+/// A regular file's blob and executable bit.
229+fn regular(kind: Option<&ChangeOp>) -> Option<(ObjectId, bool)> {
230+ match kind {
231+ Some(ChangeOp::File { blob, .. }) => Some((*blob, false)),
232+ Some(ChangeOp::Executable { blob, .. }) => Some((*blob, true)),
233+ _ => None,
234+ }
235+}
236+
237+/// The file at `path` of the tree `root`, if there is one there.
238+fn file_at<O: Objects>(
239+ objects: &O,
240+ root: ObjectId,
241+ path: &[u8],
242+) -> Result<Option<ChangeOp>, Error> {
243+ Ok(entry_at(objects, root, path)?
244+ .filter(|kind| !matches!(kind, EntryKind::Tree { .. }))
245+ .and_then(|kind| ChangeOp::from_entry(&kind)))
246+}
247+
248+/// What to write when `change` stopped on `conflicts` against `onto`: the
249+/// tree of `onto`, with every path of the change that merges cleanly, and,
250+/// for each content conflict between two regular files, the merge with
251+/// conflict markers. Other conflicts keep `onto`'s version. Returns the
252+/// tree, stored, and the conflicts as the workspace records them.
253+pub(crate) fn conflict_tree<O: Objects>(
254+ objects: &O,
255+ onto: ObjectId,
256+ change: ObjectId,
257+ conflicts: &[Conflict],
258+ labels: (&str, &str),
259+) -> Result<(ObjectId, Vec<RecordedConflict>), Error> {
260+ let theirs = read_changeset(objects, change)?;
261+ let base_root = root_of(objects, theirs.parents.first().copied())?;
262+ let onto_root = read_changeset(objects, onto)?.root;
263+ let changes = read_changes(objects, change, &theirs)?.into_owned();
264+ let conflicting = |path: &[u8]| {
265+ conflicts
266+ .iter()
267+ .any(|c| is_within(path, &c.path) || is_within(&c.path, path))
268+ };
269+
270+ let mut writes: Vec<Change> = Vec::new();
271+ for item in &changes {
272+ if conflicting(&item.path) {
273+ continue;
274+ }
275+ let ours = file_at(objects, onto_root, &item.path)?;
276+ let base = file_at(objects, base_root, &item.path)?;
277+ let theirs_op = (!matches!(item.op, ChangeOp::Delete)).then(|| item.op.clone());
278+ if theirs_op == ours {
279+ continue;
280+ }
281+ if base == ours {
282+ writes.push(item.clone());
283+ continue;
284+ }
285+ // Both changed it and the engine found no conflict: two regular
286+ // files whose lines merge.
287+ let (Some((o, o_exec)), Some((t, t_exec))) =
288+ (regular(ours.as_ref()), regular(theirs_op.as_ref()))
289+ else {
290+ continue;
291+ };
292+ let base_regular = regular(base.as_ref());
293+ let base_bytes = match base_regular {
294+ Some((b, _)) => read_blob(objects, b)?,
295+ None => Vec::new(),
296+ };
297+ let braid_engine::MergeResult::Clean(merged) = braid_engine::merge3(
298+ &base_bytes,
299+ &read_blob(objects, o)?,
300+ &read_blob(objects, t)?,
301+ ) else {
302+ continue;
303+ };
304+ let executable = match base_regular {
305+ _ if o_exec == t_exec => o_exec,
306+ Some((_, b_exec)) if b_exec == o_exec => t_exec,
307+ _ => o_exec,
308+ };
309+ let op = put_file(objects, &merged, executable)?;
310+ if Some(&op) != ours.as_ref() {
311+ writes.push(Change {
312+ path: item.path.clone(),
313+ op,
314+ });
315+ }
316+ }
317+
318+ let mut recorded = Vec::new();
319+ for conflict in conflicts {
320+ let mut markers_written = false;
321+ if let braid_engine::ConflictKind::Content { .. } = conflict.kind {
322+ let ours = conflict.ours.as_ref().and_then(ChangeOp::from_entry);
323+ let theirs_op = conflict.theirs.as_ref().and_then(ChangeOp::from_entry);
324+ let base = conflict.base.as_ref().and_then(ChangeOp::from_entry);
325+ if let (Some((o, o_exec)), Some((t, _))) =
326+ (regular(ours.as_ref()), regular(theirs_op.as_ref()))
327+ {
328+ let base_bytes = match regular(base.as_ref()) {
329+ Some((b, _)) => read_blob(objects, b)?,
330+ None => Vec::new(),
331+ };
332+ let rendered = markers::render(
333+ &base_bytes,
334+ &read_blob(objects, o)?,
335+ &read_blob(objects, t)?,
336+ labels.0,
337+ labels.1,
338+ );
339+ if let Some(content) = rendered {
340+ writes.push(Change {
341+ path: conflict.path.clone(),
342+ op: put_file(objects, &content, o_exec)?,
343+ });
344+ markers_written = true;
345+ }
346+ }
347+ }
348+ if !recorded
349+ .iter()
350+ .any(|r: &RecordedConflict| r.path == conflict.path && r.code == conflict.kind.code())
351+ {
352+ recorded.push(RecordedConflict {
353+ path: conflict.path.clone(),
354+ code: conflict.kind.code().to_owned(),
355+ markers: markers_written,
356+ resolved: false,
357+ });
358+ }
359+ }
360+ writes.sort_by(|a, b| a.path.cmp(&b.path));
361+ writes.dedup_by(|a, b| a.path == b.path);
362+ let tree = braid_engine::apply(objects, onto_root, &writes)?;
363+ Ok((tree, recorded))
364+}
365+
366+fn put_file<O: Objects>(objects: &O, content: &[u8], executable: bool) -> Result<ChangeOp, Error> {
367+ let blob = objects.put(Kind::Blob, content).map_err(store_error)?;
368+ let size = content.len() as u64;
369+ Ok(if executable {
370+ ChangeOp::Executable { blob, size }
371+ } else {
372+ ChangeOp::File { blob, size }
373+ })
374+}
375+
376+/// The extras of a changeset made by finishing a rebase of `change`.
377+pub(crate) fn rebased_extras(change: ObjectId) -> Vec<(Vec<u8>, Vec<u8>)> {
378+ vec![(REBASED_FROM.to_vec(), change.to_hex().into_bytes())]
379+}
added crates/wc/src/safe.rs +357 −0
@@ -0,0 +1,357 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! File system access inside a workspace that never follows a symlink.
5+//!
6+//! Everything goes through [`cap_std`] directory handles, one name at a time:
7+//! a directory is opened from its parent's handle with `O_NOFOLLOW`, a file
8+//! is opened or created by its single name in its directory, and the only
9+//! path that is ever resolved as a whole is the workspace root itself. A
10+//! symlink in the working copy, whoever made it, is therefore a leaf: braid
11+//! reads its target as data, replaces or removes it, and never goes through
12+//! it.
13+
14+use std::ffi::OsStr;
15+use std::io::{self, Read, Seek, SeekFrom, Write};
16+use std::path::{Path, PathBuf};
17+
18+use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
19+use cap_std::fs::{Dir, File, Metadata, OpenOptions};
20+
21+use crate::error::Error;
22+use crate::fsprobe::{SCRATCH_PREFIX, random_hex};
23+use crate::paths::{names, os_name, show};
24+
25+/// What a file system entry is, as far as a workspace cares.
26+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27+pub(crate) enum StatKind {
28+ File,
29+ Dir,
30+ Symlink,
31+ /// A device, a socket, a pipe: never part of a working copy.
32+ Other,
33+}
34+
35+/// The parts of a file's metadata that a workspace uses.
36+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37+pub(crate) struct Stat {
38+ pub kind: StatKind,
39+ /// The owner may execute it.
40+ pub executable: bool,
41+ pub size: u64,
42+ /// Modification time: seconds and nanoseconds since the Unix epoch.
43+ pub mtime: (i64, u32),
44+ /// The file's number on its device, 0 where there is none.
45+ pub ino: u64,
46+}
47+
48+impl Stat {
49+ pub(crate) fn of(meta: &Metadata) -> Stat {
50+ let file_type = meta.file_type();
51+ let kind = if file_type.is_symlink() {
52+ StatKind::Symlink
53+ } else if file_type.is_dir() {
54+ StatKind::Dir
55+ } else if file_type.is_file() {
56+ StatKind::File
57+ } else {
58+ StatKind::Other
59+ };
60+ #[cfg(unix)]
61+ {
62+ use cap_std::fs::MetadataExt;
63+ Stat {
64+ kind,
65+ executable: meta.mode() & 0o100 != 0,
66+ size: meta.size(),
67+ mtime: (meta.mtime(), u32::try_from(meta.mtime_nsec()).unwrap_or(0)),
68+ ino: meta.ino(),
69+ }
70+ }
71+ #[cfg(not(unix))]
72+ {
73+ let mtime = meta
74+ .modified()
75+ .ok()
76+ .and_then(|time| time.into_std().duration_since(std::time::UNIX_EPOCH).ok())
77+ .map_or((0, 0), |since| {
78+ (since.as_secs() as i64, since.subsec_nanos())
79+ });
80+ Stat {
81+ kind,
82+ executable: false,
83+ size: meta.len(),
84+ mtime,
85+ ino: 0,
86+ }
87+ }
88+ }
89+}
90+
91+/// What is at a path of the working copy.
92+#[derive(Debug)]
93+pub(crate) enum Found<T> {
94+ /// This.
95+ Here(T),
96+ /// Nothing, and every directory above it that exists is a directory.
97+ Missing,
98+ /// Nothing can be there: the prefix of this many bytes is a file, a
99+ /// symlink or something else that is not a directory.
100+ Blocked(usize),
101+}
102+
103+/// The root directory of a workspace, open.
104+#[derive(Debug)]
105+pub(crate) struct Root {
106+ dir: Dir,
107+ path: PathBuf,
108+}
109+
110+impl Root {
111+ /// Opens the workspace directory at `path`, which must exist.
112+ pub(crate) fn open(path: &Path) -> Result<Root, Error> {
113+ let dir = Dir::open_ambient_dir(path, cap_std::ambient_authority())
114+ .map_err(Error::io("open", path))?;
115+ Ok(Root {
116+ dir,
117+ path: path.to_path_buf(),
118+ })
119+ }
120+
121+ /// The workspace's root directory.
122+ pub(crate) fn dir(&self) -> &Dir {
123+ &self.dir
124+ }
125+
126+ /// The path the root was opened at, for messages.
127+ pub(crate) fn path(&self) -> &Path {
128+ &self.path
129+ }
130+
131+ /// The directory at `path` (empty for the root), opened name by name
132+ /// without following symlinks.
133+ pub(crate) fn open_dir(&self, path: &[u8]) -> Result<Found<Dir>, Error> {
134+ let mut dir = self
135+ .dir
136+ .try_clone()
137+ .map_err(Error::io("open", &self.path))?;
138+ let mut end = 0;
139+ for name in names(path) {
140+ end += name.len() + usize::from(end > 0);
141+ let os = os_name(name).ok_or_else(|| unrepresentable(&path[..end]))?;
142+ match dir.open_dir_nofollow(os) {
143+ Ok(next) => dir = next,
144+ Err(err) => {
145+ return match dir.symlink_metadata(os) {
146+ Err(missing) if missing.kind() == io::ErrorKind::NotFound => {
147+ Ok(Found::Missing)
148+ }
149+ Ok(meta) if !meta.is_dir() => Ok(Found::Blocked(end)),
150+ _ => Err(self.error("open", &path[..end], err)),
151+ };
152+ }
153+ }
154+ }
155+ Ok(Found::Here(dir))
156+ }
157+
158+ /// The metadata of the entry at `path`, without following symlinks.
159+ pub(crate) fn stat(&self, path: &[u8]) -> Result<Found<Stat>, Error> {
160+ let (parent, name) = crate::paths::split_last(path);
161+ let dir = match self.open_dir(parent)? {
162+ Found::Here(dir) => dir,
163+ Found::Missing => return Ok(Found::Missing),
164+ Found::Blocked(at) => return Ok(Found::Blocked(at)),
165+ };
166+ let os = os_name(name).ok_or_else(|| unrepresentable(path))?;
167+ match dir.symlink_metadata(os) {
168+ Ok(meta) => Ok(Found::Here(Stat::of(&meta))),
169+ Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Found::Missing),
170+ Err(err) => Err(self.error("read", path, err)),
171+ }
172+ }
173+
174+ /// The directory at `path`, creating the directories that are missing.
175+ /// A name on the way that is not a directory is an error, never
176+ /// something to go through.
177+ pub(crate) fn create_dirs(&self, path: &[u8]) -> Result<Dir, Error> {
178+ let mut dir = self
179+ .dir
180+ .try_clone()
181+ .map_err(Error::io("open", &self.path))?;
182+ let mut end = 0;
183+ for name in names(path) {
184+ end += name.len() + usize::from(end > 0);
185+ let os = os_name(name).ok_or_else(|| unrepresentable(&path[..end]))?;
186+ match dir.create_dir(os) {
187+ Ok(()) => {}
188+ Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
189+ Err(err) => return Err(self.error("create directory", &path[..end], err)),
190+ }
191+ dir = dir.open_dir_nofollow(os).map_err(|_| Error::Unsafe {
192+ path: path[..end].to_vec(),
193+ reason: "it is in the way of a directory: a file or a symlink".to_owned(),
194+ })?;
195+ }
196+ Ok(dir)
197+ }
198+
199+ /// The modification time the file system gives a file written now: a
200+ /// one-byte rewrite of the workspace's `.braid` file, read back. This is
201+ /// the clock and the granularity of the workspace's own file system,
202+ /// which the system clock may not match.
203+ pub(crate) fn file_system_now(&self) -> io::Result<(i64, u32)> {
204+ let mut options = OpenOptions::new();
205+ options.read(true).write(true).follow(FollowSymlinks::No);
206+ let mut file = self.dir.open_with(braid_repo::DIR, &options)?;
207+ let mut first = [0u8; 1];
208+ file.read_exact(&mut first)?;
209+ file.seek(SeekFrom::Start(0))?;
210+ file.write_all(&first)?;
211+ let meta = file.metadata()?;
212+ Ok(Stat::of(&meta).mtime)
213+ }
214+
215+ pub(crate) fn error(&self, action: &'static str, path: &[u8], source: io::Error) -> Error {
216+ Error::Io {
217+ action,
218+ path: self.path.join(show(path).as_ref()),
219+ source,
220+ }
221+ }
222+}
223+
224+fn unrepresentable(path: &[u8]) -> Error {
225+ Error::Unsafe {
226+ path: path.to_vec(),
227+ reason: "this platform cannot represent the name".to_owned(),
228+ }
229+}
230+
231+/// Opens the regular file `name` of `dir` for reading, refusing a symlink.
232+pub(crate) fn open_file(dir: &Dir, name: &OsStr) -> io::Result<File> {
233+ let mut options = OpenOptions::new();
234+ options.read(true).follow(FollowSymlinks::No);
235+ dir.open_with(name, &options)
236+}
237+
238+/// The target of the symlink `name` of `dir`, as bytes.
239+pub(crate) fn read_link(dir: &Dir, name: &OsStr) -> io::Result<Vec<u8>> {
240+ let target = dir.read_link_contents(name)?;
241+ crate::paths::name_bytes(target.as_os_str())
242+ .map(<[u8]>::to_vec)
243+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "symlink target is not text"))
244+}
245+
246+/// Writes `name` in `dir` as a regular file with `content`, mode 0644 or
247+/// 0755: into a new scratch file first, then renamed over `name`. A
248+/// directory in the way is removed first, and must be empty.
249+pub(crate) fn write_file(
250+ dir: &Dir,
251+ name: &OsStr,
252+ content: &[u8],
253+ executable: bool,
254+) -> io::Result<()> {
255+ let (scratch, mut file) = create_scratch(dir)?;
256+ let written = file
257+ .write_all(content)
258+ .and_then(|()| set_mode(&file, executable));
259+ drop(file);
260+ finish(dir, &scratch, name, written)
261+}
262+
263+/// Creates `name` in `dir` as a symlink to `target`, which is stored as it
264+/// is and never resolved; renamed over whatever file or symlink was there.
265+pub(crate) fn write_symlink(dir: &Dir, name: &OsStr, target: &[u8]) -> io::Result<()> {
266+ if target.is_empty() || target.contains(&0) {
267+ return Err(io::Error::new(
268+ io::ErrorKind::InvalidData,
269+ "a symlink target must be non-empty and hold no NUL byte",
270+ ));
271+ }
272+ let target = os_name(target).ok_or_else(|| {
273+ io::Error::new(
274+ io::ErrorKind::InvalidData,
275+ "the platform cannot represent the target",
276+ )
277+ })?;
278+ loop {
279+ let scratch = format!("{SCRATCH_PREFIX}tmp-{}", random_hex());
280+ match make_symlink(dir, target, &scratch) {
281+ Ok(()) => return finish(dir, &scratch, name, Ok(())),
282+ Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
283+ Err(err) => return Err(err),
284+ }
285+ }
286+}
287+
288+#[cfg(unix)]
289+fn make_symlink(dir: &Dir, target: &OsStr, name: &str) -> io::Result<()> {
290+ dir.symlink_contents(target, name)
291+}
292+
293+#[cfg(not(unix))]
294+fn make_symlink(_dir: &Dir, _target: &OsStr, _name: &str) -> io::Result<()> {
295+ Err(io::Error::new(
296+ io::ErrorKind::Unsupported,
297+ "symlinks are only written on Unix-like systems",
298+ ))
299+}
300+
301+/// Removes the file or symlink `name` from `dir`; nothing there is fine.
302+pub(crate) fn remove_entry(dir: &Dir, name: &OsStr) -> io::Result<()> {
303+ match dir.remove_file_or_symlink(name) {
304+ Ok(()) => Ok(()),
305+ Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
306+ Err(err) => Err(err),
307+ }
308+}
309+
310+fn create_scratch(dir: &Dir) -> io::Result<(String, File)> {
311+ loop {
312+ let name = format!("{SCRATCH_PREFIX}tmp-{}", random_hex());
313+ let mut options = OpenOptions::new();
314+ options.write(true).create_new(true);
315+ #[cfg(unix)]
316+ {
317+ use cap_std::fs::OpenOptionsExt;
318+ options.mode(0o600);
319+ }
320+ match dir.open_with(&name, &options) {
321+ Ok(file) => return Ok((name, file)),
322+ Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
323+ Err(err) => return Err(err),
324+ }
325+ }
326+}
327+
328+/// Moves the scratch entry over `name` once it is written, removing an
329+/// empty directory in the way first; removes the scratch entry on failure.
330+fn finish(dir: &Dir, scratch: &str, name: &OsStr, written: io::Result<()>) -> io::Result<()> {
331+ let result = written.and_then(|()| {
332+ if let Ok(meta) = dir.symlink_metadata(name)
333+ && meta.is_dir()
334+ {
335+ dir.remove_dir(name)?;
336+ }
337+ dir.rename(scratch, dir, name)
338+ });
339+ if result.is_err() {
340+ let _ = dir.remove_file_or_symlink(scratch);
341+ }
342+ result
343+}
344+
345+/// Sets a regular file's mode to exactly 0644, or 0755 if executable.
346+#[cfg(unix)]
347+fn set_mode(file: &File, executable: bool) -> io::Result<()> {
348+ use cap_std::fs::PermissionsExt;
349+ let mode = if executable { 0o755 } else { 0o644 };
350+ file.set_permissions(cap_std::fs::Permissions::from_mode(mode))
351+}
352+
353+/// Other systems have no executable bit.
354+#[cfg(not(unix))]
355+fn set_mode(_file: &File, _executable: bool) -> io::Result<()> {
356+ Ok(())
357+}
added crates/wc/src/scan.rs +409 −0
@@ -0,0 +1,409 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Reading a working copy: every file that counts, and its blob id.
5+//!
6+//! The walk goes one directory at a time from the workspace root, never
7+//! through a symlink, skips `.braid`, `.git` and the names that alias them,
8+//! braid's own scratch files, ignored paths that are not tracked, and
9+//! untracked directories that are another workspace or repository. Files
10+//! the stat cache cannot vouch for are hashed afterwards, in parallel, one
11+//! directory per task.
12+
13+use std::collections::{BTreeMap, HashMap};
14+use std::ffi::OsStr;
15+use std::io::{self, Read};
16+use std::path::Path;
17+use std::time::{Duration, SystemTime, UNIX_EPOCH};
18+
19+use braid_format::{ChangeOp, IdHasher, Kind, ObjectId};
20+use cap_std::fs::Dir;
21+use rayon::prelude::*;
22+
23+use crate::cache::{self, Cache};
24+use crate::error::Error;
25+use crate::fsprobe::SCRATCH_PREFIX;
26+use crate::ignores::{self, Chain};
27+use crate::paths::{join, name_bytes, os_name};
28+use crate::safe::{Found, Root, Stat, StatKind, open_file, read_link};
29+use crate::tree::Flat;
30+
31+/// What a scan found.
32+#[derive(Debug, Default)]
33+pub(crate) struct Scan {
34+ /// Every file that counts, by path: regular files, executables and
35+ /// symlinks with their blobs, and the gitlinks of the base whose
36+ /// directory is there.
37+ pub files: BTreeMap<Vec<u8>, ChangeOp>,
38+ /// The stat cache for the next scan.
39+ pub cache: Cache,
40+}
41+
42+/// A file the cache could not vouch for.
43+struct Miss {
44+ name: Vec<u8>,
45+ path: Vec<u8>,
46+ stat: Stat,
47+}
48+
49+/// Scans the working copy at `root`, whose tracked files are those of
50+/// `base`, using `old` to avoid hashing files that did not change.
51+pub(crate) fn scan(root: &Root, base: &Flat, old: &Cache) -> Result<Scan, Error> {
52+ let time = root.file_system_now().unwrap_or_else(|_| fallback_now());
53+ let mut found = Scan {
54+ files: BTreeMap::new(),
55+ cache: Cache {
56+ time,
57+ entries: HashMap::new(),
58+ },
59+ };
60+ let mut misses: BTreeMap<Vec<u8>, Vec<Miss>> = BTreeMap::new();
61+
62+ // Directories to read: path, rules in force above them, and whether
63+ // they are ignored (so only tracked files count inside).
64+ let mut pending: Vec<(Vec<u8>, Chain, bool)> = vec![(Vec::new(), None, false)];
65+ while let Some((path, above, ignored)) = pending.pop() {
66+ let dir = match root.open_dir(&path)? {
67+ Found::Here(dir) => dir,
68+ // Replaced while the walk ran: whatever is there now is not a
69+ // directory to read.
70+ Found::Missing | Found::Blocked(_) => continue,
71+ };
72+ let rules = if ignored {
73+ above
74+ } else {
75+ ignores::enter(&dir, &path, &above)
76+ };
77+ for os in sorted_names(root, &dir, &path)? {
78+ let Some(name) = name_bytes(&os) else {
79+ continue;
80+ };
81+ if skipped(name) {
82+ continue;
83+ }
84+ let child = join(&path, name);
85+ let stat = match dir.symlink_metadata(&os) {
86+ Ok(meta) => Stat::of(&meta),
87+ Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
88+ Err(err) => return Err(root.error("read", &child, err)),
89+ };
90+ let tracked = base.files.get(&child);
91+ match stat.kind {
92+ StatKind::Dir => {
93+ if let Some(gitlink @ ChangeOp::Gitlink { .. }) = tracked {
94+ // A submodule's directory: its content is not ours.
95+ found.files.insert(child, gitlink.clone());
96+ continue;
97+ }
98+ let tracked_dir = base.dirs.contains(&child);
99+ let child_ignored = ignored || ignores::is_ignored(&rules, &child, true);
100+ if child_ignored && !tracked_dir {
101+ continue;
102+ }
103+ if !tracked_dir && holds_marker(&dir, &os) {
104+ continue;
105+ }
106+ pending.push((child, rules.clone(), child_ignored));
107+ }
108+ StatKind::File | StatKind::Symlink => {
109+ let child_ignored = ignored || ignores::is_ignored(&rules, &child, false);
110+ if child_ignored && tracked.is_none() {
111+ continue;
112+ }
113+ // Symlinks are cheap to read again, and their size in
114+ // the metadata is not reliable everywhere.
115+ let cached = match stat.kind {
116+ StatKind::File => old.lookup(&child, &stat),
117+ _ => None,
118+ };
119+ match cached {
120+ Some(blob) => {
121+ found
122+ .files
123+ .insert(child.clone(), op_for(&stat, blob, stat.size));
124+ if let Some(entry) = cache::Entry::new(&stat, blob) {
125+ found.cache.entries.insert(child, entry);
126+ }
127+ }
128+ None => misses.entry(path.clone()).or_default().push(Miss {
129+ name: name.to_vec(),
130+ path: child,
131+ stat,
132+ }),
133+ }
134+ }
135+ StatKind::Other => {}
136+ }
137+ }
138+ }
139+
140+ let hashed: Vec<Vec<Hashed>> = misses
141+ .into_par_iter()
142+ .map(|(dir_path, files)| hash_directory(root, &dir_path, files))
143+ .collect::<Result<_, Error>>()?;
144+ for hashed in hashed.into_iter().flatten() {
145+ if let Some(entry) = hashed
146+ .stable
147+ .and_then(|stat| cache::Entry::new(&stat, hashed.blob))
148+ {
149+ found.cache.entries.insert(hashed.path.clone(), entry);
150+ }
151+ found.files.insert(hashed.path, hashed.op);
152+ }
153+ Ok(found)
154+}
155+
156+/// Names the walk never looks at: `.braid` and `.git` and every name that
157+/// some file system would read as one of them, and braid's scratch files.
158+fn skipped(name: &[u8]) -> bool {
159+ braid_format::name::is_reserved(name) || name.starts_with(SCRATCH_PREFIX.as_bytes())
160+}
161+
162+/// Whether the directory `name` of `dir` holds a `.braid` or `.git` entry:
163+/// another workspace or repository, which an untracked directory is not part
164+/// of this one.
165+fn holds_marker(dir: &Dir, name: &OsStr) -> bool {
166+ [braid_repo::DIR, ".git"]
167+ .iter()
168+ .any(|marker| dir.symlink_metadata(Path::new(name).join(marker)).is_ok())
169+}
170+
171+/// The names in `dir`, sorted.
172+fn sorted_names(root: &Root, dir: &Dir, path: &[u8]) -> Result<Vec<std::ffi::OsString>, Error> {
173+ let mut names = Vec::new();
174+ let entries = dir.entries().map_err(|err| root.error("read", path, err))?;
175+ for entry in entries {
176+ let entry = entry.map_err(|err| root.error("read", path, err))?;
177+ names.push(entry.file_name());
178+ }
179+ names.sort();
180+ Ok(names)
181+}
182+
183+/// The change operation that sets a path to this file.
184+fn op_for(stat: &Stat, blob: ObjectId, size: u64) -> ChangeOp {
185+ match stat.kind {
186+ StatKind::Symlink => ChangeOp::Symlink { blob, size },
187+ _ if stat.executable => ChangeOp::Executable { blob, size },
188+ _ => ChangeOp::File { blob, size },
189+ }
190+}
191+
192+/// One file hashed.
193+struct Hashed {
194+ path: Vec<u8>,
195+ op: ChangeOp,
196+ blob: ObjectId,
197+ /// Its metadata, if it did not change while it was read.
198+ stable: Option<Stat>,
199+}
200+
201+/// Hashes the files of one directory. Files that vanished since the walk
202+/// are left out.
203+fn hash_directory(root: &Root, dir_path: &[u8], files: Vec<Miss>) -> Result<Vec<Hashed>, Error> {
204+ let dir = match root.open_dir(dir_path)? {
205+ Found::Here(dir) => dir,
206+ Found::Missing | Found::Blocked(_) => return Ok(Vec::new()),
207+ };
208+ let mut out = Vec::with_capacity(files.len());
209+ for miss in files {
210+ let Some(os) = os_name(&miss.name) else {
211+ continue;
212+ };
213+ let read = match miss.stat.kind {
214+ StatKind::Symlink => hash_symlink(&dir, os),
215+ _ => match hash_file(&dir, os) {
216+ // Replaced by a symlink since the walk.
217+ Err(_) if dir.symlink_metadata(os).is_ok_and(|meta| meta.is_symlink()) => {
218+ hash_symlink(&dir, os)
219+ }
220+ other => other,
221+ },
222+ };
223+ match read {
224+ Ok((op, blob, stable)) => out.push(Hashed {
225+ path: miss.path,
226+ op,
227+ blob,
228+ stable,
229+ }),
230+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}
231+ Err(err) => return Err(root.error("read", &miss.path, err)),
232+ }
233+ }
234+ Ok(out)
235+}
236+
237+type Read3 = (ChangeOp, ObjectId, Option<Stat>);
238+
239+fn hash_file(dir: &Dir, name: &OsStr) -> io::Result<Read3> {
240+ let mut file = open_file(dir, name)?;
241+ let before = Stat::of(&file.metadata()?);
242+ if before.kind != StatKind::File {
243+ return Err(io::Error::other("not a regular file"));
244+ }
245+ let mut hasher = IdHasher::new(Kind::Blob);
246+ let mut buf = vec![0u8; 64 * 1024];
247+ let mut size = 0u64;
248+ loop {
249+ let n = match file.read(&mut buf) {
250+ Ok(0) => break,
251+ Ok(n) => n,
252+ Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
253+ Err(err) => return Err(err),
254+ };
255+ hasher.update(&buf[..n]);
256+ size += n as u64;
257+ }
258+ let after = Stat::of(&file.metadata()?);
259+ let blob = hasher.finalize();
260+ let stable = (before == after && size == after.size).then_some(after);
261+ Ok((op_for(&before, blob, size), blob, stable))
262+}
263+
264+fn hash_symlink(dir: &Dir, name: &OsStr) -> io::Result<Read3> {
265+ let target = read_link(dir, name)?;
266+ let blob = ObjectId::hash(Kind::Blob, &target);
267+ Ok((
268+ ChangeOp::Symlink {
269+ blob,
270+ size: target.len() as u64,
271+ },
272+ blob,
273+ None,
274+ ))
275+}
276+
277+/// The system clock less two seconds, for when the file system's own clock
278+/// cannot be read: older than any modification a coarse file system clock
279+/// could still date to the same instant.
280+fn fallback_now() -> (i64, u32) {
281+ let since = SystemTime::now()
282+ .duration_since(UNIX_EPOCH)
283+ .unwrap_or_default()
284+ .saturating_sub(Duration::from_secs(2));
285+ (since.as_secs() as i64, since.subsec_nanos())
286+}
287+
288+#[cfg(test)]
289+mod tests {
290+ use super::*;
291+ use std::fs;
292+ use std::io::{Seek, SeekFrom, Write};
293+ use std::time::Duration;
294+
295+ fn blob(content: &str) -> ChangeOp {
296+ ChangeOp::File {
297+ blob: ObjectId::hash(Kind::Blob, content.as_bytes()),
298+ size: content.len() as u64,
299+ }
300+ }
301+
302+ /// A directory with a `.braid` file, as every workspace has.
303+ fn workspace() -> (tempfile::TempDir, Root) {
304+ let dir = tempfile::tempdir().unwrap();
305+ fs::write(dir.path().join(braid_repo::DIR), b"braid-workspace 1\n").unwrap();
306+ let root = Root::open(dir.path()).unwrap();
307+ (dir, root)
308+ }
309+
310+ fn set_mtime(path: &Path, time: SystemTime) {
311+ fs::File::options()
312+ .write(true)
313+ .open(path)
314+ .unwrap()
315+ .set_modified(time)
316+ .unwrap();
317+ }
318+
319+ #[test]
320+ fn unchanged_files_are_not_read_again() {
321+ let (dir, root) = workspace();
322+ let path = dir.path().join("a.txt");
323+ fs::write(&path, "one").unwrap();
324+ let past = SystemTime::now() - Duration::from_secs(30);
325+ set_mtime(&path, past);
326+ let base = Flat::default();
327+
328+ let first = scan(&root, &base, &Cache::default()).unwrap();
329+ assert_eq!(first.files[&b"a.txt".to_vec()], blob("one"));
330+ assert!(first.cache.entries.contains_key(b"a.txt".as_slice()));
331+
332+ // Rewrite the content in place behind the cache's back: same inode,
333+ // same size, same modification time. The cache vouches for it, so
334+ // the file is not read, and the old blob is what the scan reports.
335+ let mut file = fs::File::options().write(true).open(&path).unwrap();
336+ file.seek(SeekFrom::Start(0)).unwrap();
337+ file.write_all(b"two").unwrap();
338+ drop(file);
339+ set_mtime(&path, past);
340+ let second = scan(&root, &base, &first.cache).unwrap();
341+ assert_eq!(second.files[&b"a.txt".to_vec()], blob("one"));
342+
343+ // A file whose time is not strictly older than the cache's scan is
344+ // read again, whatever the rest of its metadata says.
345+ let (seconds, nanos) = second.cache.time;
346+ let same_instant = UNIX_EPOCH + Duration::new(seconds as u64, nanos);
347+ set_mtime(&path, same_instant);
348+ let mut racy = second.cache.clone();
349+ racy.entries.get_mut(b"a.txt".as_slice()).unwrap().mtime = (seconds, nanos);
350+ let third = scan(&root, &base, &racy).unwrap();
351+ assert_eq!(third.files[&b"a.txt".to_vec()], blob("two"));
352+ }
353+
354+ #[test]
355+ fn what_the_walk_skips() {
356+ let (dir, root) = workspace();
357+ let at = |p: &str| dir.path().join(p);
358+ fs::write(at(".gitignore"), "*.log\nbuild/\n").unwrap();
359+ fs::write(at("app.log"), "ignored").unwrap();
360+ fs::write(at("kept.log"), "tracked, so not ignored").unwrap();
361+ fs::create_dir_all(at("build/sub")).unwrap();
362+ fs::write(at("build/out.o"), "ignored").unwrap();
363+ fs::write(at("build/sub/tracked.txt"), "tracked").unwrap();
364+ fs::create_dir_all(at(".git")).unwrap();
365+ fs::write(at(".git/config"), "skipped").unwrap();
366+ fs::write(at(".braid-tmp-0123"), "scratch").unwrap();
367+ fs::create_dir_all(at("nested")).unwrap();
368+ fs::write(at("nested/.braid"), "another workspace").unwrap();
369+ fs::write(at("nested/file"), "not ours").unwrap();
370+ fs::write(at("src.rs"), "code").unwrap();
371+
372+ let mut base = Flat::default();
373+ base.files.insert(b"kept.log".to_vec(), blob("old"));
374+ base.files
375+ .insert(b"build/sub/tracked.txt".to_vec(), blob("tracked"));
376+ base.dirs.insert(b"build".to_vec());
377+ base.dirs.insert(b"build/sub".to_vec());
378+
379+ let found = scan(&root, &base, &Cache::default()).unwrap();
380+ let paths: Vec<String> = found
381+ .files
382+ .keys()
383+ .map(|p| String::from_utf8(p.clone()).unwrap())
384+ .collect();
385+ assert_eq!(
386+ paths,
387+ [".gitignore", "build/sub/tracked.txt", "kept.log", "src.rs"]
388+ );
389+ }
390+
391+ #[cfg(unix)]
392+ #[test]
393+ fn symlinks_are_read_not_followed() {
394+ let (dir, root) = workspace();
395+ let outside = tempfile::tempdir().unwrap();
396+ fs::write(outside.path().join("secret"), "outside").unwrap();
397+ std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
398+ let found = scan(&root, &Flat::default(), &Cache::default()).unwrap();
399+ let target = outside.path().as_os_str().as_encoded_bytes().to_vec();
400+ assert_eq!(found.files.len(), 1);
401+ assert_eq!(
402+ found.files[&b"link".to_vec()],
403+ ChangeOp::Symlink {
404+ blob: ObjectId::hash(Kind::Blob, &target),
405+ size: target.len() as u64,
406+ }
407+ );
408+ }
409+}
added crates/wc/src/state.rs +349 −0
@@ -0,0 +1,349 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! The state of a workspace, kept in the repository under
5+//! `.braid/ws/<name>/`:
6+//!
7+//! ```text
8+//! state what the workspace is at (below)
9+//! stat the stat cache
10+//! lock locked while a command changes the workspace
11+//! ```
12+//!
13+//! `state` is a small text file, rewritten whole through a scratch file and
14+//! a rename. Values are escaped with [`braid_repo::text::escape`].
15+//!
16+//! ```text
17+//! braid-workspace-state 1
18+//! path <workspace directory>
19+//! branch <branch it lands on>
20+//! base <changeset the working copy is at, or none>
21+//! upstream <last changeset of the branch it was brought onto, or none>
22+//! fs ignores-case=<yes|no> ignores-normalization=<yes|no>
23+//! checkout <from tree> <to tree> only while a checkout is unfinished
24+//! track <path> one per `braid track`
25+//! rebase-change <changeset> only while a rebase is in progress:
26+//! rebase-onto <changeset> the changeset being rebased, where
27+//! rebase-pending <changeset> to, those still to rebase after it,
28+//! conflict <code> <markers> <resolved> <path> and its conflicts
29+//! ```
30+
31+use std::fs::{self, File, OpenOptions};
32+use std::io::Write;
33+use std::path::{Path, PathBuf};
34+
35+use braid_format::ObjectId;
36+use braid_repo::text::{escape, path_bytes, path_from_bytes, unescape};
37+
38+use crate::error::Error;
39+use crate::fsprobe::{FileSystem, random_hex};
40+
41+const HEADER: &str = "braid-workspace-state 1";
42+
43+/// The file that holds the state, inside the workspace's state directory.
44+pub(crate) const FILE: &str = "state";
45+
46+/// The lock file, inside the workspace's state directory.
47+pub(crate) const LOCK: &str = "lock";
48+
49+/// One conflict of a rebase in progress.
50+#[derive(Clone, Debug, PartialEq, Eq)]
51+pub struct RecordedConflict {
52+ /// Where it is.
53+ pub path: Vec<u8>,
54+ /// Its kind, as [`braid_engine::ConflictKind::code`] names it.
55+ pub code: String,
56+ /// Whether the file was written with conflict markers. Such a conflict
57+ /// is resolved by editing them out; any other by `braid resolve`.
58+ pub markers: bool,
59+ /// Whether `braid resolve` marked it resolved.
60+ pub resolved: bool,
61+}
62+
63+/// A checkout that was started and not finished: the working copy may be
64+/// anywhere between the two trees.
65+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66+pub struct Checkout {
67+ /// The tree the working copy was at.
68+ pub from: ObjectId,
69+ /// The tree it was being brought to.
70+ pub to: ObjectId,
71+}
72+
73+/// A rebase stopped by conflicts, waiting for `braid commit`.
74+#[derive(Clone, Debug, PartialEq, Eq)]
75+pub struct Rebase {
76+ /// The changeset being rebased.
77+ pub change: ObjectId,
78+ /// Where it goes: the workspace's base while the rebase lasts, and the
79+ /// parent of the changeset that `braid commit` makes.
80+ pub onto: ObjectId,
81+ /// Changesets to rebase after it, oldest first.
82+ pub pending: Vec<ObjectId>,
83+ /// Its conflicts.
84+ pub conflicts: Vec<RecordedConflict>,
85+}
86+
87+/// What a workspace is at.
88+#[derive(Clone, Debug, PartialEq, Eq)]
89+pub struct State {
90+ /// The workspace directory.
91+ pub path: PathBuf,
92+ /// The branch it lands on and updates from.
93+ pub branch: String,
94+ /// The changeset its working copy is at; `None` before the first commit
95+ /// on a branch that does not exist yet.
96+ pub base: Option<ObjectId>,
97+ /// The last changeset of the branch that the workspace was brought onto:
98+ /// where its own changesets start. A hint, checked before it is used.
99+ pub upstream: Option<ObjectId>,
100+ /// What its file system takes for the same name.
101+ pub fs: FileSystem,
102+ /// Set while a checkout is not finished.
103+ pub checkout: Option<Checkout>,
104+ /// Paths given to `braid track`.
105+ pub tracked: Vec<Vec<u8>>,
106+ /// The rebase in progress, if any.
107+ pub rebase: Option<Rebase>,
108+}
109+
110+impl State {
111+ /// Reads the state file in `dir`.
112+ pub(crate) fn load(dir: &Path) -> Result<State, Error> {
113+ let path = dir.join(FILE);
114+ let bytes = fs::read(&path).map_err(Error::io("read", &path))?;
115+ decode(&bytes).map_err(|detail| Error::BadState { path, detail })
116+ }
117+
118+ /// Writes the state file in `dir`, durably, through a scratch file and
119+ /// a rename.
120+ pub(crate) fn save(&self, dir: &Path) -> Result<(), Error> {
121+ let target = dir.join(FILE);
122+ let scratch = dir.join(format!("{FILE}.tmp-{}", random_hex()));
123+ let written = File::create_new(&scratch)
124+ .and_then(|mut file| {
125+ file.write_all(self.encode().as_bytes())?;
126+ file.sync_all()
127+ })
128+ .and_then(|()| fs::rename(&scratch, &target))
129+ .and_then(|()| File::open(dir)?.sync_all());
130+ if written.is_err() {
131+ let _ = fs::remove_file(&scratch);
132+ }
133+ written.map_err(Error::io("write", &target))
134+ }
135+
136+ fn encode(&self) -> String {
137+ let id = |id: Option<ObjectId>| id.map_or_else(|| "none".to_owned(), |id| id.to_hex());
138+ let yes = |flag: bool| if flag { "yes" } else { "no" };
139+ let mut text = format!(
140+ "{HEADER}\npath {}\nbranch {}\nbase {}\nupstream {}\nfs ignores-case={} ignores-normalization={}\n",
141+ escape(&path_bytes(&self.path).unwrap_or_default()),
142+ escape(self.branch.as_bytes()),
143+ id(self.base),
144+ id(self.upstream),
145+ yes(self.fs.ignores_case),
146+ yes(self.fs.ignores_normalization),
147+ );
148+ if let Some(Checkout { from, to }) = self.checkout {
149+ text.push_str(&format!("checkout {from} {to}\n"));
150+ }
151+ for path in &self.tracked {
152+ text.push_str(&format!("track {}\n", escape(path)));
153+ }
154+ if let Some(rebase) = &self.rebase {
155+ text.push_str(&format!("rebase-change {}\n", rebase.change));
156+ text.push_str(&format!("rebase-onto {}\n", rebase.onto));
157+ for pending in &rebase.pending {
158+ text.push_str(&format!("rebase-pending {pending}\n"));
159+ }
160+ for conflict in &rebase.conflicts {
161+ text.push_str(&format!(
162+ "conflict {} {} {} {}\n",
163+ conflict.code,
164+ yes(conflict.markers),
165+ yes(conflict.resolved),
166+ escape(&conflict.path)
167+ ));
168+ }
169+ }
170+ text
171+ }
172+}
173+
174+fn decode(bytes: &[u8]) -> Result<State, String> {
175+ let text = std::str::from_utf8(bytes).map_err(|_| "not UTF-8".to_owned())?;
176+ let mut lines = text.lines();
177+ if lines.next() != Some(HEADER) {
178+ return Err(format!("the first line is not {HEADER:?}"));
179+ }
180+ let mut state = State {
181+ path: PathBuf::new(),
182+ branch: String::new(),
183+ base: None,
184+ upstream: None,
185+ fs: FileSystem::FORGIVING,
186+ checkout: None,
187+ tracked: Vec::new(),
188+ rebase: None,
189+ };
190+ let mut change = None;
191+ let mut onto = None;
192+ let mut pending = Vec::new();
193+ let mut conflicts = Vec::new();
194+ for line in lines {
195+ let (key, value) = line.split_once(' ').unwrap_or((line, ""));
196+ let bad = || format!("bad {key} line: {line:?}");
197+ let bytes = || unescape(value).ok_or_else(bad);
198+ let id = || value.parse::<ObjectId>().map_err(|_| bad());
199+ let maybe_id = || match value {
200+ "none" => Ok(None),
201+ _ => id().map(Some),
202+ };
203+ match key {
204+ "path" => state.path = path_from_bytes(&bytes()?).ok_or_else(bad)?,
205+ "branch" => state.branch = String::from_utf8(bytes()?).map_err(|_| bad())?,
206+ "base" => state.base = maybe_id()?,
207+ "upstream" => state.upstream = maybe_id()?,
208+ "fs" => {
209+ state.fs = FileSystem {
210+ ignores_case: value.contains("ignores-case=yes"),
211+ ignores_normalization: value.contains("ignores-normalization=yes"),
212+ }
213+ }
214+ "checkout" => {
215+ let (from, to) = value.split_once(' ').ok_or_else(bad)?;
216+ state.checkout = Some(Checkout {
217+ from: from.parse().map_err(|_| bad())?,
218+ to: to.parse().map_err(|_| bad())?,
219+ });
220+ }
221+ "track" => state.tracked.push(bytes()?),
222+ "rebase-change" => change = Some(id()?),
223+ "rebase-onto" => onto = Some(id()?),
224+ "rebase-pending" => pending.push(id()?),
225+ "conflict" => {
226+ let mut parts = value.splitn(4, ' ');
227+ let (Some(code), Some(markers), Some(resolved), Some(path)) =
228+ (parts.next(), parts.next(), parts.next(), parts.next())
229+ else {
230+ return Err(bad());
231+ };
232+ conflicts.push(RecordedConflict {
233+ path: unescape(path).ok_or_else(bad)?,
234+ code: code.to_owned(),
235+ markers: markers == "yes",
236+ resolved: resolved == "yes",
237+ });
238+ }
239+ // Later versions may add lines; this one ignores them.
240+ _ => {}
241+ }
242+ }
243+ if state.branch.is_empty() {
244+ return Err("no branch".to_owned());
245+ }
246+ match (change, onto) {
247+ (Some(change), Some(onto)) => {
248+ state.rebase = Some(Rebase {
249+ change,
250+ onto,
251+ pending,
252+ conflicts,
253+ });
254+ }
255+ (None, None) => {}
256+ _ => return Err("an incomplete rebase".to_owned()),
257+ }
258+ Ok(state)
259+}
260+
261+/// The lock of a workspace, held until dropped.
262+#[derive(Debug)]
263+pub(crate) struct Lock {
264+ _file: File,
265+}
266+
267+impl Lock {
268+ /// Waits for the lock of the workspace whose state is in `dir`.
269+ pub(crate) fn acquire(dir: &Path) -> Result<Lock, Error> {
270+ let path = dir.join(LOCK);
271+ let file = OpenOptions::new()
272+ .read(true)
273+ .write(true)
274+ .create(true)
275+ .truncate(false)
276+ .open(&path)
277+ .map_err(Error::io("open", &path))?;
278+ file.lock().map_err(Error::io("lock", &path))?;
279+ Ok(Lock { _file: file })
280+ }
281+}
282+
283+#[cfg(test)]
284+mod tests {
285+ use super::*;
286+ use braid_format::Kind;
287+
288+ #[test]
289+ fn round_trip() {
290+ let dir = tempfile::tempdir().unwrap();
291+ let a = ObjectId::hash(Kind::Changeset, b"a");
292+ let b = ObjectId::hash(Kind::Changeset, b"b");
293+ let mut state = State {
294+ path: PathBuf::from("/work/agent 1"),
295+ branch: "main".to_owned(),
296+ base: Some(a),
297+ upstream: None,
298+ fs: FileSystem {
299+ ignores_case: true,
300+ ignores_normalization: false,
301+ },
302+ checkout: Some(Checkout {
303+ from: ObjectId::hash(Kind::Tree, b"t"),
304+ to: ObjectId::hash(Kind::Tree, b"u"),
305+ }),
306+ tracked: vec![b".env".to_vec(), b"keys/id rsa".to_vec()],
307+ rebase: None,
308+ };
309+ state.save(dir.path()).unwrap();
310+ assert_eq!(State::load(dir.path()).unwrap(), state);
311+
312+ state.rebase = Some(Rebase {
313+ change: a,
314+ onto: b,
315+ pending: vec![a, b],
316+ conflicts: vec![RecordedConflict {
317+ path: b"dir/with space\n".to_vec(),
318+ code: "CONTENT".to_owned(),
319+ markers: true,
320+ resolved: false,
321+ }],
322+ });
323+ state.checkout = None;
324+ state.save(dir.path()).unwrap();
325+ assert_eq!(State::load(dir.path()).unwrap(), state);
326+ // Only the state file is left.
327+ assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
328+
329+ fs::write(
330+ dir.path().join(FILE),
331+ "braid-workspace-state 1\nbase nonsense\n",
332+ )
333+ .unwrap();
334+ assert!(matches!(
335+ State::load(dir.path()),
336+ Err(Error::BadState { .. })
337+ ));
338+ }
339+
340+ #[test]
341+ fn the_lock_excludes_other_holders() {
342+ let dir = tempfile::tempdir().unwrap();
343+ let held = Lock::acquire(dir.path()).unwrap();
344+ let other = File::open(dir.path().join(LOCK)).unwrap();
345+ assert!(other.try_lock().is_err());
346+ drop(held);
347+ assert!(other.try_lock().is_ok());
348+ }
349+}
added crates/wc/src/status.rs +219 −0
@@ -0,0 +1,219 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! What differs between a working copy and its base, and the secrets guard.
5+
6+use braid_format::ChangeOp;
7+
8+use crate::paths::{is_within, split_last};
9+use crate::scan::Scan;
10+use crate::tree::{Flat, same_class};
11+
12+/// New files larger than this are not committed until `braid track` marks
13+/// them: 1 MiB.
14+pub const GUARD_SIZE: u64 = 1 << 20;
15+
16+/// How a path differs from the base.
17+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18+pub enum ChangeKind {
19+ /// A new file.
20+ Added,
21+ /// A file whose content or executable bit changed.
22+ Modified,
23+ /// A file that is gone.
24+ Deleted,
25+ /// A path that changed between a regular file, a symlink and a gitlink.
26+ TypeChanged,
27+}
28+
29+impl ChangeKind {
30+ /// A short, stable name for reports and JSON.
31+ pub fn name(self) -> &'static str {
32+ match self {
33+ ChangeKind::Added => "added",
34+ ChangeKind::Modified => "modified",
35+ ChangeKind::Deleted => "deleted",
36+ ChangeKind::TypeChanged => "typechange",
37+ }
38+ }
39+}
40+
41+/// One path that differs from the base.
42+#[derive(Clone, Debug, PartialEq, Eq)]
43+pub struct PathChange {
44+ /// The path.
45+ pub path: Vec<u8>,
46+ /// How it differs.
47+ pub kind: ChangeKind,
48+ /// What committing it records: the file as it is now, or a delete.
49+ pub op: ChangeOp,
50+}
51+
52+/// How a working copy differs from its base.
53+#[derive(Clone, Debug, Default, PartialEq, Eq)]
54+pub struct Status {
55+ /// Every path that a commit would record, sorted by path.
56+ pub changes: Vec<PathChange>,
57+ /// New files held back by the secrets guard until `braid track` marks
58+ /// them, sorted.
59+ pub needs_track: Vec<Vec<u8>>,
60+}
61+
62+impl Status {
63+ /// Whether nothing would be committed. Files waiting for `braid track`
64+ /// do not count: they are not committed until marked.
65+ pub fn is_clean(&self) -> bool {
66+ self.changes.is_empty()
67+ }
68+}
69+
70+/// Whether a new file must be marked with `braid track` before it is
71+/// committed: its name looks like a secret (`.env*`, `*.pem`, `id_*`, in
72+/// any letter case) or it is larger than [`GUARD_SIZE`].
73+pub fn is_guarded(path: &[u8], size: u64) -> bool {
74+ let name = split_last(path).1.to_ascii_lowercase();
75+ size > GUARD_SIZE
76+ || name.starts_with(b".env")
77+ || name.ends_with(b".pem")
78+ || name.starts_with(b"id_")
79+}
80+
81+/// Compares a scan with the base. A new file that the guard holds back is
82+/// listed in `needs_track` instead, unless one of `marks` (paths given to
83+/// `braid track`) is it or a directory above it.
84+pub(crate) fn compare(base: &Flat, scan: &Scan, marks: &[Vec<u8>]) -> Status {
85+ let mut status = Status::default();
86+ let mut olds = base.files.iter().peekable();
87+ let mut news = scan.files.iter().peekable();
88+ loop {
89+ let order = match (olds.peek(), news.peek()) {
90+ (None, None) => break,
91+ (Some(_), None) => std::cmp::Ordering::Less,
92+ (None, Some(_)) => std::cmp::Ordering::Greater,
93+ (Some((a, _)), Some((b, _))) => a.cmp(b),
94+ };
95+ match order {
96+ std::cmp::Ordering::Less => {
97+ let (path, _) = olds.next().expect("peeked");
98+ status.changes.push(PathChange {
99+ path: path.clone(),
100+ kind: ChangeKind::Deleted,
101+ op: ChangeOp::Delete,
102+ });
103+ }
104+ std::cmp::Ordering::Greater => {
105+ let (path, op) = news.next().expect("peeked");
106+ if is_guarded(path, size_of(op)) && !marks.iter().any(|mark| is_within(path, mark))
107+ {
108+ status.needs_track.push(path.clone());
109+ } else {
110+ status.changes.push(PathChange {
111+ path: path.clone(),
112+ kind: ChangeKind::Added,
113+ op: op.clone(),
114+ });
115+ }
116+ }
117+ std::cmp::Ordering::Equal => {
118+ let (path, old) = olds.next().expect("peeked");
119+ let (_, new) = news.next().expect("peeked");
120+ if old != new {
121+ let kind = if same_class(old, new) {
122+ ChangeKind::Modified
123+ } else {
124+ ChangeKind::TypeChanged
125+ };
126+ status.changes.push(PathChange {
127+ path: path.clone(),
128+ kind,
129+ op: new.clone(),
130+ });
131+ }
132+ }
133+ }
134+ }
135+ status
136+}
137+
138+fn size_of(op: &ChangeOp) -> u64 {
139+ match op {
140+ ChangeOp::File { size, .. }
141+ | ChangeOp::Executable { size, .. }
142+ | ChangeOp::Symlink { size, .. } => *size,
143+ ChangeOp::Gitlink { .. } | ChangeOp::Delete => 0,
144+ }
145+}
146+
147+#[cfg(test)]
148+mod tests {
149+ use super::*;
150+ use braid_format::{Kind, ObjectId};
151+
152+ fn file(content: &str) -> ChangeOp {
153+ ChangeOp::File {
154+ blob: ObjectId::hash(Kind::Blob, content.as_bytes()),
155+ size: content.len() as u64,
156+ }
157+ }
158+
159+ #[test]
160+ fn the_guard() {
161+ for guarded in [
162+ ".env",
163+ ".env.local",
164+ "config/.ENV",
165+ "key.pem",
166+ "id_rsa",
167+ "a/id_ed25519",
168+ ] {
169+ assert!(is_guarded(guarded.as_bytes(), 10), "{guarded}");
170+ }
171+ for plain in ["env", "README.md", "pem.txt", "my_id_rsa", "src/main.rs"] {
172+ assert!(!is_guarded(plain.as_bytes(), 10), "{plain}");
173+ }
174+ assert!(is_guarded(b"big.bin", GUARD_SIZE + 1));
175+ assert!(!is_guarded(b"exact.bin", GUARD_SIZE));
176+ }
177+
178+ #[test]
179+ fn comparing() {
180+ let mut base = Flat::default();
181+ base.files.insert(b"same".to_vec(), file("1"));
182+ base.files.insert(b"edited".to_vec(), file("1"));
183+ base.files.insert(b"gone".to_vec(), file("1"));
184+ base.files.insert(b"link".to_vec(), file("1"));
185+ let mut scan = Scan::default();
186+ scan.files.insert(b"same".to_vec(), file("1"));
187+ scan.files.insert(b"edited".to_vec(), file("2"));
188+ let target = ObjectId::hash(Kind::Blob, b"t");
189+ scan.files.insert(
190+ b"link".to_vec(),
191+ ChangeOp::Symlink {
192+ blob: target,
193+ size: 1,
194+ },
195+ );
196+ scan.files.insert(b"new".to_vec(), file("3"));
197+ scan.files.insert(b"secrets/.env".to_vec(), file("k=v"));
198+ scan.files.insert(b"keys/id_rsa".to_vec(), file("k"));
199+
200+ let status = compare(&base, &scan, &[b"keys".to_vec()]);
201+ let kinds: Vec<(&[u8], ChangeKind)> = status
202+ .changes
203+ .iter()
204+ .map(|c| (c.path.as_slice(), c.kind))
205+ .collect();
206+ assert_eq!(
207+ kinds,
208+ [
209+ (&b"edited"[..], ChangeKind::Modified),
210+ (b"gone", ChangeKind::Deleted),
211+ (b"keys/id_rsa", ChangeKind::Added),
212+ (b"link", ChangeKind::TypeChanged),
213+ (b"new", ChangeKind::Added),
214+ ]
215+ );
216+ assert_eq!(status.needs_track, [b"secrets/.env".to_vec()]);
217+ assert!(!status.is_clean());
218+ }
219+}
added crates/wc/src/tree.rs +98 −0
@@ -0,0 +1,98 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Trees as a workspace sees them: every file by path.
5+
6+use std::collections::{BTreeMap, BTreeSet};
7+
8+use braid_engine::{EMPTY_TREE, read_changeset, read_tree};
9+use braid_format::{ChangeOp, EntryKind, ObjectId, Objects};
10+
11+use crate::error::Error;
12+use crate::paths::join;
13+
14+/// Every file of a tree, by path, and every directory.
15+#[derive(Clone, Debug, Default, PartialEq, Eq)]
16+pub(crate) struct Flat {
17+ /// Regular files, executables, symlinks and gitlinks.
18+ pub files: BTreeMap<Vec<u8>, ChangeOp>,
19+ /// Paths of directories, the root excepted.
20+ pub dirs: BTreeSet<Vec<u8>>,
21+}
22+
23+/// Reads the whole tree `root`. The walk keeps its own stack.
24+pub(crate) fn flatten<O: Objects>(objects: &O, root: ObjectId) -> Result<Flat, Error> {
25+ let mut flat = Flat::default();
26+ let mut pending = vec![(Vec::new(), root)];
27+ while let Some((dir, tree)) = pending.pop() {
28+ for entry in read_tree(objects, tree)? {
29+ let path = join(&dir, &entry.name);
30+ match &entry.kind {
31+ EntryKind::Tree { tree } => {
32+ flat.dirs.insert(path.clone());
33+ pending.push((path, *tree));
34+ }
35+ kind => {
36+ if let Some(op) = ChangeOp::from_entry(kind) {
37+ flat.files.insert(path, op);
38+ }
39+ }
40+ }
41+ }
42+ }
43+ Ok(flat)
44+}
45+
46+/// The root tree of a changeset, or the empty tree for none.
47+pub(crate) fn root_of<O: Objects>(
48+ objects: &O,
49+ changeset: Option<ObjectId>,
50+) -> Result<ObjectId, Error> {
51+ match changeset {
52+ Some(id) => Ok(read_changeset(objects, id)?.root),
53+ None => Ok(EMPTY_TREE),
54+ }
55+}
56+
57+/// Whether two entries are the same kind of thing: regular files (with or
58+/// without the executable bit), symlinks, or gitlinks.
59+pub(crate) fn same_class(a: &ChangeOp, b: &ChangeOp) -> bool {
60+ let class = |op: &ChangeOp| match op {
61+ ChangeOp::File { .. } | ChangeOp::Executable { .. } => 0,
62+ ChangeOp::Symlink { .. } => 1,
63+ ChangeOp::Gitlink { .. } => 2,
64+ ChangeOp::Delete => 3,
65+ };
66+ class(a) == class(b)
67+}
68+
69+#[cfg(test)]
70+mod tests {
71+ use super::*;
72+ use braid_format::{Change, Kind, MemoryObjects};
73+
74+ #[test]
75+ fn flattening() {
76+ let objects = MemoryObjects::new();
77+ let blob = objects.put(Kind::Blob, b"x").unwrap();
78+ let file = ChangeOp::File { blob, size: 1 };
79+ let changes: Vec<Change> = ["a/b/c", "a/d", "e"]
80+ .iter()
81+ .map(|path| Change {
82+ path: path.as_bytes().to_vec(),
83+ op: file.clone(),
84+ })
85+ .collect();
86+ let root = braid_engine::apply(&objects, EMPTY_TREE, &changes).unwrap();
87+ let flat = flatten(&objects, root).unwrap();
88+ assert_eq!(
89+ flat.files.keys().cloned().collect::<Vec<_>>(),
90+ [b"a/b/c".to_vec(), b"a/d".to_vec(), b"e".to_vec()]
91+ );
92+ assert_eq!(
93+ flat.dirs.iter().cloned().collect::<Vec<_>>(),
94+ [b"a".to_vec(), b"a/b".to_vec()]
95+ );
96+ assert_eq!(flatten(&objects, EMPTY_TREE).unwrap(), Flat::default());
97+ }
98+}
added crates/wc/src/workspace.rs +1204 −0
@@ -0,0 +1,1204 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! A workspace: a working copy on a branch, sharing the repository's store
5+//! with every other workspace.
6+//!
7+//! Every operation that changes a workspace holds its lock from start to
8+//! end, and reads the state only once it holds it, so two processes never
9+//! change one workspace at once. Workspaces never wait for each other,
10+//! except for the short op log transaction in which a landing moves a
11+//! branch.
12+
13+use std::collections::HashSet;
14+use std::fs;
15+use std::io::{self, Read};
16+use std::path::{Path, PathBuf};
17+
18+use braid_engine::{Conflict, EMPTY_TREE, first_parent_chain_contains, read_changeset};
19+use braid_format::{Change, ChangeOp, Kind, ObjectId, Objects, Signature};
20+use braid_repo::{DIR, Repo, WORKSPACES_DIR, WorkspaceLink};
21+use braid_store::{RefUpdate, Store, TransactError};
22+
23+use crate::cache::Cache;
24+use crate::checkout::{self, Mode, Plan};
25+use crate::error::Error;
26+use crate::fsprobe::FileSystem;
27+use crate::identity::Identity;
28+use crate::markers::has_markers;
29+use crate::paths::{is_within, os_name, split_last};
30+use crate::rebase::{First, Replayed, conflict_tree, rebased_extras, replay};
31+use crate::safe::{Found, Root, Stat, StatKind, open_file, read_link};
32+use crate::scan;
33+use crate::state::{Checkout, Lock, Rebase, RecordedConflict, State};
34+use crate::status::{self, Status};
35+use crate::tree::{flatten, root_of};
36+
37+/// A workspace of a repository.
38+#[derive(Debug)]
39+pub struct Workspace<'r> {
40+ repo: &'r Repo,
41+ name: String,
42+ dir: PathBuf,
43+ state_dir: PathBuf,
44+}
45+
46+/// What `status` reports.
47+#[derive(Clone, Debug)]
48+pub struct StatusReport {
49+ /// The workspace's state.
50+ pub state: State,
51+ /// How the working copy differs from the base.
52+ pub status: Status,
53+ /// The head of the workspace's branch, if the branch exists.
54+ pub head: Option<ObjectId>,
55+ /// The workspace's own changesets that the branch does not have yet,
56+ /// oldest first.
57+ pub unlanded: Vec<ObjectId>,
58+ /// For a rebase in progress: the conflicts, each with whether conflict
59+ /// markers remain in its file.
60+ pub conflicts: Vec<(RecordedConflict, bool)>,
61+}
62+
63+/// What `commit` asks for.
64+#[derive(Clone, Debug)]
65+pub struct CommitRequest {
66+ /// The message; while a rebase is in progress, the rebased changeset's
67+ /// message is used if there is none.
68+ pub message: Option<Vec<u8>>,
69+ /// Commit only what lies at or below these paths; everything if empty.
70+ pub paths: Vec<Vec<u8>>,
71+ /// The author, if given; otherwise the rebased changeset's author while
72+ /// a rebase is in progress, and the committer otherwise.
73+ pub author: Option<Identity>,
74+ /// Who records the changeset.
75+ pub committer: Identity,
76+ /// Commit even if conflict markers remain or conflicts are not marked
77+ /// resolved.
78+ pub force: bool,
79+}
80+
81+/// Where a rebase stands after a commit or an update.
82+#[derive(Clone, Debug, PartialEq, Eq)]
83+pub enum RebaseProgress {
84+ /// No rebase was in progress.
85+ None,
86+ /// The rebase is finished: the workspace is at `tip`.
87+ Finished {
88+ /// The last rebased changeset.
89+ tip: ObjectId,
90+ },
91+ /// The next changeset conflicts too: resolve and commit again.
92+ Stopped {
93+ /// The changeset that conflicts.
94+ change: ObjectId,
95+ /// Its conflicts.
96+ conflicts: Vec<Conflict>,
97+ },
98+}
99+
100+/// What `commit` did.
101+#[derive(Clone, Debug)]
102+pub struct CommitOutcome {
103+ /// The new changeset; `None` when a rebase finished with nothing left to
104+ /// record.
105+ pub changeset: Option<ObjectId>,
106+ /// How many paths it changed.
107+ pub changes: usize,
108+ /// Where the rebase in progress, if any, stands now.
109+ pub rebase: RebaseProgress,
110+}
111+
112+/// How a landing ended.
113+#[derive(Clone, Debug, PartialEq, Eq)]
114+pub enum Landed {
115+ /// Nothing to land: the branch has the workspace's base already.
116+ Nothing,
117+ /// The branch moved to the change itself.
118+ FastForward(ObjectId),
119+ /// The change was rebased onto the head; the branch moved to the result.
120+ Rebased(ObjectId),
121+ /// The branch already had everything the change does; it did not move.
122+ AlreadyApplied,
123+ /// The change conflicts with the head; the branch did not move.
124+ Conflicts {
125+ /// The changeset that conflicts.
126+ change: ObjectId,
127+ /// The conflicts.
128+ conflicts: Vec<Conflict>,
129+ },
130+}
131+
132+/// What a landing did.
133+#[derive(Clone, Debug, PartialEq, Eq)]
134+pub struct LandReport {
135+ /// The branch.
136+ pub branch: String,
137+ /// Its head before the landing.
138+ pub previous: Option<ObjectId>,
139+ /// How it ended.
140+ pub landed: Landed,
141+ /// The op log operation that moved the branch, if it moved.
142+ pub operation: Option<u64>,
143+}
144+
145+impl LandReport {
146+ /// The branch's head after the landing.
147+ pub fn head(&self) -> Option<ObjectId> {
148+ match &self.landed {
149+ Landed::FastForward(id) | Landed::Rebased(id) => Some(*id),
150+ _ => self.previous,
151+ }
152+ }
153+}
154+
155+/// What `update` did.
156+#[derive(Clone, Debug, PartialEq, Eq)]
157+pub enum Updated {
158+ /// The workspace was on the head already, or the branch does not exist.
159+ UpToDate,
160+ /// The workspace moved to the head.
161+ Moved {
162+ /// The head.
163+ head: ObjectId,
164+ },
165+ /// The workspace's own changesets were rebased onto the head.
166+ Rebased {
167+ /// The head.
168+ head: ObjectId,
169+ /// The last rebased changeset, now the workspace's base.
170+ tip: ObjectId,
171+ },
172+ /// A changeset conflicts with the head: the working copy holds the
173+ /// head's tree with the change's clean paths and conflict markers, and
174+ /// a rebase is in progress.
175+ Conflicts {
176+ /// The head.
177+ head: ObjectId,
178+ /// The changeset that conflicts.
179+ change: ObjectId,
180+ /// Its conflicts.
181+ conflicts: Vec<Conflict>,
182+ },
183+}
184+
185+/// Why a landing transaction stops without moving the branch.
186+enum Abort {
187+ Stop,
188+ Failed(Error),
189+}
190+
191+impl From<Error> for Abort {
192+ fn from(error: Error) -> Self {
193+ Abort::Failed(error)
194+ }
195+}
196+
197+/// What a landing decided inside its transaction.
198+enum Decision {
199+ Nothing,
200+ AlreadyApplied {
201+ head: ObjectId,
202+ },
203+ Moved {
204+ tip: ObjectId,
205+ rebased: bool,
206+ tip_root: ObjectId,
207+ plan: Plan,
208+ },
209+ Conflicts {
210+ change: ObjectId,
211+ conflicts: Vec<Conflict>,
212+ },
213+}
214+
215+impl<'r> Workspace<'r> {
216+ /// The directory that holds every workspace's state.
217+ pub fn states_dir(repo: &Repo) -> PathBuf {
218+ repo.root().join(DIR).join(WORKSPACES_DIR)
219+ }
220+
221+ /// Creates a workspace named `name` in `dir`, which must not exist or be
222+ /// empty, at the changeset `at` (`None` for the empty tree), tracking
223+ /// `branch`. Writes the whole tree. Returns the workspace and how many
224+ /// files it wrote. On failure, nothing is left behind.
225+ pub fn create(
226+ repo: &'r Repo,
227+ name: &str,
228+ dir: &Path,
229+ at: Option<ObjectId>,
230+ branch: &str,
231+ ) -> Result<(Workspace<'r>, usize), Error> {
232+ if !WorkspaceLink::is_valid_name(name) {
233+ return Err(Error::InvalidName(name.to_owned()));
234+ }
235+ let states = Self::states_dir(repo);
236+ fs::create_dir_all(&states).map_err(Error::io("create", &states))?;
237+ let state_dir = states.join(name);
238+ match fs::create_dir(&state_dir) {
239+ Ok(()) => {}
240+ Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
241+ return Err(Error::WorkspaceExists(name.to_owned()));
242+ }
243+ Err(err) => return Err(Error::io("create", &state_dir)(err)),
244+ }
245+ let mut prepared = None;
246+ let made = Self::populate(repo, name, dir, &state_dir, at, branch, &mut prepared);
247+ if made.is_err() {
248+ match prepared {
249+ Some(Prepared::Created) => {
250+ let _ = fs::remove_dir_all(dir);
251+ }
252+ // It was empty: everything in it now is this workspace's.
253+ Some(Prepared::WasEmpty) => clear(dir),
254+ None => {}
255+ }
256+ let _ = fs::remove_dir_all(&state_dir);
257+ }
258+ made
259+ }
260+
261+ fn populate(
262+ repo: &'r Repo,
263+ name: &str,
264+ dir: &Path,
265+ state_dir: &Path,
266+ at: Option<ObjectId>,
267+ branch: &str,
268+ prepared: &mut Option<Prepared>,
269+ ) -> Result<(Workspace<'r>, usize), Error> {
270+ let _lock = Lock::acquire(state_dir)?;
271+ match fs::read_dir(dir) {
272+ Ok(mut entries) => {
273+ if entries.next().is_some() {
274+ return Err(Error::DirectoryNotEmpty(dir.to_path_buf()));
275+ }
276+ *prepared = Some(Prepared::WasEmpty);
277+ }
278+ Err(err) if err.kind() == io::ErrorKind::NotFound => {
279+ fs::create_dir_all(dir).map_err(Error::io("create", dir))?;
280+ *prepared = Some(Prepared::Created);
281+ }
282+ Err(err) => return Err(Error::io("read", dir)(err)),
283+ }
284+ let dir = fs::canonicalize(dir).map_err(Error::io("open", dir))?;
285+ let repository = fs::canonicalize(repo.root()).map_err(Error::io("open", repo.root()))?;
286+ let link = WorkspaceLink {
287+ repository,
288+ name: name.to_owned(),
289+ };
290+ let link_path = dir.join(DIR);
291+ fs::File::create_new(&link_path)
292+ .and_then(|mut file| io::Write::write_all(&mut file, &link.encode()))
293+ .map_err(Error::io("write", &link_path))?;
294+
295+ let workspace = Workspace {
296+ repo,
297+ name: name.to_owned(),
298+ dir: dir.clone(),
299+ state_dir: state_dir.to_path_buf(),
300+ };
301+ let root = Root::open(&dir)?;
302+ let fs = FileSystem::probe(root.dir());
303+ let store = repo.store();
304+ let to = root_of(store, at)?;
305+ let plan = checkout::plan(store, &root, fs, EMPTY_TREE, to, Mode::Checked)?;
306+ let mut state = State {
307+ path: dir,
308+ branch: branch.to_owned(),
309+ base: at,
310+ upstream: at,
311+ fs,
312+ checkout: None,
313+ tracked: Vec::new(),
314+ rebase: None,
315+ };
316+ let written = workspace.write(&root, &mut state, &plan, EMPTY_TREE, to)?;
317+ Ok((workspace, written))
318+ }
319+
320+ /// Opens the workspace named `name`, at the directory its state
321+ /// records.
322+ pub fn open(repo: &'r Repo, name: &str) -> Result<Workspace<'r>, Error> {
323+ if !WorkspaceLink::is_valid_name(name) {
324+ return Err(Error::InvalidName(name.to_owned()));
325+ }
326+ let state_dir = Self::states_dir(repo).join(name);
327+ if !state_dir.join(crate::state::FILE).is_file() {
328+ return Err(Error::NoSuchWorkspace(name.to_owned()));
329+ }
330+ let state = State::load(&state_dir)?;
331+ Ok(Workspace {
332+ repo,
333+ name: name.to_owned(),
334+ dir: state.path,
335+ state_dir,
336+ })
337+ }
338+
339+ /// Opens the workspace named `name` at `dir`, where its `.braid` file
340+ /// was found. If the directory moved, the state follows it the next
341+ /// time the workspace changes.
342+ pub fn at(repo: &'r Repo, name: &str, dir: &Path) -> Result<Workspace<'r>, Error> {
343+ let mut workspace = Self::open(repo, name)?;
344+ workspace.dir = dir.to_path_buf();
345+ Ok(workspace)
346+ }
347+
348+ /// Every workspace of `repo`, by name, with its state.
349+ pub fn list(repo: &Repo) -> Result<Vec<(String, State)>, Error> {
350+ let states = Self::states_dir(repo);
351+ let entries = match fs::read_dir(&states) {
352+ Ok(entries) => entries,
353+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
354+ Err(err) => return Err(Error::io("read", &states)(err)),
355+ };
356+ let mut found = Vec::new();
357+ for entry in entries {
358+ let entry = entry.map_err(Error::io("read", &states))?;
359+ let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
360+ continue;
361+ };
362+ if !WorkspaceLink::is_valid_name(&name)
363+ || !entry.path().join(crate::state::FILE).is_file()
364+ {
365+ continue;
366+ }
367+ found.push((name, State::load(&entry.path())?));
368+ }
369+ found.sort_by(|a, b| a.0.cmp(&b.0));
370+ Ok(found)
371+ }
372+
373+ /// Removes the workspace named `name`: its directory and its state.
374+ /// Refused while it has uncommitted changes, files waiting for `braid
375+ /// track`, changesets the branch does not have, or a rebase in progress,
376+ /// unless `force`. The directory is removed only if its `.braid` file
377+ /// still names this workspace of this repository.
378+ pub fn remove(repo: &Repo, name: &str, force: bool) -> Result<(), Error> {
379+ let workspace = Workspace::open(repo, name)?;
380+ let lock = Lock::acquire(&workspace.state_dir)?;
381+ let state = State::load(&workspace.state_dir)?;
382+ let owned = workspace.owns_directory(&state.path);
383+ if !force {
384+ if state.rebase.is_some() {
385+ return Err(Error::RebaseInProgress);
386+ }
387+ if owned {
388+ let root = Root::open(&state.path)?;
389+ let status = workspace.scan_status(&root, &state)?;
390+ let dirty: Vec<&Vec<u8>> = status
391+ .changes
392+ .iter()
393+ .map(|change| &change.path)
394+ .chain(&status.needs_track)
395+ .collect();
396+ if let Some(first) = dirty.first() {
397+ return Err(Error::Uncommitted {
398+ count: dirty.len(),
399+ first: first.to_vec(),
400+ });
401+ }
402+ }
403+ let store = repo.store();
404+ let head = store.refs()?.get(&state.branch);
405+ let unlanded = find_stack(store, head, state.base, state.upstream)?;
406+ if !unlanded.is_empty() {
407+ return Err(Error::Unlanded {
408+ count: unlanded.len(),
409+ branch: state.branch.clone(),
410+ });
411+ }
412+ }
413+ if owned {
414+ fs::remove_dir_all(&state.path).map_err(Error::io("remove", &state.path))?;
415+ }
416+ drop(lock);
417+ fs::remove_dir_all(&workspace.state_dir).map_err(Error::io("remove", &workspace.state_dir))
418+ }
419+
420+ /// Whether `dir` holds a `.braid` file naming this workspace.
421+ fn owns_directory(&self, dir: &Path) -> bool {
422+ let Ok(link) = WorkspaceLink::read(&dir.join(DIR)) else {
423+ return false;
424+ };
425+ let same_repo = match (
426+ fs::canonicalize(&link.repository),
427+ fs::canonicalize(self.repo.root()),
428+ ) {
429+ (Ok(a), Ok(b)) => a == b,
430+ _ => false,
431+ };
432+ link.name == self.name && same_repo
433+ }
434+
435+ /// The workspace's name.
436+ pub fn name(&self) -> &str {
437+ &self.name
438+ }
439+
440+ /// The workspace directory.
441+ pub fn dir(&self) -> &Path {
442+ &self.dir
443+ }
444+
445+ /// The repository.
446+ pub fn repo(&self) -> &'r Repo {
447+ self.repo
448+ }
449+
450+ /// The workspace's state as last saved, read without the lock.
451+ pub fn state(&self) -> Result<State, Error> {
452+ State::load(&self.state_dir)
453+ }
454+
455+ /// Takes the lock, reads the state, opens the working copy, and
456+ /// finishes a checkout that an earlier command left unfinished.
457+ fn begin(&self) -> Result<(Lock, State, Root), Error> {
458+ let lock = Lock::acquire(&self.state_dir)?;
459+ let mut state = State::load(&self.state_dir)?;
460+ let root = Root::open(&self.dir)?;
461+ if state.path != self.dir {
462+ state.path = self.dir.clone();
463+ state.save(&self.state_dir)?;
464+ }
465+ if let Some(Checkout { from, to }) = state.checkout {
466+ let plan = checkout::plan(self.store(), &root, state.fs, from, to, Mode::Forced)?;
467+ checkout::apply(self.store(), &root, &plan)?;
468+ state.checkout = None;
469+ state.save(&self.state_dir)?;
470+ }
471+ Ok((lock, state, root))
472+ }
473+
474+ fn store(&self) -> &'r Store {
475+ self.repo.store()
476+ }
477+
478+ /// Writes a planned checkout from tree `from` to tree `to` and saves
479+ /// `state`. The state is saved first with the checkout marked as
480+ /// unfinished, so that a command interrupted half way through is
481+ /// finished by the next one.
482+ fn write(
483+ &self,
484+ root: &Root,
485+ state: &mut State,
486+ plan: &Plan,
487+ from: ObjectId,
488+ to: ObjectId,
489+ ) -> Result<usize, Error> {
490+ if plan.len() == 0 {
491+ state.save(&self.state_dir)?;
492+ return Ok(0);
493+ }
494+ state.checkout = Some(Checkout { from, to });
495+ state.save(&self.state_dir)?;
496+ let written = checkout::apply(self.store(), root, plan)?;
497+ state.checkout = None;
498+ state.save(&self.state_dir)?;
499+ Ok(written)
500+ }
501+
502+ /// Scans the working copy, saves the new stat cache, and compares it
503+ /// with the base.
504+ fn scan_status(&self, root: &Root, state: &State) -> Result<Status, Error> {
505+ let store = self.store();
506+ let base = flatten(store, root_of(store, state.base)?)?;
507+ let cache = Cache::load(&self.state_dir);
508+ let scan = scan::scan(root, &base, &cache)?;
509+ scan.cache.save(&self.state_dir)?;
510+ Ok(status::compare(&base, &scan, &state.tracked))
511+ }
512+
513+ /// Fails if the working copy has uncommitted changes.
514+ fn require_clean(&self, root: &Root, state: &State) -> Result<(), Error> {
515+ let status = self.scan_status(root, state)?;
516+ match status.changes.first() {
517+ Some(first) => Err(Error::Uncommitted {
518+ count: status.changes.len(),
519+ first: first.path.clone(),
520+ }),
521+ None => Ok(()),
522+ }
523+ }
524+
525+ /// How the working copy differs from the base, and where the workspace
526+ /// stands against its branch.
527+ pub fn status(&self) -> Result<StatusReport, Error> {
528+ let (_lock, state, root) = self.begin()?;
529+ let status = self.scan_status(&root, &state)?;
530+ let store = self.store();
531+ let head = store.refs()?.get(&state.branch);
532+ let unlanded = find_stack(store, head, state.base, state.upstream)?;
533+ let mut conflicts = Vec::new();
534+ if let Some(rebase) = &state.rebase {
535+ for conflict in &rebase.conflicts {
536+ let remain = conflict.markers && markers_remain(&root, &conflict.path)?;
537+ conflicts.push((conflict.clone(), remain));
538+ }
539+ }
540+ Ok(StatusReport {
541+ state,
542+ status,
543+ head,
544+ unlanded,
545+ conflicts,
546+ })
547+ }
548+
549+ /// Records the working copy as a changeset on the base, and makes it
550+ /// the new base. There is no staging area: every change counts, or
551+ /// every change at or below `paths`, except new files that the secrets
552+ /// guard holds back until `braid track` marks them.
553+ ///
554+ /// While a rebase is in progress the changeset is the resolution: it is
555+ /// refused while conflict markers remain in files with content
556+ /// conflicts or other conflicts are not marked resolved (unless
557+ /// `force`), it takes no paths, and once it is made, the changesets
558+ /// that were waiting are rebased onto it.
559+ pub fn commit(&self, request: &CommitRequest) -> Result<CommitOutcome, Error> {
560+ let (_lock, mut state, root) = self.begin()?;
561+ let store = self.store();
562+ let status = self.scan_status(&root, &state)?;
563+ let original = match &state.rebase {
564+ Some(rebase) => {
565+ if !request.paths.is_empty() {
566+ return Err(Error::PathsDuringRebase);
567+ }
568+ if !request.force {
569+ check_resolved(&root, rebase)?;
570+ }
571+ Some(read_changeset(store, rebase.change)?)
572+ }
573+ None => None,
574+ };
575+ let selected: Vec<&status::PathChange> = status
576+ .changes
577+ .iter()
578+ .filter(|change| {
579+ request.paths.is_empty() || request.paths.iter().any(|p| is_within(&change.path, p))
580+ })
581+ .collect();
582+
583+ if selected.is_empty() {
584+ let Some(rebase) = state.rebase.take() else {
585+ return Err(Error::NothingToCommit);
586+ };
587+ // The resolution is the tree the rebase went onto: nothing of
588+ // this changeset is left to record.
589+ let progress = self.continue_rebase(
590+ &root,
591+ &mut state,
592+ rebase.pending,
593+ rebase.onto,
594+ &request.committer.now(),
595+ )?;
596+ state.save(&self.state_dir)?;
597+ return Ok(CommitOutcome {
598+ changeset: None,
599+ changes: 0,
600+ rebase: progress,
601+ });
602+ }
603+
604+ let message = match (&request.message, &original) {
605+ (Some(message), _) => message.clone(),
606+ (None, Some(original)) => original.message.clone(),
607+ (None, None) => return Err(Error::NoMessage),
608+ };
609+ let mut changes = Vec::with_capacity(selected.len());
610+ for change in &selected {
611+ let op = match &change.op {
612+ ChangeOp::Delete | ChangeOp::Gitlink { .. } => change.op.clone(),
613+ _ => self.store_file(&root, &change.path)?,
614+ };
615+ changes.push(Change {
616+ path: change.path.clone(),
617+ op,
618+ });
619+ }
620+ let committer = request.committer.now();
621+ let author = match (&request.author, &original) {
622+ (Some(author), _) => author.now(),
623+ (None, Some(original)) => original.author.clone(),
624+ (None, None) => committer.clone(),
625+ };
626+ let extras = state
627+ .rebase
628+ .as_ref()
629+ .map(|rebase| rebased_extras(rebase.change))
630+ .unwrap_or_default();
631+ let parents: Vec<ObjectId> = state.base.into_iter().collect();
632+ let count = changes.len();
633+ let id = braid_engine::commit(
634+ store,
635+ parents,
636+ changes,
637+ author,
638+ committer.clone(),
639+ message,
640+ extras,
641+ )?;
642+ store.sync()?;
643+
644+ // Marks for files that are now in the base have done their job.
645+ let committed: HashSet<&[u8]> = selected
646+ .iter()
647+ .map(|change| change.path.as_slice())
648+ .collect();
649+ state
650+ .tracked
651+ .retain(|mark| !committed.contains(mark.as_slice()));
652+ state.base = Some(id);
653+ let progress = match state.rebase.take() {
654+ None => RebaseProgress::None,
655+ Some(rebase) => {
656+ self.continue_rebase(&root, &mut state, rebase.pending, id, &committer)?
657+ }
658+ };
659+ state.save(&self.state_dir)?;
660+ Ok(CommitOutcome {
661+ changeset: Some(id),
662+ changes: count,
663+ rebase: progress,
664+ })
665+ }
666+
667+ /// Reads a changed file again and stores it as a blob: the content
668+ /// committed is the content read now.
669+ fn store_file(&self, root: &Root, path: &[u8]) -> Result<ChangeOp, Error> {
670+ let (parent, name) = split_last(path);
671+ let gone = || Error::Io {
672+ action: "read",
673+ path: root.path().join(crate::paths::show(path).as_ref()),
674+ source: io::Error::new(
675+ io::ErrorKind::NotFound,
676+ "the file changed while it was committed; try again",
677+ ),
678+ };
679+ let Found::Here(dir) = root.open_dir(parent)? else {
680+ return Err(gone());
681+ };
682+ let os = os_name(name).ok_or_else(gone)?;
683+ let meta = dir.symlink_metadata(os).map_err(|_| gone())?;
684+ let stat = Stat::of(&meta);
685+ let store = self.store();
686+ match stat.kind {
687+ StatKind::Symlink => {
688+ let target = read_link(&dir, os).map_err(|err| root.error("read", path, err))?;
689+ let blob = store.put(Kind::Blob, &target)?;
690+ Ok(ChangeOp::Symlink {
691+ blob,
692+ size: target.len() as u64,
693+ })
694+ }
695+ StatKind::File => {
696+ let mut file = open_file(&dir, os).map_err(|err| root.error("read", path, err))?;
697+ let executable = Stat::of(
698+ &file
699+ .metadata()
700+ .map_err(|err| root.error("read", path, err))?,
701+ )
702+ .executable;
703+ let mut content = Vec::new();
704+ file.read_to_end(&mut content)
705+ .map_err(|err| root.error("read", path, err))?;
706+ let blob = store.put(Kind::Blob, &content)?;
707+ let size = content.len() as u64;
708+ Ok(if executable {
709+ ChangeOp::Executable { blob, size }
710+ } else {
711+ ChangeOp::File { blob, size }
712+ })
713+ }
714+ StatKind::Dir | StatKind::Other => Err(gone()),
715+ }
716+ }
717+
718+ /// Rebases the changesets that waited behind a resolved conflict onto
719+ /// `tip`, the resolution, and brings the working copy along.
720+ fn continue_rebase(
721+ &self,
722+ root: &Root,
723+ state: &mut State,
724+ pending: Vec<ObjectId>,
725+ tip: ObjectId,
726+ committer: &Signature,
727+ ) -> Result<RebaseProgress, Error> {
728+ state.base = Some(tip);
729+ if pending.is_empty() {
730+ return Ok(RebaseProgress::Finished { tip });
731+ }
732+ let store = self.store();
733+ let from = root_of(store, Some(tip))?;
734+ match replay(
735+ store,
736+ &state.branch,
737+ Some(tip),
738+ &pending,
739+ committer,
740+ First::Pick,
741+ )? {
742+ Replayed::Done { tip: last, .. } => {
743+ let to = root_of(store, Some(last))?;
744+ let plan = checkout::plan(store, root, state.fs, from, to, Mode::Checked)?;
745+ state.base = Some(last);
746+ self.write(root, state, &plan, from, to)?;
747+ Ok(RebaseProgress::Finished { tip: last })
748+ }
749+ Replayed::Stopped {
750+ index,
751+ onto,
752+ conflicts,
753+ } => {
754+ let change = pending[index];
755+ self.stop_on_conflicts(
756+ root,
757+ state,
758+ from,
759+ onto,
760+ change,
761+ &pending[index + 1..],
762+ &conflicts,
763+ )?;
764+ Ok(RebaseProgress::Stopped { change, conflicts })
765+ }
766+ }
767+ }
768+
769+ /// Writes the working copy for a rebase stopped by conflicts and
770+ /// records the rebase: `onto`'s tree, with `change`'s clean paths and
771+ /// conflict markers, as the base `onto`.
772+ #[allow(clippy::too_many_arguments)]
773+ fn stop_on_conflicts(
774+ &self,
775+ root: &Root,
776+ state: &mut State,
777+ from: ObjectId,
778+ onto: ObjectId,
779+ change: ObjectId,
780+ pending: &[ObjectId],
781+ conflicts: &[Conflict],
782+ ) -> Result<(), Error> {
783+ let store = self.store();
784+ let subject = subject(&read_changeset(store, change)?.message);
785+ let ours = format!("{} ({})", state.branch, onto.short());
786+ let theirs = format!("{} ({subject})", change.short());
787+ let (tree, recorded) = conflict_tree(store, onto, change, conflicts, (&ours, &theirs))?;
788+ let plan = checkout::plan(store, root, state.fs, from, tree, Mode::Checked)?;
789+ state.base = Some(onto);
790+ state.rebase = Some(Rebase {
791+ change,
792+ onto,
793+ pending: pending.to_vec(),
794+ conflicts: recorded,
795+ });
796+ self.write(root, state, &plan, from, tree)?;
797+ Ok(())
798+ }
799+
800+ /// Lands the workspace's own changesets on `onto` (by default the
801+ /// branch it tracks), in one op log transaction: the head is read, the
802+ /// changesets are landed on it with the engine (fast-forward or
803+ /// rebase), and the branch moves with a compare-and-swap. With
804+ /// conflicts the branch does not move and nothing in the workspace
805+ /// changes. Once the branch has moved, the working copy is brought from
806+ /// the base's tree to the landed tree, writing only the difference, and
807+ /// the landed changeset becomes the base. Refused with uncommitted
808+ /// changes or a rebase in progress.
809+ pub fn land(
810+ &self,
811+ onto: Option<&str>,
812+ agent: &str,
813+ committer: &Identity,
814+ ) -> Result<LandReport, Error> {
815+ let (_lock, mut state, root) = self.begin()?;
816+ if state.rebase.is_some() {
817+ return Err(Error::RebaseInProgress);
818+ }
819+ self.require_clean(&root, &state)?;
820+ let branch = onto.unwrap_or(&state.branch).to_owned();
821+ let store = self.store();
822+ let base_root = root_of(store, state.base)?;
823+ let signature = committer.now();
824+ let mut previous = None;
825+ let mut decision = None;
826+ let description = format!("land workspace {} on {branch}", self.name);
827+ let result = store.transact(
828+ agent,
829+ &description,
830+ |refs| -> Result<Vec<RefUpdate>, Abort> {
831+ let head = refs.get(&branch);
832+ previous = head;
833+ let stack = find_stack(store, head, state.base, state.upstream)?;
834+ if stack.is_empty() {
835+ decision = Some(Decision::Nothing);
836+ return Err(Abort::Stop);
837+ }
838+ match replay(
839+ store,
840+ &branch,
841+ head,
842+ &stack,
843+ &signature,
844+ First::MustBeOnBranch,
845+ )? {
846+ Replayed::Done { tip, .. } if Some(tip) == head => {
847+ decision = Some(Decision::AlreadyApplied { head: tip });
848+ Err(Abort::Stop)
849+ }
850+ Replayed::Done { tip, rebased } => {
851+ // Check the working copy can follow before the branch
852+ // moves.
853+ let tip_root = root_of(store, Some(tip))?;
854+ let plan = checkout::plan(
855+ store,
856+ &root,
857+ state.fs,
858+ base_root,
859+ tip_root,
860+ Mode::Checked,
861+ )?;
862+ decision = Some(Decision::Moved {
863+ tip,
864+ rebased,
865+ tip_root,
866+ plan,
867+ });
868+ Ok(vec![RefUpdate::new(branch.clone(), head, Some(tip))])
869+ }
870+ Replayed::Stopped {
871+ index, conflicts, ..
872+ } => {
873+ decision = Some(Decision::Conflicts {
874+ change: stack[index],
875+ conflicts,
876+ });
877+ Err(Abort::Stop)
878+ }
879+ }
880+ },
881+ );
882+ let operation = match result {
883+ Ok(op) => Some(op.seq),
884+ Err(TransactError::Aborted(Abort::Stop)) => None,
885+ Err(TransactError::Aborted(Abort::Failed(err))) => return Err(err),
886+ Err(TransactError::Store(err)) => return Err(err.into()),
887+ };
888+ let landed = match decision {
889+ Some(Decision::Moved {
890+ tip,
891+ rebased,
892+ tip_root,
893+ plan,
894+ }) => {
895+ state.base = Some(tip);
896+ state.upstream = Some(tip);
897+ self.write(&root, &mut state, &plan, base_root, tip_root)?;
898+ if rebased {
899+ Landed::Rebased(tip)
900+ } else {
901+ Landed::FastForward(tip)
902+ }
903+ }
904+ Some(Decision::AlreadyApplied { head }) => {
905+ // The branch has it all: the workspace moves to the head.
906+ self.move_to(&root, &mut state, base_root, head)?;
907+ Landed::AlreadyApplied
908+ }
909+ Some(Decision::Conflicts { change, conflicts }) => {
910+ Landed::Conflicts { change, conflicts }
911+ }
912+ Some(Decision::Nothing) | None => Landed::Nothing,
913+ };
914+ Ok(LandReport {
915+ branch,
916+ previous,
917+ landed,
918+ operation,
919+ })
920+ }
921+
922+ /// Brings the working copy from tree `from` to `head`'s tree and makes
923+ /// `head` the base and the upstream.
924+ fn move_to(
925+ &self,
926+ root: &Root,
927+ state: &mut State,
928+ from: ObjectId,
929+ head: ObjectId,
930+ ) -> Result<(), Error> {
931+ let store = self.store();
932+ let to = root_of(store, Some(head))?;
933+ let plan = checkout::plan(store, root, state.fs, from, to, Mode::Checked)?;
934+ state.base = Some(head);
935+ state.upstream = Some(head);
936+ self.write(root, state, &plan, from, to)?;
937+ Ok(())
938+ }
939+
940+ /// Brings the workspace onto the current head of its branch. Without
941+ /// changesets of its own, it moves to the head. With some, they are
942+ /// rebased onto the head with the engine, without moving the branch;
943+ /// cleanly, the workspace moves onto the rebased changesets. With
944+ /// conflicts, the working copy becomes the head's tree with the
945+ /// change's clean paths and, for content conflicts, files with conflict
946+ /// markers; other conflicts keep the head's version and are reported. A
947+ /// rebase is then in progress until `braid commit`. Refused with
948+ /// uncommitted changes or a rebase in progress.
949+ pub fn update(&self, committer: &Identity) -> Result<Updated, Error> {
950+ let (_lock, mut state, root) = self.begin()?;
951+ if state.rebase.is_some() {
952+ return Err(Error::RebaseInProgress);
953+ }
954+ self.require_clean(&root, &state)?;
955+ let store = self.store();
956+ let Some(head) = store.refs()?.get(&state.branch) else {
957+ return Ok(Updated::UpToDate);
958+ };
959+ let base_root = root_of(store, state.base)?;
960+ let stack = find_stack(store, Some(head), state.base, state.upstream)?;
961+ if stack.is_empty() {
962+ if state.base == Some(head) {
963+ if state.upstream != Some(head) {
964+ state.upstream = Some(head);
965+ state.save(&self.state_dir)?;
966+ }
967+ return Ok(Updated::UpToDate);
968+ }
969+ self.move_to(&root, &mut state, base_root, head)?;
970+ return Ok(Updated::Moved { head });
971+ }
972+ let signature = committer.now();
973+ match replay(
974+ store,
975+ &state.branch,
976+ Some(head),
977+ &stack,
978+ &signature,
979+ First::Anywhere,
980+ )? {
981+ Replayed::Done { tip, .. } if tip == head => {
982+ self.move_to(&root, &mut state, base_root, head)?;
983+ Ok(Updated::Moved { head })
984+ }
985+ Replayed::Done { tip, .. } => {
986+ let to = root_of(store, Some(tip))?;
987+ let plan = checkout::plan(store, &root, state.fs, base_root, to, Mode::Checked)?;
988+ state.base = Some(tip);
989+ state.upstream = Some(head);
990+ self.write(&root, &mut state, &plan, base_root, to)?;
991+ Ok(Updated::Rebased { head, tip })
992+ }
993+ Replayed::Stopped {
994+ index,
995+ onto,
996+ conflicts,
997+ } => {
998+ let change = stack[index];
999+ state.upstream = Some(head);
1000+ self.stop_on_conflicts(
1001+ &root,
1002+ &mut state,
1003+ base_root,
1004+ onto,
1005+ change,
1006+ &stack[index + 1..],
1007+ &conflicts,
1008+ )?;
1009+ Ok(Updated::Conflicts {
1010+ head,
1011+ change,
1012+ conflicts,
1013+ })
1014+ }
1015+ }
1016+ }
1017+
1018+ /// Marks conflicts of the rebase in progress resolved: those at each of
1019+ /// `paths`, which must not be content conflicts with markers (those are
1020+ /// resolved by editing the markers out). Returns the conflicts still
1021+ /// unresolved.
1022+ pub fn resolve(&self, paths: &[Vec<u8>]) -> Result<Vec<RecordedConflict>, Error> {
1023+ let (_lock, mut state, _root) = self.begin()?;
1024+ let rebase = state.rebase.as_mut().ok_or(Error::NoRebase)?;
1025+ for path in paths {
1026+ let mut found = false;
1027+ for conflict in rebase.conflicts.iter_mut().filter(|c| &c.path == path) {
1028+ if conflict.markers {
1029+ return Err(Error::NotResolvable {
1030+ path: path.clone(),
1031+ reason: "a content conflict: edit the conflict markers out instead",
1032+ });
1033+ }
1034+ conflict.resolved = true;
1035+ found = true;
1036+ }
1037+ if !found {
1038+ return Err(Error::NotResolvable {
1039+ path: path.clone(),
1040+ reason: "no conflict at this path",
1041+ });
1042+ }
1043+ }
1044+ let remaining = rebase
1045+ .conflicts
1046+ .iter()
1047+ .filter(|c| !c.markers && !c.resolved)
1048+ .cloned()
1049+ .collect();
1050+ state.save(&self.state_dir)?;
1051+ Ok(remaining)
1052+ }
1053+
1054+ /// Marks paths so that the secrets guard lets the new files at or below
1055+ /// them be committed. Returns every mark.
1056+ pub fn track(&self, paths: &[Vec<u8>]) -> Result<Vec<Vec<u8>>, Error> {
1057+ let (_lock, mut state, _root) = self.begin()?;
1058+ for path in paths {
1059+ if !state.tracked.contains(path) {
1060+ state.tracked.push(path.clone());
1061+ }
1062+ }
1063+ state.tracked.sort();
1064+ state.save(&self.state_dir)?;
1065+ Ok(state.tracked)
1066+ }
1067+}
1068+
1069+/// What `create` did to the workspace's directory before filling it.
1070+#[derive(Clone, Copy, Debug)]
1071+enum Prepared {
1072+ Created,
1073+ WasEmpty,
1074+}
1075+
1076+/// Removes everything inside `dir`, best effort, leaving it empty.
1077+fn clear(dir: &Path) {
1078+ let Ok(entries) = fs::read_dir(dir) else {
1079+ return;
1080+ };
1081+ for entry in entries.flatten() {
1082+ let path = entry.path();
1083+ let _ = match entry.file_type() {
1084+ Ok(kind) if kind.is_dir() => fs::remove_dir_all(&path),
1085+ _ => fs::remove_file(&path),
1086+ };
1087+ }
1088+}
1089+
1090+/// Fails unless every conflict of the rebase is settled: no markers left in
1091+/// the files that had them, and every other conflict marked resolved.
1092+fn check_resolved(root: &Root, rebase: &Rebase) -> Result<(), Error> {
1093+ let mut with_markers = Vec::new();
1094+ let mut unresolved = Vec::new();
1095+ for conflict in &rebase.conflicts {
1096+ if conflict.markers {
1097+ if markers_remain(root, &conflict.path)? {
1098+ with_markers.push(conflict.path.clone());
1099+ }
1100+ } else if !conflict.resolved {
1101+ unresolved.push(conflict.path.clone());
1102+ }
1103+ }
1104+ if !with_markers.is_empty() {
1105+ return Err(Error::MarkersRemain(with_markers));
1106+ }
1107+ if !unresolved.is_empty() {
1108+ return Err(Error::Unresolved(unresolved));
1109+ }
1110+ Ok(())
1111+}
1112+
1113+/// Whether the regular file at `path` still holds conflict markers. A file
1114+/// that is gone, or is not a regular file any more, holds none.
1115+fn markers_remain(root: &Root, path: &[u8]) -> Result<bool, Error> {
1116+ let (parent, name) = split_last(path);
1117+ let Found::Here(dir) = root.open_dir(parent)? else {
1118+ return Ok(false);
1119+ };
1120+ let Some(os) = os_name(name) else {
1121+ return Ok(false);
1122+ };
1123+ let mut file = match open_file(&dir, os) {
1124+ Ok(file) => file,
1125+ Err(_) => return Ok(false),
1126+ };
1127+ let mut content = Vec::new();
1128+ file.read_to_end(&mut content)
1129+ .map_err(|err| root.error("read", path, err))?;
1130+ Ok(has_markers(&content))
1131+}
1132+
1133+/// The first non-empty line of a message.
1134+fn subject(message: &[u8]) -> String {
1135+ String::from_utf8_lossy(message)
1136+ .lines()
1137+ .find(|line| !line.trim().is_empty())
1138+ .unwrap_or("")
1139+ .trim()
1140+ .to_owned()
1141+}
1142+
1143+/// The workspace's own changesets that `head` does not have, oldest first:
1144+/// `base` and its first parents, back to the first one on `head`'s
1145+/// first-parent chain. `hint` is where the last walk ended; when it is on
1146+/// the chain, the walk stops there without reading the head's history.
1147+pub(crate) fn find_stack<O: Objects>(
1148+ objects: &O,
1149+ head: Option<ObjectId>,
1150+ base: Option<ObjectId>,
1151+ hint: Option<ObjectId>,
1152+) -> Result<Vec<ObjectId>, Error> {
1153+ let Some(base) = base else {
1154+ return Ok(Vec::new());
1155+ };
1156+ let parent = |id: ObjectId| -> Result<Option<ObjectId>, Error> {
1157+ Ok(read_changeset(objects, id)?.parents.first().copied())
1158+ };
1159+ let Some(head) = head else {
1160+ // A branch that does not exist has none of them.
1161+ let mut stack = Vec::new();
1162+ let mut current = Some(base);
1163+ while let Some(id) = current {
1164+ stack.push(id);
1165+ current = parent(id)?;
1166+ }
1167+ stack.reverse();
1168+ return Ok(stack);
1169+ };
1170+ if base == head {
1171+ return Ok(Vec::new());
1172+ }
1173+ if let Some(hint) = hint
1174+ && first_parent_chain_contains(objects, head, hint, usize::MAX)?
1175+ {
1176+ let mut stack = Vec::new();
1177+ let mut current = Some(base);
1178+ while let Some(id) = current {
1179+ if id == hint {
1180+ stack.reverse();
1181+ return Ok(stack);
1182+ }
1183+ stack.push(id);
1184+ current = parent(id)?;
1185+ }
1186+ }
1187+ let mut on_branch = HashSet::new();
1188+ let mut current = Some(head);
1189+ while let Some(id) = current {
1190+ on_branch.insert(id);
1191+ current = parent(id)?;
1192+ }
1193+ let mut stack = Vec::new();
1194+ let mut current = Some(base);
1195+ while let Some(id) = current {
1196+ if on_branch.contains(&id) {
1197+ break;
1198+ }
1199+ stack.push(id);
1200+ current = parent(id)?;
1201+ }
1202+ stack.reverse();
1203+ Ok(stack)
1204+}
added crates/wc/tests/common/mod.rs +135 −0
@@ -0,0 +1,135 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Helpers for the workspace tests: a repository in a temporary directory,
5+//! changesets made straight through the engine, and branches moved by hand.
6+
7+#![allow(dead_code)]
8+
9+use std::convert::Infallible;
10+use std::path::{Path, PathBuf};
11+
12+use braid_format::{Change, ChangeOp, Kind, ObjectId, Objects, Signature};
13+use braid_repo::Repo;
14+use braid_store::RefUpdate;
15+use braid_wc::Identity;
16+
17+pub struct Fixture {
18+ pub temp: tempfile::TempDir,
19+ pub repo: Repo,
20+}
21+
22+impl Fixture {
23+ pub fn new() -> Fixture {
24+ let temp = tempfile::tempdir().unwrap();
25+ let repo = Repo::init(&temp.path().join("repo")).unwrap();
26+ Fixture { temp, repo }
27+ }
28+
29+ /// A path in the fixture's temporary directory.
30+ pub fn path(&self, name: &str) -> PathBuf {
31+ self.temp.path().join(name)
32+ }
33+
34+ pub fn file(&self, content: &str) -> ChangeOp {
35+ ChangeOp::File {
36+ blob: self
37+ .repo
38+ .store()
39+ .put(Kind::Blob, content.as_bytes())
40+ .unwrap(),
41+ size: content.len() as u64,
42+ }
43+ }
44+
45+ pub fn exec(&self, content: &str) -> ChangeOp {
46+ ChangeOp::Executable {
47+ blob: self
48+ .repo
49+ .store()
50+ .put(Kind::Blob, content.as_bytes())
51+ .unwrap(),
52+ size: content.len() as u64,
53+ }
54+ }
55+
56+ pub fn symlink(&self, target: &[u8]) -> ChangeOp {
57+ ChangeOp::Symlink {
58+ blob: self.repo.store().put(Kind::Blob, target).unwrap(),
59+ size: target.len() as u64,
60+ }
61+ }
62+
63+ /// A changeset on `parents` with these changes.
64+ pub fn commit(&self, parents: &[ObjectId], changes: Vec<(&str, ChangeOp)>) -> ObjectId {
65+ let changes = changes
66+ .into_iter()
67+ .map(|(path, op)| Change {
68+ path: path.as_bytes().to_vec(),
69+ op,
70+ })
71+ .collect();
72+ let id = braid_engine::commit(
73+ self.repo.store(),
74+ parents.to_vec(),
75+ changes,
76+ signature(),
77+ signature(),
78+ b"test change\n".to_vec(),
79+ Vec::new(),
80+ )
81+ .unwrap();
82+ self.repo.store().sync().unwrap();
83+ id
84+ }
85+
86+ /// Points `branch` at `id`.
87+ pub fn set_branch(&self, branch: &str, id: ObjectId) {
88+ self.repo
89+ .store()
90+ .transact("test", "move a branch", |refs| {
91+ Ok::<_, Infallible>(vec![RefUpdate::new(branch, refs.get(branch), Some(id))])
92+ })
93+ .unwrap();
94+ }
95+
96+ pub fn head(&self, branch: &str) -> Option<ObjectId> {
97+ self.repo.store().refs().unwrap().get(branch)
98+ }
99+}
100+
101+pub fn signature() -> Signature {
102+ Signature {
103+ name: b"Ada".to_vec(),
104+ email: b"ada@example.org".to_vec(),
105+ seconds: 1_700_000_000,
106+ offset_minutes: 0,
107+ }
108+}
109+
110+pub fn ada() -> Identity {
111+ Identity::new("Ada", "ada@example.org").unwrap()
112+}
113+
114+/// Every entry under `dir`, recursively, without following symlinks.
115+pub fn listing(dir: &Path) -> Vec<String> {
116+ let mut found = Vec::new();
117+ let mut pending = vec![dir.to_path_buf()];
118+ while let Some(current) = pending.pop() {
119+ for entry in std::fs::read_dir(&current).unwrap() {
120+ let entry = entry.unwrap();
121+ let path = entry.path();
122+ found.push(
123+ path.strip_prefix(dir)
124+ .unwrap()
125+ .to_string_lossy()
126+ .into_owned(),
127+ );
128+ if entry.file_type().unwrap().is_dir() {
129+ pending.push(path);
130+ }
131+ }
132+ }
133+ found.sort();
134+ found
135+}
added crates/wc/tests/hostile.rs +234 −0
@@ -0,0 +1,234 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Checkouts of hostile trees: nothing may be written outside the
5+//! workspace, and names that collide are refused rather than both written.
6+
7+mod common;
8+
9+use std::fs;
10+
11+use braid_wc::{Error, FileSystem, Updated, Workspace};
12+use common::{Fixture, ada, listing};
13+
14+/// The bytes of an absolute path, as a symlink target.
15+fn target(path: &std::path::Path) -> Vec<u8> {
16+ path.as_os_str().as_encoded_bytes().to_vec()
17+}
18+
19+#[test]
20+fn a_symlink_replaced_by_a_directory_is_never_gone_through() {
21+ let f = Fixture::new();
22+ let outside = tempfile::tempdir().unwrap();
23+ let first = f.commit(
24+ &[],
25+ vec![
26+ ("dir", f.symlink(&target(outside.path()))),
27+ ("keep", f.file("k")),
28+ ],
29+ );
30+ f.set_branch("main", first);
31+ let ws_dir = f.path("ws");
32+ let (ws, _) = Workspace::create(&f.repo, "ws", &ws_dir, Some(first), "main").unwrap();
33+ // The symlink is there, as a symlink.
34+ assert_eq!(fs::read_link(ws_dir.join("dir")).unwrap(), outside.path());
35+
36+ // A later tree makes `dir` a directory with a file in it.
37+ let second = f.commit(
38+ &[first],
39+ vec![
40+ ("dir", braid_format::ChangeOp::Delete),
41+ ("dir/x", f.file("pwned")),
42+ ],
43+ );
44+ f.set_branch("main", second);
45+ assert_eq!(ws.update(&ada()).unwrap(), Updated::Moved { head: second });
46+ assert!(
47+ listing(outside.path()).is_empty(),
48+ "wrote outside the workspace"
49+ );
50+ assert!(fs::symlink_metadata(ws_dir.join("dir")).unwrap().is_dir());
51+ assert_eq!(fs::read(ws_dir.join("dir/x")).unwrap(), b"pwned");
52+ assert!(ws.status().unwrap().status.is_clean());
53+}
54+
55+#[test]
56+fn a_symlink_and_a_case_twin_directory_in_one_tree() {
57+ let f = Fixture::new();
58+ let outside = tempfile::tempdir().unwrap();
59+ let hostile = f.commit(
60+ &[],
61+ vec![
62+ ("dir", f.symlink(&target(outside.path()))),
63+ ("DIR/x", f.file("pwned")),
64+ ],
65+ );
66+ let ws_dir = f.path("ws");
67+ fs::create_dir(&ws_dir).unwrap();
68+ let probe = FileSystem::probe(
69+ &cap_std::fs::Dir::open_ambient_dir(&ws_dir, cap_std::ambient_authority()).unwrap(),
70+ );
71+ fs::remove_dir(&ws_dir).unwrap();
72+
73+ let created = Workspace::create(&f.repo, "ws", &ws_dir, Some(hostile), "main");
74+ if probe.ignores_case {
75+ // One file on this file system: refused, and nothing written.
76+ assert!(
77+ matches!(created, Err(Error::Collision { .. })),
78+ "{created:?}"
79+ );
80+ assert!(!ws_dir.exists());
81+ assert!(Workspace::list(&f.repo).unwrap().is_empty());
82+ } else {
83+ // Two names here: both written, the directory a real one.
84+ created.unwrap();
85+ assert!(fs::symlink_metadata(ws_dir.join("DIR")).unwrap().is_dir());
86+ assert_eq!(fs::read(ws_dir.join("DIR/x")).unwrap(), b"pwned");
87+ }
88+ assert!(
89+ listing(outside.path()).is_empty(),
90+ "wrote outside the workspace"
91+ );
92+}
93+
94+#[test]
95+fn case_twins_are_refused_where_they_would_collide() {
96+ let f = Fixture::new();
97+ let twins = f.commit(
98+ &[],
99+ vec![("README", f.file("upper")), ("readme", f.file("lower"))],
100+ );
101+ let ws_dir = f.path("ws");
102+ fs::create_dir(&ws_dir).unwrap();
103+ let probe = FileSystem::probe(
104+ &cap_std::fs::Dir::open_ambient_dir(&ws_dir, cap_std::ambient_authority()).unwrap(),
105+ );
106+ let created = Workspace::create(&f.repo, "ws", &ws_dir, Some(twins), "main");
107+ if probe.ignores_case {
108+ let Err(Error::Collision { first, second }) = created else {
109+ panic!("expected a collision, got {created:?}");
110+ };
111+ assert_eq!(
112+ (first.as_slice(), second.as_slice()),
113+ (&b"README"[..], &b"readme"[..])
114+ );
115+ // The directory was there before and stays, empty.
116+ assert!(listing(&ws_dir).is_empty());
117+ } else {
118+ created.unwrap();
119+ assert_eq!(fs::read(ws_dir.join("README")).unwrap(), b"upper");
120+ assert_eq!(fs::read(ws_dir.join("readme")).unwrap(), b"lower");
121+ }
122+}
123+
124+#[test]
125+fn an_untracked_symlink_in_the_way_is_refused() {
126+ let f = Fixture::new();
127+ let outside = tempfile::tempdir().unwrap();
128+ // `dir` is ignored, so a symlink there does not count as a change.
129+ let first = f.commit(&[], vec![(".gitignore", f.file("dir\n"))]);
130+ f.set_branch("main", first);
131+ let ws_dir = f.path("ws");
132+ let (ws, _) = Workspace::create(&f.repo, "ws", &ws_dir, Some(first), "main").unwrap();
133+ #[cfg(unix)]
134+ std::os::unix::fs::symlink(outside.path(), ws_dir.join("dir")).unwrap();
135+ assert!(ws.status().unwrap().status.is_clean());
136+
137+ let second = f.commit(&[first], vec![("dir/x", f.file("pwned"))]);
138+ f.set_branch("main", second);
139+ let updated = ws.update(&ada());
140+ assert!(
141+ matches!(&updated, Err(Error::Unsafe { path, .. }) if path == b"dir"),
142+ "{updated:?}"
143+ );
144+ assert!(
145+ listing(outside.path()).is_empty(),
146+ "wrote outside the workspace"
147+ );
148+ // Nothing moved: the workspace is still at the first changeset.
149+ assert_eq!(ws.state().unwrap().base, Some(first));
150+}
151+
152+#[test]
153+fn a_symlink_replaced_by_a_file_is_replaced_not_written_through() {
154+ let f = Fixture::new();
155+ let outside = tempfile::tempdir().unwrap();
156+ let secret = outside.path().join("secret");
157+ fs::write(&secret, "keep me").unwrap();
158+ let first = f.commit(&[], vec![("link", f.symlink(&target(&secret)))]);
159+ f.set_branch("main", first);
160+ let ws_dir = f.path("ws");
161+ let (ws, _) = Workspace::create(&f.repo, "ws", &ws_dir, Some(first), "main").unwrap();
162+ let second = f.commit(&[first], vec![("link", f.file("replaced"))]);
163+ f.set_branch("main", second);
164+ ws.update(&ada()).unwrap();
165+ assert_eq!(fs::read(&secret).unwrap(), b"keep me");
166+ assert!(fs::symlink_metadata(ws_dir.join("link")).unwrap().is_file());
167+ assert_eq!(fs::read(ws_dir.join("link")).unwrap(), b"replaced");
168+}
169+
170+#[cfg(unix)]
171+#[test]
172+fn modes_targets_and_gitlinks_are_written_as_data() {
173+ use std::os::unix::fs::PermissionsExt;
174+ let f = Fixture::new();
175+ let gitlink = braid_format::ChangeOp::Gitlink {
176+ commit: braid_format::GitId::Sha1([7; 20]),
177+ };
178+ let first = f.commit(
179+ &[],
180+ vec![
181+ ("plain", f.file("p")),
182+ ("run.sh", f.exec("#!/bin/sh\n")),
183+ ("weird", f.symlink(b"../../../../etc/passwd")),
184+ ("vendor/lib", gitlink),
185+ ],
186+ );
187+ let ws_dir = f.path("ws");
188+ let (ws, written) = Workspace::create(&f.repo, "ws", &ws_dir, Some(first), "main").unwrap();
189+ assert_eq!(written, 4);
190+ let mode = |name: &str| {
191+ fs::metadata(ws_dir.join(name))
192+ .unwrap()
193+ .permissions()
194+ .mode()
195+ & 0o7777
196+ };
197+ assert_eq!(mode("plain"), 0o644);
198+ assert_eq!(mode("run.sh"), 0o755);
199+ assert_eq!(
200+ fs::read_link(ws_dir.join("weird"))
201+ .unwrap()
202+ .as_os_str()
203+ .as_encoded_bytes(),
204+ b"../../../../etc/passwd"
205+ );
206+ assert!(
207+ fs::symlink_metadata(ws_dir.join("vendor/lib"))
208+ .unwrap()
209+ .is_dir()
210+ );
211+ assert!(listing(&ws_dir.join("vendor/lib")).is_empty());
212+ assert!(ws.status().unwrap().status.is_clean());
213+}
214+
215+#[cfg(target_vendor = "apple")]
216+#[test]
217+fn names_this_platform_cannot_hold_are_refused() {
218+ let f = Fixture::new();
219+ let bad = braid_engine::commit(
220+ f.repo.store(),
221+ Vec::new(),
222+ vec![braid_format::Change {
223+ path: b"bad-\xff".to_vec(),
224+ op: f.file("x"),
225+ }],
226+ common::signature(),
227+ common::signature(),
228+ b"m\n".to_vec(),
229+ Vec::new(),
230+ )
231+ .unwrap();
232+ let created = Workspace::create(&f.repo, "ws", &f.path("ws"), Some(bad), "main");
233+ assert!(matches!(created, Err(Error::Unsafe { .. })), "{created:?}");
234+}
added crates/wc/tests/workspaces.rs +294 −0
@@ -0,0 +1,294 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Copyright (c) 2026 UtopiaIA
3+
4+//! Workspaces through the library: refusals before anything is written,
5+//! recovery of an interrupted checkout, rebases of stacks, and the errors
6+//! agents get when they ask for the wrong thing.
7+
8+mod common;
9+
10+use std::fs;
11+
12+use braid_format::ChangeOp;
13+use braid_wc::{ChangeKind, CommitRequest, Error, Landed, RebaseProgress, Updated, Workspace};
14+use common::{Fixture, ada};
15+
16+fn commit_all(ws: &Workspace<'_>, message: &str) -> braid_wc::CommitOutcome {
17+ ws.commit(&CommitRequest {
18+ message: Some(message.as_bytes().to_vec()),
19+ paths: Vec::new(),
20+ author: None,
21+ committer: ada(),
22+ force: false,
23+ })
24+ .unwrap()
25+}
26+
27+#[test]
28+fn a_file_replacing_a_directory_with_untracked_files_is_refused() {
29+ let f = Fixture::new();
30+ let first = f.commit(
31+ &[],
32+ vec![(".gitignore", f.file("d/junk\n")), ("d/a", f.file("a"))],
33+ );
34+ f.set_branch("main", first);
35+ let dir = f.path("ws");
36+ let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap();
37+ fs::write(dir.join("d/junk"), "mine").unwrap();
38+ assert!(ws.status().unwrap().status.is_clean());
39+
40+ let second = f.commit(
41+ &[first],
42+ vec![("d/a", ChangeOp::Delete), ("d", f.file("now a file"))],
43+ );
44+ f.set_branch("main", second);
45+ let updated = ws.update(&ada());
46+ assert!(
47+ matches!(&updated, Err(Error::Unsafe { path, .. }) if path == b"d/junk"),
48+ "{updated:?}"
49+ );
50+ // Refused before anything was written.
51+ assert_eq!(fs::read(dir.join("d/a")).unwrap(), b"a");
52+ assert_eq!(fs::read(dir.join("d/junk")).unwrap(), b"mine");
53+ assert_eq!(ws.state().unwrap().base, Some(first));
54+
55+ // Once the file is out of the way, the update goes through.
56+ fs::remove_file(dir.join("d/junk")).unwrap();
57+ assert_eq!(ws.update(&ada()).unwrap(), Updated::Moved { head: second });
58+ assert_eq!(fs::read(dir.join("d")).unwrap(), b"now a file");
59+}
60+
61+#[test]
62+fn an_interrupted_checkout_is_finished_by_the_next_command() {
63+ let f = Fixture::new();
64+ let first = f.commit(&[], vec![("a", f.file("1")), ("gone", f.file("x"))]);
65+ let second = f.commit(
66+ &[first],
67+ vec![
68+ ("a", f.file("2")),
69+ ("gone", ChangeOp::Delete),
70+ ("new/b", f.file("b")),
71+ ],
72+ );
73+ f.set_branch("main", second);
74+ let dir = f.path("ws");
75+ let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap();
76+
77+ // As if a command had moved the base, written part of the checkout
78+ // and died: `a` is written, the rest is not.
79+ let state_file = f
80+ .repo
81+ .root()
82+ .join(".braid")
83+ .join("ws")
84+ .join("ws")
85+ .join("state");
86+ let text = fs::read_to_string(&state_file).unwrap();
87+ let root = |id| {
88+ braid_engine::read_changeset(f.repo.store(), id)
89+ .unwrap()
90+ .root
91+ };
92+ let text = text.replace(
93+ &format!("base {first}"),
94+ &format!("base {second}\ncheckout {} {}", root(first), root(second)),
95+ );
96+ fs::write(&state_file, text).unwrap();
97+ fs::write(dir.join("a"), "2").unwrap();
98+
99+ let report = ws.status().unwrap();
100+ assert!(report.status.is_clean(), "{:?}", report.status);
101+ assert_eq!(report.state.checkout, None);
102+ assert_eq!(report.state.base, Some(second));
103+ assert!(!dir.join("gone").exists());
104+ assert_eq!(fs::read(dir.join("new/b")).unwrap(), b"b");
105+}
106+
107+#[test]
108+fn a_stack_that_conflicts_half_way_continues_after_the_commit() {
109+ let f = Fixture::new();
110+ let seed = f.commit(&[], vec![("x", f.file("1\n2\n3\n")), ("y", f.file("y\n"))]);
111+ f.set_branch("main", seed);
112+ let dir = f.path("ws");
113+ let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(seed), "main").unwrap();
114+ // Two changesets of our own: the first is clean against main, the
115+ // second conflicts with it.
116+ fs::write(dir.join("y"), "y, ours\n").unwrap();
117+ let first = commit_all(&ws, "first").changeset.unwrap();
118+ fs::write(dir.join("x"), "1\nours\n3\n").unwrap();
119+ let second = commit_all(&ws, "second").changeset.unwrap();
120+ fs::write(dir.join("z"), "z\n").unwrap();
121+ let third = commit_all(&ws, "third").changeset.unwrap();
122+ // Main moves meanwhile.
123+ let theirs = f.commit(&[seed], vec![("x", f.file("1\ntheirs\n3\n"))]);
124+ f.set_branch("main", theirs);
125+
126+ let Updated::Conflicts {
127+ change, conflicts, ..
128+ } = ws.update(&ada()).unwrap()
129+ else {
130+ panic!("expected conflicts");
131+ };
132+ assert_eq!(change, second);
133+ assert_eq!(conflicts[0].kind.code(), "CONTENT");
134+ let state = ws.state().unwrap();
135+ let rebase = state.rebase.unwrap();
136+ assert_eq!(rebase.pending, [third]);
137+ // The working copy has the first changeset rebased, and the markers;
138+ // the third one waits.
139+ assert_eq!(fs::read(dir.join("y")).unwrap(), b"y, ours\n");
140+ assert!(!dir.join("z").exists());
141+ let merged = fs::read_to_string(dir.join("x")).unwrap();
142+ assert!(merged.contains("<<<<<<< "), "{merged}");
143+
144+ // Neither landing nor updating while the rebase lasts.
145+ assert!(matches!(
146+ ws.land(None, "t", &ada()),
147+ Err(Error::RebaseInProgress)
148+ ));
149+ assert!(matches!(ws.update(&ada()), Err(Error::RebaseInProgress)));
150+ // Paths are refused: the resolution is recorded whole.
151+ let partial = ws.commit(&CommitRequest {
152+ message: None,
153+ paths: vec![b"x".to_vec()],
154+ author: None,
155+ committer: ada(),
156+ force: false,
157+ });
158+ assert!(
159+ matches!(partial, Err(Error::PathsDuringRebase)),
160+ "{partial:?}"
161+ );
162+
163+ fs::write(dir.join("x"), "1\nboth\n3\n").unwrap();
164+ let outcome = ws
165+ .commit(&CommitRequest {
166+ message: None,
167+ paths: Vec::new(),
168+ author: None,
169+ committer: ada(),
170+ force: false,
171+ })
172+ .unwrap();
173+ let RebaseProgress::Finished { tip } = outcome.rebase else {
174+ panic!("expected the rebase to finish, got {:?}", outcome.rebase);
175+ };
176+ // The third changeset followed, and the workspace is clean on top.
177+ assert_eq!(fs::read(dir.join("z")).unwrap(), b"z\n");
178+ assert_eq!(ws.state().unwrap().base, Some(tip));
179+ let report = ws.status().unwrap();
180+ assert!(report.status.is_clean());
181+ assert_eq!(report.unlanded.len(), 3);
182+
183+ let landed = ws.land(None, "t", &ada()).unwrap();
184+ assert_eq!(landed.landed, Landed::FastForward(tip));
185+ // Main has, in order: theirs, then first, second and third, each
186+ // naming the changeset it came from; the resolution keeps the
187+ // message of the change it resolves.
188+ let mut messages = Vec::new();
189+ let mut origins = Vec::new();
190+ let mut current = f.head("main");
191+ while let Some(id) = current {
192+ let changeset = braid_engine::read_changeset(f.repo.store(), id).unwrap();
193+ messages.push(String::from_utf8(changeset.message.clone()).unwrap());
194+ origins.push(
195+ changeset
196+ .extras
197+ .iter()
198+ .find(|(key, _)| key.as_slice() == braid_engine::REBASED_FROM)
199+ .map(|(_, value)| String::from_utf8(value.clone()).unwrap()),
200+ );
201+ current = changeset.parents.first().copied();
202+ }
203+ assert_eq!(
204+ messages,
205+ ["third", "second", "first", "test change\n", "test change\n"]
206+ );
207+ let hex = |id: braid_format::ObjectId| Some(id.to_hex());
208+ assert_eq!(origins[..3], [hex(third), hex(second), hex(first)]);
209+}
210+
211+#[test]
212+fn tracked_files_count_even_when_ignored() {
213+ let f = Fixture::new();
214+ let first = f.commit(
215+ &[],
216+ vec![(".gitignore", f.file("*.log\n")), ("kept.log", f.file("1"))],
217+ );
218+ let dir = f.path("ws");
219+ let (ws, _) = Workspace::create(&f.repo, "ws", &dir, Some(first), "main").unwrap();
220+ fs::write(dir.join("kept.log"), "2").unwrap();
221+ fs::write(dir.join("new.log"), "ignored").unwrap();
222+ let status = ws.status().unwrap().status;
223+ let changes: Vec<(&[u8], ChangeKind)> = status
224+ .changes
225+ .iter()
226+ .map(|c| (c.path.as_slice(), c.kind))
227+ .collect();
228+ assert_eq!(changes, [(&b"kept.log"[..], ChangeKind::Modified)]);
229+}
230+
231+#[test]
232+fn refusals() {
233+ let f = Fixture::new();
234+ let dir = f.path("ws");
235+ for bad in ["", ".hidden", "a/b", "../up"] {
236+ assert!(matches!(
237+ Workspace::create(&f.repo, bad, &dir, None, "main"),
238+ Err(Error::InvalidName(_))
239+ ));
240+ }
241+ let full = f.path("full");
242+ fs::create_dir(&full).unwrap();
243+ fs::write(full.join("there"), "x").unwrap();
244+ assert!(matches!(
245+ Workspace::create(&f.repo, "ws", &full, None, "main"),
246+ Err(Error::DirectoryNotEmpty(_))
247+ ));
248+ // A refused creation leaves no workspace behind, so the name is free.
249+ let (ws, written) = Workspace::create(&f.repo, "ws", &dir, None, "main").unwrap();
250+ assert_eq!(written, 0);
251+ assert!(matches!(
252+ Workspace::create(&f.repo, "ws", &f.path("other"), None, "main"),
253+ Err(Error::WorkspaceExists(_))
254+ ));
255+ assert!(matches!(
256+ Workspace::open(&f.repo, "nope"),
257+ Err(Error::NoSuchWorkspace(_))
258+ ));
259+ assert!(matches!(ws.resolve(&[b"x".to_vec()]), Err(Error::NoRebase)));
260+ assert!(matches!(
261+ ws.commit(&CommitRequest {
262+ message: Some(b"m".to_vec()),
263+ paths: Vec::new(),
264+ author: None,
265+ committer: ada(),
266+ force: false,
267+ }),
268+ Err(Error::NothingToCommit)
269+ ));
270+ fs::write(dir.join("f"), "x").unwrap();
271+ assert!(matches!(
272+ ws.commit(&CommitRequest {
273+ message: None,
274+ paths: Vec::new(),
275+ author: None,
276+ committer: ada(),
277+ force: false,
278+ }),
279+ Err(Error::NoMessage)
280+ ));
281+ // Landing or updating with uncommitted changes.
282+ assert!(matches!(
283+ ws.land(None, "t", &ada()),
284+ Err(Error::Uncommitted { .. })
285+ ));
286+ assert!(matches!(ws.update(&ada()), Err(Error::Uncommitted { .. })));
287+ // Nothing to land before the first commit; then a first landing makes
288+ // the branch.
289+ let made = commit_all(&ws, "first").changeset.unwrap();
290+ let landed = ws.land(None, "t", &ada()).unwrap();
291+ assert_eq!(landed.landed, Landed::FastForward(made));
292+ assert_eq!(f.head("main"), Some(made));
293+ assert_eq!(ws.land(None, "t", &ada()).unwrap().landed, Landed::Nothing);
294+}
modified docs/design.md +41 −5
@@ -104,13 +104,49 @@
104104
105105 - One workspace per agent, all sharing one store. No staging area: tracked
106106 files are snapshotted as they are.
107+- A workspace is any directory holding a `.braid` *file*, local and never
108+ tracked, that names the repository and the workspace. The workspace's state
109+ lives in the repository, under `.braid/ws/<name>/`: `state` (the base
110+ changeset, the branch it lands on, its directory, the file system's name
111+ rules, a rebase in progress), `stat` (the stat cache) and `lock`. Every
112+ command that changes a workspace holds its lock, so two processes never
113+ change one workspace at once; different workspaces never wait for each
114+ other, except for the short transaction in which a landing moves a branch.
107115 - New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger than
108116 1 MiB need an explicit `braid track`.
109-- Status uses a stat cache, with the usual guard against files modified in the
110- same instant the cache was written. A daemon can add a file system watcher.
111-- Checkouts never follow symlinks while walking or writing, write through a
112- temporary file and a rename, refuse names that would collide on the file
113- system, and never run anything from repository content.
117+- Status uses a stat cache (modification time, size, inode, type, blob id),
118+ with the usual guard: a file whose modification time is not strictly older
119+ than the start of the scan that cached it, read from the workspace's own
120+ file system clock, is hashed again. Files the cache cannot vouch for are
121+ hashed in parallel. `.gitignore` and `.braidignore` are honoured; tracked
122+ files count whatever they say. A daemon can add a file system watcher.
123+- Checkouts never follow symlinks while walking or writing: every step opens
124+ one name from its parent's directory handle, refusing symlinks. They write
125+ through a temporary file and a rename, with modes 0644 or 0755 only, remove
126+ before they create when a path changes type, write symlink targets as data,
127+ and make gitlinks empty directories. Each workspace finds out once, with a
128+ scratch file, whether its file system ignores letter case or Unicode
129+ normalisation; names that would collide there, or that the platform cannot
130+ hold, are refused before anything is written. Untracked files in the way
131+ stop a checkout too. Nothing from repository content is ever run.
132+- `braid commit` records the working copy as a changeset on the base.
133+ `braid land` puts the workspace's changesets on its branch in one op log
134+ transaction: the engine fast-forwards or rebases them onto the head, and the
135+ branch moves with a compare-and-swap. The working copy then follows, writing
136+ only the difference. On conflicts the branch does not move, the conflicts
137+ come back as data, and the command exits with status 2.
138+- `braid update` brings a workspace onto its branch's head, rebasing its own
139+ changesets without moving the branch. On conflicts, the working copy gets
140+ the head's tree with the change's clean paths and git-style markers for
141+ content conflicts; a rebase is then in progress, `braid resolve` settles the
142+ other conflicts, and the next `braid commit` records the resolution on the
143+ head, refusing while markers remain.
144+- A changeset can also be made without any working copy: `braid change
145+ create` takes the base, the new contents and the deletions, and can require
146+ what the base holds at each path first, so that an agent never overwrites
147+ an edit it did not see.
148+- Signatures record the time in UTC for now: the local time zone offset is not
149+ computed yet.
114150
115151 ## Git bridge
116152