navid/veins / commit

c24e60840b5e

Navid M <navidmomtahen@gmail.com> · 2026-11-30

parents: 5cec66944879

Browse files at this commit · Download source

all: restructure solution, remove unused legacy implementation
--- /dev/null+++ b/veins/.gitignore@@ -0,0 +1,1 @@+/target/--- /dev/null+++ b/veins/Cargo.lock@@ -0,0 +1,467 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "blake3"+version = "1.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd"+dependencies = [+ "arrayvec",+ "cc",+ "cfg-if",+ "constant_time_eq",+ "cpufeatures",+]++[[package]]+name = "cc"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "constant_time_eq"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"+dependencies = [+ "rustversion",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "find-msvc-tools"+version = "0.1.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.3",+ "libc",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustls"+version = "0.23.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "schannel"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags",+ "core-foundation",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "veins-rust"+version = "0.1.0"+dependencies = [+ "blake3",+ "libc",+ "rayon",+ "ring",+ "rustls",+ "rustls-native-certs",+ "rustls-pki-types",+ "webpki-roots",+ "zstd",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "webpki-roots"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"++[[package]]+name = "zstd"+version = "0.13.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b04655dc7bf4abd8ebe23dac6bef20fceea52a29ad19e37a4101b3951d7e8b45"+dependencies = [+ "zstd-safe",+]++[[package]]+name = "zstd-safe"+version = "7.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df2575690b2a3eccad509fe7898cdde32a5afca06a06449ff4dcfb318c7b7281"+dependencies = [+ "zstd-sys",+]++[[package]]+name = "zstd-sys"+version = "2.2.0+zstd.1.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160"+dependencies = [+ "cc",+ "pkg-config",+]--- /dev/null+++ b/veins/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "veins-rust"+version = "0.1.0"+edition = "2024"+license = "MIT"++[[bin]]+name = "vn"+path = "src/main.rs"++[dependencies]+blake3 = "1.8"+libc = "0.2"+rayon = "1.12"+ring = "0.17"+rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }+rustls-native-certs = "0.8"+rustls-pki-types = { version = "1", features = ["std"] }+webpki-roots = "1"+zstd = "0.13"++[profile.release]+opt-level = 3+lto = false+codegen-units = 16--- /dev/null+++ b/veins/src/cli/args.rs@@ -0,0 +1,40 @@+use crate::error::{Error, Result};++pub fn is_flag(argument: &str) -> bool {+    argument.starts_with('-') && argument != "-"+}++pub fn join(parts: &[String]) -> String {+    parts.join(" ")+}++pub fn message_is_blank(parts: &[String]) -> bool {+    parts+        .iter()+        .flat_map(|part| part.bytes())+        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))+}++pub fn parse_message(args: &[String], start: usize) -> Result<Vec<String>> {+    let mut parts = Vec::new();+    let mut end_flags = false;+    let mut index = start;+    while index < args.len() {+        let argument = &args[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-m" || argument == "-message") {+            index += 1;+            if index >= args.len() {+                return Err(Error::new(format!("{argument} requires a message")));+            }+            parts.push(args[index].clone());+        } else if !end_flags && is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            parts.push(argument.clone());+        }+        index += 1;+    }+    Ok(parts)+}--- /dev/null+++ b/veins/src/cli/commands/bookmark.rs@@ -0,0 +1,222 @@+use std::path::Path;++use crate::cli::args;+use crate::error::{Error, Result};+use crate::object::view::Bookmark;+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::snapshot;++pub fn run(arguments: &[String]) -> Result<u8> {+    let Some(subcommand) = arguments.first() else {+        return Err(Error::new("bmk requires a subcommand"));+    };+    let rest = &arguments[1..];+    match subcommand.as_str() {+        "set" | "mv" => set(rest),+        "ls" => list(rest),+        "rm" => remove(rest),+        _ => Err(Error::new(format!("unknown bmk subcommand: {subcommand}"))),+    }+}++fn valid_bookmark_name(name: &str) -> bool {+    if name.is_empty() {+        return false;+    }+    let bytes = name.as_bytes();+    if bytes[0] == b'-' || bytes[0] == b'/' || bytes[0] == b'.' {+        return false;+    }+    if bytes[bytes.len() - 1] == b'/' || bytes[bytes.len() - 1] == b'.' {+        return false;+    }+    for byte in bytes {+        if *byte == 0 || *byte == b' ' || *byte < 32 || *byte == 127 {+            return false;+        }+        if matches!(*byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\') {+            return false;+        }+    }+    if name.contains("..") || name.contains("@{") || name.contains("//") {+        return false;+    }+    if name == "@" || name.ends_with(".lock") {+        return false;+    }+    true+}++fn set(arguments: &[String]) -> Result<u8> {+    let mut name = String::new();+    let mut revision = String::new();+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && args::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if name.is_empty() {+            name = argument.clone();+        } else if revision.is_empty() {+            revision = argument.clone();+        } else {+            return Err(Error::new("bmk set accepts a name and one revision"));+        }+        index += 1;+    }+    if name.is_empty() {+        return Err(Error::new("bmk set requires a name"));+    }+    if !valid_bookmark_name(&name) {+        return Err(Error::new(format!("invalid bookmark name: {name}")));+    }++    let root = layout::discover(Path::new("."))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?+        .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;++    let mut changed = true;+    match ops::find_bookmark(txn.view(), name.as_bytes()) {+        Some(existing) => {+            let bookmark = &mut txn.view_mut().bookmarks[existing];+            if ops::bookmark_points_at(bookmark, target) {+                changed = false;+            } else {+                bookmark.targets.adds = vec![Some(target)];+                bookmark.targets.removes.clear();+            }+        }+        None => {+            txn.view_mut().bookmarks.push(Bookmark {+                name: name.as_bytes().to_vec(),+                targets: crate::object::view::TargetSet {+                    adds: vec![Some(target)],+                    removes: Vec::new(),+                },+            });+        }+    }++    if !changed {+        println!("info: bookmark {name} is already at {}", target.short());+        return Ok(0);+    }+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("bookmark set {name}"))?;+    println!("info: bookmark {name} set to {}", target.short());+    Ok(0)+}++fn list(arguments: &[String]) -> Result<u8> {+    let mut column_titles = true;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && argument == "-no-col-titles" {+            column_titles = false;+        } else if !end_flags && args::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            return Err(Error::new("bmk ls takes no operands"));+        }+    }++    let root = layout::discover(Path::new("."))?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let working_copy = ops::working_copy_id(&view);+    let mut name_width = 8;+    for bookmark in &view.bookmarks {+        name_width = name_width.max(bookmark.name.len());+    }+    if column_titles {+        println!(+            "{:<name_width$}  {:<12}  {:<8}  Target",+            "Bookmark",+            "Commit",+            "Change",+            name_width = name_width+        );+    }+    for bookmark in &view.bookmarks {+        let name = String::from_utf8_lossy(&bookmark.name);+        let Some(target) = bookmark.targets.adds.first().copied().flatten() else {+            println!(+                "{:<name_width$}  {:<12}  {:<8}  (missing)",+                name,+                "<missing>",+                "",+                name_width = name_width+            );+            continue;+        };+        let change = match graph::load_commit(&mut store, target)? {+            Some(commit) => graph::base32_encode(commit.change_id)[..8].to_string(),+            None => String::new(),+        };+        let marker = if working_copy == Some(target) {+            "@"+        } else {+            ""+        };+        println!(+            "{:<name_width$}  {:<12}  {:<8}  {marker}",+            name,+            target.short(),+            change,+            name_width = name_width+        );+    }+    if view.bookmarks.is_empty() {+        println!("info: no bookmarks");+    }+    Ok(0)+}++fn remove(arguments: &[String]) -> Result<u8> {+    let mut name = String::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && args::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if !name.is_empty() {+            return Err(Error::new("bmk rm accepts exactly one name"));+        } else {+            name = argument.clone();+        }+    }+    if name.is_empty() {+        return Err(Error::new("bmk rm requires a name"));+    }+    let root = layout::discover(Path::new("."))?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let Some(existing) = ops::find_bookmark(txn.view(), name.as_bytes()) else {+        return Err(Error::new(format!("no such bookmark: {name}")));+    };+    txn.view_mut().bookmarks.remove(existing);+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("bookmark delete {name}"))?;+    println!("info: deleted bookmark {name}");+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/commands/checkout.rs@@ -0,0 +1,23 @@+use std::path::Path;++use crate::cli::args;+use crate::error::Result;+use crate::store::layout;+use crate::worktree::checkout;++pub fn run(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && args::is_flag(argument) {+            return Err(crate::Error::new(format!("unknown flag: {argument}")));+        } else if revision.is_empty() {+            revision = argument.clone();+        }+    }+    let root = layout::discover(Path::new("."))?;+    checkout::run(&root, &revision)?;+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/commands/commit.rs@@ -0,0 +1,109 @@+use std::path::Path;++use crate::cli::args;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::TYPE_COMMIT;+use crate::object::commit::{self, Commit};+use crate::object::id::Id;+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::snapshot;++enum Outcome {+    Nothing,+    Described,+}++pub fn run(arguments: &[String]) -> Result<u8> {+    let parts = args::parse_message(arguments, 0)?;+    if args::message_is_blank(&parts) {+        return Err(Error::new("commit requires a non-empty message (-message)"));+    }+    let message = args::join(&parts);+    let root = layout::discover(Path::new("."))?;+    let mut store = Store::open(&root)?;++    if matches!(+        describe(&root, &mut store, &message, true)?,+        Outcome::Nothing+    ) {+        return Ok(0);+    }+    create_empty(&root, &mut store)?;+    Ok(0)+}++fn describe(+    root: &Path,+    store: &mut Store,+    message: &str,+    require_changes: bool,+) -> Result<Outcome> {+    snapshot::run_with(root, store)?;+    let mut txn = Txn::begin(root, store)?;+    let working_copy =+        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+    let loaded = graph::load_commit(store, working_copy)?+        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+    let changed = graph::has_changes(store, &loaded)?;+    let same_message = loaded.message == message.as_bytes();+    if !changed && (require_changes || same_message) {+        if require_changes {+            println!("info: nothing to commit, working copy clean");+        }+        return Ok(Outcome::Nothing);+    }++    let signature = identity::signature(root);+    let mut updated = loaded;+    updated.committer = signature;+    updated.message = message.as_bytes().to_vec();+    let encoded = commit::encode(&updated);+    let new_id = txn.add_object(TYPE_COMMIT, encoded);+    ops::remove_head(txn.view_mut(), working_copy);+    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    txn.finish("describe")?;+    store.refresh()?;+    mark_native(root, new_id)?;+    Ok(Outcome::Described)+}++fn create_empty(root: &Path, store: &mut Store) -> Result<()> {+    let mut txn = Txn::begin(root, store)?;+    let working_copy =+        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+    let loaded = graph::load_commit(store, working_copy)?+        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+    let signature = identity::signature(root);+    let new_commit = Commit {+        version: 1,+        parents: vec![working_copy],+        root_tree: loaded.root_tree,+        change_id: identity::random_change_id(),+        author: signature.clone(),+        committer: signature,+        message: Vec::new(),+        renames_state: commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    let encoded = commit::encode(&new_commit);+    let new_id = txn.add_object(TYPE_COMMIT, encoded);+    ops::remove_head(txn.view_mut(), working_copy);+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    txn.finish("new")?;+    mark_native(root, new_id)?;+    Ok(())+}++fn mark_native(root: &Path, id: Id) -> Result<()> {+    let path = layout::git_map_dir(root).join("native");+    layout::append_file(&path, format!("{}\n", id.to_hex()).as_bytes())+}--- /dev/null+++ b/veins/src/cli/commands/init.rs@@ -0,0 +1,66 @@+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::store::layout;++pub fn run(arguments: &[String]) -> Result<u8> {+    let mut path = ".".to_string();+    let mut source = None;+    let mut remote_url = String::new();+    let mut remote_name = "o".to_string();+    let mut remote_name_given = false;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && let Some(value) = argument.strip_prefix("-git-import:") {+            if value.is_empty() {+                return Err(Error::new("-git-import: requires a path"));+            }+            source = Some(value.to_string());+        } else if !end_flags && let Some(value) = argument.strip_prefix("-remote:") {+            if value.is_empty() {+                return Err(Error::new("-remote: requires a URL"));+            }+            remote_url = value.to_string();+        } else if !end_flags && let Some(value) = argument.strip_prefix("-remote-name:") {+            if value.is_empty() {+                return Err(Error::new("-remote-name: requires a name"));+            }+            remote_name = value.to_string();+            remote_name_given = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            path = argument.clone();+        }+    }+    if remote_name_given && remote_url.is_empty() {+        return Err(Error::new("-remote-name: requires -remote:<url>"));+    }+    if source.is_none() && !remote_url.is_empty() {+        return Err(Error::new("-remote: requires -git-import:<path>"));+    }+    let root = layout::init(Path::new(&path)).map_err(|_| Error::new("init failed"))?;+    println!("info: initialized veins repository at {}", root.display());+    if let Some(source) = source {+        let prepared = crate::git::prepare_mirror(&root, &source);+        if prepared != 0 {+            if prepared == 2 {+                return Err(Error::new(format!(+                    "-git-import: {source} is not a git repository root (expected the directory containing .git)"+                )));+            }+            return Err(Error::new(format!(+                "cannot prepare git mirror from {source} (code {prepared})"+            )));+        }+        let imported = crate::git::import(&root);+        if imported != 0 {+            return Ok(1);+        }+        crate::git::configure_remote(&root, &remote_url, &remote_name);+    }+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/commands/log.rs@@ -0,0 +1,139 @@+use std::path::Path;++use crate::cli::args;+use crate::error::Result;+use crate::object::id::Id;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::time;+use crate::worktree::snapshot;++struct Record {+    id: Id,+    change: String,+    seconds: i64,+    message: Vec<u8>,+    author: Vec<u8>,+}++pub fn run(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut column_titles = true;+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(crate::Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && argument == "-no-col-titles" {+            column_titles = false;+        } else if !end_flags && args::is_flag(argument) {+            return Err(crate::Error::new(format!("unknown flag: {argument}")));+        } else {+            revision = argument.clone();+        }+        index += 1;+    }++    let root = layout::discover(Path::new("."))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let view = ops::current_view(&root, &mut store)?+        .ok_or_else(|| crate::Error::new("no operation state"))?;+    let working_copy = ops::working_copy_id(&view);++    let ids = if revision.is_empty() || revision == "all()" {+        let roots = graph::view_roots(&view);+        graph::collect_commits(&mut store, &roots)?+    } else if let Some(target) = graph::resolve_revision(&mut store, &view, &revision)? {+        graph::collect_commits(&mut store, &[target])?+    } else {+        Vec::new()+    };++    let mut records = Vec::new();+    for id in ids {+        let Some(commit) = graph::load_commit(&mut store, id)? else {+            continue;+        };+        records.push(Record {+            id,+            change: graph::base32_encode(commit.change_id),+            seconds: commit.committer.seconds,+            message: commit.message,+            author: commit.author.name,+        });+    }+    records.sort_by(|left, right| right.seconds.cmp(&left.seconds));++    let change_ids: Vec<String> = records.iter().map(|record| record.change.clone()).collect();+    let mut change_width = 6;+    let mut author_width = 6;+    for (index, record) in records.iter().enumerate() {+        change_width = change_width.max(graph::short_change_id(&change_ids, index).len());+        author_width = author_width.max(record.author.len());+    }++    if column_titles {+        println!(+            "  {:<12}  {:<change_width$}  {:<19}  {:<author_width$}  Message",+            "Commit",+            "Change",+            "Date",+            "Author",+            change_width = change_width,+            author_width = author_width,+        );+    }++    for (index, record) in records.iter().enumerate() {+        let marker = if working_copy == Some(record.id) {+            "@"+        } else {+            " "+        };+        let change = graph::short_change_id(&change_ids, index);+        let date = time::format_utc(record.seconds);+        let message = first_line(&record.message);+        print!(+            "{marker} {:<12}  {:<change_width$}  {:<19}  {:<author_width$}  {}",+            record.id.short(),+            change,+            date,+            String::from_utf8_lossy(&record.author),+            String::from_utf8_lossy(message),+            change_width = change_width,+            author_width = author_width,+        );+        for name in ops::bookmark_names(&view, record.id) {+            print!(" [{}]", String::from_utf8_lossy(&name));+        }+        for name in ops::tag_names(&view, record.id) {+            print!(" <{}>", String::from_utf8_lossy(&name));+        }+        if change_ids+            .iter()+            .enumerate()+            .any(|(other, value)| other != index && *value == record.change)+        {+            print!(" (divergent)");+        }+        println!();+    }+    Ok(0)+}++fn first_line(message: &[u8]) -> &[u8] {+    match message.iter().position(|byte| *byte == b'\n') {+        Some(position) => &message[..position],+        None => message,+    }+}--- /dev/null+++ b/veins/src/cli/commands/mod.rs@@ -0,0 +1,8 @@+pub mod bookmark;+pub mod checkout;+pub mod commit;+pub mod init;+pub mod log;+pub mod selftest;+pub mod status;+pub mod version;--- /dev/null+++ b/veins/src/cli/commands/selftest.rs@@ -0,0 +1,183 @@+use crate::error::{Error, Result};+use crate::object::blob::{self, BlobForm};+use crate::object::chunker::{gear_table, next_chunk};+use crate::object::commit::{self, Commit, Sig};+use crate::object::id::{Id, hash_bytes, object_id};+use crate::object::tree;+use crate::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef};+use crate::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};+use crate::store::pack;++pub fn run() -> Result<u8> {+    let empty_hash = hex(&hash_bytes(b""));+    expect(+        empty_hash == "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262",+        "blake3 vector",+    )?;++    let gear = gear_table();+    expect(gear[0] == 0xf8447b379cdadcd5, "gear table entry 0")?;+    expect(gear[1] == 0xbe63d125aec8ca6d, "gear table entry 1")?;++    let mut chunk_input = vec![0u8; 300_000];+    for (index, byte) in chunk_input.iter_mut().enumerate() {+        *byte = ((index * 31 + 2 * 17) % 251) as u8;+    }+    let first = next_chunk(&chunk_input);+    let second = next_chunk(&chunk_input[first..]);+    expect(first == 262_144 && second == 37_856, "chunk boundaries")?;+    expect(+        object_id(TYPE_CHUNK, &chunk_input[..first]).to_hex()+            == "c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458",+        "first chunk id",+    )?;+    expect(+        object_id(TYPE_CHUNK, &chunk_input[first..]).to_hex()+            == "0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b",+        "second chunk id",+    )?;+    let build = blob::build(&chunk_input);+    expect(+        build.root.to_hex() == "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf",+        "manifest blob id",+    )?;+    let Some(manifest_object) = build.objects.last() else {+        return expect(false, "manifest object present").map(|()| 0);+    };+    let manifest = blob::decode(&manifest_object.body)?;+    expect(manifest.form == BlobForm::Leaf, "manifest form")?;++    let empty_tree_body = vec![0u8];+    let empty_tree_id = object_id(TYPE_TREE, &empty_tree_body);+    expect(+        empty_tree_id.to_hex()+            == "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb",+        "empty tree id",+    )?;+    expect(+        tree::decode(&empty_tree_body)?.entries.is_empty(),+        "empty tree decode",+    )?;++    let inline = blob::encode_inline(b"hello");+    expect(+        object_id(TYPE_BLOB, &inline).to_hex()+            == "f04a7f7324bbb7279471b5c656c893ee51b62ed9f9bad4c8cb8a289101f68240",+        "inline blob id",+    )?;++    let change_id: [u8; 16] = [+        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,+        0x1a,+    ];+    let signature = Sig {+        name: b"Alice".to_vec(),+        email: b"alice@example.com".to_vec(),+        seconds: 1_700_000_000,+        tz_min: 0,+    };+    let commit = Commit {+        version: 1,+        parents: Vec::new(),+        root_tree: empty_tree_id,+        change_id,+        author: signature.clone(),+        committer: signature,+        message: b"initial commit".to_vec(),+        renames_state: commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    let commit_body = commit::encode(&commit);+    let commit_id = object_id(crate::object::TYPE_COMMIT, &commit_body);+    expect(+        commit_id.to_hex() == "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299",+        "commit id",+    )?;+    expect(+        commit_id+            == Id::from_hex("7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299")?,+        "commit round trip",+    )?;++    let view = View {+        heads: vec![commit_id],+        bookmarks: vec![Bookmark {+            name: b"main".to_vec(),+            targets: TargetSet {+                adds: vec![Some(commit_id)],+                removes: Vec::new(),+            },+        }],+        tags: Vec::new(),+        remote_refs: Vec::new(),+        working_copies: vec![WorkspaceRef {+            workspace: b"default".to_vec(),+            target: commit_id,+        }],+    };+    let view_body = view::encode_view(&view);+    let view_id = object_id(crate::object::TYPE_VIEW, &view_body);+    expect(+        view_id.to_hex() == "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11",+        "view id",+    )?;++    let operation = Operation {+        parents: Vec::new(),+        view: view_id,+        start: TimeMs {+            millis: 1_700_000_000_000,+            tz_min: 0,+        },+        end: TimeMs {+            millis: 1_700_000_000_000,+            tz_min: 0,+        },+        hostname: b"host".to_vec(),+        username: b"alice".to_vec(),+        description: b"selftest operation".to_vec(),+        tags: Vec::new(),+    };+    let operation_body = view::encode_operation(&operation);+    expect(+        object_id(crate::object::TYPE_OPERATION, &operation_body).to_hex()+            == "0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426",+        "operation id",+    )?;++    let output = pack::encode(&[RawObject::known(TYPE_TREE, empty_tree_id, vec![0])], 3);+    expect(+        hex(&output.pack)+            == "56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911",+        "pack bytes",+    )?;+    expect(output.index.len() == 1136, "index length")?;+    expect(+        hex(&hash_bytes(&output.index))+            == "d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc",+        "index checksum",+    )?;+    pack::decode(output.pack)?;++    println!("self-test: ok");+    Ok(0)+}++fn expect(condition: bool, message: &str) -> Result<()> {+    if condition {+        Ok(())+    } else {+        Err(Error::new(format!("self-test failed: {message}")))+    }+}++fn hex(bytes: &[u8]) -> String {+    const DIGITS: &[u8; 16] = b"0123456789abcdef";+    let mut text = String::with_capacity(bytes.len() * 2);+    for byte in bytes {+        text.push(DIGITS[(byte >> 4) as usize] as char);+        text.push(DIGITS[(byte & 0x0f) as usize] as char);+    }+    text+}--- /dev/null+++ b/veins/src/cli/commands/status.rs@@ -0,0 +1,50 @@+use std::path::Path;++use crate::error::{Error, Result};+use crate::object::tree::{KIND_CONFLICT, KIND_MISSING};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::snapshot;++pub fn run() -> Result<u8> {+    let root = layout::discover(Path::new("."))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let Some(working_copy) = ops::working_copy_id(&view) else {+        println!("info: working copy clean");+        return Ok(0);+    };+    let commit = graph::load_commit(&mut store, working_copy)?+        .ok_or_else(|| Error::new("no operation state"))?;+    let old_tree = match commit.parents.first() {+        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),+        None => None,+    };+    let changes = graph::compare_trees(&mut store, old_tree, Some(commit.root_tree))?;+    let empty = changes.is_empty();+    let mut conflicts = 0usize;+    for change in changes {+        let path = String::from_utf8_lossy(&change.path);+        if change.old_kind == KIND_MISSING {+            println!("A {path}");+        } else if change.new_kind == KIND_MISSING {+            println!("D {path}");+        } else if change.new_kind == KIND_CONFLICT {+            println!("C {path}");+            conflicts += 1;+        } else {+            println!("M {path}");+        }+    }+    if empty {+        println!("info: working copy clean");+    }+    if conflicts > 0 {+        println!("{conflicts} conflict(s)");+    }+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/commands/version.rs@@ -0,0 +1,6 @@+use crate::error::Result;++pub fn run() -> Result<u8> {+    println!("veins-rust v0.1.0 (veins-store 1)");+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/config_cmd.rs@@ -0,0 +1,214 @@+use std::collections::BTreeMap;+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::store::layout;++pub fn run(arguments: &[String]) -> Result<u8> {+    if arguments.len() == 1 && matches!(arguments[0].as_str(), "help" | "-h" | "-help") {+        usage();+        return Ok(0);+    }+    let mut global = false;+    let mut list = false;+    let mut unset = false;+    let mut show_defaults = false;+    let mut internal = false;+    let mut end_flags = false;+    let mut positional = Vec::new();+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-global" || argument == "-g") {+            global = true;+        } else if !end_flags && (argument == "-list" || argument == "-l") {+            list = true;+        } else if !end_flags && argument == "-unset" {+            unset = true;+        } else if !end_flags && (argument == "-d" || argument == "-defaults") {+            show_defaults = true;+        } else if !end_flags && (argument == "-i" || argument == "-internal") {+            internal = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            positional.push(argument.clone());+        }+    }+    if show_defaults {+        if list || unset || !positional.is_empty() {+            return Err(Error::new("cfg -d takes no operands"));+        }+        return defaults(internal);+    }+    if internal {+        return Err(Error::new("cfg -i requires -d"));+    }+    if positional.len() == 1 && matches!(positional[0].as_str(), "list" | "ls") {+        list = true;+        positional.clear();+    } else if positional.len() == 2 && positional[0] == "get" {+        positional.remove(0);+    } else if positional.len() == 3 && positional[0] == "set" {+        positional.remove(0);+    } else if positional.len() == 2 && matches!(positional[0].as_str(), "unset" | "rm" | "remove") {+        unset = true;+        positional.remove(0);+    }+    if list {+        if !positional.is_empty() {+            return Err(Error::new("cfg list takes no operands"));+        }+    } else if unset {+        if positional.len() != 1 {+            return Err(Error::new("cfg unset requires one key"));+        }+    } else if positional.len() > 2 {+        return Err(Error::new("cfg accepts a key and one value"));+    }+    let root = if global {+        None+    } else {+        Some(layout::discover(Path::new(".")).map_err(|_| Error::new("not a veins repository"))?)+    };+    if list {+        return list_entries(root.as_deref(), global);+    }+    if unset {+        return unset_entry(root.as_deref(), global, &positional[0]);+    }+    match positional.len() {+        0 => list_entries(root.as_deref(), global),+        1 => get_entry(root.as_deref(), global, &positional[0]),+        _ => set_entry(root.as_deref(), global, &positional[0], &positional[1]),+    }+}++fn usage() {+    println!("usage: vn cfg [<key>] [<value>]");+    println!("       vn cfg [<get|set|unset|list>] [<key>] [<value>]");+    println!("       vn cfg -list");+    println!("       vn cfg -d [-i]");+    println!("       vn cfg -unset <key>");+    println!();+    println!("read and write local repository configuration");+}++fn defaults(internal: bool) -> Result<u8> {+    let mut values = BTreeMap::from([+        ("core.editor", "(unset)"),+        ("core.pager", "(unset)"),+        ("editor", "vi"),+        ("log.default_amount", "20"),+        ("merge.adjacent", "strict"),+        ("pager", "less -R"),+        ("rename.autodetect", "similar"),+        ("user.email", "(unset)"),+        ("user.name", "(unset)"),+    ]);+    if internal {+        values.insert("bookmark.current", "(unset)");+        values.insert("promisor", "(unset)");+        values.insert("remote.<name>.key", "(unset)");+        values.insert("remote.<name>.tls-pin", "(unset)");+        values.insert("remote.<name>.url", "(unset)");+        values.insert("remote.current", "(unset)");+        values.insert("remote.default", "(unset)");+    }+    for (key, value) in values {+        print!("{key} = {value}");+        if let Some(current) = core::user_config_value(key) {+            print!(" (current: {current})");+        }+        println!();+    }+    Ok(0)+}++fn repo_entries(root: &Path) -> BTreeMap<String, String> {+    let Some(data) = core::read_file_opt(&layout::config_path(root), 0) else {+        return BTreeMap::new();+    };+    let text = String::from_utf8_lossy(&data);+    let mut output = BTreeMap::new();+    for raw in text.lines() {+        let line = core::trim_str(raw);+        if line.is_empty() || line.starts_with('#') {+            continue;+        }+        let Some((key, value)) = line.split_once('=') else {+            continue;+        };+        let key = core::trim_str(key);+        if !key.is_empty() {+            output.insert(key.to_string(), core::trim_str(value).to_string());+        }+    }+    output+}++fn list_entries(root: Option<&Path>, global: bool) -> Result<u8> {+    let entries = if global {+        core::user_config_entries()+    } else {+        repo_entries(root.ok_or_else(|| Error::new("not a veins repository"))?)+    };+    for (key, value) in entries {+        println!("{key} = {value}");+    }+    Ok(0)+}++fn get_value(root: Option<&Path>, global: bool, key: &str) -> Option<String> {+    if global {+        core::user_config_value(key)+    } else {+        core::repo_config_value(root?, key)+    }+}++fn get_entry(root: Option<&Path>, global: bool, key: &str) -> Result<u8> {+    let Some(value) = get_value(root, global, key) else {+        return Err(Error::new(format!("unknown config key: {key}")));+    };+    println!("{value}");+    Ok(0)+}++fn set_entry(root: Option<&Path>, global: bool, key: &str, value: &str) -> Result<u8> {+    let ok = if global {+        core::user_config_set(key, value)+    } else {+        core::repo_config_set(+            root.ok_or_else(|| Error::new("not a veins repository"))?,+            key,+            value,+        )+    };+    if !ok {+        return Err(Error::new(format!(+            "cannot write {} config",+            if global { "user" } else { "repository" }+        )));+    }+    Ok(0)+}++fn unset_entry(root: Option<&Path>, global: bool, key: &str) -> Result<u8> {+    let ok = if global {+        core::user_config_remove(key)+    } else {+        core::repo_config_remove(+            root.ok_or_else(|| Error::new("not a veins repository"))?,+            key,+        )+    };+    if !ok {+        return Err(Error::new(format!(+            "cannot write {} config",+            if global { "user" } else { "repository" }+        )));+    }+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/diff.rs@@ -0,0 +1,374 @@+use crate::object::id::Id;+use crate::object::tree::{KIND_CONFLICT, KIND_MISSING};+use crate::store::graph;+use crate::store::reader::Store;++#[derive(Clone, Copy)]+struct DiffOp {+    tag: u8,+    ai: usize,+    bi: usize,+}++pub fn split_lines(data: &[u8]) -> Vec<&[u8]> {+    let mut output = Vec::new();+    let mut start = 0;+    for (index, byte) in data.iter().enumerate() {+        if *byte == b'\n' {+            output.push(&data[start..index]);+            start = index + 1;+        }+    }+    if start < data.len() {+        output.push(&data[start..]);+    }+    output+}++fn build_ops_lcs(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {+    let n = a.len();+    let m = b.len();+    let columns = m + 1;+    let mut dp = vec![0u32; (n + 1) * columns];+    for i in 1..=n {+        for j in 1..=m {+            dp[i * columns + j] = if a[i - 1] == b[j - 1] {+                dp[(i - 1) * columns + (j - 1)] + 1+            } else {+                dp[(i - 1) * columns + j].max(dp[i * columns + (j - 1)])+            };+        }+    }+    let mut ops = Vec::with_capacity(n + m);+    let mut i = n;+    let mut j = m;+    while i > 0 || j > 0 {+        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {+            ops.push(DiffOp {+                tag: b' ',+                ai: i - 1,+                bi: j - 1,+            });+            i -= 1;+            j -= 1;+        } else if j > 0 && (i == 0 || dp[i * columns + (j - 1)] >= dp[(i - 1) * columns + j]) {+            ops.push(DiffOp {+                tag: b'+',+                ai: 0,+                bi: j - 1,+            });+            j -= 1;+        } else {+            ops.push(DiffOp {+                tag: b'-',+                ai: i - 1,+                bi: 0,+            });+            i -= 1;+        }+    }+    ops.reverse();+    ops+}++fn build_ops_myers(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {+    let n = a.len() as isize;+    let m = b.len() as isize;+    let max_d = n + m;+    let offset = max_d;+    let length = (2 * max_d + 1) as usize;+    let mut v = vec![0isize; length];+    let mut trace: Vec<Vec<isize>> = Vec::new();+    const TRACE_CAP: usize = 64 * 1024 * 1024;+    let mut found = -1isize;+    for d in 0..=max_d {+        if (trace.len() + 1) * length * std::mem::size_of::<isize>() > TRACE_CAP {+            return Vec::new();+        }+        trace.push(v.clone());+        let mut k = -d;+        while k <= d {+            let mut x = if k == -d+                || (k != d && v[(offset + k - 1) as usize] < v[(offset + k + 1) as usize])+            {+                v[(offset + k + 1) as usize]+            } else {+                v[(offset + k - 1) as usize] + 1+            };+            let mut y = x - k;+            while x < n && y < m && a[x as usize] == b[y as usize] {+                x += 1;+                y += 1;+            }+            v[(offset + k) as usize] = x;+            if x >= n && y >= m {+                found = d;+                break;+            }+            k += 2;+        }+        if found >= 0 {+            break;+        }+    }+    if found < 0 {+        return Vec::new();+    }+    let mut ops = Vec::new();+    let mut x = n;+    let mut y = m;+    let mut d = found;+    while d >= 0 {+        let previous = &trace[d as usize];+        let k = x - y;+        let previous_k = if k == -d+            || (k != d && previous[(offset + k - 1) as usize] < previous[(offset + k + 1) as usize])+        {+            k + 1+        } else {+            k - 1+        };+        let previous_x = previous[(offset + previous_k) as usize];+        let previous_y = previous_x - previous_k;+        while x > previous_x && y > previous_y {+            ops.push(DiffOp {+                tag: b' ',+                ai: (x - 1) as usize,+                bi: (y - 1) as usize,+            });+            x -= 1;+            y -= 1;+        }+        if d > 0 {+            if x == previous_x {+                ops.push(DiffOp {+                    tag: b'+',+                    ai: 0,+                    bi: (y - 1) as usize,+                });+                y -= 1;+            } else {+                ops.push(DiffOp {+                    tag: b'-',+                    ai: (x - 1) as usize,+                    bi: 0,+                });+                x -= 1;+            }+        }+        d -= 1;+    }+    ops.reverse();+    ops+}++fn build_ops_fallback(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {+    let mut prefix = 0;+    while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {+        prefix += 1;+    }+    let mut suffix = 0;+    while suffix < a.len() - prefix+        && suffix < b.len() - prefix+        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]+    {+        suffix += 1;+    }+    let mut ops = Vec::with_capacity(a.len() + b.len());+    for index in 0..prefix {+        ops.push(DiffOp {+            tag: b' ',+            ai: index,+            bi: index,+        });+    }+    for index in prefix..a.len() - suffix {+        ops.push(DiffOp {+            tag: b'-',+            ai: index,+            bi: 0,+        });+    }+    for index in prefix..b.len() - suffix {+        ops.push(DiffOp {+            tag: b'+',+            ai: 0,+            bi: index,+        });+    }+    for index in 0..suffix {+        ops.push(DiffOp {+            tag: b' ',+            ai: a.len() - suffix + index,+            bi: b.len() - suffix + index,+        });+    }+    ops+}++fn build_ops(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {+    if a.is_empty() && b.is_empty() {+        return Vec::new();+    }+    if !a.is_empty() && !b.is_empty() && (a.len() <= 2048 && b.len() <= 2048) {+        return build_ops_lcs(a, b);+    }+    if !a.is_empty() && !b.is_empty() && a.len() * b.len() <= 4_000_000 {+        return build_ops_lcs(a, b);+    }+    let myers = build_ops_myers(a, b);+    if !myers.is_empty() {+        return myers;+    }+    build_ops_fallback(a, b)+}++pub fn render_unified_for(a: &[&[u8]], b: &[&[u8]], output: &mut String) {+    render_unified(a, b, output);+}++fn render_unified(a: &[&[u8]], b: &[&[u8]], output: &mut String) {+    let ops = build_ops(a, b);+    let changes: Vec<usize> = ops+        .iter()+        .enumerate()+        .filter(|(_, op)| op.tag != b' ')+        .map(|(index, _)| index)+        .collect();+    const CONTEXT: usize = 3;+    let mut position = 0;+    let mut old_seen = 0;+    let mut new_seen = 0;+    let mut change_index = 0;+    while change_index < changes.len() {+        let first = changes[change_index];+        let start = first.saturating_sub(CONTEXT);+        let mut last = first;+        change_index += 1;+        while change_index < changes.len() && changes[change_index] <= last + CONTEXT * 2 {+            last = changes[change_index];+            change_index += 1;+        }+        let end = (last + CONTEXT + 1).min(ops.len());+        while position < start {+            match ops[position].tag {+                b' ' => {+                    old_seen += 1;+                    new_seen += 1;+                }+                b'-' => old_seen += 1,+                _ => new_seen += 1,+            }+            position += 1;+        }+        let mut old_count = 0;+        let mut new_count = 0;+        for op in &ops[start..end] {+            match op.tag {+                b' ' => {+                    old_count += 1;+                    new_count += 1;+                }+                b'-' => old_count += 1,+                _ => new_count += 1,+            }+        }+        let old_start = old_seen + usize::from(old_count > 0);+        let new_start = new_seen + usize::from(new_count > 0);+        output.push_str(&format!(+            "@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"+        ));+        while position < end {+            let op = ops[position];+            match op.tag {+                b' ' => {+                    output.push(' ');+                    output.push_str(&String::from_utf8_lossy(a[op.ai]));+                    output.push('\n');+                    old_seen += 1;+                    new_seen += 1;+                }+                b'-' => {+                    output.push_str(&super::output::red("-"));+                    output.push_str(&super::output::red(&String::from_utf8_lossy(a[op.ai])));+                    output.push('\n');+                    old_seen += 1;+                }+                _ => {+                    output.push_str(&super::output::green("+"));+                    output.push_str(&super::output::green(&String::from_utf8_lossy(b[op.bi])));+                    output.push('\n');+                    new_seen += 1;+                }+            }+            position += 1;+        }+    }+}++fn contains_nul(data: &[u8]) -> bool {+    data.iter().take(8192).any(|byte| *byte == 0)+}++pub fn render_diff(+    store: &mut Store,+    old_tree: Option<Id>,+    new_tree: Option<Id>,+    announce: bool,+    path_filter: &[u8],+) -> crate::error::Result<usize> {+    let mut changes = graph::compare_trees(store, old_tree, new_tree)?;+    if !path_filter.is_empty() {+        changes.retain(|change| {+            change.path == path_filter+                || (change.path.len() > path_filter.len()+                    && change.path.starts_with(path_filter)+                    && change.path[path_filter.len()] == b'/')+        });+    }+    let mut output = String::new();+    for change in &changes {+        let path = String::from_utf8_lossy(&change.path);+        if change.new_kind == KIND_CONFLICT {+            output.push_str(&format!("Conflict: {path}\n"));+            continue;+        }+        let old_data = match (change.old_kind, change.old_id) {+            (KIND_MISSING, _) | (_, None) => Vec::new(),+            (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),+        };+        let new_data = match (change.new_kind, change.new_id) {+            (KIND_MISSING, _) | (_, None) => Vec::new(),+            (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),+        };+        if contains_nul(&old_data) || contains_nul(&new_data) {+            output.push_str(&format!("Binary files a/{path} and b/{path} differ\n"));+            continue;+        }+        output.push_str(&super::output::red("--- "));+        if change.old_kind == KIND_MISSING {+            output.push_str(&super::output::red("/dev/null"));+        } else {+            output.push_str(&super::output::red(&format!("a/{path}")));+        }+        output.push('\n');+        output.push_str(&super::output::green("+++ "));+        if change.new_kind == KIND_MISSING {+            output.push_str(&super::output::green("/dev/null"));+        } else {+            output.push_str(&super::output::green(&format!("b/{path}")));+        }+        output.push('\n');+        render_unified(+            &split_lines(&old_data),+            &split_lines(&new_data),+            &mut output,+        );+    }+    if announce && changes.is_empty() {+        super::output::info_prefix();+        output.push_str("no diff to show\n");+    }+    print!("{output}");+    Ok(changes.len())+}--- /dev/null+++ b/veins/src/cli/history.rs@@ -0,0 +1,1301 @@+use std::collections::{HashMap, HashSet};+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::commit::{self, Commit};+use crate::object::id::Id;+use crate::object::tree::{self, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn;+use crate::store::graph::{self, LogNode};+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::snapshot;++use super::{diff, output};++fn parse_count(text: &str) -> Option<usize> {+    if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {+        return None;+    }+    let value = text.parse::<usize>().ok()?;+    (value > 0).then_some(value)+}++struct LogRecord {+    id: Id,+    root_tree: Id,+    parents: Vec<Id>,+    change: String,+    seconds: i64,+    message: String,+    author: String,+    conflicted: bool,+    has_changes: bool,+}++pub fn log(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut titles = true;+    let mut all = false;+    let mut pager = false;+    let mut limit: Option<usize> = None;+    let mut first = false;+    let mut explicit_limit = false;+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && argument == "-no-col-titles" {+            titles = false;+        } else if !end_flags && argument == "-p" {+            pager = true;+        } else if !end_flags && (argument == "-a" || argument == "-all") {+            all = true;+        } else if !end_flags && (argument == "-l" || argument == "-f") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a count")));+            }+            limit = Some(+                parse_count(&arguments[index])+                    .ok_or_else(|| Error::new(format!("{argument} requires a positive count")))?,+            );+            first = argument == "-f";+            explicit_limit = true;+        } else if !end_flags+            && argument.len() > 2+            && argument.starts_with('-')+            && matches!(argument.as_bytes()[1], b'l' | b'f')+        {+            limit = Some(+                parse_count(&argument[2..])+                    .ok_or_else(|| Error::new(format!("invalid log count: {argument}")))?,+            );+            first = argument.as_bytes()[1] == b'f';+            explicit_limit = true;+        } else if !end_flags && argument.len() > 1 && matches!(argument.as_bytes()[0], b'l' | b'f')+        {+            if let Some(count) = parse_count(&argument[1..]) {+                limit = Some(count);+                first = argument.as_bytes()[0] == b'f';+                explicit_limit = true;+            } else {+                revision = argument.clone();+            }+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            revision = argument.clone();+        }+        index += 1;+    }+    if all || (pager && !explicit_limit) {+        limit = None;+    } else if limit.is_none() {+        limit = Some(+            core::user_config_value("log.default_amount")+                .and_then(|value| parse_count(&value))+                .unwrap_or(20),+        );+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let working_copy = ops::working_copy_id(&view);+    let start = if revision.is_empty() || revision == "all()" {+        graph::view_roots(&view)+    } else {+        graph::resolve_revision(&mut store, &view, &revision)?+            .map(|id| vec![id])+            .unwrap_or_default()+    };+    let mut seen: HashSet<Id> = start.iter().copied().collect();+    let mut stack = start;+    let mut records = Vec::new();+    while let Some(id) = stack.pop() {+        let Some(commit) = graph::load_commit(&mut store, id)? else {+            continue;+        };+        let message = first_line(&commit.message);+        let has_changes = if working_copy == Some(id) {+            graph::has_changes(&mut store, &commit)?+        } else {+            false+        };+        records.push(LogRecord {+            id,+            root_tree: commit.root_tree,+            parents: commit.parents.clone(),+            change: graph::base32_encode(commit.change_id),+            seconds: commit.committer.seconds,+            message,+            author: String::from_utf8_lossy(&commit.author.name).into_owned(),+            conflicted: false,+            has_changes,+        });+        for parent in commit.parents {+            if seen.insert(parent) {+                stack.push(parent);+            }+        }+    }+    let nodes: Vec<LogNode> = records+        .iter()+        .map(|record| LogNode {+            id: record.id,+            seconds: record.seconds,+            parents: record.parents.clone(),+        })+        .collect();+    let order = graph::order_log_nodes(&nodes);+    let mut ordered = Vec::with_capacity(records.len());+    let mut slots: Vec<Option<LogRecord>> = records.into_iter().map(Some).collect();+    for position in order {+        if let Some(record) = slots[position].take() {+            ordered.push(record);+        }+    }+    let mut records = ordered;+    if let Some(limit) = limit {+        if first {+            if records.len() > limit {+                records.drain(..records.len() - limit);+            }+            records.reverse();+        } else if records.len() > limit {+            records.truncate(limit);+        }+    }+    let mut conflict_cache = std::collections::HashMap::new();+    for record in &mut records {+        record.conflicted =+            graph::tree_conflicted_with(&mut store, record.root_tree, &mut conflict_cache)?;+    }++    let mut change_ids: Vec<String> = records.iter().map(|record| record.change.clone()).collect();+    let mut change_width = 6;+    let mut author_width = 6;+    let mut change_counts: HashMap<String, usize> = HashMap::new();+    for (position, record) in records.iter().enumerate() {+        let short = graph::short_change_id(&change_ids, position);+        change_width = change_width.max(short.len());+        author_width = author_width.max(record.author.len());+        *change_counts.entry(record.change.clone()).or_insert(0) += 1;+    }+    for position in 0..change_ids.len() {+        change_ids[position] = graph::short_change_id(&change_ids, position);+    }++    let color = output::enabled();+    let mut rendered = String::new();+    if titles {+        rendered.push_str(&cell("", 1, &[], color));+        rendered.push(' ');+        rendered.push_str(&cell("Commit", 12, &[], color));+        rendered.push_str("  ");+        rendered.push_str(&cell("Change", change_width, &[], color));+        rendered.push_str("  ");+        rendered.push_str(&cell("Date", 19, &[], color));+        rendered.push_str("  ");+        rendered.push_str(&cell("Author", author_width, &[], color));+        rendered.push_str("  Message\n");+    }+    for (position, record) in records.iter().enumerate() {+        let is_working = working_copy == Some(record.id);+        let marker = if is_working { "@" } else { " " };+        let marker_codes: &[&str] = if is_working {+            if record.has_changes { &["96"] } else { &["31"] }+        } else {+            &[]+        };+        rendered.push_str(&cell(marker, 1, marker_codes, color));+        rendered.push(' ');+        rendered.push_str(&cell(&record.id.short(), 12, &["31"], color));+        rendered.push_str("  ");+        rendered.push_str(&cell(&change_ids[position], change_width, &["31"], color));+        rendered.push_str("  ");+        rendered.push_str(&cell(+            &crate::time::format_utc(record.seconds),+            19,+            &["2", "36"],+            color,+        ));+        rendered.push_str("  ");+        rendered.push_str(&cell(&record.author, author_width, &["36"], color));+        rendered.push_str("  ");+        if record.message.is_empty() {+            rendered.push_str(&paint("<unset>", &["90"], color));+        } else {+            rendered.push_str(&paint(&record.message, &["32"], color));+        }+        for name in ops::bookmark_names(&view, record.id) {+            rendered.push_str(&format!(" [{}]", String::from_utf8_lossy(&name)));+        }+        for name in ops::tag_names(&view, record.id) {+            rendered.push_str(&format!(" <{}>", String::from_utf8_lossy(&name)));+        }+        if record.conflicted {+            rendered.push_str(" (conflicted)");+        }+        if change_counts.get(&record.change).copied().unwrap_or(0) > 1 {+            rendered.push_str(" (divergent)");+        }+        rendered.push('\n');+    }+    output::pager_output(&root, &rendered, pager);+    Ok(0)+}++fn paint(text: &str, codes: &[&str], color: bool) -> String {+    if !color || codes.is_empty() {+        return text.to_string();+    }+    let mut out = String::new();+    for code in codes {+        out.push_str("\x1b[");+        out.push_str(code);+        out.push('m');+    }+    out.push_str(text);+    out.push_str("\x1b[0m");+    out+}++/// Colours a cell and pads it to `width` using visible (uncoloured) length.+fn cell(text: &str, width: usize, codes: &[&str], color: bool) -> String {+    let mut out = paint(text, codes, color);+    for _ in text.chars().count()..width {+        out.push(' ');+    }+    out+}++fn first_line(message: &[u8]) -> String {+    let position = message.iter().position(|byte| *byte == b'\n');+    String::from_utf8_lossy(match position {+        Some(position) => &message[..position],+        None => message,+    })+    .into_owned()+}++pub fn show(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut titles = true;+    let mut all = false;+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && (argument == "-a" || argument == "-all") {+            all = true;+        } else if !end_flags && argument == "-no-col-titles" {+            titles = false;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            revision = argument.clone();+        }+        index += 1;+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {+        Error::new(if revision.is_empty() {+            "no working-copy commit"+        } else {+            "unknown revision"+        })+    })?;+    let commit =+        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;+    let mut rendered = String::new();+    if titles {+        rendered.push_str(&format!("commit   {}\n", target.to_hex()));+        rendered.push_str(&format!(+            "change   {}\n",+            graph::base32_encode(commit.change_id)+        ));+        rendered.push_str(&format!(+            "author   {} <{}>\n",+            String::from_utf8_lossy(&commit.author.name),+            String::from_utf8_lossy(&commit.author.email)+        ));+        rendered.push_str(&format!(+            "date     {}\n",+            crate::time::format_utc(commit.committer.seconds)+        ));+        rendered.push_str("parents  ");+        if commit.parents.is_empty() {+            rendered.push_str("<none>");+        } else {+            for (position, parent) in commit.parents.iter().enumerate() {+                if position > 0 {+                    rendered.push(' ');+                }+                rendered.push_str(&parent.short());+            }+        }+        rendered.push('\n');+        let names = ops::bookmark_names(&view, target);+        if !names.is_empty() {+            rendered.push_str("bookmarks");+            for name in names {+                rendered.push_str(&format!(" [{}]", String::from_utf8_lossy(&name)));+            }+            rendered.push('\n');+        }+        rendered.push('\n');+        if commit.message.is_empty() {+            rendered.push_str("<unset>\n");+        } else {+            rendered.push_str(&String::from_utf8_lossy(&commit.message));+            rendered.push('\n');+        }+        rendered.push('\n');+    }+    let old_tree = match commit.parents.first() {+        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),+        None => None,+    };+    let difference = {+        let mut buffer = Vec::new();+        let mut collector = Collector::new(&mut buffer);+        collector.render(&mut store, old_tree, Some(commit.root_tree), false, b"")?;+        String::from_utf8_lossy(&buffer).into_owned()+    };+    rendered.push_str(&difference);+    let diff_count = !difference.is_empty();+    output::pager_output(&root, &rendered, diff_count && !all);+    Ok(0)+}++struct Collector<'a> {+    output: &'a mut Vec<u8>,+}++impl<'a> Collector<'a> {+    fn new(output: &'a mut Vec<u8>) -> Self {+        Self { output }+    }++    fn render(+        &mut self,+        store: &mut Store,+        old_tree: Option<Id>,+        new_tree: Option<Id>,+        announce: bool,+        filter: &[u8],+    ) -> Result<usize> {+        let mut changes = graph::compare_trees(store, old_tree, new_tree)?;+        if !filter.is_empty() {+            changes.retain(|change| {+                change.path == filter+                    || (change.path.len() > filter.len()+                        && change.path.starts_with(filter)+                        && change.path[filter.len()] == b'/')+            });+        }+        for change in &changes {+            let path = String::from_utf8_lossy(&change.path);+            if change.new_kind == KIND_CONFLICT {+                self.output+                    .extend_from_slice(format!("Conflict: {path}\n").as_bytes());+                continue;+            }+            let old_data = match (change.old_kind, change.old_id) {+                (KIND_MISSING, _) | (_, None) => Vec::new(),+                (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),+            };+            let new_data = match (change.new_kind, change.new_id) {+                (KIND_MISSING, _) | (_, None) => Vec::new(),+                (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),+            };+            if old_data.iter().take(8192).any(|byte| *byte == 0)+                || new_data.iter().take(8192).any(|byte| *byte == 0)+            {+                self.output.extend_from_slice(+                    format!("Binary files a/{path} and b/{path} differ\n").as_bytes(),+                );+                continue;+            }+            self.output.extend_from_slice(b"--- ");+            if change.old_kind == KIND_MISSING {+                self.output.extend_from_slice(b"/dev/null");+            } else {+                self.output+                    .extend_from_slice(format!("a/{path}").as_bytes());+            }+            self.output.extend_from_slice(b"\n+++ ");+            if change.new_kind == KIND_MISSING {+                self.output.extend_from_slice(b"/dev/null");+            } else {+                self.output+                    .extend_from_slice(format!("b/{path}").as_bytes());+            }+            self.output.extend_from_slice(b"\n");+            let a = diff::split_lines(&old_data);+            let b = diff::split_lines(&new_data);+            let mut rendered = String::new();+            diff::render_unified_for(&a, &b, &mut rendered);+            self.output.extend_from_slice(rendered.as_bytes());+        }+        if announce && changes.is_empty() {+            self.output.extend_from_slice(b"info: no diff to show\n");+        }+        Ok(changes.len())+    }+}++pub fn hash(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut short = false;+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && argument == "-short" {+            short = true;+        } else if !end_flags && argument == "-long" {+            short = false;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            revision = argument.clone();+        }+        index += 1;+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {+        Error::new(if revision.is_empty() {+            "no working-copy commit"+        } else {+            "unknown revision"+        })+    })?;+    let hex = target.to_hex();+    println!("{}", if short { &hex[..12] } else { &hex });+    Ok(0)+}++fn print_tree(+    store: &mut Store,+    tree_id: Id,+    prefix: &str,+    depth: usize,+    output: &mut String,+) -> Result<bool> {+    if depth > crate::object::MAX_TREE_DEPTH {+        return Ok(false);+    }+    let Some(body) = store.body(tree_id, TYPE_TREE)? else {+        return Ok(false);+    };+    let Ok(tree) = tree::decode(&body) else {+        return Ok(false);+    };+    for (index, entry) in tree.entries.iter().enumerate() {+        let last = index + 1 == tree.entries.len();+        output.push_str(prefix);+        output.push_str(if last { "`-- " } else { "|-- " });+        output.push_str(&String::from_utf8_lossy(&entry.name));+        output.push('\n');+        if entry.kind == KIND_SUBTREE {+            let next = format!("{prefix}{}", if last { "    " } else { "|   " });+            if !print_tree(store, entry.target, &next, depth + 1, output)? {+                return Ok(false);+            }+        }+    }+    Ok(true)+}++pub fn list(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut plain = false;+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-plain" || argument == "-p") {+            plain = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            revision = argument.clone();+        }+        index += 1;+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {+        Error::new(if revision.is_empty() {+            "no working-copy commit"+        } else {+            "unknown revision"+        })+    })?;+    let commit =+        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;+    if plain {+        for entry in tree::flatten(&mut store, commit.root_tree)? {+            println!("{}", String::from_utf8_lossy(&entry.path));+        }+    } else {+        let mut rendered = String::from(".\n");+        if !print_tree(&mut store, commit.root_tree, "", 0, &mut rendered)? {+            return Err(Error::new("cannot read tree"));+        }+        print!("{rendered}");+    }+    Ok(0)+}++fn existing_directory(text: &str) -> bool {+    if text.is_empty() || text.contains('\0') {+        return false;+    }+    let path = Path::new(text);+    let path = if path.is_absolute() {+        path.to_path_buf()+    } else {+        std::env::current_dir().unwrap_or_default().join(path)+    };+    path.is_dir()+}++fn view_ref_named(view: &crate::object::view::View, name: &str) -> bool {+    ops::find_bookmark(view, name.as_bytes()).is_some()+        || ops::find_tag(view, name.as_bytes()).is_some()+        || view.remote_refs.iter().any(|reference| {+            let mut joined = reference.remote.clone();+            joined.push(b'/');+            joined.extend_from_slice(&reference.name);+            joined == name.as_bytes()+        })+}++pub fn diff(arguments: &[String]) -> Result<u8> {+    let mut flag_revisions = Vec::new();+    let mut operands = Vec::new();+    let mut all = false;+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-a" || argument == "-all") {+            all = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            flag_revisions.push(arguments[index].clone());+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            operands.push(argument.clone());+        }+        index += 1;+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let mut view = ops::current_view(&root, &mut store)?;+    let mut revisions = flag_revisions;+    let mut path_filter: Option<String> = None;+    if !operands.is_empty() {+        if !revisions.is_empty() {+            if operands.len() > 1 {+                return Err(Error::new("too many arguments"));+            }+            path_filter = Some(operands[0].clone());+        } else if operands.len() >= 2 {+            if operands.len() > 2 {+                return Err(Error::new("too many revisions"));+            }+            revisions.push(operands[0].clone());+            revisions.push(operands[1].clone());+        } else if existing_directory(&operands[0])+            && view+                .as_ref()+                .is_none_or(|view| !view_ref_named(view, &operands[0]))+        {+            path_filter = Some(operands[0].clone());+        } else if view.as_ref().is_some_and(|view| {+            graph::resolve_revision(&mut store, view, &operands[0])+                .ok()+                .flatten()+                .is_some()+        }) {+            revisions.push(operands[0].clone());+        } else {+            path_filter = Some(operands[0].clone());+        }+    }+    if revisions.len() > 2 {+        return Err(Error::new("too many revisions"));+    }+    if let Some(path) = path_filter.clone() {+        let cwd = crate::worktree::pathspec::cwd_relative(&root)+            .ok_or_else(|| Error::new("cannot determine current directory"))?;+        let normalized = crate::worktree::pathspec::pathspec_normalize(&root, &cwd, &path);+        if normalized.as_ref().is_none_or(|value| value.is_empty()) {+            return Err(Error::new(format!(+                "path is outside the repository: {path}"+            )));+        }+        path_filter = normalized;+    }++    let mut needs_snapshot = revisions.is_empty();+    let mut pre_resolved: Option<Vec<Id>> = None;+    if !needs_snapshot {+        if let Some(current) = &view {+            let working = ops::working_copy_id(current);+            let mut resolved = Vec::new();+            for revision in &revisions {+                if revision.is_empty() || revision == "@" {+                    needs_snapshot = true;+                    break;+                }+                let id = graph::resolve_revision(&mut store, current, revision)?;+                match id {+                    Some(id) if working != Some(id) => resolved.push(id),+                    _ => {+                        needs_snapshot = true;+                        break;+                    }+                }+            }+            if !needs_snapshot {+                pre_resolved = Some(resolved);+            }+        } else {+            needs_snapshot = true;+        }+    }+    if needs_snapshot {+        snapshot::run_with(&root, &mut store)?;+        view = ops::current_view(&root, &mut store)?;+        pre_resolved = None;+    }+    let view = view.ok_or_else(|| Error::new("no operation state"))?;+    let tree_of = |store: &mut Store, id: Id| -> Result<Option<Id>> {+        Ok(graph::load_commit(store, id)?.map(|commit| commit.root_tree))+    };+    let parent_tree_of = |store: &mut Store, id: Id| -> Result<Option<Id>> {+        let Some(commit) = graph::load_commit(store, id)? else {+            return Ok(None);+        };+        let Some(parent) = commit.parents.first() else {+            return Ok(None);+        };+        Ok(graph::load_commit(store, *parent)?.map(|parent| parent.root_tree))+    };+    let resolve_for = |store: &mut Store, index: usize| -> Result<Option<Id>> {+        if let Some(resolved) = &pre_resolved {+            if index < resolved.len() {+                return Ok(Some(resolved[index]));+            }+        }+        graph::resolve_revision(store, &view, &revisions[index])+    };+    let (old_tree, new_tree) = match revisions.len() {+        2 => {+            let Some(a) = resolve_for(&mut store, 0)? else {+                return Err(Error::new("unknown revision"));+            };+            let Some(b) = resolve_for(&mut store, 1)? else {+                return Err(Error::new("unknown revision"));+            };+            (tree_of(&mut store, a)?, tree_of(&mut store, b)?)+        }+        1 => {+            let Some(a) = resolve_for(&mut store, 0)? else {+                return Err(Error::new("unknown revision"));+            };+            (parent_tree_of(&mut store, a)?, tree_of(&mut store, a)?)+        }+        _ => match ops::working_copy_id(&view) {+            Some(working) => (+                parent_tree_of(&mut store, working)?,+                tree_of(&mut store, working)?,+            ),+            None => (None, None),+        },+    };+    let filter = path_filter+        .as_ref()+        .map(|value| value.as_bytes())+        .unwrap_or(b"");+    let mut buffer = Vec::new();+    let count = Collector::new(&mut buffer).render(&mut store, old_tree, new_tree, true, filter)?;+    let rendered = String::from_utf8_lossy(&buffer).into_owned();+    output::pager_output(&root, &rendered, count > 0 && !all);+    Ok(0)+}++pub fn new_change(arguments: &[String]) -> Result<u8> {+    let mut revisions = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            revisions.push(argument.clone());+        }+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let working_copy = ops::working_copy_id(txn.view());+    let (parents, root_tree, old_root) = if revisions.is_empty() {+        let working_copy = working_copy.ok_or_else(|| Error::new("no working-copy commit"))?;+        let loaded = graph::load_commit(&mut store, working_copy)?+            .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+        (vec![working_copy], loaded.root_tree, Some(loaded.root_tree))+    } else {+        let mut parents = Vec::new();+        let mut root_tree = None;+        for revision in &revisions {+            let resolved = graph::resolve_revision(&mut store, txn.view(), revision)?+                .ok_or_else(|| Error::new("unknown revision"))?;+            parents.push(resolved);+            if root_tree.is_none() {+                root_tree =+                    graph::load_commit(&mut store, resolved)?.map(|commit| commit.root_tree);+            }+        }+        let old_root = match working_copy {+            Some(id) => graph::load_commit(&mut store, id)?.map(|commit| commit.root_tree),+            None => None,+        };+        (+            parents,+            root_tree.ok_or_else(|| Error::new("unknown revision"))?,+            old_root,+        )+    };+    let signature = identity::signature(&root);+    let commit = Commit {+        version: 1,+        parents,+        root_tree,+        change_id: identity::random_change_id(),+        author: signature.clone(),+        committer: signature,+        message: Vec::new(),+        renames_state: commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    let new_id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));+    if let Some(working_copy) = working_copy {+        ops::remove_head(txn.view_mut(), working_copy);+    }+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    txn.finish("new")?;+    store.refresh()?;+    mark_native(&root, new_id);+    if !revisions.is_empty() {+        crate::worktree::checkout::materialize(&root, &mut store, old_root, root_tree)?;+    }+    Ok(0)+}++fn mark_native(root: &Path, id: Id) {+    let path = layout::git_map_dir(root).join("native");+    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());+}++fn describe_impl(+    root: &Path,+    store: &mut Store,+    message: &str,+    require_changes: bool,+    start_new: bool,+) -> Result<u8> {+    snapshot::run_with(root, store)?;+    let mut txn = Txn::begin(root, store)?;+    let working_copy =+        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+    let loaded = graph::load_commit(store, working_copy)?+        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+    let changed = graph::has_changes(store, &loaded)?;+    let same = loaded.message == message.as_bytes();+    if !changed && (require_changes || same) {+        if require_changes {+            output::info_prefix();+            println!("nothing to commit, working copy clean");+            return Ok(2);+        }+        return Ok(0);+    }+    let signature = identity::signature(root);+    let mut updated = loaded;+    updated.committer = signature.clone();+    if !changed {+        updated.author = signature.clone();+    }+    updated.message = message.as_bytes().to_vec();+    let encoded = commit::encode(&updated);+    let new_id = txn.add_object(TYPE_COMMIT, encoded);+    ops::remove_head(txn.view_mut(), working_copy);+    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);+    if let Some(current) = core::current_bookmark_name(root)+        && ops::find_bookmark(txn.view(), current.as_bytes()).is_some()+    {+        ops::set_bookmark_target(txn.view_mut(), current.as_bytes(), new_id);+    }+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    if start_new {+        let view = txn.view().clone();+        let next = Commit {+            version: 1,+            parents: vec![new_id],+            root_tree: updated.root_tree,+            change_id: identity::random_change_id(),+            author: signature.clone(),+            committer: signature,+            message: Vec::new(),+            renames_state: commit::RENAMES_RECORDED,+            renames: Vec::new(),+            extra: Vec::new(),+        };+        let next_id = txn.add_object(TYPE_COMMIT, commit::encode(&next));+        ops::remove_head(txn.view_mut(), new_id);+        ops::set_workspace(txn.view_mut(), next_id);+        ops::rebuild_heads(txn.view_mut());+        let next_view = txn.view().clone();+        txn.finish_chain(vec![+            (view, "describe".to_string()),+            (next_view, "new".to_string()),+        ])?;+        store.refresh()?;+        mark_native(root, new_id);+        mark_native(root, next_id);+        return Ok(0);+    }+    txn.finish("describe")?;+    store.refresh()?;+    mark_native(root, new_id);+    Ok(0)+}++pub fn describe(arguments: &[String]) -> Result<u8> {+    let parts = super::args::parse_message(arguments, 0)?;+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    describe_impl(&root, &mut store, &output::join_args(&parts), false, false)+}++pub fn commit(arguments: &[String]) -> Result<u8> {+    let mut parts = super::args::parse_message(arguments, 0)?;+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    if output::message_is_blank(&parts) && core::stdin_is_terminal() {+        if let Some(edited) = edit_message(&root, &output::join_args(&parts))? {+            if edited.is_empty() {+                return Err(Error::new("commit requires a non-empty message (-message)"));+            }+            parts = vec![edited];+        }+    }+    if output::message_is_blank(&parts) {+        return Err(Error::new("commit requires a non-empty message (-message)"));+    }+    let mut store = Store::open(&root)?;+    let status = describe_impl(&root, &mut store, &output::join_args(&parts), true, true)?;+    if status == 2 { Ok(0) } else { Ok(status) }+}++fn edit_message(root: &Path, initial: &str) -> Result<Option<String>> {+    let file = layout::tmp_dir(root).join("commit-message.txt");+    let mut body = initial.to_string();+    if !body.is_empty() && !body.ends_with('\n') {+        body.push('\n');+    }+    body.push_str("\n# Enter a commit message. Lines starting with '#' are ignored.\n");+    if !core::write_file(&file, body.as_bytes()) {+        return Err(Error::new("cannot write message file"));+    }+    if !core::run_editor(root, &[], Some(&file)) {+        let _ = core::remove_file(&file);+        return Err(Error::new("editor exited with an error"));+    }+    let data = core::read_file_opt(&file, 0);+    let _ = core::remove_file(&file);+    let Some(data) = data else {+        return Ok(None);+    };+    let text = String::from_utf8_lossy(&data);+    let mut lines = Vec::new();+    for raw in text.lines() {+        let trimmed = raw.trim_start_matches([' ', '\t', '\r']);+        if trimmed.starts_with('#') || trimmed.is_empty() && raw.trim().is_empty() {+            lines.push(String::new());+        } else {+            lines.push(raw.trim_start_matches([' ', '\t', '\r']).to_string());+        }+    }+    while lines.last().is_some_and(|line| line.is_empty()) {+        lines.pop();+    }+    while lines.first().is_some_and(|line| line.is_empty()) {+        lines.remove(0);+    }+    Ok(Some(lines.join("\n")))+}++pub fn amend(arguments: &[String]) -> Result<u8> {+    let mut revision = String::new();+    let mut parts = Vec::new();+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-m" || argument == "-message") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a message")));+            }+            parts.push(arguments[index].clone());+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if revision.is_empty() {+            revision = argument.clone();+        } else {+            parts.push(argument.clone());+        }+        index += 1;+    }+    if revision.is_empty() {+        return Err(Error::new("amend requires a revision"));+    }+    if output::message_is_blank(&parts) {+        return Err(Error::new("amend requires a non-empty message (-message)"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?+        .ok_or_else(|| Error::new("unknown revision"))?;+    let mut pushed_roots = Vec::new();+    for reference in &txn.view().remote_refs {+        pushed_roots.push(reference.target);+    }+    if !pushed_roots.is_empty()+        && graph::collect_commits(&mut store, &pushed_roots)?.contains(&target)+    {+        return Err(Error::new("cannot amend a revision that has been pushed"));+    }+    let target_loaded = graph::load_commit(&mut store, target)?+        .ok_or_else(|| Error::new("cannot read revision"))?;+    let message = output::join_args(&parts);+    if target_loaded.message == message.as_bytes() {+        output::info_prefix();+        println!("message unchanged");+        return Ok(0);+    }+    let mut remaining = graph::all_commits(&mut store, txn.view())?;+    let mut old_ids = Vec::new();+    let mut new_ids = Vec::new();+    let signature = identity::signature(&root);+    let mut rewritten = false;+    let mut failed = false;+    while !remaining.is_empty() && !failed {+        let ready = remaining.iter().position(|id| {+            if *id == target {+                return true;+            }+            graph::load_commit(&mut store, *id)+                .ok()+                .flatten()+                .is_some_and(|commit| commit.parents.iter().any(|parent| old_ids.contains(parent)))+        });+        let Some(position) = ready else {+            break;+        };+        let chosen = remaining.remove(position);+        let Some(loaded) = graph::load_commit(&mut store, chosen)? else {+            failed = true;+            break;+        };+        let new_parents: Vec<Id> = loaded+            .parents+            .iter()+            .map(|parent| {+                old_ids+                    .iter()+                    .position(|value| value == parent)+                    .map(|index| new_ids[index])+                    .unwrap_or(*parent)+            })+            .collect();+        let mut commit = loaded;+        commit.parents = new_parents;+        commit.committer = signature.clone();+        if chosen == target {+            commit.message = message.as_bytes().to_vec();+        }+        let new_id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));+        old_ids.push(chosen);+        new_ids.push(new_id);+        if chosen == target {+            rewritten = true;+        }+    }+    if failed || !rewritten {+        return Err(Error::new("cannot amend revision"));+    }+    for bookmark in &mut txn.view_mut().bookmarks {+        remap(&old_ids, &new_ids, &mut bookmark.targets.adds);+        remap(&old_ids, &new_ids, &mut bookmark.targets.removes);+    }+    for tag in &mut txn.view_mut().tags {+        if let Some(mapped) = mapped(&old_ids, &new_ids, tag.target) {+            tag.target = mapped;+        }+    }+    for workspace in &mut txn.view_mut().working_copies {+        if let Some(mapped) = mapped(&old_ids, &new_ids, workspace.target) {+            workspace.target = mapped;+        }+    }+    for reference in &mut txn.view_mut().remote_refs {+        if let Some(mapped) = mapped(&old_ids, &new_ids, reference.target) {+            reference.target = mapped;+        }+    }+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("amend {revision}"))?;+    for id in new_ids {+        mark_native(&root, id);+    }+    Ok(0)+}++fn mapped(old: &[Id], new: &[Id], id: Id) -> Option<Id> {+    old.iter()+        .position(|value| *value == id)+        .map(|index| new[index])+}++fn remap(old: &[Id], new: &[Id], ids: &mut [Option<Id>]) {+    for value in ids {+        if let Some(id) = *value+            && let Some(mapped) = mapped(old, new, id)+        {+            *value = Some(mapped);+        }+    }+}++pub fn op(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        return Err(Error::new(+            "expected an op subcommand (log, restore, revert)",+        ));+    };+    match sub.as_str() {+        "log" => op_log(),+        "restore" => op_restore(arguments.get(1)),+        "revert" => op_revert(arguments.get(1)),+        _ => Err(Error::new(format!("unknown op subcommand: {sub}"))),+    }+}++struct OperationRecord {+    id: Id,+    operation: crate::object::view::Operation,+}++fn collect_operations(store: &mut Store, heads: &[Id]) -> Vec<OperationRecord> {+    let mut output = Vec::new();+    let mut seen = Vec::new();+    let mut stack: Vec<Id> = heads.iter().rev().copied().collect();+    while let Some(id) = stack.pop() {+        if seen.contains(&id) {+            continue;+        }+        seen.push(id);+        let Ok(Some(operation)) = store.operation(id) else {+            continue;+        };+        for parent in &operation.parents {+            if !seen.contains(parent) {+                stack.push(*parent);+            }+        }+        output.push(OperationRecord { id, operation });+    }+    output+}++fn op_log() -> Result<u8> {+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let heads = ops::read_heads(&root)?;+    let mut records = collect_operations(&mut store, &heads);+    records.sort_by(|left, right| right.operation.end.millis.cmp(&left.operation.end.millis));+    for record in records {+        let marker = if heads.contains(&record.id) { "@" } else { " " };+        println!(+            "{} {} {} {}",+            marker,+            record.id.short(),+            crate::time::format_utc(record.operation.end.millis / 1000),+            String::from_utf8_lossy(&record.operation.description)+        );+    }+    Ok(0)+}++fn resolve_operation(records: &[OperationRecord], text: &str) -> Option<usize> {+    let mut found = None;+    let mut count = 0;+    for (index, record) in records.iter().enumerate() {+        if record.id.to_hex().starts_with(text) {+            found = Some(index);+            count += 1;+        }+    }+    if count == 1 { found } else { None }+}++fn write_view(+    root: &Path,+    store: &mut Store,+    next: crate::object::view::View,+    description: &str,+) -> Result<u8> {+    let mut txn = Txn::begin(root, store)?;+    let old_tree = working_tree(store, txn.view())?;+    let new_tree = working_tree(store, &next)?;+    *txn.view_mut() = next;+    txn.finish(description)?;+    crate::worktree::checkout::materialize_optional(root, store, old_tree, new_tree)?;+    Ok(0)+}++fn working_tree(store: &mut Store, view: &crate::object::view::View) -> Result<Option<Id>> {+    let Some(working) = ops::working_copy_id(view) else {+        return Ok(None);+    };+    Ok(graph::load_commit(store, working)?.map(|commit| commit.root_tree))+}++fn op_restore(id: Option<&String>) -> Result<u8> {+    let id = id.ok_or_else(|| Error::new("op restore requires an operation id"))?;+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let heads = ops::read_heads(&root)?;+    let records = collect_operations(&mut store, &heads);+    let target = resolve_operation(&records, id).ok_or_else(|| Error::new("unknown operation"))?;+    let view = store+        .view(records[target].operation.view)?+        .ok_or_else(|| Error::new("cannot read operation view"))?;+    write_view(&root, &mut store, view, "op restore")+}++fn op_revert(id: Option<&String>) -> Result<u8> {+    let id = id.ok_or_else(|| Error::new("op revert requires an operation id"))?;+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let heads = ops::read_heads(&root)?;+    let records = collect_operations(&mut store, &heads);+    let target = resolve_operation(&records, id).ok_or_else(|| Error::new("unknown operation"))?;+    let operation = &records[target].operation;+    let mut view = crate::object::view::View::default();+    if let Some(parent) = operation.parents.first()+        && let Some(parent) = store.operation(*parent)?+        && let Some(parent_view) = store.view(parent.view)?+    {+        view = parent_view;+    }+    write_view(&root, &mut store, view, "op revert")+}++pub fn undo() -> Result<u8> {+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let heads = ops::read_heads(&root)?;+    if heads.is_empty() {+        return Err(Error::new("no operations to undo"));+    }+    let mut records = collect_operations(&mut store, &heads);+    records.sort_by(|left, right| right.operation.end.millis.cmp(&left.operation.end.millis));+    let Some(latest) = records.first() else {+        return Err(Error::new("cannot resolve undo target"));+    };+    let mut view = crate::object::view::View::default();+    if let Some(parent) = latest.operation.parents.first() {+        let parent = store+            .operation(*parent)?+            .ok_or_else(|| Error::new("cannot resolve undo target"))?;+        view = store+            .view(parent.view)?+            .ok_or_else(|| Error::new("cannot resolve undo target"))?;+    }+    write_view(&root, &mut store, view, "undo")+}--- /dev/null+++ b/veins/src/cli/info.rs@@ -0,0 +1,837 @@+use std::collections::HashMap;+use std::path::Path;++use rayon::prelude::*;++use crate::core;+use crate::error::{Error, Result};+use crate::object::tree::{self, KIND_CONFLICT, KIND_SUBTREE};+use crate::object::{TYPE_BLOB, TYPE_COMMIT, TYPE_CONFLICT, TYPE_OPERATION, TYPE_TREE, TYPE_VIEW};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::attributes::{AttributeRules, AttributeText};++use super::output;++pub fn version() -> Result<u8> {+    println!("veins v{} (store v1)", env!("CARGO_PKG_VERSION"));+    Ok(0)+}++pub fn help(arguments: &[String]) -> Result<u8> {+    let Some(command) = arguments.first() else {+        super::usage();+        return Ok(0);+    };+    let text = match command.as_str() {+        "log" => {+            "usage: vn log [-a] [-rev <revset>] [-lN | -fN] [-no-col-titles] [-p]\n\+             \nshow commit history, newest first\n\+             \noptions:\n  -a, -all                  show the entire history\n  -rev <revset>             show only the given revision set\n  -lN, -l <N>               show the last N commits (newest N)\n  -fN, -f <N>               show the first N commits (oldest N)\n  -no-col-titles            omit column titles\n  -p                        page the full history through the pager\n"+        }+        "show" => {+            "usage: vn show [-a] [rev] [-no-col-titles]\n\+             \nshow a commit's metadata and its diff against its first parent\n\+             \noptions:\n  -a, -all                  print the whole output at once\n  -no-col-titles            omit the metadata labels\n"+        }+        "diff" => {+            "usage: vn diff [-a] [-rev <rev>] [<rev> <rev>] [<path>]\n\+             \nshow a unified diff, paged when stdout is a terminal\n\+             \noptions:\n  -a, -all                  print the whole diff at once\n  -rev <rev>                compare a revision with its parent\n"+        }+        "go" | "commit" => {+            "usage: vn go -m <message>\n\+             \nrecord the working copy and start a new change\n\+             \naliases: commit\n"+        }+        "attr" => {+            "usage: vn attr <gen|txt|bin|lf|crlf|cr|rm|ls> ...\n\+             \nadd or remove .vnattribs rules\n\+             \nsubcommands:\n  vn attr gen <glob>...\n  vn attr rm gen <glob>...\n  vn attr ls\n"+        }+        "stat" | "status" => "usage: vn stat\n\nshow working-copy changes\n",+        "ls" => "usage: vn ls [rev] [-plain]\n\nlist tracked files\n",+        "hash" => "usage: vn hash [rev] [-short|-long]\n\nprint the commit hash for a revision\n",+        "new" => "usage: vn new [rev...]\n\nstart a new change\n",+        "co" | "checkout" => "usage: vn co [rev]\n\nwrite a revision into the working directory\n",+        "merge" => "usage: vn merge <rev>...\n\ncreate a merge commit; never fails\n",+        "rebase" => "usage: vn rebase -s <rev> [-d <rev>]\n\nrewrite changes onto a new parent\n",+        "xs" => "usage: vn xs [-porcelain]\n\nlist conflicted paths\n",+        "resolve" => "usage: vn resolve [-take ours|theirs] <path>\n\nresolve a conflicted path\n",+        "cfg" => "usage: vn cfg [<key>] [<value>]\n\nread and write configuration\n",+        "rm" => "usage: vn rm [-delete] <path>...\n\nuntrack paths\n",+        "mv" => "usage: vn mv <source> <destination>\n\nmove a tracked file\n",+        "ex" => "usage: vn ex <pattern>...\n\nadd exclude rules\n",+        "edit" => "usage: vn edit [path]...\n\nopen paths in the configured editor\n",+        "bmk" => {+            "usage: vn bmk <set|rename|ls|rm> ...\n\nmanage named branch pointers\n\+             \nsubcommands:\n  set <name> [-rev <rev>]   create or move a bookmark\n  rename <old> <new>        rename a bookmark\n  ls                        list bookmarks\n  rm <name>                 delete a bookmark\n"+        }+        "tag" => "usage: vn tag <set|ls|rm|latest> ...\n\nmanage named tags\n",+        "op" => "usage: vn op <log|restore|revert> ...\n\noperation log commands\n",+        "undo" => "usage: vn undo\n\nrestore the previous operation view\n",+        "fsck" => "usage: vn fsck [path] [-verbose]\n\nverify repository integrity\n",+        "inf" => "usage: vn inf [-inc-gen]\n\nshow a repository breakdown\n",+        "self-test" => "usage: vn self-test\n\nrun the format self-tests\n",+        "version" => "usage: vn version\n\nprint version information\n",+        "git" => {+            "usage: vn git <import|materialize|export|fetch|push|mirror|remote> ...\n\nimport from or export to git\n"+        }+        "remote" => "usage: vn remote <add|set-url|list|remove> ...\n\nmanage native remotes\n",+        "clone" => {+            "usage: vn clone <url> [-blobs:head|none|all] [-key:<name>] [-pin:<sha256>] [path]\n\nclone a repository\n"+        }+        "fetch" => "usage: vn fetch [<remote>] [path]\n\nfetch from a native remote\n",+        "pull" => {+            "usage: vn pull [<remote>] [path]\n\nfetch and fast-forward the current bookmark\n"+        }+        "push" | "psh" => {+            "usage: vn push [<remote>] [<bookmark>] [path]\n\npush a bookmark to a native remote\n"+        }+        "serve" => {+            "usage: vn serve -stdio <repo> [-quota <bytes>]\n\+             \x20      vn serve -listen <addr:port> -root <dir> -tls-cert <cert> -tls-key <key> [-quota <bytes>]\n\+             \nrun the native server over standard input/output or TLS 1.3\n"+        }+        "key" => "usage: vn key <generate|show|list> ...\n\nmanage local Ed25519 keys\n",+        "auth" => {+            "usage: vn auth <use|list|remove> ...\n\nremember keys for hosts and set a default\n"+        }+        "access" => {+            "usage: vn access <add|remove|anonymous|list> ...\n\nmanage a served repository's access file\n"+        }+        "whoami" => "usage: vn whoami [<remote>]\n\nreport the role granted by a server\n",+        "repack" | "gc" => "usage: vn repack [path] [-level:N] [-verbose]\n\nrewrite packs\n",+        other => {+            return Err(Error::new(format!("unknown command: {other}")));+        }+    };+    print!("{text}");+    Ok(0)+}++pub fn fsck(arguments: &[String]) -> Result<u8> {+    let mut path = ".".to_string();+    let mut verbose = false;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && matches!(argument.as_str(), "-v" | "-verbose") {+            verbose = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            path = argument.clone();+        }+    }+    let root = layout::discover(Path::new(&path))+        .map_err(|_| Error::new(format!("not a veins repository: {path}")))?;+    fsck_repository(&root, verbose)+}++fn fsck_repository(root: &Path, verbose: bool) -> Result<u8> {+    let mut errors = 0usize;+    let mut warnings = 0usize;+    let format = core::read_file_opt(&layout::format_path(root), 0);+    match format {+        Some(data) if data == b"veins-store 1" || data == b"veins-store 1\n" => {}+        _ => {+            output::error_prefix();+            println!("fsck: {}: invalid .veins/format", root.display());+            errors += 1;+        }+    }+    let promisor = core::read_file_opt(&layout::config_path(root), 0)+        .is_some_and(|data| data.windows(8).any(|window| window == b"promisor"));+    let packs = layout::packs_dir(root);+    let names = core::list_directory(&packs);+    let mut store = Store::open(root)?;+    let mut seen_objects: HashMap<_, ()> = HashMap::new();+    for name in &names {+        let text = String::from_utf8_lossy(name);+        if !text.ends_with(".vpack") {+            continue;+        }+        let path = packs.join(core::path_from_bytes(name));+        let Some(data) = core::read_file_opt(&path, crate::object::MAX_STORE_PACK_BYTES) else {+            output::error_prefix();+            println!("fsck: {}: cannot read pack", path.display());+            errors += 1;+            continue;+        };+        let pack = match crate::store::pack::decode(data) {+            Ok(pack) => pack,+            Err(_) => {+                output::error_prefix();+                println!("fsck: {}: invalid pack", path.display());+                errors += 1;+                continue;+            }+        };+        let stem = &text[..text.len() - 6];+        let index_path = packs.join(format!("{stem}.vidx"));+        let Some(index_data) =+            core::read_file_opt(&index_path, crate::object::MAX_STORE_PACK_BYTES)+        else {+            output::error_prefix();+            println!("fsck: {}: pack has no index", path.display());+            errors += 1;+            continue;+        };+        let index = match crate::store::index::decode(&index_data, Some(pack.trailer)) {+            Ok(index) => index,+            Err(_) => {+                output::error_prefix();+                println!("fsck: {}: invalid index", index_path.display());+                errors += 1;+                continue;+            }+        };+        if index.entries.len() != pack.records.len() {+            output::error_prefix();+            println!(+                "fsck: {}: pack and index object counts differ",+                path.display()+            );+            errors += 1;+            continue;+        }+        let mut visited = vec![false; pack.records.len()];+        for entry in &index.entries {+            let Some(position) = pack.find_by_offset(entry.offset) else {+                output::error_prefix();+                println!(+                    "fsck: {}: index offset names no record for {}",+                    path.display(),+                    entry.id.to_hex()+                );+                errors += 1;+                continue;+            };+            if pack.records[position].id != entry.id {+                output::error_prefix();+                println!(+                    "fsck: {}: index id does not match record for {}",+                    path.display(),+                    entry.id.to_hex()+                );+                errors += 1;+            }+            if visited[position] {+                output::error_prefix();+                println!(+                    "fsck: {}: record indexed more than once {}",+                    path.display(),+                    entry.id.to_hex()+                );+                errors += 1;+            }+            visited[position] = true;+        }+        for position in 0..pack.records.len() {+            if !visited[position] {+                output::error_prefix();+                println!(+                    "fsck: {}: record is not indexed {}",+                    path.display(),+                    pack.records[position].id.to_hex()+                );+                errors += 1;+            }+            let record = &pack.records[position];+            let Ok(body) = pack.get(position) else {+                output::error_prefix();+                println!(+                    "fsck: {}: invalid record {}",+                    path.display(),+                    record.id.to_hex()+                );+                errors += 1;+                continue;+            };+            if crate::object::id::object_id(record.kind, &body) != record.id {+                output::error_prefix();+                println!(+                    "fsck: {}: hash mismatch for {}",+                    path.display(),+                    record.id.to_hex()+                );+                errors += 1;+                continue;+            }+            if seen_objects.insert(record.id, ()).is_some() {+                warnings += 1;+            }+            check_object_refs(+                &mut store,+                &body,+                record.kind,+                promisor,+                &mut errors,+                &mut warnings,+            )?;+        }+    }+    let heads = ops::read_heads(root)?;+    for head in heads {+        if store.operation(head)?.is_none() {+            output::error_prefix();+            println!("fsck: operation head is missing: {}", head.to_hex());+            errors += 1;+        }+    }+    if verbose && warnings > 0 {+        output::warning_prefix();+        println!("{warnings} warning(s)");+    }+    if errors == 0 {+        output::info_prefix();+        println!("fsck: clean");+        Ok(0)+    } else {+        output::error_prefix();+        println!("{errors} error(s)");+        Ok(1)+    }+}++fn check_object_refs(+    store: &mut Store,+    body: &[u8],+    kind: u8,+    promisor: bool,+    errors: &mut usize,+    warnings: &mut usize,+) -> Result<()> {+    let mut check = |id: crate::object::id::Id, expected: u8| -> Result<()> {+        if store.contains(id) {+            return Ok(());+        }+        if promisor && matches!(expected, crate::object::TYPE_CHUNK | TYPE_BLOB) {+            *warnings += 1;+        } else {+            output::error_prefix();+            println!("fsck: missing object {}", id.to_hex());+            *errors += 1;+        }+        Ok(())+    };+    match kind {+        TYPE_BLOB => {+            if let Ok(blob) = crate::object::blob::decode(body) {+                if blob.form != crate::object::blob::BlobForm::Inline {+                    let expected = if blob.form == crate::object::blob::BlobForm::Leaf {+                        crate::object::TYPE_CHUNK+                    } else {+                        TYPE_BLOB+                    };+                    for entry in blob.entries {+                        check(entry.id, expected)?;+                    }+                }+            }+        }+        TYPE_TREE => {+            if let Ok(tree) = tree::decode(body) {+                for entry in tree.entries {+                    match entry.kind {+                        tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {+                            check(entry.target, TYPE_BLOB)?;+                        }+                        KIND_SUBTREE => check(entry.target, TYPE_TREE)?,+                        KIND_CONFLICT => check(entry.target, TYPE_CONFLICT)?,+                        _ => {}+                    }+                }+            }+        }+        TYPE_CONFLICT => {+            if let Ok(conflict) = crate::object::conflict::decode(body) {+                for value in conflict.adds.iter().chain(conflict.removes.iter()) {+                    if let Some(target) = value.target {+                        let expected = match value.kind {+                            1 | 2 | 3 => TYPE_BLOB,+                            4 => TYPE_TREE,+                            6 => TYPE_CONFLICT,+                            _ => continue,+                        };+                        check(target, expected)?;+                    }+                }+            }+        }+        TYPE_COMMIT => {+            if let Ok(commit) = crate::object::commit::decode(body) {+                for parent in commit.parents {+                    check(parent, TYPE_COMMIT)?;+                }+                check(commit.root_tree, TYPE_TREE)?;+            }+        }+        TYPE_OPERATION => {+            if let Ok(operation) = crate::object::view::decode_operation(body) {+                for parent in operation.parents {+                    check(parent, TYPE_OPERATION)?;+                }+                check(operation.view, TYPE_VIEW)?;+            }+        }+        TYPE_VIEW => {+            if let Ok(view) = crate::object::view::decode_view(body) {+                for head in view.heads {+                    check(head, TYPE_COMMIT)?;+                }+            }+        }+        _ => {}+    }+    Ok(())+}++pub fn repack(arguments: &[String]) -> Result<u8> {+    let mut path = ".".to_string();+    let mut verbose = false;+    let mut level = 6;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && matches!(argument.as_str(), "-v" | "-verbose") {+            verbose = true;+        } else if !end_flags && let Some(value) = argument.strip_prefix("-level:") {+            level = value+                .parse::<i32>()+                .map_err(|_| Error::new("-level: requires a value (1-19)"))?;+            if !(1..=19).contains(&level) {+                return Err(Error::new("compression level must be between 1 and 19"));+            }+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            path = argument.clone();+        }+    }+    let root = layout::discover(Path::new(&path))+        .map_err(|_| Error::new(format!("not a veins repository: {path}")))?;+    let packs = layout::packs_dir(&root);+    let mut objects = Vec::new();+    let mut seen = crate::store::pack::IdSet::default();+    let mut before = 0u64;+    let mut names = core::list_directory(&packs);+    names.sort();+    for name in names {+        let text = String::from_utf8_lossy(&name);+        if !text.ends_with(".vpack") {+            continue;+        }+        let path = packs.join(core::path_from_bytes(&name));+        let Some(data) = core::read_file_opt(&path, crate::object::MAX_STORE_PACK_BYTES) else {+            output::error_prefix();+            println!("cannot read pack {text}");+            return Ok(1);+        };+        before += data.len() as u64;+        let Ok(pack) = crate::store::pack::decode(data) else {+            output::error_prefix();+            println!("cannot decode pack {text}");+            return Ok(1);+        };+        for (index, record) in pack.records.iter().enumerate() {+            if !seen.insert(record.id) {+                continue;+            }+            let Ok(body) = pack.get(index) else {+                output::error_prefix();+                println!("cannot read object {}", record.id.to_hex());+                return Ok(1);+            };+            objects.push(crate::object::RawObject::known(+                record.kind,+                record.id,+                body,+            ));+        }+    }+    if objects.is_empty() {+        output::info_prefix();+        println!("no objects to repack");+        return Ok(0);+    }+    let output_pack = crate::store::pack::encode(&objects, level);+    if crate::store::pack::write_output(&root, &output_pack, 0) != 0 {+        output::error_prefix();+        println!("cannot write repacked pack");+        return Ok(1);+    }+    for name in core::list_directory(&packs) {+        let text = String::from_utf8_lossy(&name);+        let is_pack = text.ends_with(".vpack");+        let is_index = text.ends_with(".vidx");+        if !is_pack && !is_index {+            continue;+        }+        let stem = if is_pack {+            &text[..text.len() - 6]+        } else {+            &text[..text.len() - 5]+        };+        if stem == output_pack.name {+            continue;+        }+        let _ = core::remove_file(&packs.join(core::path_from_bytes(&name)));+    }+    if verbose {+        output::info_prefix();+        println!(+            "repacked {} objects, {} KiB -> {} KiB",+            output_pack.count,+            before / 1024,+            (output_pack.pack.len() + output_pack.index.len()) as u64 / 1024+        );+    }+    Ok(0)+}++pub fn inf(arguments: &[String]) -> Result<u8> {+    let mut include_generated = false;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags+            && matches!(+                argument.as_str(),+                "-inc-gen" | "-include-generated" | "--include-generated"+            )+        {+            include_generated = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        }+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let view = ops::current_view(&root, &mut store)?.unwrap_or_default();+    let working = ops::working_copy_id(&view);+    let rules = AttributeRules::load(&root);++    let mut total_files = 0u64;+    let mut total_lines = 0u64;+    let mut generated_files = 0u64;+    let mut generated_lines = 0u64;+    let mut generated_bytes = 0u64;+    let mut by_ext: HashMap<String, (u64, u64, u64)> = HashMap::new();++    let tree = match working {+        Some(working) => graph::load_commit(&mut store, working)?.map(|commit| commit.root_tree),+        None => None,+    };+    if let Some(tree) = tree {+        let entries = tree::flatten(&mut store, tree)?;+        let files: Vec<&tree::FlatEntry> = entries+            .iter()+            .filter(|entry| matches!(entry.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE))+            .collect();+        store.preload()?;++        struct FileResult {+            ext: String,+            lines: u64,+            bytes: u64,+            generated: bool,+        }++        let measure = |entry: &&tree::FlatEntry| -> FileResult {+            let attributes = rules.lookup(&String::from_utf8_lossy(&entry.path));+            let mut measured = graph::BlobMeasure::default();+            let ok = graph::measure_blob_loaded(&store, entry.target, &mut measured)+                .ok()+                .unwrap_or(false);+            let binary = attributes.text == AttributeText::Binary+                || (attributes.text == AttributeText::Auto && measured.has_nul);+            FileResult {+                ext: ext_of(&entry.path),+                lines: if binary || !ok { 0 } else { measured.lines },+                bytes: if ok { measured.bytes } else { 0 },+                generated: attributes.generated,+            }+        };++        let mut workers = std::thread::available_parallelism()+            .map(|value| value.get())+            .unwrap_or(1);+        workers = workers.min(files.len()).min(16);+        let results: Vec<FileResult> = if workers <= 1 {+            files.iter().map(measure).collect()+        } else {+            let pool = rayon::ThreadPoolBuilder::new()+                .num_threads(workers)+                .build()+                .map_err(|error| Error::new(error.to_string()))?;+            pool.install(|| files.par_iter().map(measure).collect())+        };++        for result in results {+            if result.generated {+                generated_files += 1;+                generated_lines += result.lines;+                generated_bytes += result.bytes;+                if !include_generated {+                    continue;+                }+            }+            total_files += 1;+            total_lines += result.lines;+            let stat = by_ext.entry(result.ext).or_insert((0, 0, 0));+            stat.0 += 1;+            stat.1 += result.lines;+            stat.2 += result.bytes;+        }+    }++    let mut commits = 0u64;+    let mut has_time = false;+    let mut created = 0i64;+    let mut last = 0i64;+    let mut authors: HashMap<String, u64> = HashMap::new();+    for id in graph::collect_commits(&mut store, &graph::view_roots(&view))? {+        let Some(commit) = graph::load_commit(&mut store, id)? else {+            continue;+        };+        commits += 1;+        let seconds = commit.committer.seconds;+        if has_time {+            created = created.min(seconds);+            last = last.max(seconds);+        } else {+            created = seconds;+            last = seconds;+            has_time = true;+        }+        let name = if commit.author.name.is_empty() {+            "(unknown)".to_string()+        } else {+            String::from_utf8_lossy(&commit.author.name).into_owned()+        };+        *authors.entry(name).or_insert(0) += 1;+    }++    println!();+    println!("{}", output::bold_cyan("Repository overview"));+    println!();+    row_value(+        "Project",+        &root.file_name().unwrap_or_default().to_string_lossy(),+    );+    print_left("HEAD", 14, None, true);+    match working {+        Some(id) => println!("{}", id.short()),+        None => println!("<none>"),+    }+    row_number("Changes", commits);+    row_number("Bookmarks", view.bookmarks.len() as u64);+    row_number("Tags", view.tags.len() as u64);+    row_number("Files", total_files);+    row_number("Lines", total_lines);+    row_number("Authors", authors.len() as u64);+    if has_time {+        show_date("Created", created);+        show_date("Last change", last);+    }+    print_left("Size", 14, None, true);+    println!("{}", size_text(dir_size(&layout::veins_dir(&root), 0)));+    if generated_files > 0 {+        print_left("Generated", 14, None, true);+        print!(+            "{generated_files} files  {generated_lines} lines  {}",+            size_text(generated_bytes)+        );+        if !include_generated {+            print!("  (excluded; use -inc-gen)");+        }+        println!();+    }+    println!();++    println!("{}", output::bold_cyan("Languages"));+    println!();+    if by_ext.is_empty() {+        println!("  no tracked files");+    } else {+        let mut entries: Vec<_> = by_ext.into_iter().collect();+        entries.sort_by(|left, right| {+            right+                .1+                .1+                .cmp(&left.1.1)+                .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))+        });+        let width = entries+            .iter()+            .fold(6usize, |width, (ext, _)| width.max(ext.len()));+        for (index, (ext, (files, lines, _))) in entries.into_iter().enumerate() {+            print_left(&ext, width, None, false);+            print!("  ");+            print_bar(lines, total_lines, index);+            print!("  ");+            print_percent(percent(lines, total_lines));+            println!("%  {lines} lines  {files} files");+        }+    }+    println!();++    println!("{}", output::bold_cyan("Authors"));+    println!();+    if authors.is_empty() {+        println!("  no commits");+    } else {+        let mut entries: Vec<_> = authors.into_iter().collect();+        entries.sort_by(|left, right| {+            right+                .1+                .cmp(&left.1)+                .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))+        });+        let width = entries+            .iter()+            .fold(6usize, |width, (name, _)| width.max(name.len()));+        for (index, (name, count)) in entries.into_iter().enumerate() {+            print_left(&name, width, Some("36"), false);+            print!("  ");+            print_bar(count, commits, index);+            print!("  ");+            print_percent(percent(count, commits));+            println!("%  {count} commits");+        }+    }+    println!();+    Ok(0)+}++fn percent(value: u64, total: u64) -> u64 {+    if total == 0 {+        0+    } else {+        (value * 100 + total / 2) / total+    }+}++fn print_percent(value: u64) {+    if value < 10 {+        print!("  {value}");+    } else if value < 100 {+        print!(" {value}");+    } else {+        print!("{value}");+    }+}++fn bar_color(index: usize) -> &'static str {+    const COLORS: [&str; 8] = ["96", "92", "93", "95", "94", "91", "36", "32"];+    COLORS[index % COLORS.len()]+}++fn print_bar(value: u64, total: u64, index: usize) {+    let mut filled = 0u64;+    if total > 0 && value > 0 {+        filled = (value * 24 + total / 2) / total;+        if filled == 0 {+            filled = 1;+        }+        if filled > 24 {+            filled = 24;+        }+    }+    for _ in 0..filled {+        output::print_styled(bar_color(index), "\u{2588}");+    }+    for _ in filled..24 {+        output::print_styled("90", "\u{2591}");+    }+}++fn print_left(text: &str, width: usize, color: Option<&str>, dim: bool) {+    if dim {+        output::print_styled("2", text);+    } else if let Some(color) = color {+        output::print_styled(color, text);+    } else {+        print!("{text}");+    }+    for _ in text.len()..width {+        print!(" ");+    }+}++fn row_value(label: &str, value: &str) {+    print_left(label, 14, None, true);+    println!("{value}");+}++fn row_number(label: &str, value: u64) {+    print_left(label, 14, None, true);+    println!("{value}");+}++fn show_date(label: &str, seconds: i64) {+    let stamp = crate::time::format_utc(seconds);+    print_left(label, 14, None, true);+    println!("{}", &stamp[..10.min(stamp.len())]);+}++fn dir_size(path: &Path, depth: usize) -> u64 {+    if depth > 64 {+        return 0;+    }+    let Ok(entries) = std::fs::read_dir(path) else {+        return 0;+    };+    let mut total = 0u64;+    for entry in entries.flatten() {+        let Ok(metadata) = entry.metadata() else {+            continue;+        };+        if metadata.is_file() {+            total += metadata.len();+        } else if metadata.is_dir() {+            total += dir_size(&entry.path(), depth + 1);+        }+    }+    total+}++fn size_text(value: u64) -> String {+    if value >= 1_073_741_824 {+        format!(+            "{}.{} GiB",+            value / 1_073_741_824,+            ((value % 1_073_741_824) * 10) / 1_073_741_824+        )+    } else if value >= 1_048_576 {+        format!(+            "{}.{} MiB",+            value / 1_048_576,+            ((value % 1_048_576) * 10) / 1_048_576+        )+    } else if value >= 1024 {+        format!("{}.{} KiB", value / 1024, ((value % 1024) * 10) / 1024)+    } else {+        format!("{value} B")+    }+}++fn ext_of(path: &[u8]) -> String {+    let text = String::from_utf8_lossy(path);+    let base_start = text.rfind('/').map(|index| index + 1).unwrap_or(0);+    let dot = text.rfind('.');+    match dot {+        Some(position) if position > base_start && position + 1 < text.len() => {+            text[position..].to_ascii_lowercase()+        }+        _ => "(none)".to_string(),+    }+}+--- /dev/null+++ b/veins/src/cli/merge_cmd.rs@@ -0,0 +1,615 @@+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::merge::engine;+use crate::object::conflict::{self, Conflict, ConflictValue};+use crate::object::id::Id;+use crate::object::tree;+use crate::object::{TYPE_COMMIT, TYPE_CONFLICT};+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::checkout;+use crate::worktree::pathspec;+use crate::worktree::snapshot;++use super::output;++pub fn run(command: &str, arguments: &[String]) -> Result<u8> {+    match command {+        "merge" => merge(arguments),+        "rebase" => rebase(arguments),+        "xs" => xs(arguments),+        "resolve" => resolve(arguments),+        _ => Err(Error::new("unknown command")),+    }+}++fn mark_native(root: &Path, id: Id) {+    let path = layout::git_map_dir(root).join("native");+    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());+}++fn merge(arguments: &[String]) -> Result<u8> {+    let mut revisions = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            revisions.push(argument.clone());+        }+    }+    if revisions.is_empty() {+        return Err(Error::new("merge requires at least one revision"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let working_copy = ops::working_copy_id(txn.view())+        .ok_or_else(|| Error::new("no working-copy commit to merge into"))?;+    let mut parents = vec![working_copy];+    for revision in &revisions {+        let resolved = graph::resolve_revision(&mut store, txn.view(), revision)?+            .ok_or_else(|| Error::new("unknown revision"))?;+        if resolved == working_copy {+            return Err(Error::new("cannot merge a commit with itself"));+        }+        parents.push(resolved);+    }+    let old_root = engine::tree_of_commit(&mut store, working_copy)?;+    let adjacent = engine::adjacent(&root);+    let outcome = engine::merge_many(&root, &mut txn, &mut store, &parents, adjacent)?;+    let author = identity::signature(&root);+    let new_id = engine::make_commit(+        &mut txn,+        &mut store,+        &root,+        &parents,+        outcome.tree,+        identity::random_change_id(),+        author,+        "",+        crate::object::commit::RENAMES_RECORDED,+        &[],+    )?;+    ops::remove_head(txn.view_mut(), working_copy);+    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    let suffix = if outcome.rerere > 0 {+        format!(" (rerere {})", outcome.rerere)+    } else {+        String::new()+    };+    txn.finish(&format!("merge {}{suffix}", revisions.join(" ")))?;+    store.refresh()?;+    mark_native(&root, new_id);+    if let Some(old) = old_root {+        checkout::materialize(&root, &mut store, Some(old), outcome.tree)?;+    }+    Ok(0)+}++fn rebase(arguments: &[String]) -> Result<u8> {+    let mut source = String::new();+    let mut destination = String::new();+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-s" || argument == "-source") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            source = arguments[index].clone();+        } else if !end_flags && (argument == "-d" || argument == "-destination") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            destination = arguments[index].clone();+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            return Err(Error::new(format!("unexpected argument: {argument}")));+        }+        index += 1;+    }+    if source.is_empty() || destination.is_empty() {+        return Err(Error::new("rebase requires -s <rev> and -d <rev>"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let source_id = graph::resolve_revision(&mut store, txn.view(), &source)?+        .ok_or_else(|| Error::new("unknown revision"))?;+    let destination_id = graph::resolve_revision(&mut store, txn.view(), &destination)?+        .ok_or_else(|| Error::new("unknown revision"))?;+    let working_copy = ops::working_copy_id(txn.view());+    let old_working_tree = match working_copy {+        Some(id) => engine::tree_of_commit(&mut store, id)?,+        None => None,+    };+    let mut set = Vec::new();+    for commit in graph::all_commits(&mut store, txn.view())? {+        if engine::is_ancestor(&mut store, source_id, commit)? {+            set.push(commit);+        }+    }+    let adjacent = engine::adjacent(&root);+    let mut old_ids = Vec::new();+    let mut new_ids = Vec::new();+    let mut new_trees = Vec::new();+    let mut remaining = set.clone();+    let mut rerere_total = 0usize;+    while !remaining.is_empty() {+        let mut ready = None;+        for (index, id) in remaining.iter().enumerate() {+            let Some(loaded) = graph::load_commit(&mut store, *id)? else {+                continue;+            };+            let mut ok = true;+            for parent in &loaded.parents {+                if set.contains(parent) && !old_ids.contains(parent) && *id != source_id {+                    ok = false;+                }+            }+            if ok {+                ready = Some(index);+                break;+            }+        }+        let Some(index) = ready else {+            return Err(Error::new("rebase could not order commits"));+        };+        let chosen = remaining.remove(index);+        let loaded = graph::load_commit(&mut store, chosen)?+            .ok_or_else(|| Error::new("cannot read revision"))?;+        let mut new_parents = Vec::new();+        let mut new_parent_trees = Vec::new();+        for (position, parent) in loaded.parents.iter().enumerate() {+            if position == 0 && chosen == source_id {+                new_parents.push(destination_id);+                new_parent_trees+                    .push(engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default());+                continue;+            }+            if let Some(mapped) = old_ids.iter().position(|value| value == parent) {+                new_parents.push(new_ids[mapped]);+                new_parent_trees.push(new_trees[mapped]);+            } else {+                new_parents.push(*parent);+                new_parent_trees+                    .push(engine::tree_of_commit(&mut store, *parent)?.unwrap_or_default());+            }+        }+        if loaded.parents.is_empty() {+            new_parents.push(destination_id);+            new_parent_trees+                .push(engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default());+        }+        let outcome = engine::rewrite_tree(+            &root,+            &mut txn,+            &mut store,+            chosen,+            loaded.root_tree,+            &loaded.parents,+            &new_parents,+            &new_parent_trees,+            adjacent,+        )?;+        rerere_total += outcome.rerere;+        let new_id = engine::make_commit(+            &mut txn,+            &mut store,+            &root,+            &new_parents,+            outcome.tree,+            loaded.change_id,+            loaded.author,+            &String::from_utf8_lossy(&loaded.message),+            loaded.renames_state,+            &loaded.extra,+        )?;+        old_ids.push(chosen);+        new_ids.push(new_id);+        new_trees.push(outcome.tree);+    }+    for bookmark in &mut txn.view_mut().bookmarks {+        remap(&old_ids, &new_ids, &mut bookmark.targets.adds);+        remap(&old_ids, &new_ids, &mut bookmark.targets.removes);+    }+    for tag in &mut txn.view_mut().tags {+        if let Some(mapped) = map_id(&old_ids, &new_ids, tag.target) {+            tag.target = mapped;+        }+    }+    for workspace in &mut txn.view_mut().working_copies {+        if let Some(mapped) = map_id(&old_ids, &new_ids, workspace.target) {+            workspace.target = mapped;+        }+    }+    ops::rebuild_heads(txn.view_mut());+    let suffix = if rerere_total > 0 {+        format!(" (rerere {rerere_total})")+    } else {+        String::new()+    };+    txn.finish(&format!("rebase {source} onto {destination}{suffix}"))?;+    for id in &new_ids {+        mark_native(&root, *id);+    }+    if let Some(working_copy) = working_copy+        && let Some(index) = old_ids.iter().position(|value| *value == working_copy)+    {+        let mut refreshed = Store::open(&root)?;+        checkout::materialize(&root, &mut refreshed, old_working_tree, new_trees[index])?;+    }+    Ok(0)+}++fn map_id(old: &[Id], new: &[Id], id: Id) -> Option<Id> {+    old.iter()+        .position(|value| *value == id)+        .map(|index| new[index])+}++fn remap(old: &[Id], new: &[Id], ids: &mut [Option<Id>]) {+    for value in ids {+        if let Some(id) = *value+            && let Some(mapped) = map_id(old, new, id)+        {+            *value = Some(mapped);+        }+    }+}++fn conflict_entries(store: &mut Store, root_tree: Id) -> Result<Vec<(Vec<u8>, Conflict)>> {+    let mut output = Vec::new();+    for entry in tree::flatten(store, root_tree)? {+        if entry.kind != tree::KIND_CONFLICT {+            continue;+        }+        let Some(body) = store.body(entry.target, TYPE_CONFLICT)? else {+            continue;+        };+        let Ok(conflict) = conflict::decode(&body) else {+            continue;+        };+        output.push((entry.path, conflict));+    }+    Ok(output)+}++fn print_range(start: usize, end: usize) -> String {+    if start == end {+        (start + 1).to_string()+    } else {+        format!("{}-{end}", start + 1)+    }+}++fn xs(arguments: &[String]) -> Result<u8> {+    let mut porcelain = false;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && matches!(argument.as_str(), "-porcelain" | "-p") {+            porcelain = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            return Err(Error::new(format!("unexpected argument: {argument}")));+        }+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let Some(working_copy) = ops::working_copy_id(&view) else {+        output::info_prefix();+        println!("no conflicts");+        return Ok(0);+    };+    let Some(commit) = graph::load_commit(&mut store, working_copy)? else {+        return Err(Error::new("cannot read working-copy commit"));+    };+    let items = conflict_entries(&mut store, commit.root_tree)?;+    let adjacent = engine::adjacent(&root);+    for (path, conflict) in items {+        let kind = engine::conflict_kind_label(&conflict);+        let ranges = engine::conflict_ranges(&mut store, &conflict, adjacent)?;+        if porcelain {+            print!("{}\t{kind}\t", String::from_utf8_lossy(&path));+            if let Some(ranges) = ranges {+                for (index, range) in ranges.ranges.iter().enumerate() {+                    if index > 0 {+                        print!(",");+                    }+                    print!("{}", print_range(range.base_start, range.base_end));+                }+                print!("\t");+                for (index, range) in ranges.ranges.iter().enumerate() {+                    if index > 0 {+                        print!(",");+                    }+                    print!("{}", print_range(range.ours_start, range.ours_end));+                }+                print!("\t");+                for (index, range) in ranges.ranges.iter().enumerate() {+                    if index > 0 {+                        print!(",");+                    }+                    print!("{}", print_range(range.theirs_start, range.theirs_end));+                }+            } else {+                print!("\t\t");+            }+            println!();+        } else {+            print!("{}: {kind} conflict", String::from_utf8_lossy(&path));+            if let Some(ranges) = ranges {+                if !ranges.ranges.is_empty() {+                    print!(" (");+                    for (index, range) in ranges.ranges.iter().enumerate() {+                        if index > 0 {+                            print!(", ");+                        }+                        print!(+                            "base {}, ours {}, theirs {}",+                            print_range(range.base_start, range.base_end),+                            print_range(range.ours_start, range.ours_end),+                            print_range(range.theirs_start, range.theirs_end)+                        );+                    }+                    print!(")");+                }+            }+            println!();+        }+    }+    if items_is_empty(&mut store, working_copy)? {+        output::info_prefix();+        println!("no conflicts");+    }+    Ok(0)+}++fn items_is_empty(store: &mut Store, working_copy: Id) -> Result<bool> {+    let Some(commit) = graph::load_commit(store, working_copy)? else {+        return Ok(true);+    };+    Ok(tree::flatten(store, commit.root_tree)?+        .iter()+        .all(|entry| entry.kind != tree::KIND_CONFLICT))+}++fn choose<'a>(conflict: &'a Conflict, take: &str) -> Option<&'a ConflictValue> {+    match take {+        "ours" => conflict.adds.first(),+        "theirs" => conflict.adds.get(1),+        "base" => conflict.removes.first(),+        _ => None,+    }+}++fn shell_replace(command: &str, key: &str, value: &str) -> String {+    command.replace(key, &format!("'{value}'"))+}++fn run_tool(root: &Path, command: &str, path: &[u8]) -> bool {+    let base = core::path_display(&root.join(core::path_from_bytes(path)));+    let expanded = shell_replace(+        &shell_replace(+            &shell_replace(+                &shell_replace(command, "$BASE", &format!("{base}.base")),+                "$OURS",+                &format!("{base}.ours"),+            ),+            "$THEIRS",+            &format!("{base}.theirs"),+        ),+        "$OUTPUT",+        &base,+    );+    std::process::Command::new("sh")+        .arg("-c")+        .arg(expanded)+        .status()+        .is_ok_and(|status| status.success())+}++fn delete_sidecars(root: &Path, path: &[u8]) {+    let base = root.join(core::path_from_bytes(path));+    let _ = core::remove_file(&base.with_file_name(format!(+        "{}.base",+        base.file_name().unwrap_or_default().to_string_lossy()+    )));+    for suffix in [".ours", ".theirs"] {+        let mut full = path.to_vec();+        full.extend_from_slice(suffix.as_bytes());+        let _ = core::remove_file(&root.join(core::path_from_bytes(&full)));+    }+    let parent = base.parent().unwrap_or(root);+    let name = base.file_name().unwrap_or_default().to_string_lossy();+    for number in 2..=64 {+        let _ = core::remove_file(&parent.join(format!("{name}.base{number}")));+        let _ = core::remove_file(&parent.join(format!("{name}.theirs{number}")));+    }+    let _ = core::remove_file(&parent.join(format!("{name}.base")));+}++fn resolve(arguments: &[String]) -> Result<u8> {+    let mut take = String::new();+    let mut tool = String::new();+    let mut list_only = false;+    let mut paths = Vec::new();+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && matches!(argument.as_str(), "-list" | "-l") {+            list_only = true;+        } else if !end_flags && (argument == "-take" || argument == "-t") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!(+                    "{argument} requires ours, theirs, or base"+                )));+            }+            take = arguments[index].clone();+        } else if !end_flags && argument == "-tool" {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a command")));+            }+            tool = arguments[index].clone();+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            paths.push(argument.clone());+        }+        index += 1;+    }+    if list_only {+        return xs(&[]);+    }+    if paths.is_empty() {+        return Err(Error::new("resolve requires at least one path"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let working_copy =+        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+    let loaded = graph::load_commit(&mut store, working_copy)?+        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+    let old_root = loaded.root_tree;+    let mut root_tree = old_root;+    let mut resolved_any = false;+    let cwd = pathspec::cwd_relative(&root);+    let mut normalized_paths = Vec::new();+    for path in &paths {+        let Some(normalized) = cwd+            .as_ref()+            .and_then(|cwd| pathspec::pathspec_normalize(&root, cwd, path))+        else {+            output::error_prefix();+            println!("invalid path");+            continue;+        };+        if normalized.is_empty() {+            output::error_prefix();+            println!("invalid path");+            continue;+        }+        normalized_paths.push(normalized.clone());+        let flat = tree::flatten(&mut store, root_tree)?;+        let Some(entry) = flat+            .iter()+            .find(|entry| entry.path == normalized.as_bytes())+        else {+            output::error_prefix();+            println!("not a conflicted path: {normalized}");+            continue;+        };+        if entry.kind != tree::KIND_CONFLICT {+            output::error_prefix();+            println!("not a conflicted path: {normalized}");+            continue;+        }+        let conflict_id = entry.target;+        let Some(body) = store.body(conflict_id, TYPE_CONFLICT)? else {+            continue;+        };+        let Ok(conflict) = conflict::decode(&body) else {+            continue;+        };+        let mut present = false;+        let mut kind = tree::KIND_FILE;+        let mut target = None;+        if let Some(chosen) = choose(&conflict, &take) {+            if chosen.kind != 0 {+                present = true;+                kind = chosen.kind;+                target = chosen.target;+            }+        } else if !tool.is_empty() {+            if run_tool(&root, &tool, normalized.as_bytes())+                && let Some(data) =+                    core::read_file_opt(&root.join(core::path_from_bytes(normalized.as_bytes())), 0)+            {+                target = Some(engine::add_blob_data(&mut txn, &data));+                present = true;+                kind = tree::KIND_FILE;+            }+        } else if let Some(data) =+            core::read_file_opt(&root.join(core::path_from_bytes(normalized.as_bytes())), 0)+        {+            target = Some(engine::add_blob_data(&mut txn, &data));+            present = true;+            kind = tree::KIND_FILE;+        }+        if present+            && let Some(info) =+                core::stat_path(&root.join(core::path_from_bytes(normalized.as_bytes())))+            && info.executable+        {+            kind = tree::KIND_EXECUTABLE;+        }+        if present+            && matches!(kind, tree::KIND_FILE | tree::KIND_EXECUTABLE)+            && let Some(target) = target+        {+            engine::resolution_store(&root, &body, target);+        }+        if let Some(replaced) = engine::edit_tree(+            &mut txn,+            &mut store,+            root_tree,+            normalized.as_bytes(),+            present,+            kind,+            target.unwrap_or_default(),+        )? {+            root_tree = replaced;+            resolved_any = true;+        }+    }+    if !resolved_any {+        return Ok(1);+    }+    let mut commit = loaded;+    commit.root_tree = root_tree;+    commit.committer = identity::signature(&root);+    let new_id = txn.add_object(TYPE_COMMIT, crate::object::commit::encode(&commit));+    ops::remove_head(txn.view_mut(), working_copy);+    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    txn.finish("resolve")?;+    let mut refreshed = Store::open(&root)?;+    checkout::materialize(&root, &mut refreshed, Some(old_root), root_tree)?;+    for path in normalized_paths {+        delete_sidecars(&root, path.as_bytes());+    }+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/mod.rs@@ -0,0 +1,126 @@+pub mod args;+pub mod commands;+pub mod config_cmd;+pub mod diff;+pub mod history;+pub mod info;+pub mod merge_cmd;+pub mod net_cmd;+pub mod output;+pub mod refs;+pub mod status;+pub mod worktree_cmd;++use crate::Result;++pub fn run(arguments: &[String]) -> u8 {+    match dispatch(arguments) {+        Ok(code) => code,+        Err(error) => {+            output::error_prefix();+            println!("{error}");+            1+        }+    }+}++fn dispatch(arguments: &[String]) -> Result<u8> {+    let Some(command) = arguments.first() else {+        usage();+        return Ok(1);+    };+    let rest = &arguments[1..];+    match command.as_str() {+        "init" => commands::init::run(rest),+        "status" | "stat" => status::run(),+        "log" => history::log(rest),+        "show" => history::show(rest),+        "hash" => history::hash(rest),+        "ls" => history::list(rest),+        "diff" => history::diff(rest),+        "new" => history::new_change(rest),+        "desc" | "describe" => history::describe(rest),+        "go" | "commit" => history::commit(rest),+        "amend" => history::amend(rest),+        "op" => history::op(rest),+        "undo" => history::undo(),+        "co" | "checkout" => commands::checkout::run(rest),+        "bmk" => refs::bookmark(rest),+        "tag" => refs::tag(rest),+        "cfg" => config_cmd::run(rest),+        "rm" => worktree_cmd::remove(rest),+        "mv" => worktree_cmd::move_path(rest),+        "ex" => worktree_cmd::exclude(rest),+        "attr" => worktree_cmd::attr(rest),+        "edit" => worktree_cmd::edit(rest),+        "fsck" => info::fsck(rest),+        "repack" | "gc" => info::repack(rest),+        "inf" => info::inf(rest),+        "about" => {+            println!("By Navid Momtahen (C) - 2026");+            println!("https://veins.pages.dev");+            println!("https://veinsforge.top/navid/veins");+            Ok(0)+        }+        "self-test" => commands::selftest::run(),+        "version" | "-version" | "-v" => info::version(),+        "merge" | "rebase" | "xs" | "resolve" => merge_cmd::run(command, rest),+        "remote" | "clone" | "fetch" | "pull" | "pl" | "push" | "psh" | "gg" | "serve" | "key"+        | "auth" | "access" | "whoami" => net_cmd::run(command, rest),+        "git" => net_cmd::git(rest),+        "help" | "-help" | "-h" => info::help(rest),+        _ => Err(crate::Error::new(format!("unknown command: {command}"))),+    }+}++fn usage() {+    println!("veins is a tool for managing source code");+    println!();+    println!("commands:");+    println!("  init         create a repository");+    println!("  git          import from or export to git");+    println!("  remote       manage native remotes");+    println!("  clone        clone a repository over the native protocol");+    println!("  fetch        fetch from a native remote");+    println!("  pull         fetch and fast-forward the current bookmark; alias: pl");+    println!("  gg           fetch the active remote, or clone a URL");+    println!("  push         push a bookmark to a native remote");+    println!("  serve        run the native server over stdio or TLS");+    println!("  key          manage local Ed25519 keys");+    println!("  auth         remember keys for hosts and set a default");+    println!("  access       manage a served repository's access file");+    println!("  whoami       report the role granted by a server");+    println!("  co           write a revision into the working directory; alias: checkout");+    println!("  stat         show working-copy changes; alias: status");+    println!("  ls           list tracked files");+    println!("  inf          show a repository breakdown");+    println!("  log          show commit history");+    println!("  show         show a commit and its diff");+    println!("  hash         print the commit hash for a revision");+    println!("  diff         show a unified diff, paged on a terminal");+    println!("  merge        create a merge commit; never fails");+    println!("  rebase       rewrite changes onto a new parent");+    println!("  xs           list conflicted paths");+    println!("  resolve      resolve a conflicted path");+    println!("  new          start a new change");+    println!("  bmk          manage named branch pointers (set, rename, ls, rm)");+    println!("  tag          manage named tags");+    println!("  cfg          read and write configuration");+    println!("  edit         open paths in the configured text editor");+    println!("  rm           untrack paths, keeping files on disk by default");+    println!("  mv           move a tracked file and record the rename");+    println!("  ex           add paths or globs to .vnexclude");+    println!("  attr         add or remove .vnattribs rules");+    println!("  desc         set the working-copy commit message; alias: describe");+    println!("  go           describe and start a new change; alias: commit");+    println!("  amend        rewrite a revision's message and its descendants");+    println!("  undo         restore the previous operation view");+    println!("  op           operation log commands");+    println!("  fsck         verify repository integrity");+    println!("  repack       rewrite packs into one delta-compressed pack; alias: gc");+    println!("  self-test    run the format self-tests");+    println!("  version      print version information");+    println!("  help         show help for a command");+    println!();+    println!("run 'vn help <command>' for details");+}--- /dev/null+++ b/veins/src/cli/net_cmd.rs@@ -0,0 +1,1356 @@+use std::collections::HashSet;+use std::path::{Path, PathBuf};++use crate::core;+use crate::crypto;+use crate::error::{Error, Result};+use crate::object::blob::{self, BlobForm};+use crate::object::commit::{self, Commit};+use crate::object::id::Id;+use crate::object::tree::{self, KIND_SUBTREE};+use crate::object::{TYPE_BLOB, TYPE_COMMIT, TYPE_TREE};+use crate::protocol::client::Client;+use crate::protocol::messages::{self, RefInfo, UpdateRef};+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::checkout;+use crate::worktree::snapshot;++use super::output;++pub fn run(command: &str, arguments: &[String]) -> Result<u8> {+    match command {+        "remote" => remote(arguments),+        "clone" => clone(arguments),+        "fetch" => fetch(arguments),+        "pull" | "pl" => pull(arguments),+        "push" | "psh" => push(arguments),+        "gg" => gg(arguments),+        "serve" => serve(arguments),+        "key" => key(arguments),+        "auth" => auth(arguments),+        "access" => access(arguments),+        "whoami" => whoami(arguments),+        _ => Err(Error::new("unknown command")),+    }+}++fn remote_key(remote: &str, field: &str) -> String {+    format!("remote.{remote}.{field}")+}++fn last_segment(path: &str) -> String {+    let trimmed = path.trim_end_matches('/');+    match trimmed.rsplit_once('/') {+        Some((_, name)) if !name.is_empty() => name.to_string(),+        _ if !trimmed.is_empty() && trimmed != "/" => trimmed.to_string(),+        _ => "repo".to_string(),+    }+}++fn list_remote_names(root: &Path) -> Vec<String> {+    let Some(data) = core::read_file_opt(&layout::config_path(root), 0) else {+        return Vec::new();+    };+    let text = String::from_utf8_lossy(&data);+    let mut output = Vec::new();+    for line in text.lines() {+        if let Some(rest) = line.strip_prefix("remote.")+            && let Some((name, _)) = rest.split_once(".url")+            && !name.is_empty()+            && !output.contains(&name.to_string())+        {+            output.push(name.to_string());+        }+    }+    output+}++fn remote(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        return Err(Error::new(+            "expected a remote subcommand (add, set-url, list, remove)",+        ));+    };+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    match sub.as_str() {+        "add" | "set-url" => {+            let replace = sub == "set-url";+            let mut name = String::new();+            let mut url = String::new();+            let mut key = None;+            let mut pin = None;+            for argument in &arguments[1..] {+                if let Some(value) = argument.strip_prefix("-key:") {+                    key = Some(value.to_string());+                } else if let Some(value) = argument.strip_prefix("-pin:") {+                    pin = Some(value.to_string());+                } else if core::is_flag(argument) {+                    return Err(Error::new(format!("unknown flag: {argument}")));+                } else if name.is_empty() {+                    name = argument.clone();+                } else if url.is_empty() {+                    url = argument.clone();+                } else {+                    return Err(Error::new("too many arguments"));+                }+            }+            if name.is_empty() || url.is_empty() {+                return Err(Error::new(if replace {+                    "remote set-url requires a name and URL"+                } else {+                    "remote add requires a name and URL"+                }));+            }+            let url_key = remote_key(&name, "url");+            let existing = core::repo_config_value(&root, &url_key);+            if existing.is_some() && !replace {+                return Err(Error::new(format!("remote already exists: {name}")));+            }+            if existing.is_none() && replace {+                return Err(Error::new(format!("unknown remote: {name}")));+            }+            if !core::repo_config_set(&root, &url_key, &url) {+                return Err(Error::new("cannot write repository config"));+            }+            if let Some(key) = key {+                let field = remote_key(&name, "key");+                let ok = if key.is_empty() {+                    core::repo_config_remove(&root, &field)+                } else {+                    core::repo_config_set(&root, &field, &key)+                };+                if !ok {+                    return Err(Error::new("cannot write repository config"));+                }+            }+            if let Some(pin) = pin {+                let field = remote_key(&name, "tls-pin");+                let ok = if pin.is_empty() {+                    core::repo_config_remove(&root, &field)+                } else {+                    core::repo_config_set(&root, &field, &pin)+                };+                if !ok {+                    return Err(Error::new("cannot write repository config"));+                }+            }+            Ok(0)+        }+        "list" | "ls" => {+            for name in list_remote_names(&root) {+                let url =+                    core::repo_config_value(&root, &remote_key(&name, "url")).unwrap_or_default();+                println!("{name}\t{url}");+            }+            Ok(0)+        }+        "remove" | "rm" => {+            let name = arguments.get(1).cloned().unwrap_or_default();+            if name.is_empty() {+                return Err(Error::new("remote remove requires a name"));+            }+            if core::repo_config_value(&root, &remote_key(&name, "url")).is_none() {+                return Err(Error::new(format!("unknown remote: {name}")));+            }+            core::repo_config_remove(&root, &remote_key(&name, "url"));+            core::repo_config_remove(&root, &remote_key(&name, "key"));+            core::repo_config_remove(&root, &remote_key(&name, "tls-pin"));+            Ok(0)+        }+        _ => Err(Error::new(format!("unknown remote subcommand: {sub}"))),+    }+}++fn active_remote(root: &Path) -> String {+    for key in ["remote.current", "remote.default"] {+        if let Some(name) = core::repo_config_value(root, key)+            && !name.is_empty()+            && core::repo_config_value(root, &remote_key(&name, "url")).is_some()+        {+            return name;+        }+    }+    if core::repo_config_value(root, &remote_key("o", "url")).is_some() {+        return "o".to_string();+    }+    list_remote_names(root)+        .into_iter()+        .next()+        .unwrap_or_else(|| "o".to_string())+}++fn remote_url(root: &Path, remote: &str) -> Option<String> {+    core::repo_config_value(root, &remote_key(remote, "url"))+}++fn remote_key_name(root: &Path, remote: &str) -> String {+    if let Some(key) = core::repo_config_value(root, &remote_key(remote, "key"))+        && crypto::local_key_exists(&key)+    {+        return key;+    }+    if let Some(url) = remote_url(root, remote)+        && let Some(key) = crypto::key_for_url(&url)+    {+        return key;+    }+    String::new()+}++fn default_target(refs: &[RefInfo]) -> Option<Id> {+    for reference in refs {+        if reference.kind == 0 && matches!(reference.name.as_str(), "main" | "master") {+            return Some(reference.target);+        }+    }+    refs.iter()+        .find(|reference| reference.kind == 0)+        .map(|reference| reference.target)+}++fn default_ref_name(refs: &[RefInfo]) -> Option<String> {+    for reference in refs {+        if reference.kind == 0 && matches!(reference.name.as_str(), "main" | "master") {+            return Some(reference.name.clone());+        }+    }+    refs.iter()+        .find(|reference| reference.kind == 0)+        .map(|reference| reference.name.clone())+}++fn set_bookmark(view: &mut crate::object::view::View, name: &str, target: Id) {+    ops::set_bookmark_target(view, name.as_bytes(), target);+}++fn set_tag(view: &mut crate::object::view::View, name: &str, target: Id) {+    if let Some(index) = ops::find_tag(view, name.as_bytes()) {+        view.tags[index].target = target;+    } else {+        view.tags.push(crate::object::view::TagRef {+            name: name.as_bytes().to_vec(),+            target,+        });+    }+}++fn set_remote_ref(view: &mut crate::object::view::View, remote: &str, name: &str, target: Id) {+    if let Some(reference) = view.remote_refs.iter_mut().find(|reference| {+        reference.remote == remote.as_bytes() && reference.name == name.as_bytes()+    }) {+        reference.target = target;+    } else {+        view.remote_refs.push(crate::object::view::RemoteRef {+            remote: remote.as_bytes().to_vec(),+            name: name.as_bytes().to_vec(),+            target,+        });+    }+}++fn apply_refs(root: &Path, refs: &[RefInfo], remote: &str, clone: bool) -> Result<()> {+    let mut store = Store::open(root)?;+    let mut txn = Txn::begin(root, &mut store)?;+    for reference in refs {+        if reference.kind == 1 {+            set_tag(txn.view_mut(), &reference.name, reference.target);+        } else if clone {+            set_bookmark(txn.view_mut(), &reference.name, reference.target);+        } else {+            set_remote_ref(txn.view_mut(), remote, &reference.name, reference.target);+            if ops::find_bookmark(txn.view(), reference.name.as_bytes()).is_none() {+                set_bookmark(txn.view_mut(), &reference.name, reference.target);+            }+        }+    }+    ops::rebuild_heads(txn.view_mut());+    if clone && let Some(target) = default_target(refs) {+        let child = create_working_copy(&mut txn, &mut store, target)?;+        ops::set_workspace(txn.view_mut(), child);+        ops::rebuild_heads(txn.view_mut());+    }+    txn.finish(if clone { "clone" } else { "fetch" })?;+    if clone {+        if let Some(name) = default_ref_name(refs) {+            core::set_current_bookmark(root, &name);+        } else {+            core::clear_current_bookmark(root);+        }+    }+    Ok(())+}++fn create_working_copy(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {+    let loaded = graph::load_commit(store, parent)?+        .ok_or_else(|| Error::new("cannot read parent commit"))?;+    let signature = crate::identity::signature(store.root());+    let commit = Commit {+        version: 1,+        parents: vec![parent],+        root_tree: loaded.root_tree,+        change_id: crate::identity::random_change_id(),+        author: signature.clone(),+        committer: signature,+        message: Vec::new(),+        renames_state: commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))+}++fn clone(arguments: &[String]) -> Result<u8> {+    let mut url = String::new();+    let mut path = String::new();+    let mut policy = "head".to_string();+    let mut key_name = String::new();+    let mut pin = String::new();+    for argument in arguments {+        if let Some(value) = argument.strip_prefix("-blobs:") {+            policy = value.to_string();+        } else if let Some(value) = argument.strip_prefix("-key:") {+            key_name = value.to_string();+        } else if let Some(value) = argument.strip_prefix("-pin:") {+            pin = value.to_string();+        } else if core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if url.is_empty() {+            url = argument.clone();+        } else {+            path = argument.clone();+        }+    }+    if url.is_empty() {+        return Err(Error::new("clone requires a URL"));+    }+    let parsed = messages::parse_url(&url).ok_or_else(|| Error::new("unsupported URL"))?;+    if path.is_empty() {+        path = last_segment(&parsed.path);+    }+    let destination = PathBuf::from(&path);+    if destination.exists() {+        if !destination.is_dir() {+            return Err(Error::new(format!(+                "destination already exists and is not a directory: {path}"+            )));+        }+        if !core::list_directory(&destination).is_empty() {+            return Err(Error::new(format!(+                "destination directory is not empty: {path}"+            )));+        }+    }+    let root = layout::init(&destination).map_err(|_| Error::new("cannot create repository"))?;+    if key_name.is_empty() {+        key_name = crypto::key_for_url(&url).unwrap_or_default();+    }+    core::repo_config_set(&root, &remote_key("o", "url"), &url);+    if !key_name.is_empty() {+        core::repo_config_set(&root, &remote_key("o", "key"), &key_name);+    }+    if !pin.is_empty() {+        core::repo_config_set(&root, &remote_key("o", "tls-pin"), &pin);+    }+    core::repo_config_set(&root, "remote.default", "o");+    let repo_name = messages::url_repo_name(&url);+    let mut client = Client::connect(&url, &key_name, &repo_name, &pin)?;+    let refs = client.list_refs()?;+    let wants: Vec<Id> = refs.iter().map(|reference| reference.target).collect();+    if wants.is_empty() {+        output::info_prefix();+        println!("cloned empty repository into {path}");+        return Ok(0);+    }+    client.negotiate(&wants, &[])?;+    client.fetch_skeleton(&root, &wants)?;+    apply_refs(&root, &refs, "o", true)?;+    core::repo_config_set(&root, "promisor", "o");+    let mut store = Store::open(&root)?;+    if let Some(view) = ops::current_view(&root, &mut store)?+        && let Some(working) = ops::working_copy_id(&view)+        && let Some(commit) = graph::load_commit(&mut store, working)?+    {+        checkout::materialize(&root, &mut store, None, commit.root_tree)?;+    }+    if policy == "none" {+        output::info_prefix();+        println!("cloned metadata only; blobs are promised");+    }+    output::info_prefix();+    println!("cloned into {path}");+    Ok(0)+}++fn fetch(arguments: &[String]) -> Result<u8> {+    let mut remote_name = String::new();+    let mut explicit_key = String::new();+    let mut explicit_pin = String::new();+    let mut path = ".".to_string();+    let mut have_remote = false;+    for argument in arguments {+        if let Some(value) = argument.strip_prefix("-key:") {+            explicit_key = value.to_string();+        } else if let Some(value) = argument.strip_prefix("-pin:") {+            explicit_pin = value.to_string();+        } else if core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if !have_remote {+            remote_name = argument.clone();+            have_remote = true;+        } else {+            path = argument.clone();+        }+    }+    let root =+        layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;+    if !have_remote {+        remote_name = active_remote(&root);+    }+    let url = remote_url(&root, &remote_name).ok_or_else(|| Error::new("unknown remote"))?;+    let key = if !explicit_key.is_empty() {+        explicit_key+    } else {+        remote_key_name(&root, &remote_name)+    };+    let repo_name = messages::url_repo_name(&url);+    let pin = if !explicit_pin.is_empty() {+        explicit_pin+    } else {+        core::repo_config_value(&root, &remote_key(&remote_name, "tls-pin")).unwrap_or_default()+    };+    let mut client = Client::connect(&url, &key, &repo_name, &pin)?;+    let refs = client.list_refs()?;+    let haves = ops::read_heads(&root)?;+    let wants: Vec<Id> = refs.iter().map(|reference| reference.target).collect();+    if wants.is_empty() {+        output::info_prefix();+        println!("no refs to fetch");+        return Ok(0);+    }+    client.negotiate(&wants, &haves)?;+    client.fetch_skeleton(&root, &wants)?;+    apply_refs(&root, &refs, &remote_name, false)?;+    output::info_prefix();+    println!("fetched from {remote_name}");+    Ok(0)+}++fn pull(arguments: &[String]) -> Result<u8> {+    let mut remote_name = String::new();+    let mut path = ".".to_string();+    let mut have_remote = false;+    for argument in arguments {+        if core::is_flag(argument) {+            if argument.starts_with("-key:") || argument.starts_with("-pin:") {+                continue;+            }+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if !have_remote {+            remote_name = argument.clone();+            have_remote = true;+        } else {+            path = argument.clone();+        }+    }+    let mut forward: Vec<String> = arguments+        .iter()+        .filter(|argument| argument.starts_with("-key:") || argument.starts_with("-pin:"))+        .cloned()+        .collect();+    if have_remote {+        forward.push(remote_name.clone());+    }+    if path != "." {+        forward.push(path.clone());+    }+    fetch(&forward)?;+    let root =+        layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;+    if !have_remote {+        remote_name = active_remote(&root);+    }+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let bookmark_name = core::current_bookmark_name(&root)+        .ok_or_else(|| Error::new("no current bookmark; check out a bookmark before pulling"))?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let Some(index) = ops::find_bookmark(&view, bookmark_name.as_bytes()) else {+        return Err(Error::new(format!(+            "current bookmark is missing: {bookmark_name}"+        )));+    };+    let bookmark = &view.bookmarks[index];+    let Some(local_target) = bookmark.targets.adds.first().copied().flatten() else {+        return Err(Error::new(format!(+            "current bookmark is conflicted: {bookmark_name}"+        )));+    };+    let remote_target = view+        .remote_refs+        .iter()+        .find(|reference| {+            reference.remote == remote_name.as_bytes() && reference.name == bookmark_name.as_bytes()+        })+        .map(|reference| reference.target)+        .ok_or_else(|| {+            Error::new(format!(+                "no {remote_name}/{bookmark_name} on remote {remote_name}"+            ))+        })?;+    if let Some(working) = ops::working_copy_id(&view)+        && let Some(loaded) = graph::load_commit(&mut store, working)?+    {+        if graph::tree_conflicted(&mut store, loaded.root_tree)? {+            return Err(Error::new("working copy has unresolved conflicts"));+        }+        if graph::has_changes(&mut store, &loaded)? {+            return Err(Error::new(+                "working copy has uncommitted changes; commit them before pulling",+            ));+        }+    }+    if local_target == remote_target {+        output::info_prefix();+        println!("already up to date with {remote_name}/{bookmark_name}");+        return checkout::run(&root, &bookmark_name).map(|_| 0);+    }+    if !engine_is_ancestor(&mut store, local_target, remote_target)? {+        if engine_is_ancestor(&mut store, remote_target, local_target)? {+            output::info_prefix();+            println!("local {bookmark_name} is ahead of {remote_name}/{bookmark_name}");+            return Ok(0);+        }+        return Err(Error::new(format!(+            "local {bookmark_name} and {remote_name}/{bookmark_name} have diverged; use 'vn merge {remote_name}/{bookmark_name}' or 'vn rebase'"+        )));+    }+    let mut txn = Txn::begin(&root, &mut store)?;+    ops::set_bookmark_target(txn.view_mut(), bookmark_name.as_bytes(), remote_target);+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("pull {bookmark_name} from {remote_name}"))?;+    store.refresh()?;+    checkout::run(&root, &bookmark_name)?;+    output::info_prefix();+    println!("pulled {bookmark_name} from {remote_name}");+    Ok(0)+}++fn engine_is_ancestor(store: &mut Store, ancestor: Id, descendant: Id) -> Result<bool> {+    if ancestor == descendant {+        return Ok(true);+    }+    Ok(graph::collect_commits(store, &[descendant])?.contains(&ancestor))+}++fn collect_commits_until(store: &mut Store, start: &[Id], stop: &HashSet<Id>) -> Result<Vec<Id>> {+    let mut output = Vec::new();+    let mut stack = Vec::new();+    let mut seen = HashSet::new();+    for id in start {+        if !stop.contains(id) && seen.insert(*id) {+            stack.push(*id);+        }+    }+    while let Some(id) = stack.pop() {+        output.push(id);+        let Some(commit) = graph::load_commit(store, id)? else {+            continue;+        };+        for parent in commit.parents {+            if !stop.contains(&parent) && seen.insert(parent) {+                stack.push(parent);+            }+        }+    }+    Ok(output)+}++#[derive(Default)]+struct ObjectWalk {+    blobs: HashSet<Id>,+    conflicts: HashSet<Id>,+    trees: HashSet<Id>,+    objects: HashSet<Id>,+    output: Vec<Id>,+}++impl ObjectWalk {+    fn add_object(&mut self, id: Id) {+        if self.objects.insert(id) {+            self.output.push(id);+        }+    }++    fn walk_blob(&mut self, store: &mut Store, id: Id) -> Result<()> {+        if !self.blobs.insert(id) {+            return Ok(());+        }+        self.add_object(id);+        let Some(body) = store.body(id, TYPE_BLOB)? else {+            return Ok(());+        };+        let Ok(blob) = blob::decode(&body) else {+            return Ok(());+        };+        match blob.form {+            BlobForm::Leaf => {+                for entry in blob.entries {+                    self.add_object(entry.id);+                }+            }+            BlobForm::Interior => {+                for entry in blob.entries {+                    self.walk_blob(store, entry.id)?;+                }+            }+            BlobForm::Inline => {}+        }+        Ok(())+    }++    fn walk_conflict(&mut self, store: &mut Store, id: Id) -> Result<()> {+        if !self.conflicts.insert(id) {+            return Ok(());+        }+        self.add_object(id);+        let Some(body) = store.body(id, crate::object::TYPE_CONFLICT)? else {+            return Ok(());+        };+        let Ok(conflict) = crate::object::conflict::decode(&body) else {+            return Ok(());+        };+        for value in conflict.adds.iter().chain(conflict.removes.iter()) {+            if let Some(target) = value.target {+                self.walk_value(store, value.kind, target)?;+            }+        }+        Ok(())+    }++    fn walk_value(&mut self, store: &mut Store, kind: u8, id: Id) -> Result<()> {+        match kind {+            KIND_SUBTREE => self.walk_tree(store, id)?,+            tree::KIND_CONFLICT => self.walk_conflict(store, id)?,+            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {+                self.walk_blob(store, id)?;+            }+            _ => {}+        }+        Ok(())+    }++    fn walk_entry(&mut self, store: &mut Store, entry: &tree::TreeEntry) -> Result<()> {+        match entry.kind {+            KIND_SUBTREE => self.walk_tree(store, entry.target)?,+            tree::KIND_CONFLICT => self.walk_conflict(store, entry.target)?,+            tree::KIND_SUBMODULE => {}+            _ => self.walk_blob(store, entry.target)?,+        }+        Ok(())+    }++    fn walk_tree(&mut self, store: &mut Store, id: Id) -> Result<()> {+        if !self.trees.insert(id) {+            return Ok(());+        }+        self.add_object(id);+        let Some(body) = store.body(id, TYPE_TREE)? else {+            return Ok(());+        };+        let Ok(tree) = tree::decode(&body) else {+            return Ok(());+        };+        for entry in &tree.entries {+            self.walk_entry(store, entry)?;+        }+        Ok(())+    }++    fn walk_tree_delta(&mut self, store: &mut Store, id: Id, old: Option<Id>) -> Result<()> {+        if old == Some(id) {+            return Ok(());+        }+        if !self.trees.insert(id) {+            return Ok(());+        }+        self.add_object(id);+        let Some(body) = store.body(id, TYPE_TREE)? else {+            return Ok(());+        };+        let Ok(tree) = tree::decode(&body) else {+            return Ok(());+        };+        let old_tree = match old {+            Some(old) => match store.body(old, TYPE_TREE)? {+                Some(body) => tree::decode(&body).ok(),+                None => None,+            },+            None => None,+        };+        let Some(old_tree) = old_tree else {+            for entry in &tree.entries {+                self.walk_entry(store, entry)?;+            }+            return Ok(());+        };+        let mut old_index = 0;+        for entry in &tree.entries {+            while old_index < old_tree.entries.len()+                && old_tree.entries[old_index].name < entry.name+            {+                old_index += 1;+            }+            if old_index >= old_tree.entries.len() || old_tree.entries[old_index].name != entry.name+            {+                self.walk_entry(store, entry)?;+                continue;+            }+            let old_entry = &old_tree.entries[old_index];+            old_index += 1;+            if old_entry.kind == entry.kind && old_entry.target == entry.target {+                continue;+            }+            if entry.kind == KIND_SUBTREE && old_entry.kind == KIND_SUBTREE {+                self.walk_tree_delta(store, entry.target, Some(old_entry.target))?;+            } else if entry.kind != tree::KIND_SUBMODULE {+                self.walk_entry(store, entry)?;+            }+        }+        Ok(())+    }+}++fn objects_for_commit_deltas(+    store: &mut Store,+    commits: &[Id],+    progress: Option<&crate::core::Progress>,+) -> Result<Vec<Id>> {+    let mut walk = ObjectWalk::default();+    for id in commits {+        walk.add_object(*id);+        if let Some(commit) = graph::load_commit(store, *id)? {+            let mut old_tree = None;+            let mut tree_covered = false;+            for parent_id in &commit.parents {+                let Some(parent) = graph::load_commit(store, *parent_id)? else {+                    continue;+                };+                if parent.root_tree == commit.root_tree {+                    tree_covered = true;+                    break;+                }+                if old_tree.is_none() {+                    old_tree = Some(parent.root_tree);+                }+            }+            if !tree_covered {+                walk.walk_tree_delta(store, commit.root_tree, old_tree)?;+            }+        }+        if let Some(progress) = progress {+            progress.advance(1);+        }+    }+    Ok(walk.output)+}++fn missing_objects(client: &mut Client, objects: &[Id]) -> Vec<Id> {+    const BATCH: usize = 100_000;+    let mut missing = Vec::new();+    for batch in objects.chunks(BATCH) {+        let Ok(bits) = client.have_query(batch) else {+            return objects.to_vec();+        };+        for (index, id) in batch.iter().enumerate() {+            if bits.get(index).copied().unwrap_or(0) == 0 {+                missing.push(*id);+            }+        }+    }+    missing+}++fn push(arguments: &[String]) -> Result<u8> {+    let mut remote_name = String::new();+    let mut bookmark = String::new();+    let mut explicit_key = String::new();+    let mut explicit_pin = String::new();+    let mut path = ".".to_string();+    let mut have_remote = false;+    for argument in arguments {+        if let Some(value) = argument.strip_prefix("-key:") {+            explicit_key = value.to_string();+        } else if let Some(value) = argument.strip_prefix("-pin:") {+            explicit_pin = value.to_string();+        } else if core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if !have_remote {+            remote_name = argument.clone();+            have_remote = true;+        } else if bookmark.is_empty() {+            bookmark = argument.clone();+        } else {+            path = argument.clone();+        }+    }+    let root =+        layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;+    if !have_remote {+        remote_name = active_remote(&root);+    }+    let url = remote_url(&root, &remote_name).ok_or_else(|| Error::new("unknown remote"))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    if bookmark.is_empty() {+        bookmark = core::current_bookmark_name(&root).unwrap_or_else(|| "master".to_string());+    }+    let bookmark_target = ops::find_bookmark(&view, bookmark.as_bytes())+        .and_then(|index| {+            view.bookmarks[index]+                .targets+                .adds+                .first()+                .copied()+                .flatten()+        })+        .ok_or_else(|| Error::new(format!("no such bookmark: {bookmark}")))?;+    let key = if !explicit_key.is_empty() {+        explicit_key+    } else {+        remote_key_name(&root, &remote_name)+    };+    let repo_name = messages::url_repo_name(&url);+    let pin = if !explicit_pin.is_empty() {+        explicit_pin+    } else {+        core::repo_config_value(&root, &remote_key(&remote_name, "tls-pin")).unwrap_or_default()+    };+    let mut client = Client::connect(&url, &key, &repo_name, &pin)?;+    let remote_refs = client.list_refs()?;+    let mut updates = Vec::new();+    let remote_bookmark = remote_refs+        .iter()+        .find(|reference| reference.kind == 0 && reference.name == bookmark)+        .map(|reference| reference.target);+    if remote_bookmark != Some(bookmark_target) {+        updates.push(UpdateRef {+            name: bookmark.clone(),+            expected: remote_bookmark,+            target: Some(bookmark_target),+        });+    }+    let mut tag_updates = 0usize;+    for tag in &view.tags {+        let name = String::from_utf8_lossy(&tag.name).into_owned();+        let remote = remote_refs+            .iter()+            .find(|reference| reference.kind == 1 && reference.name == name)+            .map(|reference| reference.target);+        if remote == Some(tag.target) {+            continue;+        }+        updates.push(UpdateRef {+            name: format!("refs/tags/{name}"),+            expected: remote,+            target: Some(tag.target),+        });+        tag_updates += 1;+    }+    if updates.is_empty() {+        output::info_prefix();+        println!("nothing to push, everything is up to date");+        return Ok(0);+    }+    let remote_commits: HashSet<Id> = remote_refs+        .iter()+        .map(|reference| reference.target)+        .collect();+    let mut roots = Vec::with_capacity(1 + view.tags.len());+    roots.push(bookmark_target);+    for tag in &view.tags {+        roots.push(tag.target);+    }+    let commits = collect_commits_until(&mut store, &roots, &remote_commits)?;+    let mut objects = Vec::new();+    if !commits.is_empty() {+        let collecting = crate::core::Progress::new("collecting objects", commits.len());+        objects = objects_for_commit_deltas(&mut store, &commits, Some(&collecting))?;+        collecting.finish();+    }+    if !objects.is_empty() {+        let missing = missing_objects(&mut client, &objects);+        if !missing.is_empty() {+            let pushing = crate::core::Progress::new("pushing objects", missing.len());+            client.push_objects(&root, &missing, Some(&pushing))?;+            pushing.finish();+        }+    }+    client.update_refs(&updates)?;+    output::info_prefix();+    println!("pushed {bookmark}");+    if tag_updates > 0 {+        output::info_prefix();+        println!("pushed {tag_updates} tag(s)");+    }+    Ok(0)+}++fn gg(arguments: &[String]) -> Result<u8> {+    let first = arguments+        .iter()+        .find(|argument| !core::is_flag(argument))+        .cloned()+        .unwrap_or_default();+    if first.contains("://") {+        return clone(arguments);+    }+    let Some(root) = layout::discover(Path::new(".")).ok() else {+        return clone(arguments);+    };+    let mut forwarded = arguments.to_vec();+    if first.is_empty() {+        forwarded.push(active_remote(&root));+    }+    fetch(&forwarded)+}++fn serve(arguments: &[String]) -> Result<u8> {+    let mut repo = ".".to_string();+    let mut stdio = false;+    let mut listen = String::new();+    let mut root = ".".to_string();+    let mut cert = String::new();+    let mut key = String::new();+    let mut quota = 0u64;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if argument == "-stdio" {+            stdio = true;+            if index + 1 < arguments.len() && !core::is_flag(&arguments[index + 1]) {+                index += 1;+                repo = arguments[index].clone();+            }+        } else if argument == "-listen" {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new("-listen requires an address"));+            }+            listen = arguments[index].clone();+        } else if argument == "-root" {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new("-root requires a directory"));+            }+            root = arguments[index].clone();+        } else if argument == "-tls-cert" {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new("-tls-cert requires a path"));+            }+            cert = arguments[index].clone();+        } else if argument == "-tls-key" {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new("-tls-key requires a path"));+            }+            key = arguments[index].clone();+        } else if argument == "-quota" {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new("-quota requires a byte count"));+            }+            quota = arguments[index]+                .parse()+                .map_err(|_| Error::new("-quota requires a byte count"))?;+        } else if let Some(value) = argument.strip_prefix("-quota:") {+            quota = value+                .parse()+                .map_err(|_| Error::new("-quota requires a byte count"))?;+        } else if core::is_flag(argument) {+            return Err(Error::new(format!("unknown serve option: {argument}")));+        } else {+            repo = argument.clone();+        }+        index += 1;+    }+    if stdio {+        let root =+            layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?;+        crate::server::serve_stdio(&root, quota)?;+        return Ok(0);+    }+    if listen.is_empty() {+        return Err(Error::new("serve requires -stdio or -listen"));+    }+    if cert.is_empty() || key.is_empty() {+        return Err(Error::new("TLS requires -tls-cert and -tls-key"));+    }+    let root = std::fs::canonicalize(&root)+        .map_err(|_| Error::new("cannot open the server root directory"))?;+    if !root.is_dir() {+        return Err(Error::new("the server root is not a directory"));+    }+    crate::server::serve_listen(&listen, &root, &cert, &key, quota)?;+    Ok(0)+}++fn key(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        return Err(Error::new("key requires a subcommand"));+    };+    match sub.as_str() {+        "generate" => {+            let name = arguments+                .get(1)+                .cloned()+                .unwrap_or_else(|| "default".to_string());+            let key =+                crypto::generate_key(&name).ok_or_else(|| Error::new("cannot generate key"))?;+            println!("name: {}", key.name);+            println!("public key: {}", crypto::format_public_key(&key.public_key));+            println!("fingerprint: {}", key.fingerprint);+            Ok(0)+        }+        "show" => {+            let name = arguments.get(1).cloned().unwrap_or_default();+            let key = crypto::load_key(&name).ok_or_else(|| Error::new("no such key"))?;+            println!("name: {}", key.name);+            println!("public key: {}", crypto::format_public_key(&key.public_key));+            println!("fingerprint: {}", key.fingerprint);+            Ok(0)+        }+        "list" | "ls" => {+            for name in crypto::list_key_names() {+                println!("{name}");+            }+            Ok(0)+        }+        _ => Err(Error::new(format!("unknown key subcommand: {sub}"))),+    }+}++fn auth(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        return Err(Error::new("auth requires a subcommand"));+    };+    match sub.as_str() {+        "use" => {+            let name = arguments.get(1).cloned().unwrap_or_default();+            if name.is_empty() {+                return Err(Error::new("auth use requires a key name"));+            }+            if !crypto::load_key(&name).is_some() {+                return Err(Error::new("no such key"));+            }+            let target = arguments+                .get(2)+                .map(|value| crypto::normalize_target(value))+                .unwrap_or_else(|| "default".to_string());+            if !crypto::set_key(&target, &name) {+                return Err(Error::new("cannot store key mapping"));+            }+            Ok(0)+        }+        "list" | "ls" => {+            for line in crypto::list_credentials() {+                print!("{line}");+            }+            Ok(0)+        }+        "remove" | "rm" => {+            let target = arguments+                .get(1)+                .map(|value| crypto::normalize_target(value))+                .unwrap_or_else(|| "default".to_string());+            if !crypto::remove_key(&target) {+                return Err(Error::new("no such key mapping"));+            }+            Ok(0)+        }+        _ => Err(Error::new(format!("unknown auth subcommand: {sub}"))),+    }+}++fn read_public_key(argument: &str) -> Option<crypto::PublicKey> {+    if argument.starts_with("ed25519:") {+        return crypto::parse_public_key(argument);+    }+    let data = core::read_file_opt(Path::new(argument), 0)?;+    let text = String::from_utf8_lossy(&data);+    crypto::parse_public_key(text.trim())+}++fn access(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        return Err(Error::new("access requires a subcommand"));+    };+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    match sub.as_str() {+        "add" => {+            let mut role = 1u8;+            let mut key = String::new();+            let mut name = String::new();+            let mut index = 1;+            while index < arguments.len() {+                match arguments[index].as_str() {+                    "-role" => {+                        index += 1;+                        if index >= arguments.len() {+                            return Err(Error::new("-role requires read or write"));+                        }+                        role = match arguments[index].as_str() {+                            "write" => 2,+                            "read" => 1,+                            _ => return Err(Error::new("-role requires read or write")),+                        };+                    }+                    "-key" => {+                        index += 1;+                        if index >= arguments.len() {+                            return Err(Error::new("-key requires a public key"));+                        }+                        key = arguments[index].clone();+                    }+                    "-name" => {+                        index += 1;+                        if index >= arguments.len() {+                            return Err(Error::new("-name requires a value"));+                        }+                        name = arguments[index].clone();+                    }+                    value if core::is_flag(value) => {+                        return Err(Error::new(format!("unknown flag: {value}")));+                    }+                    value => {+                        if key.is_empty() {+                            key = value.to_string();+                        } else if name.is_empty() {+                            name = value.to_string();+                        }+                    }+                }+                index += 1;+            }+            let public_key =+                read_public_key(&key).ok_or_else(|| Error::new("invalid public key"))?;+            if !crypto::add_access(&root, role, &public_key, &name) {+                return Err(Error::new("cannot add access entry"));+            }+            output::info_prefix();+            println!("added access entry");+            Ok(0)+        }+        "remove" | "rm" => {+            let mut fingerprint = String::new();+            let mut name = String::new();+            for argument in &arguments[1..] {+                if let Some(value) = argument.strip_prefix("-fingerprint:") {+                    fingerprint = value.to_string();+                } else if let Some(value) = argument.strip_prefix("-name:") {+                    name = value.to_string();+                } else if fingerprint.is_empty() {+                    fingerprint = argument.clone();+                } else {+                    name = argument.clone();+                }+            }+            if !crypto::remove_access(&root, &fingerprint, &name) {+                return Err(Error::new("no matching access entry"));+            }+            Ok(0)+        }+        "anonymous" => {+            let value = arguments.get(1).map(|value| value.as_str()).unwrap_or("");+            let enabled = matches!(value, "on" | "true" | "yes");+            if !crypto::set_anonymous(&root, enabled) {+                return Err(Error::new("cannot write access file"));+            }+            Ok(0)+        }+        "list" | "ls" => {+            let access = crypto::load_access(&root);+            if !access.valid {+                return Err(Error::new("invalid access file"));+            }+            if access.anonymous_read {+                println!("anonymous read");+            }+            for entry in &access.entries {+                println!(+                    "allow {} {} {}",+                    if entry.role == 2 { "write" } else { "read" },+                    crypto::format_public_key(&entry.public_key),+                    entry.name+                );+            }+            Ok(0)+        }+        _ => Err(Error::new(format!("unknown access subcommand: {sub}"))),+    }+}++fn whoami(arguments: &[String]) -> Result<u8> {+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let remote = arguments+        .first()+        .cloned()+        .unwrap_or_else(|| active_remote(&root));+    let url = remote_url(&root, &remote).ok_or_else(|| Error::new("unknown remote"))?;+    let key = remote_key_name(&root, &remote);+    let repo_name = messages::url_repo_name(&url);+    let pin = core::repo_config_value(&root, &remote_key(&remote, "tls-pin")).unwrap_or_default();+    let mut client = Client::connect(&url, &key, &repo_name, &pin)?;+    let (role, _) = client.whoami()?;+    println!("role: {}", messages::role_name(role));+    Ok(0)+}++pub fn git(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        return Err(Error::new("git requires a subcommand"));+    };+    match sub.as_str() {+        "import" => {+            let mut source = None;+            let mut remote = String::new();+            let mut path = ".".to_string();+            for argument in &arguments[1..] {+                if let Some(value) = argument.strip_prefix("-source:") {+                    source = Some(value.to_string());+                } else if let Some(value) = argument.strip_prefix("-remote:") {+                    remote = value.to_string();+                } else if !core::is_flag(argument) {+                    path = argument.clone();+                }+            }+            let root = layout::discover(Path::new(&path))+                .map_err(|_| Error::new("not a veins repository"))?;+            if let Some(source) = source {+                let prepared = crate::git::prepare_mirror(&root, &source);+                if prepared != 0 {+                    return Err(Error::new("cannot prepare git mirror"));+                }+            }+            let status = crate::git::import(&root);+            if status != 0 {+                return Ok(1);+            }+            if !remote.is_empty() {+                crate::git::configure_remote(&root, &remote, "o");+            }+            Ok(0)+        }+        "materialize" => {+            let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());+            let root = layout::discover(Path::new(&path))+                .map_err(|_| Error::new("not a veins repository"))?;+            Ok(crate::git::materialize(&root) as u8)+        }+        "export" => {+            let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());+            let root = layout::discover(Path::new(&path))+                .map_err(|_| Error::new("not a veins repository"))?;+            Ok(crate::git::export(&root) as u8)+        }+        "fetch" => {+            let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());+            let root = layout::discover(Path::new(&path))+                .map_err(|_| Error::new("not a veins repository"))?;+            Ok(crate::git::fetch(&root, "origin") as u8)+        }+        "remote" => {+            let sub = arguments.get(1).map(|value| value.as_str()).unwrap_or("");+            let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+            match sub {+                "add" => {+                    let name = arguments.get(2).cloned().unwrap_or_default();+                    let url = arguments.get(3).cloned().unwrap_or_default();+                    Ok(crate::git::mirror_remote(&root, "add", &name, &url) as u8)+                }+                "remove" | "rm" => {+                    let name = arguments.get(2).cloned().unwrap_or_default();+                    Ok(crate::git::mirror_remote(&root, "remove", &name, "") as u8)+                }+                "list" | "ls" => {+                    for name in crate::git::mirror_remote_list(&root) {+                        println!("{name}");+                    }+                    Ok(0)+                }+                _ => Err(Error::new("unknown git remote subcommand")),+            }+        }+        "mirror" => {+            let action = arguments.get(1).map(|value| value.as_str()).unwrap_or("");+            let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+            let force = !arguments.iter().any(|argument| argument == "-no-force");+            let prune = arguments.iter().any(|argument| argument == "-prune");+            let dry_run = arguments.iter().any(|argument| argument == "-dry-run");+            let options = crate::git::MirrorOptions {+                force,+                prune,+                dry_run,+            };+            match action {+                "push" | "psh" => {+                    let remote = arguments+                        .iter()+                        .skip(2)+                        .find(|argument| !core::is_flag(argument))+                        .cloned()+                        .or_else(|| crate::git::mirror_remote_list(&root).into_iter().next())+                        .unwrap_or_else(|| "origin".to_string());+                    let status = crate::git::mirror_push(&root, &remote, &options);+                    if status == 0+                        && !dry_run+                        && let Some(view) = crate::store::ops::current_view(+                            &root,+                            &mut crate::store::Store::open(&root)?,+                        )+                        .ok()+                        .flatten()+                    {+                        println!("info: mirrored {} bookmark(s)", view.bookmarks.len());+                    }+                    Ok(status as u8)+                }+                "pt" | "tag" => {+                    let tag = arguments.get(2).cloned().unwrap_or_default();+                    let remote = arguments+                        .get(3)+                        .cloned()+                        .unwrap_or_else(|| "origin".to_string());+                    let mut store = Store::open(&root)?;+                    let view = ops::current_view(&root, &mut store)?.unwrap_or_default();+                    if ops::find_tag(&view, tag.as_bytes()).is_none() {+                        return Err(Error::new(format!("unknown tag: {tag}")));+                    }+                    let status = crate::git::mirror_tag(&root, &remote, &tag, &options);+                    Ok(status as u8)+                }+                _ => Err(Error::new("unknown git mirror subcommand")),+            }+        }+        "push" => {+            let remote = arguments+                .get(1)+                .cloned()+                .unwrap_or_else(|| "origin".to_string());+            let bookmark = arguments+                .get(2)+                .cloned()+                .unwrap_or_else(|| "master".to_string());+            let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+            Ok(crate::git::push(&root, &remote, &bookmark) as u8)+        }+        _ => Err(Error::new(format!("unknown git subcommand: {sub}"))),+    }+}--- /dev/null+++ b/veins/src/cli/output.rs@@ -0,0 +1,117 @@+use crate::core;++pub fn enabled() -> bool {+    core::colors_enabled()+}++fn style(text: &str, code: &str) -> String {+    if enabled() {+        format!("\x1b[{code}m{text}\x1b[0m")+    } else {+        text.to_string()+    }+}++pub fn print_styled(code: &str, text: &str) {+    if enabled() {+        print!("\x1b[{code}m{text}\x1b[0m");+    } else {+        print!("{text}");+    }+}++pub fn error_prefix() {+    if enabled() {+        print!("\x1b[1m\x1b[31merror\x1b[0m: ");+    } else {+        print!("error: ");+    }+}++pub fn warning_prefix() {+    if enabled() {+        print!("\x1b[1m\x1b[33mwarning\x1b[0m: ");+    } else {+        print!("warning: ");+    }+}++pub fn info_prefix() {+    print!("{}: ", style("info", "36"));+}++pub fn red(text: &str) -> String {+    style(text, "31")+}++pub fn green(text: &str) -> String {+    style(text, "32")+}++pub fn cyan(text: &str) -> String {+    style(text, "36")+}++pub fn dim(text: &str) -> String {+    style(text, "2")+}++pub fn bold_cyan(text: &str) -> String {+    if enabled() {+        format!("\x1b[1m\x1b[96m{text}\x1b[0m")+    } else {+        text.to_string()+    }+}++pub fn print_cell(text: &str, width: usize) {+    print!("{text}");+    for _ in text.chars().count()..width {+        print!(" ");+    }+}++pub fn open_repo() -> Option<std::path::PathBuf> {+    crate::store::layout::discover(std::path::Path::new(".")).ok()+}++pub fn status_path(path: &[u8], cwd_rel: &str) -> String {+    let path = String::from_utf8_lossy(path);+    if cwd_rel.is_empty() {+        return path.into_owned();+    }+    let current: Vec<&str> = cwd_rel+        .split('/')+        .filter(|value| !value.is_empty())+        .collect();+    let target: Vec<&str> = path.split('/').collect();+    let mut common = 0;+    while common < current.len() && common < target.len() && current[common] == target[common] {+        common += 1;+    }+    let mut output = String::new();+    for _ in common..current.len() {+        output.push_str("../");+    }+    output.push_str(&target[common..].join("/"));+    output+}++pub fn join_args(parts: &[String]) -> String {+    parts.join(" ")+}++pub fn message_is_blank(parts: &[String]) -> bool {+    parts+        .iter()+        .flat_map(|part| part.bytes())+        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))+}++pub fn pager_output(root: &std::path::Path, text: &str, pager: bool) {+    if pager && core::stdout_is_terminal() {+        core::run_pager(root, text);+    } else {+        print!("{text}");+    }+}--- /dev/null+++ b/veins/src/cli/refs.rs@@ -0,0 +1,577 @@+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::object::view::{Bookmark, TagRef};+use crate::store::Txn;+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::snapshot;++use super::output;++fn valid_ref_name(name: &str) -> bool {+    if name.is_empty() || name.len() > crate::object::MAX_NAME_LEN {+        return false;+    }+    let bytes = name.as_bytes();+    if matches!(bytes[0], b'-' | b'/' | b'.') || matches!(bytes[bytes.len() - 1], b'/' | b'.') {+        return false;+    }+    for byte in bytes {+        if *byte == 0+            || *byte == b' '+            || *byte < 32+            || *byte == 127+            || matches!(*byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\')+        {+            return false;+        }+    }+    !name.contains("..")+        && !name.contains("@{")+        && !name.contains("//")+        && name != "@"+        && !name.ends_with(".lock")+}++fn short(id: crate::object::id::Id) -> String {+    id.short()+}++pub fn bookmark(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        bookmark_usage();+        return Ok(1);+    };+    match sub.as_str() {+        "set" | "mv" => bookmark_set(&arguments[1..]),+        "rename" | "move" => bookmark_rename(&arguments[1..]),+        "ls" => bookmark_list(&arguments[1..]),+        "rm" => bookmark_remove(&arguments[1..]),+        "help" | "-h" => {+            bookmark_usage();+            Ok(0)+        }+        _ => {+            output::error_prefix();+            println!("unknown bmk subcommand: {sub}");+            bookmark_usage();+            Ok(1)+        }+    }+}++fn bookmark_usage() {+    println!("usage: vn bmk <set|rename|ls|rm> ...");+    println!();+    println!("manage named, movable pointers to commits (branches)");+    println!();+    println!("subcommands:");+    println!("  set <name> [-rev <rev>]   create or move a bookmark (default: @)");+    println!("  mv <name> [-rev <rev>]    alias of set");+    println!("  rename <old> <new>        rename a bookmark");+    println!("  ls [-no-col-titles]       list bookmarks");+    println!("  rm <name>                 delete a bookmark");+}++fn bookmark_rename(arguments: &[String]) -> Result<u8> {+    let mut names = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            names.push(argument.clone());+        }+    }+    if names.len() != 2 {+        return Err(Error::new("bmk rename requires an old and a new name"));+    }+    let (old, new) = (&names[0], &names[1]);+    if !valid_ref_name(new) {+        return Err(Error::new(format!("invalid bookmark name: {new}")));+    }+    if old == new {+        return Err(Error::new("new bookmark name matches the old name"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let Some(index) = ops::find_bookmark(txn.view(), old.as_bytes()) else {+        return Err(Error::new(format!("no such bookmark: {old}")));+    };+    if ops::find_bookmark(txn.view(), new.as_bytes()).is_some() {+        return Err(Error::new(format!("bookmark already exists: {new}")));+    }+    let mut bookmark = txn.view_mut().bookmarks.remove(index);+    bookmark.name = new.as_bytes().to_vec();+    txn.view_mut().bookmarks.push(bookmark);+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("bookmark rename {old} {new}"))?;+    if core::current_bookmark_name(&root).is_some_and(|current| current == *old) {+        core::set_current_bookmark(&root, new);+    }+    output::info_prefix();+    println!("renamed bookmark {old} to {new}");+    Ok(0)+}++fn bookmark_set(arguments: &[String]) -> Result<u8> {+    let mut name = String::new();+    let mut revision = String::new();+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if name.is_empty() {+            name = argument.clone();+        } else if revision.is_empty() {+            revision = argument.clone();+        } else {+            return Err(Error::new("bmk set accepts a name and one revision"));+        }+        index += 1;+    }+    if name.is_empty() {+        return Err(Error::new("bmk set requires a name"));+    }+    if !valid_ref_name(&name) {+        return Err(Error::new(format!("invalid bookmark name: {name}")));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?.ok_or_else(|| {+        Error::new(if revision.is_empty() {+            "no working-copy commit"+        } else {+            "unknown revision"+        })+    })?;+    let mut changed = true;+    if let Some(existing) = ops::find_bookmark(txn.view(), name.as_bytes()) {+        let bookmark = &mut txn.view_mut().bookmarks[existing];+        if bookmark.targets.adds == vec![Some(target)] {+            changed = false;+        } else {+            bookmark.targets.adds = vec![Some(target)];+            bookmark.targets.removes.clear();+        }+    } else {+        txn.view_mut().bookmarks.push(Bookmark {+            name: name.as_bytes().to_vec(),+            targets: crate::object::view::TargetSet {+                adds: vec![Some(target)],+                removes: Vec::new(),+            },+        });+    }+    if !changed {+        core::set_current_bookmark(&root, &name);+        output::info_prefix();+        println!("bookmark {name} is already at {}", short(target));+        return Ok(0);+    }+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("bookmark set {name}"))?;+    core::set_current_bookmark(&root, &name);+    output::info_prefix();+    println!("bookmark {name} set to {}", short(target));+    Ok(0)+}++fn bookmark_remove(arguments: &[String]) -> Result<u8> {+    let mut name = String::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if !name.is_empty() {+            return Err(Error::new("bmk rm accepts exactly one name"));+        } else {+            name = argument.clone();+        }+    }+    if name.is_empty() {+        return Err(Error::new("bmk rm requires a name"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let Some(index) = ops::find_bookmark(txn.view(), name.as_bytes()) else {+        return Err(Error::new(format!("no such bookmark: {name}")));+    };+    txn.view_mut().bookmarks.remove(index);+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("bookmark delete {name}"))?;+    if core::current_bookmark_name(&root).is_some_and(|current| current == name) {+        core::clear_current_bookmark(&root);+    }+    output::info_prefix();+    println!("deleted bookmark {name}");+    Ok(0)+}++fn bookmark_list(arguments: &[String]) -> Result<u8> {+    let mut titles = true;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && argument == "-no-col-titles" {+            titles = false;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            return Err(Error::new("bmk ls takes no operands"));+        }+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let working_copy = ops::working_copy_id(&view);+    let mut name_width = 8;+    for bookmark in &view.bookmarks {+        name_width = name_width.max(String::from_utf8_lossy(&bookmark.name).len());+    }+    if titles {+        output::print_cell("Bookmark", name_width);+        print!("  ");+        output::print_cell("Commit", 12);+        print!("  ");+        output::print_cell("Change", 8);+        println!("  Target");+    }+    for bookmark in &view.bookmarks {+        let name = String::from_utf8_lossy(&bookmark.name);+        output::print_cell(&name, name_width);+        print!("  ");+        let Some(target) = bookmark.targets.adds.first().copied().flatten() else {+            output::print_cell("<missing>", 12);+            print!("  ");+            output::print_cell("", 8);+            println!("  (missing)");+            continue;+        };+        output::print_cell(&short(target), 12);+        print!("  ");+        let change = graph::load_commit(&mut store, target)?+            .map(|commit| graph::base32_encode(commit.change_id))+            .unwrap_or_default();+        output::print_cell(&change[..change.len().min(8)], 8);+        print!("  ");+        if working_copy == Some(target) {+            print!("@");+        }+        if bookmark.targets.adds.len() > 1 {+            if working_copy == Some(target) {+                print!(" ");+            }+            print!("(conflicted)");+        }+        println!();+    }+    if view.bookmarks.is_empty() {+        output::info_prefix();+        println!("no bookmarks");+    }+    Ok(0)+}++pub fn tag(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        tag_usage();+        return Ok(1);+    };+    match sub.as_str() {+        "set" => tag_set(&arguments[1..]),+        "ls" | "list" => tag_list(&arguments[1..]),+        "rm" | "remove" => tag_remove(&arguments[1..]),+        "latest" => tag_latest(&arguments[1..]),+        "help" | "-h" => {+            tag_usage();+            Ok(0)+        }+        _ => {+            output::error_prefix();+            println!("unknown tag subcommand: {sub}");+            tag_usage();+            Ok(1)+        }+    }+}++fn tag_usage() {+    println!("usage: vn tag <set|ls|rm|latest> ...");+    println!();+    println!("manage named pointers to commits (tags)");+    println!();+    println!("subcommands:");+    println!("  set <name> [-rev <rev>]   create or move a tag (default: @)");+    println!("  ls [-no-col-titles]       list tags");+    println!("  rm <name>                 delete a tag");+    println!("  latest                    print the latest tag name");+}++fn tag_set(arguments: &[String]) -> Result<u8> {+    let mut name = String::new();+    let mut revision = String::new();+    let mut end_flags = false;+    let mut index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && (argument == "-r" || argument == "-rev") {+            index += 1;+            if index >= arguments.len() {+                return Err(Error::new(format!("{argument} requires a revision")));+            }+            revision = arguments[index].clone();+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if name.is_empty() {+            name = argument.clone();+        } else if revision.is_empty() {+            revision = argument.clone();+        } else {+            return Err(Error::new("tag set accepts a name and one revision"));+        }+        index += 1;+    }+    if name.is_empty() {+        return Err(Error::new("tag set requires a name"));+    }+    if !valid_ref_name(&name) {+        return Err(Error::new(format!("invalid tag name: {name}")));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?.ok_or_else(|| {+        Error::new(if revision.is_empty() {+            "no working-copy commit"+        } else {+            "unknown revision"+        })+    })?;+    let mut changed = true;+    if let Some(existing) = ops::find_tag(txn.view(), name.as_bytes()) {+        let tag = &mut txn.view_mut().tags[existing];+        if tag.target == target {+            changed = false;+        } else {+            tag.target = target;+        }+    } else {+        txn.view_mut().tags.push(TagRef {+            name: name.as_bytes().to_vec(),+            target,+        });+    }+    if !changed {+        output::info_prefix();+        println!("tag {name} is already at {}", short(target));+        return Ok(0);+    }+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("tag set {name}"))?;+    output::info_prefix();+    println!("tag {name} set to {}", short(target));+    Ok(0)+}++fn tag_remove(arguments: &[String]) -> Result<u8> {+    let mut name = String::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else if !name.is_empty() {+            return Err(Error::new("tag rm accepts exactly one name"));+        } else {+            name = argument.clone();+        }+    }+    if name.is_empty() {+        return Err(Error::new("tag rm requires a name"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let mut txn = Txn::begin(&root, &mut store)?;+    let Some(index) = ops::find_tag(txn.view(), name.as_bytes()) else {+        return Err(Error::new(format!("no such tag: {name}")));+    };+    txn.view_mut().tags.remove(index);+    ops::rebuild_heads(txn.view_mut());+    txn.finish(&format!("tag delete {name}"))?;+    output::info_prefix();+    println!("deleted tag {name}");+    Ok(0)+}++fn tag_list(arguments: &[String]) -> Result<u8> {+    let mut titles = true;+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && argument == "-no-col-titles" {+            titles = false;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            return Err(Error::new("tag ls takes no operands"));+        }+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let working_copy = ops::working_copy_id(&view);+    let mut name_width = 3;+    for tag in &view.tags {+        name_width = name_width.max(String::from_utf8_lossy(&tag.name).len());+    }+    if titles {+        output::print_cell("Tag", name_width);+        print!("  ");+        output::print_cell("Commit", 12);+        print!("  ");+        output::print_cell("Change", 8);+        println!("  Target");+    }+    for tag in &view.tags {+        let name = String::from_utf8_lossy(&tag.name);+        output::print_cell(&name, name_width);+        print!("  ");+        output::print_cell(&short(tag.target), 12);+        print!("  ");+        let change = graph::load_commit(&mut store, tag.target)?+            .map(|commit| graph::base32_encode(commit.change_id))+            .unwrap_or_default();+        output::print_cell(&change[..change.len().min(8)], 8);+        print!("  ");+        if working_copy == Some(tag.target) {+            print!("@");+        }+        println!();+    }+    if view.tags.is_empty() {+        output::info_prefix();+        println!("no tags");+    }+    Ok(0)+}++fn natural_compare(left: &str, right: &str) -> std::cmp::Ordering {+    let left = left.as_bytes();+    let right = right.as_bytes();+    let mut i = 0;+    let mut j = 0;+    while i < left.len() && j < right.len() {+        if left[i].is_ascii_digit() && right[j].is_ascii_digit() {+            let ai = i;+            let bj = j;+            while i < left.len() && left[i].is_ascii_digit() {+                i += 1;+            }+            while j < right.len() && right[j].is_ascii_digit() {+                j += 1;+            }+            let an = left[ai..i]+                .iter()+                .position(|byte| *byte != b'0')+                .map(|offset| ai + offset)+                .unwrap_or(i);+            let bn = right[bj..j]+                .iter()+                .position(|byte| *byte != b'0')+                .map(|offset| bj + offset)+                .unwrap_or(j);+            let alen = i - an;+            let blen = j - bn;+            if alen != blen {+                return alen.cmp(&blen);+            }+            for offset in 0..alen {+                if left[an + offset] != right[bn + offset] {+                    return left[an + offset].cmp(&right[bn + offset]);+                }+            }+        } else {+            if left[i] != right[j] {+                return left[i].cmp(&right[j]);+            }+            i += 1;+            j += 1;+        }+    }+    if i < left.len() {+        std::cmp::Ordering::Greater+    } else if j < right.len() {+        std::cmp::Ordering::Less+    } else {+        std::cmp::Ordering::Equal+    }+}++fn tag_latest(arguments: &[String]) -> Result<u8> {+    if !arguments.is_empty() {+        return Err(Error::new("tag latest takes no operands"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let mut store = Store::open(&root)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    if view.tags.is_empty() {+        return Err(Error::new("no tags"));+    }+    let mut best: Option<(&TagRef, i64)> = None;+    for tag in &view.tags {+        let time = graph::load_commit(&mut store, tag.target)?+            .map(|commit| commit.committer.seconds)+            .unwrap_or(i64::MIN);+        let replace = match best {+            None => true,+            Some((current, best_time)) => {+                time > best_time+                    || (time == best_time+                        && natural_compare(+                            &String::from_utf8_lossy(&tag.name),+                            &String::from_utf8_lossy(&current.name),+                        ) == std::cmp::Ordering::Greater)+            }+        };+        if replace {+            best = Some((tag, time));+        }+    }+    if let Some((tag, _)) = best {+        println!("{}", String::from_utf8_lossy(&tag.name));+    }+    Ok(0)+}++pub fn _path_marker(_path: &Path) {}--- /dev/null+++ b/veins/src/cli/status.rs@@ -0,0 +1,81 @@+use std::collections::HashSet;++use crate::error::{Error, Result};+use crate::object::tree::KIND_CONFLICT;+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::pathspec;+use crate::worktree::snapshot;++use super::output;++pub fn run() -> Result<u8> {+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let cwd = pathspec::cwd_relative(&root).unwrap_or_default();+    let mut store = Store::open(&root)?;+    snapshot::run_with(&root, &mut store)?;+    let view =+        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+    let Some(working_copy) = ops::working_copy_id(&view) else {+        output::info_prefix();+        println!("working copy clean");+        return Ok(0);+    };+    let commit = graph::load_commit(&mut store, working_copy)?+        .ok_or_else(|| Error::new("no operation state"))?;+    let old_tree = match commit.parents.first() {+        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),+        None => None,+    };+    let changes = if old_tree == Some(commit.root_tree) {+        Vec::new()+    } else {+        graph::compare_trees(&mut store, old_tree, Some(commit.root_tree))?+    };+    let mut conflicts = 0usize;+    for change in &changes {+        let path = output::status_path(&change.path, &cwd);+        if change.old_kind == crate::object::tree::KIND_MISSING {+            output::print_styled("92", "A");+            println!(" {path}");+        } else if change.new_kind == crate::object::tree::KIND_MISSING {+            output::print_styled("31", "D");+            println!(" {path}");+        } else if change.new_kind == KIND_CONFLICT {+            output::print_styled("91", "C");+            println!(" {path}");+            conflicts += 1;+        } else {+            output::print_styled("36", "M");+            println!(" {path}");+        }+    }+    if changes.is_empty() {+        output::info_prefix();+        println!("working copy clean");+    }+    if conflicts > 0 {+        println!("{conflicts} conflict(s)");+    }+    let mut stack = vec![working_copy];+    let mut seen = HashSet::new();+    let mut conflicted_commits = 0usize;+    let mut conflict_cache = std::collections::HashMap::new();+    while let Some(id) = stack.pop() {+        if !seen.insert(id) {+            continue;+        }+        let Some(commit) = graph::load_commit(&mut store, id)? else {+            continue;+        };+        if graph::tree_conflicted_with(&mut store, commit.root_tree, &mut conflict_cache)? {+            conflicted_commits += 1;+        }+        stack.extend(commit.parents);+    }+    if conflicted_commits > 0 {+        println!("{conflicted_commits} conflicted commit(s) in ancestry");+    }+    Ok(0)+}--- /dev/null+++ b/veins/src/cli/worktree_cmd.rs@@ -0,0 +1,727 @@+use std::collections::HashSet;+use std::fs;+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::commit;+use crate::object::path::valid_path;+use crate::object::tree::{self, KIND_SUBTREE, TreeEntry};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::pathspec;+use crate::worktree::snapshot;++use super::output;++pub fn remove(arguments: &[String]) -> Result<u8> {+    let mut delete_mode = false;+    let mut operands = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && argument == "-delete" {+            delete_mode = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            operands.push(argument.clone());+        }+    }+    if operands.is_empty() {+        return Err(Error::new("rm requires at least one path"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    let normalized = normalize_operands(&root, &operands)?;+    run_removal(&root, &normalized, delete_mode)+}++fn normalize_operands(root: &Path, operands: &[String]) -> Result<Vec<String>> {+    let cwd = pathspec::cwd_relative(root)+        .ok_or_else(|| Error::new("cannot determine current directory"))?;+    let mut normalized = Vec::new();+    for argument in operands {+        let Some(normalized_path) = pathspec::pathspec_normalize(root, &cwd, argument) else {+            return Err(Error::new(format!(+                "path is outside the repository: {argument}"+            )));+        };+        if normalized_path.is_empty() || !valid_path(normalized_path.as_bytes()) {+            return Err(Error::new(format!("invalid path: {argument}")));+        }+        normalized.push(normalized_path);+    }+    Ok(normalized)+}++fn starts_with_child(path: &[u8], parent: &[u8]) -> bool {+    path.len() > parent.len() && path.starts_with(parent) && path[parent.len()] == b'/'+}++fn literal_matches(operand: &[u8], path: &[u8]) -> bool {+    path == operand || starts_with_child(path, operand)+}++fn glob_matches(operand: &str, path: &[u8]) -> bool {+    let text = String::from_utf8_lossy(path);+    if core::glob_match(operand, &text) {+        return true;+    }+    for (index, byte) in path.iter().enumerate() {+        if *byte == b'/' && core::glob_match(operand, &String::from_utf8_lossy(&path[..index])) {+            return true;+        }+    }+    false+}++fn operand_matches(operand: &str, path: &[u8]) -> bool {+    if operand.contains('*') || operand.contains('?') {+        glob_matches(operand, path)+    } else {+        literal_matches(operand.as_bytes(), path)+    }+}++fn subtree_affected(prefix: &[u8], removes: &[Vec<u8>]) -> bool {+    if prefix.is_empty() {+        return !removes.is_empty();+    }+    removes.iter().any(|remove| {+        prefix == remove.as_slice()+            || starts_with_child(remove, prefix)+            || starts_with_child(prefix, remove)+    })+}++fn path_removed(path: &[u8], removes: &[Vec<u8>]) -> bool {+    removes+        .iter()+        .any(|remove| path == remove.as_slice() || starts_with_child(path, remove))+}++fn empty_tree_id(txn: &mut Txn) -> Result<crate::object::id::Id> {+    Ok(txn.add_object(TYPE_TREE, tree::encode(&[])?))+}++fn filter_tree(+    txn: &mut Txn,+    store: &mut Store,+    tree_id: crate::object::id::Id,+    prefix: &[u8],+    removes: &[Vec<u8>],+    depth: usize,+) -> Result<Option<crate::object::id::Id>> {+    if depth > crate::object::MAX_TREE_DEPTH || !subtree_affected(prefix, removes) {+        return Ok(Some(tree_id));+    }+    let Some(body) = store.body(tree_id, TYPE_TREE)? else {+        return Ok(Some(tree_id));+    };+    let Ok(decoded) = tree::decode(&body) else {+        return Ok(Some(tree_id));+    };+    let mut entries = Vec::with_capacity(decoded.entries.len());+    for entry in decoded.entries {+        let full = crate::object::path::join(prefix, &entry.name);+        if path_removed(&full, removes) {+            continue;+        }+        if entry.kind == KIND_SUBTREE && subtree_affected(&full, removes) {+            if let Some(child) = filter_tree(txn, store, entry.target, &full, removes, depth + 1)? {+                entries.push(TreeEntry {+                    name: entry.name,+                    kind: entry.kind,+                    target: child,+                });+            }+        } else {+            entries.push(entry);+        }+    }+    if entries.is_empty() {+        return Ok(None);+    }+    Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))+}++fn delete_paths(root: &Path, removes: &[Vec<u8>]) -> u8 {+    let mut failed = 0;+    for relative in removes {+        let path = root.join(core::path_from_bytes(relative));+        if fs::remove_file(&path).is_err() {+            failed += 1;+        } else {+            prune_parents(root, relative);+        }+    }+    if failed > 0 {+        output::warning_prefix();+        println!("could not delete {failed} path(s) from disk");+        1+    } else {+        0+    }+}++fn prune_parents(root: &Path, relative: &[u8]) {+    let mut end = relative.len();+    while let Some(position) = relative[..end].iter().rposition(|byte| *byte == b'/') {+        let path = root.join(core::path_from_bytes(&relative[..position]));+        if fs::remove_dir(&path).is_err() {+            break;+        }+        end = position;+    }+}++fn run_removal(root: &Path, operands: &[String], delete_mode: bool) -> Result<u8> {+    let mut store = Store::open(root)?;+    let mut txn = Txn::begin(root, &mut store)?;+    let working_copy =+        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;+    let loaded = graph::load_commit(&mut store, working_copy)?+        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;+    let entries = tree::flatten(&mut store, loaded.root_tree)?;+    let mut matched = vec![false; operands.len()];+    let mut removes = Vec::new();+    let mut seen = HashSet::new();+    for entry in &entries {+        for (index, operand) in operands.iter().enumerate() {+            if operand_matches(operand, &entry.path) {+                matched[index] = true;+                if seen.insert(entry.path.clone()) {+                    removes.push(entry.path.clone());+                }+            }+        }+    }+    for (index, value) in matched.iter().enumerate() {+        if !value {+            return Err(Error::new(format!(+                "path is not tracked: {}",+                operands[index]+            )));+        }+    }+    if !delete_mode {+        for relative in &removes {+            if !core::ignore_path_ignored(root, &String::from_utf8_lossy(relative)) {+                output::warning_prefix();+                println!(+                    "{} is not ignored and will be re-added on the next snapshot",+                    String::from_utf8_lossy(relative)+                );+            }+        }+    }+    let new_root = filter_tree(&mut txn, &mut store, loaded.root_tree, b"", &removes, 0)?+        .unwrap_or_else(|| empty_tree_id(&mut txn).unwrap_or_default());+    if new_root == loaded.root_tree {+        return Err(Error::new("no tracked paths to remove"));+    }+    let signature = identity::signature(root);+    let mut commit = loaded;+    commit.root_tree = new_root;+    commit.committer = signature;+    commit.renames_state = commit::RENAMES_RECORDED;+    commit.renames.clear();+    let encoded = commit::encode(&commit);+    let new_id = txn.add_object(TYPE_COMMIT, encoded);+    ops::remove_head(txn.view_mut(), working_copy);+    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);+    ops::set_workspace(txn.view_mut(), new_id);+    ops::rebuild_heads(txn.view_mut());+    txn.finish("rm")?;+    mark_native(root, new_id);+    let mut status = 0;+    if delete_mode {+        status = delete_paths(root, &removes);+    }+    output::info_prefix();+    println!("untracked {} path(s)", removes.len());+    Ok(status)+}++fn mark_native(root: &Path, id: crate::object::id::Id) {+    let path = layout::git_map_dir(root).join("native");+    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());+}++pub fn move_path(arguments: &[String]) -> Result<u8> {+    let mut operands = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            operands.push(argument.clone());+        }+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    snapshot::run(&root)?;+    if operands.len() != 2 {+        return Err(Error::new("mv requires a source and a destination"));+    }+    let cwd = pathspec::cwd_relative(&root)+        .ok_or_else(|| Error::new("cannot determine current directory"))?;+    let source = pathspec::pathspec_normalize(&root, &cwd, &operands[0])+        .ok_or_else(|| Error::new("invalid path"))?;+    let destination = pathspec::pathspec_normalize(&root, &cwd, &operands[1])+        .ok_or_else(|| Error::new("invalid path"))?;+    let source_path = root.join(core::path_from_bytes(source.as_bytes()));+    let destination_path = root.join(core::path_from_bytes(destination.as_bytes()));+    if core::stat_path(&source_path).is_none() {+        return Err(Error::new(format!("not a tracked path: {source}")));+    }+    if core::stat_path(&destination_path).is_some() {+        return Err(Error::new(format!(+            "destination already exists: {destination}"+        )));+    }+    if let Some((parent, _)) = destination.rsplit_once('/') {+        if !core::ensure_directory(&root.join(parent)) {+            return Err(Error::new("cannot create destination directory"));+        }+    }+    fs::rename(&source_path, &destination_path).map_err(|_| Error::new("cannot move path"))?;+    snapshot::run(&root)?;+    Ok(0)+}++pub fn exclude(arguments: &[String]) -> Result<u8> {+    let mut operands = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            operands.push(argument.clone());+        }+    }+    if operands.is_empty() {+        return Err(Error::new("ex requires at least one pattern"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let cwd = pathspec::cwd_relative(&root)+        .ok_or_else(|| Error::new("cannot determine current directory"))?;+    let mut patterns = Vec::new();+    for argument in &operands {+        let Some(normalized) = pathspec::pathspec_normalize(&root, &cwd, argument) else {+            return Err(Error::new(format!(+                "pattern is outside the repository: {argument}"+            )));+        };+        if normalized.is_empty() || !valid_path(normalized.as_bytes()) {+            return Err(Error::new(format!(+                "{argument}\nnot a valid exclude pattern"+            )));+        }+        patterns.push(normalized);+    }+    let path = root.join(".vnexclude");+    let data = core::read_file_opt(&path, 0).unwrap_or_default();+    let text = String::from_utf8_lossy(&data);+    let mut additions = String::new();+    let mut added = Vec::new();+    for pattern in &patterns {+        if text.lines().any(|line| core::trim_str(line) == pattern)+            || added.iter().any(|value| value == pattern)+        {+            continue;+        }+        if additions.is_empty() && !data.is_empty() && !data.ends_with(b"\n") {+            additions.push('\n');+        }+        added.push(pattern.clone());+        additions.push_str(pattern);+        additions.push('\n');+    }+    if added.is_empty() {+        output::info_prefix();+        println!("no new exclude rules");+        return Ok(0);+    }+    if !core::append_file(&path, additions.as_bytes()) {+        return Err(Error::new("cannot write .vnexclude"));+    }+    output::info_prefix();+    println!("added {} exclude rule(s)", added.len());+    Ok(0)+}++pub fn edit(arguments: &[String]) -> Result<u8> {+    let mut paths = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            paths.push(argument.clone());+        }+    }+    if paths.is_empty() {+        paths.push(".".to_string());+    }+    let root = layout::discover(Path::new("."))+        .or_else(|_| std::env::current_dir())+        .map_err(|_| Error::new("cannot determine the current directory"))?;+    if !core::run_editor(&root, &paths, None) {+        return Err(Error::new("editor exited with an error"));+    }+    Ok(0)+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Attr {+    Gen,+    Txt,+    Bin,+    Lf,+    Crlf,+    Cr,+}++fn parse_attr(name: &str) -> Option<Attr> {+    match name {+        "gen" => Some(Attr::Gen),+        "txt" => Some(Attr::Txt),+        "bin" => Some(Attr::Bin),+        "lf" => Some(Attr::Lf),+        "crlf" => Some(Attr::Crlf),+        "cr" => Some(Attr::Cr),+        _ => None,+    }+}++fn canonical(attr: Attr) -> &'static str {+    match attr {+        Attr::Gen => "gen",+        Attr::Txt => "txt",+        Attr::Bin => "bin",+        Attr::Lf => "eol:lf",+        Attr::Crlf => "eol:crlf",+        Attr::Cr => "eol:cr",+    }+}++fn is_attr_token(token: &str, attr: Attr) -> bool {+    match attr {+        Attr::Gen => token == "gen" || token == "-gen",+        Attr::Txt => token == "txt" || token == "-txt",+        Attr::Bin => token == "bin" || token == "-bin",+        Attr::Lf => token == "eol:lf",+        Attr::Crlf => token == "eol:crlf",+        Attr::Cr => token == "eol:cr",+    }+}++fn clears_token(token: &str, attr: Attr) -> bool {+    match attr {+        Attr::Gen => is_attr_token(token, Attr::Gen),+        Attr::Txt | Attr::Bin => matches!(token, "txt" | "-txt" | "bin" | "-bin"),+        Attr::Lf | Attr::Crlf | Attr::Cr => {+            matches!(token, "eol:lf" | "eol:crlf" | "eol:cr" | "-eol")+        }+    }+}++struct Line {+    text: String,+    eol: String,+    is_rule: bool,+    pattern: String,+    attrs: Vec<String>,+}++fn tokenize(line: &str) -> Vec<String> {+    line.split(|character| character == ' ' || character == '\t')+        .filter(|value| !value.is_empty())+        .map(|value| value.to_string())+        .collect()+}++fn parse_lines(data: &str) -> Vec<Line> {+    let mut lines = Vec::new();+    let mut start = 0;+    while start < data.len() {+        let newline = data[start..].find('\n').map(|offset| start + offset);+        let mut line = Line {+            text: String::new(),+            eol: String::new(),+            is_rule: false,+            pattern: String::new(),+            attrs: Vec::new(),+        };+        match newline {+            None => {+                line.text = data[start..].to_string();+                start = data.len();+            }+            Some(position) => {+                let mut body = &data[start..position];+                if let Some(value) = body.strip_suffix('\r') {+                    body = value;+                    line.eol = "\r\n".to_string();+                } else {+                    line.eol = "\n".to_string();+                }+                line.text = body.to_string();+                start = position + 1;+            }+        }+        let trimmed = core::trim_str(&line.text);+        if !trimmed.is_empty() && !trimmed.starts_with('#') {+            let tokens = tokenize(trimmed);+            if !tokens.is_empty() {+                line.is_rule = true;+                line.pattern = tokens[0].clone();+                line.attrs = tokens[1..].to_vec();+            }+        }+        lines.push(line);+    }+    lines+}++fn canonical_line(line: &Line) -> String {+    let mut output = line.pattern.clone();+    for attr in &line.attrs {+        output.push(' ');+        output.push_str(attr);+    }+    output+}++fn serialize(lines: &[Line], removed: &[bool]) -> String {+    let kept: Vec<usize> = (0..lines.len())+        .filter(|index| !removed.get(*index).copied().unwrap_or(false))+        .collect();+    let mut output = String::new();+    for (position, index) in kept.iter().enumerate() {+        let line = &lines[*index];+        if line.is_rule {+            output.push_str(&canonical_line(line));+        } else {+            output.push_str(&line.text);+        }+        if position + 1 < kept.len() {+            output.push_str(if line.eol.is_empty() { "\n" } else { &line.eol });+        } else {+            output.push_str(&line.eol);+        }+    }+    if !output.is_empty() && !output.ends_with('\n') {+        output.push('\n');+    }+    output+}++fn collect_operands(arguments: &[String]) -> Result<Vec<String>> {+    let mut operands = Vec::new();+    let mut end_flags = false;+    for argument in arguments {+        if !end_flags && argument == "--" {+            end_flags = true;+        } else if !end_flags && core::is_flag(argument) {+            return Err(Error::new(format!("unknown flag: {argument}")));+        } else {+            operands.push(argument.clone());+        }+    }+    Ok(operands)+}++fn normalize_patterns(root: &Path, arguments: &[String]) -> Result<Vec<String>> {+    let cwd = pathspec::cwd_relative(root)+        .ok_or_else(|| Error::new("cannot determine current directory"))?;+    let mut patterns = Vec::new();+    for argument in arguments {+        let Some(normalized) = pathspec::pathspec_normalize(root, &cwd, argument) else {+            return Err(Error::new(format!(+                "{argument}\nnot a valid attribute pattern"+            )));+        };+        if normalized.is_empty()+            || !valid_path(normalized.as_bytes())+            || normalized.contains([' ', '\t', '\r', '\n'])+            || normalized.starts_with('#')+        {+            return Err(Error::new(format!(+                "{argument}\nnot a valid attribute pattern"+            )));+        }+        patterns.push(normalized);+    }+    Ok(patterns)+}++fn read_attribs(path: &Path) -> Result<String> {+    match core::read_file_opt(path, 0) {+        Some(data) => Ok(String::from_utf8_lossy(&data).into_owned()),+        None if path.exists() => Err(Error::new("cannot read .vnattribs")),+        None => Ok(String::new()),+    }+}++fn attr_set(attr: Attr, arguments: &[String]) -> Result<u8> {+    let operands = collect_operands(arguments)?;+    if operands.is_empty() {+        return Err(Error::new(format!(+            "attr {} requires at least one glob",+            canonical(attr)+        )));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let patterns = normalize_patterns(&root, &operands)?;+    let path = root.join(".vnattribs");+    let data = read_attribs(&path)?;+    let mut lines = parse_lines(&data);+    let mut changed = 0;+    for pattern in &patterns {+        let target = lines+            .iter()+            .enumerate()+            .filter(|(_, line)| line.is_rule && &line.pattern == pattern)+            .map(|(index, _)| index)+            .last();+        let mut attrs = Vec::new();+        if let Some(index) = target {+            for token in &lines[index].attrs {+                if !clears_token(token, attr) {+                    attrs.push(token.clone());+                }+            }+        }+        attrs.push(canonical(attr).to_string());+        if let Some(index) = target {+            if lines[index].attrs == attrs {+                continue;+            }+            lines[index].attrs = attrs;+        } else {+            if let Some(last) = lines.last_mut() {+                if last.eol.is_empty() {+                    last.eol = "\n".to_string();+                }+            }+            lines.push(Line {+                text: String::new(),+                eol: "\n".to_string(),+                is_rule: true,+                pattern: pattern.clone(),+                attrs,+            });+        }+        changed += 1;+    }+    if changed == 0 {+        output::info_prefix();+        println!("no new attribute rules");+        return Ok(0);+    }+    if !core::write_atomic_name(&path, serialize(&lines, &[]).as_bytes()) {+        return Err(Error::new("cannot write .vnattribs"));+    }+    output::info_prefix();+    println!("updated {changed} attribute rule(s)");+    Ok(0)+}++fn attr_remove(arguments: &[String]) -> Result<u8> {+    let mut operands = collect_operands(arguments)?;+    if operands.len() < 2 {+        return Err(Error::new(+            "usage: vn attr rm <gen|txt|bin|lf|crlf|cr> <glob>...",+        ));+    }+    let Some(attr) = parse_attr(&operands[0]) else {+        return Err(Error::new(format!("unknown attribute: {}", operands[0])));+    };+    operands.remove(0);+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let patterns = normalize_patterns(&root, &operands)?;+    let path = root.join(".vnattribs");+    let data = read_attribs(&path)?;+    let mut lines = parse_lines(&data);+    let mut removed = vec![false; lines.len()];+    let mut changed = 0;+    for pattern in &patterns {+        for index in 0..lines.len() {+            if removed[index] || !lines[index].is_rule || &lines[index].pattern != pattern {+                continue;+            }+            let attrs: Vec<String> = lines[index]+                .attrs+                .iter()+                .filter(|token| !is_attr_token(token, attr))+                .cloned()+                .collect();+            if attrs.len() == lines[index].attrs.len() {+                continue;+            }+            if attrs.is_empty() {+                removed[index] = true;+            } else {+                lines[index].attrs = attrs;+            }+            changed += 1;+        }+    }+    if changed == 0 {+        output::info_prefix();+        println!("no matching attribute rules");+        return Ok(0);+    }+    if !core::write_atomic_name(&path, serialize(&lines, &removed).as_bytes()) {+        return Err(Error::new("cannot write .vnattribs"));+    }+    output::info_prefix();+    println!("removed {changed} attribute rule(s)");+    Ok(0)+}++fn attr_list(arguments: &[String]) -> Result<u8> {+    let operands = collect_operands(arguments)?;+    if !operands.is_empty() {+        return Err(Error::new("usage: vn attr ls"));+    }+    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;+    let data = read_attribs(&root.join(".vnattribs"))?;+    for line in parse_lines(&data) {+        if line.is_rule {+            println!("{}", canonical_line(&line));+        }+    }+    Ok(0)+}++pub fn attr(arguments: &[String]) -> Result<u8> {+    let Some(sub) = arguments.first() else {+        output::error_prefix();+        println!("attr requires a subcommand");+        println!("run 'vn help attr' for details");+        return Ok(1);+    };+    match sub.as_str() {+        "ls" => attr_list(&arguments[1..]),+        "rm" => attr_remove(&arguments[1..]),+        value => match parse_attr(value) {+            Some(attr) => attr_set(attr, &arguments[1..]),+            None => Err(Error::new(format!("unknown attr subcommand: {value}"))),+        },+    }+}--- /dev/null+++ b/veins/src/core.rs@@ -0,0 +1,1237 @@+use std::collections::BTreeMap;+use std::env;+use std::fs;+use std::io::{Read, Write};+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};+use crate::platform;++pub fn is_flag(argument: &str) -> bool {+    !argument.is_empty() && argument.starts_with('-')+}++pub fn trim_str(text: &str) -> &str {+    text.trim_matches(|character| {+        character == ' ' || character == '\t' || character == '\r' || character == '\n'+    })+}++pub fn trim_bytes(text: &[u8]) -> &[u8] {+    let mut start = 0;+    let mut end = text.len();+    while start < end && matches!(text[start], b' ' | b'\t' | b'\r' | b'\n') {+        start += 1;+    }+    while end > start && matches!(text[end - 1], b' ' | b'\t' | b'\r' | b'\n') {+        end -= 1;+    }+    &text[start..end]+}++pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+    platform::path_from_bytes(bytes)+}++pub fn path_to_bytes(path: &Path) -> Vec<u8> {+    platform::path_to_bytes(path)+}++pub fn path_display(path: &Path) -> String {+    platform::path_display(path)+}++pub fn read_file_opt(path: &Path, maximum: u64) -> Option<Vec<u8>> {+    #[cfg(unix)]+    {+        use std::os::unix::fs::OpenOptionsExt;+        let mut file = fs::OpenOptions::new()+            .read(true)+            .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)+            .open(path)+            .ok()?;+        let metadata = file.metadata().ok()?;+        if !metadata.is_file() {+            return None;+        }+        if maximum != 0 && metadata.len() > maximum {+            return None;+        }+        let length = usize::try_from(metadata.len()).ok()?;+        if length == 0 {+            let mut data = Vec::new();+            file.read_to_end(&mut data).ok()?;+            return Some(data);+        }+        let mut data = vec![0u8; length];+        file.read_exact(&mut data).ok()?;+        Some(data)+    }+    #[cfg(not(unix))]+    {+        let metadata = fs::symlink_metadata(path).ok()?;+        if !metadata.is_file() {+            return None;+        }+        if maximum != 0 && metadata.len() > maximum {+            return None;+        }+        let mut file = fs::File::open(path).ok()?;+        let mut data = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or(0));+        file.read_to_end(&mut data).ok()?;+        Some(data)+    }+}++pub fn read_file_range(path: &Path, offset: u64, length: usize) -> Option<Vec<u8>> {+    use std::io::{Seek, SeekFrom};+    let mut file = fs::File::open(path).ok()?;+    file.seek(SeekFrom::Start(offset)).ok()?;+    let mut data = vec![0u8; length];+    let mut done = 0;+    while done < length {+        match file.read(&mut data[done..]) {+            Ok(0) => break,+            Ok(count) => done += count,+            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,+            Err(_) => return None,+        }+    }+    data.truncate(done);+    Some(data)+}++pub fn read_file(path: &Path, maximum: u64) -> Result<Vec<u8>> {+    read_file_opt(path, maximum).ok_or_else(|| Error::io(format!("cannot read {}", path.display())))+}++fn create_parent(path: &Path) -> bool {+    match path.parent() {+        Some(parent) if !parent.as_os_str().is_empty() => fs::create_dir_all(parent).is_ok(),+        _ => true,+    }+}++pub fn write_file(path: &Path, data: &[u8]) -> bool {+    let mut options = fs::OpenOptions::new();+    options.write(true).create(true).truncate(true);+    let file = match options.open(path) {+        Ok(file) => Some(file),+        Err(_) => {+            if !create_parent(path) {+                return false;+            }+            options.open(path).ok()+        }+    };+    let Some(mut file) = file else {+        return false;+    };+    file.write_all(data).is_ok() && file.flush().is_ok()+}++pub fn append_file(path: &Path, data: &[u8]) -> bool {+    let mut options = fs::OpenOptions::new();+    options.create(true).append(true);+    let file = match options.open(path) {+        Ok(file) => Some(file),+        Err(_) => {+            if !create_parent(path) {+                return false;+            }+            options.open(path).ok()+        }+    };+    let Some(mut file) = file else {+        return false;+    };+    file.write_all(data).is_ok() && file.flush().is_ok()+}++fn sync_file(path: &Path) -> bool {+    platform::sync_file(path).is_ok()+}++fn sync_directory(path: &Path) {+    platform::sync_directory(path);+}++pub fn write_atomic(tmp_path: &Path, final_path: &Path, data: &[u8]) -> bool {+    if let Some(parent) = tmp_path.parent()+        && !parent.as_os_str().is_empty()+        && fs::create_dir_all(parent).is_err()+    {+        return false;+    }+    if let Some(parent) = final_path.parent()+        && !parent.as_os_str().is_empty()+        && fs::create_dir_all(parent).is_err()+    {+        return false;+    }+    if !write_file(tmp_path, data) {+        return false;+    }+    if !sync_file(tmp_path) {+        let _ = fs::remove_file(tmp_path);+        return false;+    }+    if fs::rename(tmp_path, final_path).is_err() {+        let _ = fs::remove_file(tmp_path);+        return false;+    }+    if let Some(parent) = final_path.parent() {+        sync_directory(parent);+    }+    true+}++pub fn write_atomic_name(final_path: &Path, data: &[u8]) -> bool {+    let parent = final_path.parent().unwrap_or_else(|| Path::new(""));+    let name = final_path+        .file_name()+        .map(|value| value.to_string_lossy().into_owned())+        .unwrap_or_default();+    let temporary = parent.join(format!(".{name}.tmp.{}", random_u64()));+    write_atomic(&temporary, final_path, data)+}++pub fn ensure_directory(path: &Path) -> bool {+    fs::create_dir_all(path).is_ok()+}++pub fn remove_file(path: &Path) -> bool {+    fs::remove_file(path).is_ok()+}++pub fn remove_tree(path: &Path) -> bool {+    fs::remove_dir_all(path).is_ok()+}++pub fn list_directory(path: &Path) -> Vec<Vec<u8>> {+    let mut names = Vec::new();+    let Ok(entries) = fs::read_dir(path) else {+        return names;+    };+    for entry in entries.flatten() {+        names.push(platform::os_string_to_bytes(entry.file_name()));+    }+    names+}++pub fn same_or_under(child: &Path, parent: &Path) -> bool {+    let Ok(child) = fs::canonicalize(child) else {+        return false;+    };+    let Ok(parent) = fs::canonicalize(parent) else {+        return false;+    };+    child.starts_with(parent)+}++pub fn basename_string(path: &Path) -> String {+    path.file_name()+        .map(|value| value.to_string_lossy().into_owned())+        .unwrap_or_default()+}++pub fn path_read_symlink(path: &Path) -> Option<Vec<u8>> {+    fs::read_link(path)+        .ok()+        .map(|target| platform::path_to_bytes(&target))+}++#[derive(Clone, Copy)]+pub struct StatInfo {+    pub kind: u8,+    pub executable: bool,+    pub size: u64,+    pub mtime_ns: u64,+    pub inode: u64,+}++pub fn stat_path(path: &Path) -> Option<StatInfo> {+    let metadata = fs::symlink_metadata(path).ok()?;+    let file_type = metadata.file_type();+    let kind = if file_type.is_symlink() {+        3+    } else if file_type.is_dir() {+        2+    } else if file_type.is_file() {+        1+    } else {+        return None;+    };+    Some(StatInfo {+        kind,+        executable: platform::executable(&metadata),+        size: metadata.len(),+        mtime_ns: platform::mtime_ns(&metadata),+        inode: platform::inode(&metadata),+    })+}++thread_local! {+    static REPO_CONFIG: std::cell::RefCell<Option<(PathBuf, Vec<u8>)>> =+        const { std::cell::RefCell::new(None) };+}++fn repo_config_data(root: &Path) -> Option<Vec<u8>> {+    let path = root.join(".veins").join("config");+    REPO_CONFIG.with(|slot| {+        let mut slot = slot.borrow_mut();+        if let Some((cached_path, data)) = slot.as_ref()+            && *cached_path == path+        {+            return Some(data.clone());+        }+        let data = read_file_opt(&path, 0)?;+        *slot = Some((path, data.clone()));+        Some(data)+    })+}++fn clear_repo_config_cache() {+    REPO_CONFIG.with(|slot| *slot.borrow_mut() = None);+}++pub fn repo_config_value(root: &Path, key: &str) -> Option<String> {+    let data = repo_config_data(root)?;+    let text = String::from_utf8_lossy(&data);+    for raw in text.lines() {+        let line = trim_str(raw);+        if line.is_empty() || line.starts_with('#') {+            continue;+        }+        let Some((name, value)) = line.split_once('=') else {+            continue;+        };+        if trim_str(name) == key {+            return Some(trim_str(value).to_string());+        }+    }+    None+}++fn config_without_key(data: &[u8], key: &str) -> Vec<u8> {+    let text = String::from_utf8_lossy(data);+    let mut output = String::new();+    let lines: Vec<&str> = text.lines().collect();+    for (index, raw) in lines.iter().enumerate() {+        let line = trim_str(raw);+        let mut skip = false;+        if !line.is_empty()+            && !line.starts_with('#')+            && let Some((name, _)) = line.split_once('=')+        {+            skip = trim_str(name) == key;+        }+        if !skip {+            output.push_str(raw);+            if index + 1 < lines.len() || text.ends_with('\n') {+                output.push('\n');+            }+        }+    }+    output.into_bytes()+}++pub fn repo_config_set(root: &Path, key: &str, value: &str) -> bool {+    let path = root.join(".veins").join("config");+    let mut output = repo_config_data(root)+        .map(|data| config_without_key(&data, key))+        .unwrap_or_default();+    output.extend_from_slice(key.as_bytes());+    output.extend_from_slice(b" = ");+    output.extend_from_slice(value.as_bytes());+    output.push(b'\n');+    let written = write_file(&path, &output);+    clear_repo_config_cache();+    written+}++pub fn repo_config_remove(root: &Path, key: &str) -> bool {+    let path = root.join(".veins").join("config");+    let output = repo_config_data(root)+        .map(|data| config_without_key(&data, key))+        .unwrap_or_default();+    let written = write_file(&path, &output);+    clear_repo_config_cache();+    written+}++pub fn repo_config_bool(root: &Path, key: &str, fallback: bool) -> bool {+    let Some(value) = repo_config_value(root, key) else {+        return fallback;+    };+    let value = value.split('#').next().unwrap_or("").trim();+    matches!(value, "true" | "1" | "yes" | "on")+}++fn user_config_path() -> Option<PathBuf> {+    let home = env::var_os("HOME")?;+    if home.is_empty() {+        return None;+    }+    Some(+        PathBuf::from(home)+            .join(".local")+            .join("config")+            .join("veins")+            .join("veins.toml"),+    )+}++fn unquote_toml(raw: &str) -> Option<String> {+    let raw = trim_str(raw);+    if raw.len() >= 2 {+        let first = raw.as_bytes()[0];+        let last = raw.as_bytes()[raw.len() - 1];+        if (first == b'\'' && last == b'\'') || (first == b'"' && last == b'"') {+            let quote = first;+            let mut output = String::new();+            let bytes = raw.as_bytes();+            let mut index = 1;+            while index + 1 < bytes.len() {+                let byte = bytes[index];+                if quote == b'"' && byte == b'\\' && index + 2 < bytes.len() {+                    match bytes[index + 1] {+                        b'"' => output.push('"'),+                        b'\\' => output.push('\\'),+                        b'n' => output.push('\n'),+                        b'r' => output.push('\r'),+                        b't' => output.push('\t'),+                        other => {+                            output.push('\\');+                            output.push(other as char);+                        }+                    }+                    index += 2;+                } else {+                    output.push(byte as char);+                    index += 1;+                }+            }+            return Some(output);+        }+    }+    if raw.is_empty() {+        return None;+    }+    Some(raw.to_string())+}++fn user_config_full_key(section: &str, key: &str) -> String {+    if section.is_empty() {+        key.to_string()+    } else {+        format!("{section}.{key}")+    }+}++fn user_config_entries_inner() -> BTreeMap<String, String> {+    let mut output = BTreeMap::new();+    let Some(path) = user_config_path() else {+        return output;+    };+    let Some(data) = read_file_opt(&path, 0) else {+        return output;+    };+    let text = String::from_utf8_lossy(&data);+    let mut section = String::new();+    for raw in text.lines() {+        let line = trim_str(raw);+        if line.is_empty() || line.starts_with('#') {+            continue;+        }+        if let Some(rest) = line.strip_prefix('[') {+            if let Some(close) = rest.find(']') {+                section = trim_str(&rest[..close]).to_string();+            }+            continue;+        }+        let Some((key, value)) = line.split_once('=') else {+            continue;+        };+        let value = value.split('#').next().unwrap_or("");+        if let Some(decoded) = unquote_toml(value) {+            output.insert(user_config_full_key(&section, trim_str(key)), decoded);+        }+    }+    output+}++pub fn user_config_entries() -> BTreeMap<String, String> {+    user_config_entries_inner()+}++pub fn user_config_value(key: &str) -> Option<String> {+    user_config_entries_inner().remove(key)+}++pub fn user_config_author_name() -> Option<String> {+    user_config_value("user.name")+}++pub fn user_config_author_email() -> Option<String> {+    user_config_value("user.email")+}++fn toml_quote(value: &str) -> String {+    let mut output = String::from("\"");+    for character in value.chars() {+        match character {+            '"' => output.push_str("\\\""),+            '\\' => output.push_str("\\\\"),+            '\n' => output.push_str("\\n"),+            '\r' => output.push_str("\\r"),+            '\t' => output.push_str("\\t"),+            other => output.push(other),+        }+    }+    output.push('"');+    output+}++fn update_user_config(key: &str, value: Option<&str>) -> bool {+    if key.is_empty() {+        return false;+    }+    let Some(path) = user_config_path() else {+        return false;+    };+    let lines: Vec<String> = read_file_opt(&path, 0)+        .map(|data| {+            String::from_utf8_lossy(&data)+                .lines()+                .map(|line| line.to_string())+                .collect()+        })+        .unwrap_or_default();+    let mut output = Vec::new();+    let mut section = String::new();+    for line in lines {+        let trimmed = trim_str(&line);+        if let Some(rest) = trimmed.strip_prefix('[') {+            if let Some(close) = rest.find(']') {+                section = trim_str(&rest[..close]).to_string();+            }+            output.push(line);+            continue;+        }+        let Some((name, _)) = trimmed.split_once('=') else {+            output.push(line);+            continue;+        };+        if trimmed.is_empty() || trimmed.starts_with('#') {+            output.push(line);+            continue;+        }+        if user_config_full_key(&section, trim_str(name)) != key {+            output.push(line);+        }+    }+    if let Some(value) = value {+        output.insert(0, format!("{key} = {}", toml_quote(value)));+    } else {+        while output.last().is_some_and(|line| trim_str(line).is_empty()) {+            output.pop();+        }+    }+    let mut body = output.join("\n");+    if !output.is_empty() {+        body.push('\n');+    }+    write_file(&path, body.as_bytes())+}++pub fn user_config_set(key: &str, value: &str) -> bool {+    update_user_config(key, Some(value))+}++pub fn user_config_remove(key: &str) -> bool {+    update_user_config(key, None)+}++pub fn shell_quote_arg(value: &str) -> String {+    platform::shell_quote(value)+}++pub fn editor_command(root: &Path) -> String {+    for key in ["editor", "core.editor"] {+        if let Some(value) = user_config_value(key)+            && !value.is_empty()+        {+            return value;+        }+    }+    if let Some(value) = repo_config_value(root, "editor")+        && !value.is_empty()+    {+        return value;+    }+    for name in ["VN_EDITOR", "VISUAL", "EDITOR"] {+        if let Ok(value) = env::var(name)+            && !value.is_empty()+        {+            return value;+        }+    }+    platform::default_editor().to_string()+}++pub fn run_editor(root: &Path, paths: &[String], message_file: Option<&Path>) -> bool {+    let mut command = editor_command(root);+    for path in paths {+        command.push(' ');+        command.push_str(&shell_quote_arg(path));+    }+    if let Some(file) = message_file {+        command.push(' ');+        command.push_str(&shell_quote_arg(&path_display(file)));+    }+    platform::shell(&command)+        .status()+        .is_ok_and(|status| status.success())+}++pub fn stdin_is_terminal() -> bool {+    platform::stdin_is_terminal()+}++pub fn colors_enabled() -> bool {+    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();+    *ENABLED.get_or_init(|| {+        if env::var_os("NO_COLOR").is_some() {+            return false;+        }+        let forced =+            env::var_os("FORCE_COLOR").is_some_and(|value| !value.is_empty() && value != "0");+        if forced {+            return true;+        }+        if !stdout_is_terminal() {+            return false;+        }+        !env::var("TERM").is_ok_and(|term| term == "dumb")+    })+}++pub fn stdout_is_terminal() -> bool {+    platform::stdout_is_terminal()+}++pub fn stderr_is_terminal() -> bool {+    platform::stderr_is_terminal()+}++pub fn pager_command(root: &Path) -> String {+    for key in ["pager", "core.pager"] {+        if let Some(value) = user_config_value(key)+            && !value.is_empty()+        {+            return value;+        }+    }+    if let Some(value) = repo_config_value(root, "pager")+        && !value.is_empty()+    {+        return value;+    }+    for name in ["VN_PAGER", "PAGER"] {+        if let Ok(value) = env::var(name)+            && !value.is_empty()+        {+            return value;+        }+    }+    platform::default_pager().to_string()+}++pub fn run_pager(root: &Path, text: &str) -> bool {+    if !stdout_is_terminal() {+        print!("{text}");+        return true;+    }+    let file = env::temp_dir().join(format!("vn-pager-{}.txt", random_u64()));+    if !write_file(&file, text.as_bytes()) {+        print!("{text}");+        return false;+    }+    let command = format!(+        "{} {}",+        pager_command(root),+        shell_quote_arg(&path_display(&file))+    );+    let ok = platform::shell(&command)+        .status()+        .is_ok_and(|status| status.success());+    let _ = fs::remove_file(&file);+    if !ok {+        print!("{text}");+    }+    ok+}++pub fn current_bookmark_name(root: &Path) -> Option<String> {+    repo_config_value(root, "bookmark.current")+}++pub fn set_current_bookmark(root: &Path, name: &str) -> bool {+    if name.is_empty() {+        repo_config_remove(root, "bookmark.current")+    } else {+        repo_config_set(root, "bookmark.current", name)+    }+}++pub fn clear_current_bookmark(root: &Path) -> bool {+    repo_config_remove(root, "bookmark.current")+}++pub fn random_u64() -> u64 {+    let mut value = [0u8; 8];+    if let Ok(mut file) = fs::File::open("/dev/urandom")+        && file.read_exact(&mut value).is_ok()+    {+        return u64::from_le_bytes(value);+    }+    let mut hasher = blake3::Hasher::new();+    hasher.update(&crate::time::now_millis().to_le_bytes());+    hasher.update(&std::process::id().to_le_bytes());+    hasher.update(format!("{:?}", std::time::Instant::now()).as_bytes());+    let digest = hasher.finalize();+    let mut bytes = [0u8; 8];+    bytes.copy_from_slice(&digest.as_bytes()[..8]);+    u64::from_le_bytes(bytes)+}++impl From<std::ffi::OsString> for Error {+    fn from(value: std::ffi::OsString) -> Self {+        Error::new(value.to_string_lossy())+    }+}++#[derive(Clone, Default)]+pub struct IgnoreRule {+    pub pattern: String,+    pub negated: bool,+    pub dir_only: bool,+    pub anchored: bool,+    pub has_slash: bool,+    pub base: String,+}++#[derive(Clone, Default)]+pub struct IgnoreRules {+    pub items: Vec<IgnoreRule>,+}++pub fn ignore_empty() -> IgnoreRules {+    IgnoreRules::default()+}++fn ignore_add_line(rules: &mut IgnoreRules, base: &str, input: &str) {+    let line = trim_str(input);+    if line.is_empty() || line.starts_with('#') {+        return;+    }+    let mut negated = false;+    let mut start = 0;+    if line.starts_with('!') {+        negated = true;+        start = 1;+    }+    if start >= line.len() {+        return;+    }+    let bytes = line.as_bytes();+    let mut end = bytes.len();+    let mut dir_only = false;+    if bytes[end - 1] == b'/' {+        dir_only = true;+        end -= 1;+    }+    if start >= end {+        return;+    }+    let mut anchored = false;+    if bytes[start] == b'/' {+        anchored = true;+        start += 1;+    }+    if start >= end {+        return;+    }+    let pattern = &line[start..end];+    rules.items.push(IgnoreRule {+        pattern: pattern.to_string(),+        negated,+        dir_only,+        anchored,+        has_slash: pattern.contains('/'),+        base: base.to_string(),+    });+}++pub fn ignore_load_file(rules: &mut IgnoreRules, root: &Path, base: &str, name: &str) {+    let directory = if base.is_empty() {+        root.to_path_buf()+    } else {+        root.join(base)+    };+    let Some(data) = read_file_opt(&directory.join(name), 0) else {+        return;+    };+    let text = String::from_utf8_lossy(&data);+    for line in text.lines() {+        ignore_add_line(rules, base, line);+    }+}++pub fn ignore_load_root(rules: &mut IgnoreRules, root: &Path) {+    ignore_load_file(rules, root, "", ".vnexclude");+    ignore_load_file(rules, root, "", ".gitignore");+}++#[derive(Clone, Copy)]+struct GlobState {+    pi: usize,+    ti: usize,+}++/// LIFO of match states that keeps small searches off the heap.+struct GlobStack {+    inline: [GlobState; 128],+    spilled: Vec<GlobState>,+    length: usize,+}++impl GlobStack {+    fn new() -> Self {+        Self {+            inline: [GlobState { pi: 0, ti: 0 }; 128],+            spilled: Vec::new(),+            length: 0,+        }+    }++    fn push(&mut self, state: GlobState) {+        if self.length < self.inline.len() {+            self.inline[self.length] = state;+            self.length += 1;+        } else {+            self.spilled.push(state);+        }+    }++    fn pop(&mut self) -> Option<GlobState> {+        if let Some(state) = self.spilled.pop() {+            return Some(state);+        }+        if self.length == 0 {+            return None;+        }+        self.length -= 1;+        Some(self.inline[self.length])+    }+}++pub fn glob_match(pattern: &str, text: &str) -> bool {+    let pattern = pattern.as_bytes();+    let text = text.as_bytes();+    const MAX_WORK: usize = 1_000_000;+    fn push(stack: &mut GlobStack, work: &mut usize, state: GlobState) -> bool {+        if *work >= MAX_WORK {+            return false;+        }+        *work += 1;+        stack.push(state);+        true+    }+    let mut stack = GlobStack::new();+    let mut work = 0usize;+    if !push(&mut stack, &mut work, GlobState { pi: 0, ti: 0 }) {+        return false;+    }+    while let Some(state) = stack.pop() {+        let p = state.pi;+        let t = state.ti;+        if p >= pattern.len() {+            if t >= text.len() {+                return true;+            }+            continue;+        }+        let pc = pattern[p];+        if pc == b'*' {+            let double = p + 1 < pattern.len() && pattern[p + 1] == b'*';+            if double {+                let next = p + 2;+                if next < pattern.len() && pattern[next] == b'/' {+                    let after = next + 1;+                    let mut j = t;+                    loop {+                        if !push(&mut stack, &mut work, GlobState { pi: after, ti: j }) {+                            return false;+                        }+                        if j >= text.len() {+                            break;+                        }+                        if text[j] == b'/' {+                            j += 1;+                            continue;+                        }+                        j += 1;+                        while j < text.len() && text[j] != b'/' {+                            j += 1;+                        }+                    }+                } else {+                    let mut j = t;+                    loop {+                        if !push(&mut stack, &mut work, GlobState { pi: next, ti: j }) {+                            return false;+                        }+                        if j >= text.len() {+                            break;+                        }+                        j += 1;+                    }+                }+            } else {+                let mut j = t;+                loop {+                    if !push(&mut stack, &mut work, GlobState { pi: p + 1, ti: j }) {+                        return false;+                    }+                    if j >= text.len() || text[j] == b'/' {+                        break;+                    }+                    j += 1;+                }+            }+            continue;+        }+        if t >= text.len() {+            continue;+        }+        if pc == b'?' {+            if text[t] != b'/' {+                let _ = push(+                    &mut stack,+                    &mut work,+                    GlobState {+                        pi: p + 1,+                        ti: t + 1,+                    },+                );+            }+            continue;+        }+        if pc == text[t] {+            let _ = push(+                &mut stack,+                &mut work,+                GlobState {+                    pi: p + 1,+                    ti: t + 1,+                },+            );+        }+    }+    false+}++fn relative_to<'a>(base: &str, path: &'a str) -> Option<&'a str> {+    if base.is_empty() {+        return Some(path);+    }+    if path.len() <= base.len() || !path.starts_with(base) {+        return None;+    }+    if path.as_bytes()[base.len()] != b'/' {+        return None;+    }+    Some(&path[base.len() + 1..])+}++fn rule_matches(rule: &IgnoreRule, path: &str, is_dir: bool) -> bool {+    let Some(relative) = relative_to(&rule.base, path) else {+        return false;+    };+    if relative.is_empty() || (rule.dir_only && !is_dir) {+        return false;+    }+    if !rule.has_slash && !rule.anchored {+        let mut start = 0;+        loop {+            let end = relative[start..]+                .find('/')+                .map(|offset| start + offset)+                .unwrap_or(relative.len());+            if glob_match(&rule.pattern, &relative[start..end]) {+                return true;+            }+            if end >= relative.len() {+                break;+            }+            start = end + 1;+        }+        return false;+    }+    glob_match(&rule.pattern, relative)+}++pub fn ignore_ignored(rules: &IgnoreRules, path: &str, is_dir: bool) -> bool {+    let mut ignored = false;+    for rule in &rules.items {+        if rule_matches(rule, path, is_dir) {+            ignored = !rule.negated;+        }+    }+    ignored+}++pub fn ignore_path_ignored(root: &Path, path: &str) -> bool {+    let mut rules = ignore_empty();+    ignore_load_root(&mut rules, root);+    for (index, byte) in path.bytes().enumerate() {+        if byte == b'/' {+            let base = &path[..index];+            ignore_load_file(&mut rules, root, base, ".vnexclude");+            ignore_load_file(&mut rules, root, base, ".gitignore");+        }+    }+    for (index, byte) in path.bytes().enumerate() {+        if byte == b'/' && ignore_ignored(&rules, &path[..index], true) {+            return true;+        }+    }+    ignore_ignored(&rules, path, false)+}++const PROGRESS_WIDTH: usize = 24;++fn progress_enabled() -> bool {+    for name in ["NO_PROGRESS", "VN_NO_PROGRESS"] {+        if env::var_os(name).is_some_and(|value| !value.is_empty() && value != "0") {+            return false;+        }+    }+    if env::var_os("VN_PROGRESS").is_some_and(|value| !value.is_empty() && value != "0") {+        return true;+    }+    if env::var("TERM").is_ok_and(|term| term == "dumb") {+        return false;+    }+    stderr_is_terminal()+}++fn styled_info_prefix(color: bool) -> &'static str {+    if color {+        "\r\x1b[2K\x1b[1m\x1b[36minfo\x1b[0m: "+    } else {+        "\r\x1b[2Kinfo: "+    }+}++struct ProgressState {+    total: usize,+    done: usize,+    last_done: usize,+    last_total: usize,+    last_draw: Option<std::time::Instant>,+    drawn: bool,+    finished: bool,+}++pub struct Progress {+    label: String,+    enabled: bool,+    state: std::sync::Mutex<ProgressState>,+}++impl Progress {+    pub fn new(label: impl Into<String>, total: usize) -> Self {+        Self {+            label: label.into(),+            enabled: progress_enabled(),+            state: std::sync::Mutex::new(ProgressState {+                total,+                done: 0,+                last_done: usize::MAX,+                last_total: usize::MAX,+                last_draw: None,+                drawn: false,+                finished: false,+            }),+        }+    }++    pub fn set_total(&self, total: usize) {+        if let Ok(mut state) = self.state.lock() {+            state.total = total;+            self.refresh(&mut state, true);+        }+    }++    pub fn update(&self, done: usize, force: bool) {+        if let Ok(mut state) = self.state.lock() {+            state.done = done;+            self.refresh(&mut state, force);+        }+    }++    pub fn advance(&self, amount: usize) {+        if let Ok(mut state) = self.state.lock() {+            state.done = state.done.saturating_add(amount);+            self.refresh(&mut state, false);+        }+    }++    pub fn finish(&self) {+        let Ok(mut state) = self.state.lock() else {+            return;+        };+        if !self.enabled || state.finished {+            return;+        }+        state.finished = true;+        if state.total > 0 {+            if state.done < state.total {+                state.done = state.total;+            }+            if !state.drawn || state.last_done != state.done || state.last_total != state.total {+                self.draw(&mut state);+            }+            eprintln!();+        } else if state.drawn {+            eprint!("\r\x1b[2K");+            let _ = std::io::stderr().flush();+        }+        state.drawn = false;+    }++    pub fn clear(&self) {+        let Ok(mut state) = self.state.lock() else {+            return;+        };+        if self.enabled && state.drawn {+            eprint!("\r\x1b[2K");+            let _ = std::io::stderr().flush();+        }+        state.drawn = false;+        state.finished = true;+    }++    fn refresh(&self, state: &mut ProgressState, force: bool) {+        if !self.enabled || state.finished {+            return;+        }+        let now = std::time::Instant::now();+        let complete = state.total > 0 && state.done >= state.total;+        if !force+            && !complete+            && state+                .last_draw+                .is_some_and(|last| now.duration_since(last) < std::time::Duration::from_millis(66))+        {+            return;+        }+        state.last_draw = Some(now);+        self.draw(state);+        state.drawn = true;+    }++    fn draw(&self, state: &mut ProgressState) {+        let color = colors_enabled();+        let mut line = String::with_capacity(128);+        line.push_str(styled_info_prefix(color));+        line.push_str(&self.label);+        line.push_str("  ");+        if state.total > 0 {+            let filled = std::cmp::min(+                PROGRESS_WIDTH,+                ((state.done as u128 * PROGRESS_WIDTH as u128) / state.total as u128) as usize,+            );+            line.push('[');+            if filled >= PROGRESS_WIDTH {+                if color {+                    line.push_str("\x1b[32m");+                }+                for _ in 0..PROGRESS_WIDTH {+                    line.push('=');+                }+            } else {+                let head = if filled == 0 { 1 } else { filled };+                if color {+                    line.push_str("\x1b[32m");+                }+                for _ in 0..head.saturating_sub(1) {+                    line.push('=');+                }+                line.push('>');+                if color {+                    line.push_str("\x1b[0m");+                }+                for _ in head..PROGRESS_WIDTH {+                    line.push(' ');+                }+            }+            if color {+                line.push_str("\x1b[0m");+            }+            line.push(']');+            if color {+                line.push_str(" \x1b[36m");+            } else {+                line.push(' ');+            }+            line.push_str(&(state.done * 100 / state.total).min(100).to_string());+            line.push('%');+            if color {+                line.push_str("\x1b[0m\x1b[2m");+            }+            line.push(' ');+            line.push_str(&state.done.to_string());+            line.push('/');+            line.push_str(&state.total.to_string());+            if color {+                line.push_str("\x1b[0m");+            }+        } else {+            const FRAMES: [char; 4] = ['|', '/', '-', '\\'];+            let frame = FRAMES[state.done % 4];+            if color {+                line.push_str("\x1b[36m");+                line.push(frame);+                line.push_str("\x1b[0m\x1b[2m");+            } else {+                line.push(frame);+            }+            line.push(' ');+            line.push_str(&state.done.to_string());+            if color {+                line.push_str("\x1b[0m");+            }+        }+        eprint!("{line}");+        let _ = std::io::stderr().flush();+        state.last_done = state.done;+        state.last_total = state.total;+    }+}++impl Drop for Progress {+    fn drop(&mut self) {+        let Ok(state) = self.state.lock() else {+            return;+        };+        if !self.enabled || !state.drawn || state.finished {+            return;+        }+        eprint!("\r\x1b[2K");+        let _ = std::io::stderr().flush();+    }+}--- /dev/null+++ b/veins/src/crypto.rs@@ -0,0 +1,576 @@+use std::fs;++use ring::signature::KeyPair;++pub type PublicKey = [u8; 32];+pub type Signature = [u8; 64];++pub fn ed25519_public_from_seed(seed: &[u8]) -> Option<PublicKey> {+    if seed.len() != 32 {+        return None;+    }+    let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(seed).ok()?;+    let public = pair.public_key().as_ref();+    if public.len() != 32 {+        return None;+    }+    let mut output = [0u8; 32];+    output.copy_from_slice(public);+    Some(output)+}++pub fn ed25519_sign(seed: &[u8], message: &[u8]) -> Option<Signature> {+    if seed.len() != 32 {+        return None;+    }+    let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(seed).ok()?;+    let signature = pair.sign(message);+    let bytes = signature.as_ref();+    if bytes.len() != 64 {+        return None;+    }+    let mut output = [0u8; 64];+    output.copy_from_slice(bytes);+    Some(output)+}++pub fn ed25519_verify(public_key: &PublicKey, message: &[u8], signature: &[u8]) -> bool {+    if signature.len() != 64 {+        return false;+    }+    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key)+        .verify(message, signature)+        .is_ok()+}++pub fn key_fingerprint_bytes(public_key: &PublicKey) -> [u8; 16] {+    let mut hasher = blake3::Hasher::new();+    hasher.update(b"veins/key/1\0");+    hasher.update(public_key);+    let digest = hasher.finalize();+    let mut output = [0u8; 16];+    output.copy_from_slice(&digest.as_bytes()[..16]);+    output+}++pub fn base32_text(raw: &[u8]) -> String {+    const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+    let mut output = String::with_capacity(raw.len() * 8 / 5 + 2);+    let mut bits = 0u64;+    let mut count = 0usize;+    for byte in raw {+        bits = (bits << 8) | *byte as u64;+        count += 8;+        while count >= 5 {+            count -= 5;+            output.push(ALPHABET[((bits >> count) & 31) as usize] as char);+        }+    }+    if count > 0 {+        output.push(ALPHABET[((bits << (5 - count)) & 31) as usize] as char);+    }+    output+}++pub fn key_fingerprint(public_key: &PublicKey) -> String {+    base32_text(&key_fingerprint_bytes(public_key))+}++pub fn base64url_encode(raw: &[u8]) -> String {+    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+    let mut output = String::with_capacity(raw.len() * 4 / 3 + 4);+    let mut accumulator = 0u32;+    let mut bits = 0usize;+    for byte in raw {+        accumulator = (accumulator << 8) | *byte as u32;+        bits += 8;+        while bits >= 6 {+            bits -= 6;+            output.push(ALPHABET[((accumulator >> bits) & 63) as usize] as char);+        }+    }+    if bits > 0 {+        output.push(ALPHABET[((accumulator << (6 - bits)) & 63) as usize] as char);+    }+    output+}++pub fn base64url_decode(text: &str) -> Option<Vec<u8>> {+    if text.is_empty() {+        return None;+    }+    let value = |character: u8| -> Option<u32> {+        match character {+            b'A'..=b'Z' => Some((character - b'A') as u32),+            b'a'..=b'z' => Some((character - b'a' + 26) as u32),+            b'0'..=b'9' => Some((character - b'0' + 52) as u32),+            b'-' => Some(62),+            b'_' => Some(63),+            _ => None,+        }+    };+    let mut output = Vec::with_capacity(text.len() * 6 / 8);+    let mut accumulator = 0u32;+    let mut bits = 0usize;+    for character in text.bytes() {+        accumulator = (accumulator << 6) | value(character)?;+        bits += 6;+        if bits >= 8 {+            bits -= 8;+            output.push(((accumulator >> bits) & 255) as u8);+        }+    }+    Some(output)+}++pub fn format_public_key(public_key: &PublicKey) -> String {+    format!("ed25519:{}", base64url_encode(public_key))+}++pub fn parse_public_key(text: &str) -> Option<PublicKey> {+    let value = text.strip_prefix("ed25519:")?;+    let decoded = base64url_decode(value)?;+    if decoded.len() != 32 {+        return None;+    }+    let mut output = [0u8; 32];+    output.copy_from_slice(&decoded);+    Some(output)+}++pub fn secure_random(count: usize) -> Vec<u8> {+    use ring::rand::SecureRandom;+    let mut output = vec![0u8; count];+    let random = ring::rand::SystemRandom::new();+    if random.fill(&mut output).is_err() {+        return Vec::new();+    }+    output+}++pub struct Key {+    pub name: String,+    pub seed: Vec<u8>,+    pub public_key: PublicKey,+    pub fingerprint: String,+}++pub fn key_dir() -> std::path::PathBuf {+    if let Ok(value) = std::env::var("XDG_CONFIG_HOME")+        && !value.is_empty()+    {+        return std::path::PathBuf::from(value).join("veins").join("keys");+    }+    if let Ok(home) = std::env::var("HOME")+        && !home.is_empty()+    {+        return std::path::PathBuf::from(home)+            .join(".config")+            .join("veins")+            .join("keys");+    }+    std::path::PathBuf::from(".veins-keys")+}++fn valid_key_name(name: &str) -> bool {+    !name.is_empty() && name.len() <= 128 && !name.contains(['/', '\\', '\0'])+}++pub fn key_path(name: &str) -> std::path::PathBuf {+    key_dir().join(format!("{name}.key"))+}++pub fn load_key(name: &str) -> Option<Key> {+    if !valid_key_name(name) {+        return None;+    }+    let path = key_path(name);+    let metadata = fs::metadata(&path).ok()?;+    if crate::platform::permissions_mode(&metadata) & 63 != 0 {+        return None;+    }+    let data = fs::read(path).ok()?;+    if data.len() != 33 || data[0] != 1 {+        return None;+    }+    let seed = data[1..].to_vec();+    let public_key = ed25519_public_from_seed(&seed)?;+    Some(Key {+        name: name.to_string(),+        fingerprint: key_fingerprint(&public_key),+        seed,+        public_key,+    })+}++pub fn generate_key(name: &str) -> Option<Key> {+    if !valid_key_name(name) {+        return None;+    }+    let directory = key_dir();+    fs::create_dir_all(&directory).ok()?;+    let _ = crate::platform::set_mode(&directory, 0o700);+    let seed = secure_random(32);+    if seed.len() != 32 {+        return None;+    }+    let public_key = ed25519_public_from_seed(&seed)?;+    let mut body = Vec::with_capacity(33);+    body.push(1);+    body.extend_from_slice(&seed);+    let path = key_path(name);+    fs::write(&path, &body).ok()?;+    let _ = crate::platform::set_mode(&path, 0o600);+    Some(Key {+        name: name.to_string(),+        fingerprint: key_fingerprint(&public_key),+        seed,+        public_key,+    })+}++pub fn list_key_names() -> Vec<String> {+    let directory = key_dir();+    let mut output = Vec::new();+    for name in crate::core::list_directory(&directory) {+        let text = String::from_utf8_lossy(&name);+        if let Some(stem) = text.strip_suffix(".key") {+            output.push(stem.to_string());+        }+    }+    output+}++pub fn auth_dir() -> std::path::PathBuf {+    let directory = key_dir();+    match directory.parent() {+        Some(parent) => parent.join("auth"),+        None => std::path::PathBuf::from(".veins-auth"),+    }+}++fn authority_of(input: &str) -> Option<String> {+    let text = crate::core::trim_str(input);+    let mut start = 0;+    if let Some(scheme) = text.find("://") {+        start = scheme + 3;+    }+    if start >= text.len() {+        return None;+    }+    let end = text[start..]+        .find('/')+        .map(|offset| start + offset)+        .unwrap_or(text.len());+    if end <= start {+        return None;+    }+    let raw = &text[start..end];+    let host = raw.rsplit('@').next().unwrap_or(raw);+    if host.is_empty() {+        return None;+    }+    Some(host.to_ascii_lowercase())+}++pub fn normalize_target(target: &str) -> String {+    let text = crate::core::trim_str(target);+    if text.is_empty() || text == "default" {+        return "default".to_string();+    }+    if let Some(authority) = authority_of(text) {+        return authority;+    }+    let raw = text.split('/').next().unwrap_or(text);+    let host = raw.rsplit('@').next().unwrap_or(raw);+    if host.is_empty() {+        "default".to_string()+    } else {+        host.to_ascii_lowercase()+    }+}++fn hex_encode(data: &[u8]) -> String {+    let mut output = String::with_capacity(data.len() * 2);+    for byte in data {+        output.push_str(&format!("{byte:02x}"));+    }+    output+}++fn hex_decode(text: &str) -> Option<Vec<u8>> {+    if text.is_empty() || text.len() % 2 != 0 {+        return None;+    }+    let value = |character: u8| -> Option<u8> {+        match character {+            b'0'..=b'9' => Some(character - b'0'),+            b'a'..=b'f' => Some(character - b'a' + 10),+            _ => None,+        }+    };+    let mut output = Vec::with_capacity(text.len() / 2);+    for pair in text.as_bytes().chunks(2) {+        output.push((value(pair[0])? << 4) | value(pair[1])?);+    }+    Some(output)+}++fn target_path(directory: &std::path::Path, target: &str) -> std::path::PathBuf {+    directory.join(hex_encode(target.as_bytes()))+}++pub fn set_key(target: &str, key_name: &str) -> bool {+    if target.is_empty() || key_name.is_empty() {+        return false;+    }+    let directory = auth_dir();+    if !crate::core::ensure_directory(&directory) {+        return false;+    }+    crate::core::write_file(&target_path(&directory, target), key_name.as_bytes())+}++pub fn remove_key(target: &str) -> bool {+    crate::core::remove_file(&target_path(&auth_dir(), target))+}++pub fn list_credentials() -> Vec<String> {+    let directory = auth_dir();+    let mut output = Vec::new();+    for name in crate::core::list_directory(&directory) {+        let Some(decoded) = hex_decode(&String::from_utf8_lossy(&name)) else {+            continue;+        };+        let Ok(decoded) = String::from_utf8(decoded) else {+            continue;+        };+        let Some(data) = crate::core::read_file_opt(&target_path(&directory, &decoded), 0) else {+            continue;+        };+        let key = String::from_utf8_lossy(&data).trim().to_string();+        if !key.is_empty() {+            output.push(format!("{decoded}: {key}\n"));+        }+    }+    output+}++pub fn local_key_exists(name: &str) -> bool {+    !name.is_empty() && !name.starts_with("ed25519:") && load_key(name).is_some()+}++fn lookup_credential(directory: &std::path::Path, target: &str) -> Option<String> {+    let data = crate::core::read_file_opt(&target_path(directory, target), 0)?;+    let value = String::from_utf8_lossy(&data).trim().to_string();+    if value.is_empty() { None } else { Some(value) }+}++pub fn key_for_url(url: &str) -> Option<String> {+    let directory = auth_dir();+    if let Some(authority) = authority_of(url) {+        if let Some(key) = lookup_credential(&directory, &authority) {+            return Some(key);+        }+        if let Some((host, _)) = authority.rsplit_once(':')+            && let Some(key) = lookup_credential(&directory, host)+        {+            return Some(key);+        }+    }+    lookup_credential(&directory, "default")+}++#[derive(Clone)]+pub struct AccessEntry {+    pub public_key: PublicKey,+    pub name: String,+    pub role: u8,+}++#[derive(Clone)]+pub struct Access {+    pub valid: bool,+    pub error_line: i64,+    pub anonymous_read: bool,+    pub entries: Vec<AccessEntry>,+}++pub fn empty_access() -> Access {+    Access {+        valid: true,+        error_line: 0,+        anonymous_read: false,+        entries: Vec::new(),+    }+}++pub fn access_path(repo_root: &std::path::Path) -> std::path::PathBuf {+    crate::store::layout::veins_dir(repo_root).join("access")+}++pub fn load_access(repo_root: &std::path::Path) -> Access {+    let path = access_path(repo_root);+    if let Ok(metadata) = fs::metadata(&path)+        && crate::platform::permissions_mode(&metadata) & 18 != 0+    {+        return Access {+            valid: false,+            error_line: 0,+            anonymous_read: false,+            entries: Vec::new(),+        };+    }+    let Some(data) = crate::core::read_file_opt(&path, 0) else {+        return empty_access();+    };+    let text = String::from_utf8_lossy(&data);+    let mut access = empty_access();+    for (index, raw) in text.lines().enumerate() {+        let line = crate::core::trim_str(raw);+        if line.is_empty() || line.starts_with('#') {+            continue;+        }+        let tokens: Vec<&str> = line.split_whitespace().collect();+        let bad = if tokens.len() == 2 && tokens[0] == "anonymous" {+            if tokens[1] == "read" {+                access.anonymous_read = true;+                false+            } else {+                true+            }+        } else if tokens.len() >= 3 && tokens[0] == "allow" {+            let role = match tokens[1] {+                "read" => 1,+                "write" => 2,+                _ => 0,+            };+            match parse_public_key(tokens[2]) {+                Some(public_key) if role != 0 => {+                    if access+                        .entries+                        .iter()+                        .any(|entry| entry.public_key == public_key)+                    {+                        true+                    } else {+                        access.entries.push(AccessEntry {+                            public_key,+                            name: tokens.get(3).copied().unwrap_or("").to_string(),+                            role,+                        });+                        false+                    }+                }+                _ => true,+            }+        } else {+            true+        };+        if bad {+            return Access {+                valid: false,+                error_line: index as i64 + 1,+                anonymous_read: false,+                entries: Vec::new(),+            };+        }+    }+    access+}++fn set_mode(path: &std::path::Path, mode: u32) {+    let _ = crate::platform::set_mode(path, mode);+}++pub fn write_access(repo_root: &std::path::Path, access: &Access) -> bool {+    let mut body = String::from("# veins access policy\n");+    if access.anonymous_read {+        body.push_str("anonymous read\n");+    }+    for entry in &access.entries {+        if entry.name.len() > 64 {+            return false;+        }+        body.push_str("allow ");+        body.push_str(if entry.role == 2 { "write" } else { "read" });+        body.push(' ');+        body.push_str(&format_public_key(&entry.public_key));+        if !entry.name.is_empty() {+            body.push(' ');+            body.push_str(&entry.name);+        }+        body.push('\n');+    }+    let path = access_path(repo_root);+    if !crate::core::write_file(&path, body.as_bytes()) {+        return false;+    }+    set_mode(&path, 0o600);+    true+}++pub fn role_for(access: &Access, public_key: Option<&PublicKey>) -> u8 {+    match public_key {+        None => {+            if access.anonymous_read {+                1+            } else {+                0+            }+        }+        Some(public_key) => access+            .entries+            .iter()+            .find(|entry| entry.public_key == *public_key)+            .map(|entry| entry.role)+            .unwrap_or(255),+    }+}++pub fn add_access(+    repo_root: &std::path::Path,+    role: u8,+    public_key: &PublicKey,+    name: &str,+) -> bool {+    let mut access = load_access(repo_root);+    if !access.valid+        || access+            .entries+            .iter()+            .any(|entry| entry.public_key == *public_key)+    {+        return false;+    }+    access.entries.push(AccessEntry {+        public_key: *public_key,+        name: name.to_string(),+        role,+    });+    write_access(repo_root, &access)+}++pub fn remove_access(repo_root: &std::path::Path, fingerprint: &str, name: &str) -> bool {+    let mut access = load_access(repo_root);+    if !access.valid {+        return false;+    }+    let before = access.entries.len();+    access.entries.retain(|entry| {+        let by_fingerprint =+            !fingerprint.is_empty() && key_fingerprint(&entry.public_key) == fingerprint;+        let by_name = !name.is_empty() && entry.name == name;+        !(by_fingerprint || by_name)+    });+    access.entries.len() != before && write_access(repo_root, &access)+}++pub fn set_anonymous(repo_root: &std::path::Path, enabled: bool) -> bool {+    let mut access = load_access(repo_root);+    if !access.valid {+        return false;+    }+    access.anonymous_read = enabled;+    write_access(repo_root, &access)+}--- /dev/null+++ b/veins/src/encoding/mod.rs@@ -0,0 +1,5 @@+pub mod reader;+pub mod writer;++pub use reader::Reader;+pub use writer::Writer;--- /dev/null+++ b/veins/src/encoding/reader.rs@@ -0,0 +1,112 @@+use crate::error::{Error, Result};+use crate::object::id::Id;++pub struct Reader<'a> {+    data: &'a [u8],+    position: usize,+}++impl<'a> Reader<'a> {+    pub fn new(data: &'a [u8]) -> Self {+        Self { data, position: 0 }+    }++    pub fn offset(&self) -> usize {+        self.position+    }++    pub fn remaining(&self) -> usize {+        self.data.len().saturating_sub(self.position)+    }++    fn take(&mut self, length: usize) -> Result<&'a [u8]> {+        if length > self.remaining() {+            return Err(Error::new("unexpected end of input"));+        }+        let start = self.position;+        self.position += length;+        Ok(&self.data[start..start + length])+    }++    pub fn u8(&mut self) -> Result<u8> {+        Ok(self.take(1)?[0])+    }++    pub fn u16le(&mut self) -> Result<u16> {+        let bytes = self.take(2)?;+        Ok(u16::from_le_bytes([bytes[0], bytes[1]]))+    }++    pub fn u32le(&mut self) -> Result<u32> {+        let bytes = self.take(4)?;+        Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))+    }++    pub fn u64le(&mut self) -> Result<u64> {+        let bytes = self.take(8)?;+        let mut value = [0u8; 8];+        value.copy_from_slice(bytes);+        Ok(u64::from_le_bytes(value))+    }++    pub fn i16le(&mut self) -> Result<i16> {+        Ok(self.u16le()? as i16)+    }++    pub fn i64le(&mut self) -> Result<i64> {+        Ok(self.u64le()? as i64)+    }++    pub fn varint(&mut self) -> Result<u64> {+        let mut value = 0u64;+        for index in 0..10 {+            let byte = self.u8()?;+            if index == 9 && byte > 1 {+                return Err(Error::new("varint overflow"));+            }+            value |= u64::from(byte & 0x7f) << (index * 7);+            if byte & 0x80 == 0 {+                if index > 0 && byte == 0 {+                    return Err(Error::new("non-minimal varint"));+                }+                return Ok(value);+            }+        }+        Err(Error::new("varint too long"))+    }++    pub fn bytes(&mut self, maximum: usize) -> Result<&'a [u8]> {+        let length = self.varint()?;+        let length = usize::try_from(length).map_err(|_| Error::new("length overflow"))?;+        if length > maximum {+            return Err(Error::new("length limit exceeded"));+        }+        self.take(length)+    }++    pub fn raw(&mut self, length: usize) -> Result<&'a [u8]> {+        self.take(length)+    }++    pub fn id(&mut self) -> Result<Id> {+        let mut value = [0u8; 32];+        value.copy_from_slice(self.take(32)?);+        Ok(Id(value))+    }++    pub fn opt_id(&mut self) -> Result<Option<Id>> {+        match self.u8()? {+            0 => Ok(None),+            1 => Ok(Some(self.id()?)),+            _ => Err(Error::new("invalid optional value")),+        }+    }++    pub fn finish(&self) -> Result<()> {+        if self.position == self.data.len() {+            Ok(())+        } else {+            Err(Error::new("trailing bytes"))+        }+    }+}--- /dev/null+++ b/veins/src/encoding/writer.rs@@ -0,0 +1,105 @@+use crate::object::id::Id;++#[derive(Default)]+pub struct Writer {+    data: Vec<u8>,+}++impl Writer {+    pub fn new() -> Self {+        Self::default()+    }++    pub fn with_capacity(capacity: usize) -> Self {+        Self {+            data: Vec::with_capacity(capacity),+        }+    }++    pub fn len(&self) -> usize {+        self.data.len()+    }++    pub fn is_empty(&self) -> bool {+        self.data.is_empty()+    }++    pub fn u8(&mut self, value: u8) {+        self.data.push(value);+    }++    pub fn u16le(&mut self, value: u16) {+        self.data.extend_from_slice(&value.to_le_bytes());+    }++    pub fn u32le(&mut self, value: u32) {+        self.data.extend_from_slice(&value.to_le_bytes());+    }++    pub fn u64le(&mut self, value: u64) {+        self.data.extend_from_slice(&value.to_le_bytes());+    }++    pub fn i16le(&mut self, value: i16) {+        self.u16le(value as u16);+    }++    pub fn i64le(&mut self, value: i64) {+        self.u64le(value as u64);+    }++    pub fn varint_into(output: &mut Vec<u8>, mut value: u64) {+        loop {+            let byte = (value & 0x7f) as u8;+            value >>= 7;+            if value == 0 {+                output.push(byte);+                return;+            }+            output.push(byte | 0x80);+        }+    }++    pub fn varint(&mut self, mut value: u64) {+        loop {+            let byte = (value & 0x7f) as u8;+            value >>= 7;+            if value == 0 {+                self.data.push(byte);+                return;+            }+            self.data.push(byte | 0x80);+        }+    }++    pub fn raw(&mut self, bytes: &[u8]) {+        self.data.extend_from_slice(bytes);+    }++    pub fn bytes(&mut self, bytes: &[u8]) {+        self.varint(bytes.len() as u64);+        self.data.extend_from_slice(bytes);+    }++    pub fn id(&mut self, id: Id) {+        self.data.extend_from_slice(&id.0);+    }++    pub fn opt_id(&mut self, id: Option<Id>) {+        match id {+            Some(value) => {+                self.u8(1);+                self.id(value);+            }+            None => self.u8(0),+        }+    }++    pub fn into_vec(self) -> Vec<u8> {+        self.data+    }++    pub fn as_slice(&self) -> &[u8] {+        &self.data+    }+}--- /dev/null+++ b/veins/src/error.rs@@ -0,0 +1,69 @@+use std::fmt;+use std::io;++pub type Result<T> = std::result::Result<T, Error>;++#[derive(Debug)]+pub struct Error {+    message: String,+}++impl Error {+    pub fn new(message: impl Into<String>) -> Self {+        Self {+            message: message.into(),+        }+    }++    pub fn io(message: impl Into<String>) -> Self {+        Self::new(message)+    }++    pub fn usage(message: impl Into<String>) -> Self {+        Self::new(message)+    }++    pub fn context(self, context: impl AsRef<str>) -> Self {+        Self::new(format!("{}: {}", context.as_ref(), self.message))+    }++    pub fn message(&self) -> &str {+        &self.message+    }+}++impl fmt::Display for Error {+    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+        formatter.write_str(&self.message)+    }+}++impl std::error::Error for Error {}++impl From<io::Error> for Error {+    fn from(error: io::Error) -> Self {+        Self::new(error.to_string())+    }+}++impl From<String> for Error {+    fn from(message: String) -> Self {+        Self::new(message)+    }+}++impl From<&str> for Error {+    fn from(message: &str) -> Self {+        Self::new(message)+    }+}++pub trait OptionExt<T> {+    fn or_error(self, message: impl Into<String>) -> Result<T>;+}++impl<T> OptionExt<T> for Option<T> {+    fn or_error(self, message: impl Into<String>) -> Result<T> {+        self.ok_or_else(|| Error::new(message))+    }+}--- /dev/null+++ b/veins/src/git.rs@@ -0,0 +1,847 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::blob;+use crate::object::commit::{self, Commit, Sig};+use crate::object::id::Id;+use crate::object::tree::{self, FlatEntry, TreeEntry};+use crate::object::view::{Bookmark, TagRef};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;++#[derive(Clone, Copy)]+pub struct Oid(pub [u8; 20]);++impl Oid {+    pub fn from_hex(text: &str) -> Option<Self> {+        if text.len() != 40 {+            return None;+        }+        let mut value = [0u8; 20];+        for index in 0..20 {+            let high = hex_value(text.as_bytes()[index * 2])?;+            let low = hex_value(text.as_bytes()[index * 2 + 1])?;+            value[index] = (high << 4) | low;+        }+        Some(Self(value))+    }++    pub fn hex(self) -> String {+        let mut output = String::with_capacity(40);+        for byte in self.0 {+            output.push_str(&format!("{byte:02x}"));+        }+        output+    }+}++fn hex_value(byte: u8) -> Option<u8> {+    match byte {+        b'0'..=b'9' => Some(byte - b'0'),+        b'a'..=b'f' => Some(byte - b'a' + 10),+        b'A'..=b'F' => Some(byte - b'A' + 10),+        _ => None,+    }+}++fn mirror_dir(root: &Path) -> PathBuf {+    layout::git_dir(root)+}++fn run_git(arguments: &[&str], cwd: Option<&Path>, stdin: Option<&[u8]>) -> Result<Vec<u8>> {+    let mut command = Command::new("git");+    command.args(arguments);+    if let Some(cwd) = cwd {+        command.current_dir(cwd);+    }+    command.stdout(Stdio::piped()).stderr(Stdio::piped());+    if stdin.is_some() {+        command.stdin(Stdio::piped());+    } else {+        command.stdin(Stdio::null());+    }+    let mut child = command.spawn().map_err(Error::from)?;+    if let Some(data) = stdin {+        use std::io::Write;+        let mut pipe = child+            .stdin+            .take()+            .ok_or_else(|| Error::new("cannot open git stdin"))?;+        pipe.write_all(data).map_err(Error::from)?;+    }+    let output = child.wait_with_output().map_err(Error::from)?;+    if !output.status.success() {+        return Err(Error::new(+            String::from_utf8_lossy(&output.stderr).into_owned(),+        ));+    }+    Ok(output.stdout)+}++fn git_dir_command(arguments: &[&str], mirror: &Path, stdin: Option<&[u8]>) -> Result<Vec<u8>> {+    let mut full = vec!["--git-dir", mirror.to_str().unwrap_or("")];+    full.extend_from_slice(arguments);+    run_git(&full, None, stdin)+}++pub fn prepare_mirror(root: &Path, source: &str) -> i32 {+    let source_path = Path::new(source);+    if !source_path.join(".git").exists() {+        return 2;+    }+    let mirror = mirror_dir(root);+    let _ = std::fs::remove_dir_all(&mirror);+    if let Some(parent) = mirror.parent() {+        let _ = std::fs::create_dir_all(parent);+    }+    let mirror_text = mirror.to_str().unwrap_or("");+    match run_git(&["clone", "--mirror", source, mirror_text], None, None) {+        Ok(_) => 0,+        Err(_) => 1,+    }+}++pub fn configure_remote(root: &Path, url: &str, name: &str) {+    if url.is_empty() {+        crate::cli::output::warning_prefix();+        println!(+            "no native remote configured; set one with 'vn remote add o <url>' and push with 'vn psh o'"+        );+        return;+    }+    core::repo_config_set(root, &format!("remote.{name}.url"), url);+    core::repo_config_set(root, "remote.default", name);+}++pub fn import(root: &Path) -> i32 {+    match import_inner(root) {+        Ok(()) => 0,+        Err(error) => {+            crate::cli::output::error_prefix();+            println!("git import failed: {error}");+            1+        }+    }+}++fn import_inner(root: &Path) -> Result<()> {+    let mirror = mirror_dir(root);+    let refs_output = git_dir_command(&["for-each-ref", "--format=%(refname)"], &mirror, None)?;+    let refs_text = String::from_utf8_lossy(&refs_output);+    let mut bookmarks = Vec::new();+    let mut tags = Vec::new();+    for line in refs_text.lines() {+        let name = line.trim();+        if name.is_empty() {+            continue;+        }+        let Some(oid_text) =+            git_dir_command(&["rev-parse", &format!("{name}^{{commit}}")], &mirror, None)+                .ok()+                .and_then(|data| String::from_utf8(data).ok())+        else {+            continue;+        };+        let Some(oid) = Oid::from_hex(oid_text.trim()) else {+            continue;+        };+        if let Some(short) = name.strip_prefix("refs/heads/") {+            bookmarks.push((short.to_string(), oid));+        } else if let Some(short) = name.strip_prefix("refs/tags/") {+            tags.push((short.to_string(), oid));+        }+    }+    let revs = git_dir_command(&["rev-list", "--all", "--reverse"], &mirror, None)?;+    let revs_text = String::from_utf8_lossy(&revs);+    let mut store = Store::open(root)?;+    let mut txn = Txn::begin(root, &mut store)?;+    let mut mapped: HashMap<String, Id> = HashMap::new();+    let mut ordered: Vec<String> = revs_text+        .lines()+        .map(|line| line.trim().to_string())+        .filter(|line| !line.is_empty())+        .collect();+    ordered.reverse();+    ordered.reverse();+    let progress = crate::core::Progress::new("importing commits", ordered.len());+    for oid_text in ordered {+        let Some(oid) = Oid::from_hex(&oid_text) else {+            continue;+        };+        import_commit(&mirror, &mut txn, &mut store, oid, &mut mapped)?;+        progress.advance(1);+    }+    progress.finish();+    for (name, oid) in bookmarks {+        if let Some(target) = mapped.get(&oid.hex()) {+            set_bookmark(txn.view_mut(), &name, *target);+        }+    }+    for (name, oid) in tags {+        if let Some(target) = mapped.get(&oid.hex()) {+            set_tag(txn.view_mut(), &name, *target);+        }+    }+    ops::rebuild_heads(txn.view_mut());+    let default = bookmarks_default(&txn.view().bookmarks);+    let default_name = bookmarks_default_name(&txn.view().bookmarks);+    txn.finish("git import")?;+    store.refresh()?;+    if let Some(target) = default {+        let mut checkout_txn = Txn::begin(root, &mut store)?;+        let child = create_working_copy(&mut checkout_txn, &mut store, target)?;+        ops::set_workspace(checkout_txn.view_mut(), child);+        ops::rebuild_heads(checkout_txn.view_mut());+        checkout_txn.finish("checkout")?;+    }+    if let Some(name) = default_name {+        core::set_current_bookmark(root, &name);+    }+    materialize(root);+    Ok(())+}++fn bookmarks_default(bookmarks: &[Bookmark]) -> Option<Id> {+    for bookmark in bookmarks {+        if matches!(bookmark.name.as_slice(), b"main" | b"master") {+            return bookmark.targets.adds.first().copied().flatten();+        }+    }+    bookmarks+        .iter()+        .find_map(|bookmark| bookmark.targets.adds.first().copied().flatten())+}++fn bookmarks_default_name(bookmarks: &[Bookmark]) -> Option<String> {+    for bookmark in bookmarks {+        if matches!(bookmark.name.as_slice(), b"main" | b"master") {+            return Some(String::from_utf8_lossy(&bookmark.name).into_owned());+        }+    }+    bookmarks+        .first()+        .map(|bookmark| String::from_utf8_lossy(&bookmark.name).into_owned())+}++fn set_bookmark(view: &mut crate::object::view::View, name: &str, target: Id) {+    ops::set_bookmark_target(view, name.as_bytes(), target);+}++fn set_tag(view: &mut crate::object::view::View, name: &str, target: Id) {+    view.tags.push(TagRef {+        name: name.as_bytes().to_vec(),+        target,+    });+}++fn create_working_copy(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {+    let loaded = graph::load_commit(store, parent)?+        .ok_or_else(|| Error::new("cannot read parent commit"))?;+    let signature = identity::signature(store.root());+    let commit = Commit {+        version: 1,+        parents: vec![parent],+        root_tree: loaded.root_tree,+        change_id: identity::random_change_id(),+        author: signature.clone(),+        committer: signature,+        message: Vec::new(),+        renames_state: commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))+}++struct ParsedCommit {+    parents: Vec<String>,+    author: Sig,+    committer: Sig,+    message: Vec<u8>,+    extra: Vec<(Vec<u8>, Vec<u8>)>,+}++fn parse_sig(text: &str) -> Sig {+    let (name, rest) = text.split_once(" <").unwrap_or((text, "> 0 +0000"));+    let (email, rest) = rest.split_once('>').unwrap_or((rest, " 0 +0000"));+    let mut parts = rest.split_whitespace();+    let seconds = parts+        .next()+        .and_then(|value| value.parse().ok())+        .unwrap_or(0);+    let tz = parts.next().unwrap_or("+0000");+    let tz_min = parse_tz(tz);+    Sig {+        name: name.as_bytes().to_vec(),+        email: email.as_bytes().to_vec(),+        seconds,+        tz_min,+    }+}++fn parse_tz(text: &str) -> i16 {+    if text.len() != 5 {+        return 0;+    }+    let sign = if text.starts_with('-') { -1 } else { 1 };+    let hours: i16 = text[1..3].parse().unwrap_or(0);+    let minutes: i16 = text[3..5].parse().unwrap_or(0);+    sign * (hours * 60 + minutes)+}++fn parse_git_commit(data: &[u8]) -> Option<ParsedCommit> {+    let split = data+        .windows(2)+        .position(|window| window == b"\n\n")+        .unwrap_or(data.len());+    let header = String::from_utf8_lossy(&data[..split]);+    let message = if split + 2 <= data.len() {+        data[split + 2..].to_vec()+    } else {+        Vec::new()+    };+    let mut parents = Vec::new();+    let mut author = Sig::default();+    let mut committer = Sig::default();+    let mut extra = Vec::new();+    for line in header.lines() {+        if let Some(value) = line.strip_prefix("parent ") {+            parents.push(value.to_string());+        } else if let Some(value) = line.strip_prefix("author ") {+            author = parse_sig(value);+        } else if let Some(value) = line.strip_prefix("committer ") {+            committer = parse_sig(value);+        } else if let Some((key, value)) = line.split_once(' ')+            && !line.starts_with(' ')+            && key != "gpgsig"+        {+            extra.push((key.as_bytes().to_vec(), value.as_bytes().to_vec()));+        }+    }+    Some(ParsedCommit {+        parents,+        author,+        committer,+        message,+        extra,+    })+}++fn import_commit(+    mirror: &Path,+    txn: &mut Txn,+    store: &mut Store,+    oid: Oid,+    mapped: &mut HashMap<String, Id>,+) -> Result<()> {+    if mapped.contains_key(&oid.hex()) {+        return Ok(());+    }+    let data = git_dir_command(&["cat-file", "commit", &oid.hex()], mirror, None)?;+    let parsed = parse_git_commit(&data).ok_or_else(|| Error::new("corrupt git commit"))?;+    for parent in &parsed.parents {+        if let Some(parent_oid) = Oid::from_hex(parent)+            && !mapped.contains_key(&oid.hex())+        {+            import_commit(mirror, txn, store, parent_oid, mapped)?;+        }+    }+    let entries = git_flat_entries(mirror, &oid.hex())?;+    let root_tree = build_tree(txn, &entries)?;+    let parents: Vec<Id> = parsed+        .parents+        .iter()+        .filter_map(|parent| mapped.get(parent).copied())+        .collect();+    let change_hash = blake3::hash(oid.hex().as_bytes());+    let mut change_id = [0u8; 16];+    change_id.copy_from_slice(&change_hash.as_bytes()[..16]);+    let commit = Commit {+        version: 1,+        parents,+        root_tree,+        change_id,+        author: parsed.author,+        committer: parsed.committer,+        message: parsed.message,+        renames_state: commit::RENAMES_UNKNOWN,+        renames: Vec::new(),+        extra: parsed.extra,+    };+    let id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));+    mapped.insert(oid.hex(), id);+    Ok(())+}++fn git_flat_entries(mirror: &Path, revision: &str) -> Result<Vec<FlatEntry>> {+    let output = git_dir_command(&["ls-tree", "-r", "-z", revision], mirror, None)?;+    let mut entries = Vec::new();+    for record in output.split(|byte| *byte == 0) {+        if record.is_empty() {+            continue;+        }+        let Some(tab) = record.iter().position(|byte| *byte == b'\t') else {+            continue;+        };+        let meta = String::from_utf8_lossy(&record[..tab]).into_owned();+        let path = record[tab + 1..].to_vec();+        let mut parts = meta.split_whitespace();+        let mode = parts.next().unwrap_or("100644");+        let kind = parts.next().unwrap_or("blob");+        let oid_text = parts.next().unwrap_or("");+        let kind = if kind == "commit" || mode == "160000" {+            tree::KIND_SUBMODULE+        } else if mode == "120000" {+            tree::KIND_SYMLINK+        } else if mode == "100755" {+            tree::KIND_EXECUTABLE+        } else {+            tree::KIND_FILE+        };+        let target = if kind == tree::KIND_SUBMODULE {+            let Some(oid) = Oid::from_hex(oid_text) else {+                continue;+            };+            let mut id = [0u8; 32];+            id[..20].copy_from_slice(&oid.0);+            Id(id)+        } else {+            let data = git_dir_command(&["cat-file", "blob", oid_text], mirror, None)?;+            let build = blob::build(&data);+            for object in build.objects {+                txn_add_later(&object);+            }+            build.root+        };+        entries.push(FlatEntry { path, kind, target });+    }+    Ok(entries)+}++thread_local! {+    static PENDING: std::cell::RefCell<Vec<crate::object::RawObject>> = const { std::cell::RefCell::new(Vec::new()) };+}++fn txn_add_later(object: &crate::object::RawObject) {+    PENDING.with(|pending| pending.borrow_mut().push(object.clone()));+}++fn drain_pending(txn: &mut Txn) {+    PENDING.with(|pending| {+        for object in pending.borrow_mut().drain(..) {+            txn.add_known(object.kind, object.id, object.body);+        }+    });+}++fn build_tree(txn: &mut Txn, entries: &[FlatEntry]) -> Result<Id> {+    drain_pending(txn);+    let mut sorted = entries.to_vec();+    sorted.sort_by(|left, right| left.path.cmp(&right.path));+    build_level(txn, &sorted, 0, sorted.len(), 0)+}++fn build_level(+    txn: &mut Txn,+    entries: &[FlatEntry],+    start: usize,+    end: usize,+    prefix: usize,+) -> Result<Id> {+    let mut output = Vec::new();+    let mut index = start;+    while index < end {+        let entry = &entries[index];+        let cut = entry.path[prefix..]+            .iter()+            .position(|byte| *byte == b'/')+            .map(|offset| prefix + offset)+            .unwrap_or(entry.path.len());+        let name = entry.path[prefix..cut].to_vec();+        if cut == entry.path.len() {+            output.push(TreeEntry {+                name,+                kind: entry.kind,+                target: entry.target,+            });+            index += 1;+        } else {+            let mut next = index + 1;+            while next < end {+                let other = &entries[next];+                let other_cut = other.path[prefix..]+                    .iter()+                    .position(|byte| *byte == b'/')+                    .map(|offset| prefix + offset)+                    .unwrap_or(other.path.len());+                if other_cut != cut || other.path[prefix..cut] != entry.path[prefix..cut] {+                    break;+                }+                next += 1;+            }+            let child = build_level(txn, entries, index, next, cut + 1)?;+            output.push(TreeEntry {+                name,+                kind: tree::KIND_SUBTREE,+                target: child,+            });+            index = next;+        }+    }+    Ok(txn.add_object(TYPE_TREE, tree::encode(&output)?))+}++pub fn materialize(root: &Path) -> i32 {+    let result = (|| -> Result<()> {+        let mut store = Store::open(root)?;+        let view =+            ops::current_view(root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;+        if let Some(working) = ops::working_copy_id(&view)+            && let Some(commit) = graph::load_commit(&mut store, working)?+        {+            let progress = crate::core::Progress::new("checking out files", 0);+            crate::worktree::checkout::materialize_with_progress(+                root,+                &mut store,+                None,+                commit.root_tree,+                Some(&progress),+            )?;+        }+        Ok(())+    })();+    match result {+        Ok(()) => 0,+        Err(error) => {+            crate::cli::output::error_prefix();+            println!("git materialize failed: {error}");+            1+        }+    }+}++pub fn export(root: &Path) -> i32 {+    match export_inner(root) {+        Ok(()) => 0,+        Err(error) => {+            crate::cli::output::error_prefix();+            println!("git export failed: {error}");+            1+        }+    }+}++fn export_inner(root: &Path) -> Result<()> {+    let mirror = mirror_dir(root);+    if !mirror.is_dir() {+        std::fs::create_dir_all(&mirror)?;+        run_git(+            &["init", "--bare", mirror.to_str().unwrap_or("")],+            None,+            None,+        )?;+    }+    let mut store = Store::open(root)?;+    let view = ops::current_view(root, &mut store)?.unwrap_or_default();+    let commits = graph::collect_commits(&mut store, &graph::view_roots(&view))?;+    let nodes: Vec<graph::LogNode> = {+        let mut output = Vec::new();+        for id in &commits {+            if let Some(commit) = graph::load_commit(&mut store, *id)? {+                output.push(graph::LogNode {+                    id: *id,+                    seconds: commit.committer.seconds,+                    parents: commit.parents,+                });+            }+        }+        output+    };+    let order = graph::order_log_nodes(&nodes);+    let mut ordered = Vec::new();+    for index in order.into_iter().rev() {+        ordered.push(nodes[index].id);+    }+    let mut stream: Vec<u8> = Vec::new();+    let mut marks: HashMap<Id, usize> = HashMap::new();+    let mut blob_marks: HashMap<Id, usize> = HashMap::new();+    let mut next_mark = 1usize;+    let mut next_blob = 1_000_000usize;+    for id in &ordered {+        let Some(commit) = graph::load_commit(&mut store, *id)? else {+            continue;+        };+        let entries = tree::flatten(&mut store, commit.root_tree)?;+        let mut file_lines = Vec::new();+        for entry in &entries {+            if matches!(entry.kind, tree::KIND_CONFLICT | tree::KIND_SUBMODULE) {+                continue;+            }+            let mark = if let Some(mark) = blob_marks.get(&entry.target) {+                *mark+            } else {+                let Some(data) = graph::read_blob(&mut store, entry.target)? else {+                    continue;+                };+                let mark = next_blob;+                next_blob += 1;+                blob_marks.insert(entry.target, mark);+                stream.extend_from_slice(+                    format!("blob\nmark :{mark}\ndata {}\n", data.len()).as_bytes(),+                );+                stream.extend_from_slice(&data);+                stream.push(b'\n');+                mark+            };+            let mode = match entry.kind {+                tree::KIND_EXECUTABLE => "100755",+                tree::KIND_SYMLINK => "120000",+                _ => "100644",+            };+            let mut line = format!("M {mode} :{mark} ").into_bytes();+            line.extend_from_slice(&entry.path);+            line.push(b'\n');+            file_lines.push(line);+        }+        let mark = next_mark;+        next_mark += 1;+        marks.insert(*id, mark);+        stream.extend_from_slice(b"commit refs/veins/export\n");+        stream.extend_from_slice(format!("mark :{mark}\n").as_bytes());+        stream.extend_from_slice(+            format!(+                "author {} <{}> {} {}\n",+                String::from_utf8_lossy(&commit.author.name),+                String::from_utf8_lossy(&commit.author.email),+                commit.author.seconds,+                format_tz(commit.author.tz_min)+            )+            .as_bytes(),+        );+        stream.extend_from_slice(+            format!(+                "committer {} <{}> {} {}\n",+                String::from_utf8_lossy(&commit.committer.name),+                String::from_utf8_lossy(&commit.committer.email),+                commit.committer.seconds,+                format_tz(commit.committer.tz_min)+            )+            .as_bytes(),+        );+        stream.extend_from_slice(format!("data {}\n", commit.message.len()).as_bytes());+        stream.extend_from_slice(&commit.message);+        stream.push(b'\n');+        if let Some(parent) = commit.parents.first()+            && let Some(parent_mark) = marks.get(parent)+        {+            stream.extend_from_slice(format!("from :{parent_mark}\n").as_bytes());+        }+        for parent in commit.parents.iter().skip(1) {+            if let Some(parent_mark) = marks.get(parent) {+                stream.extend_from_slice(format!("merge :{parent_mark}\n").as_bytes());+            }+        }+        stream.extend_from_slice(b"deleteall\n");+        for line in file_lines {+            stream.extend_from_slice(&line);+        }+        stream.push(b'\n');+    }+    for bookmark in &view.bookmarks {+        if let Some(target) = bookmark.targets.adds.first().copied().flatten()+            && let Some(mark) = marks.get(&target)+        {+            stream.extend_from_slice(b"reset refs/heads/");+            stream.extend_from_slice(&bookmark.name);+            stream.extend_from_slice(format!("\nfrom :{mark}\n\n").as_bytes());+        }+    }+    for tag in &view.tags {+        if let Some(mark) = marks.get(&tag.target) {+            stream.extend_from_slice(b"reset refs/tags/");+            stream.extend_from_slice(&tag.name);+            stream.extend_from_slice(format!("\nfrom :{mark}\n\n").as_bytes());+        }+    }+    git_dir_command(+        &["fast-import", "--quiet", "--force"],+        &mirror,+        Some(&stream),+    )?;+    sync_mirror_refs(&mirror, &view)?;+    Ok(())+}++fn sync_mirror_refs(mirror: &Path, view: &crate::object::view::View) -> Result<()> {+    let output = git_dir_command(&["for-each-ref", "--format=%(refname)"], mirror, None)?;+    let text = String::from_utf8_lossy(&output);+    for line in text.lines() {+        let name = line.trim();+        if let Some(tag) = name.strip_prefix("refs/tags/") {+            if ops::find_tag(view, tag.as_bytes()).is_none() {+                let _ = git_dir_command(&["update-ref", "-d", name], mirror, None);+            }+        } else if let Some(bookmark) = name.strip_prefix("refs/heads/") {+            if ops::find_bookmark(view, bookmark.as_bytes()).is_none() {+                let _ = git_dir_command(&["update-ref", "-d", name], mirror, None);+            }+        }+    }+    Ok(())+}++fn format_tz(minutes: i16) -> String {+    let sign = if minutes < 0 { '-' } else { '+' };+    let value = minutes.abs();+    format!("{sign}{:02}{:02}", value / 60, value % 60)+}++pub fn fetch(root: &Path, remote: &str) -> i32 {+    let mirror = mirror_dir(root);+    if !mirror.is_dir() {+        std::fs::create_dir_all(&mirror).ok();+        let _ = run_git(+            &["init", "--bare", mirror.to_str().unwrap_or("")],+            None,+            None,+        );+    }+    let remote_name = if remote.is_empty() { "origin" } else { remote };+    if run_git(+        &[+            "--git-dir",+            mirror.to_str().unwrap_or(""),+            "config",+            "remote.real.url",+        ],+        None,+        None,+    )+    .is_err()+    {+        let _ = remote_name;+    }+    match git_dir_command(&["fetch", "--prune", remote_name], &mirror, None) {+        Ok(_) => import(root),+        Err(_) => 1,+    }+}++pub fn push(root: &Path, remote: &str, bookmark: &str) -> i32 {+    if export(root) != 0 {+        return 1;+    }+    let mirror = mirror_dir(root);+    let status = run_git(+        &[+            "--git-dir",+            mirror.to_str().unwrap_or(""),+            "push",+            remote,+            &format!("refs/heads/{bookmark}:refs/heads/{bookmark}"),+        ],+        None,+        None,+    );+    if status.is_err() {+        return 1;+    }+    0+}++pub struct MirrorOptions {+    pub force: bool,+    pub prune: bool,+    pub dry_run: bool,+}++pub fn mirror_push(root: &Path, remote: &str, options: &MirrorOptions) -> i32 {+    if export(root) != 0 {+        return 1;+    }+    let mirror = mirror_dir(root);+    let mut arguments = vec!["--git-dir", mirror.to_str().unwrap_or(""), "push"];+    if options.prune {+        arguments.push("--mirror");+        arguments.push("--prune");+    }+    if options.force {+        arguments.push("--force");+    }+    if options.dry_run {+        arguments.push("--dry-run");+    }+    arguments.push(remote);+    if !options.prune {+        arguments.push("refs/heads/*:refs/heads/*");+        arguments.push("refs/tags/*:refs/tags/*");+    }+    if run_git(&arguments, None, None).is_err() {+        return 1;+    }+    0+}++pub fn mirror_tag(root: &Path, remote: &str, tag: &str, options: &MirrorOptions) -> i32 {+    if export(root) != 0 {+        return 1;+    }+    let mirror = mirror_dir(root);+    let mut arguments = vec!["--git-dir", mirror.to_str().unwrap_or(""), "push"];+    if options.force {+        arguments.push("--force");+    }+    if options.dry_run {+        arguments.push("--dry-run");+    }+    let reference = format!("refs/tags/{tag}:refs/tags/{tag}");+    arguments.push(remote);+    arguments.push(&reference);+    if run_git(&arguments, None, None).is_err() {+        return 1;+    }+    0+}++pub fn mirror_remote(root: &Path, sub: &str, name: &str, url: &str) -> i32 {+    let mirror = mirror_dir(root);+    if !mirror.is_dir() {+        std::fs::create_dir_all(&mirror).ok();+        let _ = run_git(+            &["init", "--bare", mirror.to_str().unwrap_or("")],+            None,+            None,+        );+    }+    let result = match sub {+        "add" => git_dir_command(&["remote", "add", name, url], &mirror, None),+        "remove" | "rm" => git_dir_command(&["remote", "remove", name], &mirror, None),+        _ => Ok(Vec::new()),+    };+    if result.is_err() { 1 } else { 0 }+}++pub fn mirror_remote_list(root: &Path) -> Vec<String> {+    let mirror = mirror_dir(root);+    git_dir_command(&["remote"], &mirror, None)+        .map(|data| {+            String::from_utf8_lossy(&data)+                .lines()+                .map(|line| line.trim().to_string())+                .filter(|line| !line.is_empty())+                .collect()+        })+        .unwrap_or_default()+}++pub fn read_lazy_blob(_root: &Path, _id: Id) -> Option<Vec<u8>> {+    None+}--- /dev/null+++ b/veins/src/identity.rs@@ -0,0 +1,46 @@+use std::env;+use std::path::Path;++use crate::core;+use crate::object::commit::Sig;+use crate::time;++fn first_value(root: &Path, key: &str, name: bool, first: &str, second: &str) -> String {+    if let Some(value) = core::repo_config_value(root, key) {+        return value;+    }+    let user = if name {+        core::user_config_author_name()+    } else {+        core::user_config_author_email()+    };+    if let Some(value) = user {+        return value;+    }+    for variable in [first, second] {+        if let Ok(value) = env::var(variable)+            && !value.is_empty()+        {+            return value;+        }+    }+    "unknown".to_string()+}++pub fn signature(root: &Path) -> Sig {+    Sig {+        name: first_value(root, "user.name", true, "GIT_AUTHOR_NAME", "USER").into_bytes(),+        email: first_value(root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL").into_bytes(),+        seconds: time::now_seconds(),+        tz_min: 0,+    }+}++pub fn random_change_id() -> [u8; 16] {+    let first = core::random_u64().to_le_bytes();+    let second = core::random_u64().to_le_bytes();+    let mut value = [0u8; 16];+    value[..8].copy_from_slice(&first);+    value[8..].copy_from_slice(&second);+    value+}--- /dev/null+++ b/veins/src/lib.rs@@ -0,0 +1,17 @@+pub mod cli;+pub mod core;+pub mod crypto;+pub mod encoding;+pub mod error;+pub mod git;+pub mod identity;+pub mod merge;+pub mod object;+pub mod platform;+pub mod protocol;+pub mod server;+pub mod store;+pub mod time;+pub mod worktree;++pub use error::{Error, Result};--- /dev/null+++ b/veins/src/main.rs@@ -0,0 +1,12 @@+use std::process::ExitCode;++fn main() -> ExitCode {+    // `std::env::args()` panics on non-UTF-8 arguments; use the lossy OS form so+    // arbitrary commit messages and revision names degrade to text instead of+    // aborting the process.+    let args: Vec<String> = std::env::args_os()+        .skip(1)+        .map(|argument| argument.to_string_lossy().into_owned())+        .collect();+    ExitCode::from(veins_rust::cli::run(&args))+}--- /dev/null+++ b/veins/src/merge/engine.rs@@ -0,0 +1,1814 @@+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::blob::{self, BlobForm};+use crate::object::commit::{self, Commit, Rename, Sig};+use crate::object::conflict::{self, Conflict, ConflictValue};+use crate::object::id::{Id, object_id};+use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry};+use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};+use crate::store::Txn;+use crate::store::graph;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::worktree::snapshot;++fn same(left: Id, right: Id) -> bool {+    left == right+}++fn read_any(+    store: &mut Store,+    writer: Option<&Writer>,+    kind: u8,+    id: Id,+) -> Result<Option<Vec<u8>>> {+    if let Some(writer) = writer+        && let Some(body) = writer.find_cached(kind, id)+    {+        return Ok(Some(body.to_vec()));+    }+    store.body(id, kind)+}++fn append_blob(+    store: &mut Store,+    writer: Option<&Writer>,+    id: Id,+    output: &mut Vec<u8>,+    depth: usize,+) -> Result<bool> {+    if depth > 64 {+        return Ok(false);+    }+    let Some(body) = read_any(store, writer, TYPE_BLOB, id)? else {+        return Ok(false);+    };+    let blob = blob::decode(&body)?;+    match blob.form {+        BlobForm::Inline => output.extend_from_slice(&blob.data),+        BlobForm::Leaf => {+            for entry in blob.entries {+                let Some(chunk) = read_any(store, writer, TYPE_CHUNK, entry.id)? else {+                    return Ok(false);+                };+                output.extend_from_slice(&chunk);+            }+        }+        BlobForm::Interior => {+            for entry in blob.entries {+                if !append_blob(store, writer, entry.id, output, depth + 1)? {+                    return Ok(false);+                }+            }+        }+    }+    Ok(true)+}++pub fn read_blob_any(+    store: &mut Store,+    writer: Option<&Writer>,+    id: Id,+) -> Result<Option<Vec<u8>>> {+    let mut output = Vec::new();+    if append_blob(store, writer, id, &mut output, 0)? {+        Ok(Some(output))+    } else {+        Ok(None)+    }+}++fn collect_chunks(+    store: &mut Store,+    writer: Option<&Writer>,+    id: Id,+    output: &mut Vec<Id>,+    depth: usize,+) -> Result<bool> {+    if depth > 64 {+        return Ok(false);+    }+    let Some(body) = read_any(store, writer, TYPE_BLOB, id)? else {+        return Ok(false);+    };+    let blob = blob::decode(&body)?;+    match blob.form {+        BlobForm::Leaf => {+            for entry in blob.entries {+                output.push(entry.id);+            }+        }+        BlobForm::Interior => {+            for entry in blob.entries {+                if !collect_chunks(store, writer, entry.id, output, depth + 1)? {+                    return Ok(false);+                }+            }+        }+        BlobForm::Inline => {}+    }+    Ok(true)+}++fn flatten_into(+    store: &mut Store,+    writer: Option<&Writer>,+    tree_id: Id,+    prefix: &mut Vec<u8>,+    output: &mut Vec<FlatEntry>,+    depth: usize,+) -> Result<bool> {+    if depth > crate::object::MAX_TREE_DEPTH {+        return Ok(false);+    }+    let Some(body) = read_any(store, writer, TYPE_TREE, tree_id)? else {+        return Ok(false);+    };+    let tree = tree::decode(&body)?;+    for entry in tree.entries {+        let old_length = prefix.len();+        if !prefix.is_empty() {+            prefix.push(b'/');+        }+        prefix.extend_from_slice(&entry.name);+        if entry.kind == KIND_SUBTREE {+            let ok = flatten_into(store, writer, entry.target, prefix, output, depth + 1)?;+            prefix.truncate(old_length);+            if !ok {+                return Ok(false);+            }+        } else {+            output.push(FlatEntry {+                path: prefix.clone(),+                kind: entry.kind,+                target: entry.target,+            });+            prefix.truncate(old_length);+        }+    }+    Ok(true)+}++pub fn flatten_sorted(+    store: &mut Store,+    writer: Option<&Writer>,+    tree: Option<Id>,+) -> Result<Vec<FlatEntry>> {+    let Some(tree) = tree else {+        return Ok(Vec::new());+    };+    let mut output = Vec::new();+    flatten_into(store, writer, tree, &mut Vec::new(), &mut output, 0)?;+    output.sort_by(|left, right| left.path.cmp(&right.path));+    Ok(output)+}++fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {+    entries+        .binary_search_by(|entry| entry.path.as_slice().cmp(path))+        .ok()+        .map(|index| &entries[index])+}++fn tree_empty(store: &mut Store, writer: Option<&Writer>, id: Id) -> Result<bool> {+    match read_any(store, writer, TYPE_TREE, id)? {+        Some(body) => Ok(tree::decode(&body)+            .map(|tree| tree.entries.is_empty())+            .unwrap_or(true)),+        None => Ok(true),+    }+}++fn add_tree(txn: &mut Txn, entries: &[TreeEntry]) -> Result<Id> {+    Ok(txn.add_object(TYPE_TREE, tree::encode(entries)?))+}++fn add_empty_tree(txn: &mut Txn) -> Result<Id> {+    add_tree(txn, &[])+}++fn add_blob(txn: &mut Txn, data: &[u8]) -> Id {+    let build = blob::build(data);+    for object in build.objects {+        txn.add_known(object.kind, object.id, object.body);+    }+    build.root+}++fn hash_line(line: &[u8]) -> u64 {+    let mut hash = 1_469_598_103_934_665_603u64;+    for byte in line {+        hash = (hash ^ *byte as u64).wrapping_mul(1_099_511_628_211);+    }+    hash+}++fn line_similarity(left: &[u8], right: &[u8]) -> u32 {+    fn lines(data: &[u8]) -> Vec<u64> {+        let mut output = Vec::new();+        let mut start = 0;+        for index in 0..=data.len() {+            if index == data.len() || data[index] == b'\n' {+                output.push(hash_line(&data[start..index]));+                start = index + 1;+            }+        }+        output.sort_unstable();+        output+    }+    let a = lines(left);+    let b = lines(right);+    let mut ia = 0;+    let mut ib = 0;+    let mut intersection = 0;+    while ia < a.len() && ib < b.len() {+        if a[ia] == b[ib] {+            intersection += 1;+            ia += 1;+            ib += 1;+        } else if a[ia] < b[ib] {+            ia += 1;+        } else {+            ib += 1;+        }+    }+    let total = a.len() + b.len() - intersection;+    if total == 0 {+        100+    } else {+        (intersection * 100 / total) as u32+    }+}++fn chunk_similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> {+    let mut left = Vec::new();+    let mut right = Vec::new();+    if !collect_chunks(store, writer, a, &mut left, 0)?+        || !collect_chunks(store, writer, b, &mut right, 0)?+    {+        return Ok(0);+    }+    let mut intersection = 0;+    for item in &left {+        if right.contains(item) {+            intersection += 1;+        }+    }+    let total = left.len() + right.len() - intersection;+    Ok(if total == 0 {+        0+    } else {+        (intersection * 100 / total) as u32+    })+}++fn similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> {+    if same(a, b) {+        return Ok(100);+    }+    let Some(left) = read_blob_any(store, writer, a)? else {+        return Ok(0);+    };+    let Some(right) = read_blob_any(store, writer, b)? else {+        return Ok(0);+    };+    let mut result = 0;+    if left.len() >= 131_072 && right.len() >= 131_072 {+        result = chunk_similarity(store, writer, a, b)?;+    }+    if result == 0 {+        result = line_similarity(&left, &right);+    }+    Ok(result)+}++pub fn detect(+    store: &mut Store,+    writer: Option<&Writer>,+    old_tree: Option<Id>,+    new_tree: Option<Id>,+    similar_pct: u32,+    parent_index: u64,+) -> Result<Vec<Rename>> {+    let old_entries = flatten_sorted(store, writer, old_tree)?;+    let new_entries = flatten_sorted(store, writer, new_tree)?;+    let deleted: Vec<&FlatEntry> = old_entries+        .iter()+        .filter(|entry| find_flat(&new_entries, &entry.path).is_none())+        .collect();+    let added: Vec<&FlatEntry> = new_entries+        .iter()+        .filter(|entry| find_flat(&old_entries, &entry.path).is_none())+        .collect();+    let mut used_old = vec![false; deleted.len()];+    let mut used_new = vec![false; added.len()];+    let mut output = Vec::new();+    for (old_index, old) in deleted.iter().enumerate() {+        if used_old[old_index] {+            continue;+        }+        for (new_index, new) in added.iter().enumerate() {+            if used_new[new_index] {+                continue;+            }+            if old.target == new.target {+                output.push(Rename {+                    parent_index,+                    kind: 0,+                    from_path: old.path.clone(),+                    to_path: new.path.clone(),+                });+                used_old[old_index] = true;+                used_new[new_index] = true;+                break;+            }+        }+    }+    if similar_pct > 0 {+        let mut pairs = Vec::new();+        for (old_index, old) in deleted.iter().enumerate() {+            if used_old[old_index] || !matches!(old.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE) {+                continue;+            }+            for (new_index, new) in added.iter().enumerate() {+                if used_new[new_index]+                    || !matches!(new.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE)+                {+                    continue;+                }+                pairs.push((+                    old_index,+                    new_index,+                    similarity(store, writer, old.target, new.target)?,+                ));+            }+        }+        loop {+            let mut best = None;+            for (old_index, new_index, score) in &pairs {+                if used_old[*old_index] || used_new[*new_index] {+                    continue;+                }+                if best.is_none_or(|(_, _, current): (usize, usize, u32)| *score > current) {+                    best = Some((*old_index, *new_index, *score));+                }+            }+            let Some((old_index, new_index, score)) = best else {+                break;+            };+            if score < similar_pct {+                break;+            }+            used_old[old_index] = true;+            used_new[new_index] = true;+            output.push(Rename {+                parent_index,+                kind: 0,+                from_path: deleted[old_index].path.clone(),+                to_path: added[new_index].path.clone(),+            });+        }+    }+    output.sort_by(|left, right| {+        left.parent_index+            .cmp(&right.parent_index)+            .then_with(|| left.to_path.cmp(&right.to_path))+    });+    Ok(output)+}++pub fn rename_similar_pct(root: &Path) -> u32 {+    match core::repo_config_value(root, "rename.autodetect").as_deref() {+        Some("off") => 0,+        _ => 60,+    }+}++fn split_lines(data: &[u8]) -> Vec<Vec<u8>> {+    let mut output = Vec::new();+    let mut start = 0;+    for index in 0..data.len() {+        if data[index] == b'\n' {+            output.push(data[start..=index].to_vec());+            start = index + 1;+        }+    }+    if start < data.len() {+        output.push(data[start..].to_vec());+    }+    output+}++#[derive(Clone, Copy)]+struct Op {+    tag: u8,+    bi: usize,+}++fn fallback_ops(a: &[Vec<u8>], b: &[Vec<u8>]) -> Vec<Op> {+    let mut prefix = 0;+    while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {+        prefix += 1;+    }+    let mut suffix = 0;+    while suffix < a.len() - prefix+        && suffix < b.len() - prefix+        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]+    {+        suffix += 1;+    }+    let mut output = Vec::new();+    for index in 0..prefix {+        output.push(Op {+            tag: b' ',+            bi: index,+        });+    }+    for _index in prefix..a.len() - suffix {+        output.push(Op { tag: b'-', bi: 0 });+    }+    for index in prefix..b.len() - suffix {+        output.push(Op {+            tag: b'+',+            bi: index,+        });+    }+    for index in 0..suffix {+        output.push(Op {+            tag: b' ',+            bi: b.len() - suffix + index,+        });+    }+    output+}++fn build_ops(a: &[Vec<u8>], b: &[Vec<u8>]) -> Vec<Op> {+    let cells = (a.len() as u64 + 1) * (b.len() as u64 + 1);+    if cells > 8_000_000 {+        return fallback_ops(a, b);+    }+    let columns = b.len() + 1;+    let mut dp = vec![0u32; cells as usize];+    for i in 1..=a.len() {+        for j in 1..=b.len() {+            dp[i * columns + j] = if a[i - 1] == b[j - 1] {+                dp[(i - 1) * columns + j - 1] + 1+            } else {+                dp[(i - 1) * columns + j].max(dp[i * columns + j - 1])+            };+        }+    }+    let mut output = Vec::new();+    let mut i = a.len();+    let mut j = b.len();+    while i > 0 || j > 0 {+        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {+            output.push(Op {+                tag: b' ',+                bi: j - 1,+            });+            i -= 1;+            j -= 1;+        } else if j > 0 && (i == 0 || dp[i * columns + j - 1] >= dp[(i - 1) * columns + j]) {+            output.push(Op {+                tag: b'+',+                bi: j - 1,+            });+            j -= 1;+        } else {+            output.push(Op { tag: b'-', bi: 0 });+            i -= 1;+        }+    }+    output.reverse();+    output+}++#[derive(Clone)]+struct Hunk {+    start: usize,+    end: usize,+    lines: Vec<Vec<u8>>,+}++fn diff_hunks(base: &[Vec<u8>], side: &[Vec<u8>]) -> Vec<Hunk> {+    let ops = build_ops(base, side);+    let mut output = Vec::new();+    let mut base_position = 0;+    let mut index = 0;+    while index < ops.len() {+        if ops[index].tag == b' ' {+            base_position += 1;+            index += 1;+            continue;+        }+        let mut hunk = Hunk {+            start: base_position,+            end: 0,+            lines: Vec::new(),+        };+        while index < ops.len() && ops[index].tag != b' ' {+            if ops[index].tag == b'-' {+                base_position += 1;+            } else {+                hunk.lines.push(side[ops[index].bi].clone());+            }+            index += 1;+        }+        hunk.end = base_position;+        output.push(hunk);+    }+    output+}++#[derive(Clone, Copy)]+pub struct MergeRange {+    pub base_start: usize,+    pub base_end: usize,+    pub ours_start: usize,+    pub ours_end: usize,+    pub theirs_start: usize,+    pub theirs_end: usize,+}++pub struct EditResult {+    pub conflicted: bool,+    pub data: Vec<u8>,+    pub ranges: Vec<MergeRange>,+}++fn append_lines(output: &mut Vec<u8>, lines: &[Vec<u8>], start: usize, end: usize) {+    for index in start..end.min(lines.len()) {+        output.extend_from_slice(&lines[index]);+    }+}++fn apply_hunks(+    output: &mut Vec<u8>,+    base: &[Vec<u8>],+    from: usize,+    to: usize,+    hunks: &[Hunk],+    first: usize,+    last: usize,+) {+    let mut position = from;+    for hunk in &hunks[first..last] {+        if hunk.start > position && hunk.start <= to {+            append_lines(output, base, position, hunk.start);+        }+        for line in &hunk.lines {+            output.extend_from_slice(line);+        }+        if hunk.end > position {+            position = hunk.end;+        }+    }+    if position < to {+        append_lines(output, base, position, to);+    }+}++fn map_position(hunks: &[Hunk], position: usize) -> usize {+    let mut output = position as i64;+    for hunk in hunks {+        if hunk.end <= position {+            output += hunk.lines.len() as i64 - (hunk.end - hunk.start) as i64;+        } else if hunk.start < position {+            output += hunk.lines.len() as i64 - (position - hunk.start) as i64;+            break;+        } else {+            break;+        }+    }+    output.max(0) as usize+}++fn same_hunks(ours: &[Hunk], of: usize, ol: usize, theirs: &[Hunk], tf: usize, tl: usize) -> bool {+    let mut left = Vec::new();+    let mut right = Vec::new();+    for hunk in &ours[of..ol] {+        for line in &hunk.lines {+            left.extend_from_slice(line);+        }+    }+    for hunk in &theirs[tf..tl] {+        for line in &hunk.lines {+            right.extend_from_slice(line);+        }+    }+    left == right+}++pub fn merge_lines(base: &[u8], ours: &[u8], theirs: &[u8], adjacent: bool) -> EditResult {+    let base = split_lines(base);+    let ours = split_lines(ours);+    let theirs = split_lines(theirs);+    let ours_hunks = diff_hunks(&base, &ours);+    let theirs_hunks = diff_hunks(&base, &theirs);+    let mut result = EditResult {+        conflicted: false,+        data: Vec::new(),+        ranges: Vec::new(),+    };+    let mut oi = 0;+    let mut ti = 0;+    let mut position = 0;+    while oi < ours_hunks.len() || ti < theirs_hunks.len() {+        let have_ours = oi < ours_hunks.len();+        let have_theirs = ti < theirs_hunks.len();+        let ours_start = if have_ours { ours_hunks[oi].start } else { 0 };+        let theirs_start = if have_theirs {+            theirs_hunks[ti].start+        } else {+            0+        };+        let take_ours = have_ours && (!have_theirs || ours_start <= theirs_start);+        let cluster_start = if take_ours { ours_start } else { theirs_start };+        let of = oi;+        let tf = ti;+        let mut o_last = of;+        let mut t_last = tf;+        let mut end = cluster_start;+        let mut seen_ours = false;+        let mut seen_theirs = false;+        loop {+            let mut progress = false;+            if o_last < ours_hunks.len() {+                let hunk = &ours_hunks[o_last];+                let include = if o_last == of {+                    hunk.start <= end+                } else if adjacent {+                    hunk.start < end+                } else {+                    hunk.start <= end+                };+                if include {+                    seen_ours = true;+                    o_last += 1;+                    end = end.max(hunk.end);+                    progress = true;+                }+            }+            if t_last < theirs_hunks.len() {+                let hunk = &theirs_hunks[t_last];+                let include = if t_last == tf {+                    hunk.start <= end+                } else if adjacent {+                    hunk.start < end+                } else {+                    hunk.start <= end+                };+                if include {+                    seen_theirs = true;+                    t_last += 1;+                    end = end.max(hunk.end);+                    progress = true;+                }+            }+            if !progress {+                break;+            }+        }+        end = end.max(cluster_start);+        if seen_ours && !seen_theirs {+            apply_hunks(+                &mut result.data,+                &base,+                position,+                end,+                &ours_hunks,+                of,+                o_last,+            );+            position = end;+            oi = o_last;+            ti = t_last;+        } else if seen_theirs && !seen_ours {+            apply_hunks(+                &mut result.data,+                &base,+                position,+                end,+                &theirs_hunks,+                tf,+                t_last,+            );+            position = end;+            oi = o_last;+            ti = t_last;+        } else {+            if same_hunks(&ours_hunks, of, o_last, &theirs_hunks, tf, t_last) {+                apply_hunks(+                    &mut result.data,+                    &base,+                    position,+                    end,+                    &ours_hunks,+                    of,+                    o_last,+                );+                position = end;+            } else {+                result.conflicted = true;+                apply_hunks(+                    &mut result.data,+                    &base,+                    position,+                    end,+                    &ours_hunks,+                    of,+                    o_last,+                );+                result.ranges.push(MergeRange {+                    base_start: cluster_start,+                    base_end: end,+                    ours_start: map_position(&ours_hunks, cluster_start),+                    ours_end: map_position(&ours_hunks, end),+                    theirs_start: map_position(&theirs_hunks, cluster_start),+                    theirs_end: map_position(&theirs_hunks, end),+                });+                position = end;+            }+            oi = o_last;+            ti = t_last;+        }+    }+    if position < base.len() {+        append_lines(&mut result.data, &base, position, base.len());+    }+    result+}++fn merge_blobs(+    store: &mut Store,+    writer: Option<&Writer>,+    base: Id,+    ours: Id,+    theirs: Id,+    adjacent: bool,+) -> Result<Option<EditResult>> {+    let Some(base) = read_blob_any(store, writer, base)? else {+        return Ok(None);+    };+    let Some(ours) = read_blob_any(store, writer, ours)? else {+        return Ok(None);+    };+    let Some(theirs) = read_blob_any(store, writer, theirs)? else {+        return Ok(None);+    };+    Ok(Some(merge_lines(&base, &ours, &theirs, adjacent)))+}++fn value_equal(left: &ConflictValue, right: &ConflictValue) -> bool {+    left.kind == right.kind && (left.kind == 0 || left.target == right.target)+}++fn flatten_values(+    store: &mut Store,+    values: &[ConflictValue],+    positive: bool,+    adds: &mut Vec<ConflictValue>,+    removes: &mut Vec<ConflictValue>,+    depth: usize,+) -> Result<()> {+    for value in values {+        if value.kind == KIND_CONFLICT+            && let Some(target) = value.target+            && depth < 64+            && let Some(body) = store.body(target, TYPE_CONFLICT)?+            && let Ok(child) = conflict::decode(&body)+        {+            flatten_values(store, &child.adds, positive, adds, removes, depth + 1)?;+            flatten_values(store, &child.removes, !positive, adds, removes, depth + 1)?;+            continue;+        }+        if positive {+            adds.push(value.clone());+        } else {+            removes.push(value.clone());+        }+    }+    Ok(())+}++pub fn simplify(+    store: &mut Store,+    adds: &[ConflictValue],+    removes: &[ConflictValue],+) -> Result<Conflict> {+    let mut flat_adds = Vec::new();+    let mut flat_removes = Vec::new();+    flatten_values(store, adds, true, &mut flat_adds, &mut flat_removes, 0)?;+    flatten_values(store, removes, false, &mut flat_adds, &mut flat_removes, 0)?;+    let mut used_adds = vec![false; flat_adds.len()];+    let mut used_removes = vec![false; flat_removes.len()];+    for (remove_index, remove) in flat_removes.iter().enumerate() {+        for (add_index, add) in flat_adds.iter().enumerate() {+            if !used_adds[add_index] && value_equal(add, remove) {+                used_adds[add_index] = true;+                used_removes[remove_index] = true;+                break;+            }+        }+    }+    Ok(Conflict {+        adds: flat_adds+            .into_iter()+            .enumerate()+            .filter(|(index, _)| !used_adds[*index])+            .map(|(_, value)| value)+            .collect(),+        removes: flat_removes+            .into_iter()+            .enumerate()+            .filter(|(index, _)| !used_removes[*index])+            .map(|(_, value)| value)+            .collect(),+    })+}++pub fn resolved(conflict: &Conflict) -> Option<ConflictValue> {+    let first = conflict.adds.first()?;+    if conflict.adds.iter().all(|value| value_equal(value, first)) {+        Some(first.clone())+    } else {+        None+    }+}++fn all_files(conflict: &Conflict) -> bool {+    conflict+        .adds+        .iter()+        .chain(conflict.removes.iter())+        .all(|value| matches!(value.kind, 0 | tree::KIND_FILE | tree::KIND_EXECUTABLE))+}++fn merge_mode(conflict: &Conflict) -> i32 {+    if conflict.adds.len() != 2 || conflict.removes.len() != 1 {+        return -1;+    }+    let mode = |value: &ConflictValue| -> i32 {+        if value.kind == 0 {+            return -1;+        }+        if value.kind == tree::KIND_EXECUTABLE {+            1+        } else {+            0+        }+    };+    let zero = mode(&conflict.adds[0]);+    let one = mode(&conflict.adds[1]);+    let remove = mode(&conflict.removes[0]);+    if zero < 0 || one < 0 {+        return -1;+    }+    if zero == one {+        return zero;+    }+    if remove >= 0 && zero == remove {+        return one;+    }+    if remove >= 0 && one == remove {+        return zero;+    }+    -1+}++fn merge_binary(repo: &Path, path: &[u8]) -> bool {+    let Some(data) = core::read_file_opt(&repo.join(".vnmergedata"), 0) else {+        return false;+    };+    let text = String::from_utf8_lossy(&data);+    let path = String::from_utf8_lossy(path);+    let mut result = false;+    for raw in text.lines() {+        let line = core::trim_str(raw);+        if line.is_empty() || line.starts_with('#') {+            continue;+        }+        let mut parts = line.split_whitespace();+        let Some(glob) = parts.next() else {+            continue;+        };+        let base = glob.rsplit('/').next().unwrap_or(glob);+        if !core::glob_match(glob, &path) && !(!glob.contains('/') && core::glob_match(base, &path))+        {+            continue;+        }+        for token in parts {+            if let Some(value) = token.strip_prefix("merge=") {+                if value == "binary" {+                    result = true;+                } else if value == "text" {+                    result = false;+                }+            }+        }+    }+    result+}++fn resolution_lookup(repo: &Path, body: &[u8]) -> Option<Id> {+    let key = crate::object::id::hash_bytes(body);+    let data = core::read_file_opt(+        &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),+        0,+    )?;+    if data.len() < 64 {+        return None;+    }+    Id::from_hex(std::str::from_utf8(&data[..64]).ok()?).ok()+}++fn resolution_record(repo: &Path, body: &[u8], blob: Id) {+    let key = crate::object::id::hash_bytes(body);+    let _ = core::write_file(+        &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),+        blob.to_hex().as_bytes(),+    );+}++type RenameMap = Vec<(Vec<u8>, Vec<u8>)>;++fn rename_lookup(map: &RenameMap, path: &[u8]) -> Option<Vec<u8>> {+    map.iter()+        .find(|(from, _)| from == path)+        .map(|(_, to)| to.clone())+}++fn rename_apply(map: &mut RenameMap, from: &[u8], to: &[u8]) {+    for (_, destination) in map.iter_mut() {+        if destination == from {+            *destination = to.to_vec();+            return;+        }+    }+    for (source, _) in map.iter_mut() {+        if source == from {+            return;+        }+    }+    map.push((from.to_vec(), to.to_vec()));+}++fn tree_of(store: &mut Store, commit: Id) -> Result<Option<Id>> {+    Ok(graph::load_commit(store, commit)?.map(|commit| commit.root_tree))+}++fn first_parent(store: &mut Store, commit: Id) -> Result<Option<Id>> {+    Ok(graph::load_commit(store, commit)?.and_then(|commit| commit.parents.first().copied()))+}++fn map_from(store: &mut Store, base: Id, side: Id) -> Result<RenameMap> {+    let mut map = RenameMap::new();+    if base == side {+        return Ok(map);+    }+    let mut chain = Vec::new();+    let mut current = side;+    let mut reached = false;+    for _ in 0..100_000 {+        if current == base {+            reached = true;+            break;+        }+        chain.push(current);+        let Some(parent) = first_parent(store, current)? else {+            break;+        };+        current = parent;+    }+    if !reached {+        return Ok(map);+    }+    for commit_id in chain.iter().rev() {+        let Some(loaded) = graph::load_commit(store, *commit_id)? else {+            continue;+        };+        if loaded.renames_state == commit::RENAMES_RECORDED {+            for rename in &loaded.renames {+                if rename.parent_index == 0 {+                    rename_apply(&mut map, &rename.from_path, &rename.to_path);+                }+            }+        } else {+            let Some(parent) = first_parent(store, *commit_id)? else {+                continue;+            };+            let old_tree = tree_of(store, parent)?;+            let new_tree = Some(loaded.root_tree);+            for rename in detect(store, None, old_tree, new_tree, 50, 0)? {+                rename_apply(&mut map, &rename.from_path, &rename.to_path);+            }+        }+    }+    Ok(map)+}++#[derive(Clone, Copy)]+struct TreeTerm {+    positive: bool,+    present: bool,+    id: Id,+}++#[derive(Clone)]+struct EntryTerm {+    positive: bool,+    present: bool,+    kind: u8,+    target: Option<Id>,+}++#[derive(Clone)]+struct OrigEntry {+    term: usize,+    path: Vec<u8>,+    kind: u8,+    target: Id,+}++#[derive(Clone)]+struct OutEntry {+    path: Vec<u8>,+    kind: u8,+    target: Id,+}++pub struct MergeOutcome {+    pub tree: Id,+    pub rerere: usize,+}++fn build_level(+    txn: &mut Txn,+    entries: &[OutEntry],+    start: usize,+    end: usize,+    prefix: usize,+) -> Result<Id> {+    let mut output = Vec::new();+    let mut index = start;+    while index < end {+        let entry = &entries[index];+        let cut = entry.path[prefix..]+            .iter()+            .position(|byte| *byte == b'/')+            .map(|offset| prefix + offset)+            .unwrap_or(entry.path.len());+        let name = entry.path[prefix..cut].to_vec();+        if cut == entry.path.len() {+            output.push(TreeEntry {+                name,+                kind: entry.kind,+                target: entry.target,+            });+            index += 1;+        } else {+            let mut next = index + 1;+            while next < end {+                let other = &entries[next];+                let other_cut = other.path[prefix..]+                    .iter()+                    .position(|byte| *byte == b'/')+                    .map(|offset| prefix + offset)+                    .unwrap_or(other.path.len());+                if other_cut != cut || other.path[prefix..cut] != entry.path[prefix..cut] {+                    break;+                }+                next += 1;+            }+            let child = build_level(txn, entries, index, next, cut + 1)?;+            output.push(TreeEntry {+                name,+                kind: KIND_SUBTREE,+                target: child,+            });+            index = next;+        }+    }+    add_tree(txn, &output)+}++fn build_from_entries(txn: &mut Txn, entries: &mut [OutEntry]) -> Result<Id> {+    if entries.is_empty() {+        return add_empty_tree(txn);+    }+    entries.sort_by(|left, right| left.path.cmp(&right.path));+    build_level(txn, entries, 0, entries.len(), 0)+}++fn build_subtree(txn: &mut Txn, canon: &[OrigEntry], term: usize, prefix: &[u8]) -> Result<Id> {+    let mut entries = Vec::new();+    for entry in canon {+        if entry.term == term && has_prefix(&entry.path, prefix) {+            entries.push(OutEntry {+                path: entry.path[prefix.len() + 1..].to_vec(),+                kind: entry.kind,+                target: entry.target,+            });+        }+    }+    build_from_entries(txn, &mut entries)+}++fn has_prefix(path: &[u8], prefix: &[u8]) -> bool {+    path.len() > prefix.len() && path.starts_with(prefix) && path[prefix.len()] == b'/'+}++fn merge_entry(+    repo: &Path,+    txn: &mut Txn,+    store: &mut Store,+    path: &[u8],+    terms: &[EntryTerm],+    adjacent: bool,+    rerere: &mut usize,+) -> Result<Option<OutEntry>> {+    let mut adds = Vec::new();+    let mut removes = Vec::new();+    for term in terms {+        let value = ConflictValue {+            kind: if term.present { term.kind } else { 0 },+            target: term.target,+        };+        if term.positive {+            adds.push(value);+        } else {+            removes.push(value);+        }+    }+    let sum = simplify(store, &adds, &removes)?;+    if let Some(value) = resolved(&sum) {+        if value.kind == 0 {+            return Ok(None);+        }+        return Ok(Some(OutEntry {+            path: path.to_vec(),+            kind: value.kind,+            target: value+                .target+                .ok_or_else(|| Error::new("missing conflict target"))?,+        }));+    }+    if all_files(&sum)+        && sum.adds.len() == 2+        && sum.removes.len() == 1+        && sum.adds[0].kind != 0+        && sum.adds[1].kind != 0+        && sum.removes[0].kind != 0+        && !merge_binary(repo, path)+        && let (Some(base), Some(ours), Some(theirs)) = (+            sum.removes[0].target,+            sum.adds[0].target,+            sum.adds[1].target,+        )+    {+        if let Some(merged) = merge_blobs(store, Some(txn.writer()), base, ours, theirs, adjacent)?+        {+            if !merged.conflicted {+                let blob = add_blob(txn, &merged.data);+                let mode = merge_mode(&sum);+                if mode >= 0 {+                    return Ok(Some(OutEntry {+                        path: path.to_vec(),+                        kind: if mode == 1 {+                            tree::KIND_EXECUTABLE+                        } else {+                            tree::KIND_FILE+                        },+                        target: blob,+                    }));+                }+            }+        }+    }+    let body = conflict::encode(&sum);+    if all_files(&sum)+        && let Some(blob) = resolution_lookup(repo, &body)+    {+        *rerere += 1;+        return Ok(Some(OutEntry {+            path: path.to_vec(),+            kind: tree::KIND_FILE,+            target: blob,+        }));+    }+    let id = txn.add_object(TYPE_CONFLICT, body);+    Ok(Some(OutEntry {+        path: path.to_vec(),+        kind: KIND_CONFLICT,+        target: id,+    }))+}++fn treemerge(+    repo: &Path,+    txn: &mut Txn,+    store: &mut Store,+    terms: &[TreeTerm],+    maps: &[RenameMap],+    adjacent: bool,+) -> Result<MergeOutcome> {+    let mut orig = Vec::new();+    for (term_index, term) in terms.iter().enumerate() {+        if !term.present {+            continue;+        }+        for entry in flatten_sorted(store, Some(txn.writer()), Some(term.id))? {+            orig.push(OrigEntry {+                term: term_index,+                path: entry.path,+                kind: entry.kind,+                target: entry.target,+            });+        }+    }+    let canonical_targets = |path: &[u8]| -> Vec<(usize, Vec<u8>)> {+        let mut output: Vec<(usize, Vec<u8>)> = Vec::new();+        for (index, map) in maps.iter().enumerate() {+            if let Some(destination) = rename_lookup(map, path) {+                if !output.iter().any(|(_, value)| value == &destination) {+                    output.push((index, destination));+                }+            }+        }+        output+    };+    let mut canon = Vec::new();+    let mut special = Vec::new();+    let mut consumed: Vec<Vec<u8>> = Vec::new();+    for entry in &orig {+        let targets = canonical_targets(&entry.path);+        if targets.len() > 1 && !special.contains(&entry.path) {+            special.push(entry.path.clone());+        }+        let canonical = if targets.len() == 1 {+            targets[0].1.clone()+        } else {+            entry.path.clone()+        };+        canon.push(OrigEntry {+            term: entry.term,+            path: canonical,+            kind: entry.kind,+            target: entry.target,+        });+    }+    let find_orig = |term: usize, path: &[u8]| -> Option<&OrigEntry> {+        orig.iter()+            .find(|entry| entry.term == term && entry.path == path)+    };+    let find_canon = |term: usize, path: &[u8]| -> Option<&OrigEntry> {+        canon+            .iter()+            .find(|entry| entry.term == term && entry.path == path)+    };+    let mut output = Vec::new();+    let mut rerere = 0;+    for path in &special {+        let targets = canonical_targets(path);+        let mut entries = Vec::new();+        for (term, destination) in &targets {+            let mut value = EntryTerm {+                positive: true,+                present: false,+                kind: 0,+                target: None,+            };+            if let Some(found) = find_orig(*term, destination) {+                value.present = true;+                value.kind = found.kind;+                value.target = Some(found.target);+            }+            entries.push(value);+            if !consumed.contains(destination) {+                consumed.push(destination.clone());+            }+        }+        if let Some(base_term) = terms.iter().position(|term| !term.positive) {+            let mut value = EntryTerm {+                positive: false,+                present: false,+                kind: 0,+                target: None,+            };+            if let Some(found) = find_orig(base_term, path) {+                value.present = true;+                value.kind = found.kind;+                value.target = Some(found.target);+            }+            entries.push(value);+        }+        if let Some(merged) = merge_entry(repo, txn, store, path, &entries, adjacent, &mut rerere)?+        {+            output.push(merged);+        }+        if !consumed.contains(path) {+            consumed.push(path.clone());+        }+    }+    let mut paths: Vec<Vec<u8>> = Vec::new();+    for entry in &canon {+        if !paths.contains(&entry.path) {+            paths.push(entry.path.clone());+        }+    }+    paths.sort();+    for path in paths {+        if consumed.contains(&path) {+            continue;+        }+        let mut any_exact = false;+        let mut any_children = false;+        for term in 0..terms.len() {+            if find_canon(term, &path).is_some() {+                any_exact = true;+            }+            if canon+                .iter()+                .any(|entry| entry.term == term && has_prefix(&entry.path, &path))+            {+                any_children = true;+            }+        }+        if !any_exact {+            continue;+        }+        let mixed = any_children;+        let mut entries = Vec::new();+        for term in 0..terms.len() {+            let mut value = EntryTerm {+                positive: terms[term].positive,+                present: false,+                kind: 0,+                target: None,+            };+            if let Some(exact) = find_canon(term, &path) {+                value.present = true;+                value.kind = exact.kind;+                value.target = Some(exact.target);+            } else if mixed+                && canon+                    .iter()+                    .any(|entry| entry.term == term && has_prefix(&entry.path, &path))+            {+                value.present = true;+                value.kind = KIND_SUBTREE;+                value.target = Some(build_subtree(txn, &canon, term, &path)?);+            }+            entries.push(value);+        }+        if let Some(merged) = merge_entry(repo, txn, store, &path, &entries, adjacent, &mut rerere)?+        {+            output.push(merged);+        }+        if mixed {+            for entry in &canon {+                if has_prefix(&entry.path, &path) && !consumed.contains(&entry.path) {+                    consumed.push(entry.path.clone());+                }+            }+        }+    }+    Ok(MergeOutcome {+        tree: build_from_entries(txn, &mut output)?,+        rerere,+    })+}++pub fn merge_bases(store: &mut Store, a: Id, b: Id) -> Result<Vec<Id>> {+    let left = graph::collect_commits(store, &[a])?;+    let right = graph::collect_commits(store, &[b])?;+    let common: Vec<Id> = left.into_iter().filter(|id| right.contains(id)).collect();+    let mut output = Vec::new();+    for candidate in &common {+        let mut dominated = false;+        for other in &common {+            if candidate == other {+                continue;+            }+            let descendants = graph::collect_commits(store, &[*candidate])?;+            if descendants.contains(other) {+                dominated = true;+                break;+            }+        }+        if !dominated {+            output.push(*candidate);+        }+    }+    Ok(output)+}++pub fn is_ancestor(store: &mut Store, ancestor: Id, descendant: Id) -> Result<bool> {+    if ancestor == descendant {+        return Ok(true);+    }+    Ok(graph::collect_commits(store, &[descendant])?.contains(&ancestor))+}++fn base_tree(+    repo: &Path,+    txn: &mut Txn,+    store: &mut Store,+    bases: &[Id],+    adjacent: bool,+) -> Result<Option<Id>> {+    if bases.is_empty() {+        return Ok(None);+    }+    if bases.len() == 1 {+        return tree_of(store, bases[0]);+    }+    let t0 = tree_of(store, bases[0])?;+    let t1 = tree_of(store, bases[1])?;+    let lcas = merge_bases(store, bases[0], bases[1])?;+    let mut terms = vec![+        TreeTerm {+            positive: true,+            present: t0.is_some(),+            id: t0.unwrap_or_default(),+        },+        TreeTerm {+            positive: true,+            present: t1.is_some(),+            id: t1.unwrap_or_default(),+        },+    ];+    if let Some(first) = lcas.first() {+        let tree = tree_of(store, *first)?;+        terms.push(TreeTerm {+            positive: false,+            present: tree.is_some(),+            id: tree.unwrap_or_default(),+        });+    } else {+        terms.push(TreeTerm {+            positive: false,+            present: false,+            id: Id::default(),+        });+    }+    Ok(Some(+        treemerge(+            repo,+            txn,+            store,+            &terms,+            &[RenameMap::new(), RenameMap::new(), RenameMap::new()],+            adjacent,+        )?+        .tree,+    ))+}++pub fn merge_many(+    repo: &Path,+    txn: &mut Txn,+    store: &mut Store,+    heads: &[Id],+    adjacent: bool,+) -> Result<MergeOutcome> {+    if heads.len() == 1 {+        let tree = tree_of(store, heads[0])?;+        return treemerge(+            repo,+            txn,+            store,+            &[TreeTerm {+                positive: true,+                present: tree.is_some(),+                id: tree.unwrap_or_default(),+            }],+            &[RenameMap::new()],+            adjacent,+        );+    }+    let mut terms = Vec::new();+    let mut maps = Vec::new();+    let map_base = if heads.len() > 1 {+        merge_bases(store, heads[0], heads[1])?.first().copied()+    } else {+        None+    };+    for head in heads {+        let tree = tree_of(store, *head)?;+        terms.push(TreeTerm {+            positive: true,+            present: tree.is_some(),+            id: tree.unwrap_or_default(),+        });+        maps.push(match map_base {+            Some(base) => map_from(store, base, *head)?,+            None => RenameMap::new(),+        });+    }+    for head in &heads[1..] {+        let bases = merge_bases(store, heads[0], *head)?;+        let tree = base_tree(repo, txn, store, &bases, adjacent)?;+        terms.push(TreeTerm {+            positive: false,+            present: tree.is_some(),+            id: tree.unwrap_or_default(),+        });+        maps.push(RenameMap::new());+    }+    treemerge(repo, txn, store, &terms, &maps, adjacent)+}++pub fn rewrite_tree(+    repo: &Path,+    txn: &mut Txn,+    store: &mut Store,+    old_commit: Id,+    commit_tree: Id,+    old_parents: &[Id],+    new_parents: &[Id],+    new_parent_trees: &[Id],+    adjacent: bool,+) -> Result<MergeOutcome> {+    let mut terms = vec![TreeTerm {+        positive: true,+        present: true,+        id: commit_tree,+    }];+    let mut maps = Vec::new();+    maps.push(if let Some(parent) = old_parents.first() {+        map_from(store, *parent, old_commit)?+    } else {+        RenameMap::new()+    });+    if old_parents.is_empty() {+        for tree in new_parent_trees {+            terms.push(TreeTerm {+                positive: true,+                present: true,+                id: *tree,+            });+            maps.push(RenameMap::new());+        }+        terms.push(TreeTerm {+            positive: false,+            present: false,+            id: Id::default(),+        });+        maps.push(RenameMap::new());+    } else {+        for (index, parent) in old_parents.iter().enumerate() {+            let old_tree = tree_of(store, *parent)?;+            let new_tree = new_parent_trees.get(index).copied().unwrap_or_default();+            terms.push(TreeTerm {+                positive: true,+                present: true,+                id: new_tree,+            });+            terms.push(TreeTerm {+                positive: false,+                present: old_tree.is_some(),+                id: old_tree.unwrap_or_default(),+            });+            maps.push(if let Some(new_parent) = new_parents.get(index) {+                map_from(store, *parent, *new_parent)?+            } else {+                RenameMap::new()+            });+            maps.push(RenameMap::new());+        }+    }+    treemerge(repo, txn, store, &terms, &maps, adjacent)+}++pub fn make_commit(+    txn: &mut Txn,+    store: &mut Store,+    repo: &Path,+    parents: &[Id],+    root: Id,+    change: [u8; 16],+    author: Sig,+    message: &str,+    renames_state: u8,+    extra: &[(Vec<u8>, Vec<u8>)],+) -> Result<Id> {+    let mut renames = Vec::new();+    if renames_state == commit::RENAMES_RECORDED {+        for (index, parent) in parents.iter().enumerate() {+            let parent_tree = tree_of(store, *parent)?;+            let detected = detect(+                store,+                Some(txn.writer()),+                parent_tree,+                Some(root),+                0,+                index as u64,+            )?;+            renames.extend(detected);+        }+    }+    let commit = Commit {+        version: 1,+        parents: parents.to_vec(),+        root_tree: root,+        change_id: change,+        author,+        committer: identity::signature(repo),+        message: message.as_bytes().to_vec(),+        renames_state,+        renames,+        extra: extra.to_vec(),+    };+    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))+}++fn adjacent_config(root: &Path) -> bool {+    core::repo_config_value(root, "merge.adjacent").as_deref() == Some("merge")+}++pub fn conflict_kind_label(conflict: &Conflict) -> &'static str {+    if conflict+        .adds+        .iter()+        .chain(conflict.removes.iter())+        .any(|value| value.kind == KIND_SUBTREE)+    {+        return "tree";+    }+    if conflict+        .adds+        .iter()+        .chain(conflict.removes.iter())+        .any(|value| value.kind == 0)+    {+        return "delete/modify";+    }+    "text"+}++pub fn conflict_ranges(+    store: &mut Store,+    conflict: &Conflict,+    adjacent: bool,+) -> Result<Option<EditResult>> {+    if conflict.adds.len() != 2 || conflict.removes.len() != 1 {+        return Ok(None);+    }+    let ours = &conflict.adds[0];+    let theirs = &conflict.adds[1];+    let base = &conflict.removes[0];+    if ours.kind == 0 || theirs.kind == 0 || base.kind == 0 {+        return Ok(None);+    }+    if ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE || base.kind == KIND_SUBTREE {+        return Ok(None);+    }+    let (Some(base_id), Some(ours_id), Some(theirs_id)) =+        (base.target, ours.target, theirs.target)+    else {+        return Ok(None);+    };+    merge_blobs(+        store,+        None,+        base_id,+        ours_id,+        theirs_id,+        adjacent,+    )+}++pub fn edit_tree(+    txn: &mut Txn,+    store: &mut Store,+    tree_id: Id,+    path: &[u8],+    present: bool,+    kind: u8,+    target: Id,+) -> Result<Option<Id>> {+    edit_tree_into(txn, store, tree_id, path, present, kind, target, 0)+}++fn edit_tree_into(+    txn: &mut Txn,+    store: &mut Store,+    tree_id: Id,+    path: &[u8],+    present: bool,+    kind: u8,+    target: Id,+    depth: usize,+) -> Result<Option<Id>> {+    if depth > crate::object::MAX_TREE_DEPTH {+        return Ok(None);+    }+    let Some(body) = read_any(store, Some(txn.writer()), TYPE_TREE, tree_id)? else {+        return Ok(None);+    };+    let tree = tree::decode(&body)?;+    let cut = path+        .iter()+        .position(|byte| *byte == b'/')+        .unwrap_or(path.len());+    let name = &path[..cut];+    let mut entries = Vec::new();+    let mut found = false;+    for entry in tree.entries {+        if entry.name != name {+            entries.push(entry);+            continue;+        }+        found = true;+        if cut == path.len() {+            if present {+                entries.push(TreeEntry {+                    name: entry.name,+                    kind,+                    target,+                });+            }+        } else if entry.kind == KIND_SUBTREE {+            if let Some(child) = edit_tree_into(+                txn,+                store,+                entry.target,+                &path[cut + 1..],+                present,+                kind,+                target,+                depth + 1,+            )? {+                if !tree_empty(store, Some(txn.writer()), child)? {+                    entries.push(TreeEntry {+                        name: entry.name,+                        kind: KIND_SUBTREE,+                        target: child,+                    });+                }+            } else {+                entries.push(entry);+            }+        } else {+            entries.push(entry);+        }+    }+    if !found && cut == path.len() && present {+        entries.push(TreeEntry {+            name: name.to_vec(),+            kind,+            target,+        });+    }+    Ok(Some(add_tree(txn, &entries)?))+}++pub fn snapshot_run(root: &Path) -> Result<()> {+    snapshot::run(root)?;+    Ok(())+}++pub fn add_blob_data(txn: &mut Txn, data: &[u8]) -> Id {+    add_blob(txn, data)+}++pub fn object_id_of(kind: u8, body: &[u8]) -> Id {+    object_id(kind, body)+}++pub fn rename_from_map(map: &RenameMap, path: &[u8]) -> Option<Vec<u8>> {+    rename_lookup(map, path)+}++pub fn adjacent(root: &Path) -> bool {+    adjacent_config(root)+}++pub fn resolution_store(repo: &Path, body: &[u8], blob: Id) {+    resolution_record(repo, body, blob);+}++pub fn maps_empty() -> RenameMap {+    RenameMap::new()+}++pub fn apply_rename(map: &mut RenameMap, from: &[u8], to: &[u8]) {+    rename_apply(map, from, to);+}++pub fn first_parent_of(store: &mut Store, id: Id) -> Result<Option<Id>> {+    first_parent(store, id)+}++pub fn tree_of_commit(store: &mut Store, id: Id) -> Result<Option<Id>> {+    tree_of(store, id)+}++pub fn merge_binary_path(repo: &Path, path: &[u8]) -> bool {+    merge_binary(repo, path)+}--- /dev/null+++ b/veins/src/merge/mod.rs@@ -0,0 +1,2 @@+pub mod engine;+pub mod rename;--- /dev/null+++ b/veins/src/merge/rename.rs@@ -0,0 +1,21 @@+use crate::error::Result;+use crate::object::commit::Rename;+use crate::object::id::Id;+use crate::store::reader::Store;+use crate::store::writer::Writer;++pub fn detect(+    store: &mut Store,+    writer: &Writer,+    old_tree: Id,+    new_tree: Id,+) -> Result<Option<Vec<Rename>>> {+    Ok(Some(super::engine::detect(+        store,+        Some(writer),+        Some(old_tree),+        Some(new_tree),+        60,+        0,+    )?))+}--- /dev/null+++ b/veins/src/object/blob.rs@@ -0,0 +1,159 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::chunker::next_chunk;+use crate::object::id::{Id, object_id};+use crate::object::{+    INLINE_THRESHOLD, MAX_CHUNK_LEN, MAX_MANIFEST_ENTRIES, RawObject, TYPE_BLOB, TYPE_CHUNK,+};++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum BlobForm {+    Inline,+    Leaf,+    Interior,+}++#[derive(Clone)]+pub struct BlobEntry {+    pub id: Id,+    pub length: u64,+}++#[derive(Clone)]+pub struct Blob {+    pub form: BlobForm,+    pub data: Vec<u8>,+    pub entries: Vec<BlobEntry>,+}++pub struct BlobBuild {+    pub root: Id,+    pub objects: Vec<RawObject>,+}++pub fn encode_inline(data: &[u8]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(data.len() + 8);+    writer.u8(0);+    writer.bytes(data);+    writer.into_vec()+}++pub fn decode(body: &[u8]) -> Result<Blob> {+    let mut reader = Reader::new(body);+    let form = match reader.u8()? {+        0 => BlobForm::Inline,+        1 => BlobForm::Leaf,+        2 => BlobForm::Interior,+        _ => return Err(Error::new("invalid blob form")),+    };+    if form == BlobForm::Inline {+        let data = reader.bytes(INLINE_THRESHOLD)?.to_vec();+        reader.finish()?;+        return Ok(Blob {+            form,+            data,+            entries: Vec::new(),+        });+    }+    let count = reader.varint()?;+    let count = usize::try_from(count).map_err(|_| Error::new("manifest too large"))?;+    if count == 0 || count > MAX_MANIFEST_ENTRIES {+        return Err(Error::new("invalid manifest entry count"));+    }+    let mut entries = Vec::with_capacity(count);+    let mut total = 0u64;+    for _ in 0..count {+        let id = reader.id()?;+        let length = reader.varint()?;+        if length == 0 {+            return Err(Error::new("invalid manifest entry length"));+        }+        if form == BlobForm::Leaf && length > MAX_CHUNK_LEN as u64 {+            return Err(Error::new("chunk exceeds maximum size"));+        }+        total = total+            .checked_add(length)+            .ok_or_else(|| Error::new("manifest length overflow"))?;+        entries.push(BlobEntry { id, length });+    }+    reader.finish()?;+    Ok(Blob {+        form,+        data: Vec::new(),+        entries,+    })+}++fn cut_after(id: Id, current_length: usize) -> bool {+    current_length >= MAX_MANIFEST_ENTRIES || (current_length >= 16 && id.0[0] == 0)+}++struct NodeRef {+    id: Id,+    length: u64,+}++pub fn build(data: &[u8]) -> BlobBuild {+    if data.len() <= INLINE_THRESHOLD {+        let body = encode_inline(data);+        let root = object_id(TYPE_BLOB, &body);+        return BlobBuild {+            root,+            objects: vec![RawObject::known(TYPE_BLOB, root, body)],+        };+    }++    let mut objects = Vec::new();+    let mut level = Vec::new();+    let mut offset = 0;+    while offset < data.len() {+        let length = next_chunk(&data[offset..]);+        let chunk = &data[offset..offset + length];+        let id = object_id(TYPE_CHUNK, chunk);+        objects.push(RawObject::known(TYPE_CHUNK, id, chunk.to_vec()));+        level.push(NodeRef {+            id,+            length: length as u64,+        });+        offset += length;+    }++    let mut leaf_level = true;+    let root = loop {+        let mut groups = Vec::new();+        let mut start = 0;+        for index in 0..level.len() {+            let current = index - start + 1;+            if cut_after(level[index].id, current) || index + 1 == level.len() {+                groups.push((start, current));+                start = index + 1;+            }+        }++        let mut next = Vec::with_capacity(groups.len());+        for (start, count) in groups {+            let mut writer = Writer::with_capacity(count * 40 + 8);+            writer.u8(if leaf_level { 1 } else { 2 });+            writer.varint(count as u64);+            let mut total = 0u64;+            for index in 0..count {+                let node = &level[start + index];+                writer.id(node.id);+                writer.varint(node.length);+                total += node.length;+            }+            let body = writer.into_vec();+            let id = object_id(TYPE_BLOB, &body);+            objects.push(RawObject::known(TYPE_BLOB, id, body));+            next.push(NodeRef { id, length: total });+        }++        if next.len() == 1 {+            break next[0].id;+        }+        level = next;+        leaf_level = false;+    };++    BlobBuild { root, objects }+}--- /dev/null+++ b/veins/src/object/chunker.rs@@ -0,0 +1,58 @@+use std::sync::OnceLock;++static GEAR: OnceLock<[u64; 256]> = OnceLock::new();++fn build_gear() -> [u64; 256] {+    let mut table = [0u64; 256];+    for (index, slot) in table.iter_mut().enumerate() {+        let mut hasher = blake3::Hasher::new();+        hasher.update(b"veins/fastcdc/gear/v1");+        hasher.update(&[index as u8]);+        let digest = hasher.finalize();+        let mut value = [0u8; 8];+        value.copy_from_slice(&digest.as_bytes()[..8]);+        *slot = u64::from_le_bytes(value);+    }+    table+}++pub fn gear_table() -> &'static [u64; 256] {+    GEAR.get_or_init(build_gear)+}++pub fn next_chunk(data: &[u8]) -> usize {+    const MIN_SIZE: usize = 16 * 1024;+    const AVG_SIZE: usize = 64 * 1024;+    const MAX_SIZE: usize = 256 * 1024;+    const MASK_SMALL: u64 = 0x3ffff;+    const MASK_LARGE: u64 = 0x3fff;++    let length = data.len();+    if length <= MIN_SIZE {+        return length;+    }+    let limit = length.min(MAX_SIZE);+    let normal = AVG_SIZE.min(limit);+    let gear = gear_table();+    let mut fingerprint = 0u64;+    let mut index = MIN_SIZE;+    unsafe {+        while index < normal {+            let byte = *data.get_unchecked(index);+            fingerprint = (fingerprint >> 1).wrapping_add(gear[byte as usize]);+            if fingerprint & MASK_SMALL == 0 {+                return index + 1;+            }+            index += 1;+        }+        while index < limit {+            let byte = *data.get_unchecked(index);+            fingerprint = (fingerprint >> 1).wrapping_add(gear[byte as usize]);+            if fingerprint & MASK_LARGE == 0 {+                return index + 1;+            }+            index += 1;+        }+    }+    limit+}--- /dev/null+++ b/veins/src/object/commit.rs@@ -0,0 +1,197 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::{MAX_MESSAGE_LEN, MAX_NAME_LEN};++pub const RENAMES_UNKNOWN: u8 = 0;+pub const RENAMES_RECORDED: u8 = 1;++#[derive(Clone, Default)]+pub struct Sig {+    pub name: Vec<u8>,+    pub email: Vec<u8>,+    pub seconds: i64,+    pub tz_min: i16,+}++#[derive(Clone)]+pub struct Rename {+    pub parent_index: u64,+    pub kind: u8,+    pub from_path: Vec<u8>,+    pub to_path: Vec<u8>,+}++#[derive(Clone)]+pub struct Commit {+    pub version: u8,+    pub parents: Vec<Id>,+    pub root_tree: Id,+    pub change_id: [u8; 16],+    pub author: Sig,+    pub committer: Sig,+    pub message: Vec<u8>,+    pub renames_state: u8,+    pub renames: Vec<Rename>,+    pub extra: Vec<(Vec<u8>, Vec<u8>)>,+}++impl Commit {+    pub fn empty(change_id: [u8; 16], root_tree: Id, sig: Sig) -> Self {+        Self {+            version: 1,+            parents: Vec::new(),+            root_tree,+            change_id,+            author: sig.clone(),+            committer: sig,+            message: Vec::new(),+            renames_state: RENAMES_RECORDED,+            renames: Vec::new(),+            extra: Vec::new(),+        }+    }+}++fn write_sig(writer: &mut Writer, sig: &Sig) {+    writer.bytes(&sig.name);+    writer.bytes(&sig.email);+    writer.i64le(sig.seconds);+    writer.i16le(sig.tz_min);+}++fn read_sig(reader: &mut Reader<'_>) -> Result<Sig> {+    Ok(Sig {+        name: reader.bytes(MAX_NAME_LEN)?.to_vec(),+        email: reader.bytes(MAX_NAME_LEN)?.to_vec(),+        seconds: reader.i64le()?,+        tz_min: reader.i16le()?,+    })+}++pub fn encode(commit: &Commit) -> Vec<u8> {+    let mut writer = Writer::with_capacity(256);+    writer.u8(commit.version);+    writer.varint(commit.parents.len() as u64);+    for parent in &commit.parents {+        writer.id(*parent);+    }+    writer.id(commit.root_tree);+    writer.raw(&commit.change_id);+    write_sig(&mut writer, &commit.author);+    write_sig(&mut writer, &commit.committer);+    writer.bytes(&commit.message);+    writer.u8(commit.renames_state);+    writer.varint(commit.renames.len() as u64);+    for rename in &commit.renames {+        writer.varint(rename.parent_index);+        writer.u8(rename.kind);+        writer.bytes(&rename.from_path);+        writer.bytes(&rename.to_path);+    }+    writer.varint(commit.extra.len() as u64);+    for (key, value) in &commit.extra {+        writer.bytes(key);+        writer.bytes(value);+    }+    writer.into_vec()+}++pub fn decode(body: &[u8]) -> Result<Commit> {+    let mut reader = Reader::new(body);+    let version = reader.u8()?;+    if version != 1 {+        return Err(Error::new("unsupported commit version"));+    }+    let parent_count = reader.varint()?;+    let parent_count = usize::try_from(parent_count).map_err(|_| Error::new("too many parents"))?;+    if parent_count > 1024 {+        return Err(Error::new("too many parents"));+    }+    let mut parents = Vec::with_capacity(parent_count);+    for _ in 0..parent_count {+        parents.push(reader.id()?);+    }+    let root_tree = reader.id()?;+    let mut change_id = [0u8; 16];+    change_id.copy_from_slice(reader.raw(16)?);+    let author = read_sig(&mut reader)?;+    let committer = read_sig(&mut reader)?;+    let message = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+    let renames_state = reader.u8()?;+    if renames_state > 1 {+        return Err(Error::new("invalid rename state"));+    }+    let rename_count = reader.varint()?;+    let rename_count = usize::try_from(rename_count).map_err(|_| Error::new("too many renames"))?;+    if rename_count > 1_000_000 {+        return Err(Error::new("rename limit exceeded"));+    }+    if renames_state == RENAMES_UNKNOWN && rename_count != 0 {+        return Err(Error::new("unknown rename state carries renames"));+    }+    let mut renames = Vec::with_capacity(rename_count);+    let mut previous_parent = 0u64;+    let mut previous_path: Option<Vec<u8>> = None;+    for _ in 0..rename_count {+        let parent_index = reader.varint()?;+        if parent_index >= parent_count as u64 {+            return Err(Error::new("rename parent index out of range"));+        }+        let kind = reader.u8()?;+        if kind > 1 {+            return Err(Error::new("invalid rename kind"));+        }+        let from_path = reader.bytes(crate::object::MAX_PATH_LEN)?.to_vec();+        let to_path = reader.bytes(crate::object::MAX_PATH_LEN)?.to_vec();+        if !crate::object::path::valid_path(&from_path)+            || !crate::object::path::valid_path(&to_path)+        {+            return Err(Error::new("invalid rename path"));+        }+        if let Some(previous) = &previous_path {+            if parent_index < previous_parent {+                return Err(Error::new("renames are not sorted"));+            }+            if parent_index == previous_parent && previous.as_slice() >= to_path.as_slice() {+                return Err(Error::new("renames are not sorted"));+            }+        }+        previous_parent = parent_index;+        previous_path = Some(to_path.clone());+        renames.push(Rename {+            parent_index,+            kind,+            from_path,+            to_path,+        });+    }+    let extra_count = reader.varint()?;+    let extra_count =+        usize::try_from(extra_count).map_err(|_| Error::new("too many extra headers"))?;+    if extra_count > 1024 {+        return Err(Error::new("too many extra headers"));+    }+    let mut extra = Vec::with_capacity(extra_count);+    for _ in 0..extra_count {+        let key = reader.bytes(MAX_NAME_LEN)?.to_vec();+        let value = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+        if key.is_empty() {+            return Err(Error::new("empty extra header key"));+        }+        extra.push((key, value));+    }+    reader.finish()?;+    Ok(Commit {+        version,+        parents,+        root_tree,+        change_id,+        author,+        committer,+        message,+        renames_state,+        renames,+        extra,+    })+}--- /dev/null+++ b/veins/src/object/conflict.rs@@ -0,0 +1,94 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::tree::KIND_CONFLICT;++pub const MAX_CONFLICT_TERMS: usize = 64;++#[derive(Clone, PartialEq, Eq)]+pub struct ConflictValue {+    pub kind: u8,+    pub target: Option<Id>,+}++#[derive(Clone, Default)]+pub struct Conflict {+    pub adds: Vec<ConflictValue>,+    pub removes: Vec<ConflictValue>,+}++fn value_kind_valid(kind: u8) -> bool {+    kind == 0 || (1..=KIND_CONFLICT).contains(&kind)+}++fn read_value(reader: &mut Reader<'_>) -> Result<ConflictValue> {+    let kind = reader.u8()?;+    if !value_kind_valid(kind) {+        return Err(Error::new("invalid conflict value kind"));+    }+    if kind == 0 {+        return Ok(ConflictValue { kind, target: None });+    }+    Ok(ConflictValue {+        kind,+        target: Some(reader.id()?),+    })+}++fn read_values(reader: &mut Reader<'_>) -> Result<Vec<ConflictValue>> {+    let count = reader.varint()?;+    let count = usize::try_from(count).map_err(|_| Error::new("conflict term count overflow"))?;+    if count > MAX_CONFLICT_TERMS {+        return Err(Error::new("conflict term limit exceeded"));+    }+    let mut values = Vec::with_capacity(count);+    for _ in 0..count {+        values.push(read_value(reader)?);+    }+    Ok(values)+}++pub fn decode(body: &[u8]) -> Result<Conflict> {+    let mut reader = Reader::new(body);+    let adds = read_values(&mut reader)?;+    let removes = read_values(&mut reader)?;+    reader.finish()?;+    if removes.is_empty() {+        return Err(Error::new("conflict has no removed terms"));+    }+    if adds.len() != removes.len() + 1 {+        return Err(Error::new("conflict terms are unbalanced"));+    }+    if adds.len() + removes.len() > MAX_CONFLICT_TERMS {+        return Err(Error::new("conflict term limit exceeded"));+    }+    for add in &adds {+        if removes.contains(add) {+            return Err(Error::new("conflict terms are not simplified"));+        }+    }+    if adds.len() > 1 && adds.iter().all(|value| value == &adds[0]) {+        return Err(Error::new("conflict terms are not simplified"));+    }+    Ok(Conflict { adds, removes })+}++fn write_values(writer: &mut Writer, values: &[ConflictValue]) {+    writer.varint(values.len() as u64);+    for value in values {+        writer.u8(value.kind);+        if value.kind != 0+            && let Some(target) = value.target+        {+            writer.id(target);+        }+    }+}++pub fn encode(conflict: &Conflict) -> Vec<u8> {+    let mut writer =+        Writer::with_capacity((conflict.adds.len() + conflict.removes.len()) * 40 + 16);+    write_values(&mut writer, &conflict.adds);+    write_values(&mut writer, &conflict.removes);+    writer.into_vec()+}--- /dev/null+++ b/veins/src/object/id.rs@@ -0,0 +1,76 @@+use crate::error::{Error, Result};++#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct Id(pub [u8; 32]);++const HEX: &[u8; 16] = b"0123456789abcdef";++impl Id {+    pub fn to_hex(self) -> String {+        let mut text = String::with_capacity(64);+        for byte in self.0 {+            text.push(HEX[(byte >> 4) as usize] as char);+            text.push(HEX[(byte & 0x0f) as usize] as char);+        }+        text+    }++    pub fn short(self) -> String {+        self.to_hex()[..12].to_string()+    }++    pub fn from_hex(text: &str) -> Result<Self> {+        if text.len() != 64 {+            return Err(Error::new("object id must contain 64 hex digits"));+        }+        let bytes = text.as_bytes();+        let mut value = [0u8; 32];+        for index in 0..32 {+            let high = hex_value(bytes[index * 2])?;+            let low = hex_value(bytes[index * 2 + 1])?;+            value[index] = (high << 4) | low;+        }+        Ok(Self(value))+    }+}++impl std::fmt::Debug for Id {+    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+        formatter.write_str(&self.to_hex())+    }+}++fn hex_value(byte: u8) -> Result<u8> {+    match byte {+        b'0'..=b'9' => Ok(byte - b'0'),+        b'a'..=b'f' => Ok(byte - b'a' + 10),+        b'A'..=b'F' => Ok(byte - b'A' + 10),+        _ => Err(Error::new("invalid hex digit")),+    }+}++pub fn hash_bytes(data: &[u8]) -> [u8; 32] {+    *blake3::hash(data).as_bytes()+}++pub fn object_id(kind: u8, body: &[u8]) -> Id {+    let mut hasher = blake3::Hasher::new();+    hasher.update(b"veins/1\0");+    hasher.update(&[kind]);+    hasher.update(body);+    Id(*hasher.finalize().as_bytes())+}++pub fn prefix_matches(full: &str, prefix: &str) -> bool {+    if prefix.is_empty() || prefix.len() > full.len() {+        return false;+    }+    full.as_bytes()+        .iter()+        .zip(prefix.as_bytes())+        .all(|(left, right)| left.eq_ignore_ascii_case(right))+}++pub fn is_hex_prefix(text: &str) -> bool {+    (4..=64).contains(&text.len()) && text.bytes().all(|byte| byte.is_ascii_hexdigit())+}--- /dev/null+++ b/veins/src/object/mod.rs@@ -0,0 +1,51 @@+pub mod blob;+pub mod chunker;+pub mod commit;+pub mod conflict;+pub mod id;+pub mod path;+pub mod tree;+pub mod view;++use id::Id;++pub const TYPE_CHUNK: u8 = 1;+pub const TYPE_BLOB: u8 = 2;+pub const TYPE_TREE: u8 = 3;+pub const TYPE_COMMIT: u8 = 4;+pub const TYPE_CONFLICT: u8 = 5;+pub const TYPE_OPERATION: u8 = 6;+pub const TYPE_VIEW: u8 = 7;++pub const INLINE_THRESHOLD: usize = 16 * 1024;+pub const MAX_CHUNK_LEN: usize = 256 * 1024;+pub const MAX_MANIFEST_ENTRIES: usize = 1024;+pub const MAX_TREE_ENTRIES: usize = 1_000_000;+pub const MAX_TREE_DEPTH: usize = 512;+pub const MAX_NAME_LEN: usize = 4096;+pub const MAX_PATH_LEN: usize = 65_536;+pub const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024;+pub const MAX_OBJECT_BODY: usize = 64 * 1024 * 1024;+pub const MAX_STORE_PACK_BYTES: u64 = 8 * 1024 * 1024 * 1024;++#[derive(Clone)]+pub struct RawObject {+    pub kind: u8,+    pub body: Vec<u8>,+    pub id: Id,+}++impl RawObject {+    pub fn new(kind: u8, body: Vec<u8>) -> Self {+        let id = id::object_id(kind, &body);+        Self { kind, body, id }+    }++    pub fn known(kind: u8, id: Id, body: Vec<u8>) -> Self {+        Self { kind, body, id }+    }+}++pub fn type_valid(kind: u8) -> bool {+    (TYPE_CHUNK..=TYPE_VIEW).contains(&kind)+}--- /dev/null+++ b/veins/src/object/path.rs@@ -0,0 +1,48 @@+use crate::object::{MAX_NAME_LEN, MAX_PATH_LEN};++pub fn valid_component(component: &[u8]) -> bool {+    if component.is_empty() || component.len() > MAX_NAME_LEN {+        return false;+    }+    if component == b"." || component == b".." {+        return false;+    }+    component.iter().all(|byte| *byte != 0 && *byte != b'/')+}++pub fn valid_name(name: &[u8]) -> bool {+    valid_component(name) && !name.eq_ignore_ascii_case(b".veins")+}++pub fn valid_path(path: &[u8]) -> bool {+    if path.is_empty() || path.len() > MAX_PATH_LEN {+        return false;+    }+    if path[0] == b'/' {+        return false;+    }+    path.split(|byte| *byte == b'/').all(valid_component)+}++pub fn valid_checkout_component(component: &[u8]) -> bool {+    valid_name(component) && !component.eq_ignore_ascii_case(b".git")+}++pub fn valid_checkout_path(path: &[u8]) -> bool {+    if !valid_path(path) {+        return false;+    }+    path.split(|byte| *byte == b'/')+        .all(valid_checkout_component)+}++pub fn join(base: &[u8], name: &[u8]) -> Vec<u8> {+    if base.is_empty() {+        return name.to_vec();+    }+    let mut path = Vec::with_capacity(base.len() + 1 + name.len());+    path.extend_from_slice(base);+    path.push(b'/');+    path.extend_from_slice(name);+    path+}--- /dev/null+++ b/veins/src/object/tree.rs@@ -0,0 +1,188 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::path::valid_name;+use crate::object::{MAX_NAME_LEN, MAX_TREE_DEPTH, MAX_TREE_ENTRIES, TYPE_TREE};+use crate::store::reader::Store;++pub const KIND_FILE: u8 = 1;+pub const KIND_EXECUTABLE: u8 = 2;+pub const KIND_SYMLINK: u8 = 3;+pub const KIND_SUBTREE: u8 = 4;+pub const KIND_SUBMODULE: u8 = 5;+pub const KIND_CONFLICT: u8 = 6;+pub const KIND_MISSING: u8 = 0;++#[derive(Clone)]+pub struct TreeEntry {+    pub name: Vec<u8>,+    pub kind: u8,+    pub target: Id,+}++#[derive(Clone)]+pub struct Tree {+    pub entries: Vec<TreeEntry>,+}++#[derive(Clone)]+pub struct FlatEntry {+    pub path: Vec<u8>,+    pub kind: u8,+    pub target: Id,+}++fn valid_kind(kind: u8) -> bool {+    (KIND_FILE..=KIND_CONFLICT).contains(&kind)+}++fn valid_submodule_target(id: Id) -> bool {+    id.0[20..].iter().all(|byte| *byte == 0)+}++pub fn encode(entries: &[TreeEntry]) -> Result<Vec<u8>> {+    let mut writer = Writer::with_capacity(entries.len() * 48 + 8);+    writer.varint(entries.len() as u64);+    let mut previous: Option<&[u8]> = None;+    for entry in entries {+        if !valid_name(&entry.name) {+            return Err(Error::new("invalid tree entry name"));+        }+        if previous.is_some_and(|name| name >= entry.name.as_slice()) {+            return Err(Error::new("tree entries are not sorted"));+        }+        if !valid_kind(entry.kind) {+            return Err(Error::new("invalid tree entry kind"));+        }+        if entry.kind == KIND_SUBMODULE && !valid_submodule_target(entry.target) {+            return Err(Error::new("invalid submodule target"));+        }+        writer.bytes(&entry.name);+        writer.u8(entry.kind);+        writer.id(entry.target);+        previous = Some(&entry.name);+    }+    Ok(writer.into_vec())+}++pub fn decode(body: &[u8]) -> Result<Tree> {+    let mut reader = Reader::new(body);+    let count = reader.varint()?;+    let count = usize::try_from(count).map_err(|_| Error::new("tree too large"))?;+    if count > MAX_TREE_ENTRIES {+        return Err(Error::new("tree entry limit exceeded"));+    }+    let mut entries: Vec<TreeEntry> = Vec::with_capacity(count);+    for _ in 0..count {+        let name = reader.bytes(MAX_NAME_LEN)?;+        if !valid_name(name) {+            return Err(Error::new("invalid tree entry name"));+        }+        if entries+            .last()+            .is_some_and(|previous| previous.name.as_slice() >= name)+        {+            return Err(Error::new("tree entries are not sorted"));+        }+        let kind = reader.u8()?;+        if !valid_kind(kind) {+            return Err(Error::new("invalid tree entry kind"));+        }+        let target = reader.id()?;+        if kind == KIND_SUBMODULE && !valid_submodule_target(target) {+            return Err(Error::new("invalid submodule target"));+        }+        entries.push(TreeEntry {+            name: name.to_vec(),+            kind,+            target,+        });+    }+    reader.finish()?;+    Ok(Tree { entries })+}++/// Visit every entry of an encoded tree without copying names.+pub fn scan(body: &[u8], mut visit: impl FnMut(&[u8], u8, Id) -> Result<()>) -> Result<()> {+    let mut reader = Reader::new(body);+    let count = reader.varint()?;+    let count = usize::try_from(count).map_err(|_| Error::new("tree too large"))?;+    if count > MAX_TREE_ENTRIES {+        return Err(Error::new("tree entry limit exceeded"));+    }+    let mut previous: Option<&[u8]> = None;+    for _ in 0..count {+        let name = reader.bytes(MAX_NAME_LEN)?;+        if !valid_name(name) {+            return Err(Error::new("invalid tree entry name"));+        }+        if previous.is_some_and(|value| value >= name) {+            return Err(Error::new("tree entries are not sorted"));+        }+        let kind = reader.u8()?;+        if !valid_kind(kind) {+            return Err(Error::new("invalid tree entry kind"));+        }+        let target = reader.id()?;+        if kind == KIND_SUBMODULE && !valid_submodule_target(target) {+            return Err(Error::new("invalid submodule target"));+        }+        visit(name, kind, target)?;+        previous = Some(name);+    }+    reader.finish()+}++fn flatten_into(+    store: &mut Store,+    tree_id: Id,+    prefix: &mut Vec<u8>,+    output: &mut Vec<FlatEntry>,+    depth: usize,+) -> Result<()> {+    if depth > MAX_TREE_DEPTH {+        return Err(Error::new("tree nesting too deep"));+    }+    let body = store+        .body(tree_id, TYPE_TREE)?+        .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?;+    scan(&body, |name, kind, target| {+        let old_length = prefix.len();+        if !prefix.is_empty() {+            prefix.push(b'/');+        }+        prefix.extend_from_slice(name);+        if kind == KIND_SUBTREE {+            flatten_into(store, target, prefix, output, depth + 1)?;+        } else {+            output.push(FlatEntry {+                path: prefix.clone(),+                kind,+                target,+            });+        }+        prefix.truncate(old_length);+        Ok(())+    })+}++pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {+    let mut output = Vec::new();+    let mut prefix = Vec::new();+    flatten_into(store, tree_id, &mut prefix, &mut output, 0)?;+    output.sort_by(|left, right| left.path.cmp(&right.path));+    Ok(output)+}++pub fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {+    entries+        .binary_search_by(|entry| entry.path.as_slice().cmp(path))+        .ok()+        .map(|index| &entries[index])+}++pub fn find_entry(tree: &Tree, name: &[u8]) -> Option<usize> {+    tree.entries+        .binary_search_by(|entry| entry.name.as_slice().cmp(name))+        .ok()+}--- /dev/null+++ b/veins/src/object/view.rs@@ -0,0 +1,341 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::{MAX_MESSAGE_LEN, MAX_NAME_LEN};++#[derive(Clone, Default)]+pub struct TargetSet {+    pub adds: Vec<Option<Id>>,+    pub removes: Vec<Option<Id>>,+}++#[derive(Clone, Default)]+pub struct Bookmark {+    pub name: Vec<u8>,+    pub targets: TargetSet,+}++#[derive(Clone, Default)]+pub struct TagRef {+    pub name: Vec<u8>,+    pub target: Id,+}++#[derive(Clone, Default)]+pub struct RemoteRef {+    pub remote: Vec<u8>,+    pub name: Vec<u8>,+    pub target: Id,+}++#[derive(Clone, Default)]+pub struct WorkspaceRef {+    pub workspace: Vec<u8>,+    pub target: Id,+}++#[derive(Clone, Default)]+pub struct View {+    pub heads: Vec<Id>,+    pub bookmarks: Vec<Bookmark>,+    pub tags: Vec<TagRef>,+    pub remote_refs: Vec<RemoteRef>,+    pub working_copies: Vec<WorkspaceRef>,+}++#[derive(Clone, Default)]+pub struct TimeMs {+    pub millis: i64,+    pub tz_min: i16,+}++#[derive(Clone, Default)]+pub struct Operation {+    pub parents: Vec<Id>,+    pub view: Id,+    pub start: TimeMs,+    pub end: TimeMs,+    pub hostname: Vec<u8>,+    pub username: Vec<u8>,+    pub description: Vec<u8>,+    pub tags: Vec<(Vec<u8>, Vec<u8>)>,+}++fn read_opt_ids(reader: &mut Reader<'_>, maximum: usize) -> Result<Vec<Option<Id>>> {+    let count = reader.varint()?;+    let count = usize::try_from(count).map_err(|_| Error::new("list too large"))?;+    if count > maximum {+        return Err(Error::new("list limit exceeded"));+    }+    let mut ids = Vec::with_capacity(count);+    for _ in 0..count {+        ids.push(reader.opt_id()?);+    }+    Ok(ids)+}++fn write_opt_ids(writer: &mut Writer, ids: &[Option<Id>]) {+    writer.varint(ids.len() as u64);+    for id in ids {+        writer.opt_id(*id);+    }+}++fn read_target_set(reader: &mut Reader<'_>) -> Result<TargetSet> {+    let adds = read_opt_ids(reader, 64)?;+    let removes = read_opt_ids(reader, 64)?;+    if adds.is_empty() {+        return Err(Error::new("bookmark target set has no adds"));+    }+    if adds.len() != removes.len() + 1 {+        return Err(Error::new("bookmark target set is unbalanced"));+    }+    if adds.len() + removes.len() > 64 {+        return Err(Error::new("bookmark target set limit exceeded"));+    }+    for add in &adds {+        if opt_id_contains(&removes, *add) {+            return Err(Error::new("bookmark target set is not simplified"));+        }+    }+    if adds.len() > 1 && adds.iter().all(|id| id == &adds[0]) {+        return Err(Error::new("bookmark target set has duplicate adds"));+    }+    Ok(TargetSet { adds, removes })+}++fn write_target_set(writer: &mut Writer, targets: &TargetSet) {+    write_opt_ids(writer, &targets.adds);+    write_opt_ids(writer, &targets.removes);+}++fn read_name(reader: &mut Reader<'_>) -> Result<Vec<u8>> {+    let name = reader.bytes(MAX_NAME_LEN)?.to_vec();+    if name.is_empty() || name.contains(&0) {+        return Err(Error::new("invalid view name"));+    }+    Ok(name)+}++fn opt_id_contains(ids: &[Option<Id>], value: Option<Id>) -> bool {+    ids.contains(&value)+}++pub fn encode_view(view: &View) -> Vec<u8> {+    let mut writer = Writer::with_capacity(256);+    writer.varint(view.heads.len() as u64);+    for head in &view.heads {+        writer.id(*head);+    }+    writer.varint(view.bookmarks.len() as u64);+    for bookmark in &view.bookmarks {+        writer.bytes(&bookmark.name);+        write_target_set(&mut writer, &bookmark.targets);+    }+    writer.varint(view.tags.len() as u64);+    for tag in &view.tags {+        writer.bytes(&tag.name);+        writer.id(tag.target);+    }+    writer.varint(view.remote_refs.len() as u64);+    for reference in &view.remote_refs {+        writer.bytes(&reference.remote);+        writer.bytes(&reference.name);+        writer.id(reference.target);+    }+    writer.varint(view.working_copies.len() as u64);+    for workspace in &view.working_copies {+        writer.bytes(&workspace.workspace);+        writer.id(workspace.target);+    }+    writer.into_vec()+}++pub fn decode_view(body: &[u8]) -> Result<View> {+    let mut reader = Reader::new(body);+    let head_count = reader.varint()?;+    let head_count = usize::try_from(head_count).map_err(|_| Error::new("too many heads"))?;+    if head_count > 1_000_000 {+        return Err(Error::new("head limit exceeded"));+    }+    let mut heads = Vec::with_capacity(head_count);+    let mut previous: Option<Id> = None;+    for _ in 0..head_count {+        let id = reader.id()?;+        if previous.is_some_and(|value| value >= id) {+            return Err(Error::new("heads are not sorted"));+        }+        heads.push(id);+        previous = Some(id);+    }++    let bookmark_count = reader.varint()?;+    let bookmark_count =+        usize::try_from(bookmark_count).map_err(|_| Error::new("too many bookmarks"))?;+    if bookmark_count > 1_000_000 {+        return Err(Error::new("bookmark limit exceeded"));+    }+    let mut bookmarks = Vec::with_capacity(bookmark_count);+    let mut previous_name: Option<Vec<u8>> = None;+    for _ in 0..bookmark_count {+        let name = read_name(&mut reader)?;+        if previous_name.as_ref().is_some_and(|value| value >= &name) {+            return Err(Error::new("bookmarks are not sorted"));+        }+        let targets = read_target_set(&mut reader)?;+        bookmarks.push(Bookmark {+            name: name.clone(),+            targets,+        });+        previous_name = Some(name);+    }++    let tag_count = reader.varint()?;+    let tag_count = usize::try_from(tag_count).map_err(|_| Error::new("too many tags"))?;+    if tag_count > 1_000_000 {+        return Err(Error::new("tag limit exceeded"));+    }+    let mut tags = Vec::with_capacity(tag_count);+    let mut previous_name: Option<Vec<u8>> = None;+    for _ in 0..tag_count {+        let name = read_name(&mut reader)?;+        if previous_name.as_ref().is_some_and(|value| value >= &name) {+            return Err(Error::new("tags are not sorted"));+        }+        let target = reader.id()?;+        tags.push(TagRef {+            name: name.clone(),+            target,+        });+        previous_name = Some(name);+    }++    let remote_count = reader.varint()?;+    let remote_count =+        usize::try_from(remote_count).map_err(|_| Error::new("too many remote refs"))?;+    if remote_count > 1_000_000 {+        return Err(Error::new("remote ref limit exceeded"));+    }+    let mut remote_refs = Vec::with_capacity(remote_count);+    let mut previous_pair: Option<(Vec<u8>, Vec<u8>)> = None;+    for _ in 0..remote_count {+        let remote = read_name(&mut reader)?;+        let name = read_name(&mut reader)?;+        let key = (remote.clone(), name.clone());+        if previous_pair.as_ref().is_some_and(|value| value >= &key) {+            return Err(Error::new("remote refs are not sorted"));+        }+        let target = reader.id()?;+        remote_refs.push(RemoteRef {+            remote,+            name,+            target,+        });+        previous_pair = Some(key);+    }++    let workspace_count = reader.varint()?;+    let workspace_count =+        usize::try_from(workspace_count).map_err(|_| Error::new("too many workspaces"))?;+    if workspace_count > 1_000_000 {+        return Err(Error::new("workspace limit exceeded"));+    }+    let mut working_copies = Vec::with_capacity(workspace_count);+    let mut previous_name: Option<Vec<u8>> = None;+    for _ in 0..workspace_count {+        let workspace = read_name(&mut reader)?;+        if previous_name+            .as_ref()+            .is_some_and(|value| value >= &workspace)+        {+            return Err(Error::new("workspaces are not sorted"));+        }+        let target = reader.id()?;+        working_copies.push(WorkspaceRef {+            workspace: workspace.clone(),+            target,+        });+        previous_name = Some(workspace);+    }++    reader.finish()?;+    Ok(View {+        heads,+        bookmarks,+        tags,+        remote_refs,+        working_copies,+    })+}++pub fn encode_operation(operation: &Operation) -> Vec<u8> {+    let mut writer = Writer::with_capacity(256);+    writer.varint(operation.parents.len() as u64);+    for parent in &operation.parents {+        writer.id(*parent);+    }+    writer.id(operation.view);+    writer.i64le(operation.start.millis);+    writer.i16le(operation.start.tz_min);+    writer.i64le(operation.end.millis);+    writer.i16le(operation.end.tz_min);+    writer.bytes(&operation.hostname);+    writer.bytes(&operation.username);+    writer.bytes(&operation.description);+    writer.varint(operation.tags.len() as u64);+    for (key, value) in &operation.tags {+        writer.bytes(key);+        writer.bytes(value);+    }+    writer.into_vec()+}++pub fn decode_operation(body: &[u8]) -> Result<Operation> {+    let mut reader = Reader::new(body);+    let parent_count = reader.varint()?;+    let parent_count = usize::try_from(parent_count).map_err(|_| Error::new("too many parents"))?;+    if parent_count > 1024 {+        return Err(Error::new("parent limit exceeded"));+    }+    let mut parents = Vec::with_capacity(parent_count);+    for _ in 0..parent_count {+        parents.push(reader.id()?);+    }+    let view = reader.id()?;+    let start = TimeMs {+        millis: reader.i64le()?,+        tz_min: reader.i16le()?,+    };+    let end = TimeMs {+        millis: reader.i64le()?,+        tz_min: reader.i16le()?,+    };+    let hostname = reader.bytes(MAX_NAME_LEN)?.to_vec();+    let username = reader.bytes(MAX_NAME_LEN)?.to_vec();+    let description = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+    let tag_count = reader.varint()?;+    let tag_count = usize::try_from(tag_count).map_err(|_| Error::new("too many tags"))?;+    if tag_count > 1024 {+        return Err(Error::new("tag limit exceeded"));+    }+    let mut tags = Vec::with_capacity(tag_count);+    for _ in 0..tag_count {+        let key = reader.bytes(MAX_NAME_LEN)?.to_vec();+        if key.is_empty() {+            return Err(Error::new("empty operation tag key"));+        }+        let value = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();+        tags.push((key, value));+    }+    reader.finish()?;+    Ok(Operation {+        parents,+        view,+        start,+        end,+        hostname,+        username,+        description,+        tags,+    })+}--- /dev/null+++ b/veins/src/platform.rs@@ -0,0 +1,419 @@+//! Small cross-platform shims for the OS primitives the store and worktree rely on.++use std::fs::{self, File, Metadata};+use std::io;+use std::path::{Path, PathBuf};+use std::process::Command;++#[cfg(unix)]+mod imp {+    use super::*;+    use std::ffi::OsString;+    use std::os::unix::ffi::{OsStrExt, OsStringExt};+    use std::os::unix::fs::{MetadataExt, PermissionsExt};+    use std::io::IsTerminal;++    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+        PathBuf::from(OsString::from_vec(bytes.to_vec()))+    }++    pub fn path_to_bytes(path: &Path) -> Vec<u8> {+        path.as_os_str().as_bytes().to_vec()+    }++    pub fn path_display(path: &Path) -> String {+        String::from_utf8_lossy(path.as_os_str().as_bytes()).into_owned()+    }++    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {+        OsString::from_vec(bytes.to_vec())+    }++    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {+        value.into_vec()+    }++    pub fn mtime_ns(metadata: &Metadata) -> u64 {+        (metadata.mtime() as u64)+            .wrapping_mul(1_000_000_000)+            .wrapping_add(metadata.mtime_nsec() as u64)+    }++    pub fn inode(metadata: &Metadata) -> u64 {+        metadata.ino()+    }++    pub fn executable(metadata: &Metadata) -> bool {+        metadata.mode() & 0o111 != 0+    }++    pub fn permissions_mode(metadata: &Metadata) -> u32 {+        metadata.permissions().mode()+    }++    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {+        fs::set_permissions(path, fs::Permissions::from_mode(mode))+    }++    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {+        std::os::unix::fs::symlink(target, link)+    }++    pub fn sync_file(path: &Path) -> io::Result<()> {+        File::open(path)?.sync_all()+    }++    pub fn sync_directory(path: &Path) {+        if let Ok(directory) = File::open(path) {+            let _ = directory.sync_all();+        }+    }++    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {+        use std::os::unix::fs::FileExt;+        file.read_at(buffer, offset)+    }++    pub fn shell(command: &str) -> Command {+        let mut process = Command::new("sh");+        process.arg("-c").arg(command);+        process+    }++    pub fn shell_quote(value: &str) -> String {+        let mut output = String::from("'");+        for character in value.chars() {+            if character == '\'' {+                output.push_str("'\\''");+            } else {+                output.push(character);+            }+        }+        output.push('\'');+        output+    }++    pub fn default_editor() -> &'static str {+        "vi"+    }++    pub fn default_pager() -> &'static str {+        "less -R"+    }++    pub fn stdin_is_terminal() -> bool {+        io::stdin().is_terminal()+    }++    pub fn stdout_is_terminal() -> bool {+        io::stdout().is_terminal()+    }++    pub fn stderr_is_terminal() -> bool {+        io::stderr().is_terminal()+    }+}++#[cfg(windows)]+mod imp {+    use super::*;+    use std::ffi::OsString;++    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn path_to_bytes(path: &Path) -> Vec<u8> {+        path.as_os_str().to_string_lossy().into_owned().into_bytes()+    }++    pub fn path_display(path: &Path) -> String {+        path.to_string_lossy().into_owned()+    }++    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {+        OsString::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {+        value.to_string_lossy().into_owned().into_bytes()+    }++    pub fn mtime_ns(metadata: &Metadata) -> u64 {+        use std::time::UNIX_EPOCH;+        metadata+            .modified()+            .ok()+            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())+            .map(|elapsed| elapsed.as_nanos() as u64)+            .unwrap_or(0)+    }++    pub fn inode(_metadata: &Metadata) -> u64 {+        0+    }++    pub fn executable(_metadata: &Metadata) -> bool {+        false+    }++    pub fn permissions_mode(_metadata: &Metadata) -> u32 {+        0+    }++    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {+        let mut permissions = fs::metadata(path)?.permissions();+        permissions.set_readonly(mode & 0o200 == 0);+        fs::set_permissions(path, permissions)+    }++    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {+        std::os::windows::fs::symlink_file(target, link)+            .or_else(|_| std::os::windows::fs::symlink_dir(target, link))+    }++    pub fn sync_file(path: &Path) -> io::Result<()> {+        File::open(path)?.sync_all()+    }++    pub fn sync_directory(_path: &Path) {}++    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {+        use std::os::windows::fs::FileExt;+        file.seek_read(buffer, offset)+    }++    pub fn shell(command: &str) -> Command {+        let mut process = Command::new("cmd");+        process.arg("/C").arg(command);+        process+    }++    pub fn shell_quote(value: &str) -> String {+        let mut output = String::from("\"");+        for character in value.chars() {+            if character == '"' {+                output.push_str("\\\"");+            } else {+                output.push(character);+            }+        }+        output.push('"');+        output+    }++    pub fn default_editor() -> &'static str {+        "notepad"+    }++    pub fn default_pager() -> &'static str {+        "more"+    }++    pub fn stdin_is_terminal() -> bool {+        use std::io::IsTerminal;+        io::stdin().is_terminal()+    }++    pub fn stdout_is_terminal() -> bool {+        use std::io::IsTerminal;+        io::stdout().is_terminal()+    }++    pub fn stderr_is_terminal() -> bool {+        use std::io::IsTerminal;+        io::stderr().is_terminal()+    }+}++#[cfg(not(any(unix, windows)))]+mod imp {+    use super::*;+    use std::ffi::OsString;++    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {+        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn path_to_bytes(path: &Path) -> Vec<u8> {+        path.to_string_lossy().into_owned().into_bytes()+    }++    pub fn path_display(path: &Path) -> String {+        path.to_string_lossy().into_owned()+    }++    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {+        OsString::from(String::from_utf8_lossy(bytes).into_owned())+    }++    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {+        value.to_string_lossy().into_owned().into_bytes()+    }++    pub fn mtime_ns(_metadata: &Metadata) -> u64 {+        0+    }++    pub fn inode(_metadata: &Metadata) -> u64 {+        0+    }++    pub fn executable(_metadata: &Metadata) -> bool {+        false+    }++    pub fn permissions_mode(_metadata: &Metadata) -> u32 {+        0+    }++    pub fn set_mode(_path: &Path, _mode: u32) -> io::Result<()> {+        Ok(())+    }++    pub fn create_symlink(_target: &Path, _link: &Path) -> io::Result<()> {+        Err(io::Error::new(io::ErrorKind::Unsupported, "symlinks unavailable"))+    }++    pub fn sync_file(path: &Path) -> io::Result<()> {+        File::open(path)?.sync_all()+    }++    pub fn sync_directory(_path: &Path) {}++    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {+        use std::io::{Read, Seek, SeekFrom};+        let mut file = file;+        file.seek(SeekFrom::Start(offset))?;+        file.read(buffer)+    }++    pub fn shell(command: &str) -> Command {+        let mut process = Command::new("sh");+        process.arg("-c").arg(command);+        process+    }++    pub fn shell_quote(value: &str) -> String {+        let mut output = String::from("'");+        for character in value.chars() {+            if character == '\'' {+                output.push_str("'\\''");+            } else {+                output.push(character);+            }+        }+        output.push('\'');+        output+    }++    pub fn default_editor() -> &'static str {+        "vi"+    }++    pub fn default_pager() -> &'static str {+        "less -R"+    }++    pub fn stdin_is_terminal() -> bool {+        false+    }++    pub fn stdout_is_terminal() -> bool {+        false+    }++    pub fn stderr_is_terminal() -> bool {+        false+    }+}++pub use imp::*;++/// Read-only memory mapping of a pack file, used to avoid one syscall per record.+///+/// Only Unix maps; other platforms return `None` and the store falls back to+/// positioned reads, matching the C++ implementation's behaviour.+pub struct Mapping {+    #[cfg(unix)]+    ptr: *mut libc::c_void,+    #[cfg(unix)]+    len: usize,+}++#[cfg(unix)]+unsafe impl Send for Mapping {}+#[cfg(unix)]+unsafe impl Sync for Mapping {}++impl Mapping {+    pub fn open(path: &Path) -> Option<Self> {+        #[cfg(unix)]+        {+            use std::os::unix::io::AsRawFd;+            let file = File::open(path).ok()?;+            let len = file.metadata().ok()?.len();+            if len == 0 || len as u128 > usize::MAX as u128 {+                return None;+            }+            let ptr = unsafe {+                libc::mmap(+                    std::ptr::null_mut(),+                    len as usize,+                    libc::PROT_READ,+                    libc::MAP_PRIVATE,+                    file.as_raw_fd(),+                    0,+                )+            };+            if ptr == libc::MAP_FAILED {+                return None;+            }+            Some(Mapping {+                ptr,+                len: len as usize,+            })+        }+        #[cfg(not(unix))]+        {+            let _ = path;+            None+        }+    }++    pub fn as_slice(&self) -> &[u8] {+        #[cfg(unix)]+        {+            unsafe { std::slice::from_raw_parts(self.ptr as *const u8, self.len) }+        }+        #[cfg(not(unix))]+        {+            &[]+        }+    }+}++#[cfg(unix)]+impl Drop for Mapping {+    fn drop(&mut self) {+        unsafe {+            libc::munmap(self.ptr, self.len);+        }+    }+}++/// Read only the requested window of a file into a fresh buffer.+pub fn read_range(file: &File, offset: u64, length: usize) -> Option<Vec<u8>> {+    let mut data = vec![0u8; length];+    let mut done = 0;+    while done < length {+        match read_at(file, &mut data[done..], offset + done as u64) {+            Ok(0) => break,+            Ok(count) => done += count,+            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,+            Err(_) => return None,+        }+    }+    data.truncate(done);+    Some(data)+}--- /dev/null+++ b/veins/src/protocol/client.rs@@ -0,0 +1,336 @@+use std::path::Path;++use crate::crypto;+use crate::error::{Error, Result};+use crate::object::id::{Id, object_id};+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::time;++use super::messages::{self, RefInfo, UpdateRef};+use super::wire::{self, Stream};++pub struct Client {+    stream: Stream,+    pub role: u8,+    pub authenticated: bool,+    pub fingerprint: Vec<u8>,+    pub error: String,+}++impl Client {+    pub fn connect(url: &str, key_name: &str, repo_name: &str, pin: &str) -> Result<Self> {+        let parsed = messages::parse_url(url).ok_or_else(|| Error::new("invalid remote URL"))?;+        let stream = if parsed.ssh {+            let remote = [+                "vn".to_string(),+                "serve".to_string(),+                "-stdio".to_string(),+                parsed.path.clone(),+            ]+            .iter()+            .map(|part| crate::core::shell_quote_arg(part))+            .collect::<Vec<_>>()+            .join(" ");+            let mut arguments = Vec::new();+            if parsed.port != 22 {+                arguments.push("-p".to_string());+                arguments.push(parsed.port.to_string());+            }+            arguments.push(parsed.host.clone());+            arguments.push(remote);+            Stream::spawn_program("ssh", &arguments)+                .map_err(|_| Error::new("cannot start the SSH transport"))?+        } else if parsed.tls {+            super::tls::connect(&parsed.host, parsed.port, pin)?+        } else {+            Stream::spawn(&[+                "serve".to_string(),+                "-stdio".to_string(),+                parsed.path.clone(),+            ])?+        };+        let binding = stream.binding().to_vec();+        let mut client = Self {+            stream,+            role: 0,+            authenticated: false,+            fingerprint: Vec::new(),+            error: String::new(),+        };+        let nonce = crypto::secure_random(32);+        if nonce.len() != 32 {+            return Err(Error::new("cannot generate a secure nonce"));+        }+        let hello = messages::Hello {+            min_version: messages::PROTOCOL_VERSION,+            max_version: messages::PROTOCOL_VERSION,+            capabilities: vec![+                "zstd-records".to_string(),+                "lazy-chunks".to_string(),+                "push".to_string(),+                "auth-ed25519".to_string(),+            ],+            repo: repo_name.to_string(),+            client_nonce: nonce.clone(),+        };+        if !client+            .stream+            .write_frame(wire::kind::HELLO, 1, &messages::encode_hello(&hello))+        {+            return Err(Error::new(+                "connection closed during the protocol handshake",+            ));+        }+        let frame = client+            .stream+            .read_frame()+            .ok_or_else(|| Error::new("server rejected the protocol handshake"))?;+        if frame.kind != wire::kind::HELLO_OK {+            return Err(Error::new("server rejected the protocol handshake"));+        }+        let hello_ok = messages::decode_hello_ok(&frame.payload)+            .ok_or_else(|| Error::new("server sent an invalid protocol handshake"))?;+        let selected = if key_name.is_empty() && hello_ok.auth_required != 0 {+            "default"+        } else {+            key_name+        };+        if !selected.is_empty()+            && let Some(key) = crypto::load_key(selected)+        {+            let message = messages::auth_message(+                hello_ok.version,+                repo_name,+                &hello_ok.server_nonce,+                &hello.client_nonce,+                &binding,+            );+            if let Some(signature) = crypto::ed25519_sign(&key.seed, &message) {+                let auth = messages::Auth {+                    public_key: key.public_key.to_vec(),+                    signature: signature.to_vec(),+                };+                if client+                    .stream+                    .write_frame(wire::kind::AUTH, 2, &messages::encode_auth(&auth))+                {+                    if let Some(reply) = client.stream.read_frame()+                        && reply.kind == wire::kind::AUTH_OK+                        && let Some(ok) = messages::decode_auth_ok(&reply.payload)+                    {+                        client.role = ok.role;+                        client.authenticated = true;+                        client.fingerprint = ok.fingerprint;+                    }+                }+            }+        }+        if hello_ok.auth_required != 0 && !client.authenticated {+            return Err(Error::new(if selected.is_empty() {+                "authentication required but no key is configured"+            } else {+                "authentication failed: the key is missing or not authorized"+            }));+        }+        Ok(client)+    }++    fn request(&mut self, kind: u8, payload: &[u8]) -> Result<wire::Frame> {+        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;+        if !self.stream.write_frame(kind, request_id, payload) {+            return Err(Error::new("connection closed while sending request"));+        }+        let frame = self+            .stream+            .read_frame()+            .ok_or_else(|| Error::new("connection closed while waiting for server response"))?;+        if frame.kind == wire::kind::ERROR {+            let code = wire::read_error(&frame.payload);+            let message = wire::error_message(&frame.payload);+            let mut text = format!("server error: {}", wire::error_code_name(code));+            if !message.is_empty() {+                text.push_str(": ");+                text.push_str(&message);+            }+            self.error = text.clone();+            return Err(Error::new(text));+        }+        Ok(frame)+    }++    pub fn list_refs(&mut self) -> Result<Vec<RefInfo>> {+        let frame = self.request(wire::kind::LIST_REFS, &[])?;+        if frame.kind != wire::kind::REFS {+            return Err(Error::new("unexpected response to ref listing"));+        }+        messages::decode_refs(&frame.payload).ok_or_else(|| Error::new("invalid ref listing"))+    }++    pub fn negotiate(&mut self, wants: &[Id], haves: &[Id]) -> Result<()> {+        let frame = self.request(+            wire::kind::NEGOTIATE,+            &messages::encode_negotiate(wants, haves),+        )?;+        if frame.kind != wire::kind::NEGOTIATE_OK {+            return Err(Error::new("unexpected response to negotiation"));+        }+        Ok(())+    }++    fn receive_stream(&mut self, repo: &Path) -> Result<()> {+        let mut hasher = blake3::Hasher::new();+        let mut writer = Writer::default();+        loop {+            let frame = self+                .stream+                .read_frame()+                .ok_or_else(|| Error::new("connection closed while receiving data"))?;+            if frame.kind == wire::kind::END {+                let digest = hasher.finalize();+                if frame.payload.as_slice() != digest.as_bytes() {+                    return Err(Error::new("server sent a corrupt transfer checksum"));+                }+                break;+            }+            if frame.kind == wire::kind::ERROR {+                let code = wire::read_error(&frame.payload);+                let message = wire::error_message(&frame.payload);+                return Err(Error::new(format!(+                    "server error: {}: {message}",+                    wire::error_code_name(code)+                )));+            }+            if frame.kind != wire::kind::RECORDS {+                return Err(Error::new("unexpected message while receiving data"));+            }+            hasher.update(&frame.payload);+            let record = wire::parse_record(&frame.payload)+                .ok_or_else(|| Error::new("invalid transfer record"))?;+            if object_id(record.kind, &record.body) != record.id {+                return Err(Error::new("transfer record hash mismatch"));+            }+            writer.add_known(record.kind, record.id, record.body);+        }+        if writer.finish(repo) != 0 {+            return Err(Error::new("cannot write incoming objects to the store"));+        }+        Ok(())+    }++    pub fn fetch_skeleton(&mut self, repo: &Path, wants: &[Id]) -> Result<()> {+        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;+        if !self.stream.write_frame(+            wire::kind::FETCH_SKELETON,+            request_id,+            &messages::encode_ids(wants),+        ) {+            return Err(Error::new("connection closed while requesting objects"));+        }+        self.receive_stream(repo)+    }++    pub fn get_chunks(&mut self, repo: &Path, ids: &[Id]) -> Result<()> {+        if ids.is_empty() {+            return Ok(());+        }+        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;+        if !self.stream.write_frame(+            wire::kind::GET_CHUNKS,+            request_id,+            &messages::encode_ids(ids),+        ) {+            return Err(Error::new("connection closed while requesting chunks"));+        }+        self.receive_stream(repo)+    }++    pub fn have_query(&mut self, ids: &[Id]) -> Result<Vec<u8>> {+        let frame = self.request(wire::kind::HAVE_QUERY, &messages::encode_ids(ids))?;+        if frame.kind != wire::kind::HAVE_BITMAP {+            return Err(Error::new("unexpected response to object query"));+        }+        messages::decode_bitmap(&frame.payload).ok_or_else(|| Error::new("invalid bitmap"))+    }++    pub fn push_objects(+        &mut self,+        repo: &Path,+        ids: &[Id],+        progress: Option<&crate::core::Progress>,+    ) -> Result<()> {+        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;+        if !self+            .stream+            .write_frame(wire::kind::PUT_RECORDS, request_id, &[])+        {+            return Err(Error::new("connection closed while starting push"));+        }+        let mut store = Store::open(repo)?;+        let mut hasher = blake3::Hasher::new();+        for id in ids {+            let location = store+                .find(*id)+                .ok_or_else(|| Error::new(format!("local object is missing: {}", id.to_hex())))?;+            let body = store+                .body(*id, location.kind)?+                .ok_or_else(|| Error::new(format!("cannot read local object: {}", id.to_hex())))?;+            let record = wire::make_record(*id, location.kind, &body);+            hasher.update(&record);+            if !self+                .stream+                .write_frame(wire::kind::RECORDS, request_id, &record)+            {+                return Err(Error::new("connection closed while sending object"));+            }+            if let Some(progress) = progress {+                progress.advance(1);+            }+        }+        let digest = hasher.finalize();+        if !self+            .stream+            .write_frame(wire::kind::END, request_id, digest.as_bytes())+        {+            return Err(Error::new("connection closed while finishing push"));+        }+        let ack = self+            .stream+            .read_frame()+            .ok_or_else(|| Error::new("server closed the connection before acknowledging"))?;+        if ack.kind == wire::kind::END {+            return Ok(());+        }+        Err(Error::new("push was rejected"))+    }++    pub fn update_refs(&mut self, updates: &[UpdateRef]) -> Result<()> {+        let frame = self.request(+            wire::kind::UPDATE_REFS,+            &messages::encode_update_refs(updates),+        )?;+        if frame.kind != wire::kind::UPDATE_REFS_OK {+            return Err(Error::new("unexpected response to ref update"));+        }+        Ok(())+    }++    pub fn whoami(&mut self) -> Result<(u8, Vec<u8>)> {+        let frame = self.request(wire::kind::WHOAMI, &[])?;+        if frame.kind != wire::kind::WHOAMI_OK {+            return Err(Error::new("unexpected response to whoami"));+        }+        let mut reader = crate::encoding::Reader::new(&frame.payload);+        let role = reader.u8()?;+        let fingerprint = reader.bytes(64)?.to_vec();+        Ok((role, fingerprint))+    }++    pub fn has_connection(&self) -> bool {+        true+    }+}++pub fn same_id(left: Id, right: Id) -> bool {+    left == right+}--- /dev/null+++ b/veins/src/protocol/messages.rs@@ -0,0 +1,427 @@+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::id::Id;++pub const PROTOCOL_VERSION: u16 = 1;++pub struct Hello {+    pub min_version: u16,+    pub max_version: u16,+    pub capabilities: Vec<String>,+    pub repo: String,+    pub client_nonce: Vec<u8>,+}++pub struct HelloOk {+    pub version: u16,+    pub capabilities: Vec<String>,+    pub server_nonce: Vec<u8>,+    pub auth_required: u8,+}++pub struct Auth {+    pub public_key: Vec<u8>,+    pub signature: Vec<u8>,+}++pub struct AuthOk {+    pub role: u8,+    pub fingerprint: Vec<u8>,+}++pub struct RefInfo {+    pub name: String,+    pub target: Id,+    pub change_id: String,+    pub kind: u8,+}++pub struct Negotiate {+    pub wants: Vec<Id>,+    pub haves: Vec<Id>,+}++#[derive(Clone)]+pub struct UpdateRef {+    pub name: String,+    pub expected: Option<Id>,+    pub target: Option<Id>,+}++fn put_u16(writer: &mut Writer, value: u16) {+    writer.u8((value >> 8) as u8);+    writer.u8(value as u8);+}++fn read_u16(reader: &mut Reader<'_>) -> Result<u16> {+    let high = reader.u8()?;+    let low = reader.u8()?;+    Ok(u16::from_be_bytes([high, low]))+}++fn encode_string_list(items: &[String]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(128);+    writer.varint(items.len() as u64);+    for item in items {+        writer.bytes(item.as_bytes());+    }+    writer.into_vec()+}++fn decode_string_list(reader: &mut Reader<'_>, maximum: usize) -> Result<Vec<String>> {+    let count = reader.varint()?;+    let count = usize::try_from(count).map_err(|_| Error::new("string list overflow"))?;+    if count > maximum {+        return Err(Error::new("string list limit exceeded"));+    }+    let mut output = Vec::with_capacity(count);+    for _ in 0..count {+        let value = reader.bytes(4096)?;+        output.push(String::from_utf8_lossy(value).into_owned());+    }+    Ok(output)+}++pub fn encode_hello(hello: &Hello) -> Vec<u8> {+    let mut writer = Writer::with_capacity(128);+    put_u16(&mut writer, hello.min_version);+    put_u16(&mut writer, hello.max_version);+    writer.raw(&encode_string_list(&hello.capabilities));+    writer.bytes(hello.repo.as_bytes());+    writer.bytes(&hello.client_nonce);+    writer.into_vec()+}++pub fn decode_hello(data: &[u8]) -> Option<Hello> {+    let mut reader = Reader::new(data);+    let min_version = read_u16(&mut reader).ok()?;+    let max_version = read_u16(&mut reader).ok()?;+    let capabilities = decode_string_list(&mut reader, 64).ok()?;+    let repo = reader.bytes(4096).ok()?;+    let nonce = reader.bytes(64).ok()?;+    reader.finish().ok()?;+    Some(Hello {+        min_version,+        max_version,+        capabilities,+        repo: String::from_utf8_lossy(repo).into_owned(),+        client_nonce: nonce.to_vec(),+    })+}++pub fn encode_hello_ok(hello: &HelloOk) -> Vec<u8> {+    let mut writer = Writer::with_capacity(128);+    put_u16(&mut writer, hello.version);+    writer.raw(&encode_string_list(&hello.capabilities));+    writer.bytes(&hello.server_nonce);+    writer.u8(hello.auth_required);+    writer.into_vec()+}++pub fn decode_hello_ok(data: &[u8]) -> Option<HelloOk> {+    let mut reader = Reader::new(data);+    let version = read_u16(&mut reader).ok()?;+    let capabilities = decode_string_list(&mut reader, 64).ok()?;+    let nonce = reader.bytes(64).ok()?;+    let auth_required = reader.u8().ok()?;+    reader.finish().ok()?;+    Some(HelloOk {+        version,+        capabilities,+        server_nonce: nonce.to_vec(),+        auth_required,+    })+}++pub fn encode_auth(auth: &Auth) -> Vec<u8> {+    let mut writer = Writer::with_capacity(128);+    writer.bytes(&auth.public_key);+    writer.bytes(&auth.signature);+    writer.into_vec()+}++pub fn decode_auth(data: &[u8]) -> Option<Auth> {+    let mut reader = Reader::new(data);+    let public_key = reader.bytes(64).ok()?;+    let signature = reader.bytes(128).ok()?;+    reader.finish().ok()?;+    Some(Auth {+        public_key: public_key.to_vec(),+        signature: signature.to_vec(),+    })+}++pub fn encode_auth_ok(auth: &AuthOk) -> Vec<u8> {+    let mut writer = Writer::with_capacity(64);+    writer.u8(auth.role);+    writer.bytes(&auth.fingerprint);+    writer.into_vec()+}++pub fn decode_auth_ok(data: &[u8]) -> Option<AuthOk> {+    let mut reader = Reader::new(data);+    let role = reader.u8().ok()?;+    let fingerprint = reader.bytes(64).ok()?;+    reader.finish().ok()?;+    Some(AuthOk {+        role,+        fingerprint: fingerprint.to_vec(),+    })+}++pub fn encode_refs(refs: &[RefInfo]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(256);+    writer.varint(refs.len() as u64);+    for reference in refs {+        writer.bytes(reference.name.as_bytes());+        writer.id(reference.target);+        writer.bytes(reference.change_id.as_bytes());+        writer.u8(reference.kind);+    }+    writer.into_vec()+}++pub fn decode_refs(data: &[u8]) -> Option<Vec<RefInfo>> {+    let mut reader = Reader::new(data);+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > 1_000_000 {+        return None;+    }+    let mut output = Vec::with_capacity(count);+    for _ in 0..count {+        let name = reader.bytes(4096).ok()?;+        let target = reader.id().ok()?;+        let change = reader.bytes(64).ok()?;+        let kind = reader.u8().ok()?;+        output.push(RefInfo {+            name: String::from_utf8_lossy(name).into_owned(),+            target,+            change_id: String::from_utf8_lossy(change).into_owned(),+            kind,+        });+    }+    reader.finish().ok()?;+    Some(output)+}++pub fn encode_ids(ids: &[Id]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(ids.len() * 32 + 8);+    writer.varint(ids.len() as u64);+    for id in ids {+        writer.id(*id);+    }+    writer.into_vec()+}++pub fn decode_ids(data: &[u8], maximum: usize) -> Option<Vec<Id>> {+    let mut reader = Reader::new(data);+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > maximum {+        return None;+    }+    let mut output = Vec::with_capacity(count);+    for _ in 0..count {+        output.push(reader.id().ok()?);+    }+    reader.finish().ok()?;+    Some(output)+}++pub fn encode_negotiate(wants: &[Id], haves: &[Id]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(256);+    writer.raw(&encode_ids(wants));+    writer.raw(&encode_ids(haves));+    writer.into_vec()+}++pub fn decode_negotiate(data: &[u8]) -> Option<Negotiate> {+    let mut reader = Reader::new(data);+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > 1_000_000 {+        return None;+    }+    let mut wants = Vec::with_capacity(count);+    for _ in 0..count {+        wants.push(reader.id().ok()?);+    }+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > 1_000_000 {+        return None;+    }+    let mut haves = Vec::with_capacity(count);+    for _ in 0..count {+        haves.push(reader.id().ok()?);+    }+    reader.finish().ok()?;+    Some(Negotiate { wants, haves })+}++pub fn encode_negotiate_ok(known: &[u8], enough: u8) -> Vec<u8> {+    let mut writer = Writer::with_capacity(known.len() + 16);+    writer.u8(enough);+    writer.varint(known.len() as u64);+    writer.raw(known);+    writer.into_vec()+}++pub fn decode_negotiate_ok(data: &[u8]) -> Option<Vec<u8>> {+    let mut reader = Reader::new(data);+    reader.u8().ok()?;+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > 1_000_000 {+        return None;+    }+    let bits = reader.raw(count).ok()?.to_vec();+    reader.finish().ok()?;+    Some(bits)+}++pub fn encode_bitmap(bits: &[u8]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(bits.len() + 8);+    writer.varint(bits.len() as u64);+    writer.raw(bits);+    writer.into_vec()+}++pub fn decode_bitmap(data: &[u8]) -> Option<Vec<u8>> {+    let mut reader = Reader::new(data);+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > 1_000_000 {+        return None;+    }+    let bits = reader.raw(count).ok()?.to_vec();+    reader.finish().ok()?;+    Some(bits)+}++pub fn encode_update_refs(updates: &[UpdateRef]) -> Vec<u8> {+    let mut writer = Writer::with_capacity(256);+    writer.varint(updates.len() as u64);+    for update in updates {+        writer.bytes(update.name.as_bytes());+        writer.opt_id(update.expected);+        writer.opt_id(update.target);+    }+    writer.into_vec()+}++pub fn decode_update_refs(data: &[u8]) -> Option<Vec<UpdateRef>> {+    let mut reader = Reader::new(data);+    let count = reader.varint().ok()?;+    let count = usize::try_from(count).ok()?;+    if count > 1_000_000 {+        return None;+    }+    let mut output = Vec::with_capacity(count);+    for _ in 0..count {+        let name = reader.bytes(4096).ok()?;+        let expected = reader.opt_id().ok()?;+        let target = reader.opt_id().ok()?;+        output.push(UpdateRef {+            name: String::from_utf8_lossy(name).into_owned(),+            expected,+            target,+        });+    }+    reader.finish().ok()?;+    Some(output)+}++pub fn auth_message(+    version: u16,+    repo: &str,+    server_nonce: &[u8],+    client_nonce: &[u8],+    binding: &[u8],+) -> Vec<u8> {+    let mut writer = Writer::with_capacity(128);+    writer.raw(b"veins-auth/1");+    writer.u8(0);+    put_u16(&mut writer, version);+    writer.bytes(repo.as_bytes());+    writer.raw(server_nonce);+    writer.raw(client_nonce);+    writer.raw(binding);+    writer.into_vec()+}++pub fn role_name(role: u8) -> &'static str {+    match role {+        2 => "write",+        1 => "read",+        _ => "anonymous",+    }+}++pub struct Url {+    pub tls: bool,+    pub ssh: bool,+    pub host: String,+    pub port: i32,+    pub path: String,+}++fn parse_authority(authority: &str, default_port: i32, strip_user: bool) -> (String, i32) {+    let authority = if strip_user {+        authority.rsplit('@').next().unwrap_or(authority)+    } else {+        authority+    };+    let mut host = authority.to_string();+    let mut port = default_port;+    if let Some((name, value)) = authority.rsplit_once(':') {+        host = name.to_string();+        if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {+            port = value.parse().unwrap_or(default_port);+        }+    }+    (host, port)+}++pub fn parse_url(url: &str) -> Option<Url> {+    if let Some(path) = url.strip_prefix("file://") {+        return Some(Url {+            tls: false,+            ssh: false,+            host: String::new(),+            port: 0,+            path: path.to_string(),+        });+    }+    if let Some(rest) = url.strip_prefix("ssh://") {+        let slash = rest.find('/')?;+        let (host, port) = parse_authority(&rest[..slash], 22, true);+        return Some(Url {+            tls: false,+            ssh: true,+            host,+            port,+            path: rest[slash + 1..].to_string(),+        });+    }+    if let Some(rest) = url.strip_prefix("veins://") {+        let slash = rest.find('/')?;+        let (host, port) = parse_authority(&rest[..slash], 7419, false);+        return Some(Url {+            tls: true,+            ssh: false,+            host,+            port,+            path: rest[slash + 1..].to_string(),+        });+    }+    None+}++pub fn url_repo_name(url: &str) -> String {+    match parse_url(url) {+        Some(parsed) if parsed.tls => parsed.path,+        _ => String::new(),+    }+}--- /dev/null+++ b/veins/src/protocol/mod.rs@@ -0,0 +1,4 @@+pub mod client;+pub mod messages;+pub mod tls;+pub mod wire;--- /dev/null+++ b/veins/src/protocol/tls.rs@@ -0,0 +1,219 @@+use std::net::TcpStream;+use std::sync::Arc;++use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};+use rustls::pki_types::pem::PemObject;+use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};+use rustls::{+    ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore, ServerConfig,+    ServerConnection, SignatureScheme, StreamOwned,+};++use crate::error::{Error, Result};++use super::wire::Stream;++const EXPORTER_LABEL: &[u8] = b"EXPORTER-veins-auth/1";++#[derive(Debug)]+struct PinnedVerifier {+    algorithms: rustls::crypto::WebPkiSupportedAlgorithms,+}++impl ServerCertVerifier for PinnedVerifier {+    fn verify_server_cert(+        &self,+        _end_entity: &CertificateDer<'_>,+        _intermediates: &[CertificateDer<'_>],+        _server_name: &ServerName<'_>,+        _ocsp_response: &[u8],+        _now: UnixTime,+    ) -> std::result::Result<ServerCertVerified, rustls::Error> {+        Ok(ServerCertVerified::assertion())+    }++    fn verify_tls12_signature(+        &self,+        message: &[u8],+        cert: &CertificateDer<'_>,+        signature: &DigitallySignedStruct,+    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {+        rustls::crypto::verify_tls12_signature(message, cert, signature, &self.algorithms)+    }++    fn verify_tls13_signature(+        &self,+        message: &[u8],+        cert: &CertificateDer<'_>,+        signature: &DigitallySignedStruct,+    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {+        rustls::crypto::verify_tls13_signature(message, cert, signature, &self.algorithms)+    }++    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {+        self.algorithms.supported_schemes()+    }+}++pub fn client_context(pinned: bool) -> Result<Arc<ClientConfig>> {+    let provider = rustls::crypto::ring::default_provider();+    let builder = ClientConfig::builder_with_provider(Arc::new(provider.clone()))+        .with_protocol_versions(&[&rustls::version::TLS13])+        .map_err(|error| Error::new(error.to_string()))?;+    let config = if pinned {+        builder+            .dangerous()+            .with_custom_certificate_verifier(Arc::new(PinnedVerifier {+                algorithms: provider.signature_verification_algorithms,+            }))+            .with_no_client_auth()+    } else {+        let mut roots = RootCertStore::empty();+        let native = rustls_native_certs::load_native_certs();+        roots.add_parsable_certificates(native.certs);+        if roots.is_empty() {+            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());+        }+        if roots.is_empty() {+            return Err(Error::new("no trusted TLS roots are available"));+        }+        builder.with_root_certificates(roots).with_no_client_auth()+    };+    Ok(Arc::new(config))+}++pub fn connect(host: &str, port: i32, pin: &str) -> Result<Stream> {+    let pinned = !pin.is_empty();+    let config = client_context(pinned)?;+    let name =+        ServerName::try_from(host.to_string()).map_err(|_| Error::new("invalid TLS host name"))?;+    let mut socket = TcpStream::connect((host, port as u16))+        .map_err(|_| Error::new("cannot connect: host refused the connection or is unreachable"))?;+    let mut connection = ClientConnection::new(config, name)+        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+    connection+        .complete_io(&mut socket)+        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+    if pinned {+        let Some(certificate) = connection+            .peer_certificates()+            .and_then(|certs| certs.first())+        else {+            return Err(Error::new("TLS certificate pin mismatch"));+        };+        let digest = ring::digest::digest(&ring::digest::SHA256, certificate.as_ref());+        if !hex_equal(&hex_encode(digest.as_ref()), pin) {+            return Err(Error::new("TLS certificate pin mismatch"));+        }+    }+    let binding = exporter(&connection);+    Ok(Stream::from_duplex(+        Box::new(StreamOwned::new(connection, socket)),+        binding,+    ))+}++pub fn server_context(cert_path: &str, key_path: &str) -> Result<Arc<ServerConfig>> {+    let certificates: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert_path)+        .map_err(|_| Error::new("cannot read the TLS certificate"))?+        .collect::<std::result::Result<_, _>>()+        .map_err(|_| Error::new("cannot parse the TLS certificate"))?;+    if certificates.is_empty() {+        return Err(Error::new("cannot parse the TLS certificate"));+    }+    let key = PrivateKeyDer::from_pem_file(key_path)+        .map_err(|_| Error::new("cannot read the TLS private key"))?;+    let provider = rustls::crypto::ring::default_provider();+    let config = ServerConfig::builder_with_provider(Arc::new(provider))+        .with_protocol_versions(&[&rustls::version::TLS13])+        .map_err(|error| Error::new(error.to_string()))?+        .with_no_client_auth()+        .with_single_cert(certificates, key)+        .map_err(|_| Error::new("cannot load the TLS certificate or key"))?;+    Ok(Arc::new(config))+}++pub fn accept(socket: TcpStream, config: Arc<ServerConfig>) -> Result<Stream> {+    let mut connection = ServerConnection::new(config)+        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+    let mut socket = socket;+    connection+        .complete_io(&mut socket)+        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;+    let binding = exporter(&connection);+    Ok(Stream::from_duplex(+        Box::new(StreamOwned::new(connection, socket)),+        binding,+    ))+}++fn exporter(connection: &impl Exportable) -> Vec<u8> {+    let mut output = [0u8; 32];+    if connection+        .export_keying_material(&mut output, EXPORTER_LABEL, None)+        .is_ok()+    {+        output.to_vec()+    } else {+        Vec::new()+    }+}++trait Exportable {+    fn export_keying_material<T: AsMut<[u8]>>(+        &self,+        output: T,+        label: &[u8],+        context: Option<&[u8]>,+    ) -> std::result::Result<T, rustls::Error>;+}++impl Exportable for ClientConnection {+    fn export_keying_material<T: AsMut<[u8]>>(+        &self,+        output: T,+        label: &[u8],+        context: Option<&[u8]>,+    ) -> std::result::Result<T, rustls::Error> {+        ConnectionCommon::export_keying_material(self, output, label, context)+    }+}++impl Exportable for ServerConnection {+    fn export_keying_material<T: AsMut<[u8]>>(+        &self,+        output: T,+        label: &[u8],+        context: Option<&[u8]>,+    ) -> std::result::Result<T, rustls::Error> {+        ConnectionCommon::export_keying_material(self, output, label, context)+    }+}++use rustls::ConnectionCommon;++fn hex_encode(data: &[u8]) -> String {+    const DIGITS: &[u8; 16] = b"0123456789abcdef";+    let mut output = String::with_capacity(data.len() * 2);+    for byte in data {+        output.push(DIGITS[(byte >> 4) as usize] as char);+        output.push(DIGITS[(byte & 0x0f) as usize] as char);+    }+    output+}++fn hex_equal(left: &str, right: &str) -> bool {+    let mut left = left+        .bytes()+        .filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');+    let mut right = right+        .bytes()+        .filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');+    loop {+        match (left.next(), right.next()) {+            (None, None) => return true,+            (Some(a), Some(b)) if a.to_ascii_lowercase() == b.to_ascii_lowercase() => {}+            _ => return false,+        }+    }+}--- /dev/null+++ b/veins/src/protocol/wire.rs@@ -0,0 +1,298 @@+use std::io::{Read, Write};+use std::sync::{Arc, Mutex};++use crate::error::{Error, Result};+use crate::object::MAX_OBJECT_BODY;+use crate::object::id::Id;++pub const MAX_FRAME: usize = 16 * 1024 * 1024;++pub trait Duplex: Read + Write + Send {}+impl<T: Read + Write + Send> Duplex for T {}++struct SharedReader(Arc<Mutex<Box<dyn Duplex>>>);++impl Read for SharedReader {+    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {+        self.0+            .lock()+            .map_err(|_| std::io::Error::other("stream lock poisoned"))?+            .read(buffer)+    }+}++struct SharedWriter(Arc<Mutex<Box<dyn Duplex>>>);++impl Write for SharedWriter {+    fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {+        self.0+            .lock()+            .map_err(|_| std::io::Error::other("stream lock poisoned"))?+            .write(buffer)+    }++    fn flush(&mut self) -> std::io::Result<()> {+        self.0+            .lock()+            .map_err(|_| std::io::Error::other("stream lock poisoned"))?+            .flush()+    }+}++pub mod kind {+    pub const HELLO: u8 = 1;+    pub const HELLO_OK: u8 = 2;+    pub const AUTH: u8 = 3;+    pub const AUTH_OK: u8 = 4;+    pub const WHOAMI: u8 = 5;+    pub const WHOAMI_OK: u8 = 6;+    pub const LIST_REFS: u8 = 7;+    pub const REFS: u8 = 8;+    pub const NEGOTIATE: u8 = 9;+    pub const NEGOTIATE_OK: u8 = 10;+    pub const FETCH_SKELETON: u8 = 11;+    pub const GET_CHUNKS: u8 = 12;+    pub const HAVE_QUERY: u8 = 13;+    pub const HAVE_BITMAP: u8 = 14;+    pub const PUT_RECORDS: u8 = 15;+    pub const UPDATE_REFS: u8 = 16;+    pub const UPDATE_REFS_OK: u8 = 17;+    pub const RECORDS: u8 = 18;+    pub const END: u8 = 19;+    pub const ERROR: u8 = 20;+}++pub mod error_code {+    pub const UNSUPPORTED_VERSION: u8 = 1;+    pub const BAD_FRAME: u8 = 2;+    pub const NOT_FOUND: u8 = 3;+    pub const HASH_MISMATCH: u8 = 4;+    pub const NON_CANONICAL: u8 = 5;+    pub const MISSING_CLOSURE: u8 = 6;+    pub const REF_CONFLICT: u8 = 7;+    pub const REJECTED: u8 = 8;+    pub const INTERNAL: u8 = 9;+    pub const UNAUTHENTICATED: u8 = 10;+    pub const FORBIDDEN: u8 = 11;+    pub const AUTH_FAILED: u8 = 12;+    pub const QUOTA: u8 = 13;+    pub const TOO_LARGE: u8 = 14;+}++pub struct Frame {+    pub kind: u8,+    pub request_id: u32,+    pub payload: Vec<u8>,+}++pub struct Stream {+    reader: Box<dyn Read + Send>,+    writer: Box<dyn Write + Send>,+    child: Option<std::process::Child>,+    binding: Vec<u8>,+}++impl Stream {+    pub fn stdio() -> Self {+        Self {+            reader: Box::new(std::io::stdin()),+            writer: Box::new(std::io::stdout()),+            child: None,+            binding: Vec::new(),+        }+    }++    pub fn spawn(arguments: &[String]) -> Result<Self> {+        let executable = std::env::current_exe().map_err(Error::from)?;+        Self::spawn_program(&executable.to_string_lossy(), arguments)+    }++    pub fn spawn_program(program: &str, arguments: &[String]) -> Result<Self> {+        let mut child = std::process::Command::new(program)+            .args(arguments)+            .stdin(std::process::Stdio::piped())+            .stdout(std::process::Stdio::piped())+            .stderr(std::process::Stdio::inherit())+            .spawn()+            .map_err(Error::from)?;+        let stdin = child+            .stdin+            .take()+            .ok_or_else(|| Error::new("cannot open child stdin"))?;+        let stdout = child+            .stdout+            .take()+            .ok_or_else(|| Error::new("cannot open child stdout"))?;+        Ok(Self {+            reader: Box::new(stdout),+            writer: Box::new(stdin),+            child: Some(child),+            binding: Vec::new(),+        })+    }++    pub fn from_duplex(stream: Box<dyn Duplex>, binding: Vec<u8>) -> Self {+        let shared = Arc::new(Mutex::new(stream));+        Self {+            reader: Box::new(SharedReader(shared.clone())),+            writer: Box::new(SharedWriter(shared)),+            child: None,+            binding,+        }+    }++    pub fn binding(&self) -> &[u8] {+        &self.binding+    }++    fn read_exact(&mut self, buffer: &mut [u8]) -> bool {+        let mut done = 0;+        while done < buffer.len() {+            match self.reader.read(&mut buffer[done..]) {+                Ok(0) => return false,+                Ok(count) => done += count,+                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,+                Err(_) => return false,+            }+        }+        true+    }++    pub fn read_frame(&mut self) -> Option<Frame> {+        let mut head = [0u8; 4];+        if !self.read_exact(&mut head) {+            return None;+        }+        let length = u32::from_be_bytes(head) as usize;+        if !(5..=MAX_FRAME).contains(&length) {+            return None;+        }+        let mut body = vec![0u8; length];+        if !self.read_exact(&mut body) {+            return None;+        }+        Some(Frame {+            kind: body[0],+            request_id: u32::from_be_bytes([body[1], body[2], body[3], body[4]]),+            payload: body[5..].to_vec(),+        })+    }++    pub fn write_frame(&mut self, kind: u8, request_id: u32, payload: &[u8]) -> bool {+        if payload.len() > MAX_FRAME - 5 {+            return false;+        }+        let length = 5 + payload.len();+        let mut head = Vec::with_capacity(9 + payload.len());+        head.extend_from_slice(&(length as u32).to_be_bytes());+        head.push(kind);+        head.extend_from_slice(&request_id.to_be_bytes());+        head.extend_from_slice(payload);+        self.writer.write_all(&head).is_ok() && self.writer.flush().is_ok()+    }++    pub fn write_simple(&mut self, kind: u8, request_id: u32) -> bool {+        self.write_frame(kind, request_id, &[])+    }++    pub fn write_error(&mut self, request_id: u32, code: u8, message: &str) -> bool {+        let mut payload = Vec::with_capacity(message.len() + 8);+        payload.push(code);+        crate::encoding::Writer::varint_into(&mut payload, message.len() as u64);+        payload.extend_from_slice(message.as_bytes());+        self.write_frame(kind::ERROR, request_id, &payload)+    }+}++impl Drop for Stream {+    fn drop(&mut self) {+        if let Some(child) = &mut self.child {+            let _ = child.kill();+            let _ = child.wait();+        }+    }+}++pub fn read_error(payload: &[u8]) -> u8 {+    payload.first().copied().unwrap_or(error_code::INTERNAL)+}++pub fn error_message(payload: &[u8]) -> String {+    if payload.len() < 2 {+        return String::new();+    }+    let mut reader = crate::encoding::Reader::new(&payload[1..]);+    match reader.bytes(4096) {+        Ok(value) => String::from_utf8_lossy(value).into_owned(),+        Err(_) => String::new(),+    }+}++pub fn error_code_name(code: u8) -> &'static str {+    match code {+        error_code::UNSUPPORTED_VERSION => "unsupported protocol version",+        error_code::BAD_FRAME => "bad frame",+        error_code::NOT_FOUND => "object not found",+        error_code::HASH_MISMATCH => "hash mismatch",+        error_code::NON_CANONICAL => "non-canonical object",+        error_code::MISSING_CLOSURE => "missing object closure",+        error_code::REF_CONFLICT => "ref conflict",+        error_code::REJECTED => "request rejected",+        error_code::INTERNAL => "server internal error",+        error_code::UNAUTHENTICATED => "authentication required",+        error_code::FORBIDDEN => "permission denied",+        error_code::AUTH_FAILED => "authentication failed",+        error_code::QUOTA => "storage quota exceeded",+        error_code::TOO_LARGE => "push too large",+        _ => "unknown server error",+    }+}++pub struct IncomingRecord {+    pub id: Id,+    pub kind: u8,+    pub body: Vec<u8>,+}++pub fn parse_record(data: &[u8]) -> Option<IncomingRecord> {+    if data.len() < 35 {+        return None;+    }+    let mut reader = crate::encoding::Reader::new(data);+    let id = reader.id().ok()?;+    let kind = reader.u8().ok()?;+    let compression = reader.u8().ok()?;+    let raw_len = reader.varint().ok()?;+    let stored_len = reader.varint().ok()?;+    if raw_len == 0 || raw_len > MAX_OBJECT_BODY as u64 || stored_len > MAX_FRAME as u64 {+        return None;+    }+    let stored = reader.raw(stored_len as usize).ok()?;+    reader.finish().ok()?;+    if compression == 0 {+        if stored.len() as u64 != raw_len {+            return None;+        }+        return Some(IncomingRecord {+            id,+            kind,+            body: stored.to_vec(),+        });+    }+    let body = zstd::bulk::decompress(stored, raw_len as usize).ok()?;+    if body.len() as u64 != raw_len {+        return None;+    }+    Some(IncomingRecord { id, kind, body })+}++pub fn make_record(id: Id, kind: u8, body: &[u8]) -> Vec<u8> {+    let mut writer = crate::encoding::Writer::with_capacity(body.len() + 64);+    writer.id(id);+    writer.u8(kind);+    writer.u8(0);+    writer.varint(body.len() as u64);+    writer.varint(body.len() as u64);+    writer.raw(body);+    writer.into_vec()+}--- /dev/null+++ b/veins/src/server.rs@@ -0,0 +1,934 @@+use std::path::{Path, PathBuf};+use std::sync::Arc;++use crate::crypto;+use crate::error::Result;+use crate::object::blob::{self, BlobForm};+use crate::object::conflict;+use crate::object::id::{Id, object_id};+use crate::object::tree::{self, KIND_SUBTREE};+use crate::object::view::{Bookmark, TagRef};+use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};+use crate::protocol::messages::{self, RefInfo};+use crate::protocol::wire::{self, Stream};+use crate::store::Txn;+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;++const MAX_CHUNKS: usize = 4096;+const MAX_PUSH_RECORDS: usize = 100_000;+const QUOTA_RESERVE: u64 = 1 << 20;+const DRAIN_BYTES: usize = 64 << 20;++struct Session {+    stream: Stream,+    repo: PathBuf,+    repo_present: bool,+    root: PathBuf,+    quota_bytes: u64,+    store: Store,+    access: crypto::Access,+    hello_repo: String,+    client_nonce: Vec<u8>,+    server_nonce: Vec<u8>,+    binding: Vec<u8>,+    version: u16,+    authed: bool,+    role: u8,+    public_key: Option<crypto::PublicKey>,+    fingerprint: Vec<u8>,+    haves: Vec<Id>,+}++fn deny(session: &mut Session, request_id: u32, write: bool) -> bool {+    let role = session.role;+    if write {+        if role == 2 {+            return false;+        }+        let code = if session.authed {+            wire::error_code::FORBIDDEN+        } else {+            wire::error_code::UNAUTHENTICATED+        };+        session+            .stream+            .write_error(request_id, code, "permission denied");+        return true;+    }+    if role == 1 || role == 2 {+        return false;+    }+    let code = if session.authed {+        wire::error_code::FORBIDDEN+    } else {+        wire::error_code::UNAUTHENTICATED+    };+    session+        .stream+        .write_error(request_id, code, "permission denied");+    true+}++fn change_id(store: &mut Store, id: Id) -> String {+    graph::load_commit(store, id)+        .ok()+        .flatten()+        .map(|commit| String::from_utf8_lossy(&commit.change_id).into_owned())+        .unwrap_or_default()+}++fn send_record(+    stream: &mut Stream,+    request_id: u32,+    hasher: &mut blake3::Hasher,+    id: Id,+    kind: u8,+    body: &[u8],+) -> bool {+    let record = wire::make_record(id, kind, body);+    hasher.update(&record);+    stream.write_frame(wire::kind::RECORDS, request_id, &record)+}++fn send_end(stream: &mut Stream, request_id: u32, hasher: &blake3::Hasher) -> bool {+    let digest = hasher.finalize();+    stream.write_frame(wire::kind::END, request_id, digest.as_bytes())+}++fn send_tree(+    session: &mut Session,+    request_id: u32,+    hasher: &mut blake3::Hasher,+    id: Id,+    seen: &mut std::collections::HashSet<Id>,+) -> Result<()> {+    if !seen.insert(id) {+        return Ok(());+    }+    let Some(body) = session.store.body(id, TYPE_TREE)? else {+        return Err(crate::error::Error::new("missing tree"));+    };+    if !send_record(+        &mut session.stream,+        request_id,+        hasher,+        id,+        TYPE_TREE,+        &body,+    ) {+        return Err(crate::error::Error::new("write failed"));+    }+    let tree = tree::decode(&body)?;+    for entry in tree.entries {+        match entry.kind {+            KIND_SUBTREE => send_tree(session, request_id, hasher, entry.target, seen)?,+            tree::KIND_CONFLICT => send_object(+                session,+                request_id,+                hasher,+                entry.target,+                TYPE_CONFLICT,+                seen,+            )?,+            tree::KIND_SUBMODULE => {}+            _ => send_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen)?,+        }+    }+    Ok(())+}++fn send_object(+    session: &mut Session,+    request_id: u32,+    hasher: &mut blake3::Hasher,+    id: Id,+    kind: u8,+    seen: &mut std::collections::HashSet<Id>,+) -> Result<()> {+    if !seen.insert(id) {+        return Ok(());+    }+    let Some(body) = session.store.body(id, kind)? else {+        return Err(crate::error::Error::new("missing object"));+    };+    if !send_record(&mut session.stream, request_id, hasher, id, kind, &body) {+        return Err(crate::error::Error::new("write failed"));+    }+    if kind == TYPE_BLOB {+        let blob = blob::decode(&body)?;+        match blob.form {+            BlobForm::Leaf => {+                for entry in blob.entries {+                    if seen.insert(entry.id)+                        && let Some(chunk) = session.store.body(entry.id, TYPE_CHUNK)?+                        && !send_record(+                            &mut session.stream,+                            request_id,+                            hasher,+                            entry.id,+                            TYPE_CHUNK,+                            &chunk,+                        )+                    {+                        return Err(crate::error::Error::new("write failed"));+                    }+                }+            }+            BlobForm::Interior => {+                for entry in blob.entries {+                    send_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen)?;+                }+            }+            BlobForm::Inline => {}+        }+    } else if kind == TYPE_CONFLICT {+        let value = conflict::decode(&body)?;+        for item in value.adds.iter().chain(value.removes.iter()) {+            let Some(target) = item.target else {+                continue;+            };+            let child = match item.kind {+                4 => TYPE_TREE,+                6 => TYPE_CONFLICT,+                0 | 5 => continue,+                _ => TYPE_BLOB,+            };+            if child == TYPE_TREE {+                send_tree(session, request_id, hasher, target, seen)?;+            } else {+                send_object(session, request_id, hasher, target, child, seen)?;+            }+        }+    }+    Ok(())+}++fn safe_repo_name(name: &str) -> bool {+    if name.is_empty() || name.len() > 4096 {+        return false;+    }+    if name.starts_with('/') || name.contains('\0') || name.contains('\\') {+        return false;+    }+    name.split('/').all(|part| part != "..")+}++fn dir_usage(path: &Path, depth: usize) -> u64 {+    if depth > 64 {+        return 0;+    }+    let Ok(entries) = std::fs::read_dir(path) else {+        return 0;+    };+    let mut total = 0u64;+    for entry in entries.flatten() {+        let Ok(metadata) = entry.metadata() else {+            continue;+        };+        if metadata.is_file() {+            total = total.saturating_add(metadata.len());+        } else if metadata.is_dir() {+            total = total.saturating_add(dir_usage(&entry.path(), depth + 1));+        }+    }+    total+}++fn handle_hello(session: &mut Session, frame: &wire::Frame) -> bool {+    let Some(hello) = messages::decode_hello(&frame.payload) else {+        session+            .stream+            .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad HELLO");+        return false;+    };+    if hello.min_version > messages::PROTOCOL_VERSION+        || hello.max_version < messages::PROTOCOL_VERSION+    {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::UNSUPPORTED_VERSION,+            "no common version",+        );+        return false;+    }+    session.hello_repo = hello.repo;+    session.client_nonce = hello.client_nonce;+    if !session.repo_present {+        if !safe_repo_name(&session.hello_repo) {+            session.stream.write_error(+                frame.request_id,+                wire::error_code::NOT_FOUND,+                "repository not found",+            );+            return false;+        }+        let candidate = session+            .root+            .join(crate::core::path_from_bytes(session.hello_repo.as_bytes()));+        match crate::store::layout::discover(&candidate) {+            Ok(found) => {+                session.repo = found;+                session.repo_present = true;+            }+            Err(_) => {+                session.stream.write_error(+                    frame.request_id,+                    wire::error_code::NOT_FOUND,+                    "repository not found",+                );+                return false;+            }+        }+    }+    if !session.repo_present || !session.repo.join(".veins").join("format").is_file() {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::NOT_FOUND,+            "repository not found",+        );+        return false;+    }+    session.access = crypto::load_access(&session.repo);+    session.role = crypto::role_for(&session.access, None);+    if !session.access.valid {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::INTERNAL,+            "invalid access file",+        );+        return false;+    }+    session.store = match Store::open(&session.repo) {+        Ok(store) => store,+        Err(_) => {+            session.stream.write_error(+                frame.request_id,+                wire::error_code::INTERNAL,+                "cannot open store",+            );+            return false;+        }+    };+    let nonce = crypto::secure_random(32);+    if nonce.len() != 32 {+        return false;+    }+    session.server_nonce = nonce.clone();+    let hello_ok = messages::HelloOk {+        version: messages::PROTOCOL_VERSION,+        capabilities: vec![+            "zstd-records".to_string(),+            "lazy-chunks".to_string(),+            "push".to_string(),+            "auth-ed25519".to_string(),+        ],+        server_nonce: session.server_nonce.clone(),+        auth_required: u8::from(!session.access.anonymous_read),+    };+    session.stream.write_frame(+        wire::kind::HELLO_OK,+        frame.request_id,+        &messages::encode_hello_ok(&hello_ok),+    )+}++fn handle_auth(session: &mut Session, frame: &wire::Frame) -> bool {+    let Some(auth) = messages::decode_auth(&frame.payload) else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::AUTH_FAILED,+            "authentication failed",+        );+        return true;+    };+    let public_key = if auth.public_key.len() == 32 {+        let mut value = [0u8; 32];+        value.copy_from_slice(&auth.public_key);+        Some(value)+    } else {+        None+    };+    let role = crypto::role_for(&session.access, public_key.as_ref());+    let message = messages::auth_message(+        session.version,+        &session.hello_repo,+        &session.server_nonce,+        &session.client_nonce,+        &session.binding,+    );+    let valid = role != 255+        && public_key.is_some_and(|key| crypto::ed25519_verify(&key, &message, &auth.signature));+    if !valid {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::AUTH_FAILED,+            "authentication failed",+        );+        return true;+    }+    let Some(public_key) = public_key else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::AUTH_FAILED,+            "authentication failed",+        );+        return true;+    };+    session.authed = true;+    session.role = role;+    session.public_key = Some(public_key);+    session.fingerprint = crypto::key_fingerprint_bytes(&public_key).to_vec();+    let ok = messages::AuthOk {+        role,+        fingerprint: session.fingerprint.clone(),+    };+    session.stream.write_frame(+        wire::kind::AUTH_OK,+        frame.request_id,+        &messages::encode_auth_ok(&ok),+    )+}++fn handle_list_refs(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, false) {+        return Ok(true);+    }+    let view = ops::current_view(&session.repo, &mut session.store)?.unwrap_or_default();+    let mut refs = Vec::new();+    for bookmark in &view.bookmarks {+        if bookmark.targets.adds.len() != 1 {+            continue;+        }+        let Some(target) = bookmark.targets.adds[0] else {+            continue;+        };+        refs.push(RefInfo {+            name: String::from_utf8_lossy(&bookmark.name).into_owned(),+            target,+            change_id: change_id(&mut session.store, target),+            kind: 0,+        });+    }+    for tag in &view.tags {+        refs.push(RefInfo {+            name: String::from_utf8_lossy(&tag.name).into_owned(),+            target: tag.target,+            change_id: change_id(&mut session.store, tag.target),+            kind: 1,+        });+    }+    Ok(session.stream.write_frame(+        wire::kind::REFS,+        frame.request_id,+        &messages::encode_refs(&refs),+    ))+}++fn handle_fetch(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, false) {+        return Ok(true);+    }+    let Some(wants) = messages::decode_ids(&frame.payload, 1_000_000) else {+        session+            .stream+            .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad wants");+        return Ok(true);+    };+    let commits = graph::collect_commits(&mut session.store, &wants)?;+    let mut exclude = std::collections::HashSet::new();+    for have in &session.haves {+        for id in graph::collect_commits(&mut session.store, &[*have])? {+            exclude.insert(id);+        }+    }+    let mut hasher = blake3::Hasher::new();+    let mut seen = std::collections::HashSet::new();+    for id in commits {+        if exclude.contains(&id) {+            continue;+        }+        let Some(commit) = graph::load_commit(&mut session.store, id)? else {+            continue;+        };+        let body = crate::object::commit::encode(&commit);+        if !send_record(+            &mut session.stream,+            frame.request_id,+            &mut hasher,+            id,+            TYPE_COMMIT,+            &body,+        ) {+            return Ok(false);+        }+        send_tree(+            session,+            frame.request_id,+            &mut hasher,+            commit.root_tree,+            &mut seen,+        )?;+    }+    send_end(&mut session.stream, frame.request_id, &hasher);+    Ok(true)+}++fn handle_get_chunks(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, false) {+        return Ok(true);+    }+    let Some(ids) = messages::decode_ids(&frame.payload, MAX_CHUNKS) else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::BAD_FRAME,+            "bad chunk list",+        );+        return Ok(true);+    };+    let mut hasher = blake3::Hasher::new();+    for id in ids {+        let Some(body) = session.store.body(id, TYPE_CHUNK)? else {+            session.stream.write_error(+                frame.request_id,+                wire::error_code::NOT_FOUND,+                "chunk not found",+            );+            return Ok(true);+        };+        if !send_record(+            &mut session.stream,+            frame.request_id,+            &mut hasher,+            id,+            TYPE_CHUNK,+            &body,+        ) {+            return Ok(false);+        }+    }+    send_end(&mut session.stream, frame.request_id, &hasher);+    Ok(true)+}++fn handle_negotiate(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, false) {+        return Ok(true);+    }+    let Some(negotiate) = messages::decode_negotiate(&frame.payload) else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::BAD_FRAME,+            "bad NEGOTIATE",+        );+        return Ok(true);+    };+    session.haves = negotiate.haves.clone();+    let mut known = Vec::with_capacity(negotiate.haves.len());+    let mut any = false;+    for id in negotiate.haves {+        let found = session.store.contains(id);+        known.push(u8::from(found));+        any |= found;+    }+    let enough = u8::from(session.haves.is_empty() || any);+    Ok(session.stream.write_frame(+        wire::kind::NEGOTIATE_OK,+        frame.request_id,+        &messages::encode_negotiate_ok(&known, enough),+    ))+}++fn handle_have_query(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, true) {+        return Ok(true);+    }+    let Some(ids) = messages::decode_ids(&frame.payload, 1_000_000) else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::BAD_FRAME,+            "bad HAVE_QUERY",+        );+        return Ok(true);+    };+    let mut bits = Vec::with_capacity(ids.len());+    for id in ids {+        bits.push(u8::from(session.store.contains(id)));+    }+    Ok(session.stream.write_frame(+        wire::kind::HAVE_BITMAP,+        frame.request_id,+        &messages::encode_bitmap(&bits),+    ))+}++fn drain_push(session: &mut Session) -> bool {+    let mut total = 0usize;+    loop {+        let Some(frame) = session.stream.read_frame() else {+            return false;+        };+        if frame.kind == wire::kind::END {+            return true;+        }+        total = total.saturating_add(frame.payload.len());+        if total > DRAIN_BYTES {+            return false;+        }+    }+}++fn handle_put_records(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, true) {+        return Ok(true);+    }+    let mut limit = 0u64;+    if session.quota_bytes > 0 {+        let used = dir_usage(&session.repo, 0);+        if used.saturating_add(QUOTA_RESERVE) >= session.quota_bytes {+            drain_push(session);+            session.stream.write_error(+                frame.request_id,+                wire::error_code::QUOTA,+                "storage quota exceeded",+            );+            return Ok(true);+        }+        limit = session.quota_bytes - used - QUOTA_RESERVE;+    }+    let mut writer = Writer::default();+    writer.set_limit(limit);+    let mut hasher = blake3::Hasher::new();+    let mut records = 0usize;+    loop {+        let Some(incoming) = session.stream.read_frame() else {+            return Ok(false);+        };+        if incoming.kind == wire::kind::END {+            if incoming.payload.as_slice() != hasher.finalize().as_bytes() {+                session.stream.write_error(+                    frame.request_id,+                    wire::error_code::HASH_MISMATCH,+                    "transfer checksum mismatch",+                );+                return Ok(true);+            }+            break;+        }+        if incoming.kind != wire::kind::RECORDS {+            drain_push(session);+            session+                .stream+                .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record");+            return Ok(true);+        }+        records += 1;+        if records > MAX_PUSH_RECORDS {+            drain_push(session);+            session.stream.write_error(+                frame.request_id,+                wire::error_code::TOO_LARGE,+                "too many objects in one push",+            );+            return Ok(true);+        }+        hasher.update(&incoming.payload);+        let Some(record) = wire::parse_record(&incoming.payload) else {+            drain_push(session);+            session+                .stream+                .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record");+            return Ok(true);+        };+        if object_id(record.kind, &record.body) != record.id {+            drain_push(session);+            session.stream.write_error(+                frame.request_id,+                wire::error_code::HASH_MISMATCH,+                "record hash mismatch",+            );+            return Ok(true);+        }+        writer.add_known(record.kind, record.id, record.body);+        if writer.quota_hit() {+            drain_push(session);+            session.stream.write_error(+                frame.request_id,+                wire::error_code::QUOTA,+                "storage quota exceeded",+            );+            return Ok(true);+        }+    }+    let status = writer.finish(&session.repo);+    if status != 0 {+        session.stream.write_error(+            frame.request_id,+            if status == 2 {+                wire::error_code::QUOTA+            } else {+                wire::error_code::INTERNAL+            },+            if status == 2 {+                "storage quota exceeded"+            } else {+                "pack write failed"+            },+        );+        return Ok(true);+    }+    session.store.refresh()?;+    Ok(session+        .stream+        .write_frame(wire::kind::END, frame.request_id, &[]))+}++fn ref_matches(view: &crate::object::view::View, name: &str, expected: Option<Id>) -> bool {+    let current = if let Some(tag) = name.strip_prefix("refs/tags/") {+        ops::find_tag(view, tag.as_bytes()).map(|index| view.tags[index].target)+    } else {+        ops::find_bookmark(view, name.as_bytes())+            .and_then(|index| {+                view.bookmarks[index]+                    .targets+                    .adds+                    .first()+                    .copied()+                    .flatten()+            })+            .or_else(|| ops::find_tag(view, name.as_bytes()).map(|index| view.tags[index].target))+    };+    match expected {+        None => current.is_none(),+        Some(expected) => current == Some(expected),+    }+}++fn apply_ref(view: &mut crate::object::view::View, name: &str, target: Option<Id>) {+    if let Some(tag) = name.strip_prefix("refs/tags/") {+        match (ops::find_tag(view, tag.as_bytes()), target) {+            (Some(index), Some(target)) => view.tags[index].target = target,+            (Some(index), None) => {+                view.tags.remove(index);+            }+            (None, Some(target)) => view.tags.push(TagRef {+                name: tag.as_bytes().to_vec(),+                target,+            }),+            (None, None) => {}+        }+        return;+    }+    if let Some(target) = target {+        if let Some(index) = ops::find_bookmark(view, name.as_bytes()) {+            view.bookmarks[index].targets.adds = vec![Some(target)];+            view.bookmarks[index].targets.removes.clear();+        } else if let Some(index) = ops::find_tag(view, name.as_bytes()) {+            view.tags[index].target = target;+        } else {+            view.bookmarks.push(Bookmark {+                name: name.as_bytes().to_vec(),+                targets: crate::object::view::TargetSet {+                    adds: vec![Some(target)],+                    removes: Vec::new(),+                },+            });+        }+    } else {+        if let Some(index) = ops::find_bookmark(view, name.as_bytes()) {+            view.bookmarks.remove(index);+        }+        if let Some(index) = ops::find_tag(view, name.as_bytes()) {+            view.tags.remove(index);+        }+    }+}++fn valid_ref_name(name: &str) -> bool {+    if name.is_empty()+        || name.len() > crate::object::MAX_NAME_LEN+        || matches!(name, "@" | "." | "..")+    {+        return false;+    }+    if matches!(name.as_bytes()[0], b'-' | b'/')+        || matches!(name.as_bytes()[name.len() - 1], b'/' | b'.')+    {+        return false;+    }+    if name.contains("..") || name.contains("@{") || name.contains("//") || name.ends_with(".lock")+    {+        return false;+    }+    name.bytes().all(|byte| {+        byte >= 32+            && byte != 127+            && byte != b' '+            && !matches!(byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\')+    })+}++fn handle_update_refs(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, true) {+        return Ok(true);+    }+    let Some(updates) = messages::decode_update_refs(&frame.payload) else {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::BAD_FRAME,+            "bad UPDATE_REFS",+        );+        return Ok(true);+    };+    let mut txn = Txn::begin(&session.repo, &mut session.store)?;+    for update in &updates {+        let ref_name = update+            .name+            .strip_prefix("refs/tags/")+            .unwrap_or(&update.name);+        if update.target.is_some() && !valid_ref_name(ref_name) {+            session.stream.write_error(+                frame.request_id,+                wire::error_code::REJECTED,+                "invalid ref name",+            );+            return Ok(true);+        }+        if !ref_matches(txn.view(), &update.name, update.expected) {+            session.stream.write_error(+                frame.request_id,+                wire::error_code::REF_CONFLICT,+                "ref changed",+            );+            return Ok(true);+        }+    }+    for update in &updates {+        apply_ref(txn.view_mut(), &update.name, update.target);+    }+    ops::rebuild_heads(txn.view_mut());+    txn.finish("remote push")?;+    session.store.refresh()?;+    Ok(session+        .stream+        .write_simple(wire::kind::UPDATE_REFS_OK, frame.request_id))+}++fn dispatch(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    match frame.kind {+        wire::kind::HELLO => Ok(handle_hello(session, frame)),+        wire::kind::AUTH => Ok(handle_auth(session, frame)),+        wire::kind::WHOAMI => {+            let mut payload = Vec::new();+            payload.push(session.role);+            crate::encoding::Writer::varint_into(&mut payload, session.fingerprint.len() as u64);+            payload.extend_from_slice(&session.fingerprint);+            Ok(session+                .stream+                .write_frame(wire::kind::WHOAMI_OK, frame.request_id, &payload))+        }+        wire::kind::LIST_REFS => handle_list_refs(session, frame),+        wire::kind::NEGOTIATE => handle_negotiate(session, frame),+        wire::kind::FETCH_SKELETON => handle_fetch(session, frame),+        wire::kind::GET_CHUNKS => handle_get_chunks(session, frame),+        wire::kind::HAVE_QUERY => handle_have_query(session, frame),+        wire::kind::PUT_RECORDS => handle_put_records(session, frame),+        wire::kind::UPDATE_REFS => handle_update_refs(session, frame),+        _ => {+            session.stream.write_error(+                frame.request_id,+                wire::error_code::BAD_FRAME,+                "unknown request",+            );+            Ok(true)+        }+    }+}++fn run_session(+    stream: Stream,+    fixed: Option<PathBuf>,+    root: Option<PathBuf>,+    binding: Vec<u8>,+    quota: u64,+) -> Result<()> {+    let repo_present = fixed.is_some();+    let repo = fixed.clone().unwrap_or_default();+    let base = root.clone().unwrap_or_default();+    let open_path = if repo_present { repo.clone() } else { base };+    let access = if repo_present {+        crypto::load_access(&repo)+    } else {+        crypto::empty_access()+    };+    let mut session = Session {+        stream,+        repo,+        repo_present,+        root: root.unwrap_or_default(),+        quota_bytes: quota,+        store: Store::open(&open_path)?,+        access,+        hello_repo: String::new(),+        client_nonce: Vec::new(),+        server_nonce: Vec::new(),+        binding,+        version: messages::PROTOCOL_VERSION,+        authed: false,+        role: 0,+        public_key: None,+        fingerprint: Vec::new(),+        haves: Vec::new(),+    };+    loop {+        let Some(frame) = session.stream.read_frame() else {+            break;+        };+        match dispatch(&mut session, &frame) {+            Ok(true) => {}+            Ok(false) | Err(_) => break,+        }+    }+    Ok(())+}++pub fn serve_stdio(repo: &Path, quota: u64) -> Result<()> {+    run_session(+        Stream::stdio(),+        Some(repo.to_path_buf()),+        None,+        Vec::new(),+        quota,+    )+}++pub fn serve_listen(+    address: &str,+    root: &Path,+    cert_path: &str,+    key_path: &str,+    quota: u64,+) -> Result<()> {+    let config = super::protocol::tls::server_context(cert_path, key_path)?;+    let listener = std::net::TcpListener::bind(address)+        .map_err(|_| crate::error::Error::new(format!("cannot listen on {address}")))?;+    crate::cli::output::info_prefix();+    println!("listening on {address}");+    for incoming in listener.incoming() {+        let Ok(socket) = incoming else {+            break;+        };+        let config = Arc::clone(&config);+        let root = root.to_path_buf();+        std::thread::spawn(move || {+            let Ok(stream) = super::protocol::tls::accept(socket, config) else {+                return;+            };+            let binding = stream.binding().to_vec();+            let _ = run_session(stream, None, Some(root), binding, quota);+        });+    }+    Ok(())+}--- /dev/null+++ b/veins/src/store/graph.rs@@ -0,0 +1,533 @@+use std::collections::{HashMap, HashSet};++use crate::error::{Error, Result};+use crate::object::blob::{self, BlobForm};+use crate::object::commit::{self, Commit};+use crate::object::id::{Id, is_hex_prefix, prefix_matches};+use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE};+use crate::object::view::View;+use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT};+use crate::store::ops;+use crate::store::reader::Store;++pub fn load_commit(store: &mut Store, id: Id) -> Result<Option<Commit>> {+    let Some(body) = store.body(id, TYPE_COMMIT)? else {+        return Ok(None);+    };+    Ok(Some(commit::decode(&body)?))+}++pub fn has_changes(store: &mut Store, commit: &Commit) -> Result<bool> {+    if let Some(parent) = commit.parents.first() {+        let Some(parent) = load_commit(store, *parent)? else {+            return Ok(true);+        };+        return Ok(parent.root_tree != commit.root_tree);+    }+    Ok(!tree::flatten(store, commit.root_tree)?.is_empty())+}++pub fn collect_commits(store: &mut Store, start: &[Id]) -> Result<Vec<Id>> {+    let mut output = Vec::new();+    let mut stack = Vec::new();+    let mut seen = HashSet::new();+    for id in start {+        if seen.insert(*id) {+            stack.push(*id);+        }+    }+    while let Some(id) = stack.pop() {+        output.push(id);+        if let Some(commit) = load_commit(store, id)? {+            for parent in commit.parents {+                if seen.insert(parent) {+                    stack.push(parent);+                }+            }+        }+    }+    Ok(output)+}++pub struct LogNode {+    pub id: Id,+    pub seconds: i64,+    pub parents: Vec<Id>,+}++pub fn order_log_nodes(nodes: &[LogNode]) -> Vec<usize> {+    use std::cmp::Reverse;+    use std::collections::{BinaryHeap, HashMap};+    let mut index = HashMap::new();+    for (position, node) in nodes.iter().enumerate() {+        index.insert(node.id, position);+    }+    let mut unemitted = vec![0usize; nodes.len()];+    for node in nodes {+        for parent in &node.parents {+            if let Some(found) = index.get(parent) {+                unemitted[*found] += 1;+            }+        }+    }+    let mut ready = BinaryHeap::new();+    for (position, node) in nodes.iter().enumerate() {+        if unemitted[position] == 0 {+            ready.push((node.seconds, Reverse(position)));+        }+    }+    let mut emitted = vec![false; nodes.len()];+    let mut order = Vec::with_capacity(nodes.len());+    while let Some((_, Reverse(position))) = ready.pop() {+        if emitted[position] {+            continue;+        }+        emitted[position] = true;+        order.push(position);+        for parent in &nodes[position].parents {+            let Some(found) = index.get(parent).copied() else {+                continue;+            };+            if unemitted[found] > 0 {+                unemitted[found] -= 1;+            }+            if unemitted[found] == 0 {+                ready.push((nodes[found].seconds, Reverse(found)));+            }+        }+    }+    for position in 0..nodes.len() {+        if !emitted[position] {+            order.push(position);+        }+    }+    order+}++pub fn view_roots(view: &View) -> Vec<Id> {+    let mut roots = Vec::new();+    let mut add = |id: Id| {+        if !roots.contains(&id) {+            roots.push(id);+        }+    };+    for head in &view.heads {+        add(*head);+    }+    for bookmark in &view.bookmarks {+        for id in bookmark.targets.adds.iter().flatten() {+            add(*id);+        }+    }+    for tag in &view.tags {+        add(tag.target);+    }+    for workspace in &view.working_copies {+        add(workspace.target);+    }+    roots+}++pub fn all_commits(store: &mut Store, view: &View) -> Result<Vec<Id>> {+    collect_commits(store, &view_roots(view))+}++pub fn bookmark_target(view: &View, name: &[u8]) -> Option<Id> {+    view.bookmarks.iter().find_map(|bookmark| {+        if bookmark.name == name+            && bookmark.targets.adds.len() == 1+            && bookmark.targets.adds[0].is_some()+        {+            bookmark.targets.adds[0]+        } else {+            None+        }+    })+}++fn is_change_id_prefix(text: &str) -> bool {+    if text.is_empty() || text.len() > 26 {+        return false;+    }+    text.bytes().all(|byte| {+        let lower = byte.to_ascii_lowercase();+        lower.is_ascii_lowercase() || (b'2'..=b'7').contains(&lower)+    })+}++pub fn resolve_revision(store: &mut Store, view: &View, revision: &str) -> Result<Option<Id>> {+    if revision.is_empty() || revision == "@" {+        return Ok(ops::working_copy_id(view));+    }+    if let Some(id) = bookmark_target(view, revision.as_bytes()) {+        return Ok(Some(id));+    }+    if let Some(id) = view+        .tags+        .iter()+        .find(|tag| tag.name == revision.as_bytes())+        .map(|tag| tag.target)+    {+        return Ok(Some(id));+    }+    if let Some(id) = view.remote_refs.iter().find_map(|reference| {+        let mut joined = reference.remote.clone();+        joined.push(b'/');+        joined.extend_from_slice(&reference.name);+        (joined == revision.as_bytes()).then_some(reference.target)+    }) {+        return Ok(Some(id));+    }++    if revision.len() == 64 {+        if let Ok(id) = Id::from_hex(revision)+            && load_commit(store, id)?.is_some()+        {+            return Ok(Some(id));+        }+        return Ok(None);+    }++    let hex_prefix = is_hex_prefix(revision);+    let change_prefix = is_change_id_prefix(revision);+    if !hex_prefix && !change_prefix {+        return Ok(None);+    }++    let ids = all_commits(store, view)?;+    let mut matches = Vec::new();+    if hex_prefix {+        for id in &ids {+            if prefix_matches(&id.to_hex(), revision) {+                matches.push(*id);+            }+        }+    }+    if matches.is_empty() && change_prefix {+        for id in &ids {+            if let Some(commit) = load_commit(store, *id)? {+                let encoded = base32_encode(commit.change_id);+                if prefix_matches(&encoded, revision) {+                    matches.push(*id);+                }+            }+        }+    }+    if matches.len() == 1 {+        Ok(Some(matches[0]))+    } else {+        Ok(None)+    }+}++pub fn base32_encode(value: [u8; 16]) -> String {+    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";+    let mut output = String::with_capacity(26);+    let mut buffer = 0u64;+    let mut bits = 0usize;+    for byte in value {+        buffer = (buffer << 8) | u64::from(byte);+        bits += 8;+        while bits >= 5 {+            let shift = bits - 5;+            let index = ((buffer >> shift) & 31) as usize;+            output.push(ALPHABET[index] as char);+            bits = shift;+        }+        if bits == 0 {+            buffer = 0;+        } else {+            buffer &= (1u64 << bits) - 1;+        }+    }+    if bits > 0 {+        output.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);+    }+    output+}++pub fn short_change_id(ids: &[String], index: usize) -> String {+    let target = &ids[index];+    let mut length = 4.min(target.len());+    while length < target.len() {+        let prefix = &target[..length];+        let unique = ids.iter().enumerate().all(|(other_index, other)| {+            other_index == index || other == target || !other.starts_with(prefix)+        });+        if unique {+            break;+        }+        length += 1;+    }+    target[..length].to_string()+}++fn append_blob(store: &Store, id: Id, output: &mut Vec<u8>, depth: usize) -> Result<bool> {+    if depth > 64 {+        return Err(Error::new("blob nesting too deep"));+    }+    let Some(body) = store.body_loaded(id, TYPE_BLOB)? else {+        return Ok(false);+    };+    let blob = blob::decode(&body)?;+    match blob.form {+        BlobForm::Inline => {+            output.extend_from_slice(&blob.data);+        }+        BlobForm::Leaf => {+            let total: u64 = blob.entries.iter().map(|entry| entry.length).sum();+            if let Ok(total) = usize::try_from(total) {+                if total <= crate::object::MAX_OBJECT_BODY {+                    output.reserve(total);+                }+            }+            for entry in blob.entries {+                let Some(chunk) = store.body_raw_loaded(entry.id, TYPE_CHUNK)? else {+                    return Ok(false);+                };+                output.extend_from_slice(&chunk);+            }+        }+        BlobForm::Interior => {+            for entry in blob.entries {+                if !append_blob(store, entry.id, output, depth + 1)? {+                    return Ok(false);+                }+            }+        }+    }+    Ok(true)+}++pub fn read_blob_loaded(store: &Store, id: Id) -> Result<Option<Vec<u8>>> {+    let mut output = Vec::new();+    if append_blob(store, id, &mut output, 0)? {+        Ok(Some(output))+    } else {+        Ok(None)+    }+}++pub fn read_blob(store: &mut Store, id: Id) -> Result<Option<Vec<u8>>> {+    store.preload()?;+    read_blob_loaded(store, id)+}++#[derive(Default)]+pub struct BlobMeasure {+    pub bytes: u64,+    pub lines: u64,+    pub has_nul: bool,+    line_has_content: bool,+}++fn scan_blob_bytes(data: &[u8], out: &mut BlobMeasure) {+    if out.bytes < 8192 {+        let prefix = data.len().min((8192 - out.bytes) as usize);+        if data[..prefix].contains(&0) {+            out.has_nul = true;+        }+    }+    let mut start = 0;+    while start < data.len() {+        let end = data[start..]+            .iter()+            .position(|byte| *byte == b'\n')+            .map(|offset| start + offset)+            .unwrap_or(data.len());+        if !out.line_has_content+            && data[start..end]+                .iter()+                .any(|byte| !matches!(*byte, b' ' | b'\t' | b'\r'))+        {+            out.line_has_content = true;+        }+        if end >= data.len() {+            break;+        }+        if out.line_has_content {+            out.lines += 1;+        }+        out.line_has_content = false;+        start = end + 1;+    }+    out.bytes += data.len() as u64;+}++fn measure_blob_into(+    store: &Store,+    id: Id,+    output: &mut BlobMeasure,+    depth: usize,+) -> Result<bool> {+    if depth > 64 {+        return Err(Error::new("blob nesting too deep"));+    }+    let Some(body) = store.body_raw_loaded(id, TYPE_BLOB)? else {+        return Ok(false);+    };+    let blob = blob::decode(&body)?;+    match blob.form {+        BlobForm::Inline => scan_blob_bytes(&blob.data, output),+        BlobForm::Leaf => {+            for entry in blob.entries {+                let Some(chunk) = store.body_raw_loaded(entry.id, TYPE_CHUNK)? else {+                    return Ok(false);+                };+                scan_blob_bytes(&chunk, output);+            }+        }+        BlobForm::Interior => {+            for entry in blob.entries {+                if !measure_blob_into(store, entry.id, output, depth + 1)? {+                    return Ok(false);+                }+            }+        }+    }+    Ok(true)+}++pub fn measure_blob_loaded(store: &Store, id: Id, output: &mut BlobMeasure) -> Result<bool> {+    if !measure_blob_into(store, id, output, 0)? {+        return Ok(false);+    }+    if output.line_has_content {+        output.lines += 1;+        output.line_has_content = false;+    }+    Ok(true)+}++#[derive(Clone)]+pub struct TreeChange {+    pub path: Vec<u8>,+    pub old_kind: u8,+    pub new_kind: u8,+    pub old_id: Option<Id>,+    pub new_id: Option<Id>,+}++pub fn compare_trees(+    store: &mut Store,+    old_tree: Option<Id>,+    new_tree: Option<Id>,+) -> Result<Vec<TreeChange>> {+    let old_entries = match old_tree {+        Some(id) => tree::flatten(store, id)?,+        None => Vec::new(),+    };+    let new_entries = match new_tree {+        Some(id) => tree::flatten(store, id)?,+        None => Vec::new(),+    };+    let mut changes = Vec::new();+    let mut old_index = 0;+    let mut new_index = 0;+    while old_index < old_entries.len() || new_index < new_entries.len() {+        let ordering = if old_index >= old_entries.len() {+            std::cmp::Ordering::Greater+        } else if new_index >= new_entries.len() {+            std::cmp::Ordering::Less+        } else {+            old_entries[old_index]+                .path+                .cmp(&new_entries[new_index].path)+        };+        match ordering {+            std::cmp::Ordering::Less => {+                let entry = &old_entries[old_index];+                changes.push(TreeChange {+                    path: entry.path.clone(),+                    old_kind: entry.kind,+                    new_kind: KIND_MISSING,+                    old_id: Some(entry.target),+                    new_id: None,+                });+                old_index += 1;+            }+            std::cmp::Ordering::Greater => {+                let entry = &new_entries[new_index];+                changes.push(TreeChange {+                    path: entry.path.clone(),+                    old_kind: KIND_MISSING,+                    new_kind: entry.kind,+                    old_id: None,+                    new_id: Some(entry.target),+                });+                new_index += 1;+            }+            std::cmp::Ordering::Equal => {+                let old = &old_entries[old_index];+                let new = &new_entries[new_index];+                if old.kind != new.kind || old.target != new.target {+                    changes.push(TreeChange {+                        path: old.path.clone(),+                        old_kind: old.kind,+                        new_kind: new.kind,+                        old_id: Some(old.target),+                        new_id: Some(new.target),+                    });+                }+                old_index += 1;+                new_index += 1;+            }+        }+    }+    Ok(changes)+}++pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {+    tree::flatten(store, tree_id)+}++fn conflicted_into(+    store: &mut Store,+    tree_id: Id,+    depth: usize,+    cache: &mut HashMap<Id, bool>,+) -> Result<bool> {+    if depth > crate::object::MAX_TREE_DEPTH {+        return Ok(true);+    }+    if let Some(known) = cache.get(&tree_id) {+        return Ok(*known);+    }+    let Some(body) = store.body(tree_id, crate::object::TYPE_TREE)? else {+        cache.insert(tree_id, true);+        return Ok(true);+    };+    let mut found = false;+    let scanned = tree::scan(&body, |_name, kind, target| {+        if found {+            return Ok(());+        }+        if kind == KIND_CONFLICT {+            found = true;+            return Ok(());+        }+        if kind == KIND_SUBTREE && conflicted_into(store, target, depth + 1, cache)? {+            found = true;+        }+        Ok(())+    });+    if scanned.is_err() {+        cache.insert(tree_id, true);+        return Ok(true);+    }+    cache.insert(tree_id, found);+    Ok(found)+}++pub fn tree_conflicted_with(+    store: &mut Store,+    tree_id: Id,+    cache: &mut std::collections::HashMap<Id, bool>,+) -> Result<bool> {+    conflicted_into(store, tree_id, 0, cache)+}++pub fn tree_conflicted(store: &mut Store, tree_id: Id) -> Result<bool> {+    let mut cache = std::collections::HashMap::new();+    conflicted_into(store, tree_id, 0, &mut cache)+}--- /dev/null+++ b/veins/src/store/index.rs@@ -0,0 +1,126 @@+use crate::encoding::Reader;+use crate::error::{Error, Result};+use crate::object::id::{Id, hash_bytes};++#[derive(Clone)]+pub struct IndexEntry {+    pub id: Id,+    pub offset: u64,+}++#[derive(Clone)]+pub struct Index {+    pub entries: Vec<IndexEntry>,+    pub pack_trailer: [u8; 32],+}++impl Index {+    pub fn find(&self, id: Id) -> Option<usize> {+        self.entries+            .binary_search_by(|entry| entry.id.0.cmp(&id.0))+            .ok()+    }+}++pub fn decode(data: &[u8], expected_pack_trailer: Option<[u8; 32]>) -> Result<Index> {+    const BASE: usize = 1032 + 64;+    if data.len() < BASE {+        return Err(Error::new("index is truncated"));+    }+    if &data[..4] != b"VIX1" {+        return Err(Error::new("invalid index magic"));+    }+    let mut reader = Reader::new(data);+    reader.raw(4)?;+    let version = reader.u32le()?;+    if version != 1 {+        return Err(Error::new("unsupported index version"));+    }+    let mut fanout = [0u32; 256];+    let mut previous = 0u32;+    for slot in &mut fanout {+        let value = reader.u32le()?;+        if value < previous {+            return Err(Error::new("index fanout is not sorted"));+        }+        previous = value;+        *slot = value;+    }+    let body = data.len() - BASE;+    if !body.is_multiple_of(40) {+        return Err(Error::new("index body has an invalid length"));+    }+    let count = body / 40;+    if count != fanout[255] as usize {+        return Err(Error::new("index fanout does not match entry count"));+    }+    let ids_start = 1032;+    let offsets_start = ids_start + count * 32;+    let trailer_offset = data.len() - 32;+    let mut entries: Vec<IndexEntry> = Vec::with_capacity(count);+    let mut counts = [0u32; 256];+    let mut previous: Option<[u8; 32]> = None;+    for (index, chunk) in data[ids_start..offsets_start].chunks_exact(32).enumerate() {+        let mut id = [0u8; 32];+        id.copy_from_slice(chunk);+        if previous.is_some_and(|value| value >= id) {+            return Err(Error::new("index ids are not sorted"));+        }+        previous = Some(id);+        counts[id[0] as usize] += 1;+        let mut offset_bytes = [0u8; 8];+        let start = offsets_start + index * 8;+        offset_bytes.copy_from_slice(&data[start..start + 8]);+        entries.push(IndexEntry {+            id: Id(id),+            offset: u64::from_le_bytes(offset_bytes),+        });+    }+    let mut pack_trailer = [0u8; 32];+    pack_trailer.copy_from_slice(&data[trailer_offset - 32..trailer_offset]);+    if hash_bytes(&data[..trailer_offset])[..] != data[trailer_offset..] {+        return Err(Error::new("index checksum mismatch"));+    }+    if expected_pack_trailer.is_some_and(|value| value != pack_trailer) {+        return Err(Error::new("index pack trailer mismatch"));+    }+    let mut running = 0u32;+    for index in 0..256 {+        running += counts[index];+        if running != fanout[index] {+            return Err(Error::new("index fanout is inconsistent"));+        }+    }+    Ok(Index {+        entries,+        pack_trailer,+    })+}++pub fn encode(entries: &[IndexEntry], pack_trailer: [u8; 32]) -> Vec<u8> {+    use crate::encoding::Writer;++    let mut counts = [0u32; 256];+    for entry in entries {+        counts[entry.id.0[0] as usize] += 1;+    }+    let mut writer = Writer::with_capacity(entries.len() * 40 + 128);+    writer.raw(b"VIX1");+    writer.u32le(1);+    let mut running = 0u32;+    for count in counts {+        running += count;+        writer.u32le(running);+    }+    for entry in entries {+        writer.id(entry.id);+    }+    for entry in entries {+        writer.u64le(entry.offset);+    }+    writer.raw(&pack_trailer);+    let mut data = writer.into_vec();+    let digest = hash_bytes(&data);+    data.extend_from_slice(&digest);+    data+}--- /dev/null+++ b/veins/src/store/layout.rs@@ -0,0 +1,158 @@+use std::fs::{self, File};+use std::io::Write;+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};+use crate::platform;++pub fn veins_dir(root: &Path) -> PathBuf {+    root.join(".veins")+}++pub fn packs_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("store").join("packs")+}++pub fn tmp_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("store").join("tmp")+}++pub fn op_heads_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("op-heads")+}++pub fn git_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("git")+}++pub fn git_map_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("git-map")+}++pub fn working_copy_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("working-copy")+}++pub fn resolutions_dir(root: &Path) -> PathBuf {+    veins_dir(root).join("resolutions")+}++pub fn config_path(root: &Path) -> PathBuf {+    veins_dir(root).join("config")+}++pub fn format_path(root: &Path) -> PathBuf {+    veins_dir(root).join("format")+}++pub fn discover(start: &Path) -> Result<PathBuf> {+    let mut current = fs::canonicalize(start)?;+    loop {+        if format_path(&current).is_file() {+            return Ok(current);+        }+        match current.parent() {+            Some(parent) => current = parent.to_path_buf(),+            None => return Err(Error::new("not a veins repository")),+        }+    }+}++pub fn init(path: &Path) -> Result<PathBuf> {+    let root = if path.as_os_str().is_empty() {+        PathBuf::from(".")+    } else {+        path.to_path_buf()+    };+    fs::create_dir_all(&root)?;+    let format = format_path(&root);+    let expected = b"veins-store 1";+    if format.exists() {+        let data = fs::read(&format)?;+        if data != expected {+            return Err(Error::new("unsupported repository format"));+        }+    }+    ensure_layout(&root)?;+    if !format.exists() {+        fs::write(&format, expected)?;+    }+    if !config_path(&root).exists() {+        fs::write(config_path(&root), [])?;+    }+    Ok(root)+}++fn ensure_layout(root: &Path) -> Result<()> {+    let directories = [+        veins_dir(root),+        veins_dir(root).join("store"),+        packs_dir(root),+        tmp_dir(root),+        op_heads_dir(root),+        git_map_dir(root),+        git_map_dir(root).join("raw"),+        working_copy_dir(root),+        resolutions_dir(root),+    ];+    for directory in directories {+        fs::create_dir_all(directory)?;+    }+    Ok(())+}++pub fn write_atomic(final_path: &Path, data: &[u8]) -> Result<()> {+    if let Some(parent) = final_path.parent() {+        fs::create_dir_all(parent)?;+    }+    let parent = final_path+        .parent()+        .ok_or_else(|| Error::new("path has no parent"))?;+    let name = final_path+        .file_name()+        .ok_or_else(|| Error::new("path has no file name"))?+        .to_string_lossy();+    let temporary = parent.join(format!(".{name}.tmp"));+    {+        let mut file = File::create(&temporary)?;+        file.write_all(data)?;+    }+    sync_file(&temporary)?;+    fs::rename(&temporary, final_path)?;+    sync_directory(parent);+    Ok(())+}++fn sync_file(path: &Path) -> Result<()> {+    Ok(platform::sync_file(path)?)+}++fn sync_directory(path: &Path) {+    platform::sync_directory(path);+}++pub fn read_directory(path: &Path) -> Result<Vec<Vec<u8>>> {+    let mut names = Vec::new();+    for entry in fs::read_dir(path)? {+        let entry = entry?;+        names.push(platform::os_string_to_bytes(entry.file_name()));+    }+    names.sort();+    Ok(names)+}++pub fn os_string(bytes: &[u8]) -> std::ffi::OsString {+    platform::os_string_from_bytes(bytes)+}++pub fn append_file(path: &Path, data: &[u8]) -> Result<()> {+    if let Some(parent) = path.parent() {+        fs::create_dir_all(parent)?;+    }+    let mut file = fs::OpenOptions::new()+        .create(true)+        .append(true)+        .open(path)?;+    file.write_all(data)?;+    Ok(())+}--- /dev/null+++ b/veins/src/store/mod.rs@@ -0,0 +1,11 @@+pub mod graph;+pub mod index;+pub mod layout;+pub mod ops;+pub mod pack;+pub mod reader;+pub mod transaction;+pub mod writer;++pub use reader::{Location, Store, set_promisor_fetcher};+pub use transaction::Txn;--- /dev/null+++ b/veins/src/store/ops.rs@@ -0,0 +1,228 @@+use std::fs;+use std::path::Path;++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::view::{Bookmark, View, WorkspaceRef};+use crate::store::layout;+use crate::store::reader::Store;++pub fn read_heads(root: &Path) -> Result<Vec<Id>> {+    let directory = layout::op_heads_dir(root);+    let mut heads = Vec::new();+    if let Ok(entries) = fs::read_dir(&directory) {+        for entry in entries.flatten() {+            let name = entry.file_name();+            let text = name.to_string_lossy();+            if text.len() == 64+                && let Ok(id) = Id::from_hex(&text)+            {+                heads.push(id);+            }+        }+    }+    heads.sort_by(|left, right| left.0.cmp(&right.0));+    Ok(heads)+}++pub fn write_head(root: &Path, id: Id) -> Result<()> {+    let path = layout::op_heads_dir(root).join(id.to_hex());+    layout::write_atomic(&path, &[])+}++pub fn delete_head(root: &Path, id: Id) -> Result<()> {+    let path = layout::op_heads_dir(root).join(id.to_hex());+    match fs::remove_file(path) {+        Ok(()) => Ok(()),+        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+        Err(error) => Err(error.into()),+    }+}++pub fn empty_view() -> View {+    View::default()+}++pub fn current_view(root: &Path, store: &mut Store) -> Result<Option<View>> {+    let heads = read_heads(root)?;+    let Some(first) = heads.first() else {+        return Ok(None);+    };+    let mut view =+        load_view_for_head(store, *first)?.ok_or_else(|| Error::new("missing operation state"))?;+    for head in &heads[1..] {+        if let Some(extra) = load_view_for_head(store, *head)? {+            merge_view_into(&mut view, &extra);+        }+    }+    sort_view(&mut view);+    Ok(Some(view))+}++fn load_view_for_head(store: &mut Store, id: Id) -> Result<Option<View>> {+    let Some(operation) = store.operation(id)? else {+        return Ok(None);+    };+    store.view(operation.view)+}++pub fn merge_view_into(target: &mut View, source: &View) {+    for head in &source.heads {+        add_unique_head(target, *head);+    }+    for bookmark in &source.bookmarks {+        match find_bookmark(target, &bookmark.name) {+            None => target.bookmarks.push(bookmark.clone()),+            Some(index) => {+                let existing = &mut target.bookmarks[index];+                let left = existing.targets.adds.first().copied().flatten();+                let right = bookmark.targets.adds.first().copied().flatten();+                if left != right || existing.targets.adds.len() != bookmark.targets.adds.len() {+                    existing.targets.adds = vec![left, right];+                    existing.targets.removes = vec![None];+                }+            }+        }+    }+    for tag in &source.tags {+        if !target.tags.iter().any(|value| value.name == tag.name) {+            target.tags.push(tag.clone());+        }+    }+    for workspace in &source.working_copies {+        if !target+            .working_copies+            .iter()+            .any(|value| value.workspace == workspace.workspace)+        {+            target.working_copies.push(workspace.clone());+        }+    }+}++pub fn working_copy_id(view: &View) -> Option<Id> {+    view.working_copies+        .iter()+        .find(|workspace| workspace.workspace == b"default")+        .map(|workspace| workspace.target)+}++pub fn sort_ids(ids: &mut [Id]) {+    ids.sort_by(|left, right| left.0.cmp(&right.0));+}++pub fn sort_view(view: &mut View) {+    view.heads.sort_by(|left, right| left.0.cmp(&right.0));+    view.bookmarks+        .sort_by(|left, right| left.name.cmp(&right.name));+    view.tags.sort_by(|left, right| left.name.cmp(&right.name));+    view.remote_refs.sort_by(|left, right| {+        left.remote+            .cmp(&right.remote)+            .then_with(|| left.name.cmp(&right.name))+    });+    view.working_copies+        .sort_by(|left, right| left.workspace.cmp(&right.workspace));+}++pub fn add_unique_head(view: &mut View, id: Id) {+    if !view.heads.contains(&id) {+        view.heads.push(id);+    }+}++pub fn rebuild_heads(view: &mut View) {+    view.heads.clear();+    let mut ids = Vec::new();+    for bookmark in &view.bookmarks {+        for id in bookmark.targets.adds.iter().flatten() {+            ids.push(*id);+        }+    }+    for tag in &view.tags {+        ids.push(tag.target);+    }+    for workspace in &view.working_copies {+        ids.push(workspace.target);+    }+    for id in ids {+        add_unique_head(view, id);+    }+    sort_ids(&mut view.heads);+}++pub fn set_workspace(view: &mut View, id: Id) {+    for workspace in &mut view.working_copies {+        if workspace.workspace == b"default" {+            workspace.target = id;+            return;+        }+    }+    view.working_copies.push(WorkspaceRef {+        workspace: b"default".to_vec(),+        target: id,+    });+    view.working_copies+        .sort_by(|left, right| left.workspace.cmp(&right.workspace));+}++pub fn remove_head(view: &mut View, id: Id) {+    view.heads.retain(|head| *head != id);+}++pub fn move_bookmarks(view: &mut View, old_id: Id, new_id: Id) {+    if old_id == new_id {+        return;+    }+    for bookmark in &mut view.bookmarks {+        if bookmark.targets.adds.contains(&Some(old_id)) {+            bookmark.targets.adds = vec![Some(new_id)];+            bookmark.targets.removes.clear();+        }+    }+}++pub fn set_bookmark_target(view: &mut View, name: &[u8], target: Id) {+    if let Some(index) = find_bookmark(view, name) {+        view.bookmarks[index].targets.adds = vec![Some(target)];+        view.bookmarks[index].targets.removes.clear();+        return;+    }+    view.bookmarks.push(Bookmark {+        name: name.to_vec(),+        targets: crate::object::view::TargetSet {+            adds: vec![Some(target)],+            removes: Vec::new(),+        },+    });+}++pub fn find_bookmark(view: &View, name: &[u8]) -> Option<usize> {+    view.bookmarks+        .iter()+        .position(|bookmark| bookmark.name == name)+}++pub fn find_tag(view: &View, name: &[u8]) -> Option<usize> {+    view.tags.iter().position(|tag| tag.name == name)+}++pub fn bookmark_points_at(bookmark: &Bookmark, target: Id) -> bool {+    bookmark.targets.adds.len() == 1 && bookmark.targets.adds[0] == Some(target)+}++pub fn tag_names(view: &View, id: Id) -> Vec<Vec<u8>> {+    view.tags+        .iter()+        .filter(|tag| tag.target == id)+        .map(|tag| tag.name.clone())+        .collect()+}++pub fn bookmark_names(view: &View, id: Id) -> Vec<Vec<u8>> {+    view.bookmarks+        .iter()+        .filter(|bookmark| bookmark.targets.adds.contains(&Some(id)))+        .map(|bookmark| bookmark.name.clone())+        .collect()+}--- /dev/null+++ b/veins/src/store/pack.rs@@ -0,0 +1,858 @@+use std::collections::{HashMap, HashSet};+use std::hash::{BuildHasherDefault, Hasher};+use std::io::{Read, Seek, SeekFrom};+use std::path::Path;++use rayon::prelude::*;++use crate::core;+use crate::encoding::{Reader, Writer};+use crate::error::{Error, Result};+use crate::object::blob::{self, BlobEntry, BlobForm};+use crate::object::id::{Id, hash_bytes};+use crate::object::{+    MAX_CHUNK_LEN, MAX_OBJECT_BODY, MAX_STORE_PACK_BYTES, RawObject, TYPE_BLOB, TYPE_CHUNK,+    type_valid,+};+use crate::store::index::{self, IndexEntry};++/// FNV-1a over the raw bytes of an object id. `Id`'s derived `Hash` writes 32+/// individual bytes through SipHash, which dominates map-heavy pack encoding.+pub struct IdHasher(u64);++impl Default for IdHasher {+    fn default() -> Self {+        Self(0xcbf2_9ce4_8422_2325)+    }+}++impl Hasher for IdHasher {+    fn finish(&self) -> u64 {+        self.0+    }++    fn write(&mut self, bytes: &[u8]) {+        for byte in bytes {+            self.0 ^= u64::from(*byte);+            self.0 = self.0.wrapping_mul(0x100_0000_01b3);+        }+    }+}++pub type IdBuildHasher = BuildHasherDefault<IdHasher>;+pub type IdMap<V> = HashMap<Id, V, IdBuildHasher>;+pub type IdSet = HashSet<Id, IdBuildHasher>;++#[derive(Clone)]+pub struct PackRecord {+    pub id: Id,+    pub kind: u8,+    pub compression: u8,+    pub raw_len: u64,+    pub stored_len: u64,+    pub data_offset: usize,+    pub record_offset: usize,+}++pub struct Pack {+    pub data: Vec<u8>,+    pub records: Vec<PackRecord>,+    pub trailer: [u8; 32],+}++pub fn record_limit(kind: u8) -> usize {+    if kind == TYPE_CHUNK {+        MAX_CHUNK_LEN+    } else {+        MAX_OBJECT_BODY+    }+}++thread_local! {+    static DECOMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Decompressor<'static>>> =+        const { std::cell::RefCell::new(None) };+    static DICT_DECOMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Decompressor<'static>>> =+        const { std::cell::RefCell::new(None) };+}++pub(crate) fn decompress(data: &[u8], raw_len: usize) -> Result<Vec<u8>> {+    DECOMPRESSOR.with(|slot| {+        let mut slot = slot.borrow_mut();+        if slot.is_none() {+            *slot = zstd::bulk::Decompressor::new().ok();+        }+        let decoder = slot+            .as_mut()+            .ok_or_else(|| Error::new("cannot create zstd decoder"))?;+        decoder+            .decompress(data, raw_len)+            .map_err(|error| Error::new(error.to_string()))+    })+}++pub(crate) fn decompress_dict(data: &[u8], raw_len: usize, dictionary: &[u8]) -> Result<Vec<u8>> {+    DICT_DECOMPRESSOR.with(|slot| {+        let mut slot = slot.borrow_mut();+        if slot.is_none() {+            *slot = zstd::bulk::Decompressor::new().ok();+        }+        let decoder = slot+            .as_mut()+            .ok_or_else(|| Error::new("cannot create zstd decoder"))?;+        decoder+            .set_dictionary(dictionary)+            .map_err(|error| Error::new(error.to_string()))?;+        decoder+            .decompress(data, raw_len)+            .map_err(|error| Error::new(error.to_string()))+    })+}++fn get_body(pack: &Pack, index: usize, depth: usize) -> Result<Vec<u8>> {+    if depth > 32 {+        return Err(Error::new("pack delta chain is too deep"));+    }+    let record = pack+        .records+        .get(index)+        .ok_or_else(|| Error::new("pack record out of range"))?;+    if record.raw_len == 0 {+        return Ok(Vec::new());+    }+    let raw_len = usize::try_from(record.raw_len).map_err(|_| Error::new("raw length overflow"))?;+    let stored_len =+        usize::try_from(record.stored_len).map_err(|_| Error::new("stored length overflow"))?;+    let end = record+        .data_offset+        .checked_add(stored_len)+        .ok_or_else(|| Error::new("pack offset overflow"))?;+    if end > pack.data.len() {+        return Err(Error::new("pack record exceeds file"));+    }+    let stored = &pack.data[record.data_offset..end];+    match record.compression {+        0 => Ok(stored.to_vec()),+        1 => decompress(stored, raw_len),+        2 => {+            let mut reader = Reader::new(stored);+            let base_offset = reader.varint()?;+            if base_offset >= record.record_offset as u64 {+                return Err(Error::new("invalid pack delta base"));+            }+            let frame = reader.raw(reader.remaining())?;+            if frame.is_empty() {+                return Err(Error::new("pack delta frame is empty"));+            }+            let base_index = pack+                .find_by_offset(base_offset)+                .ok_or_else(|| Error::new("missing pack delta base"))?;+            let base = get_body(pack, base_index, depth + 1)?;+            decompress_dict(frame, raw_len, &base)+        }+        _ => Err(Error::new("invalid pack compression")),+    }+}++impl Pack {+    pub fn find_by_offset(&self, offset: u64) -> Option<usize> {+        let value = usize::try_from(offset).ok()?;+        self.records+            .binary_search_by(|record| record.record_offset.cmp(&value))+            .ok()+    }++    pub fn get(&self, index: usize) -> Result<Vec<u8>> {+        get_body(self, index, 0)+    }+}++pub fn decode(data: Vec<u8>) -> Result<Pack> {+    const HEADER: usize = 16;+    const RECORD_MINIMUM: usize = 36;+    if data.len() < HEADER + 32 {+        return Err(Error::new("pack is truncated"));+    }+    if &data[..4] != b"VPK1" {+        return Err(Error::new("invalid pack magic"));+    }+    let mut header = Reader::new(&data[..HEADER]);+    header.raw(4)?;+    let version = header.u32le()?;+    if version != 1 {+        return Err(Error::new("unsupported pack version"));+    }+    let count = header.u64le()?;+    let body_end = data.len() - 32;+    if hash_bytes(&data[..body_end])[..] != data[body_end..] {+        return Err(Error::new("pack checksum mismatch"));+    }+    if count > (body_end / RECORD_MINIMUM) as u64 {+        return Err(Error::new("pack record count is impossible"));+    }+    let count = usize::try_from(count).map_err(|_| Error::new("pack record count overflow"))?;+    let mut records = Vec::with_capacity(count);+    {+        let mut reader = Reader::new(&data[..body_end]);+        reader.raw(HEADER)?;+        for _ in 0..count {+            let record_offset = reader.offset();+            let id = reader.id()?;+            let kind = reader.u8()?;+            if !type_valid(kind) {+                return Err(Error::new("invalid pack object type"));+            }+            let compression = reader.u8()?;+            if compression > 2 {+                return Err(Error::new("invalid pack compression"));+            }+            let raw_len = reader.varint()?;+            let stored_len = reader.varint()?;+            if raw_len == 0 || raw_len > record_limit(kind) as u64 {+                return Err(Error::new("invalid pack record length"));+            }+            if compression == 0 && raw_len != stored_len {+                return Err(Error::new("uncompressed pack record length mismatch"));+            }+            if stored_len > reader.remaining() as u64 {+                return Err(Error::new("pack record exceeds body"));+            }+            let data_offset = reader.offset();+            if compression == 2 {+                let stored = reader.raw(stored_len as usize)?;+                let mut delta = Reader::new(stored);+                let base_offset = delta.varint()?;+                if base_offset >= record_offset as u64 || delta.remaining() == 0 {+                    return Err(Error::new("invalid pack delta record"));+                }+            } else {+                reader.raw(stored_len as usize)?;+            }+            records.push(PackRecord {+                id,+                kind,+                compression,+                raw_len,+                stored_len,+                data_offset,+                record_offset,+            });+        }+        if reader.offset() != body_end {+            return Err(Error::new("pack has trailing bytes"));+        }+    }+    let mut trailer = [0u8; 32];+    trailer.copy_from_slice(&data[body_end..]);+    Ok(Pack {+        data,+        records,+        trailer,+    })+}++pub struct PackOutput {+    pub pack: Vec<u8>,+    pub index: Vec<u8>,+    pub name: String,+    pub count: usize,+}++thread_local! {+    static COMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Compressor<'static>>> =+        const { std::cell::RefCell::new(None) };+    static DICT_COMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Compressor<'static>>> =+        const { std::cell::RefCell::new(None) };+}++fn compress(data: &[u8], level: i32) -> Option<Vec<u8>> {+    if data.is_empty() {+        return None;+    }+    COMPRESSOR.with(|slot| {+        let mut slot = slot.borrow_mut();+        if slot.is_none() {+            *slot = zstd::bulk::Compressor::new(level).ok();+        }+        let encoder = slot.as_mut()?;+        encoder.set_compression_level(level).ok()?;+        let mut compressed = encoder.compress(data).ok()?;+        compressed.shrink_to_fit();+        (compressed.len() < data.len()).then_some(compressed)+    })+}++// Candidate selection only needs relative sizes, so probe a prefix at a cheap+// level and re-compress the winner at the requested level. Frames written to+// the pack are always produced at `level`.+fn probe_level(level: i32) -> i32 {+    if level > 1 { 1 } else { level }+}++fn probe_delta_size(target: &[u8], base: &[u8], level: i32) -> Option<usize> {+    let frame = compress_dict(target, base, probe_level(level))?;+    Some(frame.len() + 10)+}++fn compress_dict(data: &[u8], dictionary: &[u8], level: i32) -> Option<Vec<u8>> {+    if data.is_empty() || dictionary.is_empty() {+        return None;+    }+    DICT_COMPRESSOR.with(|slot| {+        let mut slot = slot.borrow_mut();+        if slot.is_none() {+            *slot = zstd::bulk::Compressor::new(level).ok();+        }+        let encoder = slot.as_mut()?;+        encoder.set_dictionary(level, dictionary).ok()?;+        let mut compressed = encoder.compress(data).ok()?;+        compressed.shrink_to_fit();+        (compressed.len() < data.len()).then_some(compressed)+    })+}++struct BlobRoot {+    entries: Vec<BlobEntry>,+    offsets: Vec<u64>,+    length: u64,+}++fn select_pack_deltas(+    ids: &[Id],+    kinds: &[u8],+    bodies: &[&[u8]],+    compression: &mut [u8],+    compressed: &mut [Vec<u8>],+    base: &mut [Option<usize>],+    level: i32,+) {+    let mut blob_index: IdMap<usize> = IdMap::default();+    let mut chunk_index: IdMap<usize> = IdMap::default();+    for index in 0..ids.len() {+        if kinds[index] == TYPE_BLOB {+            blob_index.insert(ids[index], index);+        } else if kinds[index] == TYPE_CHUNK {+            chunk_index.insert(ids[index], index);+        }+    }+    if blob_index.is_empty() || chunk_index.is_empty() {+        return;+    }++    let mut children: IdSet = IdSet::default();+    for index in 0..ids.len() {+        if kinds[index] != TYPE_BLOB {+            continue;+        }+        if let Ok(decoded) = blob::decode(&bodies[index])+            && decoded.form == BlobForm::Interior+        {+            for entry in decoded.entries {+                children.insert(entry.id);+            }+        }+    }++    let mut roots = Vec::new();+    for index in 0..ids.len() {+        if kinds[index] != TYPE_BLOB {+            continue;+        }+        let Ok(decoded) = blob::decode(&bodies[index]) else {+            continue;+        };+        if decoded.form == BlobForm::Inline || children.contains(&ids[index]) {+            continue;+        }+        let mut entries = Vec::new();+        let mut valid = true;+        if decoded.form == BlobForm::Leaf {+            entries.extend(decoded.entries);+        } else {+            fn flatten(+                id: Id,+                depth: usize,+                blob_index: &IdMap<usize>,+                bodies: &[&[u8]],+                output: &mut Vec<BlobEntry>,+            ) -> bool {+                if depth > 64 {+                    return false;+                }+                let Some(index) = blob_index.get(&id).copied() else {+                    return false;+                };+                let Ok(decoded) = blob::decode(&bodies[index]) else {+                    return false;+                };+                match decoded.form {+                    BlobForm::Leaf => {+                        output.extend(decoded.entries);+                        true+                    }+                    BlobForm::Interior => decoded+                        .entries+                        .into_iter()+                        .all(|entry| flatten(entry.id, depth + 1, blob_index, bodies, output)),+                    BlobForm::Inline => false,+                }+            }+            valid = flatten(ids[index], 0, &blob_index, bodies, &mut entries);+        }+        if !valid || entries.is_empty() {+            continue;+        }+        let mut offsets = Vec::with_capacity(entries.len());+        let mut offset = 0u64;+        for entry in &entries {+            offsets.push(offset);+            offset = offset.saturating_add(entry.length);+        }+        roots.push(BlobRoot {+            entries,+            offsets,+            length: offset,+        });+    }+    if roots.len() < 2 {+        return;+    }++    let mut parent = vec![usize::MAX; roots.len()];+    {+        let mut last_root: IdMap<usize> = IdMap::default();+        let mut last_bucket: HashMap<u64, Vec<usize>> = HashMap::new();++        let score = |target: usize, base_root: usize| -> Option<(usize, usize)> {+            let target_root = &roots[target];+            let base = &roots[base_root];+            let count = target_root.entries.len();+            let mut sampled = 0usize;+            let mut delta_sum = 0usize;+            let mut solo_sum = 0usize;+            for sample in 0..3 {+                let selected = (count * (2 * sample + 1)) / 6;+                if selected >= count || count == 0 {+                    continue;+                }+                let Some(chunk) = chunk_index.get(&target_root.entries[selected].id).copied()+                else {+                    continue;+                };+                let solo = if compression[chunk] == 1 {+                    compressed[chunk].len()+                } else {+                    bodies[chunk].len()+                };+                if solo == 0 {+                    continue;+                }+                sampled += 1;+                solo_sum += solo;+                let mut best = solo;+                let position = target_root.offsets[selected];+                let near = base.offsets.partition_point(|value| *value < position);+                for delta in -1i64..=1 {+                    let candidate = near as i64 + delta;+                    if candidate < 0 || candidate as usize >= base.entries.len() {+                        continue;+                    }+                    let candidate = candidate as usize;+                    let Some(base_index) = chunk_index.get(&base.entries[candidate].id).copied()+                    else {+                        continue;+                    };+                    if base_index >= chunk {+                        continue;+                    }+                    if let Some(frame) =+                        compress_dict(bodies[chunk], bodies[base_index], probe_level(level))+                    {+                        best = best.min(frame.len() + 10);+                    }+                }+                delta_sum += best;+            }+            if sampled == 0 {+                None+            } else {+                Some((delta_sum, solo_sum))+            }+        };++        const MAX_CANDIDATES: usize = 16;+        for root_index in 0..roots.len() {+            let mut candidates: Vec<usize> = Vec::new();+            let mut votes: HashMap<usize, usize> = HashMap::new();+            for entry in &roots[root_index].entries {+                let Some(candidate) = last_root.get(&entry.id).copied() else {+                    continue;+                };+                if roots[candidate].length == 0 || roots[root_index].length == 0 {+                    continue;+                }+                let ratio = roots[candidate].length as f64 / roots[root_index].length as f64;+                if ratio < 0.4 || ratio > 2.5 {+                    continue;+                }+                *votes.entry(candidate).or_insert(0) += 1;+            }+            let mut voted = usize::MAX;+            let mut voted_count = 0;+            for (candidate, count) in votes {+                if count > voted_count || (count == voted_count && candidate < voted) {+                    voted_count = count;+                    voted = candidate;+                }+            }+            if voted != usize::MAX {+                candidates.push(voted);+            }++            let low = (roots[root_index].length * 9) / 10;+            let high = (roots[root_index].length * 11) / 10;+            let mut nearby: HashMap<usize, u64> = HashMap::new();+            let mut bucket = low >> 13;+            while bucket <= (high >> 13) {+                if let Some(items) = last_bucket.get(&bucket) {+                    for candidate in items {+                        let other = &roots[*candidate];+                        if other.length == 0 || roots[root_index].length == 0 {+                            continue;+                        }+                        let ratio = other.length as f64 / roots[root_index].length as f64;+                        if ratio < 0.9 || ratio > 1.1 {+                            continue;+                        }+                        let difference = other.length.abs_diff(roots[root_index].length);+                        nearby+                            .entry(*candidate)+                            .and_modify(|value| *value = (*value).min(difference))+                            .or_insert(difference);+                    }+                }+                bucket += 1;+            }+            let mut ranked: Vec<(u64, usize)> = nearby+                .into_iter()+                .map(|(candidate, difference)| (difference, candidate))+                .collect();+            ranked.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| right.1.cmp(&left.1)));+            for (_, candidate) in ranked {+                candidates.push(candidate);+            }+            let mut unique = Vec::new();+            for candidate in candidates {+                if !unique.contains(&candidate) {+                    unique.push(candidate);+                }+            }+            if unique.len() > MAX_CANDIDATES {+                unique.truncate(MAX_CANDIDATES);+            }++            let mut best = usize::MAX;+            let mut best_sum = usize::MAX;+            let mut best_solo = 0usize;+            for candidate in unique {+                if candidate == root_index {+                    continue;+                }+                let Some((sum, solo)) = score(root_index, candidate) else {+                    continue;+                };+                if solo == 0 || sum >= solo {+                    continue;+                }+                if sum < best_sum {+                    best_sum = sum;+                    best_solo = solo;+                    best = candidate;+                }+            }+            if best != usize::MAX && best_solo > 0 {+                parent[root_index] = best;+            }++            for entry in &roots[root_index].entries {+                last_root.insert(entry.id, root_index);+            }+            let bucket = roots[root_index].length >> 13;+            let items = last_bucket.entry(bucket).or_default();+            items.push(root_index);+            if items.len() > 4 {+                items.remove(0);+            }+        }+    }++    for root_index in 0..roots.len() {+        if parent[root_index] == usize::MAX {+            continue;+        }+        let base_root = &roots[parent[root_index]];+        for position in 0..roots[root_index].entries.len() {+            let Some(target_index) = chunk_index+                .get(&roots[root_index].entries[position].id)+                .copied()+            else {+                continue;+            };+            if base[target_index].is_some() || kinds[target_index] != TYPE_CHUNK {+                continue;+            }+            let solo = if compression[target_index] == 1 {+                compressed[target_index].len()+            } else {+                bodies[target_index].len()+            };+            if solo == 0 {+                continue;+            }+            let target_offset = roots[root_index].offsets[position];+            let nearest = base_root+                .offsets+                .partition_point(|value| *value < target_offset);+            let mut best_size = solo;+            let mut best_base = usize::MAX;+            for delta in [0i64, -1, 1] {+                let candidate = nearest as i64 + delta;+                if candidate < 0 || candidate as usize >= base_root.entries.len() {+                    continue;+                }+                let candidate = candidate as usize;+                let Some(base_index) = chunk_index.get(&base_root.entries[candidate].id).copied()+                else {+                    continue;+                };+                if base_index >= target_index+                    || kinds[base_index] != TYPE_CHUNK+                    || bodies[base_index].is_empty()+                    || bodies[target_index].is_empty()+                {+                    continue;+                }+                let ratio = bodies[base_index].len() as f64 / bodies[target_index].len() as f64;+                if ratio < 0.3 || ratio > 3.0 {+                    continue;+                }+                if let Some(estimate) =+                    probe_delta_size(bodies[target_index], bodies[base_index], level)+                {+                    if estimate < best_size {+                        best_size = estimate;+                        best_base = base_index;+                    }+                }+            }+            if best_base != usize::MAX+                && let Some(frame) = compress_dict(&bodies[target_index], &bodies[best_base], level)+                && frame.len() + 10 < solo+            {+                base[target_index] = Some(best_base);+                compression[target_index] = 2;+                compressed[target_index] = frame;+            }+        }+    }++    const MAX_DELTA_DEPTH: usize = 4;+    let mut depth = vec![0usize; ids.len()];+    for index in 0..ids.len() {+        let Some(base_index) = base[index] else {+            continue;+        };+        depth[index] = depth[base_index] + 1;+        if depth[index] <= MAX_DELTA_DEPTH {+            continue;+        }+        base[index] = None;+        compression[index] = 0;+        compressed[index].clear();+        depth[index] = 0;+        if bodies[index].len() >= 64+            && let Some(value) = compress(&bodies[index], level)+        {+            compression[index] = 1;+            compressed[index] = value;+        }+    }+}++pub fn encode(objects: &[RawObject], level: i32) -> PackOutput {+    let mut seen: IdSet = IdSet::default();+    let mut unique = Vec::new();+    for object in objects {+        if type_valid(object.kind) && seen.insert(object.id) {+            unique.push(object);+        }+    }++    let mut ids: Vec<Id> = unique.iter().map(|object| object.id).collect();+    let mut kinds: Vec<u8> = unique.iter().map(|object| object.kind).collect();+    let mut bodies: Vec<&[u8]> = unique.iter().map(|object| object.body.as_slice()).collect();+    let mut compression = vec![0u8; unique.len()];+    let mut compressed: Vec<Vec<u8>> = vec![Vec::new(); unique.len()];+    let mut base: Vec<Option<usize>> = vec![None; unique.len()];++    fn initial_compression(body: &[u8], level: i32) -> (u8, Vec<u8>) {+        if body.len() < 64 {+            (0, Vec::new())+        } else if let Some(value) = compress(body, level) {+            (1, value)+        } else {+            (0, Vec::new())+        }+    }++    let initial: Vec<(u8, Vec<u8>)> =+        if std::thread::available_parallelism().map_or(false, |n| n.get() > 1) {+            bodies+                .par_iter()+                .map(|body| initial_compression(body, level))+                .collect()+        } else {+            bodies+                .iter()+                .map(|body| initial_compression(body, level))+                .collect()+        };+    for (index, (kind, value)) in initial.into_iter().enumerate() {+        compression[index] = kind;+        compressed[index] = value;+    }++    select_pack_deltas(+        &ids,+        &kinds,+        &bodies,+        &mut compression,+        &mut compressed,+        &mut base,+        level,+    );++    let estimate = (0..unique.len())+        .map(|index| {+            let stored = if base[index].is_some() || compression[index] != 0 {+                compressed[index].len() + 10+            } else {+                bodies[index].len()+            };+            stored + 64+        })+        .sum::<usize>()+        + 16;+    let mut writer = Writer::with_capacity(estimate);+    writer.raw(b"VPK1");+    writer.u32le(1);+    writer.u64le(0);+    let mut metas = Vec::with_capacity(unique.len());+    let mut record_offsets = vec![0u64; unique.len()];+    for index in 0..unique.len() {+        let offset = writer.len() as u64;+        record_offsets[index] = offset;+        writer.id(ids[index]);+        writer.u8(kinds[index]);+        if let Some(base_index) = base[index] {+            writer.u8(2);+            let mut stored = Writer::with_capacity(compressed[index].len() + 10);+            stored.varint(record_offsets[base_index]);+            stored.raw(&compressed[index]);+            let stored = stored.into_vec();+            writer.varint(bodies[index].len() as u64);+            writer.varint(stored.len() as u64);+            writer.raw(&stored);+        } else {+            writer.u8(compression[index]);+            let stored: &[u8] = if compression[index] == 1 {+                &compressed[index]+            } else {+                &bodies[index]+            };+            writer.varint(bodies[index].len() as u64);+            writer.varint(stored.len() as u64);+            writer.raw(stored);+        }+        metas.push(IndexEntry {+            id: ids[index],+            offset,+        });+    }+    let mut pack = writer.into_vec();+    pack[8..16].copy_from_slice(&(metas.len() as u64).to_le_bytes());+    let digest = hash_bytes(&pack);+    pack.extend_from_slice(&digest);+    metas.sort_by(|left, right| left.id.0.cmp(&right.id.0));+    let index = index::encode(&metas, digest);+    let name = Id(digest).to_hex();+    ids.clear();+    kinds.clear();+    bodies.clear();+    compressed.clear();+    PackOutput {+        pack,+        index,+        name,+        count: metas.len(),+    }+}++pub fn write_output(root: &Path, output: &PackOutput, limit: u64) -> i32 {+    if output.count == 0 {+        return 0;+    }+    if limit > 0 && (output.pack.len() as u64).saturating_add(output.index.len() as u64) > limit {+        return 2;+    }+    let packs = crate::store::layout::packs_dir(root);+    let temporary = crate::store::layout::tmp_dir(root);+    let pack_final = packs.join(format!("{}.vpack", output.name));+    let index_final = packs.join(format!("{}.vidx", output.name));+    let suffix = format!("{}.tmp", core::random_u64());+    let pack_tmp = temporary.join(format!("{}.vpack.{suffix}", output.name));+    let index_tmp = temporary.join(format!("{}.vidx.{suffix}", output.name));+    if !core::write_atomic(&pack_tmp, &pack_final, &output.pack) {+        return 1;+    }+    if !core::write_atomic(&index_tmp, &index_final, &output.index) {+        let _ = core::remove_file(&pack_final);+        return 1;+    }+    0+}++pub fn write_pack(root: &Path, objects: &[RawObject], limit: u64, level: i32) -> i32 {+    let output = encode(objects, level);+    write_output(root, &output, limit)+}++pub struct RawPackReader {+    file: std::fs::File,+}++impl RawPackReader {+    pub fn open(path: &Path) -> std::io::Result<Self> {+        Ok(Self {+            file: std::fs::File::open(path)?,+        })+    }++    pub fn range(&mut self, offset: u64, length: usize) -> Option<Vec<u8>> {+        if length as u64 > MAX_STORE_PACK_BYTES {+            return None;+        }+        self.file.seek(SeekFrom::Start(offset)).ok()?;+        let mut data = vec![0u8; length];+        let mut done = 0;+        while done < length {+            match self.file.read(&mut data[done..]) {+                Ok(0) => break,+                Ok(count) => done += count,+                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,+                Err(_) => return None,+            }+        }+        data.truncate(done);+        Some(data)+    }+}--- /dev/null+++ b/veins/src/store/reader.rs@@ -0,0 +1,428 @@+use std::fs::{self, File};+use std::path::{Path, PathBuf};+use std::sync::{Mutex, OnceLock};++use crate::encoding::Reader;+use crate::error::{Error, Result};+use crate::object::id::{Id, object_id};+use crate::object::view::{self, Operation, View};+use crate::object::{MAX_STORE_PACK_BYTES, TYPE_CHUNK, type_valid};+use crate::platform::{self, Mapping};+use crate::store::index::{self, Index};+use crate::store::layout;+use crate::store::pack::{self, Pack, record_limit};++type PromisorFetcher = Box<dyn Fn(&Path, Id) -> bool + Send + Sync>;++fn fetcher() -> &'static Mutex<Option<PromisorFetcher>> {+    static FETCHER: OnceLock<Mutex<Option<PromisorFetcher>>> = OnceLock::new();+    FETCHER.get_or_init(|| Mutex::new(None))+}++pub fn set_promisor_fetcher(value: Option<PromisorFetcher>) {+    if let Ok(mut slot) = fetcher().lock() {+        *slot = value;+    }+}++fn fetch_promised(root: &Path, id: Id) -> bool {+    let Ok(slot) = fetcher().lock() else {+        return false;+    };+    slot.as_ref().is_some_and(|fetch| fetch(root, id))+}++#[derive(Clone, Copy)]+pub struct Location {+    pub pack: usize,+    pub kind: u8,+    pub record_offset: u64,+    pub data_offset: u64,+    pub raw_len: u64,+    pub stored_len: u64,+    pub compression: u8,+}++fn read_at_into(file: &File, offset: u64, buffer: &mut [u8]) -> Option<usize> {+    let mut done = 0;+    while done < buffer.len() {+        match platform::read_at(file, &mut buffer[done..], offset + done as u64) {+            Ok(0) => break,+            Ok(count) => done += count,+            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,+            Err(_) => return None,+        }+    }+    Some(done)+}++struct PackFile {+    path: PathBuf,+    mtime_ns: u64,+    index: Option<Index>,+    file: Option<File>,+    map: Option<Mapping>,+}++pub struct Store {+    root: PathBuf,+    packs: Vec<PackFile>,+}++impl Store {+    pub fn open(root: &Path) -> Result<Self> {+        let mut store = Self {+            root: root.to_path_buf(),+            packs: Vec::new(),+        };+        store.refresh()?;+        Ok(store)+    }++    pub fn root(&self) -> &Path {+        &self.root+    }++    pub fn refresh(&mut self) -> Result<()> {+        let directory = layout::packs_dir(&self.root);+        let mut known = std::collections::HashSet::new();+        for pack in &self.packs {+            known.insert(pack.path.clone());+        }+        if let Ok(entries) = fs::read_dir(&directory) {+            for entry in entries.flatten() {+                let path = entry.path();+                if path.extension().and_then(|value| value.to_str()) != Some("vpack") {+                    continue;+                }+                if known.contains(&path) {+                    continue;+                }+                let mtime_ns = entry+                    .metadata()+                    .ok()+                    .map(|metadata| platform::mtime_ns(&metadata))+                    .unwrap_or(0);+                self.packs.push(PackFile {+                    path,+                    mtime_ns,+                    index: None,+                    file: None,+                    map: None,+                });+            }+        }+        self.packs.sort_by(|left, right| {+            right+                .mtime_ns+                .cmp(&left.mtime_ns)+                .then_with(|| left.path.cmp(&right.path))+        });+        Ok(())+    }++    fn ensure_index(&mut self, index: usize) -> bool {+        let pack = &mut self.packs[index];+        if pack.index.is_some() {+            return true;+        }+        let Some(name) = pack.path.file_name().and_then(|value| value.to_str()) else {+            return false;+        };+        if name.len() <= 6 {+            return false;+        }+        let stem = &name[..name.len() - 6];+        let index_path = pack.path.with_file_name(format!("{stem}.vidx"));+        let Some(data) = crate::core::read_file_opt(&index_path, MAX_STORE_PACK_BYTES) else {+            return false;+        };+        let Ok(decoded) = index::decode(&data, None) else {+            return false;+        };+        if stem != Id(decoded.pack_trailer).to_hex() {+            return false;+        }+        pack.index = Some(decoded);+        true+    }++    fn open_file(&mut self, index: usize) -> bool {+        let pack = &mut self.packs[index];+        if pack.file.is_some() {+            return true;+        }+        match File::open(&pack.path) {+            Ok(file) => {+                pack.file = Some(file);+                true+            }+            Err(_) => false,+        }+    }++    fn ensure_mapping(&mut self, index: usize) {+        let pack = &mut self.packs[index];+        if pack.map.is_none() {+            pack.map = Mapping::open(&pack.path);+        }+    }++    fn read_at_shared(+        &self,+        index: usize,+        offset: u64,+        length: usize,+    ) -> Option<std::borrow::Cow<'_, [u8]>> {+        if length as u64 > MAX_STORE_PACK_BYTES {+            return None;+        }+        let pack = self.packs.get(index)?;+        if let Some(map) = &pack.map {+            let data = map.as_slice();+            let start = usize::try_from(offset).ok()?;+            if start >= data.len() {+                return None;+            }+            let end = start.saturating_add(length).min(data.len());+            return Some(std::borrow::Cow::Borrowed(&data[start..end]));+        }+        let file = pack.file.as_ref()?;+        let mut data = vec![0u8; length];+        let done = read_at_into(file, offset, &mut data)?;+        data.truncate(done);+        Some(std::borrow::Cow::Owned(data))+    }++    fn record_at(&self, pack_index: usize, offset: u64, expected: Option<Id>) -> Option<Location> {+        let mut header_buffer = [0u8; 96];+        let header: &[u8] = {+            let pack = self.packs.get(pack_index)?;+            if let Some(map) = &pack.map {+                let data = map.as_slice();+                let start = usize::try_from(offset).ok()?;+                if start >= data.len() {+                    return None;+                }+                let end = start.saturating_add(header_buffer.len()).min(data.len());+                &data[start..end]+            } else {+                let file = pack.file.as_ref()?;+                let length = read_at_into(file, offset, &mut header_buffer)?;+                &header_buffer[..length]+            }+        };+        if header.len() < 34 {+            return None;+        }+        let mut reader = Reader::new(header);+        let id = reader.id().ok()?;+        let kind = reader.u8().ok()?;+        let compression = reader.u8().ok()?;+        let raw_len = reader.varint().ok()?;+        let stored_len = reader.varint().ok()?;+        if expected.is_some_and(|value| value != id) {+            return None;+        }+        if !type_valid(kind) || compression > 2 || raw_len == 0 {+            return None;+        }+        if raw_len > record_limit(kind) as u64 {+            return None;+        }+        if stored_len > record_limit(kind) as u64 + crate::object::MAX_CHUNK_LEN as u64 {+            return None;+        }+        if compression == 0 && raw_len != stored_len {+            return None;+        }+        Some(Location {+            pack: pack_index,+            kind,+            record_offset: offset,+            data_offset: offset + reader.offset() as u64,+            raw_len,+            stored_len,+            compression,+        })+    }++    fn find_loaded(&self, id: Id) -> Option<Location> {+        for index in 0..self.packs.len() {+            let Some(entry) = self.packs[index].index.as_ref() else {+                continue;+            };+            let Some(position) = entry.find(id) else {+                continue;+            };+            let offset = entry.entries[position].offset;+            if let Some(location) = self.record_at(index, offset, Some(id)) {+                return Some(location);+            }+        }+        None+    }++    pub fn find(&mut self, id: Id) -> Option<Location> {+        for index in 0..self.packs.len() {+            if !self.ensure_index(index) {+                continue;+            }+            let offset = {+                let Some(entry) = self.packs[index].index.as_ref() else {+                    continue;+                };+                let Some(position) = entry.find(id) else {+                    continue;+                };+                entry.entries[position].offset+            };+            if !self.open_file(index) {+                continue;+            }+            self.ensure_mapping(index);+            if let Some(location) = self.record_at(index, offset, Some(id)) {+                return Some(location);+            }+        }+        None+    }++    pub fn contains(&mut self, id: Id) -> bool {+        self.find(id).is_some()+    }++    fn get_at(&self, location: Location, depth: usize) -> Result<Vec<u8>> {+        if depth > 32 {+            return Err(Error::new("pack delta chain is too deep"));+        }+        let stored_len = usize::try_from(location.stored_len)+            .map_err(|_| Error::new("stored length overflow"))?;+        let stored = self+            .read_at_shared(location.pack, location.data_offset, stored_len)+            .ok_or_else(|| Error::new("cannot read pack record"))?;+        if stored.len() != stored_len {+            return Err(Error::new("pack record is truncated"));+        }+        let raw_len =+            usize::try_from(location.raw_len).map_err(|_| Error::new("raw length overflow"))?;+        match location.compression {+            0 => Ok(stored.into_owned()),+            1 => crate::store::pack::decompress(stored.as_ref(), raw_len),+            2 => {+                let mut reader = Reader::new(stored.as_ref());+                let base_offset = reader.varint()?;+                if base_offset >= location.record_offset {+                    return Err(Error::new("invalid pack delta base"));+                }+                let frame = reader.raw(reader.remaining())?;+                let base = self+                    .record_at(location.pack, base_offset, None)+                    .ok_or_else(|| Error::new("missing pack delta base"))?;+                let body = self.get_at(base, depth + 1)?;+                crate::store::pack::decompress_dict(frame, raw_len, &body)+            }+            _ => Err(Error::new("invalid pack compression")),+        }+    }++    pub fn get(&mut self, location: Location) -> Result<Vec<u8>> {+        if location.pack >= self.packs.len() {+            return Err(Error::new("pack location out of range"));+        }+        self.open_file(location.pack);+        self.ensure_mapping(location.pack);+        self.get_at(location, 0)+    }++    pub fn body(&mut self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {+        let mut location = self.find(id);+        if location.is_none() && expected == TYPE_CHUNK && fetch_promised(&self.root, id) {+            self.refresh()?;+            location = self.find(id);+        }+        let Some(location) = location else {+            return Ok(None);+        };+        if location.kind != expected {+            return Ok(None);+        }+        let body = self.get(location)?;+        if object_id(expected, &body) != id {+            return Ok(None);+        }+        Ok(Some(body))+    }++    pub fn body_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {+        let Some(location) = self.find_loaded(id) else {+            return Ok(None);+        };+        if location.kind != expected {+            return Ok(None);+        }+        let body = self.get_at(location, 0)?;+        if object_id(expected, &body) != id {+            return Ok(None);+        }+        Ok(Some(body))+    }++    /// Read a body without re-hashing it, for callers that only inspect contents.+    pub fn body_raw_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {+        let Some(location) = self.find_loaded(id) else {+            return Ok(None);+        };+        if location.kind != expected {+            return Ok(None);+        }+        Ok(Some(self.get_at(location, 0)?))+    }++    pub fn preload(&mut self) -> Result<()> {+        for index in 0..self.packs.len() {+            self.ensure_index(index);+            self.open_file(index);+            self.ensure_mapping(index);+        }+        Ok(())+    }++    pub fn view(&mut self, id: Id) -> Result<Option<View>> {+        let Some(body) = self.body(id, crate::object::TYPE_VIEW)? else {+            return Ok(None);+        };+        Ok(Some(view::decode_view(&body)?))+    }++    pub fn operation(&mut self, id: Id) -> Result<Option<Operation>> {+        let Some(body) = self.body(id, crate::object::TYPE_OPERATION)? else {+            return Ok(None);+        };+        Ok(Some(view::decode_operation(&body)?))+    }++    pub fn has_promisor(&self) -> bool {+        crate::core::read_file_opt(&layout::config_path(&self.root), 0)+            .is_some_and(|data| data.windows(8).any(|window| window == b"promisor"))+    }++    pub fn pack_count(&self) -> usize {+        self.packs.len()+    }++    pub fn pack_paths(&self) -> Vec<PathBuf> {+        self.packs.iter().map(|pack| pack.path.clone()).collect()+    }++    pub fn decode_pack(&self, index: usize) -> Result<Pack> {+        let path = self+            .packs+            .get(index)+            .map(|pack| pack.path.clone())+            .ok_or_else(|| Error::new("pack out of range"))?;+        let data = crate::core::read_file_opt(&path, MAX_STORE_PACK_BYTES)+            .ok_or_else(|| Error::new("cannot read pack"))?;+        pack::decode(data)+    }+}--- /dev/null+++ b/veins/src/store/transaction.rs@@ -0,0 +1,172 @@+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::view::{Operation, TimeMs, View, encode_operation, encode_view};+use crate::object::{TYPE_OPERATION, TYPE_VIEW};+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::time;++pub struct Txn {+    root: PathBuf,+    view: View,+    parents: Vec<Id>,+    start_ms: i64,+    writer: Writer,+}++impl Txn {+    pub fn begin(root: &Path, store: &mut Store) -> Result<Self> {+        let heads = ops::read_heads(root)?;+        let view = if heads.is_empty() {+            ops::empty_view()+        } else if heads.len() == 1 {+            load_view(store, heads[0])?+        } else {+            let mut merged = load_view(store, heads[0])?;+            for head in &heads[1..] {+                let extra = load_view(store, *head)?;+                merge_view_into(&mut merged, &extra);+            }+            ops::add_unique_head(&mut merged, heads[0]);+            merged+        };+        let mut view = view;+        ops::sort_view(&mut view);+        Ok(Self {+            root: root.to_path_buf(),+            view,+            parents: heads,+            start_ms: time::now_millis(),+            writer: Writer::default(),+        })+    }++    pub fn view(&self) -> &View {+        &self.view+    }++    pub fn view_mut(&mut self) -> &mut View {+        &mut self.view+    }++    pub fn writer(&mut self) -> &mut Writer {+        &mut self.writer+    }++    pub fn add_object(&mut self, kind: u8, body: Vec<u8>) -> Id {+        self.writer.add(kind, body)+    }++    pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {+        self.writer.add_known(kind, id, body)+    }++    pub fn finish(&mut self, description: &str) -> Result<Id> {+        let view = self.view.clone();+        self.finish_chain(vec![(view, description.to_string())])+    }++    pub fn finish_chain(&mut self, operations: Vec<(View, String)>) -> Result<Id> {+        if operations.is_empty() {+            return Err(Error::new("no operations to write"));+        }+        let mut parents = self.parents.clone();+        let mut last = Id::default();+        for (view, description) in operations {+            let mut view = view;+            ops::sort_view(&mut view);+            let view_body = encode_view(&view);+            let view_id = self.writer.add(TYPE_VIEW, view_body);+            let now = time::now_millis();+            let operation = Operation {+                parents,+                view: view_id,+                start: TimeMs {+                    millis: self.start_ms,+                    tz_min: 0,+                },+                end: TimeMs {+                    millis: now,+                    tz_min: 0,+                },+                hostname: host_name(),+                username: user_name(),+                description: description.as_bytes().to_vec(),+                tags: vec![(b"command".to_vec(), description.as_bytes().to_vec())],+            };+            let operation_body = encode_operation(&operation);+            last = self.writer.add(TYPE_OPERATION, operation_body);+            parents = vec![last];+        }+        if self.writer.finish(&self.root) != 0 {+            return Err(Error::new("failed to write object pack"));+        }+        ops::write_head(&self.root, last)?;+        for parent in &self.parents {+            ops::delete_head(&self.root, *parent)?;+        }+        Ok(last)+    }+}++fn load_view(store: &mut Store, head: Id) -> Result<View> {+    let operation = store+        .operation(head)?+        .ok_or_else(|| Error::new("cannot load operation state"))?;+    store+        .view(operation.view)?+        .ok_or_else(|| Error::new("cannot load view state"))+}++fn merge_view_into(target: &mut View, source: &View) {+    for head in &source.heads {+        ops::add_unique_head(target, *head);+    }+    for bookmark in &source.bookmarks {+        match ops::find_bookmark(target, &bookmark.name) {+            None => target.bookmarks.push(bookmark.clone()),+            Some(index) => {+                let existing = &mut target.bookmarks[index];+                let left = existing.targets.adds.first().copied().flatten();+                let right = bookmark.targets.adds.first().copied().flatten();+                if left != right || existing.targets.adds.len() != bookmark.targets.adds.len() {+                    existing.targets.adds = vec![left, right];+                    existing.targets.removes = vec![None];+                }+            }+        }+    }+    for tag in &source.tags {+        if !target.tags.iter().any(|value| value.name == tag.name) {+            target.tags.push(tag.clone());+        }+    }+    for workspace in &source.working_copies {+        if !target+            .working_copies+            .iter()+            .any(|value| value.workspace == workspace.workspace)+        {+            target.working_copies.push(workspace.clone());+        }+    }+}++fn host_name() -> Vec<u8> {+    std::env::var("HOSTNAME")+        .ok()+        .filter(|value| !value.is_empty())+        .unwrap_or_else(|| "localhost".to_string())+        .into_bytes()+}++fn user_name() -> Vec<u8> {+    std::env::var("USER")+        .ok()+        .filter(|value| !value.is_empty())+        .unwrap_or_else(|| "unknown".to_string())+        .into_bytes()+}--- /dev/null+++ b/veins/src/store/writer.rs@@ -0,0 +1,91 @@+use std::collections::HashSet;+use std::path::Path;++use crate::object::id::{Id, object_id};+use crate::object::{RawObject, TYPE_CHUNK};+use crate::store::pack::{self, PackOutput};++// Commits favour latency; `vn repack` re-compresses the history afterwards.+const COMMIT_LEVEL: i32 = 2;++#[derive(Default)]+pub struct Writer {+    objects: Vec<RawObject>,+    cache: std::collections::HashMap<(u8, Id), usize>,+    seen: HashSet<Id>,+    cache_chunks: bool,+    limit: u64,+    raw_bytes: u64,+    quota_hit: bool,+}++impl Writer {+    pub fn enable_chunk_cache(&mut self) {+        self.cache_chunks = true;+    }++    pub fn set_limit(&mut self, limit: u64) {+        self.limit = limit;+    }++    pub fn quota_hit(&self) -> bool {+        self.quota_hit+    }++    pub fn objects(&self) -> &[RawObject] {+        &self.objects+    }++    fn should_accept(&mut self, id: Id, body: &[u8]) -> bool {+        if self.quota_hit || !self.seen.insert(id) {+            return false;+        }+        if self.limit > 0 && self.raw_bytes.saturating_add(body.len() as u64) > self.limit {+            self.quota_hit = true;+            return false;+        }+        self.raw_bytes = self.raw_bytes.saturating_add(body.len() as u64);+        true+    }++    pub fn add(&mut self, kind: u8, body: Vec<u8>) -> Id {+        let id = object_id(kind, &body);+        if !self.should_accept(id, &body) {+            return id;+        }+        if kind != TYPE_CHUNK || self.cache_chunks {+            self.cache.insert((kind, id), self.objects.len());+        }+        self.objects.push(RawObject::known(kind, id, body));+        id+    }++    pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {+        if !self.should_accept(id, &body) {+            return id;+        }+        if kind != TYPE_CHUNK || self.cache_chunks {+            self.cache.insert((kind, id), self.objects.len());+        }+        self.objects.push(RawObject::known(kind, id, body));+        id+    }++    pub fn find_cached(&self, kind: u8, id: Id) -> Option<&[u8]> {+        self.cache+            .get(&(kind, id))+            .and_then(|index| self.objects.get(*index))+            .map(|object| object.body.as_slice())+    }++    pub fn finish(&self, root: &Path) -> i32 {+        if self.quota_hit {+            return 2;+        }+        pack::write_pack(root, &self.objects, self.limit, COMMIT_LEVEL)+    }++    pub fn encode_finish(&self) -> PackOutput {+        pack::encode(&self.objects, COMMIT_LEVEL)+    }+}--- /dev/null+++ b/veins/src/time.rs@@ -0,0 +1,47 @@+use std::time::{SystemTime, UNIX_EPOCH};++pub fn now_millis() -> i64 {+    SystemTime::now()+        .duration_since(UNIX_EPOCH)+        .map(|duration| duration.as_millis() as i64)+        .unwrap_or(0)+}++pub fn now_seconds() -> i64 {+    SystemTime::now()+        .duration_since(UNIX_EPOCH)+        .map(|duration| duration.as_secs() as i64)+        .unwrap_or(0)+}++fn floor_div(value: i64, divisor: i64) -> i64 {+    let quotient = value / divisor;+    let remainder = value % divisor;+    if remainder != 0 && (remainder < 0) != (divisor < 0) {+        quotient - 1+    } else {+        quotient+    }+}++pub fn format_utc(seconds: i64) -> String {+    let days = floor_div(seconds, 86_400);+    let remainder = seconds - days * 86_400;+    let hour = remainder / 3_600;+    let minute = (remainder % 3_600) / 60;+    let second = remainder % 60;++    let z = days + 719_468;+    let era = floor_div(z, 146_097);+    let doe = z - era * 146_097;+    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;+    let y0 = yoe + era * 400;+    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+    let mp = (5 * doy + 2) / 153;+    let day = doy - (153 * mp + 2) / 5 + 1;+    let month0 = mp + 3;+    let month = if mp >= 10 { mp - 9 } else { month0 };+    let year = if month <= 2 { y0 + 1 } else { y0 };++    format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}")+}--- /dev/null+++ b/veins/src/worktree/attributes.rs@@ -0,0 +1,223 @@+use std::path::Path;++use crate::core;++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum AttributeEol {+    None,+    Lf,+    Crlf,+    Cr,+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub enum AttributeText {+    Auto,+    Text,+    Binary,+}++#[derive(Clone, Copy)]+pub struct PathAttributes {+    pub generated: bool,+    pub text: AttributeText,+    pub eol: AttributeEol,+}++impl Default for PathAttributes {+    fn default() -> Self {+        Self {+            generated: false,+            text: AttributeText::Auto,+            eol: AttributeEol::None,+        }+    }+}++#[derive(Clone)]+struct Rule {+    pattern: String,+    has_slash: bool,+    generated_set: bool,+    generated: bool,+    text_set: bool,+    text: AttributeText,+    eol_set: bool,+    eol: AttributeEol,+}++#[derive(Clone, Default)]+pub struct AttributeRules {+    rules: Vec<Rule>,+    mtime_ns: i64,+}++fn next_token<'a>(text: &'a str, position: &mut usize) -> &'a str {+    while *position < text.len() && matches!(text.as_bytes()[*position], b' ' | b'\t') {+        *position += 1;+    }+    let start = *position;+    while *position < text.len() && !matches!(text.as_bytes()[*position], b' ' | b'\t') {+        *position += 1;+    }+    &text[start..*position]+}++fn basename(path: &str) -> &str {+    path.rsplit_once('/').map(|(_, name)| name).unwrap_or(path)+}++fn rule_matches(pattern: &str, has_slash: bool, path: &str) -> bool {+    core::glob_match(pattern, path) || (!has_slash && core::glob_match(pattern, basename(path)))+}++fn parse_eol(value: &str) -> AttributeEol {+    match value {+        "lf" => AttributeEol::Lf,+        "crlf" => AttributeEol::Crlf,+        "cr" => AttributeEol::Cr,+        _ => AttributeEol::None,+    }+}++impl AttributeRules {+    pub fn load(root: &Path) -> Self {+        let mut rules = Self::default();+        let path = root.join(".vnattribs");+        if let Some(info) = core::stat_path(&path) {+            rules.mtime_ns = info.mtime_ns as i64;+        }+        let Some(data) = core::read_file_opt(&path, 0) else {+            return rules;+        };+        let text = String::from_utf8_lossy(&data);+        for raw in text.lines() {+            let line = core::trim_str(raw);+            if line.is_empty() || line.starts_with('#') {+                continue;+            }+            let mut position = 0;+            let pattern = next_token(line, &mut position);+            if pattern.is_empty() {+                continue;+            }+            let mut rule = Rule {+                pattern: pattern.to_string(),+                has_slash: pattern.contains('/'),+                generated_set: false,+                generated: false,+                text_set: false,+                text: AttributeText::Auto,+                eol_set: false,+                eol: AttributeEol::None,+            };+            while position < line.len() {+                let token = next_token(line, &mut position);+                if token.is_empty() {+                    break;+                }+                match token {+                    "gen" => {+                        rule.generated_set = true;+                        rule.generated = true;+                    }+                    "-gen" => {+                        rule.generated_set = true;+                        rule.generated = false;+                    }+                    "txt" => {+                        rule.text_set = true;+                        rule.text = AttributeText::Text;+                    }+                    "bin" => {+                        rule.text_set = true;+                        rule.text = AttributeText::Binary;+                    }+                    "-txt" | "-bin" => {+                        rule.text_set = true;+                        rule.text = AttributeText::Auto;+                    }+                    "-eol" => {+                        rule.eol_set = true;+                        rule.eol = AttributeEol::None;+                    }+                    value if value.starts_with("eol:") => {+                        let value = &value[4..];+                        if matches!(value, "lf" | "crlf" | "cr") {+                            rule.eol_set = true;+                            rule.eol = parse_eol(value);+                        }+                    }+                    _ => {}+                }+            }+            rules.rules.push(rule);+        }+        rules+    }++    pub fn lookup(&self, path: &str) -> PathAttributes {+        let mut attributes = PathAttributes::default();+        for rule in &self.rules {+            if !rule_matches(&rule.pattern, rule.has_slash, path) {+                continue;+            }+            if rule.generated_set {+                attributes.generated = rule.generated;+            }+            if rule.text_set {+                attributes.text = rule.text;+            }+            if rule.eol_set {+                attributes.eol = rule.eol;+            }+        }+        attributes+    }++    pub fn changed_since(&self, cache_written_ms: i64) -> bool {+        if cache_written_ms <= 0 {+            return true;+        }+        if self.mtime_ns == 0 {+            return false;+        }+        self.mtime_ns > cache_written_ms * 1_000_000+    }+}++pub fn normalize_eol(data: &[u8], eol: AttributeEol) -> Vec<u8> {+    let (first, second) = match eol {+        AttributeEol::None => return data.to_vec(),+        AttributeEol::Lf => (b'\n', 0),+        AttributeEol::Crlf => (b'\r', b'\n'),+        AttributeEol::Cr => (b'\r', 0),+    };+    let mut output = Vec::with_capacity(data.len());+    let mut index = 0;+    while index < data.len() {+        let byte = data[index];+        if byte == b'\r' {+            if index + 1 < data.len() && data[index + 1] == b'\n' {+                index += 1;+            }+            output.push(first);+            if second != 0 {+                output.push(second);+            }+        } else if byte == b'\n' {+            output.push(first);+            if second != 0 {+                output.push(second);+            }+        } else {+            output.push(byte);+        }+        index += 1;+    }+    output+}++pub fn attributes_of<'a>(rules: &'a AttributeRules, path: &[u8]) -> PathAttributes {+    rules.lookup(&String::from_utf8_lossy(path))+}--- /dev/null+++ b/veins/src/worktree/checkout.rs@@ -0,0 +1,568 @@+use std::fs;+use std::path::{Path, PathBuf};++use rayon::prelude::*;++use crate::core;+use crate::error::{Error, Result};+use crate::object::conflict::{self, Conflict, ConflictValue};+use crate::object::id::Id;+use crate::object::path::valid_checkout_path;+use crate::object::tree::{self, FlatEntry};+use crate::platform;+use crate::store::Txn;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText};+use crate::worktree::snapshot;+use crate::worktree::stat_cache::{self, CacheEntry};++pub fn run(root: &Path, revision: &str) -> Result<()> {+    let mut store = Store::open(root)?;+    snapshot::run_with(root, &mut store)?;++    let view = ops::current_view(root, &mut store)?+        .ok_or_else(|| Error::new("no operation state; import a repository first"))?;+    let target = graph::resolve_revision(&mut store, &view, revision)?+        .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;+    let target_commit =+        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;++    let bookmark_checkout = !revision.is_empty()+        && revision != "@"+        && ops::find_bookmark(&view, revision.as_bytes()).is_some();+    let detach_bookmark = !revision.is_empty() && revision != "@" && !bookmark_checkout;++    let working_copy = ops::working_copy_id(&view);+    let old_root = match working_copy {+        Some(id) => graph::load_commit(&mut store, id)?.map(|commit| commit.root_tree),+        None => None,+    };++    if old_root != Some(target_commit.root_tree) {+        materialize(root, &mut store, old_root, target_commit.root_tree)?;+    }++    if working_copy != Some(target) {+        let already_empty_child = match working_copy {+            Some(id) => graph::load_commit(&mut store, id)?.is_some_and(|commit| {+                commit.parents.len() == 1+                    && commit.parents[0] == target+                    && commit.root_tree == target_commit.root_tree+                    && commit.message.is_empty()+            }),+            None => false,+        };+        if !already_empty_child {+            let mut txn = Txn::begin(root, &mut store)?;+            if let Some(old_id) = working_copy {+                ops::remove_head(txn.view_mut(), old_id);+            }+            let child = create_working_copy_commit(&mut txn, &mut store, target)?;+            ops::set_workspace(txn.view_mut(), child);+            ops::rebuild_heads(txn.view_mut());+            txn.finish("checkout")?;+        }+    }+    if bookmark_checkout {+        core::set_current_bookmark(root, revision);+    } else if detach_bookmark {+        core::clear_current_bookmark(root);+    }+    Ok(())+}++fn create_working_copy_commit(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {+    let loaded = graph::load_commit(store, parent)?+        .ok_or_else(|| Error::new("cannot read parent commit"))?;+    let signature = crate::identity::signature(store.root());+    let commit = crate::object::commit::Commit {+        version: 1,+        parents: vec![parent],+        root_tree: loaded.root_tree,+        change_id: crate::identity::random_change_id(),+        author: signature.clone(),+        committer: signature,+        message: Vec::new(),+        renames_state: crate::object::commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    Ok(txn.add_object(+        crate::object::TYPE_COMMIT,+        crate::object::commit::encode(&commit),+    ))+}++fn sidecar_suffixes() -> Vec<String> {+    let mut suffixes = vec![+        ".base".to_string(),+        ".ours".to_string(),+        ".theirs".to_string(),+    ];+    for number in 2..=64 {+        suffixes.push(format!(".base{number}"));+        suffixes.push(format!(".theirs{number}"));+    }+    suffixes+}++fn remove_any(path: &Path) -> Result<()> {+    let metadata = fs::symlink_metadata(path)?;+    if metadata.is_dir() && !metadata.file_type().is_symlink() {+        fs::remove_dir_all(path)?;+    } else {+        fs::remove_file(path)?;+    }+    Ok(())+}++fn prune_empty_parents(root: &Path, relative: &[u8]) -> Result<()> {+    let mut end = relative.len();+    while end > 0 {+        let Some(position) = relative[..end].iter().rposition(|byte| *byte == b'/') else {+            break;+        };+        let path = root.join(core::path_from_bytes(&relative[..position]));+        if fs::remove_dir(&path).is_err() {+            break;+        }+        end = position;+    }+    Ok(())+}++fn remove_tracked_path(root: &Path, relative: &[u8]) -> Result<()> {+    let path = root.join(core::path_from_bytes(relative));+    match fs::symlink_metadata(&path) {+        Ok(_) => {+            remove_any(&path)?;+            prune_empty_parents(root, relative)?;+        }+        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+        Err(error) => return Err(error.into()),+    }+    Ok(())+}++fn delete_sidecars(root: &Path, path: &[u8]) -> Result<()> {+    for suffix in sidecar_suffixes() {+        let mut full = path.to_vec();+        full.extend_from_slice(suffix.as_bytes());+        remove_tracked_path(root, &full)?;+    }+    Ok(())+}++fn has_symlink_component(root: &Path, relative: &[u8]) -> bool {+    let mut current = root.to_path_buf();+    let mut start = 0;+    for index in 0..relative.len() {+        if relative[index] != b'/' {+            continue;+        }+        if index == start {+            return true;+        }+        current = current.join(core::path_from_bytes(&relative[start..index]));+        if core::stat_path(&current).is_some_and(|info| info.kind == 3) {+            return true;+        }+        start = index + 1;+    }+    false+}++fn ensure_safe_dirs(root: &Path, relative: &[u8]) -> Result<()> {+    if relative.is_empty() {+        return Ok(());+    }+    let mut current = root.to_path_buf();+    let mut start = 0;+    for index in 0..=relative.len() {+        let at_end = index == relative.len();+        if !at_end && relative[index] != b'/' {+            continue;+        }+        let component = &relative[start..index];+        if component.is_empty() {+            return Err(Error::new("empty path component"));+        }+        if at_end {+            break;+        }+        current = current.join(core::path_from_bytes(component));+        match fs::symlink_metadata(&current) {+            Ok(metadata) => {+                if metadata.file_type().is_symlink() || !metadata.is_dir() {+                    return Err(Error::new("unsafe path component"));+                }+            }+            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+                fs::create_dir(&current)?;+            }+            Err(error) => return Err(error.into()),+        }+        start = index + 1;+    }+    Ok(())+}++fn write_bytes(root: &Path, relative: &[u8], data: &[u8], executable: bool) -> Result<()> {+    if !valid_checkout_path(relative) || has_symlink_component(root, relative) {+        return Err(Error::new(format!(+            "invalid checkout path: {}",+            String::from_utf8_lossy(relative)+        )));+    }+    ensure_safe_dirs(root, relative)?;+    let path = root.join(core::path_from_bytes(relative));+    if let Ok(metadata) = fs::symlink_metadata(&path) {+        if metadata.is_dir() && !metadata.file_type().is_symlink() {+            return Err(Error::new("checkout path collides with a directory"));+        }+        if metadata.file_type().is_symlink() {+            fs::remove_file(&path)?;+        }+    }+    if !core::write_file(&path, data) {+        return Err(Error::new("cannot write checkout file"));+    }+    let mode = if executable { 0o755 } else { 0o644 };+    platform::set_mode(&path, mode)?;+    Ok(())+}++fn write_symlink(root: &Path, relative: &[u8], target: &[u8]) -> Result<()> {+    if !valid_checkout_path(relative) || has_symlink_component(root, relative) {+        return Err(Error::new("invalid checkout path"));+    }+    ensure_safe_dirs(root, relative)?;+    let path = root.join(core::path_from_bytes(relative));+    if let Ok(metadata) = fs::symlink_metadata(&path) {+        if metadata.is_dir() && !metadata.file_type().is_symlink() {+            return Err(Error::new("checkout path collides with a directory"));+        }+        remove_any(&path)?;+    }+    platform::create_symlink(&core::path_from_bytes(target), &path)?;+    Ok(())+}++fn write_entry(+    store: &Store,+    root: &Path,+    entry: &FlatEntry,+    attributes: &AttributeRules,+) -> Result<()> {+    let data =+        graph::read_blob_loaded(store, entry.target)?.ok_or_else(|| Error::new("missing blob"))?;+    if entry.kind == tree::KIND_SYMLINK {+        return write_symlink(root, &entry.path, &data);+    }+    let path_attributes = attributes.lookup(&String::from_utf8_lossy(&entry.path));+    if path_attributes.eol != AttributeEol::None && path_attributes.text != AttributeText::Binary {+        let normalized = attributes::normalize_eol(&data, path_attributes.eol);+        write_bytes(+            root,+            &entry.path,+            &normalized,+            entry.kind == tree::KIND_EXECUTABLE,+        )+    } else {+        write_bytes(+            root,+            &entry.path,+            &data,+            entry.kind == tree::KIND_EXECUTABLE,+        )+    }+}++fn delete_stale(root: &Path, old_entries: &[FlatEntry], new_entries: &[FlatEntry]) -> Result<()> {+    for entry in old_entries {+        if entry.kind == tree::KIND_SUBMODULE {+            continue;+        }+        if tree::find_flat(new_entries, &entry.path).is_some() {+            continue;+        }+        remove_tracked_path(root, &entry.path)?;+        if entry.kind == tree::KIND_CONFLICT {+            delete_sidecars(root, &entry.path)?;+        }+    }+    Ok(())+}++fn load_conflict(store: &mut Store, id: Id) -> Result<Option<Conflict>> {+    let Some(body) = store.body(id, crate::object::TYPE_CONFLICT)? else {+        return Ok(None);+    };+    Ok(Some(conflict::decode(&body)?))+}++fn write_tree_side(+    store: &mut Store,+    root: &Path,+    tree_id: Id,+    prefix: &[u8],+    attributes: &AttributeRules,+) -> Result<()> {+    let entries = tree::flatten(store, tree_id)?;+    for entry in entries {+        if entry.kind == tree::KIND_CONFLICT || entry.kind == tree::KIND_SUBMODULE {+            continue;+        }+        let path = crate::object::path::join(prefix, &entry.path);+        write_entry(store, root, &FlatEntry { path, ..entry }, attributes)?;+    }+    Ok(())+}++fn materialize_value(+    store: &mut Store,+    root: &Path,+    path: &[u8],+    value: &ConflictValue,+    attributes: &AttributeRules,+) -> Result<()> {+    if value.kind == 0 {+        return remove_tracked_path(root, path);+    }+    let target = value+        .target+        .ok_or_else(|| Error::new("conflict value has no target"))?;+    if value.kind == tree::KIND_SUBTREE {+        remove_tracked_path(root, path)?;+        return write_tree_side(store, root, target, path, attributes);+    }+    write_entry(+        store,+        root,+        &FlatEntry {+            path: path.to_vec(),+            kind: value.kind,+            target,+        },+        attributes,+    )+}++fn materialize_conflict(+    store: &mut Store,+    root: &Path,+    path: &[u8],+    target: Id,+    attributes: &AttributeRules,+) -> Result<()> {+    let conflict =+        load_conflict(store, target)?.ok_or_else(|| Error::new("cannot read conflict value"))?;+    for (index, value) in conflict.removes.iter().enumerate() {+        let suffix = if index == 0 {+            ".base".to_string()+        } else {+            format!(".base{}", index + 1)+        };+        let mut full = path.to_vec();+        full.extend_from_slice(suffix.as_bytes());+        materialize_value(store, root, &full, value, attributes)?;+    }+    for (index, value) in conflict.adds.iter().enumerate() {+        let suffix = match index {+            0 => ".ours".to_string(),+            1 => ".theirs".to_string(),+            _ => format!(".theirs{}", index + 1),+        };+        let mut full = path.to_vec();+        full.extend_from_slice(suffix.as_bytes());+        materialize_value(store, root, &full, value, attributes)?;+    }+    if let Some(first) = conflict.adds.first() {+        materialize_value(store, root, path, first, attributes)?;+    } else {+        remove_tracked_path(root, path)?;+    }+    Ok(())+}++fn save_checkout_cache(root: &Path, entries: &[FlatEntry]) -> Result<()> {+    let now_ms = crate::time::now_millis();+    let mut cache = Vec::new();+    for entry in entries {+        if !matches!(+            entry.kind,+            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK+        ) {+            continue;+        }+        let Some(info) = core::stat_path(&root.join(core::path_from_bytes(&entry.path))) else {+            continue;+        };+        cache.push(CacheEntry {+            path: entry.path.clone(),+            size: info.size,+            mtime_ns: info.mtime_ns,+            inode: info.inode,+            kind: info.kind,+            executable: info.executable,+            target: entry.target,+            trusted: true,+        });+    }+    stat_cache::save(root, &mut cache, now_ms)+}++pub fn materialize(+    root: &Path,+    store: &mut Store,+    old_root: Option<Id>,+    new_root: Id,+) -> Result<()> {+    materialize_with_progress(root, store, old_root, new_root, None)+}++pub fn materialize_with_progress(+    root: &Path,+    store: &mut Store,+    old_root: Option<Id>,+    new_root: Id,+    progress: Option<&core::Progress>,+) -> Result<()> {+    if old_root == Some(new_root) {+        return Ok(());+    }+    let old_entries = match old_root {+        Some(id) => tree::flatten(store, id)?,+        None => Vec::new(),+    };+    let attributes = AttributeRules::load(root);+    let new_entries = tree::flatten(store, new_root)?;++    let mut directories: Vec<Vec<u8>> = Vec::new();+    let mut files: Vec<FlatEntry> = Vec::new();+    let mut conflicts: Vec<FlatEntry> = Vec::new();+    for entry in &new_entries {+        if !valid_checkout_path(&entry.path) {+            return Err(Error::new(format!(+                "checkout tree validation failed at: {}",+                String::from_utf8_lossy(&entry.path)+            )));+        }+        let mut start = 0;+        for index in 0..entry.path.len() {+            if entry.path[index] == b'/' {+                directories.push(entry.path[start..index].to_vec());+                start = index + 1;+            }+        }+        match entry.kind {+            tree::KIND_CONFLICT => conflicts.push(entry.clone()),+            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {+                files.push(entry.clone())+            }+            _ => {}+        }+    }++    let suffixes = sidecar_suffixes();+    for conflict in &conflicts {+        for suffix in &suffixes {+            let mut full = conflict.path.clone();+            full.extend_from_slice(suffix.as_bytes());+            if tree::find_flat(&old_entries, &full).is_some() {+                return Err(Error::new(format!(+                    "conflict sidecar would overwrite a tracked path: {}",+                    String::from_utf8_lossy(&full)+                )));+            }+        }+    }++    for entry in &old_entries {+        if entry.kind == tree::KIND_CONFLICT {+            delete_sidecars(root, &entry.path)?;+        }+    }++    delete_stale(root, &old_entries, &new_entries)?;+    for directory in &directories {+        ensure_safe_dirs(root, directory)?;+    }+    ensure_safe_dirs(root, b"")?;++    store.preload()?;+    if let Some(progress) = progress+        && (!files.is_empty() || !conflicts.is_empty())+    {+        progress.set_total(files.len() + conflicts.len());+    }+    let write_all = |entry: &FlatEntry| -> Result<()> {+        write_entry(store, root, entry, &attributes)?;+        if let Some(progress) = progress {+            progress.advance(1);+        }+        Ok(())+    };+    let written = if std::thread::available_parallelism().map_or(false, |n| n.get() > 1) {+        files.par_iter().try_for_each(write_all)+    } else {+        files.iter().try_for_each(write_all)+    };+    if let Err(error) = written {+        if let Some(progress) = progress {+            progress.clear();+        }+        return Err(error);+    }+    for conflict in &conflicts {+        if let Err(error) =+            materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)+        {+            if let Some(progress) = progress {+                progress.clear();+            }+            return Err(error);+        }+        if let Some(progress) = progress {+            progress.advance(1);+        }+    }++    save_checkout_cache(root, &new_entries)?;+    if let Some(progress) = progress {+        progress.finish();+    }+    println!("info: checked out {} files", files.len());+    Ok(())+}++pub fn materialize_optional(+    root: &Path,+    store: &mut Store,+    old_root: Option<Id>,+    new_root: Option<Id>,+) -> Result<()> {+    match new_root {+        Some(new_root) => materialize(root, store, old_root, new_root),+        None => {+            let old_entries = match old_root {+                Some(id) => tree::flatten(store, id)?,+                None => Vec::new(),+            };+            delete_stale(root, &old_entries, &[])?;+            clear_stat_cache(root);+            Ok(())+        }+    }+}++pub fn clear_stat_cache(root: &Path) {+    let _ = fs::remove_file(layout::working_copy_dir(root).join("stat-cache"));+}++pub fn path_buf(bytes: &[u8]) -> PathBuf {+    core::path_from_bytes(bytes)+}--- /dev/null+++ b/veins/src/worktree/mod.rs@@ -0,0 +1,5 @@+pub mod attributes;+pub mod checkout;+pub mod pathspec;+pub mod snapshot;+pub mod stat_cache;--- /dev/null+++ b/veins/src/worktree/pathspec.rs@@ -0,0 +1,73 @@+use std::path::Path;++use crate::core;++pub fn cwd_relative(root: &Path) -> Option<String> {+    let current = std::env::current_dir().ok()?;+    let current = std::fs::canonicalize(current).ok()?;+    let root = std::fs::canonicalize(root).ok()?;+    if current == root {+        return Some(String::new());+    }+    let relative = current.strip_prefix(&root).ok()?;+    Some(String::from_utf8_lossy(&core::path_to_bytes(relative)).into_owned())+}++fn normalize_components(input: &str) -> Option<String> {+    let mut components: Vec<&str> = Vec::new();+    let mut start = 0;+    for index in 0..=input.len() {+        let at_end = index == input.len();+        if !at_end && input.as_bytes()[index] != b'/' {+            continue;+        }+        let component = &input[start..index];+        if !component.is_empty() && component != "." {+            if component == ".." {+                if components.is_empty() {+                    return None;+                }+                components.pop();+            } else {+                components.push(component);+            }+        }+        start = index + 1;+    }+    Some(components.join("/"))+}++fn join_relative(base: &str, argument: &str) -> String {+    if base.is_empty() {+        argument.to_string()+    } else if argument.is_empty() {+        base.to_string()+    } else {+        format!("{base}/{argument}")+    }+}++pub fn pathspec_normalize(root: &Path, cwd_rel: &str, argument: &str) -> Option<String> {+    if argument.is_empty() {+        return None;+    }+    if argument.starts_with('/') {+        let normalized = normalize_components(argument)?;+        let mut root_view = core::path_display(root);+        if root_view.starts_with('/') {+            root_view.remove(0);+        }+        if normalized.len() > root_view.len()+            && normalized.starts_with(&root_view)+            && normalized.as_bytes()[root_view.len()] == b'/'+        {+            return Some(normalized[root_view.len() + 1..].to_string());+        }+        return None;+    }+    normalize_components(&join_relative(cwd_rel, argument))+}++pub fn pathspec_has_glob(value: &str) -> bool {+    value.contains('*') || value.contains('?')+}--- /dev/null+++ b/veins/src/worktree/snapshot.rs@@ -0,0 +1,624 @@+use std::path::{Path, PathBuf};++use rayon::prelude::*;++use crate::core::{self, IgnoreRules};+use crate::error::{Error, Result};+use crate::identity;+use crate::object::blob;+use crate::object::commit::{self, Commit, Rename};+use crate::object::id::Id;+use crate::object::path;+use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::Txn;+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::time;+use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText};+use crate::worktree::stat_cache::{self, Cache, CacheEntry};++pub fn run(root: &Path) -> Result<bool> {+    let mut store = Store::open(root)?;+    run_with(root, &mut store)+}++fn name_ends_with(name: &[u8], suffix: &[u8]) -> bool {+    name.len() >= suffix.len() && &name[name.len() - suffix.len()..] == suffix+}++fn sidecar_base(name: &[u8]) -> Option<Vec<u8>> {+    if name_ends_with(name, b".base") && name.len() > 5 {+        return Some(name[..name.len() - 5].to_vec());+    }+    if name_ends_with(name, b".ours") && name.len() > 5 {+        return Some(name[..name.len() - 5].to_vec());+    }+    if name_ends_with(name, b".theirs") && name.len() > 7 {+        return Some(name[..name.len() - 7].to_vec());+    }+    let mut digits = 0;+    while digits < name.len() && name[name.len() - 1 - digits].is_ascii_digit() {+        digits += 1;+    }+    if digits > 0 {+        let stem = &name[..name.len() - digits];+        if stem.len() > 5 && name_ends_with(stem, b".base") {+            return Some(stem[..stem.len() - 5].to_vec());+        }+        if stem.len() > 7 && name_ends_with(stem, b".theirs") {+            return Some(stem[..stem.len() - 7].to_vec());+        }+    }+    None+}++fn join_rel(base: &[u8], name: &[u8]) -> Vec<u8> {+    path::join(base, name)+}++struct BuildState {+    failed: bool,+}++enum PlanKind {+    Conflict,+    Directory,+    Symlink,+    File,+}++struct Plan {+    kind: PlanKind,+    name: Vec<u8>,+    rel: Vec<u8>,+    path: PathBuf,+    info: core::StatInfo,+    target: Option<Id>,+    child_old: Option<Id>,+    executable: bool,+    needs_read: bool,+    trusted: bool,+}++fn build_dir(+    txn: &mut Txn,+    store: &mut Store,+    root: &Path,+    base: &[u8],+    old_tree_id: Option<Id>,+    base_rules: &IgnoreRules,+    attributes: &AttributeRules,+    cache_valid: bool,+    cache: &Cache,+    new_cache: &mut Vec<CacheEntry>,+    now_ms: i64,+    state: &mut BuildState,+    depth: usize,+) -> Result<Option<Id>> {+    if depth > crate::object::MAX_TREE_DEPTH {+        state.failed = true;+        return Ok(None);+    }++    let mut local = base_rules.clone();+    let base_text = String::from_utf8_lossy(base);+    core::ignore_load_file(&mut local, root, &base_text, ".vnexclude");+    core::ignore_load_file(&mut local, root, &base_text, ".gitignore");++    let old_tree = match old_tree_id {+        Some(id) => {+            let body = store.body(id, TYPE_TREE)?.ok_or_else(|| {+                Error::new(format!(+                    "missing tree {} at {}",+                    id.to_hex(),+                    String::from_utf8_lossy(base)+                ))+            })?;+            match tree::decode(&body).ok() {+                Some(tree) => Some(tree),+                None => {+                    state.failed = true;+                    return Ok(None);+                }+            }+        }+        None => None,+    };++    let directory = if base.is_empty() {+        root.to_path_buf()+    } else {+        root.join(core::path_from_bytes(base))+    };+    if !directory.is_dir() {+        state.failed = true;+        return Ok(None);+    }++    let mut names = core::list_directory(&directory);+    names.sort();++    let infos: Vec<Option<core::StatInfo>> = if names.len() >= 256 {+        names+            .par_iter()+            .map(|name| core::stat_path(&directory.join(core::path_from_bytes(name))))+            .collect()+    } else {+        names+            .iter()+            .map(|name| core::stat_path(&directory.join(core::path_from_bytes(name))))+            .collect()+    };++    let mut plans: Vec<Plan> = Vec::with_capacity(names.len());+    for (index, name) in names.iter().enumerate() {+        if name == b".veins" || name == b".git" {+            continue;+        }+        let Some(info) = infos[index] else {+            continue;+        };+        if let Some(tree) = &old_tree+            && let Some(sidecar) = sidecar_base(name)+        {+            if let Some(found) = tree::find_entry(tree, &sidecar) {+                if tree.entries[found].kind == KIND_CONFLICT {+                    continue;+                }+            }+        }+        let relative = join_rel(base, name);+        let relative_text = String::from_utf8_lossy(&relative);+        let is_dir = info.kind == 2;+        let ignored = core::ignore_ignored(&local, &relative_text, is_dir);+        let old_index = old_tree+            .as_ref()+            .and_then(|tree| tree::find_entry(tree, name));+        if let (Some(found), Some(tree)) = (old_index, old_tree.as_ref())+            && tree.entries[found].kind == KIND_CONFLICT+        {+            plans.push(Plan {+                kind: PlanKind::Conflict,+                name: name.clone(),+                rel: relative,+                path: directory.join(core::path_from_bytes(name)),+                info,+                target: Some(tree.entries[found].target),+                child_old: None,+                executable: false,+                needs_read: false,+                trusted: false,+            });+            continue;+        }+        if ignored && old_index.is_none() {+            continue;+        }+        let mut plan = Plan {+            kind: if is_dir {+                PlanKind::Directory+            } else if info.kind == 3 {+                PlanKind::Symlink+            } else {+                PlanKind::File+            },+            name: name.clone(),+            rel: relative,+            path: directory.join(core::path_from_bytes(name)),+            info,+            target: None,+            child_old: None,+            executable: info.executable,+            needs_read: false,+            trusted: false,+        };+        if is_dir {+            if let (Some(found), Some(tree)) = (old_index, old_tree.as_ref()) {+                let entry = &tree.entries[found];+                if entry.kind == KIND_SUBTREE {+                    plan.child_old = Some(entry.target);+                }+            }+        } else if info.kind == 1 {+            if cache_valid+                && let Some(entry) = stat_cache::lookup(cache, &plan.rel)+                && stat_cache::matches(entry, &plan.info, plan.executable, now_ms, cache.written_ms)+            {+                plan.target = Some(entry.target);+                plan.trusted = entry.trusted;+            }+            plan.needs_read = plan.target.is_none();+        }+        plans.push(plan);+    }++    let jobs: Vec<usize> = plans+        .iter()+        .enumerate()+        .filter(|(_, plan)| matches!(plan.kind, PlanKind::File) && plan.needs_read)+        .map(|(index, _)| index)+        .collect();+    let job_bytes: u64 = jobs.iter().map(|index| plans[*index].info.size).sum();++    // Spinning up rayon costs more than it saves for the small, common case;+    // only parallelise once there is enough hashing work to amortise it.+    const PARALLEL_HASH_MIN_BYTES: u64 = 32 * 1024 * 1024;+    let built: Vec<Option<(blob::BlobBuild, bool)>> = if job_bytes >= PARALLEL_HASH_MIN_BYTES {+        jobs.par_iter()+            .map(|index| read_build(&plans[*index], attributes))+            .collect()+    } else {+        jobs.iter()+            .map(|index| read_build(&plans[*index], attributes))+            .collect()+    };++    for (job, build) in jobs.iter().zip(built) {+        let Some((build, trusted)) = build else {+            state.failed = true;+            return Ok(None);+        };+        for object in build.objects {+            txn.add_known(object.kind, object.id, object.body);+        }+        plans[*job].target = Some(build.root);+        plans[*job].trusted = plans[*job].trusted || trusted;+    }++    let mut entries = Vec::with_capacity(plans.len());+    for plan in plans {+        match plan.kind {+            PlanKind::Conflict => {+                if let Some(target) = plan.target {+                    entries.push(TreeEntry {+                        name: plan.name,+                        kind: KIND_CONFLICT,+                        target,+                    });+                }+            }+            PlanKind::Directory => {+                let child = build_dir(+                    txn,+                    store,+                    root,+                    &plan.rel,+                    plan.child_old,+                    &local,+                    attributes,+                    cache_valid,+                    cache,+                    new_cache,+                    now_ms,+                    state,+                    depth + 1,+                )?;+                if state.failed {+                    return Ok(None);+                }+                if let Some(child) = child {+                    entries.push(TreeEntry {+                        name: plan.name,+                        kind: KIND_SUBTREE,+                        target: child,+                    });+                }+            }+            PlanKind::Symlink => {+                let Some(target) = core::path_read_symlink(&plan.path) else {+                    state.failed = true;+                    return Ok(None);+                };+                let Some(build) = read_blob_from_bytes(txn, &target) else {+                    state.failed = true;+                    return Ok(None);+                };+                entries.push(TreeEntry {+                    name: plan.name,+                    kind: tree::KIND_SYMLINK,+                    target: build,+                });+                new_cache.push(CacheEntry {+                    path: plan.rel,+                    size: plan.info.size,+                    mtime_ns: plan.info.mtime_ns,+                    inode: plan.info.inode,+                    kind: plan.info.kind,+                    executable: false,+                    target: build,+                    trusted: false,+                });+            }+            PlanKind::File => {+                let Some(target) = plan.target else {+                    state.failed = true;+                    return Ok(None);+                };+                new_cache.push(CacheEntry {+                    path: plan.rel,+                    size: plan.info.size,+                    mtime_ns: plan.info.mtime_ns,+                    inode: plan.info.inode,+                    kind: plan.info.kind,+                    executable: plan.executable,+                    target,+                    trusted: plan.trusted,+                });+                entries.push(TreeEntry {+                    name: plan.name,+                    kind: if plan.executable {+                        tree::KIND_EXECUTABLE+                    } else {+                        tree::KIND_FILE+                    },+                    target,+                });+            }+        }+    }++    if entries.is_empty() {+        return Ok(None);+    }+    Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))+}++fn read_build(plan: &Plan, attributes: &AttributeRules) -> Option<(blob::BlobBuild, bool)> {+    let data = core::read_file_opt(&plan.path, 0)?;+    let path_attributes = attributes.lookup(&String::from_utf8_lossy(&plan.rel));+    let build = if path_attributes.eol != AttributeEol::None+        && path_attributes.text != AttributeText::Binary+    {+        blob::build(&attributes::normalize_eol(&data, path_attributes.eol))+    } else {+        blob::build(&data)+    };+    let trusted = plan.info.mtime_ns % 1_000_000 != 0+        && core::stat_path(&plan.path).is_some_and(|again| {+            again.size == plan.info.size+                && again.mtime_ns == plan.info.mtime_ns+                && again.inode == plan.info.inode+                && again.kind == plan.info.kind+                && again.executable == plan.info.executable+        });+    Some((build, trusted))+}++fn read_blob_from_bytes(txn: &mut Txn, data: &[u8]) -> Option<Id> {+    let build = blob::build(data);+    for object in build.objects {+        txn.add_known(object.kind, object.id, object.body);+    }+    Some(build.root)+}++pub fn run_with(root: &Path, store: &mut Store) -> Result<bool> {+    let mut txn = Txn::begin(root, store)?;+    let working_copy = ops::working_copy_id(txn.view());+    let old_commit = match working_copy {+        Some(id) => Some(+            graph::load_commit(store, id)?+                .ok_or_else(|| Error::new("missing working-copy commit"))?,+        ),+        None => None,+    };+    let old_tree = old_commit.as_ref().map(|commit| commit.root_tree);+    let old_empty = match &old_commit {+        Some(commit) if commit.parents.len() == 1 => graph::load_commit(store, commit.parents[0])?+            .is_some_and(|parent| parent.root_tree == commit.root_tree),+        _ => false,+    };++    let mut rules = core::ignore_empty();+    core::ignore_load_root(&mut rules, root);+    let cache = stat_cache::load(root);+    let attributes = AttributeRules::load(root);+    let cache_valid = !attributes.changed_since(cache.written_ms);+    let now_ms = time::now_millis();+    let mut new_cache = Vec::new();+    let mut state = BuildState { failed: false };+    let built = build_dir(+        &mut txn,+        store,+        root,+        b"",+        old_tree,+        &rules,+        &attributes,+        cache_valid,+        &cache,+        &mut new_cache,+        now_ms,+        &mut state,+        0,+    )?;+    let new_root = match built {+        Some(id) => id,+        None if !state.failed => txn.add_object(TYPE_TREE, tree::encode(&[])?),+        None => return Err(Error::new("failed to build working-copy tree")),+    };++    if old_tree == Some(new_root) {+        stat_cache::save(root, &mut new_cache, now_ms)?;+        return Ok(false);+    }++    let committer = identity::signature(root);+    let (parents, change_id, message, author, extra) = match &old_commit {+        Some(commit) => (+            commit.parents.clone(),+            commit.change_id,+            commit.message.clone(),+            if old_empty {+                committer.clone()+            } else {+                commit.author.clone()+            },+            commit.extra.clone(),+        ),+        None => (+            Vec::new(),+            identity::random_change_id(),+            Vec::new(),+            committer.clone(),+            Vec::new(),+        ),+    };++    let mut renames = old_commit+        .as_ref()+        .map(|commit| commit.renames.clone())+        .unwrap_or_default();+    if let Some(old) = old_tree {+        let mut detected = detect_renames(store, txn.writer(), old, new_root)?;+        renames.append(&mut detected);+    }+    renames.sort_by(|left, right| {+        left.parent_index+            .cmp(&right.parent_index)+            .then_with(|| left.to_path.cmp(&right.to_path))+    });++    let new_commit = Commit {+        version: 1,+        parents,+        root_tree: new_root,+        change_id,+        author,+        committer,+        message,+        renames_state: commit::RENAMES_RECORDED,+        renames,+        extra,+    };+    let encoded = commit::encode(&new_commit);+    let commit_id = txn.add_object(TYPE_COMMIT, encoded);++    if let Some(old_id) = working_copy {+        ops::remove_head(txn.view_mut(), old_id);+        ops::move_bookmarks(txn.view_mut(), old_id, commit_id);+    }+    if let Some(current) = core::current_bookmark_name(root)+        && ops::find_bookmark(txn.view(), current.as_bytes()).is_some()+    {+        ops::set_bookmark_target(txn.view_mut(), current.as_bytes(), commit_id);+    }+    ops::set_workspace(txn.view_mut(), commit_id);+    ops::rebuild_heads(txn.view_mut());+    txn.finish("snapshot")?;+    store.refresh()?;+    mark_native(root, commit_id)?;+    stat_cache::save(root, &mut new_cache, now_ms)?;+    Ok(true)+}++fn flatten_any(+    store: &mut Store,+    writer: Option<&Writer>,+    tree_id: Id,+    prefix: &mut Vec<u8>,+    output: &mut Vec<FlatEntry>,+    depth: usize,+) -> Result<()> {+    if depth > crate::object::MAX_TREE_DEPTH {+        return Err(Error::new("tree nesting too deep"));+    }+    let body = match writer.and_then(|writer| writer.find_cached(TYPE_TREE, tree_id)) {+        Some(body) => body.to_vec(),+        None => store+            .body(tree_id, TYPE_TREE)?+            .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?,+    };+    let tree = tree::decode(&body)?;+    for entry in tree.entries {+        let old_length = prefix.len();+        if !prefix.is_empty() {+            prefix.push(b'/');+        }+        prefix.extend_from_slice(&entry.name);+        if entry.kind == KIND_SUBTREE {+            flatten_any(store, writer, entry.target, prefix, output, depth + 1)?;+        } else {+            output.push(FlatEntry {+                path: prefix.clone(),+                kind: entry.kind,+                target: entry.target,+            });+        }+        prefix.truncate(old_length);+    }+    Ok(())+}++fn detect_renames(+    store: &mut Store,+    writer: &Writer,+    old_tree: Id,+    new_tree: Id,+) -> Result<Vec<Rename>> {+    if let Some(found) = crate::merge::rename::detect(store, writer, old_tree, new_tree)? {+        return Ok(found);+    }+    let mut old_entries = Vec::new();+    flatten_any(store, None, old_tree, &mut Vec::new(), &mut old_entries, 0)?;+    let mut new_entries = Vec::new();+    flatten_any(+        store,+        Some(writer),+        new_tree,+        &mut Vec::new(),+        &mut new_entries,+        0,+    )?;+    old_entries.sort_by(|left, right| left.path.cmp(&right.path));+    new_entries.sort_by(|left, right| left.path.cmp(&right.path));+    let deleted: Vec<&FlatEntry> = old_entries+        .iter()+        .filter(|entry| tree::find_flat(&new_entries, &entry.path).is_none())+        .collect();+    let added: Vec<&FlatEntry> = new_entries+        .iter()+        .filter(|entry| tree::find_flat(&old_entries, &entry.path).is_none())+        .collect();+    let mut used_old = vec![false; deleted.len()];+    let mut used_new = vec![false; added.len()];+    let mut renames = Vec::new();+    for (old_index, old) in deleted.iter().enumerate() {+        if used_old[old_index] {+            continue;+        }+        for (new_index, new) in added.iter().enumerate() {+            if used_new[new_index] {+                continue;+            }+            if old.target == new.target {+                renames.push(Rename {+                    parent_index: 0,+                    kind: 0,+                    from_path: old.path.clone(),+                    to_path: new.path.clone(),+                });+                used_old[old_index] = true;+                used_new[new_index] = true;+                break;+            }+        }+    }+    Ok(renames)+}++fn mark_native(root: &Path, id: Id) -> Result<()> {+    let path = crate::store::layout::git_map_dir(root).join("native");+    if core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes()) {+        Ok(())+    } else {+        Err(Error::new("cannot write native marker"))+    }+}++pub fn path_to_os_string(bytes: &[u8]) -> PathBuf {+    core::path_from_bytes(bytes)+}--- /dev/null+++ b/veins/src/worktree/stat_cache.rs@@ -0,0 +1,153 @@+use std::fs;+use std::path::Path;++use crate::encoding::{Reader, Writer};+use crate::error::Result;+use crate::object::id::Id;+use crate::store::layout;++#[derive(Clone)]+pub struct CacheEntry {+    pub path: Vec<u8>,+    pub size: u64,+    pub mtime_ns: u64,+    pub inode: u64,+    pub kind: u8,+    pub executable: bool,+    pub target: Id,+    pub trusted: bool,+}++pub struct Cache {+    pub entries: Vec<CacheEntry>,+    pub written_ms: i64,+}++pub fn load(root: &Path) -> Cache {+    let mut cache = Cache {+        entries: Vec::new(),+        written_ms: 0,+    };+    let Ok(data) = fs::read(layout::working_copy_dir(root).join("stat-cache")) else {+        return cache;+    };+    if data.len() < 13 || &data[..4] != b"VST1" {+        return cache;+    }+    let mut reader = Reader::new(&data[4..]);+    let Ok(version) = reader.u8() else {+        return cache;+    };+    if version != 49 && version != 50 {+        return cache;+    }+    let Ok(written) = reader.u64le() else {+        return cache;+    };+    cache.written_ms = written as i64;+    let Ok(count) = reader.varint() else {+        return cache;+    };+    for _ in 0..count {+        let Ok(path) = reader.bytes(65_536) else {+            break;+        };+        let path = path.to_vec();+        let (Ok(size), Ok(mtime), Ok(inode), Ok(kind), Ok(executable)) = (+            reader.u64le(),+            reader.u64le(),+            reader.u64le(),+            reader.u8(),+            reader.u8(),+        ) else {+            break;+        };+        let trusted = if version >= 50 {+            match reader.u8() {+                Ok(value) => value != 0,+                Err(_) => break,+            }+        } else {+            false+        };+        let Ok(target) = reader.id() else {+            break;+        };+        cache.entries.push(CacheEntry {+            path,+            size,+            mtime_ns: mtime,+            inode,+            kind,+            executable: executable != 0,+            target,+            trusted,+        });+    }+    cache+        .entries+        .sort_by(|left, right| left.path.cmp(&right.path));+    cache+}++pub fn save(root: &Path, entries: &mut [CacheEntry], written_ms: i64) -> Result<()> {+    entries.sort_by(|left, right| left.path.cmp(&right.path));+    let mut writer = Writer::with_capacity(4096);+    writer.raw(b"VST1");+    writer.u8(50);+    writer.u64le(written_ms as u64);+    writer.varint(entries.len() as u64);+    for entry in entries {+        writer.bytes(&entry.path);+        writer.u64le(entry.size);+        writer.u64le(entry.mtime_ns);+        writer.u64le(entry.inode);+        writer.u8(entry.kind);+        writer.u8(u8::from(entry.executable));+        writer.u8(u8::from(entry.trusted));+        writer.id(entry.target);+    }+    let path = layout::working_copy_dir(root).join("stat-cache");+    // The stat cache is rebuildable; matching C++, write it without fsync so a+    // cache refresh does not pay two sync barriers.+    crate::core::write_file(&path, &writer.into_vec());+    Ok(())+}++pub fn lookup<'a>(cache: &'a Cache, path: &[u8]) -> Option<&'a CacheEntry> {+    cache+        .entries+        .binary_search_by(|entry| entry.path.as_slice().cmp(path))+        .ok()+        .map(|index| &cache.entries[index])+}++pub fn matches(+    entry: &CacheEntry,+    info: &crate::core::StatInfo,+    executable: bool,+    now_ms: i64,+    written_ms: i64,+) -> bool {+    if entry.size != info.size+        || entry.mtime_ns != info.mtime_ns+        || entry.inode != info.inode+        || entry.executable != executable+        || entry.kind != info.kind+    {+        return false;+    }+    if entry.trusted {+        return true;+    }+    let now_ns = now_ms.saturating_mul(1_000_000);+    let written_ns = written_ms.saturating_mul(1_000_000);+    const WINDOW: i64 = 2_000_000_000;+    if info.mtime_ns as i64 >= written_ns - WINDOW {+        return false;+    }+    if now_ns - (info.mtime_ns as i64) < WINDOW {+        return false;+    }+    true+}--- /dev/null+++ b/veins/tests/end_to_end.rs@@ -0,0 +1,87 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::process::{Command, Output};+use std::time::{SystemTime, UNIX_EPOCH};++struct TempDirectory(PathBuf);++impl TempDirectory {+    fn new() -> Self {+        let stamp = SystemTime::now()+            .duration_since(UNIX_EPOCH)+            .unwrap()+            .as_nanos();+        let path =+            std::env::temp_dir().join(format!("veins-rust-test-{}-{stamp}", std::process::id()));+        fs::create_dir_all(&path).unwrap();+        Self(path)+    }++    fn path(&self) -> &Path {+        &self.0+    }+}++impl Drop for TempDirectory {+    fn drop(&mut self) {+        let _ = fs::remove_dir_all(&self.0);+    }+}++fn vn(directory: &Path, arguments: &[&str]) -> Output {+    Command::new(env!("CARGO_BIN_EXE_vn"))+        .args(arguments)+        .current_dir(directory)+        .env("NO_COLOR", "1")+        .output()+        .unwrap()+}++fn ok(directory: &Path, arguments: &[&str]) -> String {+    let output = vn(directory, arguments);+    assert!(+        output.status.success(),+        "command {:?} failed: {}",+        arguments,+        String::from_utf8_lossy(&output.stderr)+    );+    String::from_utf8(output.stdout).unwrap()+}++#[test]+fn commit_log_checkout_and_bookmarks() {+    let temporary = TempDirectory::new();+    let root = temporary.path();+    ok(root, &["init", "."]);+    fs::write(+        root.join(".veins/config"),+        "user.name = Bench\nuser.email = bench@example.com\n",+    )+    .unwrap();+    fs::write(root.join("a.txt"), "hello\n").unwrap();+    fs::create_dir(root.join("src")).unwrap();+    fs::write(root.join("src/b.txt"), "world\n").unwrap();+    ok(root, &["go", "-m", "first"]);++    fs::write(root.join("a.txt"), "hello again\n").unwrap();+    ok(root, &["go", "-m", "second"]);++    let log = ok(root, &["log", "-no-col-titles"]);+    let first = log+        .lines()+        .find(|line| line.contains("first"))+        .and_then(|line| {+            line.split_whitespace().find(|token| {+                token.len() == 12 && token.bytes().all(|byte| byte.is_ascii_hexdigit())+            })+        })+        .expect("first commit id");+    ok(root, &["co", first]);+    assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "hello\n");++    ok(root, &["status"]);+    ok(root, &["bmk", "set", "main"]);+    let bookmarks = ok(root, &["bmk", "ls"]);+    assert!(bookmarks.contains("main"));+    ok(root, &["self-test"]);+}--- /dev/null+++ b/veins/tests/format_vectors.rs@@ -0,0 +1,154 @@+use veins_rust::object::blob;+use veins_rust::object::chunker::{gear_table, next_chunk};+use veins_rust::object::commit::{self, Commit, Sig};+use veins_rust::object::id::{Id, hash_bytes, object_id};+use veins_rust::object::tree;+use veins_rust::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef};+use veins_rust::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};+use veins_rust::store::pack;++fn hex(bytes: &[u8]) -> String {+    bytes.iter().map(|byte| format!("{byte:02x}")).collect()+}++#[test]+fn published_vectors_match() {+    assert_eq!(+        hex(&hash_bytes(b"")),+        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"+    );+    assert_eq!(gear_table()[0], 0xf8447b379cdadcd5);+    assert_eq!(gear_table()[1], 0xbe63d125aec8ca6d);++    let mut input = vec![0u8; 300_000];+    for (index, byte) in input.iter_mut().enumerate() {+        *byte = ((index * 31 + 34) % 251) as u8;+    }+    let first = next_chunk(&input);+    assert_eq!(first, 262_144);+    assert_eq!(next_chunk(&input[first..]), 37_856);+    assert_eq!(+        object_id(TYPE_CHUNK, &input[..first]).to_hex(),+        "c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458"+    );+    assert_eq!(+        object_id(TYPE_CHUNK, &input[first..]).to_hex(),+        "0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b"+    );+    assert_eq!(+        blob::build(&input).root.to_hex(),+        "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf"+    );++    let empty_tree = vec![0u8];+    let empty_tree_id = object_id(TYPE_TREE, &empty_tree);+    assert_eq!(+        empty_tree_id.to_hex(),+        "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb"+    );+    assert!(tree::decode(&empty_tree).unwrap().entries.is_empty());++    assert_eq!(+        object_id(TYPE_BLOB, &blob::encode_inline(b"hello")).to_hex(),+        "f04a7f7324bbb7279471b5c656c893ee51b62ed9f9bad4c8cb8a289101f68240"+    );+}++#[test]+fn objects_round_trip_and_pack_is_canonical() {+    let change_id = [+        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,+        0x1a,+    ];+    let signature = Sig {+        name: b"Alice".to_vec(),+        email: b"alice@example.com".to_vec(),+        seconds: 1_700_000_000,+        tz_min: 0,+    };+    let empty_tree_id =+        Id::from_hex("8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb").unwrap();+    let commit = Commit {+        version: 1,+        parents: Vec::new(),+        root_tree: empty_tree_id,+        change_id,+        author: signature.clone(),+        committer: signature,+        message: b"initial commit".to_vec(),+        renames_state: commit::RENAMES_RECORDED,+        renames: Vec::new(),+        extra: Vec::new(),+    };+    let commit_body = commit::encode(&commit);+    let commit_id = object_id(veins_rust::object::TYPE_COMMIT, &commit_body);+    assert_eq!(+        commit_id.to_hex(),+        "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299"+    );+    assert_eq!(+        commit::decode(&commit_body).unwrap().message,+        b"initial commit"+    );++    let view = View {+        heads: vec![commit_id],+        bookmarks: vec![Bookmark {+            name: b"main".to_vec(),+            targets: TargetSet {+                adds: vec![Some(commit_id)],+                removes: Vec::new(),+            },+        }],+        tags: Vec::new(),+        remote_refs: Vec::new(),+        working_copies: vec![WorkspaceRef {+            workspace: b"default".to_vec(),+            target: commit_id,+        }],+    };+    let view_body = view::encode_view(&view);+    let view_id = object_id(veins_rust::object::TYPE_VIEW, &view_body);+    assert_eq!(+        view_id.to_hex(),+        "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11"+    );+    assert_eq!(+        view::decode_view(&view_body).unwrap().heads,+        vec![commit_id]+    );++    let operation = Operation {+        parents: Vec::new(),+        view: view_id,+        start: TimeMs {+            millis: 1_700_000_000_000,+            tz_min: 0,+        },+        end: TimeMs {+            millis: 1_700_000_000_000,+            tz_min: 0,+        },+        hostname: b"host".to_vec(),+        username: b"alice".to_vec(),+        description: b"selftest operation".to_vec(),+        tags: Vec::new(),+    };+    let operation_body = view::encode_operation(&operation);+    assert_eq!(+        object_id(veins_rust::object::TYPE_OPERATION, &operation_body).to_hex(),+        "0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426"+    );++    let output = pack::encode(&[RawObject::known(TYPE_TREE, empty_tree_id, vec![0])], 3);+    assert_eq!(+        hex(&output.pack),+        "56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911"+    );+    assert_eq!(output.index.len(), 1136);+    assert_eq!(+        hex(&hash_bytes(&output.index)),+        "d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc"+    );+    pack::decode(output.pack).unwrap();+}--- /dev/null+++ b/veins/tests/integration.rs@@ -0,0 +1,929 @@+use std::fs;+use std::net::TcpListener;+use std::path::{Path, PathBuf};+use std::process::{Command, Output, Stdio};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++struct Fixture {+    root: PathBuf,+    home: PathBuf,+    repo: PathBuf,+}++impl Fixture {+    fn new() -> Self {+        let stamp = SystemTime::now()+            .duration_since(UNIX_EPOCH)+            .unwrap()+            .as_nanos();+        let root = std::env::temp_dir().join(format!(+            "veins-rust-integration-{}-{stamp}",+            std::process::id()+        ));+        let home = root.join("home");+        let repo = root.join("repo");+        fs::create_dir_all(home.join(".config")).unwrap();+        fs::create_dir_all(&repo).unwrap();+        Self { root, home, repo }+    }++    fn command(&self, arguments: &[&str], cwd: &Path) -> Output {+        let owned: Vec<std::ffi::OsString> =+            arguments.iter().map(std::ffi::OsString::from).collect();+        self.command_os(&owned, cwd)+    }++    fn command_os(&self, arguments: &[std::ffi::OsString], cwd: &Path) -> Output {+        Command::new(env!("CARGO_BIN_EXE_vn"))+            .args(arguments)+            .current_dir(cwd)+            .env("HOME", &self.home)+            .env("XDG_CONFIG_HOME", self.home.join(".config"))+            .env("USER", "tester")+            .env("GIT_AUTHOR_NAME", "Tester")+            .env("GIT_AUTHOR_EMAIL", "tester@example.com")+            .env("GIT_COMMITTER_NAME", "Tester")+            .env("GIT_COMMITTER_EMAIL", "tester@example.com")+            .env("NO_COLOR", "1")+            .env("TZ", "UTC")+            .env("VN_EDITOR", "/bin/true")+            .output()+            .unwrap()+    }++    fn vn(&self, arguments: &[&str]) -> String {+        self.vn_in(&self.repo, arguments)+    }++    fn vn_in(&self, cwd: &Path, arguments: &[&str]) -> String {+        let output = self.command(arguments, cwd);+        assert!(+            output.status.success(),+            "{arguments:?} failed: {}{}",+            String::from_utf8_lossy(&output.stdout),+            String::from_utf8_lossy(&output.stderr)+        );+        String::from_utf8_lossy(&output.stdout).into_owned()+    }++    fn fail(&self, arguments: &[&str]) -> String {+        let output = self.command(arguments, &self.repo);+        assert!(+            !output.status.success(),+            "{arguments:?} unexpectedly passed"+        );+        format!(+            "{}{}",+            String::from_utf8_lossy(&output.stdout),+            String::from_utf8_lossy(&output.stderr)+        )+    }++    fn init(&self) {+        self.vn(&["init", "."]);+    }++    fn write(&self, path: &str, content: &str) {+        self.write_in(&self.repo, path, content);+    }++    fn write_in(&self, root: &Path, path: &str, content: &str) {+        let path = root.join(path);+        if let Some(parent) = path.parent() {+            fs::create_dir_all(parent).unwrap();+        }+        fs::write(path, content).unwrap();+    }++    fn read(&self, path: &str) -> String {+        self.read_in(&self.repo, path)+    }++    fn read_in(&self, root: &Path, path: &str) -> String {+        fs::read_to_string(root.join(path)).unwrap()+    }++    fn exists(&self, path: &str) -> bool {+        self.repo.join(path).exists()+    }++    fn commit(&self, message: &str) {+        self.vn(&["go", "-m", message]);+    }++    fn hash(&self, revision: &str) -> String {+        self.vn(&["hash", revision]).trim().to_string()+    }++    fn log_lines(&self) -> Vec<String> {+        self.vn(&["log", "-a", "-no-col-titles"])+            .lines()+            .map(|line| line.to_string())+            .collect()+    }+}++impl Drop for Fixture {+    fn drop(&mut self) {+        let _ = fs::remove_dir_all(&self.root);+    }+}++#[test]+fn init_status_list_and_diff() {+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "alpha\n");+    f.write("dir/b.txt", "beta\n");+    let status = f.vn(&["stat"]);+    assert!(status.contains("A a.txt"));+    assert!(status.contains("A dir/b.txt"));+    let plain = f.vn(&["ls", "-plain"]);+    assert_eq!(+        plain.lines().collect::<Vec<_>>(),+        vec!["a.txt", "dir/b.txt"]+    );+    let diff = f.vn(&["diff"]);+    assert!(diff.contains("+alpha"));+    assert!(diff.contains("+beta"));+}++#[test]+fn status_paths_are_relative_to_cwd() {+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "alpha\n");+    f.write("dir/b.txt", "beta\n");+    f.write("dir/sub/c.txt", "gamma\n");+    let sub = f.repo.join("dir/sub");+    let status = f.vn_in(&sub, &["stat"]);+    assert!(status.contains("A ../../a.txt"));+    assert!(status.contains("A ../b.txt"));+    assert!(status.contains("A c.txt"));+}++#[test]+fn commit_log_show_and_hash() {+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "one\n");+    f.commit("first commit");+    assert!(f.vn(&["stat"]).contains("working copy clean"));+    let rows = f.log_lines();+    assert!(rows.len() >= 2);+    assert!(rows[0].trim_start().starts_with('@'));+    let commit = f+        .log_lines()+        .iter()+        .find(|line| line.contains("first commit"))+        .and_then(|line| line.split_whitespace().nth(1))+        .unwrap()+        .to_string();+    let shown = f.vn(&["show", &commit]);+    assert!(shown.contains("first commit"));+    assert!(shown.contains("+one"));+    assert_eq!(f.hash(&commit).len(), 64);+    let short = f.vn(&["hash", "-short", &commit]).trim().to_string();+    assert_eq!(short, &f.hash(&commit)[..12]);+}++#[test]+fn log_limits_and_revisions() {+    let f = Fixture::new();+    f.init();+    for index in 0..4 {+        f.write("a.txt", &format!("value {index}\n"));+        f.commit(&format!("commit {index}"));+    }+    assert_eq!(f.log_lines().len(), 5);+    assert_eq!(f.vn(&["log", "-l2", "-no-col-titles"]).lines().count(), 2);+    let oldest: Vec<String> = f+        .vn(&["log", "-f2", "-no-col-titles"])+        .lines()+        .map(|line| line.to_string())+        .collect();+    assert!(oldest[0].contains("commit 0"));+    assert!(oldest[1].contains("commit 1"));+    assert_eq!(f.vn(&["log", "l2", "-no-col-titles"]).lines().count(), 2);+    assert!(f.fail(&["log", "-l0"]).contains("error"));+    assert!(f.fail(&["log", "-bad"]).contains("unknown flag"));+}++#[test]+fn checkout_materializes_and_new() {+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "one\n");+    f.vn(&["bmk", "set", "main"]);+    f.commit("first");+    let first = f.hash("main");+    f.write("a.txt", "two\n");+    f.write("later.txt", "later\n");+    f.commit("second");+    let second = f.hash("main");+    f.vn(&["bmk", "set", "main", "-rev", &first]);+    f.vn(&["bmk", "set", "feature", "-rev", &second]);+    f.vn(&["co", "main"]);+    assert_eq!(f.read("a.txt"), "one\n");+    assert!(!f.exists("later.txt"));+    assert!(f.vn(&["stat"]).contains("working copy clean"));+    f.vn(&["co", "feature"]);+    assert_eq!(f.read("a.txt"), "two\n");+    assert!(f.exists("later.txt"));+    f.vn(&["new"]);+    assert!(f.vn(&["stat"]).contains("working copy clean"));+}++#[test]+fn worktree_rename_delete_exclude_remove() {+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "alpha\n");+    f.write("b.txt", "beta\n");+    f.commit("base");+    f.vn(&["mv", "a.txt", "renamed.txt"]);+    assert!(!f.exists("a.txt"));+    assert_eq!(f.read("renamed.txt"), "alpha\n");+    let status = f.vn(&["stat"]);+    assert!(status.contains("D a.txt"));+    assert!(status.contains("A renamed.txt"));+    f.commit("rename");+    fs::remove_file(f.repo.join("b.txt")).unwrap();+    assert!(f.vn(&["stat"]).contains("D b.txt"));+    f.commit("delete");+    f.write("src/a.c", "a\n");+    f.write("src/b.c", "b\n");+    f.write("docs/readme.md", "docs\n");+    assert!(f.vn(&["rm", "src/*.c"]).contains("will be re-added"));+    f.vn(&["ex", "src/*.c"]);+    assert!(f.read(".vnexclude").contains("src/*.c"));+    f.vn(&["rm", "-delete", "docs/readme.md"]);+    assert!(!f.exists("docs/readme.md"));+}++#[test]+fn ignore_rules_and_attributes() {+    let f = Fixture::new();+    f.init();+    f.write(".gitignore", "*.log\nbuild/\n");+    f.write("debug.log", "ignored\n");+    f.write("build/out.bin", "ignored\n");+    f.write("src/.gitignore", "*.tmp\n");+    f.write("src/notes.tmp", "ignored\n");+    f.write("src/main.c", "kept\n");+    let listing = f.vn(&["ls", "-plain"]);+    let tracked: Vec<&str> = listing.lines().collect();+    assert_eq!(tracked, vec![".gitignore", "src/.gitignore", "src/main.c"]);+    f.write(".vnattribs", "*.txt txt eol:lf\n*.cmd txt eol:crlf\n");+    f.write("a.txt", "a\r\nb\r\n");+    f.write("b.cmd", "x\ny\n");+    f.commit("base");+    fs::remove_file(f.repo.join("a.txt")).unwrap();+    fs::remove_file(f.repo.join("b.cmd")).unwrap();+    let base = f+        .vn(&["log", "-a", "-no-col-titles"])+        .lines()+        .find(|line| line.contains("base"))+        .and_then(|line| line.split_whitespace().nth(1))+        .unwrap()+        .to_string();+    f.vn(&["co", &base]);+    assert_eq!(f.read("a.txt"), "a\nb\n");+    assert_eq!(f.read("b.cmd"), "x\r\ny\r\n");+}++#[test]+fn attributes_command() {+    let f = Fixture::new();+    f.init();+    assert!(+        f.vn(&["attr", "gen", "*.ssa", "*.bin"])+            .contains("updated 2")+    );+    assert_eq!(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n");+    f.vn(&["attr", "txt", "*.c"]);+    f.vn(&["attr", "crlf", "*.c"]);+    assert_eq!(+        f.read(".vnattribs"),+        "*.ssa gen\n*.bin gen\n*.c txt eol:crlf\n"+    );+    f.vn(&["attr", "rm", "crlf", "*.c"]);+    assert_eq!(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n*.c txt\n");+    assert!(+        f.fail(&["attr", "gen", "bad pattern"])+            .contains("not a valid attribute pattern")+    );+    assert!(f.vn(&["attr", "ls"]).contains("*.c txt"));+}++#[test]+fn bookmarks_and_tags() {+    let f = Fixture::new();+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    f.vn(&["bmk", "set", "main"]);+    f.write("f.txt", "two\n");+    f.commit("two");+    let listing = f.vn(&["bmk", "ls"]);+    assert!(listing.contains("main"));+    f.vn(&["bmk", "rename", "main", "trunk"]);+    let listing = f.vn(&["bmk", "ls"]);+    assert!(listing.contains("trunk"));+    assert!(!listing.contains("main"));+    assert!(+        f.fail(&["bmk", "rename", "trunk", "trunk"])+            .contains("matches the old name")+    );+    assert!(+        f.fail(&["bmk", "rename", "missing", "other"])+            .contains("no such bookmark")+    );+    f.vn(&["tag", "set", "v0.0.9"]);+    f.vn(&["tag", "set", "v0.0.10"]);+    assert_eq!(f.vn(&["tag", "latest"]).trim(), "v0.0.10");+    f.vn(&["tag", "rm", "v0.0.9"]);+    assert!(f.fail(&["tag", "rm", "missing"]).contains("no such tag"));+}++#[test]+fn config_local_global_and_defaults() {+    let f = Fixture::new();+    f.init();+    f.vn(&["cfg", "test.key", "value"]);+    assert_eq!(f.vn(&["cfg", "test.key"]).trim(), "value");+    f.vn(&["cfg", "-global", "user.name", "Global Tester"]);+    f.vn(&["cfg", "-global", "user.email", "global@example.com"]);+    f.write("f.txt", "content\n");+    f.commit("global identity");+    assert!(f.vn(&["show", "@"]).contains("Global Tester"));+    assert!(f.home.join(".local/config/veins/veins.toml").exists());+    let defaults = f.vn(&["cfg", "-d"]);+    assert!(defaults.contains("log.default_amount = 20"));+    assert!(defaults.contains("rename.autodetect = similar"));+}++#[test]+fn amend_and_undo() {+    let f = Fixture::new();+    f.init();+    f.write("f.txt", "one\n");+    f.commit("one");+    let one = f+        .vn(&["log", "-a", "-no-col-titles"])+        .lines()+        .find(|line| line.contains("one"))+        .and_then(|line| line.split_whitespace().nth(1))+        .unwrap()+        .to_string();+    f.write("f.txt", "two\n");+    f.commit("two");+    f.vn(&["amend", &one, "-m", "one renamed"]);+    assert!(f.vn(&["log"]).contains("one renamed"));+    f.vn(&["undo"]);+    assert!(!f.vn(&["log"]).contains("one renamed"));+}++#[test]+fn merge_clean_and_conflict() {+    let f = Fixture::new();+    f.init();+    f.write("f.txt", "base\n");+    f.vn(&["bmk", "set", "master"]);+    f.commit("base");+    f.vn(&["bmk", "set", "left"]);+    f.vn(&["new", "left"]);+    f.write("f.txt", "left\n");+    f.write("left.txt", "left\n");+    f.commit("left");+    f.vn(&["bmk", "set", "right"]);+    f.vn(&["new", "master"]);+    f.write("f.txt", "right\n");+    f.write("right.txt", "right\n");+    f.commit("right");+    f.vn(&["merge", "left"]);+    assert!(f.vn(&["stat"]).contains("C f.txt"));+    assert!(f.exists("f.txt.base"));+    assert!(f.vn(&["xs", "-porcelain"]).contains("f.txt\ttext\t"));+    f.vn(&["resolve", "-take", "theirs", "f.txt"]);+    assert_eq!(f.read("f.txt"), "left\n");+    assert!(f.vn(&["xs"]).contains("no conflicts"));+    f.commit("resolved");+    assert!(f.vn(&["stat"]).contains("working copy clean"));+    assert!(f.vn(&["fsck"]).contains("fsck: clean"));+}++#[test]+fn rebase_changes_parent_and_rewrites_descendants() {+    let f = Fixture::new();+    f.init();+    f.write("base.txt", "base\n");+    f.vn(&["bmk", "set", "master"]);+    f.commit("base");+    f.vn(&["bmk", "set", "side"]);+    f.vn(&["new", "side"]);+    f.write("one.txt", "one\n");+    f.commit("one");+    f.write("two.txt", "two\n");+    f.commit("two");+    f.vn(&["bmk", "set", "target"]);+    f.vn(&["new", "master"]);+    f.write("target.txt", "target\n");+    f.commit("target");+    let target = f.hash("target");+    f.vn(&["rebase", "-s", "side", "-d", "target"]);+    assert!(f.vn(&["log", "-a"]).contains("two"));+    let _ = target;+}++#[test]+fn error_handling_never_panics() {+    let f = Fixture::new();+    f.init();+    f.write("tracked.txt", "one\n");+    f.commit("initial");+    for command in ["stat", "log", "ls", "diff", "show", "hash", "inf", "fsck"] {+        for token in ["", "-", "--", "-x", "..", "/", "999999999999999999999999"] {+            let output = f.command(&[command, token], &f.repo);+            let text = format!(+                "{}{}",+                String::from_utf8_lossy(&output.stdout),+                String::from_utf8_lossy(&output.stderr)+            );+            assert!(!text.contains("panic"), "{command} {token}: {text}");+        }+    }+}++#[cfg(unix)]+#[test]+fn invalid_utf8_arguments_do_not_panic() {+    use std::ffi::OsString;+    use std::os::unix::ffi::OsStringExt;++    let f = Fixture::new();+    f.init();+    f.write("tracked.txt", "one\n");+    f.commit("initial");+    let cases = [+        vec![+            OsString::from("go"),+            OsString::from("-m"),+            OsString::from_vec(b"caf\xe9 raw \xff\xfe".to_vec()),+        ],+        vec![+            OsString::from("co"),+            OsString::from_vec(b"caf\xe9".to_vec()),+        ],+    ];+    for arguments in cases {+        let output = f.command_os(&arguments, &f.repo);+        let text = format!(+            "{}{}",+            String::from_utf8_lossy(&output.stdout),+            String::from_utf8_lossy(&output.stderr)+        );+        assert!(!text.contains("panicked"), "{arguments:?}: {text}");+        assert!(!text.contains("panic"), "{arguments:?}: {text}");+    }+}++#[test]+fn error_prefix_is_colored() {+    let f = Fixture::new();+    f.init();+    let output = Command::new(env!("CARGO_BIN_EXE_vn"))+        .args(["bmk", "rename", "only"])+        .current_dir(&f.repo)+        .env("HOME", &f.home)+        .env("XDG_CONFIG_HOME", f.home.join(".config"))+        .env("FORCE_COLOR", "1")+        .env_remove("NO_COLOR")+        .output()+        .unwrap();+    assert!(!output.status.success());+    assert!(+        String::from_utf8_lossy(&output.stdout)+            .contains("\x1b[1m\x1b[31merror\x1b[0m: bmk rename requires")+    );+}++#[test]+fn inf_reports_breakdown_with_bars() {+    let f = Fixture::new();+    f.init();+    f.write("main.rs", "fn main() {}\n// two\n");+    f.write("notes.txt", "one\ntwo\nthree\n");+    f.commit("initial");+    let output = f.vn(&["inf"]);+    assert!(output.contains("Repository overview"));+    assert!(output.contains("Languages"));+    assert!(output.contains("Authors"));+    assert!(output.contains("Created"));+    assert!(output.contains("Size"));+    assert!(output.contains(".rs"));+    assert!(output.contains("lines"));+    assert!(output.contains('\u{2588}') || output.contains('\u{2591}'));+    let colored = Command::new(env!("CARGO_BIN_EXE_vn"))+        .args(["inf"])+        .current_dir(&f.repo)+        .env("HOME", &f.home)+        .env("XDG_CONFIG_HOME", f.home.join(".config"))+        .env("FORCE_COLOR", "1")+        .env_remove("NO_COLOR")+        .output()+        .unwrap();+    assert!(+        String::from_utf8_lossy(&colored.stdout).contains("\x1b[1m\x1b[96mRepository overview")+    );+}++#[test]+fn tls_clone_and_push() {+    if Command::new("openssl").arg("version").output().is_err() {+        return;+    }+    let f = Fixture::new();+    let source = f.root.join("source");+    fs::create_dir_all(&source).unwrap();+    f.vn_in(&source, &["init", "."]);+    f.write_in(&source, "a.txt", "hello\n");+    f.vn_in(&source, &["bmk", "set", "master"]);+    f.vn_in(&source, &["go", "-m", "initial"]);+    f.vn_in(&source, &["access", "anonymous", "on"]);++    let cert = f.root.join("cert.pem");+    let key = f.root.join("key.pem");+    let generated = Command::new("openssl")+        .args([+            "req",+            "-x509",+            "-newkey",+            "rsa:2048",+            "-nodes",+            "-keyout",+            key.to_str().unwrap(),+            "-out",+            cert.to_str().unwrap(),+            "-days",+            "1",+            "-subj",+            "/CN=localhost",+            "-addext",+            "subjectAltName=DNS:localhost,IP:127.0.0.1",+        ])+        .stdout(Stdio::null())+        .stderr(Stdio::null())+        .status()+        .unwrap();+    if !generated.success() {+        return;+    }+    let fingerprint = Command::new("openssl")+        .args([+            "x509",+            "-in",+            cert.to_str().unwrap(),+            "-noout",+            "-fingerprint",+            "-sha256",+        ])+        .output()+        .unwrap();+    let pin = String::from_utf8_lossy(&fingerprint.stdout)+        .split('=')+        .nth(1)+        .unwrap_or("")+        .trim()+        .to_string();++    let probe = TcpListener::bind("127.0.0.1:0").unwrap();+    let port = probe.local_addr().unwrap().port();+    drop(probe);+    let mut server = Command::new(env!("CARGO_BIN_EXE_vn"))+        .args([+            "serve",+            "-listen",+            &format!("127.0.0.1:{port}"),+            "-root",+            f.root.to_str().unwrap(),+            "-tls-cert",+            cert.to_str().unwrap(),+            "-tls-key",+            key.to_str().unwrap(),+        ])+        .current_dir(&f.root)+        .env("HOME", &f.home)+        .env("XDG_CONFIG_HOME", f.home.join(".config"))+        .env("NO_COLOR", "1")+        .stdout(Stdio::null())+        .stderr(Stdio::null())+        .spawn()+        .unwrap();++    let address = format!("127.0.0.1:{port}");+    let mut ready = false;+    for _ in 0..100 {+        if std::net::TcpStream::connect(&address).is_ok() {+            ready = true;+            break;+        }+        std::thread::sleep(Duration::from_millis(30));+    }+    assert!(ready, "TLS server did not start");++    let clone = f.root.join("clone");+    let url = format!("veins://localhost:{port}/source");+    f.vn_in(+        &f.root,+        &[+            "clone",+            &url,+            clone.to_str().unwrap(),+            &format!("-pin:{pin}"),+        ],+    );+    assert_eq!(f.read_in(&clone, "a.txt"), "hello\n");+    server.kill().ok();+    server.wait().ok();+}++#[test]+fn protocol_clone_push_fetch_pull() {+    let f = Fixture::new();+    let source = f.root.join("source");+    fs::create_dir_all(&source).unwrap();+    f.vn_in(&source, &["init", "."]);+    f.write_in(&source, "a.txt", "hello\n");+    f.vn_in(&source, &["bmk", "set", "master"]);+    f.vn_in(&source, &["go", "-m", "initial"]);+    f.vn_in(&source, &["access", "anonymous", "on"]);+    let key_output = f.vn_in(&source, &["key", "generate", "integration"]);+    let public_key = key_output+        .lines()+        .find_map(|line| line.strip_prefix("public key: "))+        .unwrap()+        .to_string();+    f.vn_in(+        &source,+        &[+            "access",+            "add",+            "-role",+            "write",+            "-key",+            &public_key,+            "-name",+            "integration",+        ],+    );+    let clone_a = f.root.join("clone-a");+    let clone_b = f.root.join("clone-b");+    let url = format!("file://{}", source.display());+    f.vn_in(&f.root, &["clone", &url, clone_a.to_str().unwrap()]);+    f.vn_in(&f.root, &["clone", &url, clone_b.to_str().unwrap()]);+    assert_eq!(f.read_in(&clone_a, "a.txt"), "hello\n");+    f.vn_in(&clone_a, &["cfg", "remote.o.key", "integration"]);+    f.vn_in(&clone_b, &["cfg", "remote.o.key", "integration"]);+    f.write_in(&clone_a, "b.txt", "from a\n");+    f.vn_in(&clone_a, &["go", "-m", "a change"]);+    f.vn_in(&clone_a, &["push", "o", "master"]);+    f.vn_in(&clone_b, &["pull"]);+    assert_eq!(f.read_in(&clone_b, "b.txt"), "from a\n");+    assert!(f.vn_in(&clone_b, &["whoami", "o"]).contains("role: write"));+}++#[test]+fn git_import_materialize_export() {+    if Command::new("git").arg("--version").output().is_err() {+        return;+    }+    let f = Fixture::new();+    let git_repo = f.root.join("gitrepo");+    fs::create_dir_all(&git_repo).unwrap();+    for arguments in [+        vec!["init", "-q"],+        vec!["config", "user.name", "Tester"],+        vec!["config", "user.email", "tester@example.com"],+    ] {+        assert!(+            Command::new("git")+                .args(&arguments)+                .current_dir(&git_repo)+                .status()+                .unwrap()+                .success()+        );+    }+    fs::write(git_repo.join("a.txt"), "one\ntwo\n").unwrap();+    for arguments in [vec!["add", "a.txt"], vec!["commit", "-qm", "git one"]] {+        assert!(+            Command::new("git")+                .args(&arguments)+                .current_dir(&git_repo)+                .status()+                .unwrap()+                .success()+        );+    }+    let vn_repo = f.root.join("vnrepo");+    f.vn_in(+        &f.root,+        &[+            "init",+            vn_repo.to_str().unwrap(),+            &format!("-git-import:{}", git_repo.display()),+        ],+    );+    assert!(f.vn_in(&vn_repo, &["log", "-a"]).contains("git one"));+    assert_eq!(f.read_in(&vn_repo, "a.txt"), "one\ntwo\n");+    f.write_in(&vn_repo, "b.txt", "native\n");+    f.vn_in(&vn_repo, &["go", "-m", "native commit"]);+    f.vn_in(&vn_repo, &["git", "export"]);+    let output = Command::new("git")+        .args([+            "--git-dir",+            vn_repo.join(".veins/git").to_str().unwrap(),+            "log",+            "--format=%s",+            "--all",+        ])+        .output()+        .unwrap();+    assert!(String::from_utf8_lossy(&output.stdout).contains("native commit"));+}++#[test]+fn merge_multiple_parents_and_resolve_current() {+    let f = Fixture::new();+    f.init();+    f.write("f.txt", "base\n");+    f.vn(&["bmk", "set", "master"]);+    f.commit("base");+    f.vn(&["bmk", "set", "left"]);+    f.vn(&["new", "left"]);+    f.write("left.txt", "left\n");+    f.commit("left");+    f.vn(&["bmk", "set", "right"]);+    f.vn(&["new", "master"]);+    f.write("right.txt", "right\n");+    f.commit("right");+    f.vn(&["merge", "left", "right"]);+    let metadata = f.vn(&["show", "@"]);+    let parents = metadata+        .lines()+        .find_map(|line| line.strip_prefix("parents  "))+        .unwrap();+    assert_eq!(parents.split_whitespace().count(), 3);+}++#[test]+fn rebase_conflict_produces_conflicted_commit() {+    let f = Fixture::new();+    f.init();+    f.write("f.txt", "base\n");+    f.vn(&["bmk", "set", "master"]);+    f.commit("base");+    f.vn(&["bmk", "set", "left"]);+    f.vn(&["new", "left"]);+    f.write("f.txt", "left\n");+    f.commit("left");+    f.vn(&["bmk", "set", "right"]);+    f.vn(&["new", "master"]);+    f.write("f.txt", "right\n");+    f.commit("right");+    f.vn(&["rebase", "-s", "left", "-d", "right"]);+    assert!(+        f.log_lines()+            .iter()+            .any(|line| line.contains("(conflicted)"))+    );+    f.vn(&["co", "left"]);+    assert!(f.vn(&["xs"]).contains("f.txt"));+    assert!(f.exists("f.txt.base"));+}++#[test]+fn git_mirror_push_and_tag_prune() {+    if Command::new("git").arg("--version").output().is_err() {+        return;+    }+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "one\n");+    f.vn(&["bmk", "set", "master"]);+    f.commit("first");+    let mirror = f.root.join("mirror.git");+    fs::create_dir_all(&mirror).unwrap();+    assert!(+        Command::new("git")+            .args(["init", "-q", "--bare", mirror.to_str().unwrap()])+            .status()+            .unwrap()+            .success()+    );+    f.vn(&["git", "remote", "add", "mirror", mirror.to_str().unwrap()]);+    assert!(+        f.vn(&["git", "mirror", "psh"])+            .contains("mirrored 1 bookmark(s)")+    );+    f.vn(&["tag", "set", "v0.0.1"]);+    f.vn(&["tag", "set", "v0.0.2"]);+    f.vn(&["git", "mirror", "pt", "v0.0.1", "mirror"]);+    let tags = Command::new("git")+        .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])+        .output()+        .unwrap();+    let tags = String::from_utf8_lossy(&tags.stdout);+    assert!(tags.contains("refs/tags/v0.0.1"));+    assert!(!tags.contains("refs/tags/v0.0.2"));+    f.vn(&["git", "mirror", "push", "mirror"]);+    f.vn(&["tag", "rm", "v0.0.2"]);+    f.vn(&["git", "mirror", "push", "mirror"]);+    let tags = Command::new("git")+        .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])+        .output()+        .unwrap();+    assert!(String::from_utf8_lossy(&tags.stdout).contains("refs/tags/v0.0.2"));+    f.vn(&["git", "mirror", "push", "mirror", "-prune"]);+    let tags = Command::new("git")+        .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])+        .output()+        .unwrap();+    assert!(!String::from_utf8_lossy(&tags.stdout).contains("refs/tags/v0.0.2"));+    assert!(+        f.fail(&["git", "mirror", "pt", "missing", "mirror"])+            .contains("unknown tag")+    );+}++#[test]+fn lazy_checkout_of_old_commit() {+    let f = Fixture::new();+    let source = f.root.join("source");+    fs::create_dir_all(&source).unwrap();+    f.vn_in(&source, &["init", "."]);+    for index in 1..=20 {+        f.write_in(&source, &format!("f{index}.txt"), &format!("old {index}\n"));+    }+    f.write_in(&source, "a.txt", "hello\n");+    f.vn_in(&source, &["bmk", "set", "master"]);+    f.vn_in(&source, &["go", "-m", "initial"]);+    f.vn_in(&source, &["access", "anonymous", "on"]);+    for index in 1..=20 {+        f.write_in(&source, &format!("f{index}.txt"), &format!("new {index}\n"));+    }+    f.write_in(&source, "a.txt", "updated\n");+    f.vn_in(&source, &["go", "-m", "second"]);+    let first = f+        .vn_in(&source, &["log", "-a", "-no-col-titles"])+        .lines()+        .find(|line| line.contains("initial"))+        .and_then(|line| line.split_whitespace().nth(1))+        .map(|value| value.trim_start_matches('@').to_string())+        .unwrap();+    let clone = f.root.join("clone");+    f.vn_in(+        &f.root,+        &[+            "clone",+            &format!("file://{}", source.display()),+            clone.to_str().unwrap(),+        ],+    );+    f.vn_in(&clone, &["co", &first]);+    assert_eq!(f.read_in(&clone, "a.txt"), "hello\n");+    assert_eq!(f.read_in(&clone, "f1.txt"), "old 1\n");+    assert!(f.vn_in(&clone, &["stat"]).contains("working copy clean"));+}++#[test]+fn corrupt_repository_does_not_panic() {+    let f = Fixture::new();+    f.init();+    f.write("a.txt", "one\n");+    f.commit("first");+    fs::write(f.repo.join(".veins/config"), b"bad\0line\n").unwrap();+    let pack = fs::read_dir(f.repo.join(".veins/store/packs"))+        .unwrap()+        .flatten()+        .map(|entry| entry.path())+        .find(|path| path.extension().and_then(|value| value.to_str()) == Some("vpack"));+    if let Some(pack) = pack {+        let mut data = fs::read(&pack).unwrap();+        if !data.is_empty() {+            let middle = data.len() / 2;+            data[middle] ^= 0xff;+            fs::write(&pack, data).unwrap();+        }+    }+    for command in [&["stat"][..], &["log"], &["fsck"], &["show"], &["ls"]] {+        let output = f.command(command, &f.repo);+        let text = format!(+            "{}{}",+            String::from_utf8_lossy(&output.stdout),+            String::from_utf8_lossy(&output.stderr)+        );+        assert!(!text.contains("panic"), "{command:?}: {text}");+    }+}--- a/veinsrs/.gitignore+++ /dev/null@@ -1,1 +0,0 @@-/target/--- a/veinsrs/Cargo.lock+++ /dev/null@@ -1,467 +0,0 @@-# This file is automatically @generated by Cargo.-# It is not intended for manual editing.-version = 4--[[package]]-name = "arrayvec"-version = "0.7.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"--[[package]]-name = "bitflags"-version = "2.13.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"--[[package]]-name = "blake3"-version = "1.8.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "64c0e36294adc8db531500e3f2b8ec75c4af9177271e9c6d33f93609d56e57cd"-dependencies = [- "arrayvec",- "cc",- "cfg-if",- "constant_time_eq",- "cpufeatures",-]--[[package]]-name = "cc"-version = "1.12.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66"-dependencies = [- "find-msvc-tools",- "jobserver",- "libc",- "shlex",-]--[[package]]-name = "cfg-if"-version = "1.0.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"--[[package]]-name = "constant_time_eq"-version = "0.6.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7"-dependencies = [- "rustversion",-]--[[package]]-name = "core-foundation"-version = "0.10.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"-dependencies = [- "core-foundation-sys",- "libc",-]--[[package]]-name = "core-foundation-sys"-version = "0.8.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"--[[package]]-name = "cpufeatures"-version = "0.3.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"-dependencies = [- "libc",-]--[[package]]-name = "crossbeam-deque"-version = "0.8.8"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"-dependencies = [- "crossbeam-epoch",- "crossbeam-utils",-]--[[package]]-name = "crossbeam-epoch"-version = "0.9.21"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"-dependencies = [- "crossbeam-utils",-]--[[package]]-name = "crossbeam-utils"-version = "0.8.23"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"--[[package]]-name = "either"-version = "1.19.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"--[[package]]-name = "find-msvc-tools"-version = "0.1.16"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"--[[package]]-name = "getrandom"-version = "0.2.17"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"-dependencies = [- "cfg-if",- "libc",- "wasi",-]--[[package]]-name = "getrandom"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"-dependencies = [- "cfg-if",- "libc",- "r-efi",-]--[[package]]-name = "jobserver"-version = "0.1.35"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"-dependencies = [- "getrandom 0.4.3",- "libc",-]--[[package]]-name = "libc"-version = "0.2.191"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"--[[package]]-name = "once_cell"-version = "1.21.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"--[[package]]-name = "openssl-probe"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"--[[package]]-name = "pkg-config"-version = "0.3.34"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"--[[package]]-name = "r-efi"-version = "6.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"--[[package]]-name = "rayon"-version = "1.12.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"-dependencies = [- "either",- "rayon-core",-]--[[package]]-name = "rayon-core"-version = "1.13.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"-dependencies = [- "crossbeam-deque",- "crossbeam-utils",-]--[[package]]-name = "ring"-version = "0.17.14"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"-dependencies = [- "cc",- "cfg-if",- "getrandom 0.2.17",- "libc",- "untrusted",- "windows-sys 0.52.0",-]--[[package]]-name = "rustls"-version = "0.23.45"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"-dependencies = [- "once_cell",- "ring",- "rustls-pki-types",- "rustls-webpki",- "subtle",- "zeroize",-]--[[package]]-name = "rustls-native-certs"-version = "0.8.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"-dependencies = [- "openssl-probe",- "rustls-pki-types",- "schannel",- "security-framework",-]--[[package]]-name = "rustls-pki-types"-version = "1.15.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"-dependencies = [- "zeroize",-]--[[package]]-name = "rustls-webpki"-version = "0.103.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"-dependencies = [- "ring",- "rustls-pki-types",- "untrusted",-]--[[package]]-name = "rustversion"-version = "1.0.23"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"--[[package]]-name = "schannel"-version = "0.1.30"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"-dependencies = [- "windows-sys 0.61.2",-]--[[package]]-name = "security-framework"-version = "3.7.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"-dependencies = [- "bitflags",- "core-foundation",- "core-foundation-sys",- "libc",- "security-framework-sys",-]--[[package]]-name = "security-framework-sys"-version = "2.17.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"-dependencies = [- "core-foundation-sys",- "libc",-]--[[package]]-name = "shlex"-version = "2.0.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"--[[package]]-name = "subtle"-version = "2.6.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"--[[package]]-name = "untrusted"-version = "0.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"--[[package]]-name = "veins-rust"-version = "0.1.0"-dependencies = [- "blake3",- "libc",- "rayon",- "ring",- "rustls",- "rustls-native-certs",- "rustls-pki-types",- "webpki-roots",- "zstd",-]--[[package]]-name = "wasi"-version = "0.11.1+wasi-snapshot-preview1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"--[[package]]-name = "webpki-roots"-version = "1.0.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"-dependencies = [- "rustls-pki-types",-]--[[package]]-name = "windows-link"-version = "0.2.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"--[[package]]-name = "windows-sys"-version = "0.52.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"-dependencies = [- "windows-targets",-]--[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]--[[package]]-name = "windows-targets"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"-dependencies = [- "windows_aarch64_gnullvm",- "windows_aarch64_msvc",- "windows_i686_gnu",- "windows_i686_gnullvm",- "windows_i686_msvc",- "windows_x86_64_gnu",- "windows_x86_64_gnullvm",- "windows_x86_64_msvc",-]--[[package]]-name = "windows_aarch64_gnullvm"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"--[[package]]-name = "windows_aarch64_msvc"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"--[[package]]-name = "windows_i686_gnu"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"--[[package]]-name = "windows_i686_gnullvm"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"--[[package]]-name = "windows_i686_msvc"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"--[[package]]-name = "windows_x86_64_gnu"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"--[[package]]-name = "windows_x86_64_gnullvm"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"--[[package]]-name = "windows_x86_64_msvc"-version = "0.52.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"--[[package]]-name = "zeroize"-version = "1.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"--[[package]]-name = "zstd"-version = "0.13.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b04655dc7bf4abd8ebe23dac6bef20fceea52a29ad19e37a4101b3951d7e8b45"-dependencies = [- "zstd-safe",-]--[[package]]-name = "zstd-safe"-version = "7.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "df2575690b2a3eccad509fe7898cdde32a5afca06a06449ff4dcfb318c7b7281"-dependencies = [- "zstd-sys",-]--[[package]]-name = "zstd-sys"-version = "2.2.0+zstd.1.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160"-dependencies = [- "cc",- "pkg-config",-]--- a/veinsrs/Cargo.toml+++ /dev/null@@ -1,25 +0,0 @@-[package]-name = "veins-rust"-version = "0.1.0"-edition = "2024"-license = "MIT"--[[bin]]-name = "vn"-path = "src/main.rs"--[dependencies]-blake3 = "1.8"-libc = "0.2"-rayon = "1.12"-ring = "0.17"-rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }-rustls-native-certs = "0.8"-rustls-pki-types = { version = "1", features = ["std"] }-webpki-roots = "1"-zstd = "0.13"--[profile.release]-opt-level = 3-lto = false-codegen-units = 16--- a/veinsrs/src/cli/args.rs+++ /dev/null@@ -1,40 +0,0 @@-use crate::error::{Error, Result};--pub fn is_flag(argument: &str) -> bool {-    argument.starts_with('-') && argument != "-"-}--pub fn join(parts: &[String]) -> String {-    parts.join(" ")-}--pub fn message_is_blank(parts: &[String]) -> bool {-    parts-        .iter()-        .flat_map(|part| part.bytes())-        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))-}--pub fn parse_message(args: &[String], start: usize) -> Result<Vec<String>> {-    let mut parts = Vec::new();-    let mut end_flags = false;-    let mut index = start;-    while index < args.len() {-        let argument = &args[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-m" || argument == "-message") {-            index += 1;-            if index >= args.len() {-                return Err(Error::new(format!("{argument} requires a message")));-            }-            parts.push(args[index].clone());-        } else if !end_flags && is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            parts.push(argument.clone());-        }-        index += 1;-    }-    Ok(parts)-}--- a/veinsrs/src/cli/commands/bookmark.rs+++ /dev/null@@ -1,222 +0,0 @@-use std::path::Path;--use crate::cli::args;-use crate::error::{Error, Result};-use crate::object::view::Bookmark;-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::snapshot;--pub fn run(arguments: &[String]) -> Result<u8> {-    let Some(subcommand) = arguments.first() else {-        return Err(Error::new("bmk requires a subcommand"));-    };-    let rest = &arguments[1..];-    match subcommand.as_str() {-        "set" | "mv" => set(rest),-        "ls" => list(rest),-        "rm" => remove(rest),-        _ => Err(Error::new(format!("unknown bmk subcommand: {subcommand}"))),-    }-}--fn valid_bookmark_name(name: &str) -> bool {-    if name.is_empty() {-        return false;-    }-    let bytes = name.as_bytes();-    if bytes[0] == b'-' || bytes[0] == b'/' || bytes[0] == b'.' {-        return false;-    }-    if bytes[bytes.len() - 1] == b'/' || bytes[bytes.len() - 1] == b'.' {-        return false;-    }-    for byte in bytes {-        if *byte == 0 || *byte == b' ' || *byte < 32 || *byte == 127 {-            return false;-        }-        if matches!(*byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\') {-            return false;-        }-    }-    if name.contains("..") || name.contains("@{") || name.contains("//") {-        return false;-    }-    if name == "@" || name.ends_with(".lock") {-        return false;-    }-    true-}--fn set(arguments: &[String]) -> Result<u8> {-    let mut name = String::new();-    let mut revision = String::new();-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && args::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if name.is_empty() {-            name = argument.clone();-        } else if revision.is_empty() {-            revision = argument.clone();-        } else {-            return Err(Error::new("bmk set accepts a name and one revision"));-        }-        index += 1;-    }-    if name.is_empty() {-        return Err(Error::new("bmk set requires a name"));-    }-    if !valid_bookmark_name(&name) {-        return Err(Error::new(format!("invalid bookmark name: {name}")));-    }--    let root = layout::discover(Path::new("."))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?-        .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;--    let mut changed = true;-    match ops::find_bookmark(txn.view(), name.as_bytes()) {-        Some(existing) => {-            let bookmark = &mut txn.view_mut().bookmarks[existing];-            if ops::bookmark_points_at(bookmark, target) {-                changed = false;-            } else {-                bookmark.targets.adds = vec![Some(target)];-                bookmark.targets.removes.clear();-            }-        }-        None => {-            txn.view_mut().bookmarks.push(Bookmark {-                name: name.as_bytes().to_vec(),-                targets: crate::object::view::TargetSet {-                    adds: vec![Some(target)],-                    removes: Vec::new(),-                },-            });-        }-    }--    if !changed {-        println!("info: bookmark {name} is already at {}", target.short());-        return Ok(0);-    }-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("bookmark set {name}"))?;-    println!("info: bookmark {name} set to {}", target.short());-    Ok(0)-}--fn list(arguments: &[String]) -> Result<u8> {-    let mut column_titles = true;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && argument == "-no-col-titles" {-            column_titles = false;-        } else if !end_flags && args::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            return Err(Error::new("bmk ls takes no operands"));-        }-    }--    let root = layout::discover(Path::new("."))?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let working_copy = ops::working_copy_id(&view);-    let mut name_width = 8;-    for bookmark in &view.bookmarks {-        name_width = name_width.max(bookmark.name.len());-    }-    if column_titles {-        println!(-            "{:<name_width$}  {:<12}  {:<8}  Target",-            "Bookmark",-            "Commit",-            "Change",-            name_width = name_width-        );-    }-    for bookmark in &view.bookmarks {-        let name = String::from_utf8_lossy(&bookmark.name);-        let Some(target) = bookmark.targets.adds.first().copied().flatten() else {-            println!(-                "{:<name_width$}  {:<12}  {:<8}  (missing)",-                name,-                "<missing>",-                "",-                name_width = name_width-            );-            continue;-        };-        let change = match graph::load_commit(&mut store, target)? {-            Some(commit) => graph::base32_encode(commit.change_id)[..8].to_string(),-            None => String::new(),-        };-        let marker = if working_copy == Some(target) {-            "@"-        } else {-            ""-        };-        println!(-            "{:<name_width$}  {:<12}  {:<8}  {marker}",-            name,-            target.short(),-            change,-            name_width = name_width-        );-    }-    if view.bookmarks.is_empty() {-        println!("info: no bookmarks");-    }-    Ok(0)-}--fn remove(arguments: &[String]) -> Result<u8> {-    let mut name = String::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && args::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if !name.is_empty() {-            return Err(Error::new("bmk rm accepts exactly one name"));-        } else {-            name = argument.clone();-        }-    }-    if name.is_empty() {-        return Err(Error::new("bmk rm requires a name"));-    }-    let root = layout::discover(Path::new("."))?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let Some(existing) = ops::find_bookmark(txn.view(), name.as_bytes()) else {-        return Err(Error::new(format!("no such bookmark: {name}")));-    };-    txn.view_mut().bookmarks.remove(existing);-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("bookmark delete {name}"))?;-    println!("info: deleted bookmark {name}");-    Ok(0)-}--- a/veinsrs/src/cli/commands/checkout.rs+++ /dev/null@@ -1,23 +0,0 @@-use std::path::Path;--use crate::cli::args;-use crate::error::Result;-use crate::store::layout;-use crate::worktree::checkout;--pub fn run(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && args::is_flag(argument) {-            return Err(crate::Error::new(format!("unknown flag: {argument}")));-        } else if revision.is_empty() {-            revision = argument.clone();-        }-    }-    let root = layout::discover(Path::new("."))?;-    checkout::run(&root, &revision)?;-    Ok(0)-}--- a/veinsrs/src/cli/commands/commit.rs+++ /dev/null@@ -1,109 +0,0 @@-use std::path::Path;--use crate::cli::args;-use crate::error::{Error, Result};-use crate::identity;-use crate::object::TYPE_COMMIT;-use crate::object::commit::{self, Commit};-use crate::object::id::Id;-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::snapshot;--enum Outcome {-    Nothing,-    Described,-}--pub fn run(arguments: &[String]) -> Result<u8> {-    let parts = args::parse_message(arguments, 0)?;-    if args::message_is_blank(&parts) {-        return Err(Error::new("commit requires a non-empty message (-message)"));-    }-    let message = args::join(&parts);-    let root = layout::discover(Path::new("."))?;-    let mut store = Store::open(&root)?;--    if matches!(-        describe(&root, &mut store, &message, true)?,-        Outcome::Nothing-    ) {-        return Ok(0);-    }-    create_empty(&root, &mut store)?;-    Ok(0)-}--fn describe(-    root: &Path,-    store: &mut Store,-    message: &str,-    require_changes: bool,-) -> Result<Outcome> {-    snapshot::run_with(root, store)?;-    let mut txn = Txn::begin(root, store)?;-    let working_copy =-        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;-    let loaded = graph::load_commit(store, working_copy)?-        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;-    let changed = graph::has_changes(store, &loaded)?;-    let same_message = loaded.message == message.as_bytes();-    if !changed && (require_changes || same_message) {-        if require_changes {-            println!("info: nothing to commit, working copy clean");-        }-        return Ok(Outcome::Nothing);-    }--    let signature = identity::signature(root);-    let mut updated = loaded;-    updated.committer = signature;-    updated.message = message.as_bytes().to_vec();-    let encoded = commit::encode(&updated);-    let new_id = txn.add_object(TYPE_COMMIT, encoded);-    ops::remove_head(txn.view_mut(), working_copy);-    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    txn.finish("describe")?;-    store.refresh()?;-    mark_native(root, new_id)?;-    Ok(Outcome::Described)-}--fn create_empty(root: &Path, store: &mut Store) -> Result<()> {-    let mut txn = Txn::begin(root, store)?;-    let working_copy =-        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;-    let loaded = graph::load_commit(store, working_copy)?-        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;-    let signature = identity::signature(root);-    let new_commit = Commit {-        version: 1,-        parents: vec![working_copy],-        root_tree: loaded.root_tree,-        change_id: identity::random_change_id(),-        author: signature.clone(),-        committer: signature,-        message: Vec::new(),-        renames_state: commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    let encoded = commit::encode(&new_commit);-    let new_id = txn.add_object(TYPE_COMMIT, encoded);-    ops::remove_head(txn.view_mut(), working_copy);-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    txn.finish("new")?;-    mark_native(root, new_id)?;-    Ok(())-}--fn mark_native(root: &Path, id: Id) -> Result<()> {-    let path = layout::git_map_dir(root).join("native");-    layout::append_file(&path, format!("{}\n", id.to_hex()).as_bytes())-}--- a/veinsrs/src/cli/commands/init.rs+++ /dev/null@@ -1,66 +0,0 @@-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::store::layout;--pub fn run(arguments: &[String]) -> Result<u8> {-    let mut path = ".".to_string();-    let mut source = None;-    let mut remote_url = String::new();-    let mut remote_name = "o".to_string();-    let mut remote_name_given = false;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && let Some(value) = argument.strip_prefix("-git-import:") {-            if value.is_empty() {-                return Err(Error::new("-git-import: requires a path"));-            }-            source = Some(value.to_string());-        } else if !end_flags && let Some(value) = argument.strip_prefix("-remote:") {-            if value.is_empty() {-                return Err(Error::new("-remote: requires a URL"));-            }-            remote_url = value.to_string();-        } else if !end_flags && let Some(value) = argument.strip_prefix("-remote-name:") {-            if value.is_empty() {-                return Err(Error::new("-remote-name: requires a name"));-            }-            remote_name = value.to_string();-            remote_name_given = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            path = argument.clone();-        }-    }-    if remote_name_given && remote_url.is_empty() {-        return Err(Error::new("-remote-name: requires -remote:<url>"));-    }-    if source.is_none() && !remote_url.is_empty() {-        return Err(Error::new("-remote: requires -git-import:<path>"));-    }-    let root = layout::init(Path::new(&path)).map_err(|_| Error::new("init failed"))?;-    println!("info: initialized veins repository at {}", root.display());-    if let Some(source) = source {-        let prepared = crate::git::prepare_mirror(&root, &source);-        if prepared != 0 {-            if prepared == 2 {-                return Err(Error::new(format!(-                    "-git-import: {source} is not a git repository root (expected the directory containing .git)"-                )));-            }-            return Err(Error::new(format!(-                "cannot prepare git mirror from {source} (code {prepared})"-            )));-        }-        let imported = crate::git::import(&root);-        if imported != 0 {-            return Ok(1);-        }-        crate::git::configure_remote(&root, &remote_url, &remote_name);-    }-    Ok(0)-}--- a/veinsrs/src/cli/commands/log.rs+++ /dev/null@@ -1,139 +0,0 @@-use std::path::Path;--use crate::cli::args;-use crate::error::Result;-use crate::object::id::Id;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::time;-use crate::worktree::snapshot;--struct Record {-    id: Id,-    change: String,-    seconds: i64,-    message: Vec<u8>,-    author: Vec<u8>,-}--pub fn run(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut column_titles = true;-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(crate::Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && argument == "-no-col-titles" {-            column_titles = false;-        } else if !end_flags && args::is_flag(argument) {-            return Err(crate::Error::new(format!("unknown flag: {argument}")));-        } else {-            revision = argument.clone();-        }-        index += 1;-    }--    let root = layout::discover(Path::new("."))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let view = ops::current_view(&root, &mut store)?-        .ok_or_else(|| crate::Error::new("no operation state"))?;-    let working_copy = ops::working_copy_id(&view);--    let ids = if revision.is_empty() || revision == "all()" {-        let roots = graph::view_roots(&view);-        graph::collect_commits(&mut store, &roots)?-    } else if let Some(target) = graph::resolve_revision(&mut store, &view, &revision)? {-        graph::collect_commits(&mut store, &[target])?-    } else {-        Vec::new()-    };--    let mut records = Vec::new();-    for id in ids {-        let Some(commit) = graph::load_commit(&mut store, id)? else {-            continue;-        };-        records.push(Record {-            id,-            change: graph::base32_encode(commit.change_id),-            seconds: commit.committer.seconds,-            message: commit.message,-            author: commit.author.name,-        });-    }-    records.sort_by(|left, right| right.seconds.cmp(&left.seconds));--    let change_ids: Vec<String> = records.iter().map(|record| record.change.clone()).collect();-    let mut change_width = 6;-    let mut author_width = 6;-    for (index, record) in records.iter().enumerate() {-        change_width = change_width.max(graph::short_change_id(&change_ids, index).len());-        author_width = author_width.max(record.author.len());-    }--    if column_titles {-        println!(-            "  {:<12}  {:<change_width$}  {:<19}  {:<author_width$}  Message",-            "Commit",-            "Change",-            "Date",-            "Author",-            change_width = change_width,-            author_width = author_width,-        );-    }--    for (index, record) in records.iter().enumerate() {-        let marker = if working_copy == Some(record.id) {-            "@"-        } else {-            " "-        };-        let change = graph::short_change_id(&change_ids, index);-        let date = time::format_utc(record.seconds);-        let message = first_line(&record.message);-        print!(-            "{marker} {:<12}  {:<change_width$}  {:<19}  {:<author_width$}  {}",-            record.id.short(),-            change,-            date,-            String::from_utf8_lossy(&record.author),-            String::from_utf8_lossy(message),-            change_width = change_width,-            author_width = author_width,-        );-        for name in ops::bookmark_names(&view, record.id) {-            print!(" [{}]", String::from_utf8_lossy(&name));-        }-        for name in ops::tag_names(&view, record.id) {-            print!(" <{}>", String::from_utf8_lossy(&name));-        }-        if change_ids-            .iter()-            .enumerate()-            .any(|(other, value)| other != index && *value == record.change)-        {-            print!(" (divergent)");-        }-        println!();-    }-    Ok(0)-}--fn first_line(message: &[u8]) -> &[u8] {-    match message.iter().position(|byte| *byte == b'\n') {-        Some(position) => &message[..position],-        None => message,-    }-}--- a/veinsrs/src/cli/commands/mod.rs+++ /dev/null@@ -1,8 +0,0 @@-pub mod bookmark;-pub mod checkout;-pub mod commit;-pub mod init;-pub mod log;-pub mod selftest;-pub mod status;-pub mod version;--- a/veinsrs/src/cli/commands/selftest.rs+++ /dev/null@@ -1,183 +0,0 @@-use crate::error::{Error, Result};-use crate::object::blob::{self, BlobForm};-use crate::object::chunker::{gear_table, next_chunk};-use crate::object::commit::{self, Commit, Sig};-use crate::object::id::{Id, hash_bytes, object_id};-use crate::object::tree;-use crate::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef};-use crate::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};-use crate::store::pack;--pub fn run() -> Result<u8> {-    let empty_hash = hex(&hash_bytes(b""));-    expect(-        empty_hash == "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262",-        "blake3 vector",-    )?;--    let gear = gear_table();-    expect(gear[0] == 0xf8447b379cdadcd5, "gear table entry 0")?;-    expect(gear[1] == 0xbe63d125aec8ca6d, "gear table entry 1")?;--    let mut chunk_input = vec![0u8; 300_000];-    for (index, byte) in chunk_input.iter_mut().enumerate() {-        *byte = ((index * 31 + 2 * 17) % 251) as u8;-    }-    let first = next_chunk(&chunk_input);-    let second = next_chunk(&chunk_input[first..]);-    expect(first == 262_144 && second == 37_856, "chunk boundaries")?;-    expect(-        object_id(TYPE_CHUNK, &chunk_input[..first]).to_hex()-            == "c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458",-        "first chunk id",-    )?;-    expect(-        object_id(TYPE_CHUNK, &chunk_input[first..]).to_hex()-            == "0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b",-        "second chunk id",-    )?;-    let build = blob::build(&chunk_input);-    expect(-        build.root.to_hex() == "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf",-        "manifest blob id",-    )?;-    let Some(manifest_object) = build.objects.last() else {-        return expect(false, "manifest object present").map(|()| 0);-    };-    let manifest = blob::decode(&manifest_object.body)?;-    expect(manifest.form == BlobForm::Leaf, "manifest form")?;--    let empty_tree_body = vec![0u8];-    let empty_tree_id = object_id(TYPE_TREE, &empty_tree_body);-    expect(-        empty_tree_id.to_hex()-            == "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb",-        "empty tree id",-    )?;-    expect(-        tree::decode(&empty_tree_body)?.entries.is_empty(),-        "empty tree decode",-    )?;--    let inline = blob::encode_inline(b"hello");-    expect(-        object_id(TYPE_BLOB, &inline).to_hex()-            == "f04a7f7324bbb7279471b5c656c893ee51b62ed9f9bad4c8cb8a289101f68240",-        "inline blob id",-    )?;--    let change_id: [u8; 16] = [-        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,-        0x1a,-    ];-    let signature = Sig {-        name: b"Alice".to_vec(),-        email: b"alice@example.com".to_vec(),-        seconds: 1_700_000_000,-        tz_min: 0,-    };-    let commit = Commit {-        version: 1,-        parents: Vec::new(),-        root_tree: empty_tree_id,-        change_id,-        author: signature.clone(),-        committer: signature,-        message: b"initial commit".to_vec(),-        renames_state: commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    let commit_body = commit::encode(&commit);-    let commit_id = object_id(crate::object::TYPE_COMMIT, &commit_body);-    expect(-        commit_id.to_hex() == "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299",-        "commit id",-    )?;-    expect(-        commit_id-            == Id::from_hex("7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299")?,-        "commit round trip",-    )?;--    let view = View {-        heads: vec![commit_id],-        bookmarks: vec![Bookmark {-            name: b"main".to_vec(),-            targets: TargetSet {-                adds: vec![Some(commit_id)],-                removes: Vec::new(),-            },-        }],-        tags: Vec::new(),-        remote_refs: Vec::new(),-        working_copies: vec![WorkspaceRef {-            workspace: b"default".to_vec(),-            target: commit_id,-        }],-    };-    let view_body = view::encode_view(&view);-    let view_id = object_id(crate::object::TYPE_VIEW, &view_body);-    expect(-        view_id.to_hex() == "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11",-        "view id",-    )?;--    let operation = Operation {-        parents: Vec::new(),-        view: view_id,-        start: TimeMs {-            millis: 1_700_000_000_000,-            tz_min: 0,-        },-        end: TimeMs {-            millis: 1_700_000_000_000,-            tz_min: 0,-        },-        hostname: b"host".to_vec(),-        username: b"alice".to_vec(),-        description: b"selftest operation".to_vec(),-        tags: Vec::new(),-    };-    let operation_body = view::encode_operation(&operation);-    expect(-        object_id(crate::object::TYPE_OPERATION, &operation_body).to_hex()-            == "0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426",-        "operation id",-    )?;--    let output = pack::encode(&[RawObject::known(TYPE_TREE, empty_tree_id, vec![0])], 3);-    expect(-        hex(&output.pack)-            == "56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911",-        "pack bytes",-    )?;-    expect(output.index.len() == 1136, "index length")?;-    expect(-        hex(&hash_bytes(&output.index))-            == "d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc",-        "index checksum",-    )?;-    pack::decode(output.pack)?;--    println!("self-test: ok");-    Ok(0)-}--fn expect(condition: bool, message: &str) -> Result<()> {-    if condition {-        Ok(())-    } else {-        Err(Error::new(format!("self-test failed: {message}")))-    }-}--fn hex(bytes: &[u8]) -> String {-    const DIGITS: &[u8; 16] = b"0123456789abcdef";-    let mut text = String::with_capacity(bytes.len() * 2);-    for byte in bytes {-        text.push(DIGITS[(byte >> 4) as usize] as char);-        text.push(DIGITS[(byte & 0x0f) as usize] as char);-    }-    text-}--- a/veinsrs/src/cli/commands/status.rs+++ /dev/null@@ -1,50 +0,0 @@-use std::path::Path;--use crate::error::{Error, Result};-use crate::object::tree::{KIND_CONFLICT, KIND_MISSING};-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::snapshot;--pub fn run() -> Result<u8> {-    let root = layout::discover(Path::new("."))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let Some(working_copy) = ops::working_copy_id(&view) else {-        println!("info: working copy clean");-        return Ok(0);-    };-    let commit = graph::load_commit(&mut store, working_copy)?-        .ok_or_else(|| Error::new("no operation state"))?;-    let old_tree = match commit.parents.first() {-        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),-        None => None,-    };-    let changes = graph::compare_trees(&mut store, old_tree, Some(commit.root_tree))?;-    let empty = changes.is_empty();-    let mut conflicts = 0usize;-    for change in changes {-        let path = String::from_utf8_lossy(&change.path);-        if change.old_kind == KIND_MISSING {-            println!("A {path}");-        } else if change.new_kind == KIND_MISSING {-            println!("D {path}");-        } else if change.new_kind == KIND_CONFLICT {-            println!("C {path}");-            conflicts += 1;-        } else {-            println!("M {path}");-        }-    }-    if empty {-        println!("info: working copy clean");-    }-    if conflicts > 0 {-        println!("{conflicts} conflict(s)");-    }-    Ok(0)-}--- a/veinsrs/src/cli/commands/version.rs+++ /dev/null@@ -1,6 +0,0 @@-use crate::error::Result;--pub fn run() -> Result<u8> {-    println!("veins-rust v0.1.0 (veins-store 1)");-    Ok(0)-}--- a/veinsrs/src/cli/config_cmd.rs+++ /dev/null@@ -1,214 +0,0 @@-use std::collections::BTreeMap;-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::store::layout;--pub fn run(arguments: &[String]) -> Result<u8> {-    if arguments.len() == 1 && matches!(arguments[0].as_str(), "help" | "-h" | "-help") {-        usage();-        return Ok(0);-    }-    let mut global = false;-    let mut list = false;-    let mut unset = false;-    let mut show_defaults = false;-    let mut internal = false;-    let mut end_flags = false;-    let mut positional = Vec::new();-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-global" || argument == "-g") {-            global = true;-        } else if !end_flags && (argument == "-list" || argument == "-l") {-            list = true;-        } else if !end_flags && argument == "-unset" {-            unset = true;-        } else if !end_flags && (argument == "-d" || argument == "-defaults") {-            show_defaults = true;-        } else if !end_flags && (argument == "-i" || argument == "-internal") {-            internal = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            positional.push(argument.clone());-        }-    }-    if show_defaults {-        if list || unset || !positional.is_empty() {-            return Err(Error::new("cfg -d takes no operands"));-        }-        return defaults(internal);-    }-    if internal {-        return Err(Error::new("cfg -i requires -d"));-    }-    if positional.len() == 1 && matches!(positional[0].as_str(), "list" | "ls") {-        list = true;-        positional.clear();-    } else if positional.len() == 2 && positional[0] == "get" {-        positional.remove(0);-    } else if positional.len() == 3 && positional[0] == "set" {-        positional.remove(0);-    } else if positional.len() == 2 && matches!(positional[0].as_str(), "unset" | "rm" | "remove") {-        unset = true;-        positional.remove(0);-    }-    if list {-        if !positional.is_empty() {-            return Err(Error::new("cfg list takes no operands"));-        }-    } else if unset {-        if positional.len() != 1 {-            return Err(Error::new("cfg unset requires one key"));-        }-    } else if positional.len() > 2 {-        return Err(Error::new("cfg accepts a key and one value"));-    }-    let root = if global {-        None-    } else {-        Some(layout::discover(Path::new(".")).map_err(|_| Error::new("not a veins repository"))?)-    };-    if list {-        return list_entries(root.as_deref(), global);-    }-    if unset {-        return unset_entry(root.as_deref(), global, &positional[0]);-    }-    match positional.len() {-        0 => list_entries(root.as_deref(), global),-        1 => get_entry(root.as_deref(), global, &positional[0]),-        _ => set_entry(root.as_deref(), global, &positional[0], &positional[1]),-    }-}--fn usage() {-    println!("usage: vn cfg [<key>] [<value>]");-    println!("       vn cfg [<get|set|unset|list>] [<key>] [<value>]");-    println!("       vn cfg -list");-    println!("       vn cfg -d [-i]");-    println!("       vn cfg -unset <key>");-    println!();-    println!("read and write local repository configuration");-}--fn defaults(internal: bool) -> Result<u8> {-    let mut values = BTreeMap::from([-        ("core.editor", "(unset)"),-        ("core.pager", "(unset)"),-        ("editor", "vi"),-        ("log.default_amount", "20"),-        ("merge.adjacent", "strict"),-        ("pager", "less -R"),-        ("rename.autodetect", "similar"),-        ("user.email", "(unset)"),-        ("user.name", "(unset)"),-    ]);-    if internal {-        values.insert("bookmark.current", "(unset)");-        values.insert("promisor", "(unset)");-        values.insert("remote.<name>.key", "(unset)");-        values.insert("remote.<name>.tls-pin", "(unset)");-        values.insert("remote.<name>.url", "(unset)");-        values.insert("remote.current", "(unset)");-        values.insert("remote.default", "(unset)");-    }-    for (key, value) in values {-        print!("{key} = {value}");-        if let Some(current) = core::user_config_value(key) {-            print!(" (current: {current})");-        }-        println!();-    }-    Ok(0)-}--fn repo_entries(root: &Path) -> BTreeMap<String, String> {-    let Some(data) = core::read_file_opt(&layout::config_path(root), 0) else {-        return BTreeMap::new();-    };-    let text = String::from_utf8_lossy(&data);-    let mut output = BTreeMap::new();-    for raw in text.lines() {-        let line = core::trim_str(raw);-        if line.is_empty() || line.starts_with('#') {-            continue;-        }-        let Some((key, value)) = line.split_once('=') else {-            continue;-        };-        let key = core::trim_str(key);-        if !key.is_empty() {-            output.insert(key.to_string(), core::trim_str(value).to_string());-        }-    }-    output-}--fn list_entries(root: Option<&Path>, global: bool) -> Result<u8> {-    let entries = if global {-        core::user_config_entries()-    } else {-        repo_entries(root.ok_or_else(|| Error::new("not a veins repository"))?)-    };-    for (key, value) in entries {-        println!("{key} = {value}");-    }-    Ok(0)-}--fn get_value(root: Option<&Path>, global: bool, key: &str) -> Option<String> {-    if global {-        core::user_config_value(key)-    } else {-        core::repo_config_value(root?, key)-    }-}--fn get_entry(root: Option<&Path>, global: bool, key: &str) -> Result<u8> {-    let Some(value) = get_value(root, global, key) else {-        return Err(Error::new(format!("unknown config key: {key}")));-    };-    println!("{value}");-    Ok(0)-}--fn set_entry(root: Option<&Path>, global: bool, key: &str, value: &str) -> Result<u8> {-    let ok = if global {-        core::user_config_set(key, value)-    } else {-        core::repo_config_set(-            root.ok_or_else(|| Error::new("not a veins repository"))?,-            key,-            value,-        )-    };-    if !ok {-        return Err(Error::new(format!(-            "cannot write {} config",-            if global { "user" } else { "repository" }-        )));-    }-    Ok(0)-}--fn unset_entry(root: Option<&Path>, global: bool, key: &str) -> Result<u8> {-    let ok = if global {-        core::user_config_remove(key)-    } else {-        core::repo_config_remove(-            root.ok_or_else(|| Error::new("not a veins repository"))?,-            key,-        )-    };-    if !ok {-        return Err(Error::new(format!(-            "cannot write {} config",-            if global { "user" } else { "repository" }-        )));-    }-    Ok(0)-}--- a/veinsrs/src/cli/diff.rs+++ /dev/null@@ -1,374 +0,0 @@-use crate::object::id::Id;-use crate::object::tree::{KIND_CONFLICT, KIND_MISSING};-use crate::store::graph;-use crate::store::reader::Store;--#[derive(Clone, Copy)]-struct DiffOp {-    tag: u8,-    ai: usize,-    bi: usize,-}--pub fn split_lines(data: &[u8]) -> Vec<&[u8]> {-    let mut output = Vec::new();-    let mut start = 0;-    for (index, byte) in data.iter().enumerate() {-        if *byte == b'\n' {-            output.push(&data[start..index]);-            start = index + 1;-        }-    }-    if start < data.len() {-        output.push(&data[start..]);-    }-    output-}--fn build_ops_lcs(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {-    let n = a.len();-    let m = b.len();-    let columns = m + 1;-    let mut dp = vec![0u32; (n + 1) * columns];-    for i in 1..=n {-        for j in 1..=m {-            dp[i * columns + j] = if a[i - 1] == b[j - 1] {-                dp[(i - 1) * columns + (j - 1)] + 1-            } else {-                dp[(i - 1) * columns + j].max(dp[i * columns + (j - 1)])-            };-        }-    }-    let mut ops = Vec::with_capacity(n + m);-    let mut i = n;-    let mut j = m;-    while i > 0 || j > 0 {-        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {-            ops.push(DiffOp {-                tag: b' ',-                ai: i - 1,-                bi: j - 1,-            });-            i -= 1;-            j -= 1;-        } else if j > 0 && (i == 0 || dp[i * columns + (j - 1)] >= dp[(i - 1) * columns + j]) {-            ops.push(DiffOp {-                tag: b'+',-                ai: 0,-                bi: j - 1,-            });-            j -= 1;-        } else {-            ops.push(DiffOp {-                tag: b'-',-                ai: i - 1,-                bi: 0,-            });-            i -= 1;-        }-    }-    ops.reverse();-    ops-}--fn build_ops_myers(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {-    let n = a.len() as isize;-    let m = b.len() as isize;-    let max_d = n + m;-    let offset = max_d;-    let length = (2 * max_d + 1) as usize;-    let mut v = vec![0isize; length];-    let mut trace: Vec<Vec<isize>> = Vec::new();-    const TRACE_CAP: usize = 64 * 1024 * 1024;-    let mut found = -1isize;-    for d in 0..=max_d {-        if (trace.len() + 1) * length * std::mem::size_of::<isize>() > TRACE_CAP {-            return Vec::new();-        }-        trace.push(v.clone());-        let mut k = -d;-        while k <= d {-            let mut x = if k == -d-                || (k != d && v[(offset + k - 1) as usize] < v[(offset + k + 1) as usize])-            {-                v[(offset + k + 1) as usize]-            } else {-                v[(offset + k - 1) as usize] + 1-            };-            let mut y = x - k;-            while x < n && y < m && a[x as usize] == b[y as usize] {-                x += 1;-                y += 1;-            }-            v[(offset + k) as usize] = x;-            if x >= n && y >= m {-                found = d;-                break;-            }-            k += 2;-        }-        if found >= 0 {-            break;-        }-    }-    if found < 0 {-        return Vec::new();-    }-    let mut ops = Vec::new();-    let mut x = n;-    let mut y = m;-    let mut d = found;-    while d >= 0 {-        let previous = &trace[d as usize];-        let k = x - y;-        let previous_k = if k == -d-            || (k != d && previous[(offset + k - 1) as usize] < previous[(offset + k + 1) as usize])-        {-            k + 1-        } else {-            k - 1-        };-        let previous_x = previous[(offset + previous_k) as usize];-        let previous_y = previous_x - previous_k;-        while x > previous_x && y > previous_y {-            ops.push(DiffOp {-                tag: b' ',-                ai: (x - 1) as usize,-                bi: (y - 1) as usize,-            });-            x -= 1;-            y -= 1;-        }-        if d > 0 {-            if x == previous_x {-                ops.push(DiffOp {-                    tag: b'+',-                    ai: 0,-                    bi: (y - 1) as usize,-                });-                y -= 1;-            } else {-                ops.push(DiffOp {-                    tag: b'-',-                    ai: (x - 1) as usize,-                    bi: 0,-                });-                x -= 1;-            }-        }-        d -= 1;-    }-    ops.reverse();-    ops-}--fn build_ops_fallback(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {-    let mut prefix = 0;-    while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {-        prefix += 1;-    }-    let mut suffix = 0;-    while suffix < a.len() - prefix-        && suffix < b.len() - prefix-        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]-    {-        suffix += 1;-    }-    let mut ops = Vec::with_capacity(a.len() + b.len());-    for index in 0..prefix {-        ops.push(DiffOp {-            tag: b' ',-            ai: index,-            bi: index,-        });-    }-    for index in prefix..a.len() - suffix {-        ops.push(DiffOp {-            tag: b'-',-            ai: index,-            bi: 0,-        });-    }-    for index in prefix..b.len() - suffix {-        ops.push(DiffOp {-            tag: b'+',-            ai: 0,-            bi: index,-        });-    }-    for index in 0..suffix {-        ops.push(DiffOp {-            tag: b' ',-            ai: a.len() - suffix + index,-            bi: b.len() - suffix + index,-        });-    }-    ops-}--fn build_ops(a: &[&[u8]], b: &[&[u8]]) -> Vec<DiffOp> {-    if a.is_empty() && b.is_empty() {-        return Vec::new();-    }-    if !a.is_empty() && !b.is_empty() && (a.len() <= 2048 && b.len() <= 2048) {-        return build_ops_lcs(a, b);-    }-    if !a.is_empty() && !b.is_empty() && a.len() * b.len() <= 4_000_000 {-        return build_ops_lcs(a, b);-    }-    let myers = build_ops_myers(a, b);-    if !myers.is_empty() {-        return myers;-    }-    build_ops_fallback(a, b)-}--pub fn render_unified_for(a: &[&[u8]], b: &[&[u8]], output: &mut String) {-    render_unified(a, b, output);-}--fn render_unified(a: &[&[u8]], b: &[&[u8]], output: &mut String) {-    let ops = build_ops(a, b);-    let changes: Vec<usize> = ops-        .iter()-        .enumerate()-        .filter(|(_, op)| op.tag != b' ')-        .map(|(index, _)| index)-        .collect();-    const CONTEXT: usize = 3;-    let mut position = 0;-    let mut old_seen = 0;-    let mut new_seen = 0;-    let mut change_index = 0;-    while change_index < changes.len() {-        let first = changes[change_index];-        let start = first.saturating_sub(CONTEXT);-        let mut last = first;-        change_index += 1;-        while change_index < changes.len() && changes[change_index] <= last + CONTEXT * 2 {-            last = changes[change_index];-            change_index += 1;-        }-        let end = (last + CONTEXT + 1).min(ops.len());-        while position < start {-            match ops[position].tag {-                b' ' => {-                    old_seen += 1;-                    new_seen += 1;-                }-                b'-' => old_seen += 1,-                _ => new_seen += 1,-            }-            position += 1;-        }-        let mut old_count = 0;-        let mut new_count = 0;-        for op in &ops[start..end] {-            match op.tag {-                b' ' => {-                    old_count += 1;-                    new_count += 1;-                }-                b'-' => old_count += 1,-                _ => new_count += 1,-            }-        }-        let old_start = old_seen + usize::from(old_count > 0);-        let new_start = new_seen + usize::from(new_count > 0);-        output.push_str(&format!(-            "@@ -{old_start},{old_count} +{new_start},{new_count} @@\n"-        ));-        while position < end {-            let op = ops[position];-            match op.tag {-                b' ' => {-                    output.push(' ');-                    output.push_str(&String::from_utf8_lossy(a[op.ai]));-                    output.push('\n');-                    old_seen += 1;-                    new_seen += 1;-                }-                b'-' => {-                    output.push_str(&super::output::red("-"));-                    output.push_str(&super::output::red(&String::from_utf8_lossy(a[op.ai])));-                    output.push('\n');-                    old_seen += 1;-                }-                _ => {-                    output.push_str(&super::output::green("+"));-                    output.push_str(&super::output::green(&String::from_utf8_lossy(b[op.bi])));-                    output.push('\n');-                    new_seen += 1;-                }-            }-            position += 1;-        }-    }-}--fn contains_nul(data: &[u8]) -> bool {-    data.iter().take(8192).any(|byte| *byte == 0)-}--pub fn render_diff(-    store: &mut Store,-    old_tree: Option<Id>,-    new_tree: Option<Id>,-    announce: bool,-    path_filter: &[u8],-) -> crate::error::Result<usize> {-    let mut changes = graph::compare_trees(store, old_tree, new_tree)?;-    if !path_filter.is_empty() {-        changes.retain(|change| {-            change.path == path_filter-                || (change.path.len() > path_filter.len()-                    && change.path.starts_with(path_filter)-                    && change.path[path_filter.len()] == b'/')-        });-    }-    let mut output = String::new();-    for change in &changes {-        let path = String::from_utf8_lossy(&change.path);-        if change.new_kind == KIND_CONFLICT {-            output.push_str(&format!("Conflict: {path}\n"));-            continue;-        }-        let old_data = match (change.old_kind, change.old_id) {-            (KIND_MISSING, _) | (_, None) => Vec::new(),-            (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),-        };-        let new_data = match (change.new_kind, change.new_id) {-            (KIND_MISSING, _) | (_, None) => Vec::new(),-            (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),-        };-        if contains_nul(&old_data) || contains_nul(&new_data) {-            output.push_str(&format!("Binary files a/{path} and b/{path} differ\n"));-            continue;-        }-        output.push_str(&super::output::red("--- "));-        if change.old_kind == KIND_MISSING {-            output.push_str(&super::output::red("/dev/null"));-        } else {-            output.push_str(&super::output::red(&format!("a/{path}")));-        }-        output.push('\n');-        output.push_str(&super::output::green("+++ "));-        if change.new_kind == KIND_MISSING {-            output.push_str(&super::output::green("/dev/null"));-        } else {-            output.push_str(&super::output::green(&format!("b/{path}")));-        }-        output.push('\n');-        render_unified(-            &split_lines(&old_data),-            &split_lines(&new_data),-            &mut output,-        );-    }-    if announce && changes.is_empty() {-        super::output::info_prefix();-        output.push_str("no diff to show\n");-    }-    print!("{output}");-    Ok(changes.len())-}--- a/veinsrs/src/cli/history.rs+++ /dev/null@@ -1,1301 +0,0 @@-use std::collections::{HashMap, HashSet};-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::identity;-use crate::object::commit::{self, Commit};-use crate::object::id::Id;-use crate::object::tree::{self, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE};-use crate::object::{TYPE_COMMIT, TYPE_TREE};-use crate::store::Txn;-use crate::store::graph::{self, LogNode};-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::snapshot;--use super::{diff, output};--fn parse_count(text: &str) -> Option<usize> {-    if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {-        return None;-    }-    let value = text.parse::<usize>().ok()?;-    (value > 0).then_some(value)-}--struct LogRecord {-    id: Id,-    root_tree: Id,-    parents: Vec<Id>,-    change: String,-    seconds: i64,-    message: String,-    author: String,-    conflicted: bool,-    has_changes: bool,-}--pub fn log(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut titles = true;-    let mut all = false;-    let mut pager = false;-    let mut limit: Option<usize> = None;-    let mut first = false;-    let mut explicit_limit = false;-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && argument == "-no-col-titles" {-            titles = false;-        } else if !end_flags && argument == "-p" {-            pager = true;-        } else if !end_flags && (argument == "-a" || argument == "-all") {-            all = true;-        } else if !end_flags && (argument == "-l" || argument == "-f") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a count")));-            }-            limit = Some(-                parse_count(&arguments[index])-                    .ok_or_else(|| Error::new(format!("{argument} requires a positive count")))?,-            );-            first = argument == "-f";-            explicit_limit = true;-        } else if !end_flags-            && argument.len() > 2-            && argument.starts_with('-')-            && matches!(argument.as_bytes()[1], b'l' | b'f')-        {-            limit = Some(-                parse_count(&argument[2..])-                    .ok_or_else(|| Error::new(format!("invalid log count: {argument}")))?,-            );-            first = argument.as_bytes()[1] == b'f';-            explicit_limit = true;-        } else if !end_flags && argument.len() > 1 && matches!(argument.as_bytes()[0], b'l' | b'f')-        {-            if let Some(count) = parse_count(&argument[1..]) {-                limit = Some(count);-                first = argument.as_bytes()[0] == b'f';-                explicit_limit = true;-            } else {-                revision = argument.clone();-            }-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            revision = argument.clone();-        }-        index += 1;-    }-    if all || (pager && !explicit_limit) {-        limit = None;-    } else if limit.is_none() {-        limit = Some(-            core::user_config_value("log.default_amount")-                .and_then(|value| parse_count(&value))-                .unwrap_or(20),-        );-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let working_copy = ops::working_copy_id(&view);-    let start = if revision.is_empty() || revision == "all()" {-        graph::view_roots(&view)-    } else {-        graph::resolve_revision(&mut store, &view, &revision)?-            .map(|id| vec![id])-            .unwrap_or_default()-    };-    let mut seen: HashSet<Id> = start.iter().copied().collect();-    let mut stack = start;-    let mut records = Vec::new();-    while let Some(id) = stack.pop() {-        let Some(commit) = graph::load_commit(&mut store, id)? else {-            continue;-        };-        let message = first_line(&commit.message);-        let has_changes = if working_copy == Some(id) {-            graph::has_changes(&mut store, &commit)?-        } else {-            false-        };-        records.push(LogRecord {-            id,-            root_tree: commit.root_tree,-            parents: commit.parents.clone(),-            change: graph::base32_encode(commit.change_id),-            seconds: commit.committer.seconds,-            message,-            author: String::from_utf8_lossy(&commit.author.name).into_owned(),-            conflicted: false,-            has_changes,-        });-        for parent in commit.parents {-            if seen.insert(parent) {-                stack.push(parent);-            }-        }-    }-    let nodes: Vec<LogNode> = records-        .iter()-        .map(|record| LogNode {-            id: record.id,-            seconds: record.seconds,-            parents: record.parents.clone(),-        })-        .collect();-    let order = graph::order_log_nodes(&nodes);-    let mut ordered = Vec::with_capacity(records.len());-    let mut slots: Vec<Option<LogRecord>> = records.into_iter().map(Some).collect();-    for position in order {-        if let Some(record) = slots[position].take() {-            ordered.push(record);-        }-    }-    let mut records = ordered;-    if let Some(limit) = limit {-        if first {-            if records.len() > limit {-                records.drain(..records.len() - limit);-            }-            records.reverse();-        } else if records.len() > limit {-            records.truncate(limit);-        }-    }-    let mut conflict_cache = std::collections::HashMap::new();-    for record in &mut records {-        record.conflicted =-            graph::tree_conflicted_with(&mut store, record.root_tree, &mut conflict_cache)?;-    }--    let mut change_ids: Vec<String> = records.iter().map(|record| record.change.clone()).collect();-    let mut change_width = 6;-    let mut author_width = 6;-    let mut change_counts: HashMap<String, usize> = HashMap::new();-    for (position, record) in records.iter().enumerate() {-        let short = graph::short_change_id(&change_ids, position);-        change_width = change_width.max(short.len());-        author_width = author_width.max(record.author.len());-        *change_counts.entry(record.change.clone()).or_insert(0) += 1;-    }-    for position in 0..change_ids.len() {-        change_ids[position] = graph::short_change_id(&change_ids, position);-    }--    let color = output::enabled();-    let mut rendered = String::new();-    if titles {-        rendered.push_str(&cell("", 1, &[], color));-        rendered.push(' ');-        rendered.push_str(&cell("Commit", 12, &[], color));-        rendered.push_str("  ");-        rendered.push_str(&cell("Change", change_width, &[], color));-        rendered.push_str("  ");-        rendered.push_str(&cell("Date", 19, &[], color));-        rendered.push_str("  ");-        rendered.push_str(&cell("Author", author_width, &[], color));-        rendered.push_str("  Message\n");-    }-    for (position, record) in records.iter().enumerate() {-        let is_working = working_copy == Some(record.id);-        let marker = if is_working { "@" } else { " " };-        let marker_codes: &[&str] = if is_working {-            if record.has_changes { &["96"] } else { &["31"] }-        } else {-            &[]-        };-        rendered.push_str(&cell(marker, 1, marker_codes, color));-        rendered.push(' ');-        rendered.push_str(&cell(&record.id.short(), 12, &["31"], color));-        rendered.push_str("  ");-        rendered.push_str(&cell(&change_ids[position], change_width, &["31"], color));-        rendered.push_str("  ");-        rendered.push_str(&cell(-            &crate::time::format_utc(record.seconds),-            19,-            &["2", "36"],-            color,-        ));-        rendered.push_str("  ");-        rendered.push_str(&cell(&record.author, author_width, &["36"], color));-        rendered.push_str("  ");-        if record.message.is_empty() {-            rendered.push_str(&paint("<unset>", &["90"], color));-        } else {-            rendered.push_str(&paint(&record.message, &["32"], color));-        }-        for name in ops::bookmark_names(&view, record.id) {-            rendered.push_str(&format!(" [{}]", String::from_utf8_lossy(&name)));-        }-        for name in ops::tag_names(&view, record.id) {-            rendered.push_str(&format!(" <{}>", String::from_utf8_lossy(&name)));-        }-        if record.conflicted {-            rendered.push_str(" (conflicted)");-        }-        if change_counts.get(&record.change).copied().unwrap_or(0) > 1 {-            rendered.push_str(" (divergent)");-        }-        rendered.push('\n');-    }-    output::pager_output(&root, &rendered, pager);-    Ok(0)-}--fn paint(text: &str, codes: &[&str], color: bool) -> String {-    if !color || codes.is_empty() {-        return text.to_string();-    }-    let mut out = String::new();-    for code in codes {-        out.push_str("\x1b[");-        out.push_str(code);-        out.push('m');-    }-    out.push_str(text);-    out.push_str("\x1b[0m");-    out-}--/// Colours a cell and pads it to `width` using visible (uncoloured) length.-fn cell(text: &str, width: usize, codes: &[&str], color: bool) -> String {-    let mut out = paint(text, codes, color);-    for _ in text.chars().count()..width {-        out.push(' ');-    }-    out-}--fn first_line(message: &[u8]) -> String {-    let position = message.iter().position(|byte| *byte == b'\n');-    String::from_utf8_lossy(match position {-        Some(position) => &message[..position],-        None => message,-    })-    .into_owned()-}--pub fn show(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut titles = true;-    let mut all = false;-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && (argument == "-a" || argument == "-all") {-            all = true;-        } else if !end_flags && argument == "-no-col-titles" {-            titles = false;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            revision = argument.clone();-        }-        index += 1;-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {-        Error::new(if revision.is_empty() {-            "no working-copy commit"-        } else {-            "unknown revision"-        })-    })?;-    let commit =-        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;-    let mut rendered = String::new();-    if titles {-        rendered.push_str(&format!("commit   {}\n", target.to_hex()));-        rendered.push_str(&format!(-            "change   {}\n",-            graph::base32_encode(commit.change_id)-        ));-        rendered.push_str(&format!(-            "author   {} <{}>\n",-            String::from_utf8_lossy(&commit.author.name),-            String::from_utf8_lossy(&commit.author.email)-        ));-        rendered.push_str(&format!(-            "date     {}\n",-            crate::time::format_utc(commit.committer.seconds)-        ));-        rendered.push_str("parents  ");-        if commit.parents.is_empty() {-            rendered.push_str("<none>");-        } else {-            for (position, parent) in commit.parents.iter().enumerate() {-                if position > 0 {-                    rendered.push(' ');-                }-                rendered.push_str(&parent.short());-            }-        }-        rendered.push('\n');-        let names = ops::bookmark_names(&view, target);-        if !names.is_empty() {-            rendered.push_str("bookmarks");-            for name in names {-                rendered.push_str(&format!(" [{}]", String::from_utf8_lossy(&name)));-            }-            rendered.push('\n');-        }-        rendered.push('\n');-        if commit.message.is_empty() {-            rendered.push_str("<unset>\n");-        } else {-            rendered.push_str(&String::from_utf8_lossy(&commit.message));-            rendered.push('\n');-        }-        rendered.push('\n');-    }-    let old_tree = match commit.parents.first() {-        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),-        None => None,-    };-    let difference = {-        let mut buffer = Vec::new();-        let mut collector = Collector::new(&mut buffer);-        collector.render(&mut store, old_tree, Some(commit.root_tree), false, b"")?;-        String::from_utf8_lossy(&buffer).into_owned()-    };-    rendered.push_str(&difference);-    let diff_count = !difference.is_empty();-    output::pager_output(&root, &rendered, diff_count && !all);-    Ok(0)-}--struct Collector<'a> {-    output: &'a mut Vec<u8>,-}--impl<'a> Collector<'a> {-    fn new(output: &'a mut Vec<u8>) -> Self {-        Self { output }-    }--    fn render(-        &mut self,-        store: &mut Store,-        old_tree: Option<Id>,-        new_tree: Option<Id>,-        announce: bool,-        filter: &[u8],-    ) -> Result<usize> {-        let mut changes = graph::compare_trees(store, old_tree, new_tree)?;-        if !filter.is_empty() {-            changes.retain(|change| {-                change.path == filter-                    || (change.path.len() > filter.len()-                        && change.path.starts_with(filter)-                        && change.path[filter.len()] == b'/')-            });-        }-        for change in &changes {-            let path = String::from_utf8_lossy(&change.path);-            if change.new_kind == KIND_CONFLICT {-                self.output-                    .extend_from_slice(format!("Conflict: {path}\n").as_bytes());-                continue;-            }-            let old_data = match (change.old_kind, change.old_id) {-                (KIND_MISSING, _) | (_, None) => Vec::new(),-                (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),-            };-            let new_data = match (change.new_kind, change.new_id) {-                (KIND_MISSING, _) | (_, None) => Vec::new(),-                (_, Some(id)) => graph::read_blob(store, id)?.unwrap_or_default(),-            };-            if old_data.iter().take(8192).any(|byte| *byte == 0)-                || new_data.iter().take(8192).any(|byte| *byte == 0)-            {-                self.output.extend_from_slice(-                    format!("Binary files a/{path} and b/{path} differ\n").as_bytes(),-                );-                continue;-            }-            self.output.extend_from_slice(b"--- ");-            if change.old_kind == KIND_MISSING {-                self.output.extend_from_slice(b"/dev/null");-            } else {-                self.output-                    .extend_from_slice(format!("a/{path}").as_bytes());-            }-            self.output.extend_from_slice(b"\n+++ ");-            if change.new_kind == KIND_MISSING {-                self.output.extend_from_slice(b"/dev/null");-            } else {-                self.output-                    .extend_from_slice(format!("b/{path}").as_bytes());-            }-            self.output.extend_from_slice(b"\n");-            let a = diff::split_lines(&old_data);-            let b = diff::split_lines(&new_data);-            let mut rendered = String::new();-            diff::render_unified_for(&a, &b, &mut rendered);-            self.output.extend_from_slice(rendered.as_bytes());-        }-        if announce && changes.is_empty() {-            self.output.extend_from_slice(b"info: no diff to show\n");-        }-        Ok(changes.len())-    }-}--pub fn hash(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut short = false;-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && argument == "-short" {-            short = true;-        } else if !end_flags && argument == "-long" {-            short = false;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            revision = argument.clone();-        }-        index += 1;-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {-        Error::new(if revision.is_empty() {-            "no working-copy commit"-        } else {-            "unknown revision"-        })-    })?;-    let hex = target.to_hex();-    println!("{}", if short { &hex[..12] } else { &hex });-    Ok(0)-}--fn print_tree(-    store: &mut Store,-    tree_id: Id,-    prefix: &str,-    depth: usize,-    output: &mut String,-) -> Result<bool> {-    if depth > crate::object::MAX_TREE_DEPTH {-        return Ok(false);-    }-    let Some(body) = store.body(tree_id, TYPE_TREE)? else {-        return Ok(false);-    };-    let Ok(tree) = tree::decode(&body) else {-        return Ok(false);-    };-    for (index, entry) in tree.entries.iter().enumerate() {-        let last = index + 1 == tree.entries.len();-        output.push_str(prefix);-        output.push_str(if last { "`-- " } else { "|-- " });-        output.push_str(&String::from_utf8_lossy(&entry.name));-        output.push('\n');-        if entry.kind == KIND_SUBTREE {-            let next = format!("{prefix}{}", if last { "    " } else { "|   " });-            if !print_tree(store, entry.target, &next, depth + 1, output)? {-                return Ok(false);-            }-        }-    }-    Ok(true)-}--pub fn list(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut plain = false;-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-plain" || argument == "-p") {-            plain = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            revision = argument.clone();-        }-        index += 1;-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let target = graph::resolve_revision(&mut store, &view, &revision)?.ok_or_else(|| {-        Error::new(if revision.is_empty() {-            "no working-copy commit"-        } else {-            "unknown revision"-        })-    })?;-    let commit =-        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;-    if plain {-        for entry in tree::flatten(&mut store, commit.root_tree)? {-            println!("{}", String::from_utf8_lossy(&entry.path));-        }-    } else {-        let mut rendered = String::from(".\n");-        if !print_tree(&mut store, commit.root_tree, "", 0, &mut rendered)? {-            return Err(Error::new("cannot read tree"));-        }-        print!("{rendered}");-    }-    Ok(0)-}--fn existing_directory(text: &str) -> bool {-    if text.is_empty() || text.contains('\0') {-        return false;-    }-    let path = Path::new(text);-    let path = if path.is_absolute() {-        path.to_path_buf()-    } else {-        std::env::current_dir().unwrap_or_default().join(path)-    };-    path.is_dir()-}--fn view_ref_named(view: &crate::object::view::View, name: &str) -> bool {-    ops::find_bookmark(view, name.as_bytes()).is_some()-        || ops::find_tag(view, name.as_bytes()).is_some()-        || view.remote_refs.iter().any(|reference| {-            let mut joined = reference.remote.clone();-            joined.push(b'/');-            joined.extend_from_slice(&reference.name);-            joined == name.as_bytes()-        })-}--pub fn diff(arguments: &[String]) -> Result<u8> {-    let mut flag_revisions = Vec::new();-    let mut operands = Vec::new();-    let mut all = false;-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-a" || argument == "-all") {-            all = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            flag_revisions.push(arguments[index].clone());-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            operands.push(argument.clone());-        }-        index += 1;-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let mut view = ops::current_view(&root, &mut store)?;-    let mut revisions = flag_revisions;-    let mut path_filter: Option<String> = None;-    if !operands.is_empty() {-        if !revisions.is_empty() {-            if operands.len() > 1 {-                return Err(Error::new("too many arguments"));-            }-            path_filter = Some(operands[0].clone());-        } else if operands.len() >= 2 {-            if operands.len() > 2 {-                return Err(Error::new("too many revisions"));-            }-            revisions.push(operands[0].clone());-            revisions.push(operands[1].clone());-        } else if existing_directory(&operands[0])-            && view-                .as_ref()-                .is_none_or(|view| !view_ref_named(view, &operands[0]))-        {-            path_filter = Some(operands[0].clone());-        } else if view.as_ref().is_some_and(|view| {-            graph::resolve_revision(&mut store, view, &operands[0])-                .ok()-                .flatten()-                .is_some()-        }) {-            revisions.push(operands[0].clone());-        } else {-            path_filter = Some(operands[0].clone());-        }-    }-    if revisions.len() > 2 {-        return Err(Error::new("too many revisions"));-    }-    if let Some(path) = path_filter.clone() {-        let cwd = crate::worktree::pathspec::cwd_relative(&root)-            .ok_or_else(|| Error::new("cannot determine current directory"))?;-        let normalized = crate::worktree::pathspec::pathspec_normalize(&root, &cwd, &path);-        if normalized.as_ref().is_none_or(|value| value.is_empty()) {-            return Err(Error::new(format!(-                "path is outside the repository: {path}"-            )));-        }-        path_filter = normalized;-    }--    let mut needs_snapshot = revisions.is_empty();-    let mut pre_resolved: Option<Vec<Id>> = None;-    if !needs_snapshot {-        if let Some(current) = &view {-            let working = ops::working_copy_id(current);-            let mut resolved = Vec::new();-            for revision in &revisions {-                if revision.is_empty() || revision == "@" {-                    needs_snapshot = true;-                    break;-                }-                let id = graph::resolve_revision(&mut store, current, revision)?;-                match id {-                    Some(id) if working != Some(id) => resolved.push(id),-                    _ => {-                        needs_snapshot = true;-                        break;-                    }-                }-            }-            if !needs_snapshot {-                pre_resolved = Some(resolved);-            }-        } else {-            needs_snapshot = true;-        }-    }-    if needs_snapshot {-        snapshot::run_with(&root, &mut store)?;-        view = ops::current_view(&root, &mut store)?;-        pre_resolved = None;-    }-    let view = view.ok_or_else(|| Error::new("no operation state"))?;-    let tree_of = |store: &mut Store, id: Id| -> Result<Option<Id>> {-        Ok(graph::load_commit(store, id)?.map(|commit| commit.root_tree))-    };-    let parent_tree_of = |store: &mut Store, id: Id| -> Result<Option<Id>> {-        let Some(commit) = graph::load_commit(store, id)? else {-            return Ok(None);-        };-        let Some(parent) = commit.parents.first() else {-            return Ok(None);-        };-        Ok(graph::load_commit(store, *parent)?.map(|parent| parent.root_tree))-    };-    let resolve_for = |store: &mut Store, index: usize| -> Result<Option<Id>> {-        if let Some(resolved) = &pre_resolved {-            if index < resolved.len() {-                return Ok(Some(resolved[index]));-            }-        }-        graph::resolve_revision(store, &view, &revisions[index])-    };-    let (old_tree, new_tree) = match revisions.len() {-        2 => {-            let Some(a) = resolve_for(&mut store, 0)? else {-                return Err(Error::new("unknown revision"));-            };-            let Some(b) = resolve_for(&mut store, 1)? else {-                return Err(Error::new("unknown revision"));-            };-            (tree_of(&mut store, a)?, tree_of(&mut store, b)?)-        }-        1 => {-            let Some(a) = resolve_for(&mut store, 0)? else {-                return Err(Error::new("unknown revision"));-            };-            (parent_tree_of(&mut store, a)?, tree_of(&mut store, a)?)-        }-        _ => match ops::working_copy_id(&view) {-            Some(working) => (-                parent_tree_of(&mut store, working)?,-                tree_of(&mut store, working)?,-            ),-            None => (None, None),-        },-    };-    let filter = path_filter-        .as_ref()-        .map(|value| value.as_bytes())-        .unwrap_or(b"");-    let mut buffer = Vec::new();-    let count = Collector::new(&mut buffer).render(&mut store, old_tree, new_tree, true, filter)?;-    let rendered = String::from_utf8_lossy(&buffer).into_owned();-    output::pager_output(&root, &rendered, count > 0 && !all);-    Ok(0)-}--pub fn new_change(arguments: &[String]) -> Result<u8> {-    let mut revisions = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            revisions.push(argument.clone());-        }-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let working_copy = ops::working_copy_id(txn.view());-    let (parents, root_tree, old_root) = if revisions.is_empty() {-        let working_copy = working_copy.ok_or_else(|| Error::new("no working-copy commit"))?;-        let loaded = graph::load_commit(&mut store, working_copy)?-            .ok_or_else(|| Error::new("cannot read working-copy commit"))?;-        (vec![working_copy], loaded.root_tree, Some(loaded.root_tree))-    } else {-        let mut parents = Vec::new();-        let mut root_tree = None;-        for revision in &revisions {-            let resolved = graph::resolve_revision(&mut store, txn.view(), revision)?-                .ok_or_else(|| Error::new("unknown revision"))?;-            parents.push(resolved);-            if root_tree.is_none() {-                root_tree =-                    graph::load_commit(&mut store, resolved)?.map(|commit| commit.root_tree);-            }-        }-        let old_root = match working_copy {-            Some(id) => graph::load_commit(&mut store, id)?.map(|commit| commit.root_tree),-            None => None,-        };-        (-            parents,-            root_tree.ok_or_else(|| Error::new("unknown revision"))?,-            old_root,-        )-    };-    let signature = identity::signature(&root);-    let commit = Commit {-        version: 1,-        parents,-        root_tree,-        change_id: identity::random_change_id(),-        author: signature.clone(),-        committer: signature,-        message: Vec::new(),-        renames_state: commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    let new_id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));-    if let Some(working_copy) = working_copy {-        ops::remove_head(txn.view_mut(), working_copy);-    }-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    txn.finish("new")?;-    store.refresh()?;-    mark_native(&root, new_id);-    if !revisions.is_empty() {-        crate::worktree::checkout::materialize(&root, &mut store, old_root, root_tree)?;-    }-    Ok(0)-}--fn mark_native(root: &Path, id: Id) {-    let path = layout::git_map_dir(root).join("native");-    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());-}--fn describe_impl(-    root: &Path,-    store: &mut Store,-    message: &str,-    require_changes: bool,-    start_new: bool,-) -> Result<u8> {-    snapshot::run_with(root, store)?;-    let mut txn = Txn::begin(root, store)?;-    let working_copy =-        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;-    let loaded = graph::load_commit(store, working_copy)?-        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;-    let changed = graph::has_changes(store, &loaded)?;-    let same = loaded.message == message.as_bytes();-    if !changed && (require_changes || same) {-        if require_changes {-            output::info_prefix();-            println!("nothing to commit, working copy clean");-            return Ok(2);-        }-        return Ok(0);-    }-    let signature = identity::signature(root);-    let mut updated = loaded;-    updated.committer = signature.clone();-    if !changed {-        updated.author = signature.clone();-    }-    updated.message = message.as_bytes().to_vec();-    let encoded = commit::encode(&updated);-    let new_id = txn.add_object(TYPE_COMMIT, encoded);-    ops::remove_head(txn.view_mut(), working_copy);-    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);-    if let Some(current) = core::current_bookmark_name(root)-        && ops::find_bookmark(txn.view(), current.as_bytes()).is_some()-    {-        ops::set_bookmark_target(txn.view_mut(), current.as_bytes(), new_id);-    }-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    if start_new {-        let view = txn.view().clone();-        let next = Commit {-            version: 1,-            parents: vec![new_id],-            root_tree: updated.root_tree,-            change_id: identity::random_change_id(),-            author: signature.clone(),-            committer: signature,-            message: Vec::new(),-            renames_state: commit::RENAMES_RECORDED,-            renames: Vec::new(),-            extra: Vec::new(),-        };-        let next_id = txn.add_object(TYPE_COMMIT, commit::encode(&next));-        ops::remove_head(txn.view_mut(), new_id);-        ops::set_workspace(txn.view_mut(), next_id);-        ops::rebuild_heads(txn.view_mut());-        let next_view = txn.view().clone();-        txn.finish_chain(vec![-            (view, "describe".to_string()),-            (next_view, "new".to_string()),-        ])?;-        store.refresh()?;-        mark_native(root, new_id);-        mark_native(root, next_id);-        return Ok(0);-    }-    txn.finish("describe")?;-    store.refresh()?;-    mark_native(root, new_id);-    Ok(0)-}--pub fn describe(arguments: &[String]) -> Result<u8> {-    let parts = super::args::parse_message(arguments, 0)?;-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    describe_impl(&root, &mut store, &output::join_args(&parts), false, false)-}--pub fn commit(arguments: &[String]) -> Result<u8> {-    let mut parts = super::args::parse_message(arguments, 0)?;-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    if output::message_is_blank(&parts) && core::stdin_is_terminal() {-        if let Some(edited) = edit_message(&root, &output::join_args(&parts))? {-            if edited.is_empty() {-                return Err(Error::new("commit requires a non-empty message (-message)"));-            }-            parts = vec![edited];-        }-    }-    if output::message_is_blank(&parts) {-        return Err(Error::new("commit requires a non-empty message (-message)"));-    }-    let mut store = Store::open(&root)?;-    let status = describe_impl(&root, &mut store, &output::join_args(&parts), true, true)?;-    if status == 2 { Ok(0) } else { Ok(status) }-}--fn edit_message(root: &Path, initial: &str) -> Result<Option<String>> {-    let file = layout::tmp_dir(root).join("commit-message.txt");-    let mut body = initial.to_string();-    if !body.is_empty() && !body.ends_with('\n') {-        body.push('\n');-    }-    body.push_str("\n# Enter a commit message. Lines starting with '#' are ignored.\n");-    if !core::write_file(&file, body.as_bytes()) {-        return Err(Error::new("cannot write message file"));-    }-    if !core::run_editor(root, &[], Some(&file)) {-        let _ = core::remove_file(&file);-        return Err(Error::new("editor exited with an error"));-    }-    let data = core::read_file_opt(&file, 0);-    let _ = core::remove_file(&file);-    let Some(data) = data else {-        return Ok(None);-    };-    let text = String::from_utf8_lossy(&data);-    let mut lines = Vec::new();-    for raw in text.lines() {-        let trimmed = raw.trim_start_matches([' ', '\t', '\r']);-        if trimmed.starts_with('#') || trimmed.is_empty() && raw.trim().is_empty() {-            lines.push(String::new());-        } else {-            lines.push(raw.trim_start_matches([' ', '\t', '\r']).to_string());-        }-    }-    while lines.last().is_some_and(|line| line.is_empty()) {-        lines.pop();-    }-    while lines.first().is_some_and(|line| line.is_empty()) {-        lines.remove(0);-    }-    Ok(Some(lines.join("\n")))-}--pub fn amend(arguments: &[String]) -> Result<u8> {-    let mut revision = String::new();-    let mut parts = Vec::new();-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-m" || argument == "-message") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a message")));-            }-            parts.push(arguments[index].clone());-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if revision.is_empty() {-            revision = argument.clone();-        } else {-            parts.push(argument.clone());-        }-        index += 1;-    }-    if revision.is_empty() {-        return Err(Error::new("amend requires a revision"));-    }-    if output::message_is_blank(&parts) {-        return Err(Error::new("amend requires a non-empty message (-message)"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?-        .ok_or_else(|| Error::new("unknown revision"))?;-    let mut pushed_roots = Vec::new();-    for reference in &txn.view().remote_refs {-        pushed_roots.push(reference.target);-    }-    if !pushed_roots.is_empty()-        && graph::collect_commits(&mut store, &pushed_roots)?.contains(&target)-    {-        return Err(Error::new("cannot amend a revision that has been pushed"));-    }-    let target_loaded = graph::load_commit(&mut store, target)?-        .ok_or_else(|| Error::new("cannot read revision"))?;-    let message = output::join_args(&parts);-    if target_loaded.message == message.as_bytes() {-        output::info_prefix();-        println!("message unchanged");-        return Ok(0);-    }-    let mut remaining = graph::all_commits(&mut store, txn.view())?;-    let mut old_ids = Vec::new();-    let mut new_ids = Vec::new();-    let signature = identity::signature(&root);-    let mut rewritten = false;-    let mut failed = false;-    while !remaining.is_empty() && !failed {-        let ready = remaining.iter().position(|id| {-            if *id == target {-                return true;-            }-            graph::load_commit(&mut store, *id)-                .ok()-                .flatten()-                .is_some_and(|commit| commit.parents.iter().any(|parent| old_ids.contains(parent)))-        });-        let Some(position) = ready else {-            break;-        };-        let chosen = remaining.remove(position);-        let Some(loaded) = graph::load_commit(&mut store, chosen)? else {-            failed = true;-            break;-        };-        let new_parents: Vec<Id> = loaded-            .parents-            .iter()-            .map(|parent| {-                old_ids-                    .iter()-                    .position(|value| value == parent)-                    .map(|index| new_ids[index])-                    .unwrap_or(*parent)-            })-            .collect();-        let mut commit = loaded;-        commit.parents = new_parents;-        commit.committer = signature.clone();-        if chosen == target {-            commit.message = message.as_bytes().to_vec();-        }-        let new_id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));-        old_ids.push(chosen);-        new_ids.push(new_id);-        if chosen == target {-            rewritten = true;-        }-    }-    if failed || !rewritten {-        return Err(Error::new("cannot amend revision"));-    }-    for bookmark in &mut txn.view_mut().bookmarks {-        remap(&old_ids, &new_ids, &mut bookmark.targets.adds);-        remap(&old_ids, &new_ids, &mut bookmark.targets.removes);-    }-    for tag in &mut txn.view_mut().tags {-        if let Some(mapped) = mapped(&old_ids, &new_ids, tag.target) {-            tag.target = mapped;-        }-    }-    for workspace in &mut txn.view_mut().working_copies {-        if let Some(mapped) = mapped(&old_ids, &new_ids, workspace.target) {-            workspace.target = mapped;-        }-    }-    for reference in &mut txn.view_mut().remote_refs {-        if let Some(mapped) = mapped(&old_ids, &new_ids, reference.target) {-            reference.target = mapped;-        }-    }-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("amend {revision}"))?;-    for id in new_ids {-        mark_native(&root, id);-    }-    Ok(0)-}--fn mapped(old: &[Id], new: &[Id], id: Id) -> Option<Id> {-    old.iter()-        .position(|value| *value == id)-        .map(|index| new[index])-}--fn remap(old: &[Id], new: &[Id], ids: &mut [Option<Id>]) {-    for value in ids {-        if let Some(id) = *value-            && let Some(mapped) = mapped(old, new, id)-        {-            *value = Some(mapped);-        }-    }-}--pub fn op(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        return Err(Error::new(-            "expected an op subcommand (log, restore, revert)",-        ));-    };-    match sub.as_str() {-        "log" => op_log(),-        "restore" => op_restore(arguments.get(1)),-        "revert" => op_revert(arguments.get(1)),-        _ => Err(Error::new(format!("unknown op subcommand: {sub}"))),-    }-}--struct OperationRecord {-    id: Id,-    operation: crate::object::view::Operation,-}--fn collect_operations(store: &mut Store, heads: &[Id]) -> Vec<OperationRecord> {-    let mut output = Vec::new();-    let mut seen = Vec::new();-    let mut stack: Vec<Id> = heads.iter().rev().copied().collect();-    while let Some(id) = stack.pop() {-        if seen.contains(&id) {-            continue;-        }-        seen.push(id);-        let Ok(Some(operation)) = store.operation(id) else {-            continue;-        };-        for parent in &operation.parents {-            if !seen.contains(parent) {-                stack.push(*parent);-            }-        }-        output.push(OperationRecord { id, operation });-    }-    output-}--fn op_log() -> Result<u8> {-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let heads = ops::read_heads(&root)?;-    let mut records = collect_operations(&mut store, &heads);-    records.sort_by(|left, right| right.operation.end.millis.cmp(&left.operation.end.millis));-    for record in records {-        let marker = if heads.contains(&record.id) { "@" } else { " " };-        println!(-            "{} {} {} {}",-            marker,-            record.id.short(),-            crate::time::format_utc(record.operation.end.millis / 1000),-            String::from_utf8_lossy(&record.operation.description)-        );-    }-    Ok(0)-}--fn resolve_operation(records: &[OperationRecord], text: &str) -> Option<usize> {-    let mut found = None;-    let mut count = 0;-    for (index, record) in records.iter().enumerate() {-        if record.id.to_hex().starts_with(text) {-            found = Some(index);-            count += 1;-        }-    }-    if count == 1 { found } else { None }-}--fn write_view(-    root: &Path,-    store: &mut Store,-    next: crate::object::view::View,-    description: &str,-) -> Result<u8> {-    let mut txn = Txn::begin(root, store)?;-    let old_tree = working_tree(store, txn.view())?;-    let new_tree = working_tree(store, &next)?;-    *txn.view_mut() = next;-    txn.finish(description)?;-    crate::worktree::checkout::materialize_optional(root, store, old_tree, new_tree)?;-    Ok(0)-}--fn working_tree(store: &mut Store, view: &crate::object::view::View) -> Result<Option<Id>> {-    let Some(working) = ops::working_copy_id(view) else {-        return Ok(None);-    };-    Ok(graph::load_commit(store, working)?.map(|commit| commit.root_tree))-}--fn op_restore(id: Option<&String>) -> Result<u8> {-    let id = id.ok_or_else(|| Error::new("op restore requires an operation id"))?;-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let heads = ops::read_heads(&root)?;-    let records = collect_operations(&mut store, &heads);-    let target = resolve_operation(&records, id).ok_or_else(|| Error::new("unknown operation"))?;-    let view = store-        .view(records[target].operation.view)?-        .ok_or_else(|| Error::new("cannot read operation view"))?;-    write_view(&root, &mut store, view, "op restore")-}--fn op_revert(id: Option<&String>) -> Result<u8> {-    let id = id.ok_or_else(|| Error::new("op revert requires an operation id"))?;-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let heads = ops::read_heads(&root)?;-    let records = collect_operations(&mut store, &heads);-    let target = resolve_operation(&records, id).ok_or_else(|| Error::new("unknown operation"))?;-    let operation = &records[target].operation;-    let mut view = crate::object::view::View::default();-    if let Some(parent) = operation.parents.first()-        && let Some(parent) = store.operation(*parent)?-        && let Some(parent_view) = store.view(parent.view)?-    {-        view = parent_view;-    }-    write_view(&root, &mut store, view, "op revert")-}--pub fn undo() -> Result<u8> {-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let heads = ops::read_heads(&root)?;-    if heads.is_empty() {-        return Err(Error::new("no operations to undo"));-    }-    let mut records = collect_operations(&mut store, &heads);-    records.sort_by(|left, right| right.operation.end.millis.cmp(&left.operation.end.millis));-    let Some(latest) = records.first() else {-        return Err(Error::new("cannot resolve undo target"));-    };-    let mut view = crate::object::view::View::default();-    if let Some(parent) = latest.operation.parents.first() {-        let parent = store-            .operation(*parent)?-            .ok_or_else(|| Error::new("cannot resolve undo target"))?;-        view = store-            .view(parent.view)?-            .ok_or_else(|| Error::new("cannot resolve undo target"))?;-    }-    write_view(&root, &mut store, view, "undo")-}--- a/veinsrs/src/cli/info.rs+++ /dev/null@@ -1,837 +0,0 @@-use std::collections::HashMap;-use std::path::Path;--use rayon::prelude::*;--use crate::core;-use crate::error::{Error, Result};-use crate::object::tree::{self, KIND_CONFLICT, KIND_SUBTREE};-use crate::object::{TYPE_BLOB, TYPE_COMMIT, TYPE_CONFLICT, TYPE_OPERATION, TYPE_TREE, TYPE_VIEW};-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::attributes::{AttributeRules, AttributeText};--use super::output;--pub fn version() -> Result<u8> {-    println!("veins v{} (store v1)", env!("CARGO_PKG_VERSION"));-    Ok(0)-}--pub fn help(arguments: &[String]) -> Result<u8> {-    let Some(command) = arguments.first() else {-        super::usage();-        return Ok(0);-    };-    let text = match command.as_str() {-        "log" => {-            "usage: vn log [-a] [-rev <revset>] [-lN | -fN] [-no-col-titles] [-p]\n\-             \nshow commit history, newest first\n\-             \noptions:\n  -a, -all                  show the entire history\n  -rev <revset>             show only the given revision set\n  -lN, -l <N>               show the last N commits (newest N)\n  -fN, -f <N>               show the first N commits (oldest N)\n  -no-col-titles            omit column titles\n  -p                        page the full history through the pager\n"-        }-        "show" => {-            "usage: vn show [-a] [rev] [-no-col-titles]\n\-             \nshow a commit's metadata and its diff against its first parent\n\-             \noptions:\n  -a, -all                  print the whole output at once\n  -no-col-titles            omit the metadata labels\n"-        }-        "diff" => {-            "usage: vn diff [-a] [-rev <rev>] [<rev> <rev>] [<path>]\n\-             \nshow a unified diff, paged when stdout is a terminal\n\-             \noptions:\n  -a, -all                  print the whole diff at once\n  -rev <rev>                compare a revision with its parent\n"-        }-        "go" | "commit" => {-            "usage: vn go -m <message>\n\-             \nrecord the working copy and start a new change\n\-             \naliases: commit\n"-        }-        "attr" => {-            "usage: vn attr <gen|txt|bin|lf|crlf|cr|rm|ls> ...\n\-             \nadd or remove .vnattribs rules\n\-             \nsubcommands:\n  vn attr gen <glob>...\n  vn attr rm gen <glob>...\n  vn attr ls\n"-        }-        "stat" | "status" => "usage: vn stat\n\nshow working-copy changes\n",-        "ls" => "usage: vn ls [rev] [-plain]\n\nlist tracked files\n",-        "hash" => "usage: vn hash [rev] [-short|-long]\n\nprint the commit hash for a revision\n",-        "new" => "usage: vn new [rev...]\n\nstart a new change\n",-        "co" | "checkout" => "usage: vn co [rev]\n\nwrite a revision into the working directory\n",-        "merge" => "usage: vn merge <rev>...\n\ncreate a merge commit; never fails\n",-        "rebase" => "usage: vn rebase -s <rev> [-d <rev>]\n\nrewrite changes onto a new parent\n",-        "xs" => "usage: vn xs [-porcelain]\n\nlist conflicted paths\n",-        "resolve" => "usage: vn resolve [-take ours|theirs] <path>\n\nresolve a conflicted path\n",-        "cfg" => "usage: vn cfg [<key>] [<value>]\n\nread and write configuration\n",-        "rm" => "usage: vn rm [-delete] <path>...\n\nuntrack paths\n",-        "mv" => "usage: vn mv <source> <destination>\n\nmove a tracked file\n",-        "ex" => "usage: vn ex <pattern>...\n\nadd exclude rules\n",-        "edit" => "usage: vn edit [path]...\n\nopen paths in the configured editor\n",-        "bmk" => {-            "usage: vn bmk <set|rename|ls|rm> ...\n\nmanage named branch pointers\n\-             \nsubcommands:\n  set <name> [-rev <rev>]   create or move a bookmark\n  rename <old> <new>        rename a bookmark\n  ls                        list bookmarks\n  rm <name>                 delete a bookmark\n"-        }-        "tag" => "usage: vn tag <set|ls|rm|latest> ...\n\nmanage named tags\n",-        "op" => "usage: vn op <log|restore|revert> ...\n\noperation log commands\n",-        "undo" => "usage: vn undo\n\nrestore the previous operation view\n",-        "fsck" => "usage: vn fsck [path] [-verbose]\n\nverify repository integrity\n",-        "inf" => "usage: vn inf [-inc-gen]\n\nshow a repository breakdown\n",-        "self-test" => "usage: vn self-test\n\nrun the format self-tests\n",-        "version" => "usage: vn version\n\nprint version information\n",-        "git" => {-            "usage: vn git <import|materialize|export|fetch|push|mirror|remote> ...\n\nimport from or export to git\n"-        }-        "remote" => "usage: vn remote <add|set-url|list|remove> ...\n\nmanage native remotes\n",-        "clone" => {-            "usage: vn clone <url> [-blobs:head|none|all] [-key:<name>] [-pin:<sha256>] [path]\n\nclone a repository\n"-        }-        "fetch" => "usage: vn fetch [<remote>] [path]\n\nfetch from a native remote\n",-        "pull" => {-            "usage: vn pull [<remote>] [path]\n\nfetch and fast-forward the current bookmark\n"-        }-        "push" | "psh" => {-            "usage: vn push [<remote>] [<bookmark>] [path]\n\npush a bookmark to a native remote\n"-        }-        "serve" => {-            "usage: vn serve -stdio <repo> [-quota <bytes>]\n\-             \x20      vn serve -listen <addr:port> -root <dir> -tls-cert <cert> -tls-key <key> [-quota <bytes>]\n\-             \nrun the native server over standard input/output or TLS 1.3\n"-        }-        "key" => "usage: vn key <generate|show|list> ...\n\nmanage local Ed25519 keys\n",-        "auth" => {-            "usage: vn auth <use|list|remove> ...\n\nremember keys for hosts and set a default\n"-        }-        "access" => {-            "usage: vn access <add|remove|anonymous|list> ...\n\nmanage a served repository's access file\n"-        }-        "whoami" => "usage: vn whoami [<remote>]\n\nreport the role granted by a server\n",-        "repack" | "gc" => "usage: vn repack [path] [-level:N] [-verbose]\n\nrewrite packs\n",-        other => {-            return Err(Error::new(format!("unknown command: {other}")));-        }-    };-    print!("{text}");-    Ok(0)-}--pub fn fsck(arguments: &[String]) -> Result<u8> {-    let mut path = ".".to_string();-    let mut verbose = false;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && matches!(argument.as_str(), "-v" | "-verbose") {-            verbose = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            path = argument.clone();-        }-    }-    let root = layout::discover(Path::new(&path))-        .map_err(|_| Error::new(format!("not a veins repository: {path}")))?;-    fsck_repository(&root, verbose)-}--fn fsck_repository(root: &Path, verbose: bool) -> Result<u8> {-    let mut errors = 0usize;-    let mut warnings = 0usize;-    let format = core::read_file_opt(&layout::format_path(root), 0);-    match format {-        Some(data) if data == b"veins-store 1" || data == b"veins-store 1\n" => {}-        _ => {-            output::error_prefix();-            println!("fsck: {}: invalid .veins/format", root.display());-            errors += 1;-        }-    }-    let promisor = core::read_file_opt(&layout::config_path(root), 0)-        .is_some_and(|data| data.windows(8).any(|window| window == b"promisor"));-    let packs = layout::packs_dir(root);-    let names = core::list_directory(&packs);-    let mut store = Store::open(root)?;-    let mut seen_objects: HashMap<_, ()> = HashMap::new();-    for name in &names {-        let text = String::from_utf8_lossy(name);-        if !text.ends_with(".vpack") {-            continue;-        }-        let path = packs.join(core::path_from_bytes(name));-        let Some(data) = core::read_file_opt(&path, crate::object::MAX_STORE_PACK_BYTES) else {-            output::error_prefix();-            println!("fsck: {}: cannot read pack", path.display());-            errors += 1;-            continue;-        };-        let pack = match crate::store::pack::decode(data) {-            Ok(pack) => pack,-            Err(_) => {-                output::error_prefix();-                println!("fsck: {}: invalid pack", path.display());-                errors += 1;-                continue;-            }-        };-        let stem = &text[..text.len() - 6];-        let index_path = packs.join(format!("{stem}.vidx"));-        let Some(index_data) =-            core::read_file_opt(&index_path, crate::object::MAX_STORE_PACK_BYTES)-        else {-            output::error_prefix();-            println!("fsck: {}: pack has no index", path.display());-            errors += 1;-            continue;-        };-        let index = match crate::store::index::decode(&index_data, Some(pack.trailer)) {-            Ok(index) => index,-            Err(_) => {-                output::error_prefix();-                println!("fsck: {}: invalid index", index_path.display());-                errors += 1;-                continue;-            }-        };-        if index.entries.len() != pack.records.len() {-            output::error_prefix();-            println!(-                "fsck: {}: pack and index object counts differ",-                path.display()-            );-            errors += 1;-            continue;-        }-        let mut visited = vec![false; pack.records.len()];-        for entry in &index.entries {-            let Some(position) = pack.find_by_offset(entry.offset) else {-                output::error_prefix();-                println!(-                    "fsck: {}: index offset names no record for {}",-                    path.display(),-                    entry.id.to_hex()-                );-                errors += 1;-                continue;-            };-            if pack.records[position].id != entry.id {-                output::error_prefix();-                println!(-                    "fsck: {}: index id does not match record for {}",-                    path.display(),-                    entry.id.to_hex()-                );-                errors += 1;-            }-            if visited[position] {-                output::error_prefix();-                println!(-                    "fsck: {}: record indexed more than once {}",-                    path.display(),-                    entry.id.to_hex()-                );-                errors += 1;-            }-            visited[position] = true;-        }-        for position in 0..pack.records.len() {-            if !visited[position] {-                output::error_prefix();-                println!(-                    "fsck: {}: record is not indexed {}",-                    path.display(),-                    pack.records[position].id.to_hex()-                );-                errors += 1;-            }-            let record = &pack.records[position];-            let Ok(body) = pack.get(position) else {-                output::error_prefix();-                println!(-                    "fsck: {}: invalid record {}",-                    path.display(),-                    record.id.to_hex()-                );-                errors += 1;-                continue;-            };-            if crate::object::id::object_id(record.kind, &body) != record.id {-                output::error_prefix();-                println!(-                    "fsck: {}: hash mismatch for {}",-                    path.display(),-                    record.id.to_hex()-                );-                errors += 1;-                continue;-            }-            if seen_objects.insert(record.id, ()).is_some() {-                warnings += 1;-            }-            check_object_refs(-                &mut store,-                &body,-                record.kind,-                promisor,-                &mut errors,-                &mut warnings,-            )?;-        }-    }-    let heads = ops::read_heads(root)?;-    for head in heads {-        if store.operation(head)?.is_none() {-            output::error_prefix();-            println!("fsck: operation head is missing: {}", head.to_hex());-            errors += 1;-        }-    }-    if verbose && warnings > 0 {-        output::warning_prefix();-        println!("{warnings} warning(s)");-    }-    if errors == 0 {-        output::info_prefix();-        println!("fsck: clean");-        Ok(0)-    } else {-        output::error_prefix();-        println!("{errors} error(s)");-        Ok(1)-    }-}--fn check_object_refs(-    store: &mut Store,-    body: &[u8],-    kind: u8,-    promisor: bool,-    errors: &mut usize,-    warnings: &mut usize,-) -> Result<()> {-    let mut check = |id: crate::object::id::Id, expected: u8| -> Result<()> {-        if store.contains(id) {-            return Ok(());-        }-        if promisor && matches!(expected, crate::object::TYPE_CHUNK | TYPE_BLOB) {-            *warnings += 1;-        } else {-            output::error_prefix();-            println!("fsck: missing object {}", id.to_hex());-            *errors += 1;-        }-        Ok(())-    };-    match kind {-        TYPE_BLOB => {-            if let Ok(blob) = crate::object::blob::decode(body) {-                if blob.form != crate::object::blob::BlobForm::Inline {-                    let expected = if blob.form == crate::object::blob::BlobForm::Leaf {-                        crate::object::TYPE_CHUNK-                    } else {-                        TYPE_BLOB-                    };-                    for entry in blob.entries {-                        check(entry.id, expected)?;-                    }-                }-            }-        }-        TYPE_TREE => {-            if let Ok(tree) = tree::decode(body) {-                for entry in tree.entries {-                    match entry.kind {-                        tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {-                            check(entry.target, TYPE_BLOB)?;-                        }-                        KIND_SUBTREE => check(entry.target, TYPE_TREE)?,-                        KIND_CONFLICT => check(entry.target, TYPE_CONFLICT)?,-                        _ => {}-                    }-                }-            }-        }-        TYPE_CONFLICT => {-            if let Ok(conflict) = crate::object::conflict::decode(body) {-                for value in conflict.adds.iter().chain(conflict.removes.iter()) {-                    if let Some(target) = value.target {-                        let expected = match value.kind {-                            1 | 2 | 3 => TYPE_BLOB,-                            4 => TYPE_TREE,-                            6 => TYPE_CONFLICT,-                            _ => continue,-                        };-                        check(target, expected)?;-                    }-                }-            }-        }-        TYPE_COMMIT => {-            if let Ok(commit) = crate::object::commit::decode(body) {-                for parent in commit.parents {-                    check(parent, TYPE_COMMIT)?;-                }-                check(commit.root_tree, TYPE_TREE)?;-            }-        }-        TYPE_OPERATION => {-            if let Ok(operation) = crate::object::view::decode_operation(body) {-                for parent in operation.parents {-                    check(parent, TYPE_OPERATION)?;-                }-                check(operation.view, TYPE_VIEW)?;-            }-        }-        TYPE_VIEW => {-            if let Ok(view) = crate::object::view::decode_view(body) {-                for head in view.heads {-                    check(head, TYPE_COMMIT)?;-                }-            }-        }-        _ => {}-    }-    Ok(())-}--pub fn repack(arguments: &[String]) -> Result<u8> {-    let mut path = ".".to_string();-    let mut verbose = false;-    let mut level = 6;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && matches!(argument.as_str(), "-v" | "-verbose") {-            verbose = true;-        } else if !end_flags && let Some(value) = argument.strip_prefix("-level:") {-            level = value-                .parse::<i32>()-                .map_err(|_| Error::new("-level: requires a value (1-19)"))?;-            if !(1..=19).contains(&level) {-                return Err(Error::new("compression level must be between 1 and 19"));-            }-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            path = argument.clone();-        }-    }-    let root = layout::discover(Path::new(&path))-        .map_err(|_| Error::new(format!("not a veins repository: {path}")))?;-    let packs = layout::packs_dir(&root);-    let mut objects = Vec::new();-    let mut seen = crate::store::pack::IdSet::default();-    let mut before = 0u64;-    let mut names = core::list_directory(&packs);-    names.sort();-    for name in names {-        let text = String::from_utf8_lossy(&name);-        if !text.ends_with(".vpack") {-            continue;-        }-        let path = packs.join(core::path_from_bytes(&name));-        let Some(data) = core::read_file_opt(&path, crate::object::MAX_STORE_PACK_BYTES) else {-            output::error_prefix();-            println!("cannot read pack {text}");-            return Ok(1);-        };-        before += data.len() as u64;-        let Ok(pack) = crate::store::pack::decode(data) else {-            output::error_prefix();-            println!("cannot decode pack {text}");-            return Ok(1);-        };-        for (index, record) in pack.records.iter().enumerate() {-            if !seen.insert(record.id) {-                continue;-            }-            let Ok(body) = pack.get(index) else {-                output::error_prefix();-                println!("cannot read object {}", record.id.to_hex());-                return Ok(1);-            };-            objects.push(crate::object::RawObject::known(-                record.kind,-                record.id,-                body,-            ));-        }-    }-    if objects.is_empty() {-        output::info_prefix();-        println!("no objects to repack");-        return Ok(0);-    }-    let output_pack = crate::store::pack::encode(&objects, level);-    if crate::store::pack::write_output(&root, &output_pack, 0) != 0 {-        output::error_prefix();-        println!("cannot write repacked pack");-        return Ok(1);-    }-    for name in core::list_directory(&packs) {-        let text = String::from_utf8_lossy(&name);-        let is_pack = text.ends_with(".vpack");-        let is_index = text.ends_with(".vidx");-        if !is_pack && !is_index {-            continue;-        }-        let stem = if is_pack {-            &text[..text.len() - 6]-        } else {-            &text[..text.len() - 5]-        };-        if stem == output_pack.name {-            continue;-        }-        let _ = core::remove_file(&packs.join(core::path_from_bytes(&name)));-    }-    if verbose {-        output::info_prefix();-        println!(-            "repacked {} objects, {} KiB -> {} KiB",-            output_pack.count,-            before / 1024,-            (output_pack.pack.len() + output_pack.index.len()) as u64 / 1024-        );-    }-    Ok(0)-}--pub fn inf(arguments: &[String]) -> Result<u8> {-    let mut include_generated = false;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags-            && matches!(-                argument.as_str(),-                "-inc-gen" | "-include-generated" | "--include-generated"-            )-        {-            include_generated = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        }-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let view = ops::current_view(&root, &mut store)?.unwrap_or_default();-    let working = ops::working_copy_id(&view);-    let rules = AttributeRules::load(&root);--    let mut total_files = 0u64;-    let mut total_lines = 0u64;-    let mut generated_files = 0u64;-    let mut generated_lines = 0u64;-    let mut generated_bytes = 0u64;-    let mut by_ext: HashMap<String, (u64, u64, u64)> = HashMap::new();--    let tree = match working {-        Some(working) => graph::load_commit(&mut store, working)?.map(|commit| commit.root_tree),-        None => None,-    };-    if let Some(tree) = tree {-        let entries = tree::flatten(&mut store, tree)?;-        let files: Vec<&tree::FlatEntry> = entries-            .iter()-            .filter(|entry| matches!(entry.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE))-            .collect();-        store.preload()?;--        struct FileResult {-            ext: String,-            lines: u64,-            bytes: u64,-            generated: bool,-        }--        let measure = |entry: &&tree::FlatEntry| -> FileResult {-            let attributes = rules.lookup(&String::from_utf8_lossy(&entry.path));-            let mut measured = graph::BlobMeasure::default();-            let ok = graph::measure_blob_loaded(&store, entry.target, &mut measured)-                .ok()-                .unwrap_or(false);-            let binary = attributes.text == AttributeText::Binary-                || (attributes.text == AttributeText::Auto && measured.has_nul);-            FileResult {-                ext: ext_of(&entry.path),-                lines: if binary || !ok { 0 } else { measured.lines },-                bytes: if ok { measured.bytes } else { 0 },-                generated: attributes.generated,-            }-        };--        let mut workers = std::thread::available_parallelism()-            .map(|value| value.get())-            .unwrap_or(1);-        workers = workers.min(files.len()).min(16);-        let results: Vec<FileResult> = if workers <= 1 {-            files.iter().map(measure).collect()-        } else {-            let pool = rayon::ThreadPoolBuilder::new()-                .num_threads(workers)-                .build()-                .map_err(|error| Error::new(error.to_string()))?;-            pool.install(|| files.par_iter().map(measure).collect())-        };--        for result in results {-            if result.generated {-                generated_files += 1;-                generated_lines += result.lines;-                generated_bytes += result.bytes;-                if !include_generated {-                    continue;-                }-            }-            total_files += 1;-            total_lines += result.lines;-            let stat = by_ext.entry(result.ext).or_insert((0, 0, 0));-            stat.0 += 1;-            stat.1 += result.lines;-            stat.2 += result.bytes;-        }-    }--    let mut commits = 0u64;-    let mut has_time = false;-    let mut created = 0i64;-    let mut last = 0i64;-    let mut authors: HashMap<String, u64> = HashMap::new();-    for id in graph::collect_commits(&mut store, &graph::view_roots(&view))? {-        let Some(commit) = graph::load_commit(&mut store, id)? else {-            continue;-        };-        commits += 1;-        let seconds = commit.committer.seconds;-        if has_time {-            created = created.min(seconds);-            last = last.max(seconds);-        } else {-            created = seconds;-            last = seconds;-            has_time = true;-        }-        let name = if commit.author.name.is_empty() {-            "(unknown)".to_string()-        } else {-            String::from_utf8_lossy(&commit.author.name).into_owned()-        };-        *authors.entry(name).or_insert(0) += 1;-    }--    println!();-    println!("{}", output::bold_cyan("Repository overview"));-    println!();-    row_value(-        "Project",-        &root.file_name().unwrap_or_default().to_string_lossy(),-    );-    print_left("HEAD", 14, None, true);-    match working {-        Some(id) => println!("{}", id.short()),-        None => println!("<none>"),-    }-    row_number("Changes", commits);-    row_number("Bookmarks", view.bookmarks.len() as u64);-    row_number("Tags", view.tags.len() as u64);-    row_number("Files", total_files);-    row_number("Lines", total_lines);-    row_number("Authors", authors.len() as u64);-    if has_time {-        show_date("Created", created);-        show_date("Last change", last);-    }-    print_left("Size", 14, None, true);-    println!("{}", size_text(dir_size(&layout::veins_dir(&root), 0)));-    if generated_files > 0 {-        print_left("Generated", 14, None, true);-        print!(-            "{generated_files} files  {generated_lines} lines  {}",-            size_text(generated_bytes)-        );-        if !include_generated {-            print!("  (excluded; use -inc-gen)");-        }-        println!();-    }-    println!();--    println!("{}", output::bold_cyan("Languages"));-    println!();-    if by_ext.is_empty() {-        println!("  no tracked files");-    } else {-        let mut entries: Vec<_> = by_ext.into_iter().collect();-        entries.sort_by(|left, right| {-            right-                .1-                .1-                .cmp(&left.1.1)-                .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))-        });-        let width = entries-            .iter()-            .fold(6usize, |width, (ext, _)| width.max(ext.len()));-        for (index, (ext, (files, lines, _))) in entries.into_iter().enumerate() {-            print_left(&ext, width, None, false);-            print!("  ");-            print_bar(lines, total_lines, index);-            print!("  ");-            print_percent(percent(lines, total_lines));-            println!("%  {lines} lines  {files} files");-        }-    }-    println!();--    println!("{}", output::bold_cyan("Authors"));-    println!();-    if authors.is_empty() {-        println!("  no commits");-    } else {-        let mut entries: Vec<_> = authors.into_iter().collect();-        entries.sort_by(|left, right| {-            right-                .1-                .cmp(&left.1)-                .then_with(|| left.0.as_bytes().cmp(right.0.as_bytes()))-        });-        let width = entries-            .iter()-            .fold(6usize, |width, (name, _)| width.max(name.len()));-        for (index, (name, count)) in entries.into_iter().enumerate() {-            print_left(&name, width, Some("36"), false);-            print!("  ");-            print_bar(count, commits, index);-            print!("  ");-            print_percent(percent(count, commits));-            println!("%  {count} commits");-        }-    }-    println!();-    Ok(0)-}--fn percent(value: u64, total: u64) -> u64 {-    if total == 0 {-        0-    } else {-        (value * 100 + total / 2) / total-    }-}--fn print_percent(value: u64) {-    if value < 10 {-        print!("  {value}");-    } else if value < 100 {-        print!(" {value}");-    } else {-        print!("{value}");-    }-}--fn bar_color(index: usize) -> &'static str {-    const COLORS: [&str; 8] = ["96", "92", "93", "95", "94", "91", "36", "32"];-    COLORS[index % COLORS.len()]-}--fn print_bar(value: u64, total: u64, index: usize) {-    let mut filled = 0u64;-    if total > 0 && value > 0 {-        filled = (value * 24 + total / 2) / total;-        if filled == 0 {-            filled = 1;-        }-        if filled > 24 {-            filled = 24;-        }-    }-    for _ in 0..filled {-        output::print_styled(bar_color(index), "\u{2588}");-    }-    for _ in filled..24 {-        output::print_styled("90", "\u{2591}");-    }-}--fn print_left(text: &str, width: usize, color: Option<&str>, dim: bool) {-    if dim {-        output::print_styled("2", text);-    } else if let Some(color) = color {-        output::print_styled(color, text);-    } else {-        print!("{text}");-    }-    for _ in text.len()..width {-        print!(" ");-    }-}--fn row_value(label: &str, value: &str) {-    print_left(label, 14, None, true);-    println!("{value}");-}--fn row_number(label: &str, value: u64) {-    print_left(label, 14, None, true);-    println!("{value}");-}--fn show_date(label: &str, seconds: i64) {-    let stamp = crate::time::format_utc(seconds);-    print_left(label, 14, None, true);-    println!("{}", &stamp[..10.min(stamp.len())]);-}--fn dir_size(path: &Path, depth: usize) -> u64 {-    if depth > 64 {-        return 0;-    }-    let Ok(entries) = std::fs::read_dir(path) else {-        return 0;-    };-    let mut total = 0u64;-    for entry in entries.flatten() {-        let Ok(metadata) = entry.metadata() else {-            continue;-        };-        if metadata.is_file() {-            total += metadata.len();-        } else if metadata.is_dir() {-            total += dir_size(&entry.path(), depth + 1);-        }-    }-    total-}--fn size_text(value: u64) -> String {-    if value >= 1_073_741_824 {-        format!(-            "{}.{} GiB",-            value / 1_073_741_824,-            ((value % 1_073_741_824) * 10) / 1_073_741_824-        )-    } else if value >= 1_048_576 {-        format!(-            "{}.{} MiB",-            value / 1_048_576,-            ((value % 1_048_576) * 10) / 1_048_576-        )-    } else if value >= 1024 {-        format!("{}.{} KiB", value / 1024, ((value % 1024) * 10) / 1024)-    } else {-        format!("{value} B")-    }-}--fn ext_of(path: &[u8]) -> String {-    let text = String::from_utf8_lossy(path);-    let base_start = text.rfind('/').map(|index| index + 1).unwrap_or(0);-    let dot = text.rfind('.');-    match dot {-        Some(position) if position > base_start && position + 1 < text.len() => {-            text[position..].to_ascii_lowercase()-        }-        _ => "(none)".to_string(),-    }-}---- a/veinsrs/src/cli/merge_cmd.rs+++ /dev/null@@ -1,615 +0,0 @@-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::identity;-use crate::merge::engine;-use crate::object::conflict::{self, Conflict, ConflictValue};-use crate::object::id::Id;-use crate::object::tree;-use crate::object::{TYPE_COMMIT, TYPE_CONFLICT};-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::checkout;-use crate::worktree::pathspec;-use crate::worktree::snapshot;--use super::output;--pub fn run(command: &str, arguments: &[String]) -> Result<u8> {-    match command {-        "merge" => merge(arguments),-        "rebase" => rebase(arguments),-        "xs" => xs(arguments),-        "resolve" => resolve(arguments),-        _ => Err(Error::new("unknown command")),-    }-}--fn mark_native(root: &Path, id: Id) {-    let path = layout::git_map_dir(root).join("native");-    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());-}--fn merge(arguments: &[String]) -> Result<u8> {-    let mut revisions = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            revisions.push(argument.clone());-        }-    }-    if revisions.is_empty() {-        return Err(Error::new("merge requires at least one revision"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let working_copy = ops::working_copy_id(txn.view())-        .ok_or_else(|| Error::new("no working-copy commit to merge into"))?;-    let mut parents = vec![working_copy];-    for revision in &revisions {-        let resolved = graph::resolve_revision(&mut store, txn.view(), revision)?-            .ok_or_else(|| Error::new("unknown revision"))?;-        if resolved == working_copy {-            return Err(Error::new("cannot merge a commit with itself"));-        }-        parents.push(resolved);-    }-    let old_root = engine::tree_of_commit(&mut store, working_copy)?;-    let adjacent = engine::adjacent(&root);-    let outcome = engine::merge_many(&root, &mut txn, &mut store, &parents, adjacent)?;-    let author = identity::signature(&root);-    let new_id = engine::make_commit(-        &mut txn,-        &mut store,-        &root,-        &parents,-        outcome.tree,-        identity::random_change_id(),-        author,-        "",-        crate::object::commit::RENAMES_RECORDED,-        &[],-    )?;-    ops::remove_head(txn.view_mut(), working_copy);-    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    let suffix = if outcome.rerere > 0 {-        format!(" (rerere {})", outcome.rerere)-    } else {-        String::new()-    };-    txn.finish(&format!("merge {}{suffix}", revisions.join(" ")))?;-    store.refresh()?;-    mark_native(&root, new_id);-    if let Some(old) = old_root {-        checkout::materialize(&root, &mut store, Some(old), outcome.tree)?;-    }-    Ok(0)-}--fn rebase(arguments: &[String]) -> Result<u8> {-    let mut source = String::new();-    let mut destination = String::new();-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-s" || argument == "-source") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            source = arguments[index].clone();-        } else if !end_flags && (argument == "-d" || argument == "-destination") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            destination = arguments[index].clone();-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            return Err(Error::new(format!("unexpected argument: {argument}")));-        }-        index += 1;-    }-    if source.is_empty() || destination.is_empty() {-        return Err(Error::new("rebase requires -s <rev> and -d <rev>"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let source_id = graph::resolve_revision(&mut store, txn.view(), &source)?-        .ok_or_else(|| Error::new("unknown revision"))?;-    let destination_id = graph::resolve_revision(&mut store, txn.view(), &destination)?-        .ok_or_else(|| Error::new("unknown revision"))?;-    let working_copy = ops::working_copy_id(txn.view());-    let old_working_tree = match working_copy {-        Some(id) => engine::tree_of_commit(&mut store, id)?,-        None => None,-    };-    let mut set = Vec::new();-    for commit in graph::all_commits(&mut store, txn.view())? {-        if engine::is_ancestor(&mut store, source_id, commit)? {-            set.push(commit);-        }-    }-    let adjacent = engine::adjacent(&root);-    let mut old_ids = Vec::new();-    let mut new_ids = Vec::new();-    let mut new_trees = Vec::new();-    let mut remaining = set.clone();-    let mut rerere_total = 0usize;-    while !remaining.is_empty() {-        let mut ready = None;-        for (index, id) in remaining.iter().enumerate() {-            let Some(loaded) = graph::load_commit(&mut store, *id)? else {-                continue;-            };-            let mut ok = true;-            for parent in &loaded.parents {-                if set.contains(parent) && !old_ids.contains(parent) && *id != source_id {-                    ok = false;-                }-            }-            if ok {-                ready = Some(index);-                break;-            }-        }-        let Some(index) = ready else {-            return Err(Error::new("rebase could not order commits"));-        };-        let chosen = remaining.remove(index);-        let loaded = graph::load_commit(&mut store, chosen)?-            .ok_or_else(|| Error::new("cannot read revision"))?;-        let mut new_parents = Vec::new();-        let mut new_parent_trees = Vec::new();-        for (position, parent) in loaded.parents.iter().enumerate() {-            if position == 0 && chosen == source_id {-                new_parents.push(destination_id);-                new_parent_trees-                    .push(engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default());-                continue;-            }-            if let Some(mapped) = old_ids.iter().position(|value| value == parent) {-                new_parents.push(new_ids[mapped]);-                new_parent_trees.push(new_trees[mapped]);-            } else {-                new_parents.push(*parent);-                new_parent_trees-                    .push(engine::tree_of_commit(&mut store, *parent)?.unwrap_or_default());-            }-        }-        if loaded.parents.is_empty() {-            new_parents.push(destination_id);-            new_parent_trees-                .push(engine::tree_of_commit(&mut store, destination_id)?.unwrap_or_default());-        }-        let outcome = engine::rewrite_tree(-            &root,-            &mut txn,-            &mut store,-            chosen,-            loaded.root_tree,-            &loaded.parents,-            &new_parents,-            &new_parent_trees,-            adjacent,-        )?;-        rerere_total += outcome.rerere;-        let new_id = engine::make_commit(-            &mut txn,-            &mut store,-            &root,-            &new_parents,-            outcome.tree,-            loaded.change_id,-            loaded.author,-            &String::from_utf8_lossy(&loaded.message),-            loaded.renames_state,-            &loaded.extra,-        )?;-        old_ids.push(chosen);-        new_ids.push(new_id);-        new_trees.push(outcome.tree);-    }-    for bookmark in &mut txn.view_mut().bookmarks {-        remap(&old_ids, &new_ids, &mut bookmark.targets.adds);-        remap(&old_ids, &new_ids, &mut bookmark.targets.removes);-    }-    for tag in &mut txn.view_mut().tags {-        if let Some(mapped) = map_id(&old_ids, &new_ids, tag.target) {-            tag.target = mapped;-        }-    }-    for workspace in &mut txn.view_mut().working_copies {-        if let Some(mapped) = map_id(&old_ids, &new_ids, workspace.target) {-            workspace.target = mapped;-        }-    }-    ops::rebuild_heads(txn.view_mut());-    let suffix = if rerere_total > 0 {-        format!(" (rerere {rerere_total})")-    } else {-        String::new()-    };-    txn.finish(&format!("rebase {source} onto {destination}{suffix}"))?;-    for id in &new_ids {-        mark_native(&root, *id);-    }-    if let Some(working_copy) = working_copy-        && let Some(index) = old_ids.iter().position(|value| *value == working_copy)-    {-        let mut refreshed = Store::open(&root)?;-        checkout::materialize(&root, &mut refreshed, old_working_tree, new_trees[index])?;-    }-    Ok(0)-}--fn map_id(old: &[Id], new: &[Id], id: Id) -> Option<Id> {-    old.iter()-        .position(|value| *value == id)-        .map(|index| new[index])-}--fn remap(old: &[Id], new: &[Id], ids: &mut [Option<Id>]) {-    for value in ids {-        if let Some(id) = *value-            && let Some(mapped) = map_id(old, new, id)-        {-            *value = Some(mapped);-        }-    }-}--fn conflict_entries(store: &mut Store, root_tree: Id) -> Result<Vec<(Vec<u8>, Conflict)>> {-    let mut output = Vec::new();-    for entry in tree::flatten(store, root_tree)? {-        if entry.kind != tree::KIND_CONFLICT {-            continue;-        }-        let Some(body) = store.body(entry.target, TYPE_CONFLICT)? else {-            continue;-        };-        let Ok(conflict) = conflict::decode(&body) else {-            continue;-        };-        output.push((entry.path, conflict));-    }-    Ok(output)-}--fn print_range(start: usize, end: usize) -> String {-    if start == end {-        (start + 1).to_string()-    } else {-        format!("{}-{end}", start + 1)-    }-}--fn xs(arguments: &[String]) -> Result<u8> {-    let mut porcelain = false;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && matches!(argument.as_str(), "-porcelain" | "-p") {-            porcelain = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            return Err(Error::new(format!("unexpected argument: {argument}")));-        }-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let Some(working_copy) = ops::working_copy_id(&view) else {-        output::info_prefix();-        println!("no conflicts");-        return Ok(0);-    };-    let Some(commit) = graph::load_commit(&mut store, working_copy)? else {-        return Err(Error::new("cannot read working-copy commit"));-    };-    let items = conflict_entries(&mut store, commit.root_tree)?;-    let adjacent = engine::adjacent(&root);-    for (path, conflict) in items {-        let kind = engine::conflict_kind_label(&conflict);-        let ranges = engine::conflict_ranges(&mut store, &conflict, adjacent)?;-        if porcelain {-            print!("{}\t{kind}\t", String::from_utf8_lossy(&path));-            if let Some(ranges) = ranges {-                for (index, range) in ranges.ranges.iter().enumerate() {-                    if index > 0 {-                        print!(",");-                    }-                    print!("{}", print_range(range.base_start, range.base_end));-                }-                print!("\t");-                for (index, range) in ranges.ranges.iter().enumerate() {-                    if index > 0 {-                        print!(",");-                    }-                    print!("{}", print_range(range.ours_start, range.ours_end));-                }-                print!("\t");-                for (index, range) in ranges.ranges.iter().enumerate() {-                    if index > 0 {-                        print!(",");-                    }-                    print!("{}", print_range(range.theirs_start, range.theirs_end));-                }-            } else {-                print!("\t\t");-            }-            println!();-        } else {-            print!("{}: {kind} conflict", String::from_utf8_lossy(&path));-            if let Some(ranges) = ranges {-                if !ranges.ranges.is_empty() {-                    print!(" (");-                    for (index, range) in ranges.ranges.iter().enumerate() {-                        if index > 0 {-                            print!(", ");-                        }-                        print!(-                            "base {}, ours {}, theirs {}",-                            print_range(range.base_start, range.base_end),-                            print_range(range.ours_start, range.ours_end),-                            print_range(range.theirs_start, range.theirs_end)-                        );-                    }-                    print!(")");-                }-            }-            println!();-        }-    }-    if items_is_empty(&mut store, working_copy)? {-        output::info_prefix();-        println!("no conflicts");-    }-    Ok(0)-}--fn items_is_empty(store: &mut Store, working_copy: Id) -> Result<bool> {-    let Some(commit) = graph::load_commit(store, working_copy)? else {-        return Ok(true);-    };-    Ok(tree::flatten(store, commit.root_tree)?-        .iter()-        .all(|entry| entry.kind != tree::KIND_CONFLICT))-}--fn choose<'a>(conflict: &'a Conflict, take: &str) -> Option<&'a ConflictValue> {-    match take {-        "ours" => conflict.adds.first(),-        "theirs" => conflict.adds.get(1),-        "base" => conflict.removes.first(),-        _ => None,-    }-}--fn shell_replace(command: &str, key: &str, value: &str) -> String {-    command.replace(key, &format!("'{value}'"))-}--fn run_tool(root: &Path, command: &str, path: &[u8]) -> bool {-    let base = core::path_display(&root.join(core::path_from_bytes(path)));-    let expanded = shell_replace(-        &shell_replace(-            &shell_replace(-                &shell_replace(command, "$BASE", &format!("{base}.base")),-                "$OURS",-                &format!("{base}.ours"),-            ),-            "$THEIRS",-            &format!("{base}.theirs"),-        ),-        "$OUTPUT",-        &base,-    );-    std::process::Command::new("sh")-        .arg("-c")-        .arg(expanded)-        .status()-        .is_ok_and(|status| status.success())-}--fn delete_sidecars(root: &Path, path: &[u8]) {-    let base = root.join(core::path_from_bytes(path));-    let _ = core::remove_file(&base.with_file_name(format!(-        "{}.base",-        base.file_name().unwrap_or_default().to_string_lossy()-    )));-    for suffix in [".ours", ".theirs"] {-        let mut full = path.to_vec();-        full.extend_from_slice(suffix.as_bytes());-        let _ = core::remove_file(&root.join(core::path_from_bytes(&full)));-    }-    let parent = base.parent().unwrap_or(root);-    let name = base.file_name().unwrap_or_default().to_string_lossy();-    for number in 2..=64 {-        let _ = core::remove_file(&parent.join(format!("{name}.base{number}")));-        let _ = core::remove_file(&parent.join(format!("{name}.theirs{number}")));-    }-    let _ = core::remove_file(&parent.join(format!("{name}.base")));-}--fn resolve(arguments: &[String]) -> Result<u8> {-    let mut take = String::new();-    let mut tool = String::new();-    let mut list_only = false;-    let mut paths = Vec::new();-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && matches!(argument.as_str(), "-list" | "-l") {-            list_only = true;-        } else if !end_flags && (argument == "-take" || argument == "-t") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!(-                    "{argument} requires ours, theirs, or base"-                )));-            }-            take = arguments[index].clone();-        } else if !end_flags && argument == "-tool" {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a command")));-            }-            tool = arguments[index].clone();-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            paths.push(argument.clone());-        }-        index += 1;-    }-    if list_only {-        return xs(&[]);-    }-    if paths.is_empty() {-        return Err(Error::new("resolve requires at least one path"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let working_copy =-        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;-    let loaded = graph::load_commit(&mut store, working_copy)?-        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;-    let old_root = loaded.root_tree;-    let mut root_tree = old_root;-    let mut resolved_any = false;-    let cwd = pathspec::cwd_relative(&root);-    let mut normalized_paths = Vec::new();-    for path in &paths {-        let Some(normalized) = cwd-            .as_ref()-            .and_then(|cwd| pathspec::pathspec_normalize(&root, cwd, path))-        else {-            output::error_prefix();-            println!("invalid path");-            continue;-        };-        if normalized.is_empty() {-            output::error_prefix();-            println!("invalid path");-            continue;-        }-        normalized_paths.push(normalized.clone());-        let flat = tree::flatten(&mut store, root_tree)?;-        let Some(entry) = flat-            .iter()-            .find(|entry| entry.path == normalized.as_bytes())-        else {-            output::error_prefix();-            println!("not a conflicted path: {normalized}");-            continue;-        };-        if entry.kind != tree::KIND_CONFLICT {-            output::error_prefix();-            println!("not a conflicted path: {normalized}");-            continue;-        }-        let conflict_id = entry.target;-        let Some(body) = store.body(conflict_id, TYPE_CONFLICT)? else {-            continue;-        };-        let Ok(conflict) = conflict::decode(&body) else {-            continue;-        };-        let mut present = false;-        let mut kind = tree::KIND_FILE;-        let mut target = None;-        if let Some(chosen) = choose(&conflict, &take) {-            if chosen.kind != 0 {-                present = true;-                kind = chosen.kind;-                target = chosen.target;-            }-        } else if !tool.is_empty() {-            if run_tool(&root, &tool, normalized.as_bytes())-                && let Some(data) =-                    core::read_file_opt(&root.join(core::path_from_bytes(normalized.as_bytes())), 0)-            {-                target = Some(engine::add_blob_data(&mut txn, &data));-                present = true;-                kind = tree::KIND_FILE;-            }-        } else if let Some(data) =-            core::read_file_opt(&root.join(core::path_from_bytes(normalized.as_bytes())), 0)-        {-            target = Some(engine::add_blob_data(&mut txn, &data));-            present = true;-            kind = tree::KIND_FILE;-        }-        if present-            && let Some(info) =-                core::stat_path(&root.join(core::path_from_bytes(normalized.as_bytes())))-            && info.executable-        {-            kind = tree::KIND_EXECUTABLE;-        }-        if present-            && matches!(kind, tree::KIND_FILE | tree::KIND_EXECUTABLE)-            && let Some(target) = target-        {-            engine::resolution_store(&root, &body, target);-        }-        if let Some(replaced) = engine::edit_tree(-            &mut txn,-            &mut store,-            root_tree,-            normalized.as_bytes(),-            present,-            kind,-            target.unwrap_or_default(),-        )? {-            root_tree = replaced;-            resolved_any = true;-        }-    }-    if !resolved_any {-        return Ok(1);-    }-    let mut commit = loaded;-    commit.root_tree = root_tree;-    commit.committer = identity::signature(&root);-    let new_id = txn.add_object(TYPE_COMMIT, crate::object::commit::encode(&commit));-    ops::remove_head(txn.view_mut(), working_copy);-    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    txn.finish("resolve")?;-    let mut refreshed = Store::open(&root)?;-    checkout::materialize(&root, &mut refreshed, Some(old_root), root_tree)?;-    for path in normalized_paths {-        delete_sidecars(&root, path.as_bytes());-    }-    Ok(0)-}--- a/veinsrs/src/cli/mod.rs+++ /dev/null@@ -1,126 +0,0 @@-pub mod args;-pub mod commands;-pub mod config_cmd;-pub mod diff;-pub mod history;-pub mod info;-pub mod merge_cmd;-pub mod net_cmd;-pub mod output;-pub mod refs;-pub mod status;-pub mod worktree_cmd;--use crate::Result;--pub fn run(arguments: &[String]) -> u8 {-    match dispatch(arguments) {-        Ok(code) => code,-        Err(error) => {-            output::error_prefix();-            println!("{error}");-            1-        }-    }-}--fn dispatch(arguments: &[String]) -> Result<u8> {-    let Some(command) = arguments.first() else {-        usage();-        return Ok(1);-    };-    let rest = &arguments[1..];-    match command.as_str() {-        "init" => commands::init::run(rest),-        "status" | "stat" => status::run(),-        "log" => history::log(rest),-        "show" => history::show(rest),-        "hash" => history::hash(rest),-        "ls" => history::list(rest),-        "diff" => history::diff(rest),-        "new" => history::new_change(rest),-        "desc" | "describe" => history::describe(rest),-        "go" | "commit" => history::commit(rest),-        "amend" => history::amend(rest),-        "op" => history::op(rest),-        "undo" => history::undo(),-        "co" | "checkout" => commands::checkout::run(rest),-        "bmk" => refs::bookmark(rest),-        "tag" => refs::tag(rest),-        "cfg" => config_cmd::run(rest),-        "rm" => worktree_cmd::remove(rest),-        "mv" => worktree_cmd::move_path(rest),-        "ex" => worktree_cmd::exclude(rest),-        "attr" => worktree_cmd::attr(rest),-        "edit" => worktree_cmd::edit(rest),-        "fsck" => info::fsck(rest),-        "repack" | "gc" => info::repack(rest),-        "inf" => info::inf(rest),-        "about" => {-            println!("By Navid Momtahen (C) - 2026");-            println!("https://veins.pages.dev");-            println!("https://veinsforge.top/navid/veins");-            Ok(0)-        }-        "self-test" => commands::selftest::run(),-        "version" | "-version" | "-v" => info::version(),-        "merge" | "rebase" | "xs" | "resolve" => merge_cmd::run(command, rest),-        "remote" | "clone" | "fetch" | "pull" | "pl" | "push" | "psh" | "gg" | "serve" | "key"-        | "auth" | "access" | "whoami" => net_cmd::run(command, rest),-        "git" => net_cmd::git(rest),-        "help" | "-help" | "-h" => info::help(rest),-        _ => Err(crate::Error::new(format!("unknown command: {command}"))),-    }-}--fn usage() {-    println!("veins is a tool for managing source code");-    println!();-    println!("commands:");-    println!("  init         create a repository");-    println!("  git          import from or export to git");-    println!("  remote       manage native remotes");-    println!("  clone        clone a repository over the native protocol");-    println!("  fetch        fetch from a native remote");-    println!("  pull         fetch and fast-forward the current bookmark; alias: pl");-    println!("  gg           fetch the active remote, or clone a URL");-    println!("  push         push a bookmark to a native remote");-    println!("  serve        run the native server over stdio or TLS");-    println!("  key          manage local Ed25519 keys");-    println!("  auth         remember keys for hosts and set a default");-    println!("  access       manage a served repository's access file");-    println!("  whoami       report the role granted by a server");-    println!("  co           write a revision into the working directory; alias: checkout");-    println!("  stat         show working-copy changes; alias: status");-    println!("  ls           list tracked files");-    println!("  inf          show a repository breakdown");-    println!("  log          show commit history");-    println!("  show         show a commit and its diff");-    println!("  hash         print the commit hash for a revision");-    println!("  diff         show a unified diff, paged on a terminal");-    println!("  merge        create a merge commit; never fails");-    println!("  rebase       rewrite changes onto a new parent");-    println!("  xs           list conflicted paths");-    println!("  resolve      resolve a conflicted path");-    println!("  new          start a new change");-    println!("  bmk          manage named branch pointers (set, rename, ls, rm)");-    println!("  tag          manage named tags");-    println!("  cfg          read and write configuration");-    println!("  edit         open paths in the configured text editor");-    println!("  rm           untrack paths, keeping files on disk by default");-    println!("  mv           move a tracked file and record the rename");-    println!("  ex           add paths or globs to .vnexclude");-    println!("  attr         add or remove .vnattribs rules");-    println!("  desc         set the working-copy commit message; alias: describe");-    println!("  go           describe and start a new change; alias: commit");-    println!("  amend        rewrite a revision's message and its descendants");-    println!("  undo         restore the previous operation view");-    println!("  op           operation log commands");-    println!("  fsck         verify repository integrity");-    println!("  repack       rewrite packs into one delta-compressed pack; alias: gc");-    println!("  self-test    run the format self-tests");-    println!("  version      print version information");-    println!("  help         show help for a command");-    println!();-    println!("run 'vn help <command>' for details");-}--- a/veinsrs/src/cli/net_cmd.rs+++ /dev/null@@ -1,1356 +0,0 @@-use std::collections::HashSet;-use std::path::{Path, PathBuf};--use crate::core;-use crate::crypto;-use crate::error::{Error, Result};-use crate::object::blob::{self, BlobForm};-use crate::object::commit::{self, Commit};-use crate::object::id::Id;-use crate::object::tree::{self, KIND_SUBTREE};-use crate::object::{TYPE_BLOB, TYPE_COMMIT, TYPE_TREE};-use crate::protocol::client::Client;-use crate::protocol::messages::{self, RefInfo, UpdateRef};-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::checkout;-use crate::worktree::snapshot;--use super::output;--pub fn run(command: &str, arguments: &[String]) -> Result<u8> {-    match command {-        "remote" => remote(arguments),-        "clone" => clone(arguments),-        "fetch" => fetch(arguments),-        "pull" | "pl" => pull(arguments),-        "push" | "psh" => push(arguments),-        "gg" => gg(arguments),-        "serve" => serve(arguments),-        "key" => key(arguments),-        "auth" => auth(arguments),-        "access" => access(arguments),-        "whoami" => whoami(arguments),-        _ => Err(Error::new("unknown command")),-    }-}--fn remote_key(remote: &str, field: &str) -> String {-    format!("remote.{remote}.{field}")-}--fn last_segment(path: &str) -> String {-    let trimmed = path.trim_end_matches('/');-    match trimmed.rsplit_once('/') {-        Some((_, name)) if !name.is_empty() => name.to_string(),-        _ if !trimmed.is_empty() && trimmed != "/" => trimmed.to_string(),-        _ => "repo".to_string(),-    }-}--fn list_remote_names(root: &Path) -> Vec<String> {-    let Some(data) = core::read_file_opt(&layout::config_path(root), 0) else {-        return Vec::new();-    };-    let text = String::from_utf8_lossy(&data);-    let mut output = Vec::new();-    for line in text.lines() {-        if let Some(rest) = line.strip_prefix("remote.")-            && let Some((name, _)) = rest.split_once(".url")-            && !name.is_empty()-            && !output.contains(&name.to_string())-        {-            output.push(name.to_string());-        }-    }-    output-}--fn remote(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        return Err(Error::new(-            "expected a remote subcommand (add, set-url, list, remove)",-        ));-    };-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    match sub.as_str() {-        "add" | "set-url" => {-            let replace = sub == "set-url";-            let mut name = String::new();-            let mut url = String::new();-            let mut key = None;-            let mut pin = None;-            for argument in &arguments[1..] {-                if let Some(value) = argument.strip_prefix("-key:") {-                    key = Some(value.to_string());-                } else if let Some(value) = argument.strip_prefix("-pin:") {-                    pin = Some(value.to_string());-                } else if core::is_flag(argument) {-                    return Err(Error::new(format!("unknown flag: {argument}")));-                } else if name.is_empty() {-                    name = argument.clone();-                } else if url.is_empty() {-                    url = argument.clone();-                } else {-                    return Err(Error::new("too many arguments"));-                }-            }-            if name.is_empty() || url.is_empty() {-                return Err(Error::new(if replace {-                    "remote set-url requires a name and URL"-                } else {-                    "remote add requires a name and URL"-                }));-            }-            let url_key = remote_key(&name, "url");-            let existing = core::repo_config_value(&root, &url_key);-            if existing.is_some() && !replace {-                return Err(Error::new(format!("remote already exists: {name}")));-            }-            if existing.is_none() && replace {-                return Err(Error::new(format!("unknown remote: {name}")));-            }-            if !core::repo_config_set(&root, &url_key, &url) {-                return Err(Error::new("cannot write repository config"));-            }-            if let Some(key) = key {-                let field = remote_key(&name, "key");-                let ok = if key.is_empty() {-                    core::repo_config_remove(&root, &field)-                } else {-                    core::repo_config_set(&root, &field, &key)-                };-                if !ok {-                    return Err(Error::new("cannot write repository config"));-                }-            }-            if let Some(pin) = pin {-                let field = remote_key(&name, "tls-pin");-                let ok = if pin.is_empty() {-                    core::repo_config_remove(&root, &field)-                } else {-                    core::repo_config_set(&root, &field, &pin)-                };-                if !ok {-                    return Err(Error::new("cannot write repository config"));-                }-            }-            Ok(0)-        }-        "list" | "ls" => {-            for name in list_remote_names(&root) {-                let url =-                    core::repo_config_value(&root, &remote_key(&name, "url")).unwrap_or_default();-                println!("{name}\t{url}");-            }-            Ok(0)-        }-        "remove" | "rm" => {-            let name = arguments.get(1).cloned().unwrap_or_default();-            if name.is_empty() {-                return Err(Error::new("remote remove requires a name"));-            }-            if core::repo_config_value(&root, &remote_key(&name, "url")).is_none() {-                return Err(Error::new(format!("unknown remote: {name}")));-            }-            core::repo_config_remove(&root, &remote_key(&name, "url"));-            core::repo_config_remove(&root, &remote_key(&name, "key"));-            core::repo_config_remove(&root, &remote_key(&name, "tls-pin"));-            Ok(0)-        }-        _ => Err(Error::new(format!("unknown remote subcommand: {sub}"))),-    }-}--fn active_remote(root: &Path) -> String {-    for key in ["remote.current", "remote.default"] {-        if let Some(name) = core::repo_config_value(root, key)-            && !name.is_empty()-            && core::repo_config_value(root, &remote_key(&name, "url")).is_some()-        {-            return name;-        }-    }-    if core::repo_config_value(root, &remote_key("o", "url")).is_some() {-        return "o".to_string();-    }-    list_remote_names(root)-        .into_iter()-        .next()-        .unwrap_or_else(|| "o".to_string())-}--fn remote_url(root: &Path, remote: &str) -> Option<String> {-    core::repo_config_value(root, &remote_key(remote, "url"))-}--fn remote_key_name(root: &Path, remote: &str) -> String {-    if let Some(key) = core::repo_config_value(root, &remote_key(remote, "key"))-        && crypto::local_key_exists(&key)-    {-        return key;-    }-    if let Some(url) = remote_url(root, remote)-        && let Some(key) = crypto::key_for_url(&url)-    {-        return key;-    }-    String::new()-}--fn default_target(refs: &[RefInfo]) -> Option<Id> {-    for reference in refs {-        if reference.kind == 0 && matches!(reference.name.as_str(), "main" | "master") {-            return Some(reference.target);-        }-    }-    refs.iter()-        .find(|reference| reference.kind == 0)-        .map(|reference| reference.target)-}--fn default_ref_name(refs: &[RefInfo]) -> Option<String> {-    for reference in refs {-        if reference.kind == 0 && matches!(reference.name.as_str(), "main" | "master") {-            return Some(reference.name.clone());-        }-    }-    refs.iter()-        .find(|reference| reference.kind == 0)-        .map(|reference| reference.name.clone())-}--fn set_bookmark(view: &mut crate::object::view::View, name: &str, target: Id) {-    ops::set_bookmark_target(view, name.as_bytes(), target);-}--fn set_tag(view: &mut crate::object::view::View, name: &str, target: Id) {-    if let Some(index) = ops::find_tag(view, name.as_bytes()) {-        view.tags[index].target = target;-    } else {-        view.tags.push(crate::object::view::TagRef {-            name: name.as_bytes().to_vec(),-            target,-        });-    }-}--fn set_remote_ref(view: &mut crate::object::view::View, remote: &str, name: &str, target: Id) {-    if let Some(reference) = view.remote_refs.iter_mut().find(|reference| {-        reference.remote == remote.as_bytes() && reference.name == name.as_bytes()-    }) {-        reference.target = target;-    } else {-        view.remote_refs.push(crate::object::view::RemoteRef {-            remote: remote.as_bytes().to_vec(),-            name: name.as_bytes().to_vec(),-            target,-        });-    }-}--fn apply_refs(root: &Path, refs: &[RefInfo], remote: &str, clone: bool) -> Result<()> {-    let mut store = Store::open(root)?;-    let mut txn = Txn::begin(root, &mut store)?;-    for reference in refs {-        if reference.kind == 1 {-            set_tag(txn.view_mut(), &reference.name, reference.target);-        } else if clone {-            set_bookmark(txn.view_mut(), &reference.name, reference.target);-        } else {-            set_remote_ref(txn.view_mut(), remote, &reference.name, reference.target);-            if ops::find_bookmark(txn.view(), reference.name.as_bytes()).is_none() {-                set_bookmark(txn.view_mut(), &reference.name, reference.target);-            }-        }-    }-    ops::rebuild_heads(txn.view_mut());-    if clone && let Some(target) = default_target(refs) {-        let child = create_working_copy(&mut txn, &mut store, target)?;-        ops::set_workspace(txn.view_mut(), child);-        ops::rebuild_heads(txn.view_mut());-    }-    txn.finish(if clone { "clone" } else { "fetch" })?;-    if clone {-        if let Some(name) = default_ref_name(refs) {-            core::set_current_bookmark(root, &name);-        } else {-            core::clear_current_bookmark(root);-        }-    }-    Ok(())-}--fn create_working_copy(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {-    let loaded = graph::load_commit(store, parent)?-        .ok_or_else(|| Error::new("cannot read parent commit"))?;-    let signature = crate::identity::signature(store.root());-    let commit = Commit {-        version: 1,-        parents: vec![parent],-        root_tree: loaded.root_tree,-        change_id: crate::identity::random_change_id(),-        author: signature.clone(),-        committer: signature,-        message: Vec::new(),-        renames_state: commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))-}--fn clone(arguments: &[String]) -> Result<u8> {-    let mut url = String::new();-    let mut path = String::new();-    let mut policy = "head".to_string();-    let mut key_name = String::new();-    let mut pin = String::new();-    for argument in arguments {-        if let Some(value) = argument.strip_prefix("-blobs:") {-            policy = value.to_string();-        } else if let Some(value) = argument.strip_prefix("-key:") {-            key_name = value.to_string();-        } else if let Some(value) = argument.strip_prefix("-pin:") {-            pin = value.to_string();-        } else if core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if url.is_empty() {-            url = argument.clone();-        } else {-            path = argument.clone();-        }-    }-    if url.is_empty() {-        return Err(Error::new("clone requires a URL"));-    }-    let parsed = messages::parse_url(&url).ok_or_else(|| Error::new("unsupported URL"))?;-    if path.is_empty() {-        path = last_segment(&parsed.path);-    }-    let destination = PathBuf::from(&path);-    if destination.exists() {-        if !destination.is_dir() {-            return Err(Error::new(format!(-                "destination already exists and is not a directory: {path}"-            )));-        }-        if !core::list_directory(&destination).is_empty() {-            return Err(Error::new(format!(-                "destination directory is not empty: {path}"-            )));-        }-    }-    let root = layout::init(&destination).map_err(|_| Error::new("cannot create repository"))?;-    if key_name.is_empty() {-        key_name = crypto::key_for_url(&url).unwrap_or_default();-    }-    core::repo_config_set(&root, &remote_key("o", "url"), &url);-    if !key_name.is_empty() {-        core::repo_config_set(&root, &remote_key("o", "key"), &key_name);-    }-    if !pin.is_empty() {-        core::repo_config_set(&root, &remote_key("o", "tls-pin"), &pin);-    }-    core::repo_config_set(&root, "remote.default", "o");-    let repo_name = messages::url_repo_name(&url);-    let mut client = Client::connect(&url, &key_name, &repo_name, &pin)?;-    let refs = client.list_refs()?;-    let wants: Vec<Id> = refs.iter().map(|reference| reference.target).collect();-    if wants.is_empty() {-        output::info_prefix();-        println!("cloned empty repository into {path}");-        return Ok(0);-    }-    client.negotiate(&wants, &[])?;-    client.fetch_skeleton(&root, &wants)?;-    apply_refs(&root, &refs, "o", true)?;-    core::repo_config_set(&root, "promisor", "o");-    let mut store = Store::open(&root)?;-    if let Some(view) = ops::current_view(&root, &mut store)?-        && let Some(working) = ops::working_copy_id(&view)-        && let Some(commit) = graph::load_commit(&mut store, working)?-    {-        checkout::materialize(&root, &mut store, None, commit.root_tree)?;-    }-    if policy == "none" {-        output::info_prefix();-        println!("cloned metadata only; blobs are promised");-    }-    output::info_prefix();-    println!("cloned into {path}");-    Ok(0)-}--fn fetch(arguments: &[String]) -> Result<u8> {-    let mut remote_name = String::new();-    let mut explicit_key = String::new();-    let mut explicit_pin = String::new();-    let mut path = ".".to_string();-    let mut have_remote = false;-    for argument in arguments {-        if let Some(value) = argument.strip_prefix("-key:") {-            explicit_key = value.to_string();-        } else if let Some(value) = argument.strip_prefix("-pin:") {-            explicit_pin = value.to_string();-        } else if core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if !have_remote {-            remote_name = argument.clone();-            have_remote = true;-        } else {-            path = argument.clone();-        }-    }-    let root =-        layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;-    if !have_remote {-        remote_name = active_remote(&root);-    }-    let url = remote_url(&root, &remote_name).ok_or_else(|| Error::new("unknown remote"))?;-    let key = if !explicit_key.is_empty() {-        explicit_key-    } else {-        remote_key_name(&root, &remote_name)-    };-    let repo_name = messages::url_repo_name(&url);-    let pin = if !explicit_pin.is_empty() {-        explicit_pin-    } else {-        core::repo_config_value(&root, &remote_key(&remote_name, "tls-pin")).unwrap_or_default()-    };-    let mut client = Client::connect(&url, &key, &repo_name, &pin)?;-    let refs = client.list_refs()?;-    let haves = ops::read_heads(&root)?;-    let wants: Vec<Id> = refs.iter().map(|reference| reference.target).collect();-    if wants.is_empty() {-        output::info_prefix();-        println!("no refs to fetch");-        return Ok(0);-    }-    client.negotiate(&wants, &haves)?;-    client.fetch_skeleton(&root, &wants)?;-    apply_refs(&root, &refs, &remote_name, false)?;-    output::info_prefix();-    println!("fetched from {remote_name}");-    Ok(0)-}--fn pull(arguments: &[String]) -> Result<u8> {-    let mut remote_name = String::new();-    let mut path = ".".to_string();-    let mut have_remote = false;-    for argument in arguments {-        if core::is_flag(argument) {-            if argument.starts_with("-key:") || argument.starts_with("-pin:") {-                continue;-            }-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if !have_remote {-            remote_name = argument.clone();-            have_remote = true;-        } else {-            path = argument.clone();-        }-    }-    let mut forward: Vec<String> = arguments-        .iter()-        .filter(|argument| argument.starts_with("-key:") || argument.starts_with("-pin:"))-        .cloned()-        .collect();-    if have_remote {-        forward.push(remote_name.clone());-    }-    if path != "." {-        forward.push(path.clone());-    }-    fetch(&forward)?;-    let root =-        layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;-    if !have_remote {-        remote_name = active_remote(&root);-    }-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let bookmark_name = core::current_bookmark_name(&root)-        .ok_or_else(|| Error::new("no current bookmark; check out a bookmark before pulling"))?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let Some(index) = ops::find_bookmark(&view, bookmark_name.as_bytes()) else {-        return Err(Error::new(format!(-            "current bookmark is missing: {bookmark_name}"-        )));-    };-    let bookmark = &view.bookmarks[index];-    let Some(local_target) = bookmark.targets.adds.first().copied().flatten() else {-        return Err(Error::new(format!(-            "current bookmark is conflicted: {bookmark_name}"-        )));-    };-    let remote_target = view-        .remote_refs-        .iter()-        .find(|reference| {-            reference.remote == remote_name.as_bytes() && reference.name == bookmark_name.as_bytes()-        })-        .map(|reference| reference.target)-        .ok_or_else(|| {-            Error::new(format!(-                "no {remote_name}/{bookmark_name} on remote {remote_name}"-            ))-        })?;-    if let Some(working) = ops::working_copy_id(&view)-        && let Some(loaded) = graph::load_commit(&mut store, working)?-    {-        if graph::tree_conflicted(&mut store, loaded.root_tree)? {-            return Err(Error::new("working copy has unresolved conflicts"));-        }-        if graph::has_changes(&mut store, &loaded)? {-            return Err(Error::new(-                "working copy has uncommitted changes; commit them before pulling",-            ));-        }-    }-    if local_target == remote_target {-        output::info_prefix();-        println!("already up to date with {remote_name}/{bookmark_name}");-        return checkout::run(&root, &bookmark_name).map(|_| 0);-    }-    if !engine_is_ancestor(&mut store, local_target, remote_target)? {-        if engine_is_ancestor(&mut store, remote_target, local_target)? {-            output::info_prefix();-            println!("local {bookmark_name} is ahead of {remote_name}/{bookmark_name}");-            return Ok(0);-        }-        return Err(Error::new(format!(-            "local {bookmark_name} and {remote_name}/{bookmark_name} have diverged; use 'vn merge {remote_name}/{bookmark_name}' or 'vn rebase'"-        )));-    }-    let mut txn = Txn::begin(&root, &mut store)?;-    ops::set_bookmark_target(txn.view_mut(), bookmark_name.as_bytes(), remote_target);-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("pull {bookmark_name} from {remote_name}"))?;-    store.refresh()?;-    checkout::run(&root, &bookmark_name)?;-    output::info_prefix();-    println!("pulled {bookmark_name} from {remote_name}");-    Ok(0)-}--fn engine_is_ancestor(store: &mut Store, ancestor: Id, descendant: Id) -> Result<bool> {-    if ancestor == descendant {-        return Ok(true);-    }-    Ok(graph::collect_commits(store, &[descendant])?.contains(&ancestor))-}--fn collect_commits_until(store: &mut Store, start: &[Id], stop: &HashSet<Id>) -> Result<Vec<Id>> {-    let mut output = Vec::new();-    let mut stack = Vec::new();-    let mut seen = HashSet::new();-    for id in start {-        if !stop.contains(id) && seen.insert(*id) {-            stack.push(*id);-        }-    }-    while let Some(id) = stack.pop() {-        output.push(id);-        let Some(commit) = graph::load_commit(store, id)? else {-            continue;-        };-        for parent in commit.parents {-            if !stop.contains(&parent) && seen.insert(parent) {-                stack.push(parent);-            }-        }-    }-    Ok(output)-}--#[derive(Default)]-struct ObjectWalk {-    blobs: HashSet<Id>,-    conflicts: HashSet<Id>,-    trees: HashSet<Id>,-    objects: HashSet<Id>,-    output: Vec<Id>,-}--impl ObjectWalk {-    fn add_object(&mut self, id: Id) {-        if self.objects.insert(id) {-            self.output.push(id);-        }-    }--    fn walk_blob(&mut self, store: &mut Store, id: Id) -> Result<()> {-        if !self.blobs.insert(id) {-            return Ok(());-        }-        self.add_object(id);-        let Some(body) = store.body(id, TYPE_BLOB)? else {-            return Ok(());-        };-        let Ok(blob) = blob::decode(&body) else {-            return Ok(());-        };-        match blob.form {-            BlobForm::Leaf => {-                for entry in blob.entries {-                    self.add_object(entry.id);-                }-            }-            BlobForm::Interior => {-                for entry in blob.entries {-                    self.walk_blob(store, entry.id)?;-                }-            }-            BlobForm::Inline => {}-        }-        Ok(())-    }--    fn walk_conflict(&mut self, store: &mut Store, id: Id) -> Result<()> {-        if !self.conflicts.insert(id) {-            return Ok(());-        }-        self.add_object(id);-        let Some(body) = store.body(id, crate::object::TYPE_CONFLICT)? else {-            return Ok(());-        };-        let Ok(conflict) = crate::object::conflict::decode(&body) else {-            return Ok(());-        };-        for value in conflict.adds.iter().chain(conflict.removes.iter()) {-            if let Some(target) = value.target {-                self.walk_value(store, value.kind, target)?;-            }-        }-        Ok(())-    }--    fn walk_value(&mut self, store: &mut Store, kind: u8, id: Id) -> Result<()> {-        match kind {-            KIND_SUBTREE => self.walk_tree(store, id)?,-            tree::KIND_CONFLICT => self.walk_conflict(store, id)?,-            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {-                self.walk_blob(store, id)?;-            }-            _ => {}-        }-        Ok(())-    }--    fn walk_entry(&mut self, store: &mut Store, entry: &tree::TreeEntry) -> Result<()> {-        match entry.kind {-            KIND_SUBTREE => self.walk_tree(store, entry.target)?,-            tree::KIND_CONFLICT => self.walk_conflict(store, entry.target)?,-            tree::KIND_SUBMODULE => {}-            _ => self.walk_blob(store, entry.target)?,-        }-        Ok(())-    }--    fn walk_tree(&mut self, store: &mut Store, id: Id) -> Result<()> {-        if !self.trees.insert(id) {-            return Ok(());-        }-        self.add_object(id);-        let Some(body) = store.body(id, TYPE_TREE)? else {-            return Ok(());-        };-        let Ok(tree) = tree::decode(&body) else {-            return Ok(());-        };-        for entry in &tree.entries {-            self.walk_entry(store, entry)?;-        }-        Ok(())-    }--    fn walk_tree_delta(&mut self, store: &mut Store, id: Id, old: Option<Id>) -> Result<()> {-        if old == Some(id) {-            return Ok(());-        }-        if !self.trees.insert(id) {-            return Ok(());-        }-        self.add_object(id);-        let Some(body) = store.body(id, TYPE_TREE)? else {-            return Ok(());-        };-        let Ok(tree) = tree::decode(&body) else {-            return Ok(());-        };-        let old_tree = match old {-            Some(old) => match store.body(old, TYPE_TREE)? {-                Some(body) => tree::decode(&body).ok(),-                None => None,-            },-            None => None,-        };-        let Some(old_tree) = old_tree else {-            for entry in &tree.entries {-                self.walk_entry(store, entry)?;-            }-            return Ok(());-        };-        let mut old_index = 0;-        for entry in &tree.entries {-            while old_index < old_tree.entries.len()-                && old_tree.entries[old_index].name < entry.name-            {-                old_index += 1;-            }-            if old_index >= old_tree.entries.len() || old_tree.entries[old_index].name != entry.name-            {-                self.walk_entry(store, entry)?;-                continue;-            }-            let old_entry = &old_tree.entries[old_index];-            old_index += 1;-            if old_entry.kind == entry.kind && old_entry.target == entry.target {-                continue;-            }-            if entry.kind == KIND_SUBTREE && old_entry.kind == KIND_SUBTREE {-                self.walk_tree_delta(store, entry.target, Some(old_entry.target))?;-            } else if entry.kind != tree::KIND_SUBMODULE {-                self.walk_entry(store, entry)?;-            }-        }-        Ok(())-    }-}--fn objects_for_commit_deltas(-    store: &mut Store,-    commits: &[Id],-    progress: Option<&crate::core::Progress>,-) -> Result<Vec<Id>> {-    let mut walk = ObjectWalk::default();-    for id in commits {-        walk.add_object(*id);-        if let Some(commit) = graph::load_commit(store, *id)? {-            let mut old_tree = None;-            let mut tree_covered = false;-            for parent_id in &commit.parents {-                let Some(parent) = graph::load_commit(store, *parent_id)? else {-                    continue;-                };-                if parent.root_tree == commit.root_tree {-                    tree_covered = true;-                    break;-                }-                if old_tree.is_none() {-                    old_tree = Some(parent.root_tree);-                }-            }-            if !tree_covered {-                walk.walk_tree_delta(store, commit.root_tree, old_tree)?;-            }-        }-        if let Some(progress) = progress {-            progress.advance(1);-        }-    }-    Ok(walk.output)-}--fn missing_objects(client: &mut Client, objects: &[Id]) -> Vec<Id> {-    const BATCH: usize = 100_000;-    let mut missing = Vec::new();-    for batch in objects.chunks(BATCH) {-        let Ok(bits) = client.have_query(batch) else {-            return objects.to_vec();-        };-        for (index, id) in batch.iter().enumerate() {-            if bits.get(index).copied().unwrap_or(0) == 0 {-                missing.push(*id);-            }-        }-    }-    missing-}--fn push(arguments: &[String]) -> Result<u8> {-    let mut remote_name = String::new();-    let mut bookmark = String::new();-    let mut explicit_key = String::new();-    let mut explicit_pin = String::new();-    let mut path = ".".to_string();-    let mut have_remote = false;-    for argument in arguments {-        if let Some(value) = argument.strip_prefix("-key:") {-            explicit_key = value.to_string();-        } else if let Some(value) = argument.strip_prefix("-pin:") {-            explicit_pin = value.to_string();-        } else if core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if !have_remote {-            remote_name = argument.clone();-            have_remote = true;-        } else if bookmark.is_empty() {-            bookmark = argument.clone();-        } else {-            path = argument.clone();-        }-    }-    let root =-        layout::discover(Path::new(&path)).map_err(|_| Error::new("not a veins repository"))?;-    if !have_remote {-        remote_name = active_remote(&root);-    }-    let url = remote_url(&root, &remote_name).ok_or_else(|| Error::new("unknown remote"))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    if bookmark.is_empty() {-        bookmark = core::current_bookmark_name(&root).unwrap_or_else(|| "master".to_string());-    }-    let bookmark_target = ops::find_bookmark(&view, bookmark.as_bytes())-        .and_then(|index| {-            view.bookmarks[index]-                .targets-                .adds-                .first()-                .copied()-                .flatten()-        })-        .ok_or_else(|| Error::new(format!("no such bookmark: {bookmark}")))?;-    let key = if !explicit_key.is_empty() {-        explicit_key-    } else {-        remote_key_name(&root, &remote_name)-    };-    let repo_name = messages::url_repo_name(&url);-    let pin = if !explicit_pin.is_empty() {-        explicit_pin-    } else {-        core::repo_config_value(&root, &remote_key(&remote_name, "tls-pin")).unwrap_or_default()-    };-    let mut client = Client::connect(&url, &key, &repo_name, &pin)?;-    let remote_refs = client.list_refs()?;-    let mut updates = Vec::new();-    let remote_bookmark = remote_refs-        .iter()-        .find(|reference| reference.kind == 0 && reference.name == bookmark)-        .map(|reference| reference.target);-    if remote_bookmark != Some(bookmark_target) {-        updates.push(UpdateRef {-            name: bookmark.clone(),-            expected: remote_bookmark,-            target: Some(bookmark_target),-        });-    }-    let mut tag_updates = 0usize;-    for tag in &view.tags {-        let name = String::from_utf8_lossy(&tag.name).into_owned();-        let remote = remote_refs-            .iter()-            .find(|reference| reference.kind == 1 && reference.name == name)-            .map(|reference| reference.target);-        if remote == Some(tag.target) {-            continue;-        }-        updates.push(UpdateRef {-            name: format!("refs/tags/{name}"),-            expected: remote,-            target: Some(tag.target),-        });-        tag_updates += 1;-    }-    if updates.is_empty() {-        output::info_prefix();-        println!("nothing to push, everything is up to date");-        return Ok(0);-    }-    let remote_commits: HashSet<Id> = remote_refs-        .iter()-        .map(|reference| reference.target)-        .collect();-    let mut roots = Vec::with_capacity(1 + view.tags.len());-    roots.push(bookmark_target);-    for tag in &view.tags {-        roots.push(tag.target);-    }-    let commits = collect_commits_until(&mut store, &roots, &remote_commits)?;-    let mut objects = Vec::new();-    if !commits.is_empty() {-        let collecting = crate::core::Progress::new("collecting objects", commits.len());-        objects = objects_for_commit_deltas(&mut store, &commits, Some(&collecting))?;-        collecting.finish();-    }-    if !objects.is_empty() {-        let missing = missing_objects(&mut client, &objects);-        if !missing.is_empty() {-            let pushing = crate::core::Progress::new("pushing objects", missing.len());-            client.push_objects(&root, &missing, Some(&pushing))?;-            pushing.finish();-        }-    }-    client.update_refs(&updates)?;-    output::info_prefix();-    println!("pushed {bookmark}");-    if tag_updates > 0 {-        output::info_prefix();-        println!("pushed {tag_updates} tag(s)");-    }-    Ok(0)-}--fn gg(arguments: &[String]) -> Result<u8> {-    let first = arguments-        .iter()-        .find(|argument| !core::is_flag(argument))-        .cloned()-        .unwrap_or_default();-    if first.contains("://") {-        return clone(arguments);-    }-    let Some(root) = layout::discover(Path::new(".")).ok() else {-        return clone(arguments);-    };-    let mut forwarded = arguments.to_vec();-    if first.is_empty() {-        forwarded.push(active_remote(&root));-    }-    fetch(&forwarded)-}--fn serve(arguments: &[String]) -> Result<u8> {-    let mut repo = ".".to_string();-    let mut stdio = false;-    let mut listen = String::new();-    let mut root = ".".to_string();-    let mut cert = String::new();-    let mut key = String::new();-    let mut quota = 0u64;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if argument == "-stdio" {-            stdio = true;-            if index + 1 < arguments.len() && !core::is_flag(&arguments[index + 1]) {-                index += 1;-                repo = arguments[index].clone();-            }-        } else if argument == "-listen" {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new("-listen requires an address"));-            }-            listen = arguments[index].clone();-        } else if argument == "-root" {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new("-root requires a directory"));-            }-            root = arguments[index].clone();-        } else if argument == "-tls-cert" {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new("-tls-cert requires a path"));-            }-            cert = arguments[index].clone();-        } else if argument == "-tls-key" {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new("-tls-key requires a path"));-            }-            key = arguments[index].clone();-        } else if argument == "-quota" {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new("-quota requires a byte count"));-            }-            quota = arguments[index]-                .parse()-                .map_err(|_| Error::new("-quota requires a byte count"))?;-        } else if let Some(value) = argument.strip_prefix("-quota:") {-            quota = value-                .parse()-                .map_err(|_| Error::new("-quota requires a byte count"))?;-        } else if core::is_flag(argument) {-            return Err(Error::new(format!("unknown serve option: {argument}")));-        } else {-            repo = argument.clone();-        }-        index += 1;-    }-    if stdio {-        let root =-            layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?;-        crate::server::serve_stdio(&root, quota)?;-        return Ok(0);-    }-    if listen.is_empty() {-        return Err(Error::new("serve requires -stdio or -listen"));-    }-    if cert.is_empty() || key.is_empty() {-        return Err(Error::new("TLS requires -tls-cert and -tls-key"));-    }-    let root = std::fs::canonicalize(&root)-        .map_err(|_| Error::new("cannot open the server root directory"))?;-    if !root.is_dir() {-        return Err(Error::new("the server root is not a directory"));-    }-    crate::server::serve_listen(&listen, &root, &cert, &key, quota)?;-    Ok(0)-}--fn key(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        return Err(Error::new("key requires a subcommand"));-    };-    match sub.as_str() {-        "generate" => {-            let name = arguments-                .get(1)-                .cloned()-                .unwrap_or_else(|| "default".to_string());-            let key =-                crypto::generate_key(&name).ok_or_else(|| Error::new("cannot generate key"))?;-            println!("name: {}", key.name);-            println!("public key: {}", crypto::format_public_key(&key.public_key));-            println!("fingerprint: {}", key.fingerprint);-            Ok(0)-        }-        "show" => {-            let name = arguments.get(1).cloned().unwrap_or_default();-            let key = crypto::load_key(&name).ok_or_else(|| Error::new("no such key"))?;-            println!("name: {}", key.name);-            println!("public key: {}", crypto::format_public_key(&key.public_key));-            println!("fingerprint: {}", key.fingerprint);-            Ok(0)-        }-        "list" | "ls" => {-            for name in crypto::list_key_names() {-                println!("{name}");-            }-            Ok(0)-        }-        _ => Err(Error::new(format!("unknown key subcommand: {sub}"))),-    }-}--fn auth(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        return Err(Error::new("auth requires a subcommand"));-    };-    match sub.as_str() {-        "use" => {-            let name = arguments.get(1).cloned().unwrap_or_default();-            if name.is_empty() {-                return Err(Error::new("auth use requires a key name"));-            }-            if !crypto::load_key(&name).is_some() {-                return Err(Error::new("no such key"));-            }-            let target = arguments-                .get(2)-                .map(|value| crypto::normalize_target(value))-                .unwrap_or_else(|| "default".to_string());-            if !crypto::set_key(&target, &name) {-                return Err(Error::new("cannot store key mapping"));-            }-            Ok(0)-        }-        "list" | "ls" => {-            for line in crypto::list_credentials() {-                print!("{line}");-            }-            Ok(0)-        }-        "remove" | "rm" => {-            let target = arguments-                .get(1)-                .map(|value| crypto::normalize_target(value))-                .unwrap_or_else(|| "default".to_string());-            if !crypto::remove_key(&target) {-                return Err(Error::new("no such key mapping"));-            }-            Ok(0)-        }-        _ => Err(Error::new(format!("unknown auth subcommand: {sub}"))),-    }-}--fn read_public_key(argument: &str) -> Option<crypto::PublicKey> {-    if argument.starts_with("ed25519:") {-        return crypto::parse_public_key(argument);-    }-    let data = core::read_file_opt(Path::new(argument), 0)?;-    let text = String::from_utf8_lossy(&data);-    crypto::parse_public_key(text.trim())-}--fn access(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        return Err(Error::new("access requires a subcommand"));-    };-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    match sub.as_str() {-        "add" => {-            let mut role = 1u8;-            let mut key = String::new();-            let mut name = String::new();-            let mut index = 1;-            while index < arguments.len() {-                match arguments[index].as_str() {-                    "-role" => {-                        index += 1;-                        if index >= arguments.len() {-                            return Err(Error::new("-role requires read or write"));-                        }-                        role = match arguments[index].as_str() {-                            "write" => 2,-                            "read" => 1,-                            _ => return Err(Error::new("-role requires read or write")),-                        };-                    }-                    "-key" => {-                        index += 1;-                        if index >= arguments.len() {-                            return Err(Error::new("-key requires a public key"));-                        }-                        key = arguments[index].clone();-                    }-                    "-name" => {-                        index += 1;-                        if index >= arguments.len() {-                            return Err(Error::new("-name requires a value"));-                        }-                        name = arguments[index].clone();-                    }-                    value if core::is_flag(value) => {-                        return Err(Error::new(format!("unknown flag: {value}")));-                    }-                    value => {-                        if key.is_empty() {-                            key = value.to_string();-                        } else if name.is_empty() {-                            name = value.to_string();-                        }-                    }-                }-                index += 1;-            }-            let public_key =-                read_public_key(&key).ok_or_else(|| Error::new("invalid public key"))?;-            if !crypto::add_access(&root, role, &public_key, &name) {-                return Err(Error::new("cannot add access entry"));-            }-            output::info_prefix();-            println!("added access entry");-            Ok(0)-        }-        "remove" | "rm" => {-            let mut fingerprint = String::new();-            let mut name = String::new();-            for argument in &arguments[1..] {-                if let Some(value) = argument.strip_prefix("-fingerprint:") {-                    fingerprint = value.to_string();-                } else if let Some(value) = argument.strip_prefix("-name:") {-                    name = value.to_string();-                } else if fingerprint.is_empty() {-                    fingerprint = argument.clone();-                } else {-                    name = argument.clone();-                }-            }-            if !crypto::remove_access(&root, &fingerprint, &name) {-                return Err(Error::new("no matching access entry"));-            }-            Ok(0)-        }-        "anonymous" => {-            let value = arguments.get(1).map(|value| value.as_str()).unwrap_or("");-            let enabled = matches!(value, "on" | "true" | "yes");-            if !crypto::set_anonymous(&root, enabled) {-                return Err(Error::new("cannot write access file"));-            }-            Ok(0)-        }-        "list" | "ls" => {-            let access = crypto::load_access(&root);-            if !access.valid {-                return Err(Error::new("invalid access file"));-            }-            if access.anonymous_read {-                println!("anonymous read");-            }-            for entry in &access.entries {-                println!(-                    "allow {} {} {}",-                    if entry.role == 2 { "write" } else { "read" },-                    crypto::format_public_key(&entry.public_key),-                    entry.name-                );-            }-            Ok(0)-        }-        _ => Err(Error::new(format!("unknown access subcommand: {sub}"))),-    }-}--fn whoami(arguments: &[String]) -> Result<u8> {-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let remote = arguments-        .first()-        .cloned()-        .unwrap_or_else(|| active_remote(&root));-    let url = remote_url(&root, &remote).ok_or_else(|| Error::new("unknown remote"))?;-    let key = remote_key_name(&root, &remote);-    let repo_name = messages::url_repo_name(&url);-    let pin = core::repo_config_value(&root, &remote_key(&remote, "tls-pin")).unwrap_or_default();-    let mut client = Client::connect(&url, &key, &repo_name, &pin)?;-    let (role, _) = client.whoami()?;-    println!("role: {}", messages::role_name(role));-    Ok(0)-}--pub fn git(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        return Err(Error::new("git requires a subcommand"));-    };-    match sub.as_str() {-        "import" => {-            let mut source = None;-            let mut remote = String::new();-            let mut path = ".".to_string();-            for argument in &arguments[1..] {-                if let Some(value) = argument.strip_prefix("-source:") {-                    source = Some(value.to_string());-                } else if let Some(value) = argument.strip_prefix("-remote:") {-                    remote = value.to_string();-                } else if !core::is_flag(argument) {-                    path = argument.clone();-                }-            }-            let root = layout::discover(Path::new(&path))-                .map_err(|_| Error::new("not a veins repository"))?;-            if let Some(source) = source {-                let prepared = crate::git::prepare_mirror(&root, &source);-                if prepared != 0 {-                    return Err(Error::new("cannot prepare git mirror"));-                }-            }-            let status = crate::git::import(&root);-            if status != 0 {-                return Ok(1);-            }-            if !remote.is_empty() {-                crate::git::configure_remote(&root, &remote, "o");-            }-            Ok(0)-        }-        "materialize" => {-            let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());-            let root = layout::discover(Path::new(&path))-                .map_err(|_| Error::new("not a veins repository"))?;-            Ok(crate::git::materialize(&root) as u8)-        }-        "export" => {-            let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());-            let root = layout::discover(Path::new(&path))-                .map_err(|_| Error::new("not a veins repository"))?;-            Ok(crate::git::export(&root) as u8)-        }-        "fetch" => {-            let path = arguments.get(1).cloned().unwrap_or_else(|| ".".to_string());-            let root = layout::discover(Path::new(&path))-                .map_err(|_| Error::new("not a veins repository"))?;-            Ok(crate::git::fetch(&root, "origin") as u8)-        }-        "remote" => {-            let sub = arguments.get(1).map(|value| value.as_str()).unwrap_or("");-            let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-            match sub {-                "add" => {-                    let name = arguments.get(2).cloned().unwrap_or_default();-                    let url = arguments.get(3).cloned().unwrap_or_default();-                    Ok(crate::git::mirror_remote(&root, "add", &name, &url) as u8)-                }-                "remove" | "rm" => {-                    let name = arguments.get(2).cloned().unwrap_or_default();-                    Ok(crate::git::mirror_remote(&root, "remove", &name, "") as u8)-                }-                "list" | "ls" => {-                    for name in crate::git::mirror_remote_list(&root) {-                        println!("{name}");-                    }-                    Ok(0)-                }-                _ => Err(Error::new("unknown git remote subcommand")),-            }-        }-        "mirror" => {-            let action = arguments.get(1).map(|value| value.as_str()).unwrap_or("");-            let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-            let force = !arguments.iter().any(|argument| argument == "-no-force");-            let prune = arguments.iter().any(|argument| argument == "-prune");-            let dry_run = arguments.iter().any(|argument| argument == "-dry-run");-            let options = crate::git::MirrorOptions {-                force,-                prune,-                dry_run,-            };-            match action {-                "push" | "psh" => {-                    let remote = arguments-                        .iter()-                        .skip(2)-                        .find(|argument| !core::is_flag(argument))-                        .cloned()-                        .or_else(|| crate::git::mirror_remote_list(&root).into_iter().next())-                        .unwrap_or_else(|| "origin".to_string());-                    let status = crate::git::mirror_push(&root, &remote, &options);-                    if status == 0-                        && !dry_run-                        && let Some(view) = crate::store::ops::current_view(-                            &root,-                            &mut crate::store::Store::open(&root)?,-                        )-                        .ok()-                        .flatten()-                    {-                        println!("info: mirrored {} bookmark(s)", view.bookmarks.len());-                    }-                    Ok(status as u8)-                }-                "pt" | "tag" => {-                    let tag = arguments.get(2).cloned().unwrap_or_default();-                    let remote = arguments-                        .get(3)-                        .cloned()-                        .unwrap_or_else(|| "origin".to_string());-                    let mut store = Store::open(&root)?;-                    let view = ops::current_view(&root, &mut store)?.unwrap_or_default();-                    if ops::find_tag(&view, tag.as_bytes()).is_none() {-                        return Err(Error::new(format!("unknown tag: {tag}")));-                    }-                    let status = crate::git::mirror_tag(&root, &remote, &tag, &options);-                    Ok(status as u8)-                }-                _ => Err(Error::new("unknown git mirror subcommand")),-            }-        }-        "push" => {-            let remote = arguments-                .get(1)-                .cloned()-                .unwrap_or_else(|| "origin".to_string());-            let bookmark = arguments-                .get(2)-                .cloned()-                .unwrap_or_else(|| "master".to_string());-            let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-            Ok(crate::git::push(&root, &remote, &bookmark) as u8)-        }-        _ => Err(Error::new(format!("unknown git subcommand: {sub}"))),-    }-}--- a/veinsrs/src/cli/output.rs+++ /dev/null@@ -1,117 +0,0 @@-use crate::core;--pub fn enabled() -> bool {-    core::colors_enabled()-}--fn style(text: &str, code: &str) -> String {-    if enabled() {-        format!("\x1b[{code}m{text}\x1b[0m")-    } else {-        text.to_string()-    }-}--pub fn print_styled(code: &str, text: &str) {-    if enabled() {-        print!("\x1b[{code}m{text}\x1b[0m");-    } else {-        print!("{text}");-    }-}--pub fn error_prefix() {-    if enabled() {-        print!("\x1b[1m\x1b[31merror\x1b[0m: ");-    } else {-        print!("error: ");-    }-}--pub fn warning_prefix() {-    if enabled() {-        print!("\x1b[1m\x1b[33mwarning\x1b[0m: ");-    } else {-        print!("warning: ");-    }-}--pub fn info_prefix() {-    print!("{}: ", style("info", "36"));-}--pub fn red(text: &str) -> String {-    style(text, "31")-}--pub fn green(text: &str) -> String {-    style(text, "32")-}--pub fn cyan(text: &str) -> String {-    style(text, "36")-}--pub fn dim(text: &str) -> String {-    style(text, "2")-}--pub fn bold_cyan(text: &str) -> String {-    if enabled() {-        format!("\x1b[1m\x1b[96m{text}\x1b[0m")-    } else {-        text.to_string()-    }-}--pub fn print_cell(text: &str, width: usize) {-    print!("{text}");-    for _ in text.chars().count()..width {-        print!(" ");-    }-}--pub fn open_repo() -> Option<std::path::PathBuf> {-    crate::store::layout::discover(std::path::Path::new(".")).ok()-}--pub fn status_path(path: &[u8], cwd_rel: &str) -> String {-    let path = String::from_utf8_lossy(path);-    if cwd_rel.is_empty() {-        return path.into_owned();-    }-    let current: Vec<&str> = cwd_rel-        .split('/')-        .filter(|value| !value.is_empty())-        .collect();-    let target: Vec<&str> = path.split('/').collect();-    let mut common = 0;-    while common < current.len() && common < target.len() && current[common] == target[common] {-        common += 1;-    }-    let mut output = String::new();-    for _ in common..current.len() {-        output.push_str("../");-    }-    output.push_str(&target[common..].join("/"));-    output-}--pub fn join_args(parts: &[String]) -> String {-    parts.join(" ")-}--pub fn message_is_blank(parts: &[String]) -> bool {-    parts-        .iter()-        .flat_map(|part| part.bytes())-        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))-}--pub fn pager_output(root: &std::path::Path, text: &str, pager: bool) {-    if pager && core::stdout_is_terminal() {-        core::run_pager(root, text);-    } else {-        print!("{text}");-    }-}--- a/veinsrs/src/cli/refs.rs+++ /dev/null@@ -1,577 +0,0 @@-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::object::view::{Bookmark, TagRef};-use crate::store::Txn;-use crate::store::graph;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::snapshot;--use super::output;--fn valid_ref_name(name: &str) -> bool {-    if name.is_empty() || name.len() > crate::object::MAX_NAME_LEN {-        return false;-    }-    let bytes = name.as_bytes();-    if matches!(bytes[0], b'-' | b'/' | b'.') || matches!(bytes[bytes.len() - 1], b'/' | b'.') {-        return false;-    }-    for byte in bytes {-        if *byte == 0-            || *byte == b' '-            || *byte < 32-            || *byte == 127-            || matches!(*byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\')-        {-            return false;-        }-    }-    !name.contains("..")-        && !name.contains("@{")-        && !name.contains("//")-        && name != "@"-        && !name.ends_with(".lock")-}--fn short(id: crate::object::id::Id) -> String {-    id.short()-}--pub fn bookmark(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        bookmark_usage();-        return Ok(1);-    };-    match sub.as_str() {-        "set" | "mv" => bookmark_set(&arguments[1..]),-        "rename" | "move" => bookmark_rename(&arguments[1..]),-        "ls" => bookmark_list(&arguments[1..]),-        "rm" => bookmark_remove(&arguments[1..]),-        "help" | "-h" => {-            bookmark_usage();-            Ok(0)-        }-        _ => {-            output::error_prefix();-            println!("unknown bmk subcommand: {sub}");-            bookmark_usage();-            Ok(1)-        }-    }-}--fn bookmark_usage() {-    println!("usage: vn bmk <set|rename|ls|rm> ...");-    println!();-    println!("manage named, movable pointers to commits (branches)");-    println!();-    println!("subcommands:");-    println!("  set <name> [-rev <rev>]   create or move a bookmark (default: @)");-    println!("  mv <name> [-rev <rev>]    alias of set");-    println!("  rename <old> <new>        rename a bookmark");-    println!("  ls [-no-col-titles]       list bookmarks");-    println!("  rm <name>                 delete a bookmark");-}--fn bookmark_rename(arguments: &[String]) -> Result<u8> {-    let mut names = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            names.push(argument.clone());-        }-    }-    if names.len() != 2 {-        return Err(Error::new("bmk rename requires an old and a new name"));-    }-    let (old, new) = (&names[0], &names[1]);-    if !valid_ref_name(new) {-        return Err(Error::new(format!("invalid bookmark name: {new}")));-    }-    if old == new {-        return Err(Error::new("new bookmark name matches the old name"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let Some(index) = ops::find_bookmark(txn.view(), old.as_bytes()) else {-        return Err(Error::new(format!("no such bookmark: {old}")));-    };-    if ops::find_bookmark(txn.view(), new.as_bytes()).is_some() {-        return Err(Error::new(format!("bookmark already exists: {new}")));-    }-    let mut bookmark = txn.view_mut().bookmarks.remove(index);-    bookmark.name = new.as_bytes().to_vec();-    txn.view_mut().bookmarks.push(bookmark);-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("bookmark rename {old} {new}"))?;-    if core::current_bookmark_name(&root).is_some_and(|current| current == *old) {-        core::set_current_bookmark(&root, new);-    }-    output::info_prefix();-    println!("renamed bookmark {old} to {new}");-    Ok(0)-}--fn bookmark_set(arguments: &[String]) -> Result<u8> {-    let mut name = String::new();-    let mut revision = String::new();-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if name.is_empty() {-            name = argument.clone();-        } else if revision.is_empty() {-            revision = argument.clone();-        } else {-            return Err(Error::new("bmk set accepts a name and one revision"));-        }-        index += 1;-    }-    if name.is_empty() {-        return Err(Error::new("bmk set requires a name"));-    }-    if !valid_ref_name(&name) {-        return Err(Error::new(format!("invalid bookmark name: {name}")));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?.ok_or_else(|| {-        Error::new(if revision.is_empty() {-            "no working-copy commit"-        } else {-            "unknown revision"-        })-    })?;-    let mut changed = true;-    if let Some(existing) = ops::find_bookmark(txn.view(), name.as_bytes()) {-        let bookmark = &mut txn.view_mut().bookmarks[existing];-        if bookmark.targets.adds == vec![Some(target)] {-            changed = false;-        } else {-            bookmark.targets.adds = vec![Some(target)];-            bookmark.targets.removes.clear();-        }-    } else {-        txn.view_mut().bookmarks.push(Bookmark {-            name: name.as_bytes().to_vec(),-            targets: crate::object::view::TargetSet {-                adds: vec![Some(target)],-                removes: Vec::new(),-            },-        });-    }-    if !changed {-        core::set_current_bookmark(&root, &name);-        output::info_prefix();-        println!("bookmark {name} is already at {}", short(target));-        return Ok(0);-    }-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("bookmark set {name}"))?;-    core::set_current_bookmark(&root, &name);-    output::info_prefix();-    println!("bookmark {name} set to {}", short(target));-    Ok(0)-}--fn bookmark_remove(arguments: &[String]) -> Result<u8> {-    let mut name = String::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if !name.is_empty() {-            return Err(Error::new("bmk rm accepts exactly one name"));-        } else {-            name = argument.clone();-        }-    }-    if name.is_empty() {-        return Err(Error::new("bmk rm requires a name"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let Some(index) = ops::find_bookmark(txn.view(), name.as_bytes()) else {-        return Err(Error::new(format!("no such bookmark: {name}")));-    };-    txn.view_mut().bookmarks.remove(index);-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("bookmark delete {name}"))?;-    if core::current_bookmark_name(&root).is_some_and(|current| current == name) {-        core::clear_current_bookmark(&root);-    }-    output::info_prefix();-    println!("deleted bookmark {name}");-    Ok(0)-}--fn bookmark_list(arguments: &[String]) -> Result<u8> {-    let mut titles = true;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && argument == "-no-col-titles" {-            titles = false;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            return Err(Error::new("bmk ls takes no operands"));-        }-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let working_copy = ops::working_copy_id(&view);-    let mut name_width = 8;-    for bookmark in &view.bookmarks {-        name_width = name_width.max(String::from_utf8_lossy(&bookmark.name).len());-    }-    if titles {-        output::print_cell("Bookmark", name_width);-        print!("  ");-        output::print_cell("Commit", 12);-        print!("  ");-        output::print_cell("Change", 8);-        println!("  Target");-    }-    for bookmark in &view.bookmarks {-        let name = String::from_utf8_lossy(&bookmark.name);-        output::print_cell(&name, name_width);-        print!("  ");-        let Some(target) = bookmark.targets.adds.first().copied().flatten() else {-            output::print_cell("<missing>", 12);-            print!("  ");-            output::print_cell("", 8);-            println!("  (missing)");-            continue;-        };-        output::print_cell(&short(target), 12);-        print!("  ");-        let change = graph::load_commit(&mut store, target)?-            .map(|commit| graph::base32_encode(commit.change_id))-            .unwrap_or_default();-        output::print_cell(&change[..change.len().min(8)], 8);-        print!("  ");-        if working_copy == Some(target) {-            print!("@");-        }-        if bookmark.targets.adds.len() > 1 {-            if working_copy == Some(target) {-                print!(" ");-            }-            print!("(conflicted)");-        }-        println!();-    }-    if view.bookmarks.is_empty() {-        output::info_prefix();-        println!("no bookmarks");-    }-    Ok(0)-}--pub fn tag(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        tag_usage();-        return Ok(1);-    };-    match sub.as_str() {-        "set" => tag_set(&arguments[1..]),-        "ls" | "list" => tag_list(&arguments[1..]),-        "rm" | "remove" => tag_remove(&arguments[1..]),-        "latest" => tag_latest(&arguments[1..]),-        "help" | "-h" => {-            tag_usage();-            Ok(0)-        }-        _ => {-            output::error_prefix();-            println!("unknown tag subcommand: {sub}");-            tag_usage();-            Ok(1)-        }-    }-}--fn tag_usage() {-    println!("usage: vn tag <set|ls|rm|latest> ...");-    println!();-    println!("manage named pointers to commits (tags)");-    println!();-    println!("subcommands:");-    println!("  set <name> [-rev <rev>]   create or move a tag (default: @)");-    println!("  ls [-no-col-titles]       list tags");-    println!("  rm <name>                 delete a tag");-    println!("  latest                    print the latest tag name");-}--fn tag_set(arguments: &[String]) -> Result<u8> {-    let mut name = String::new();-    let mut revision = String::new();-    let mut end_flags = false;-    let mut index = 0;-    while index < arguments.len() {-        let argument = &arguments[index];-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && (argument == "-r" || argument == "-rev") {-            index += 1;-            if index >= arguments.len() {-                return Err(Error::new(format!("{argument} requires a revision")));-            }-            revision = arguments[index].clone();-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if name.is_empty() {-            name = argument.clone();-        } else if revision.is_empty() {-            revision = argument.clone();-        } else {-            return Err(Error::new("tag set accepts a name and one revision"));-        }-        index += 1;-    }-    if name.is_empty() {-        return Err(Error::new("tag set requires a name"));-    }-    if !valid_ref_name(&name) {-        return Err(Error::new(format!("invalid tag name: {name}")));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let target = graph::resolve_revision(&mut store, txn.view(), &revision)?.ok_or_else(|| {-        Error::new(if revision.is_empty() {-            "no working-copy commit"-        } else {-            "unknown revision"-        })-    })?;-    let mut changed = true;-    if let Some(existing) = ops::find_tag(txn.view(), name.as_bytes()) {-        let tag = &mut txn.view_mut().tags[existing];-        if tag.target == target {-            changed = false;-        } else {-            tag.target = target;-        }-    } else {-        txn.view_mut().tags.push(TagRef {-            name: name.as_bytes().to_vec(),-            target,-        });-    }-    if !changed {-        output::info_prefix();-        println!("tag {name} is already at {}", short(target));-        return Ok(0);-    }-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("tag set {name}"))?;-    output::info_prefix();-    println!("tag {name} set to {}", short(target));-    Ok(0)-}--fn tag_remove(arguments: &[String]) -> Result<u8> {-    let mut name = String::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else if !name.is_empty() {-            return Err(Error::new("tag rm accepts exactly one name"));-        } else {-            name = argument.clone();-        }-    }-    if name.is_empty() {-        return Err(Error::new("tag rm requires a name"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let mut txn = Txn::begin(&root, &mut store)?;-    let Some(index) = ops::find_tag(txn.view(), name.as_bytes()) else {-        return Err(Error::new(format!("no such tag: {name}")));-    };-    txn.view_mut().tags.remove(index);-    ops::rebuild_heads(txn.view_mut());-    txn.finish(&format!("tag delete {name}"))?;-    output::info_prefix();-    println!("deleted tag {name}");-    Ok(0)-}--fn tag_list(arguments: &[String]) -> Result<u8> {-    let mut titles = true;-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && argument == "-no-col-titles" {-            titles = false;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            return Err(Error::new("tag ls takes no operands"));-        }-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let working_copy = ops::working_copy_id(&view);-    let mut name_width = 3;-    for tag in &view.tags {-        name_width = name_width.max(String::from_utf8_lossy(&tag.name).len());-    }-    if titles {-        output::print_cell("Tag", name_width);-        print!("  ");-        output::print_cell("Commit", 12);-        print!("  ");-        output::print_cell("Change", 8);-        println!("  Target");-    }-    for tag in &view.tags {-        let name = String::from_utf8_lossy(&tag.name);-        output::print_cell(&name, name_width);-        print!("  ");-        output::print_cell(&short(tag.target), 12);-        print!("  ");-        let change = graph::load_commit(&mut store, tag.target)?-            .map(|commit| graph::base32_encode(commit.change_id))-            .unwrap_or_default();-        output::print_cell(&change[..change.len().min(8)], 8);-        print!("  ");-        if working_copy == Some(tag.target) {-            print!("@");-        }-        println!();-    }-    if view.tags.is_empty() {-        output::info_prefix();-        println!("no tags");-    }-    Ok(0)-}--fn natural_compare(left: &str, right: &str) -> std::cmp::Ordering {-    let left = left.as_bytes();-    let right = right.as_bytes();-    let mut i = 0;-    let mut j = 0;-    while i < left.len() && j < right.len() {-        if left[i].is_ascii_digit() && right[j].is_ascii_digit() {-            let ai = i;-            let bj = j;-            while i < left.len() && left[i].is_ascii_digit() {-                i += 1;-            }-            while j < right.len() && right[j].is_ascii_digit() {-                j += 1;-            }-            let an = left[ai..i]-                .iter()-                .position(|byte| *byte != b'0')-                .map(|offset| ai + offset)-                .unwrap_or(i);-            let bn = right[bj..j]-                .iter()-                .position(|byte| *byte != b'0')-                .map(|offset| bj + offset)-                .unwrap_or(j);-            let alen = i - an;-            let blen = j - bn;-            if alen != blen {-                return alen.cmp(&blen);-            }-            for offset in 0..alen {-                if left[an + offset] != right[bn + offset] {-                    return left[an + offset].cmp(&right[bn + offset]);-                }-            }-        } else {-            if left[i] != right[j] {-                return left[i].cmp(&right[j]);-            }-            i += 1;-            j += 1;-        }-    }-    if i < left.len() {-        std::cmp::Ordering::Greater-    } else if j < right.len() {-        std::cmp::Ordering::Less-    } else {-        std::cmp::Ordering::Equal-    }-}--fn tag_latest(arguments: &[String]) -> Result<u8> {-    if !arguments.is_empty() {-        return Err(Error::new("tag latest takes no operands"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let mut store = Store::open(&root)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    if view.tags.is_empty() {-        return Err(Error::new("no tags"));-    }-    let mut best: Option<(&TagRef, i64)> = None;-    for tag in &view.tags {-        let time = graph::load_commit(&mut store, tag.target)?-            .map(|commit| commit.committer.seconds)-            .unwrap_or(i64::MIN);-        let replace = match best {-            None => true,-            Some((current, best_time)) => {-                time > best_time-                    || (time == best_time-                        && natural_compare(-                            &String::from_utf8_lossy(&tag.name),-                            &String::from_utf8_lossy(&current.name),-                        ) == std::cmp::Ordering::Greater)-            }-        };-        if replace {-            best = Some((tag, time));-        }-    }-    if let Some((tag, _)) = best {-        println!("{}", String::from_utf8_lossy(&tag.name));-    }-    Ok(0)-}--pub fn _path_marker(_path: &Path) {}--- a/veinsrs/src/cli/status.rs+++ /dev/null@@ -1,81 +0,0 @@-use std::collections::HashSet;--use crate::error::{Error, Result};-use crate::object::tree::KIND_CONFLICT;-use crate::store::graph;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::pathspec;-use crate::worktree::snapshot;--use super::output;--pub fn run() -> Result<u8> {-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let cwd = pathspec::cwd_relative(&root).unwrap_or_default();-    let mut store = Store::open(&root)?;-    snapshot::run_with(&root, &mut store)?;-    let view =-        ops::current_view(&root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-    let Some(working_copy) = ops::working_copy_id(&view) else {-        output::info_prefix();-        println!("working copy clean");-        return Ok(0);-    };-    let commit = graph::load_commit(&mut store, working_copy)?-        .ok_or_else(|| Error::new("no operation state"))?;-    let old_tree = match commit.parents.first() {-        Some(parent) => graph::load_commit(&mut store, *parent)?.map(|parent| parent.root_tree),-        None => None,-    };-    let changes = if old_tree == Some(commit.root_tree) {-        Vec::new()-    } else {-        graph::compare_trees(&mut store, old_tree, Some(commit.root_tree))?-    };-    let mut conflicts = 0usize;-    for change in &changes {-        let path = output::status_path(&change.path, &cwd);-        if change.old_kind == crate::object::tree::KIND_MISSING {-            output::print_styled("92", "A");-            println!(" {path}");-        } else if change.new_kind == crate::object::tree::KIND_MISSING {-            output::print_styled("31", "D");-            println!(" {path}");-        } else if change.new_kind == KIND_CONFLICT {-            output::print_styled("91", "C");-            println!(" {path}");-            conflicts += 1;-        } else {-            output::print_styled("36", "M");-            println!(" {path}");-        }-    }-    if changes.is_empty() {-        output::info_prefix();-        println!("working copy clean");-    }-    if conflicts > 0 {-        println!("{conflicts} conflict(s)");-    }-    let mut stack = vec![working_copy];-    let mut seen = HashSet::new();-    let mut conflicted_commits = 0usize;-    let mut conflict_cache = std::collections::HashMap::new();-    while let Some(id) = stack.pop() {-        if !seen.insert(id) {-            continue;-        }-        let Some(commit) = graph::load_commit(&mut store, id)? else {-            continue;-        };-        if graph::tree_conflicted_with(&mut store, commit.root_tree, &mut conflict_cache)? {-            conflicted_commits += 1;-        }-        stack.extend(commit.parents);-    }-    if conflicted_commits > 0 {-        println!("{conflicted_commits} conflicted commit(s) in ancestry");-    }-    Ok(0)-}--- a/veinsrs/src/cli/worktree_cmd.rs+++ /dev/null@@ -1,727 +0,0 @@-use std::collections::HashSet;-use std::fs;-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::identity;-use crate::object::commit;-use crate::object::path::valid_path;-use crate::object::tree::{self, KIND_SUBTREE, TreeEntry};-use crate::object::{TYPE_COMMIT, TYPE_TREE};-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::pathspec;-use crate::worktree::snapshot;--use super::output;--pub fn remove(arguments: &[String]) -> Result<u8> {-    let mut delete_mode = false;-    let mut operands = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && argument == "-delete" {-            delete_mode = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            operands.push(argument.clone());-        }-    }-    if operands.is_empty() {-        return Err(Error::new("rm requires at least one path"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    let normalized = normalize_operands(&root, &operands)?;-    run_removal(&root, &normalized, delete_mode)-}--fn normalize_operands(root: &Path, operands: &[String]) -> Result<Vec<String>> {-    let cwd = pathspec::cwd_relative(root)-        .ok_or_else(|| Error::new("cannot determine current directory"))?;-    let mut normalized = Vec::new();-    for argument in operands {-        let Some(normalized_path) = pathspec::pathspec_normalize(root, &cwd, argument) else {-            return Err(Error::new(format!(-                "path is outside the repository: {argument}"-            )));-        };-        if normalized_path.is_empty() || !valid_path(normalized_path.as_bytes()) {-            return Err(Error::new(format!("invalid path: {argument}")));-        }-        normalized.push(normalized_path);-    }-    Ok(normalized)-}--fn starts_with_child(path: &[u8], parent: &[u8]) -> bool {-    path.len() > parent.len() && path.starts_with(parent) && path[parent.len()] == b'/'-}--fn literal_matches(operand: &[u8], path: &[u8]) -> bool {-    path == operand || starts_with_child(path, operand)-}--fn glob_matches(operand: &str, path: &[u8]) -> bool {-    let text = String::from_utf8_lossy(path);-    if core::glob_match(operand, &text) {-        return true;-    }-    for (index, byte) in path.iter().enumerate() {-        if *byte == b'/' && core::glob_match(operand, &String::from_utf8_lossy(&path[..index])) {-            return true;-        }-    }-    false-}--fn operand_matches(operand: &str, path: &[u8]) -> bool {-    if operand.contains('*') || operand.contains('?') {-        glob_matches(operand, path)-    } else {-        literal_matches(operand.as_bytes(), path)-    }-}--fn subtree_affected(prefix: &[u8], removes: &[Vec<u8>]) -> bool {-    if prefix.is_empty() {-        return !removes.is_empty();-    }-    removes.iter().any(|remove| {-        prefix == remove.as_slice()-            || starts_with_child(remove, prefix)-            || starts_with_child(prefix, remove)-    })-}--fn path_removed(path: &[u8], removes: &[Vec<u8>]) -> bool {-    removes-        .iter()-        .any(|remove| path == remove.as_slice() || starts_with_child(path, remove))-}--fn empty_tree_id(txn: &mut Txn) -> Result<crate::object::id::Id> {-    Ok(txn.add_object(TYPE_TREE, tree::encode(&[])?))-}--fn filter_tree(-    txn: &mut Txn,-    store: &mut Store,-    tree_id: crate::object::id::Id,-    prefix: &[u8],-    removes: &[Vec<u8>],-    depth: usize,-) -> Result<Option<crate::object::id::Id>> {-    if depth > crate::object::MAX_TREE_DEPTH || !subtree_affected(prefix, removes) {-        return Ok(Some(tree_id));-    }-    let Some(body) = store.body(tree_id, TYPE_TREE)? else {-        return Ok(Some(tree_id));-    };-    let Ok(decoded) = tree::decode(&body) else {-        return Ok(Some(tree_id));-    };-    let mut entries = Vec::with_capacity(decoded.entries.len());-    for entry in decoded.entries {-        let full = crate::object::path::join(prefix, &entry.name);-        if path_removed(&full, removes) {-            continue;-        }-        if entry.kind == KIND_SUBTREE && subtree_affected(&full, removes) {-            if let Some(child) = filter_tree(txn, store, entry.target, &full, removes, depth + 1)? {-                entries.push(TreeEntry {-                    name: entry.name,-                    kind: entry.kind,-                    target: child,-                });-            }-        } else {-            entries.push(entry);-        }-    }-    if entries.is_empty() {-        return Ok(None);-    }-    Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))-}--fn delete_paths(root: &Path, removes: &[Vec<u8>]) -> u8 {-    let mut failed = 0;-    for relative in removes {-        let path = root.join(core::path_from_bytes(relative));-        if fs::remove_file(&path).is_err() {-            failed += 1;-        } else {-            prune_parents(root, relative);-        }-    }-    if failed > 0 {-        output::warning_prefix();-        println!("could not delete {failed} path(s) from disk");-        1-    } else {-        0-    }-}--fn prune_parents(root: &Path, relative: &[u8]) {-    let mut end = relative.len();-    while let Some(position) = relative[..end].iter().rposition(|byte| *byte == b'/') {-        let path = root.join(core::path_from_bytes(&relative[..position]));-        if fs::remove_dir(&path).is_err() {-            break;-        }-        end = position;-    }-}--fn run_removal(root: &Path, operands: &[String], delete_mode: bool) -> Result<u8> {-    let mut store = Store::open(root)?;-    let mut txn = Txn::begin(root, &mut store)?;-    let working_copy =-        ops::working_copy_id(txn.view()).ok_or_else(|| Error::new("no working-copy commit"))?;-    let loaded = graph::load_commit(&mut store, working_copy)?-        .ok_or_else(|| Error::new("cannot read working-copy commit"))?;-    let entries = tree::flatten(&mut store, loaded.root_tree)?;-    let mut matched = vec![false; operands.len()];-    let mut removes = Vec::new();-    let mut seen = HashSet::new();-    for entry in &entries {-        for (index, operand) in operands.iter().enumerate() {-            if operand_matches(operand, &entry.path) {-                matched[index] = true;-                if seen.insert(entry.path.clone()) {-                    removes.push(entry.path.clone());-                }-            }-        }-    }-    for (index, value) in matched.iter().enumerate() {-        if !value {-            return Err(Error::new(format!(-                "path is not tracked: {}",-                operands[index]-            )));-        }-    }-    if !delete_mode {-        for relative in &removes {-            if !core::ignore_path_ignored(root, &String::from_utf8_lossy(relative)) {-                output::warning_prefix();-                println!(-                    "{} is not ignored and will be re-added on the next snapshot",-                    String::from_utf8_lossy(relative)-                );-            }-        }-    }-    let new_root = filter_tree(&mut txn, &mut store, loaded.root_tree, b"", &removes, 0)?-        .unwrap_or_else(|| empty_tree_id(&mut txn).unwrap_or_default());-    if new_root == loaded.root_tree {-        return Err(Error::new("no tracked paths to remove"));-    }-    let signature = identity::signature(root);-    let mut commit = loaded;-    commit.root_tree = new_root;-    commit.committer = signature;-    commit.renames_state = commit::RENAMES_RECORDED;-    commit.renames.clear();-    let encoded = commit::encode(&commit);-    let new_id = txn.add_object(TYPE_COMMIT, encoded);-    ops::remove_head(txn.view_mut(), working_copy);-    ops::move_bookmarks(txn.view_mut(), working_copy, new_id);-    ops::set_workspace(txn.view_mut(), new_id);-    ops::rebuild_heads(txn.view_mut());-    txn.finish("rm")?;-    mark_native(root, new_id);-    let mut status = 0;-    if delete_mode {-        status = delete_paths(root, &removes);-    }-    output::info_prefix();-    println!("untracked {} path(s)", removes.len());-    Ok(status)-}--fn mark_native(root: &Path, id: crate::object::id::Id) {-    let path = layout::git_map_dir(root).join("native");-    core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes());-}--pub fn move_path(arguments: &[String]) -> Result<u8> {-    let mut operands = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            operands.push(argument.clone());-        }-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    snapshot::run(&root)?;-    if operands.len() != 2 {-        return Err(Error::new("mv requires a source and a destination"));-    }-    let cwd = pathspec::cwd_relative(&root)-        .ok_or_else(|| Error::new("cannot determine current directory"))?;-    let source = pathspec::pathspec_normalize(&root, &cwd, &operands[0])-        .ok_or_else(|| Error::new("invalid path"))?;-    let destination = pathspec::pathspec_normalize(&root, &cwd, &operands[1])-        .ok_or_else(|| Error::new("invalid path"))?;-    let source_path = root.join(core::path_from_bytes(source.as_bytes()));-    let destination_path = root.join(core::path_from_bytes(destination.as_bytes()));-    if core::stat_path(&source_path).is_none() {-        return Err(Error::new(format!("not a tracked path: {source}")));-    }-    if core::stat_path(&destination_path).is_some() {-        return Err(Error::new(format!(-            "destination already exists: {destination}"-        )));-    }-    if let Some((parent, _)) = destination.rsplit_once('/') {-        if !core::ensure_directory(&root.join(parent)) {-            return Err(Error::new("cannot create destination directory"));-        }-    }-    fs::rename(&source_path, &destination_path).map_err(|_| Error::new("cannot move path"))?;-    snapshot::run(&root)?;-    Ok(0)-}--pub fn exclude(arguments: &[String]) -> Result<u8> {-    let mut operands = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            operands.push(argument.clone());-        }-    }-    if operands.is_empty() {-        return Err(Error::new("ex requires at least one pattern"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let cwd = pathspec::cwd_relative(&root)-        .ok_or_else(|| Error::new("cannot determine current directory"))?;-    let mut patterns = Vec::new();-    for argument in &operands {-        let Some(normalized) = pathspec::pathspec_normalize(&root, &cwd, argument) else {-            return Err(Error::new(format!(-                "pattern is outside the repository: {argument}"-            )));-        };-        if normalized.is_empty() || !valid_path(normalized.as_bytes()) {-            return Err(Error::new(format!(-                "{argument}\nnot a valid exclude pattern"-            )));-        }-        patterns.push(normalized);-    }-    let path = root.join(".vnexclude");-    let data = core::read_file_opt(&path, 0).unwrap_or_default();-    let text = String::from_utf8_lossy(&data);-    let mut additions = String::new();-    let mut added = Vec::new();-    for pattern in &patterns {-        if text.lines().any(|line| core::trim_str(line) == pattern)-            || added.iter().any(|value| value == pattern)-        {-            continue;-        }-        if additions.is_empty() && !data.is_empty() && !data.ends_with(b"\n") {-            additions.push('\n');-        }-        added.push(pattern.clone());-        additions.push_str(pattern);-        additions.push('\n');-    }-    if added.is_empty() {-        output::info_prefix();-        println!("no new exclude rules");-        return Ok(0);-    }-    if !core::append_file(&path, additions.as_bytes()) {-        return Err(Error::new("cannot write .vnexclude"));-    }-    output::info_prefix();-    println!("added {} exclude rule(s)", added.len());-    Ok(0)-}--pub fn edit(arguments: &[String]) -> Result<u8> {-    let mut paths = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            paths.push(argument.clone());-        }-    }-    if paths.is_empty() {-        paths.push(".".to_string());-    }-    let root = layout::discover(Path::new("."))-        .or_else(|_| std::env::current_dir())-        .map_err(|_| Error::new("cannot determine the current directory"))?;-    if !core::run_editor(&root, &paths, None) {-        return Err(Error::new("editor exited with an error"));-    }-    Ok(0)-}--#[derive(Clone, Copy, PartialEq, Eq)]-enum Attr {-    Gen,-    Txt,-    Bin,-    Lf,-    Crlf,-    Cr,-}--fn parse_attr(name: &str) -> Option<Attr> {-    match name {-        "gen" => Some(Attr::Gen),-        "txt" => Some(Attr::Txt),-        "bin" => Some(Attr::Bin),-        "lf" => Some(Attr::Lf),-        "crlf" => Some(Attr::Crlf),-        "cr" => Some(Attr::Cr),-        _ => None,-    }-}--fn canonical(attr: Attr) -> &'static str {-    match attr {-        Attr::Gen => "gen",-        Attr::Txt => "txt",-        Attr::Bin => "bin",-        Attr::Lf => "eol:lf",-        Attr::Crlf => "eol:crlf",-        Attr::Cr => "eol:cr",-    }-}--fn is_attr_token(token: &str, attr: Attr) -> bool {-    match attr {-        Attr::Gen => token == "gen" || token == "-gen",-        Attr::Txt => token == "txt" || token == "-txt",-        Attr::Bin => token == "bin" || token == "-bin",-        Attr::Lf => token == "eol:lf",-        Attr::Crlf => token == "eol:crlf",-        Attr::Cr => token == "eol:cr",-    }-}--fn clears_token(token: &str, attr: Attr) -> bool {-    match attr {-        Attr::Gen => is_attr_token(token, Attr::Gen),-        Attr::Txt | Attr::Bin => matches!(token, "txt" | "-txt" | "bin" | "-bin"),-        Attr::Lf | Attr::Crlf | Attr::Cr => {-            matches!(token, "eol:lf" | "eol:crlf" | "eol:cr" | "-eol")-        }-    }-}--struct Line {-    text: String,-    eol: String,-    is_rule: bool,-    pattern: String,-    attrs: Vec<String>,-}--fn tokenize(line: &str) -> Vec<String> {-    line.split(|character| character == ' ' || character == '\t')-        .filter(|value| !value.is_empty())-        .map(|value| value.to_string())-        .collect()-}--fn parse_lines(data: &str) -> Vec<Line> {-    let mut lines = Vec::new();-    let mut start = 0;-    while start < data.len() {-        let newline = data[start..].find('\n').map(|offset| start + offset);-        let mut line = Line {-            text: String::new(),-            eol: String::new(),-            is_rule: false,-            pattern: String::new(),-            attrs: Vec::new(),-        };-        match newline {-            None => {-                line.text = data[start..].to_string();-                start = data.len();-            }-            Some(position) => {-                let mut body = &data[start..position];-                if let Some(value) = body.strip_suffix('\r') {-                    body = value;-                    line.eol = "\r\n".to_string();-                } else {-                    line.eol = "\n".to_string();-                }-                line.text = body.to_string();-                start = position + 1;-            }-        }-        let trimmed = core::trim_str(&line.text);-        if !trimmed.is_empty() && !trimmed.starts_with('#') {-            let tokens = tokenize(trimmed);-            if !tokens.is_empty() {-                line.is_rule = true;-                line.pattern = tokens[0].clone();-                line.attrs = tokens[1..].to_vec();-            }-        }-        lines.push(line);-    }-    lines-}--fn canonical_line(line: &Line) -> String {-    let mut output = line.pattern.clone();-    for attr in &line.attrs {-        output.push(' ');-        output.push_str(attr);-    }-    output-}--fn serialize(lines: &[Line], removed: &[bool]) -> String {-    let kept: Vec<usize> = (0..lines.len())-        .filter(|index| !removed.get(*index).copied().unwrap_or(false))-        .collect();-    let mut output = String::new();-    for (position, index) in kept.iter().enumerate() {-        let line = &lines[*index];-        if line.is_rule {-            output.push_str(&canonical_line(line));-        } else {-            output.push_str(&line.text);-        }-        if position + 1 < kept.len() {-            output.push_str(if line.eol.is_empty() { "\n" } else { &line.eol });-        } else {-            output.push_str(&line.eol);-        }-    }-    if !output.is_empty() && !output.ends_with('\n') {-        output.push('\n');-    }-    output-}--fn collect_operands(arguments: &[String]) -> Result<Vec<String>> {-    let mut operands = Vec::new();-    let mut end_flags = false;-    for argument in arguments {-        if !end_flags && argument == "--" {-            end_flags = true;-        } else if !end_flags && core::is_flag(argument) {-            return Err(Error::new(format!("unknown flag: {argument}")));-        } else {-            operands.push(argument.clone());-        }-    }-    Ok(operands)-}--fn normalize_patterns(root: &Path, arguments: &[String]) -> Result<Vec<String>> {-    let cwd = pathspec::cwd_relative(root)-        .ok_or_else(|| Error::new("cannot determine current directory"))?;-    let mut patterns = Vec::new();-    for argument in arguments {-        let Some(normalized) = pathspec::pathspec_normalize(root, &cwd, argument) else {-            return Err(Error::new(format!(-                "{argument}\nnot a valid attribute pattern"-            )));-        };-        if normalized.is_empty()-            || !valid_path(normalized.as_bytes())-            || normalized.contains([' ', '\t', '\r', '\n'])-            || normalized.starts_with('#')-        {-            return Err(Error::new(format!(-                "{argument}\nnot a valid attribute pattern"-            )));-        }-        patterns.push(normalized);-    }-    Ok(patterns)-}--fn read_attribs(path: &Path) -> Result<String> {-    match core::read_file_opt(path, 0) {-        Some(data) => Ok(String::from_utf8_lossy(&data).into_owned()),-        None if path.exists() => Err(Error::new("cannot read .vnattribs")),-        None => Ok(String::new()),-    }-}--fn attr_set(attr: Attr, arguments: &[String]) -> Result<u8> {-    let operands = collect_operands(arguments)?;-    if operands.is_empty() {-        return Err(Error::new(format!(-            "attr {} requires at least one glob",-            canonical(attr)-        )));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let patterns = normalize_patterns(&root, &operands)?;-    let path = root.join(".vnattribs");-    let data = read_attribs(&path)?;-    let mut lines = parse_lines(&data);-    let mut changed = 0;-    for pattern in &patterns {-        let target = lines-            .iter()-            .enumerate()-            .filter(|(_, line)| line.is_rule && &line.pattern == pattern)-            .map(|(index, _)| index)-            .last();-        let mut attrs = Vec::new();-        if let Some(index) = target {-            for token in &lines[index].attrs {-                if !clears_token(token, attr) {-                    attrs.push(token.clone());-                }-            }-        }-        attrs.push(canonical(attr).to_string());-        if let Some(index) = target {-            if lines[index].attrs == attrs {-                continue;-            }-            lines[index].attrs = attrs;-        } else {-            if let Some(last) = lines.last_mut() {-                if last.eol.is_empty() {-                    last.eol = "\n".to_string();-                }-            }-            lines.push(Line {-                text: String::new(),-                eol: "\n".to_string(),-                is_rule: true,-                pattern: pattern.clone(),-                attrs,-            });-        }-        changed += 1;-    }-    if changed == 0 {-        output::info_prefix();-        println!("no new attribute rules");-        return Ok(0);-    }-    if !core::write_atomic_name(&path, serialize(&lines, &[]).as_bytes()) {-        return Err(Error::new("cannot write .vnattribs"));-    }-    output::info_prefix();-    println!("updated {changed} attribute rule(s)");-    Ok(0)-}--fn attr_remove(arguments: &[String]) -> Result<u8> {-    let mut operands = collect_operands(arguments)?;-    if operands.len() < 2 {-        return Err(Error::new(-            "usage: vn attr rm <gen|txt|bin|lf|crlf|cr> <glob>...",-        ));-    }-    let Some(attr) = parse_attr(&operands[0]) else {-        return Err(Error::new(format!("unknown attribute: {}", operands[0])));-    };-    operands.remove(0);-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let patterns = normalize_patterns(&root, &operands)?;-    let path = root.join(".vnattribs");-    let data = read_attribs(&path)?;-    let mut lines = parse_lines(&data);-    let mut removed = vec![false; lines.len()];-    let mut changed = 0;-    for pattern in &patterns {-        for index in 0..lines.len() {-            if removed[index] || !lines[index].is_rule || &lines[index].pattern != pattern {-                continue;-            }-            let attrs: Vec<String> = lines[index]-                .attrs-                .iter()-                .filter(|token| !is_attr_token(token, attr))-                .cloned()-                .collect();-            if attrs.len() == lines[index].attrs.len() {-                continue;-            }-            if attrs.is_empty() {-                removed[index] = true;-            } else {-                lines[index].attrs = attrs;-            }-            changed += 1;-        }-    }-    if changed == 0 {-        output::info_prefix();-        println!("no matching attribute rules");-        return Ok(0);-    }-    if !core::write_atomic_name(&path, serialize(&lines, &removed).as_bytes()) {-        return Err(Error::new("cannot write .vnattribs"));-    }-    output::info_prefix();-    println!("removed {changed} attribute rule(s)");-    Ok(0)-}--fn attr_list(arguments: &[String]) -> Result<u8> {-    let operands = collect_operands(arguments)?;-    if !operands.is_empty() {-        return Err(Error::new("usage: vn attr ls"));-    }-    let root = output::open_repo().ok_or_else(|| Error::new("not a veins repository"))?;-    let data = read_attribs(&root.join(".vnattribs"))?;-    for line in parse_lines(&data) {-        if line.is_rule {-            println!("{}", canonical_line(&line));-        }-    }-    Ok(0)-}--pub fn attr(arguments: &[String]) -> Result<u8> {-    let Some(sub) = arguments.first() else {-        output::error_prefix();-        println!("attr requires a subcommand");-        println!("run 'vn help attr' for details");-        return Ok(1);-    };-    match sub.as_str() {-        "ls" => attr_list(&arguments[1..]),-        "rm" => attr_remove(&arguments[1..]),-        value => match parse_attr(value) {-            Some(attr) => attr_set(attr, &arguments[1..]),-            None => Err(Error::new(format!("unknown attr subcommand: {value}"))),-        },-    }-}--- a/veinsrs/src/core.rs+++ /dev/null@@ -1,1237 +0,0 @@-use std::collections::BTreeMap;-use std::env;-use std::fs;-use std::io::{Read, Write};-use std::path::{Path, PathBuf};--use crate::error::{Error, Result};-use crate::platform;--pub fn is_flag(argument: &str) -> bool {-    !argument.is_empty() && argument.starts_with('-')-}--pub fn trim_str(text: &str) -> &str {-    text.trim_matches(|character| {-        character == ' ' || character == '\t' || character == '\r' || character == '\n'-    })-}--pub fn trim_bytes(text: &[u8]) -> &[u8] {-    let mut start = 0;-    let mut end = text.len();-    while start < end && matches!(text[start], b' ' | b'\t' | b'\r' | b'\n') {-        start += 1;-    }-    while end > start && matches!(text[end - 1], b' ' | b'\t' | b'\r' | b'\n') {-        end -= 1;-    }-    &text[start..end]-}--pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {-    platform::path_from_bytes(bytes)-}--pub fn path_to_bytes(path: &Path) -> Vec<u8> {-    platform::path_to_bytes(path)-}--pub fn path_display(path: &Path) -> String {-    platform::path_display(path)-}--pub fn read_file_opt(path: &Path, maximum: u64) -> Option<Vec<u8>> {-    #[cfg(unix)]-    {-        use std::os::unix::fs::OpenOptionsExt;-        let mut file = fs::OpenOptions::new()-            .read(true)-            .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC)-            .open(path)-            .ok()?;-        let metadata = file.metadata().ok()?;-        if !metadata.is_file() {-            return None;-        }-        if maximum != 0 && metadata.len() > maximum {-            return None;-        }-        let length = usize::try_from(metadata.len()).ok()?;-        if length == 0 {-            let mut data = Vec::new();-            file.read_to_end(&mut data).ok()?;-            return Some(data);-        }-        let mut data = vec![0u8; length];-        file.read_exact(&mut data).ok()?;-        Some(data)-    }-    #[cfg(not(unix))]-    {-        let metadata = fs::symlink_metadata(path).ok()?;-        if !metadata.is_file() {-            return None;-        }-        if maximum != 0 && metadata.len() > maximum {-            return None;-        }-        let mut file = fs::File::open(path).ok()?;-        let mut data = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or(0));-        file.read_to_end(&mut data).ok()?;-        Some(data)-    }-}--pub fn read_file_range(path: &Path, offset: u64, length: usize) -> Option<Vec<u8>> {-    use std::io::{Seek, SeekFrom};-    let mut file = fs::File::open(path).ok()?;-    file.seek(SeekFrom::Start(offset)).ok()?;-    let mut data = vec![0u8; length];-    let mut done = 0;-    while done < length {-        match file.read(&mut data[done..]) {-            Ok(0) => break,-            Ok(count) => done += count,-            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,-            Err(_) => return None,-        }-    }-    data.truncate(done);-    Some(data)-}--pub fn read_file(path: &Path, maximum: u64) -> Result<Vec<u8>> {-    read_file_opt(path, maximum).ok_or_else(|| Error::io(format!("cannot read {}", path.display())))-}--fn create_parent(path: &Path) -> bool {-    match path.parent() {-        Some(parent) if !parent.as_os_str().is_empty() => fs::create_dir_all(parent).is_ok(),-        _ => true,-    }-}--pub fn write_file(path: &Path, data: &[u8]) -> bool {-    let mut options = fs::OpenOptions::new();-    options.write(true).create(true).truncate(true);-    let file = match options.open(path) {-        Ok(file) => Some(file),-        Err(_) => {-            if !create_parent(path) {-                return false;-            }-            options.open(path).ok()-        }-    };-    let Some(mut file) = file else {-        return false;-    };-    file.write_all(data).is_ok() && file.flush().is_ok()-}--pub fn append_file(path: &Path, data: &[u8]) -> bool {-    let mut options = fs::OpenOptions::new();-    options.create(true).append(true);-    let file = match options.open(path) {-        Ok(file) => Some(file),-        Err(_) => {-            if !create_parent(path) {-                return false;-            }-            options.open(path).ok()-        }-    };-    let Some(mut file) = file else {-        return false;-    };-    file.write_all(data).is_ok() && file.flush().is_ok()-}--fn sync_file(path: &Path) -> bool {-    platform::sync_file(path).is_ok()-}--fn sync_directory(path: &Path) {-    platform::sync_directory(path);-}--pub fn write_atomic(tmp_path: &Path, final_path: &Path, data: &[u8]) -> bool {-    if let Some(parent) = tmp_path.parent()-        && !parent.as_os_str().is_empty()-        && fs::create_dir_all(parent).is_err()-    {-        return false;-    }-    if let Some(parent) = final_path.parent()-        && !parent.as_os_str().is_empty()-        && fs::create_dir_all(parent).is_err()-    {-        return false;-    }-    if !write_file(tmp_path, data) {-        return false;-    }-    if !sync_file(tmp_path) {-        let _ = fs::remove_file(tmp_path);-        return false;-    }-    if fs::rename(tmp_path, final_path).is_err() {-        let _ = fs::remove_file(tmp_path);-        return false;-    }-    if let Some(parent) = final_path.parent() {-        sync_directory(parent);-    }-    true-}--pub fn write_atomic_name(final_path: &Path, data: &[u8]) -> bool {-    let parent = final_path.parent().unwrap_or_else(|| Path::new(""));-    let name = final_path-        .file_name()-        .map(|value| value.to_string_lossy().into_owned())-        .unwrap_or_default();-    let temporary = parent.join(format!(".{name}.tmp.{}", random_u64()));-    write_atomic(&temporary, final_path, data)-}--pub fn ensure_directory(path: &Path) -> bool {-    fs::create_dir_all(path).is_ok()-}--pub fn remove_file(path: &Path) -> bool {-    fs::remove_file(path).is_ok()-}--pub fn remove_tree(path: &Path) -> bool {-    fs::remove_dir_all(path).is_ok()-}--pub fn list_directory(path: &Path) -> Vec<Vec<u8>> {-    let mut names = Vec::new();-    let Ok(entries) = fs::read_dir(path) else {-        return names;-    };-    for entry in entries.flatten() {-        names.push(platform::os_string_to_bytes(entry.file_name()));-    }-    names-}--pub fn same_or_under(child: &Path, parent: &Path) -> bool {-    let Ok(child) = fs::canonicalize(child) else {-        return false;-    };-    let Ok(parent) = fs::canonicalize(parent) else {-        return false;-    };-    child.starts_with(parent)-}--pub fn basename_string(path: &Path) -> String {-    path.file_name()-        .map(|value| value.to_string_lossy().into_owned())-        .unwrap_or_default()-}--pub fn path_read_symlink(path: &Path) -> Option<Vec<u8>> {-    fs::read_link(path)-        .ok()-        .map(|target| platform::path_to_bytes(&target))-}--#[derive(Clone, Copy)]-pub struct StatInfo {-    pub kind: u8,-    pub executable: bool,-    pub size: u64,-    pub mtime_ns: u64,-    pub inode: u64,-}--pub fn stat_path(path: &Path) -> Option<StatInfo> {-    let metadata = fs::symlink_metadata(path).ok()?;-    let file_type = metadata.file_type();-    let kind = if file_type.is_symlink() {-        3-    } else if file_type.is_dir() {-        2-    } else if file_type.is_file() {-        1-    } else {-        return None;-    };-    Some(StatInfo {-        kind,-        executable: platform::executable(&metadata),-        size: metadata.len(),-        mtime_ns: platform::mtime_ns(&metadata),-        inode: platform::inode(&metadata),-    })-}--thread_local! {-    static REPO_CONFIG: std::cell::RefCell<Option<(PathBuf, Vec<u8>)>> =-        const { std::cell::RefCell::new(None) };-}--fn repo_config_data(root: &Path) -> Option<Vec<u8>> {-    let path = root.join(".veins").join("config");-    REPO_CONFIG.with(|slot| {-        let mut slot = slot.borrow_mut();-        if let Some((cached_path, data)) = slot.as_ref()-            && *cached_path == path-        {-            return Some(data.clone());-        }-        let data = read_file_opt(&path, 0)?;-        *slot = Some((path, data.clone()));-        Some(data)-    })-}--fn clear_repo_config_cache() {-    REPO_CONFIG.with(|slot| *slot.borrow_mut() = None);-}--pub fn repo_config_value(root: &Path, key: &str) -> Option<String> {-    let data = repo_config_data(root)?;-    let text = String::from_utf8_lossy(&data);-    for raw in text.lines() {-        let line = trim_str(raw);-        if line.is_empty() || line.starts_with('#') {-            continue;-        }-        let Some((name, value)) = line.split_once('=') else {-            continue;-        };-        if trim_str(name) == key {-            return Some(trim_str(value).to_string());-        }-    }-    None-}--fn config_without_key(data: &[u8], key: &str) -> Vec<u8> {-    let text = String::from_utf8_lossy(data);-    let mut output = String::new();-    let lines: Vec<&str> = text.lines().collect();-    for (index, raw) in lines.iter().enumerate() {-        let line = trim_str(raw);-        let mut skip = false;-        if !line.is_empty()-            && !line.starts_with('#')-            && let Some((name, _)) = line.split_once('=')-        {-            skip = trim_str(name) == key;-        }-        if !skip {-            output.push_str(raw);-            if index + 1 < lines.len() || text.ends_with('\n') {-                output.push('\n');-            }-        }-    }-    output.into_bytes()-}--pub fn repo_config_set(root: &Path, key: &str, value: &str) -> bool {-    let path = root.join(".veins").join("config");-    let mut output = repo_config_data(root)-        .map(|data| config_without_key(&data, key))-        .unwrap_or_default();-    output.extend_from_slice(key.as_bytes());-    output.extend_from_slice(b" = ");-    output.extend_from_slice(value.as_bytes());-    output.push(b'\n');-    let written = write_file(&path, &output);-    clear_repo_config_cache();-    written-}--pub fn repo_config_remove(root: &Path, key: &str) -> bool {-    let path = root.join(".veins").join("config");-    let output = repo_config_data(root)-        .map(|data| config_without_key(&data, key))-        .unwrap_or_default();-    let written = write_file(&path, &output);-    clear_repo_config_cache();-    written-}--pub fn repo_config_bool(root: &Path, key: &str, fallback: bool) -> bool {-    let Some(value) = repo_config_value(root, key) else {-        return fallback;-    };-    let value = value.split('#').next().unwrap_or("").trim();-    matches!(value, "true" | "1" | "yes" | "on")-}--fn user_config_path() -> Option<PathBuf> {-    let home = env::var_os("HOME")?;-    if home.is_empty() {-        return None;-    }-    Some(-        PathBuf::from(home)-            .join(".local")-            .join("config")-            .join("veins")-            .join("veins.toml"),-    )-}--fn unquote_toml(raw: &str) -> Option<String> {-    let raw = trim_str(raw);-    if raw.len() >= 2 {-        let first = raw.as_bytes()[0];-        let last = raw.as_bytes()[raw.len() - 1];-        if (first == b'\'' && last == b'\'') || (first == b'"' && last == b'"') {-            let quote = first;-            let mut output = String::new();-            let bytes = raw.as_bytes();-            let mut index = 1;-            while index + 1 < bytes.len() {-                let byte = bytes[index];-                if quote == b'"' && byte == b'\\' && index + 2 < bytes.len() {-                    match bytes[index + 1] {-                        b'"' => output.push('"'),-                        b'\\' => output.push('\\'),-                        b'n' => output.push('\n'),-                        b'r' => output.push('\r'),-                        b't' => output.push('\t'),-                        other => {-                            output.push('\\');-                            output.push(other as char);-                        }-                    }-                    index += 2;-                } else {-                    output.push(byte as char);-                    index += 1;-                }-            }-            return Some(output);-        }-    }-    if raw.is_empty() {-        return None;-    }-    Some(raw.to_string())-}--fn user_config_full_key(section: &str, key: &str) -> String {-    if section.is_empty() {-        key.to_string()-    } else {-        format!("{section}.{key}")-    }-}--fn user_config_entries_inner() -> BTreeMap<String, String> {-    let mut output = BTreeMap::new();-    let Some(path) = user_config_path() else {-        return output;-    };-    let Some(data) = read_file_opt(&path, 0) else {-        return output;-    };-    let text = String::from_utf8_lossy(&data);-    let mut section = String::new();-    for raw in text.lines() {-        let line = trim_str(raw);-        if line.is_empty() || line.starts_with('#') {-            continue;-        }-        if let Some(rest) = line.strip_prefix('[') {-            if let Some(close) = rest.find(']') {-                section = trim_str(&rest[..close]).to_string();-            }-            continue;-        }-        let Some((key, value)) = line.split_once('=') else {-            continue;-        };-        let value = value.split('#').next().unwrap_or("");-        if let Some(decoded) = unquote_toml(value) {-            output.insert(user_config_full_key(&section, trim_str(key)), decoded);-        }-    }-    output-}--pub fn user_config_entries() -> BTreeMap<String, String> {-    user_config_entries_inner()-}--pub fn user_config_value(key: &str) -> Option<String> {-    user_config_entries_inner().remove(key)-}--pub fn user_config_author_name() -> Option<String> {-    user_config_value("user.name")-}--pub fn user_config_author_email() -> Option<String> {-    user_config_value("user.email")-}--fn toml_quote(value: &str) -> String {-    let mut output = String::from("\"");-    for character in value.chars() {-        match character {-            '"' => output.push_str("\\\""),-            '\\' => output.push_str("\\\\"),-            '\n' => output.push_str("\\n"),-            '\r' => output.push_str("\\r"),-            '\t' => output.push_str("\\t"),-            other => output.push(other),-        }-    }-    output.push('"');-    output-}--fn update_user_config(key: &str, value: Option<&str>) -> bool {-    if key.is_empty() {-        return false;-    }-    let Some(path) = user_config_path() else {-        return false;-    };-    let lines: Vec<String> = read_file_opt(&path, 0)-        .map(|data| {-            String::from_utf8_lossy(&data)-                .lines()-                .map(|line| line.to_string())-                .collect()-        })-        .unwrap_or_default();-    let mut output = Vec::new();-    let mut section = String::new();-    for line in lines {-        let trimmed = trim_str(&line);-        if let Some(rest) = trimmed.strip_prefix('[') {-            if let Some(close) = rest.find(']') {-                section = trim_str(&rest[..close]).to_string();-            }-            output.push(line);-            continue;-        }-        let Some((name, _)) = trimmed.split_once('=') else {-            output.push(line);-            continue;-        };-        if trimmed.is_empty() || trimmed.starts_with('#') {-            output.push(line);-            continue;-        }-        if user_config_full_key(&section, trim_str(name)) != key {-            output.push(line);-        }-    }-    if let Some(value) = value {-        output.insert(0, format!("{key} = {}", toml_quote(value)));-    } else {-        while output.last().is_some_and(|line| trim_str(line).is_empty()) {-            output.pop();-        }-    }-    let mut body = output.join("\n");-    if !output.is_empty() {-        body.push('\n');-    }-    write_file(&path, body.as_bytes())-}--pub fn user_config_set(key: &str, value: &str) -> bool {-    update_user_config(key, Some(value))-}--pub fn user_config_remove(key: &str) -> bool {-    update_user_config(key, None)-}--pub fn shell_quote_arg(value: &str) -> String {-    platform::shell_quote(value)-}--pub fn editor_command(root: &Path) -> String {-    for key in ["editor", "core.editor"] {-        if let Some(value) = user_config_value(key)-            && !value.is_empty()-        {-            return value;-        }-    }-    if let Some(value) = repo_config_value(root, "editor")-        && !value.is_empty()-    {-        return value;-    }-    for name in ["VN_EDITOR", "VISUAL", "EDITOR"] {-        if let Ok(value) = env::var(name)-            && !value.is_empty()-        {-            return value;-        }-    }-    platform::default_editor().to_string()-}--pub fn run_editor(root: &Path, paths: &[String], message_file: Option<&Path>) -> bool {-    let mut command = editor_command(root);-    for path in paths {-        command.push(' ');-        command.push_str(&shell_quote_arg(path));-    }-    if let Some(file) = message_file {-        command.push(' ');-        command.push_str(&shell_quote_arg(&path_display(file)));-    }-    platform::shell(&command)-        .status()-        .is_ok_and(|status| status.success())-}--pub fn stdin_is_terminal() -> bool {-    platform::stdin_is_terminal()-}--pub fn colors_enabled() -> bool {-    static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();-    *ENABLED.get_or_init(|| {-        if env::var_os("NO_COLOR").is_some() {-            return false;-        }-        let forced =-            env::var_os("FORCE_COLOR").is_some_and(|value| !value.is_empty() && value != "0");-        if forced {-            return true;-        }-        if !stdout_is_terminal() {-            return false;-        }-        !env::var("TERM").is_ok_and(|term| term == "dumb")-    })-}--pub fn stdout_is_terminal() -> bool {-    platform::stdout_is_terminal()-}--pub fn stderr_is_terminal() -> bool {-    platform::stderr_is_terminal()-}--pub fn pager_command(root: &Path) -> String {-    for key in ["pager", "core.pager"] {-        if let Some(value) = user_config_value(key)-            && !value.is_empty()-        {-            return value;-        }-    }-    if let Some(value) = repo_config_value(root, "pager")-        && !value.is_empty()-    {-        return value;-    }-    for name in ["VN_PAGER", "PAGER"] {-        if let Ok(value) = env::var(name)-            && !value.is_empty()-        {-            return value;-        }-    }-    platform::default_pager().to_string()-}--pub fn run_pager(root: &Path, text: &str) -> bool {-    if !stdout_is_terminal() {-        print!("{text}");-        return true;-    }-    let file = env::temp_dir().join(format!("vn-pager-{}.txt", random_u64()));-    if !write_file(&file, text.as_bytes()) {-        print!("{text}");-        return false;-    }-    let command = format!(-        "{} {}",-        pager_command(root),-        shell_quote_arg(&path_display(&file))-    );-    let ok = platform::shell(&command)-        .status()-        .is_ok_and(|status| status.success());-    let _ = fs::remove_file(&file);-    if !ok {-        print!("{text}");-    }-    ok-}--pub fn current_bookmark_name(root: &Path) -> Option<String> {-    repo_config_value(root, "bookmark.current")-}--pub fn set_current_bookmark(root: &Path, name: &str) -> bool {-    if name.is_empty() {-        repo_config_remove(root, "bookmark.current")-    } else {-        repo_config_set(root, "bookmark.current", name)-    }-}--pub fn clear_current_bookmark(root: &Path) -> bool {-    repo_config_remove(root, "bookmark.current")-}--pub fn random_u64() -> u64 {-    let mut value = [0u8; 8];-    if let Ok(mut file) = fs::File::open("/dev/urandom")-        && file.read_exact(&mut value).is_ok()-    {-        return u64::from_le_bytes(value);-    }-    let mut hasher = blake3::Hasher::new();-    hasher.update(&crate::time::now_millis().to_le_bytes());-    hasher.update(&std::process::id().to_le_bytes());-    hasher.update(format!("{:?}", std::time::Instant::now()).as_bytes());-    let digest = hasher.finalize();-    let mut bytes = [0u8; 8];-    bytes.copy_from_slice(&digest.as_bytes()[..8]);-    u64::from_le_bytes(bytes)-}--impl From<std::ffi::OsString> for Error {-    fn from(value: std::ffi::OsString) -> Self {-        Error::new(value.to_string_lossy())-    }-}--#[derive(Clone, Default)]-pub struct IgnoreRule {-    pub pattern: String,-    pub negated: bool,-    pub dir_only: bool,-    pub anchored: bool,-    pub has_slash: bool,-    pub base: String,-}--#[derive(Clone, Default)]-pub struct IgnoreRules {-    pub items: Vec<IgnoreRule>,-}--pub fn ignore_empty() -> IgnoreRules {-    IgnoreRules::default()-}--fn ignore_add_line(rules: &mut IgnoreRules, base: &str, input: &str) {-    let line = trim_str(input);-    if line.is_empty() || line.starts_with('#') {-        return;-    }-    let mut negated = false;-    let mut start = 0;-    if line.starts_with('!') {-        negated = true;-        start = 1;-    }-    if start >= line.len() {-        return;-    }-    let bytes = line.as_bytes();-    let mut end = bytes.len();-    let mut dir_only = false;-    if bytes[end - 1] == b'/' {-        dir_only = true;-        end -= 1;-    }-    if start >= end {-        return;-    }-    let mut anchored = false;-    if bytes[start] == b'/' {-        anchored = true;-        start += 1;-    }-    if start >= end {-        return;-    }-    let pattern = &line[start..end];-    rules.items.push(IgnoreRule {-        pattern: pattern.to_string(),-        negated,-        dir_only,-        anchored,-        has_slash: pattern.contains('/'),-        base: base.to_string(),-    });-}--pub fn ignore_load_file(rules: &mut IgnoreRules, root: &Path, base: &str, name: &str) {-    let directory = if base.is_empty() {-        root.to_path_buf()-    } else {-        root.join(base)-    };-    let Some(data) = read_file_opt(&directory.join(name), 0) else {-        return;-    };-    let text = String::from_utf8_lossy(&data);-    for line in text.lines() {-        ignore_add_line(rules, base, line);-    }-}--pub fn ignore_load_root(rules: &mut IgnoreRules, root: &Path) {-    ignore_load_file(rules, root, "", ".vnexclude");-    ignore_load_file(rules, root, "", ".gitignore");-}--#[derive(Clone, Copy)]-struct GlobState {-    pi: usize,-    ti: usize,-}--/// LIFO of match states that keeps small searches off the heap.-struct GlobStack {-    inline: [GlobState; 128],-    spilled: Vec<GlobState>,-    length: usize,-}--impl GlobStack {-    fn new() -> Self {-        Self {-            inline: [GlobState { pi: 0, ti: 0 }; 128],-            spilled: Vec::new(),-            length: 0,-        }-    }--    fn push(&mut self, state: GlobState) {-        if self.length < self.inline.len() {-            self.inline[self.length] = state;-            self.length += 1;-        } else {-            self.spilled.push(state);-        }-    }--    fn pop(&mut self) -> Option<GlobState> {-        if let Some(state) = self.spilled.pop() {-            return Some(state);-        }-        if self.length == 0 {-            return None;-        }-        self.length -= 1;-        Some(self.inline[self.length])-    }-}--pub fn glob_match(pattern: &str, text: &str) -> bool {-    let pattern = pattern.as_bytes();-    let text = text.as_bytes();-    const MAX_WORK: usize = 1_000_000;-    fn push(stack: &mut GlobStack, work: &mut usize, state: GlobState) -> bool {-        if *work >= MAX_WORK {-            return false;-        }-        *work += 1;-        stack.push(state);-        true-    }-    let mut stack = GlobStack::new();-    let mut work = 0usize;-    if !push(&mut stack, &mut work, GlobState { pi: 0, ti: 0 }) {-        return false;-    }-    while let Some(state) = stack.pop() {-        let p = state.pi;-        let t = state.ti;-        if p >= pattern.len() {-            if t >= text.len() {-                return true;-            }-            continue;-        }-        let pc = pattern[p];-        if pc == b'*' {-            let double = p + 1 < pattern.len() && pattern[p + 1] == b'*';-            if double {-                let next = p + 2;-                if next < pattern.len() && pattern[next] == b'/' {-                    let after = next + 1;-                    let mut j = t;-                    loop {-                        if !push(&mut stack, &mut work, GlobState { pi: after, ti: j }) {-                            return false;-                        }-                        if j >= text.len() {-                            break;-                        }-                        if text[j] == b'/' {-                            j += 1;-                            continue;-                        }-                        j += 1;-                        while j < text.len() && text[j] != b'/' {-                            j += 1;-                        }-                    }-                } else {-                    let mut j = t;-                    loop {-                        if !push(&mut stack, &mut work, GlobState { pi: next, ti: j }) {-                            return false;-                        }-                        if j >= text.len() {-                            break;-                        }-                        j += 1;-                    }-                }-            } else {-                let mut j = t;-                loop {-                    if !push(&mut stack, &mut work, GlobState { pi: p + 1, ti: j }) {-                        return false;-                    }-                    if j >= text.len() || text[j] == b'/' {-                        break;-                    }-                    j += 1;-                }-            }-            continue;-        }-        if t >= text.len() {-            continue;-        }-        if pc == b'?' {-            if text[t] != b'/' {-                let _ = push(-                    &mut stack,-                    &mut work,-                    GlobState {-                        pi: p + 1,-                        ti: t + 1,-                    },-                );-            }-            continue;-        }-        if pc == text[t] {-            let _ = push(-                &mut stack,-                &mut work,-                GlobState {-                    pi: p + 1,-                    ti: t + 1,-                },-            );-        }-    }-    false-}--fn relative_to<'a>(base: &str, path: &'a str) -> Option<&'a str> {-    if base.is_empty() {-        return Some(path);-    }-    if path.len() <= base.len() || !path.starts_with(base) {-        return None;-    }-    if path.as_bytes()[base.len()] != b'/' {-        return None;-    }-    Some(&path[base.len() + 1..])-}--fn rule_matches(rule: &IgnoreRule, path: &str, is_dir: bool) -> bool {-    let Some(relative) = relative_to(&rule.base, path) else {-        return false;-    };-    if relative.is_empty() || (rule.dir_only && !is_dir) {-        return false;-    }-    if !rule.has_slash && !rule.anchored {-        let mut start = 0;-        loop {-            let end = relative[start..]-                .find('/')-                .map(|offset| start + offset)-                .unwrap_or(relative.len());-            if glob_match(&rule.pattern, &relative[start..end]) {-                return true;-            }-            if end >= relative.len() {-                break;-            }-            start = end + 1;-        }-        return false;-    }-    glob_match(&rule.pattern, relative)-}--pub fn ignore_ignored(rules: &IgnoreRules, path: &str, is_dir: bool) -> bool {-    let mut ignored = false;-    for rule in &rules.items {-        if rule_matches(rule, path, is_dir) {-            ignored = !rule.negated;-        }-    }-    ignored-}--pub fn ignore_path_ignored(root: &Path, path: &str) -> bool {-    let mut rules = ignore_empty();-    ignore_load_root(&mut rules, root);-    for (index, byte) in path.bytes().enumerate() {-        if byte == b'/' {-            let base = &path[..index];-            ignore_load_file(&mut rules, root, base, ".vnexclude");-            ignore_load_file(&mut rules, root, base, ".gitignore");-        }-    }-    for (index, byte) in path.bytes().enumerate() {-        if byte == b'/' && ignore_ignored(&rules, &path[..index], true) {-            return true;-        }-    }-    ignore_ignored(&rules, path, false)-}--const PROGRESS_WIDTH: usize = 24;--fn progress_enabled() -> bool {-    for name in ["NO_PROGRESS", "VN_NO_PROGRESS"] {-        if env::var_os(name).is_some_and(|value| !value.is_empty() && value != "0") {-            return false;-        }-    }-    if env::var_os("VN_PROGRESS").is_some_and(|value| !value.is_empty() && value != "0") {-        return true;-    }-    if env::var("TERM").is_ok_and(|term| term == "dumb") {-        return false;-    }-    stderr_is_terminal()-}--fn styled_info_prefix(color: bool) -> &'static str {-    if color {-        "\r\x1b[2K\x1b[1m\x1b[36minfo\x1b[0m: "-    } else {-        "\r\x1b[2Kinfo: "-    }-}--struct ProgressState {-    total: usize,-    done: usize,-    last_done: usize,-    last_total: usize,-    last_draw: Option<std::time::Instant>,-    drawn: bool,-    finished: bool,-}--pub struct Progress {-    label: String,-    enabled: bool,-    state: std::sync::Mutex<ProgressState>,-}--impl Progress {-    pub fn new(label: impl Into<String>, total: usize) -> Self {-        Self {-            label: label.into(),-            enabled: progress_enabled(),-            state: std::sync::Mutex::new(ProgressState {-                total,-                done: 0,-                last_done: usize::MAX,-                last_total: usize::MAX,-                last_draw: None,-                drawn: false,-                finished: false,-            }),-        }-    }--    pub fn set_total(&self, total: usize) {-        if let Ok(mut state) = self.state.lock() {-            state.total = total;-            self.refresh(&mut state, true);-        }-    }--    pub fn update(&self, done: usize, force: bool) {-        if let Ok(mut state) = self.state.lock() {-            state.done = done;-            self.refresh(&mut state, force);-        }-    }--    pub fn advance(&self, amount: usize) {-        if let Ok(mut state) = self.state.lock() {-            state.done = state.done.saturating_add(amount);-            self.refresh(&mut state, false);-        }-    }--    pub fn finish(&self) {-        let Ok(mut state) = self.state.lock() else {-            return;-        };-        if !self.enabled || state.finished {-            return;-        }-        state.finished = true;-        if state.total > 0 {-            if state.done < state.total {-                state.done = state.total;-            }-            if !state.drawn || state.last_done != state.done || state.last_total != state.total {-                self.draw(&mut state);-            }-            eprintln!();-        } else if state.drawn {-            eprint!("\r\x1b[2K");-            let _ = std::io::stderr().flush();-        }-        state.drawn = false;-    }--    pub fn clear(&self) {-        let Ok(mut state) = self.state.lock() else {-            return;-        };-        if self.enabled && state.drawn {-            eprint!("\r\x1b[2K");-            let _ = std::io::stderr().flush();-        }-        state.drawn = false;-        state.finished = true;-    }--    fn refresh(&self, state: &mut ProgressState, force: bool) {-        if !self.enabled || state.finished {-            return;-        }-        let now = std::time::Instant::now();-        let complete = state.total > 0 && state.done >= state.total;-        if !force-            && !complete-            && state-                .last_draw-                .is_some_and(|last| now.duration_since(last) < std::time::Duration::from_millis(66))-        {-            return;-        }-        state.last_draw = Some(now);-        self.draw(state);-        state.drawn = true;-    }--    fn draw(&self, state: &mut ProgressState) {-        let color = colors_enabled();-        let mut line = String::with_capacity(128);-        line.push_str(styled_info_prefix(color));-        line.push_str(&self.label);-        line.push_str("  ");-        if state.total > 0 {-            let filled = std::cmp::min(-                PROGRESS_WIDTH,-                ((state.done as u128 * PROGRESS_WIDTH as u128) / state.total as u128) as usize,-            );-            line.push('[');-            if filled >= PROGRESS_WIDTH {-                if color {-                    line.push_str("\x1b[32m");-                }-                for _ in 0..PROGRESS_WIDTH {-                    line.push('=');-                }-            } else {-                let head = if filled == 0 { 1 } else { filled };-                if color {-                    line.push_str("\x1b[32m");-                }-                for _ in 0..head.saturating_sub(1) {-                    line.push('=');-                }-                line.push('>');-                if color {-                    line.push_str("\x1b[0m");-                }-                for _ in head..PROGRESS_WIDTH {-                    line.push(' ');-                }-            }-            if color {-                line.push_str("\x1b[0m");-            }-            line.push(']');-            if color {-                line.push_str(" \x1b[36m");-            } else {-                line.push(' ');-            }-            line.push_str(&(state.done * 100 / state.total).min(100).to_string());-            line.push('%');-            if color {-                line.push_str("\x1b[0m\x1b[2m");-            }-            line.push(' ');-            line.push_str(&state.done.to_string());-            line.push('/');-            line.push_str(&state.total.to_string());-            if color {-                line.push_str("\x1b[0m");-            }-        } else {-            const FRAMES: [char; 4] = ['|', '/', '-', '\\'];-            let frame = FRAMES[state.done % 4];-            if color {-                line.push_str("\x1b[36m");-                line.push(frame);-                line.push_str("\x1b[0m\x1b[2m");-            } else {-                line.push(frame);-            }-            line.push(' ');-            line.push_str(&state.done.to_string());-            if color {-                line.push_str("\x1b[0m");-            }-        }-        eprint!("{line}");-        let _ = std::io::stderr().flush();-        state.last_done = state.done;-        state.last_total = state.total;-    }-}--impl Drop for Progress {-    fn drop(&mut self) {-        let Ok(state) = self.state.lock() else {-            return;-        };-        if !self.enabled || !state.drawn || state.finished {-            return;-        }-        eprint!("\r\x1b[2K");-        let _ = std::io::stderr().flush();-    }-}--- a/veinsrs/src/crypto.rs+++ /dev/null@@ -1,576 +0,0 @@-use std::fs;--use ring::signature::KeyPair;--pub type PublicKey = [u8; 32];-pub type Signature = [u8; 64];--pub fn ed25519_public_from_seed(seed: &[u8]) -> Option<PublicKey> {-    if seed.len() != 32 {-        return None;-    }-    let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(seed).ok()?;-    let public = pair.public_key().as_ref();-    if public.len() != 32 {-        return None;-    }-    let mut output = [0u8; 32];-    output.copy_from_slice(public);-    Some(output)-}--pub fn ed25519_sign(seed: &[u8], message: &[u8]) -> Option<Signature> {-    if seed.len() != 32 {-        return None;-    }-    let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(seed).ok()?;-    let signature = pair.sign(message);-    let bytes = signature.as_ref();-    if bytes.len() != 64 {-        return None;-    }-    let mut output = [0u8; 64];-    output.copy_from_slice(bytes);-    Some(output)-}--pub fn ed25519_verify(public_key: &PublicKey, message: &[u8], signature: &[u8]) -> bool {-    if signature.len() != 64 {-        return false;-    }-    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key)-        .verify(message, signature)-        .is_ok()-}--pub fn key_fingerprint_bytes(public_key: &PublicKey) -> [u8; 16] {-    let mut hasher = blake3::Hasher::new();-    hasher.update(b"veins/key/1\0");-    hasher.update(public_key);-    let digest = hasher.finalize();-    let mut output = [0u8; 16];-    output.copy_from_slice(&digest.as_bytes()[..16]);-    output-}--pub fn base32_text(raw: &[u8]) -> String {-    const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";-    let mut output = String::with_capacity(raw.len() * 8 / 5 + 2);-    let mut bits = 0u64;-    let mut count = 0usize;-    for byte in raw {-        bits = (bits << 8) | *byte as u64;-        count += 8;-        while count >= 5 {-            count -= 5;-            output.push(ALPHABET[((bits >> count) & 31) as usize] as char);-        }-    }-    if count > 0 {-        output.push(ALPHABET[((bits << (5 - count)) & 31) as usize] as char);-    }-    output-}--pub fn key_fingerprint(public_key: &PublicKey) -> String {-    base32_text(&key_fingerprint_bytes(public_key))-}--pub fn base64url_encode(raw: &[u8]) -> String {-    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";-    let mut output = String::with_capacity(raw.len() * 4 / 3 + 4);-    let mut accumulator = 0u32;-    let mut bits = 0usize;-    for byte in raw {-        accumulator = (accumulator << 8) | *byte as u32;-        bits += 8;-        while bits >= 6 {-            bits -= 6;-            output.push(ALPHABET[((accumulator >> bits) & 63) as usize] as char);-        }-    }-    if bits > 0 {-        output.push(ALPHABET[((accumulator << (6 - bits)) & 63) as usize] as char);-    }-    output-}--pub fn base64url_decode(text: &str) -> Option<Vec<u8>> {-    if text.is_empty() {-        return None;-    }-    let value = |character: u8| -> Option<u32> {-        match character {-            b'A'..=b'Z' => Some((character - b'A') as u32),-            b'a'..=b'z' => Some((character - b'a' + 26) as u32),-            b'0'..=b'9' => Some((character - b'0' + 52) as u32),-            b'-' => Some(62),-            b'_' => Some(63),-            _ => None,-        }-    };-    let mut output = Vec::with_capacity(text.len() * 6 / 8);-    let mut accumulator = 0u32;-    let mut bits = 0usize;-    for character in text.bytes() {-        accumulator = (accumulator << 6) | value(character)?;-        bits += 6;-        if bits >= 8 {-            bits -= 8;-            output.push(((accumulator >> bits) & 255) as u8);-        }-    }-    Some(output)-}--pub fn format_public_key(public_key: &PublicKey) -> String {-    format!("ed25519:{}", base64url_encode(public_key))-}--pub fn parse_public_key(text: &str) -> Option<PublicKey> {-    let value = text.strip_prefix("ed25519:")?;-    let decoded = base64url_decode(value)?;-    if decoded.len() != 32 {-        return None;-    }-    let mut output = [0u8; 32];-    output.copy_from_slice(&decoded);-    Some(output)-}--pub fn secure_random(count: usize) -> Vec<u8> {-    use ring::rand::SecureRandom;-    let mut output = vec![0u8; count];-    let random = ring::rand::SystemRandom::new();-    if random.fill(&mut output).is_err() {-        return Vec::new();-    }-    output-}--pub struct Key {-    pub name: String,-    pub seed: Vec<u8>,-    pub public_key: PublicKey,-    pub fingerprint: String,-}--pub fn key_dir() -> std::path::PathBuf {-    if let Ok(value) = std::env::var("XDG_CONFIG_HOME")-        && !value.is_empty()-    {-        return std::path::PathBuf::from(value).join("veins").join("keys");-    }-    if let Ok(home) = std::env::var("HOME")-        && !home.is_empty()-    {-        return std::path::PathBuf::from(home)-            .join(".config")-            .join("veins")-            .join("keys");-    }-    std::path::PathBuf::from(".veins-keys")-}--fn valid_key_name(name: &str) -> bool {-    !name.is_empty() && name.len() <= 128 && !name.contains(['/', '\\', '\0'])-}--pub fn key_path(name: &str) -> std::path::PathBuf {-    key_dir().join(format!("{name}.key"))-}--pub fn load_key(name: &str) -> Option<Key> {-    if !valid_key_name(name) {-        return None;-    }-    let path = key_path(name);-    let metadata = fs::metadata(&path).ok()?;-    if crate::platform::permissions_mode(&metadata) & 63 != 0 {-        return None;-    }-    let data = fs::read(path).ok()?;-    if data.len() != 33 || data[0] != 1 {-        return None;-    }-    let seed = data[1..].to_vec();-    let public_key = ed25519_public_from_seed(&seed)?;-    Some(Key {-        name: name.to_string(),-        fingerprint: key_fingerprint(&public_key),-        seed,-        public_key,-    })-}--pub fn generate_key(name: &str) -> Option<Key> {-    if !valid_key_name(name) {-        return None;-    }-    let directory = key_dir();-    fs::create_dir_all(&directory).ok()?;-    let _ = crate::platform::set_mode(&directory, 0o700);-    let seed = secure_random(32);-    if seed.len() != 32 {-        return None;-    }-    let public_key = ed25519_public_from_seed(&seed)?;-    let mut body = Vec::with_capacity(33);-    body.push(1);-    body.extend_from_slice(&seed);-    let path = key_path(name);-    fs::write(&path, &body).ok()?;-    let _ = crate::platform::set_mode(&path, 0o600);-    Some(Key {-        name: name.to_string(),-        fingerprint: key_fingerprint(&public_key),-        seed,-        public_key,-    })-}--pub fn list_key_names() -> Vec<String> {-    let directory = key_dir();-    let mut output = Vec::new();-    for name in crate::core::list_directory(&directory) {-        let text = String::from_utf8_lossy(&name);-        if let Some(stem) = text.strip_suffix(".key") {-            output.push(stem.to_string());-        }-    }-    output-}--pub fn auth_dir() -> std::path::PathBuf {-    let directory = key_dir();-    match directory.parent() {-        Some(parent) => parent.join("auth"),-        None => std::path::PathBuf::from(".veins-auth"),-    }-}--fn authority_of(input: &str) -> Option<String> {-    let text = crate::core::trim_str(input);-    let mut start = 0;-    if let Some(scheme) = text.find("://") {-        start = scheme + 3;-    }-    if start >= text.len() {-        return None;-    }-    let end = text[start..]-        .find('/')-        .map(|offset| start + offset)-        .unwrap_or(text.len());-    if end <= start {-        return None;-    }-    let raw = &text[start..end];-    let host = raw.rsplit('@').next().unwrap_or(raw);-    if host.is_empty() {-        return None;-    }-    Some(host.to_ascii_lowercase())-}--pub fn normalize_target(target: &str) -> String {-    let text = crate::core::trim_str(target);-    if text.is_empty() || text == "default" {-        return "default".to_string();-    }-    if let Some(authority) = authority_of(text) {-        return authority;-    }-    let raw = text.split('/').next().unwrap_or(text);-    let host = raw.rsplit('@').next().unwrap_or(raw);-    if host.is_empty() {-        "default".to_string()-    } else {-        host.to_ascii_lowercase()-    }-}--fn hex_encode(data: &[u8]) -> String {-    let mut output = String::with_capacity(data.len() * 2);-    for byte in data {-        output.push_str(&format!("{byte:02x}"));-    }-    output-}--fn hex_decode(text: &str) -> Option<Vec<u8>> {-    if text.is_empty() || text.len() % 2 != 0 {-        return None;-    }-    let value = |character: u8| -> Option<u8> {-        match character {-            b'0'..=b'9' => Some(character - b'0'),-            b'a'..=b'f' => Some(character - b'a' + 10),-            _ => None,-        }-    };-    let mut output = Vec::with_capacity(text.len() / 2);-    for pair in text.as_bytes().chunks(2) {-        output.push((value(pair[0])? << 4) | value(pair[1])?);-    }-    Some(output)-}--fn target_path(directory: &std::path::Path, target: &str) -> std::path::PathBuf {-    directory.join(hex_encode(target.as_bytes()))-}--pub fn set_key(target: &str, key_name: &str) -> bool {-    if target.is_empty() || key_name.is_empty() {-        return false;-    }-    let directory = auth_dir();-    if !crate::core::ensure_directory(&directory) {-        return false;-    }-    crate::core::write_file(&target_path(&directory, target), key_name.as_bytes())-}--pub fn remove_key(target: &str) -> bool {-    crate::core::remove_file(&target_path(&auth_dir(), target))-}--pub fn list_credentials() -> Vec<String> {-    let directory = auth_dir();-    let mut output = Vec::new();-    for name in crate::core::list_directory(&directory) {-        let Some(decoded) = hex_decode(&String::from_utf8_lossy(&name)) else {-            continue;-        };-        let Ok(decoded) = String::from_utf8(decoded) else {-            continue;-        };-        let Some(data) = crate::core::read_file_opt(&target_path(&directory, &decoded), 0) else {-            continue;-        };-        let key = String::from_utf8_lossy(&data).trim().to_string();-        if !key.is_empty() {-            output.push(format!("{decoded}: {key}\n"));-        }-    }-    output-}--pub fn local_key_exists(name: &str) -> bool {-    !name.is_empty() && !name.starts_with("ed25519:") && load_key(name).is_some()-}--fn lookup_credential(directory: &std::path::Path, target: &str) -> Option<String> {-    let data = crate::core::read_file_opt(&target_path(directory, target), 0)?;-    let value = String::from_utf8_lossy(&data).trim().to_string();-    if value.is_empty() { None } else { Some(value) }-}--pub fn key_for_url(url: &str) -> Option<String> {-    let directory = auth_dir();-    if let Some(authority) = authority_of(url) {-        if let Some(key) = lookup_credential(&directory, &authority) {-            return Some(key);-        }-        if let Some((host, _)) = authority.rsplit_once(':')-            && let Some(key) = lookup_credential(&directory, host)-        {-            return Some(key);-        }-    }-    lookup_credential(&directory, "default")-}--#[derive(Clone)]-pub struct AccessEntry {-    pub public_key: PublicKey,-    pub name: String,-    pub role: u8,-}--#[derive(Clone)]-pub struct Access {-    pub valid: bool,-    pub error_line: i64,-    pub anonymous_read: bool,-    pub entries: Vec<AccessEntry>,-}--pub fn empty_access() -> Access {-    Access {-        valid: true,-        error_line: 0,-        anonymous_read: false,-        entries: Vec::new(),-    }-}--pub fn access_path(repo_root: &std::path::Path) -> std::path::PathBuf {-    crate::store::layout::veins_dir(repo_root).join("access")-}--pub fn load_access(repo_root: &std::path::Path) -> Access {-    let path = access_path(repo_root);-    if let Ok(metadata) = fs::metadata(&path)-        && crate::platform::permissions_mode(&metadata) & 18 != 0-    {-        return Access {-            valid: false,-            error_line: 0,-            anonymous_read: false,-            entries: Vec::new(),-        };-    }-    let Some(data) = crate::core::read_file_opt(&path, 0) else {-        return empty_access();-    };-    let text = String::from_utf8_lossy(&data);-    let mut access = empty_access();-    for (index, raw) in text.lines().enumerate() {-        let line = crate::core::trim_str(raw);-        if line.is_empty() || line.starts_with('#') {-            continue;-        }-        let tokens: Vec<&str> = line.split_whitespace().collect();-        let bad = if tokens.len() == 2 && tokens[0] == "anonymous" {-            if tokens[1] == "read" {-                access.anonymous_read = true;-                false-            } else {-                true-            }-        } else if tokens.len() >= 3 && tokens[0] == "allow" {-            let role = match tokens[1] {-                "read" => 1,-                "write" => 2,-                _ => 0,-            };-            match parse_public_key(tokens[2]) {-                Some(public_key) if role != 0 => {-                    if access-                        .entries-                        .iter()-                        .any(|entry| entry.public_key == public_key)-                    {-                        true-                    } else {-                        access.entries.push(AccessEntry {-                            public_key,-                            name: tokens.get(3).copied().unwrap_or("").to_string(),-                            role,-                        });-                        false-                    }-                }-                _ => true,-            }-        } else {-            true-        };-        if bad {-            return Access {-                valid: false,-                error_line: index as i64 + 1,-                anonymous_read: false,-                entries: Vec::new(),-            };-        }-    }-    access-}--fn set_mode(path: &std::path::Path, mode: u32) {-    let _ = crate::platform::set_mode(path, mode);-}--pub fn write_access(repo_root: &std::path::Path, access: &Access) -> bool {-    let mut body = String::from("# veins access policy\n");-    if access.anonymous_read {-        body.push_str("anonymous read\n");-    }-    for entry in &access.entries {-        if entry.name.len() > 64 {-            return false;-        }-        body.push_str("allow ");-        body.push_str(if entry.role == 2 { "write" } else { "read" });-        body.push(' ');-        body.push_str(&format_public_key(&entry.public_key));-        if !entry.name.is_empty() {-            body.push(' ');-            body.push_str(&entry.name);-        }-        body.push('\n');-    }-    let path = access_path(repo_root);-    if !crate::core::write_file(&path, body.as_bytes()) {-        return false;-    }-    set_mode(&path, 0o600);-    true-}--pub fn role_for(access: &Access, public_key: Option<&PublicKey>) -> u8 {-    match public_key {-        None => {-            if access.anonymous_read {-                1-            } else {-                0-            }-        }-        Some(public_key) => access-            .entries-            .iter()-            .find(|entry| entry.public_key == *public_key)-            .map(|entry| entry.role)-            .unwrap_or(255),-    }-}--pub fn add_access(-    repo_root: &std::path::Path,-    role: u8,-    public_key: &PublicKey,-    name: &str,-) -> bool {-    let mut access = load_access(repo_root);-    if !access.valid-        || access-            .entries-            .iter()-            .any(|entry| entry.public_key == *public_key)-    {-        return false;-    }-    access.entries.push(AccessEntry {-        public_key: *public_key,-        name: name.to_string(),-        role,-    });-    write_access(repo_root, &access)-}--pub fn remove_access(repo_root: &std::path::Path, fingerprint: &str, name: &str) -> bool {-    let mut access = load_access(repo_root);-    if !access.valid {-        return false;-    }-    let before = access.entries.len();-    access.entries.retain(|entry| {-        let by_fingerprint =-            !fingerprint.is_empty() && key_fingerprint(&entry.public_key) == fingerprint;-        let by_name = !name.is_empty() && entry.name == name;-        !(by_fingerprint || by_name)-    });-    access.entries.len() != before && write_access(repo_root, &access)-}--pub fn set_anonymous(repo_root: &std::path::Path, enabled: bool) -> bool {-    let mut access = load_access(repo_root);-    if !access.valid {-        return false;-    }-    access.anonymous_read = enabled;-    write_access(repo_root, &access)-}--- a/veinsrs/src/encoding/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod reader;-pub mod writer;--pub use reader::Reader;-pub use writer::Writer;--- a/veinsrs/src/encoding/reader.rs+++ /dev/null@@ -1,112 +0,0 @@-use crate::error::{Error, Result};-use crate::object::id::Id;--pub struct Reader<'a> {-    data: &'a [u8],-    position: usize,-}--impl<'a> Reader<'a> {-    pub fn new(data: &'a [u8]) -> Self {-        Self { data, position: 0 }-    }--    pub fn offset(&self) -> usize {-        self.position-    }--    pub fn remaining(&self) -> usize {-        self.data.len().saturating_sub(self.position)-    }--    fn take(&mut self, length: usize) -> Result<&'a [u8]> {-        if length > self.remaining() {-            return Err(Error::new("unexpected end of input"));-        }-        let start = self.position;-        self.position += length;-        Ok(&self.data[start..start + length])-    }--    pub fn u8(&mut self) -> Result<u8> {-        Ok(self.take(1)?[0])-    }--    pub fn u16le(&mut self) -> Result<u16> {-        let bytes = self.take(2)?;-        Ok(u16::from_le_bytes([bytes[0], bytes[1]]))-    }--    pub fn u32le(&mut self) -> Result<u32> {-        let bytes = self.take(4)?;-        Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))-    }--    pub fn u64le(&mut self) -> Result<u64> {-        let bytes = self.take(8)?;-        let mut value = [0u8; 8];-        value.copy_from_slice(bytes);-        Ok(u64::from_le_bytes(value))-    }--    pub fn i16le(&mut self) -> Result<i16> {-        Ok(self.u16le()? as i16)-    }--    pub fn i64le(&mut self) -> Result<i64> {-        Ok(self.u64le()? as i64)-    }--    pub fn varint(&mut self) -> Result<u64> {-        let mut value = 0u64;-        for index in 0..10 {-            let byte = self.u8()?;-            if index == 9 && byte > 1 {-                return Err(Error::new("varint overflow"));-            }-            value |= u64::from(byte & 0x7f) << (index * 7);-            if byte & 0x80 == 0 {-                if index > 0 && byte == 0 {-                    return Err(Error::new("non-minimal varint"));-                }-                return Ok(value);-            }-        }-        Err(Error::new("varint too long"))-    }--    pub fn bytes(&mut self, maximum: usize) -> Result<&'a [u8]> {-        let length = self.varint()?;-        let length = usize::try_from(length).map_err(|_| Error::new("length overflow"))?;-        if length > maximum {-            return Err(Error::new("length limit exceeded"));-        }-        self.take(length)-    }--    pub fn raw(&mut self, length: usize) -> Result<&'a [u8]> {-        self.take(length)-    }--    pub fn id(&mut self) -> Result<Id> {-        let mut value = [0u8; 32];-        value.copy_from_slice(self.take(32)?);-        Ok(Id(value))-    }--    pub fn opt_id(&mut self) -> Result<Option<Id>> {-        match self.u8()? {-            0 => Ok(None),-            1 => Ok(Some(self.id()?)),-            _ => Err(Error::new("invalid optional value")),-        }-    }--    pub fn finish(&self) -> Result<()> {-        if self.position == self.data.len() {-            Ok(())-        } else {-            Err(Error::new("trailing bytes"))-        }-    }-}--- a/veinsrs/src/encoding/writer.rs+++ /dev/null@@ -1,105 +0,0 @@-use crate::object::id::Id;--#[derive(Default)]-pub struct Writer {-    data: Vec<u8>,-}--impl Writer {-    pub fn new() -> Self {-        Self::default()-    }--    pub fn with_capacity(capacity: usize) -> Self {-        Self {-            data: Vec::with_capacity(capacity),-        }-    }--    pub fn len(&self) -> usize {-        self.data.len()-    }--    pub fn is_empty(&self) -> bool {-        self.data.is_empty()-    }--    pub fn u8(&mut self, value: u8) {-        self.data.push(value);-    }--    pub fn u16le(&mut self, value: u16) {-        self.data.extend_from_slice(&value.to_le_bytes());-    }--    pub fn u32le(&mut self, value: u32) {-        self.data.extend_from_slice(&value.to_le_bytes());-    }--    pub fn u64le(&mut self, value: u64) {-        self.data.extend_from_slice(&value.to_le_bytes());-    }--    pub fn i16le(&mut self, value: i16) {-        self.u16le(value as u16);-    }--    pub fn i64le(&mut self, value: i64) {-        self.u64le(value as u64);-    }--    pub fn varint_into(output: &mut Vec<u8>, mut value: u64) {-        loop {-            let byte = (value & 0x7f) as u8;-            value >>= 7;-            if value == 0 {-                output.push(byte);-                return;-            }-            output.push(byte | 0x80);-        }-    }--    pub fn varint(&mut self, mut value: u64) {-        loop {-            let byte = (value & 0x7f) as u8;-            value >>= 7;-            if value == 0 {-                self.data.push(byte);-                return;-            }-            self.data.push(byte | 0x80);-        }-    }--    pub fn raw(&mut self, bytes: &[u8]) {-        self.data.extend_from_slice(bytes);-    }--    pub fn bytes(&mut self, bytes: &[u8]) {-        self.varint(bytes.len() as u64);-        self.data.extend_from_slice(bytes);-    }--    pub fn id(&mut self, id: Id) {-        self.data.extend_from_slice(&id.0);-    }--    pub fn opt_id(&mut self, id: Option<Id>) {-        match id {-            Some(value) => {-                self.u8(1);-                self.id(value);-            }-            None => self.u8(0),-        }-    }--    pub fn into_vec(self) -> Vec<u8> {-        self.data-    }--    pub fn as_slice(&self) -> &[u8] {-        &self.data-    }-}--- a/veinsrs/src/error.rs+++ /dev/null@@ -1,69 +0,0 @@-use std::fmt;-use std::io;--pub type Result<T> = std::result::Result<T, Error>;--#[derive(Debug)]-pub struct Error {-    message: String,-}--impl Error {-    pub fn new(message: impl Into<String>) -> Self {-        Self {-            message: message.into(),-        }-    }--    pub fn io(message: impl Into<String>) -> Self {-        Self::new(message)-    }--    pub fn usage(message: impl Into<String>) -> Self {-        Self::new(message)-    }--    pub fn context(self, context: impl AsRef<str>) -> Self {-        Self::new(format!("{}: {}", context.as_ref(), self.message))-    }--    pub fn message(&self) -> &str {-        &self.message-    }-}--impl fmt::Display for Error {-    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {-        formatter.write_str(&self.message)-    }-}--impl std::error::Error for Error {}--impl From<io::Error> for Error {-    fn from(error: io::Error) -> Self {-        Self::new(error.to_string())-    }-}--impl From<String> for Error {-    fn from(message: String) -> Self {-        Self::new(message)-    }-}--impl From<&str> for Error {-    fn from(message: &str) -> Self {-        Self::new(message)-    }-}--pub trait OptionExt<T> {-    fn or_error(self, message: impl Into<String>) -> Result<T>;-}--impl<T> OptionExt<T> for Option<T> {-    fn or_error(self, message: impl Into<String>) -> Result<T> {-        self.ok_or_else(|| Error::new(message))-    }-}--- a/veinsrs/src/git.rs+++ /dev/null@@ -1,847 +0,0 @@-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::process::{Command, Stdio};--use crate::core;-use crate::error::{Error, Result};-use crate::identity;-use crate::object::blob;-use crate::object::commit::{self, Commit, Sig};-use crate::object::id::Id;-use crate::object::tree::{self, FlatEntry, TreeEntry};-use crate::object::view::{Bookmark, TagRef};-use crate::object::{TYPE_COMMIT, TYPE_TREE};-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;--#[derive(Clone, Copy)]-pub struct Oid(pub [u8; 20]);--impl Oid {-    pub fn from_hex(text: &str) -> Option<Self> {-        if text.len() != 40 {-            return None;-        }-        let mut value = [0u8; 20];-        for index in 0..20 {-            let high = hex_value(text.as_bytes()[index * 2])?;-            let low = hex_value(text.as_bytes()[index * 2 + 1])?;-            value[index] = (high << 4) | low;-        }-        Some(Self(value))-    }--    pub fn hex(self) -> String {-        let mut output = String::with_capacity(40);-        for byte in self.0 {-            output.push_str(&format!("{byte:02x}"));-        }-        output-    }-}--fn hex_value(byte: u8) -> Option<u8> {-    match byte {-        b'0'..=b'9' => Some(byte - b'0'),-        b'a'..=b'f' => Some(byte - b'a' + 10),-        b'A'..=b'F' => Some(byte - b'A' + 10),-        _ => None,-    }-}--fn mirror_dir(root: &Path) -> PathBuf {-    layout::git_dir(root)-}--fn run_git(arguments: &[&str], cwd: Option<&Path>, stdin: Option<&[u8]>) -> Result<Vec<u8>> {-    let mut command = Command::new("git");-    command.args(arguments);-    if let Some(cwd) = cwd {-        command.current_dir(cwd);-    }-    command.stdout(Stdio::piped()).stderr(Stdio::piped());-    if stdin.is_some() {-        command.stdin(Stdio::piped());-    } else {-        command.stdin(Stdio::null());-    }-    let mut child = command.spawn().map_err(Error::from)?;-    if let Some(data) = stdin {-        use std::io::Write;-        let mut pipe = child-            .stdin-            .take()-            .ok_or_else(|| Error::new("cannot open git stdin"))?;-        pipe.write_all(data).map_err(Error::from)?;-    }-    let output = child.wait_with_output().map_err(Error::from)?;-    if !output.status.success() {-        return Err(Error::new(-            String::from_utf8_lossy(&output.stderr).into_owned(),-        ));-    }-    Ok(output.stdout)-}--fn git_dir_command(arguments: &[&str], mirror: &Path, stdin: Option<&[u8]>) -> Result<Vec<u8>> {-    let mut full = vec!["--git-dir", mirror.to_str().unwrap_or("")];-    full.extend_from_slice(arguments);-    run_git(&full, None, stdin)-}--pub fn prepare_mirror(root: &Path, source: &str) -> i32 {-    let source_path = Path::new(source);-    if !source_path.join(".git").exists() {-        return 2;-    }-    let mirror = mirror_dir(root);-    let _ = std::fs::remove_dir_all(&mirror);-    if let Some(parent) = mirror.parent() {-        let _ = std::fs::create_dir_all(parent);-    }-    let mirror_text = mirror.to_str().unwrap_or("");-    match run_git(&["clone", "--mirror", source, mirror_text], None, None) {-        Ok(_) => 0,-        Err(_) => 1,-    }-}--pub fn configure_remote(root: &Path, url: &str, name: &str) {-    if url.is_empty() {-        crate::cli::output::warning_prefix();-        println!(-            "no native remote configured; set one with 'vn remote add o <url>' and push with 'vn psh o'"-        );-        return;-    }-    core::repo_config_set(root, &format!("remote.{name}.url"), url);-    core::repo_config_set(root, "remote.default", name);-}--pub fn import(root: &Path) -> i32 {-    match import_inner(root) {-        Ok(()) => 0,-        Err(error) => {-            crate::cli::output::error_prefix();-            println!("git import failed: {error}");-            1-        }-    }-}--fn import_inner(root: &Path) -> Result<()> {-    let mirror = mirror_dir(root);-    let refs_output = git_dir_command(&["for-each-ref", "--format=%(refname)"], &mirror, None)?;-    let refs_text = String::from_utf8_lossy(&refs_output);-    let mut bookmarks = Vec::new();-    let mut tags = Vec::new();-    for line in refs_text.lines() {-        let name = line.trim();-        if name.is_empty() {-            continue;-        }-        let Some(oid_text) =-            git_dir_command(&["rev-parse", &format!("{name}^{{commit}}")], &mirror, None)-                .ok()-                .and_then(|data| String::from_utf8(data).ok())-        else {-            continue;-        };-        let Some(oid) = Oid::from_hex(oid_text.trim()) else {-            continue;-        };-        if let Some(short) = name.strip_prefix("refs/heads/") {-            bookmarks.push((short.to_string(), oid));-        } else if let Some(short) = name.strip_prefix("refs/tags/") {-            tags.push((short.to_string(), oid));-        }-    }-    let revs = git_dir_command(&["rev-list", "--all", "--reverse"], &mirror, None)?;-    let revs_text = String::from_utf8_lossy(&revs);-    let mut store = Store::open(root)?;-    let mut txn = Txn::begin(root, &mut store)?;-    let mut mapped: HashMap<String, Id> = HashMap::new();-    let mut ordered: Vec<String> = revs_text-        .lines()-        .map(|line| line.trim().to_string())-        .filter(|line| !line.is_empty())-        .collect();-    ordered.reverse();-    ordered.reverse();-    let progress = crate::core::Progress::new("importing commits", ordered.len());-    for oid_text in ordered {-        let Some(oid) = Oid::from_hex(&oid_text) else {-            continue;-        };-        import_commit(&mirror, &mut txn, &mut store, oid, &mut mapped)?;-        progress.advance(1);-    }-    progress.finish();-    for (name, oid) in bookmarks {-        if let Some(target) = mapped.get(&oid.hex()) {-            set_bookmark(txn.view_mut(), &name, *target);-        }-    }-    for (name, oid) in tags {-        if let Some(target) = mapped.get(&oid.hex()) {-            set_tag(txn.view_mut(), &name, *target);-        }-    }-    ops::rebuild_heads(txn.view_mut());-    let default = bookmarks_default(&txn.view().bookmarks);-    let default_name = bookmarks_default_name(&txn.view().bookmarks);-    txn.finish("git import")?;-    store.refresh()?;-    if let Some(target) = default {-        let mut checkout_txn = Txn::begin(root, &mut store)?;-        let child = create_working_copy(&mut checkout_txn, &mut store, target)?;-        ops::set_workspace(checkout_txn.view_mut(), child);-        ops::rebuild_heads(checkout_txn.view_mut());-        checkout_txn.finish("checkout")?;-    }-    if let Some(name) = default_name {-        core::set_current_bookmark(root, &name);-    }-    materialize(root);-    Ok(())-}--fn bookmarks_default(bookmarks: &[Bookmark]) -> Option<Id> {-    for bookmark in bookmarks {-        if matches!(bookmark.name.as_slice(), b"main" | b"master") {-            return bookmark.targets.adds.first().copied().flatten();-        }-    }-    bookmarks-        .iter()-        .find_map(|bookmark| bookmark.targets.adds.first().copied().flatten())-}--fn bookmarks_default_name(bookmarks: &[Bookmark]) -> Option<String> {-    for bookmark in bookmarks {-        if matches!(bookmark.name.as_slice(), b"main" | b"master") {-            return Some(String::from_utf8_lossy(&bookmark.name).into_owned());-        }-    }-    bookmarks-        .first()-        .map(|bookmark| String::from_utf8_lossy(&bookmark.name).into_owned())-}--fn set_bookmark(view: &mut crate::object::view::View, name: &str, target: Id) {-    ops::set_bookmark_target(view, name.as_bytes(), target);-}--fn set_tag(view: &mut crate::object::view::View, name: &str, target: Id) {-    view.tags.push(TagRef {-        name: name.as_bytes().to_vec(),-        target,-    });-}--fn create_working_copy(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {-    let loaded = graph::load_commit(store, parent)?-        .ok_or_else(|| Error::new("cannot read parent commit"))?;-    let signature = identity::signature(store.root());-    let commit = Commit {-        version: 1,-        parents: vec![parent],-        root_tree: loaded.root_tree,-        change_id: identity::random_change_id(),-        author: signature.clone(),-        committer: signature,-        message: Vec::new(),-        renames_state: commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))-}--struct ParsedCommit {-    parents: Vec<String>,-    author: Sig,-    committer: Sig,-    message: Vec<u8>,-    extra: Vec<(Vec<u8>, Vec<u8>)>,-}--fn parse_sig(text: &str) -> Sig {-    let (name, rest) = text.split_once(" <").unwrap_or((text, "> 0 +0000"));-    let (email, rest) = rest.split_once('>').unwrap_or((rest, " 0 +0000"));-    let mut parts = rest.split_whitespace();-    let seconds = parts-        .next()-        .and_then(|value| value.parse().ok())-        .unwrap_or(0);-    let tz = parts.next().unwrap_or("+0000");-    let tz_min = parse_tz(tz);-    Sig {-        name: name.as_bytes().to_vec(),-        email: email.as_bytes().to_vec(),-        seconds,-        tz_min,-    }-}--fn parse_tz(text: &str) -> i16 {-    if text.len() != 5 {-        return 0;-    }-    let sign = if text.starts_with('-') { -1 } else { 1 };-    let hours: i16 = text[1..3].parse().unwrap_or(0);-    let minutes: i16 = text[3..5].parse().unwrap_or(0);-    sign * (hours * 60 + minutes)-}--fn parse_git_commit(data: &[u8]) -> Option<ParsedCommit> {-    let split = data-        .windows(2)-        .position(|window| window == b"\n\n")-        .unwrap_or(data.len());-    let header = String::from_utf8_lossy(&data[..split]);-    let message = if split + 2 <= data.len() {-        data[split + 2..].to_vec()-    } else {-        Vec::new()-    };-    let mut parents = Vec::new();-    let mut author = Sig::default();-    let mut committer = Sig::default();-    let mut extra = Vec::new();-    for line in header.lines() {-        if let Some(value) = line.strip_prefix("parent ") {-            parents.push(value.to_string());-        } else if let Some(value) = line.strip_prefix("author ") {-            author = parse_sig(value);-        } else if let Some(value) = line.strip_prefix("committer ") {-            committer = parse_sig(value);-        } else if let Some((key, value)) = line.split_once(' ')-            && !line.starts_with(' ')-            && key != "gpgsig"-        {-            extra.push((key.as_bytes().to_vec(), value.as_bytes().to_vec()));-        }-    }-    Some(ParsedCommit {-        parents,-        author,-        committer,-        message,-        extra,-    })-}--fn import_commit(-    mirror: &Path,-    txn: &mut Txn,-    store: &mut Store,-    oid: Oid,-    mapped: &mut HashMap<String, Id>,-) -> Result<()> {-    if mapped.contains_key(&oid.hex()) {-        return Ok(());-    }-    let data = git_dir_command(&["cat-file", "commit", &oid.hex()], mirror, None)?;-    let parsed = parse_git_commit(&data).ok_or_else(|| Error::new("corrupt git commit"))?;-    for parent in &parsed.parents {-        if let Some(parent_oid) = Oid::from_hex(parent)-            && !mapped.contains_key(&oid.hex())-        {-            import_commit(mirror, txn, store, parent_oid, mapped)?;-        }-    }-    let entries = git_flat_entries(mirror, &oid.hex())?;-    let root_tree = build_tree(txn, &entries)?;-    let parents: Vec<Id> = parsed-        .parents-        .iter()-        .filter_map(|parent| mapped.get(parent).copied())-        .collect();-    let change_hash = blake3::hash(oid.hex().as_bytes());-    let mut change_id = [0u8; 16];-    change_id.copy_from_slice(&change_hash.as_bytes()[..16]);-    let commit = Commit {-        version: 1,-        parents,-        root_tree,-        change_id,-        author: parsed.author,-        committer: parsed.committer,-        message: parsed.message,-        renames_state: commit::RENAMES_UNKNOWN,-        renames: Vec::new(),-        extra: parsed.extra,-    };-    let id = txn.add_object(TYPE_COMMIT, commit::encode(&commit));-    mapped.insert(oid.hex(), id);-    Ok(())-}--fn git_flat_entries(mirror: &Path, revision: &str) -> Result<Vec<FlatEntry>> {-    let output = git_dir_command(&["ls-tree", "-r", "-z", revision], mirror, None)?;-    let mut entries = Vec::new();-    for record in output.split(|byte| *byte == 0) {-        if record.is_empty() {-            continue;-        }-        let Some(tab) = record.iter().position(|byte| *byte == b'\t') else {-            continue;-        };-        let meta = String::from_utf8_lossy(&record[..tab]).into_owned();-        let path = record[tab + 1..].to_vec();-        let mut parts = meta.split_whitespace();-        let mode = parts.next().unwrap_or("100644");-        let kind = parts.next().unwrap_or("blob");-        let oid_text = parts.next().unwrap_or("");-        let kind = if kind == "commit" || mode == "160000" {-            tree::KIND_SUBMODULE-        } else if mode == "120000" {-            tree::KIND_SYMLINK-        } else if mode == "100755" {-            tree::KIND_EXECUTABLE-        } else {-            tree::KIND_FILE-        };-        let target = if kind == tree::KIND_SUBMODULE {-            let Some(oid) = Oid::from_hex(oid_text) else {-                continue;-            };-            let mut id = [0u8; 32];-            id[..20].copy_from_slice(&oid.0);-            Id(id)-        } else {-            let data = git_dir_command(&["cat-file", "blob", oid_text], mirror, None)?;-            let build = blob::build(&data);-            for object in build.objects {-                txn_add_later(&object);-            }-            build.root-        };-        entries.push(FlatEntry { path, kind, target });-    }-    Ok(entries)-}--thread_local! {-    static PENDING: std::cell::RefCell<Vec<crate::object::RawObject>> = const { std::cell::RefCell::new(Vec::new()) };-}--fn txn_add_later(object: &crate::object::RawObject) {-    PENDING.with(|pending| pending.borrow_mut().push(object.clone()));-}--fn drain_pending(txn: &mut Txn) {-    PENDING.with(|pending| {-        for object in pending.borrow_mut().drain(..) {-            txn.add_known(object.kind, object.id, object.body);-        }-    });-}--fn build_tree(txn: &mut Txn, entries: &[FlatEntry]) -> Result<Id> {-    drain_pending(txn);-    let mut sorted = entries.to_vec();-    sorted.sort_by(|left, right| left.path.cmp(&right.path));-    build_level(txn, &sorted, 0, sorted.len(), 0)-}--fn build_level(-    txn: &mut Txn,-    entries: &[FlatEntry],-    start: usize,-    end: usize,-    prefix: usize,-) -> Result<Id> {-    let mut output = Vec::new();-    let mut index = start;-    while index < end {-        let entry = &entries[index];-        let cut = entry.path[prefix..]-            .iter()-            .position(|byte| *byte == b'/')-            .map(|offset| prefix + offset)-            .unwrap_or(entry.path.len());-        let name = entry.path[prefix..cut].to_vec();-        if cut == entry.path.len() {-            output.push(TreeEntry {-                name,-                kind: entry.kind,-                target: entry.target,-            });-            index += 1;-        } else {-            let mut next = index + 1;-            while next < end {-                let other = &entries[next];-                let other_cut = other.path[prefix..]-                    .iter()-                    .position(|byte| *byte == b'/')-                    .map(|offset| prefix + offset)-                    .unwrap_or(other.path.len());-                if other_cut != cut || other.path[prefix..cut] != entry.path[prefix..cut] {-                    break;-                }-                next += 1;-            }-            let child = build_level(txn, entries, index, next, cut + 1)?;-            output.push(TreeEntry {-                name,-                kind: tree::KIND_SUBTREE,-                target: child,-            });-            index = next;-        }-    }-    Ok(txn.add_object(TYPE_TREE, tree::encode(&output)?))-}--pub fn materialize(root: &Path) -> i32 {-    let result = (|| -> Result<()> {-        let mut store = Store::open(root)?;-        let view =-            ops::current_view(root, &mut store)?.ok_or_else(|| Error::new("no operation state"))?;-        if let Some(working) = ops::working_copy_id(&view)-            && let Some(commit) = graph::load_commit(&mut store, working)?-        {-            let progress = crate::core::Progress::new("checking out files", 0);-            crate::worktree::checkout::materialize_with_progress(-                root,-                &mut store,-                None,-                commit.root_tree,-                Some(&progress),-            )?;-        }-        Ok(())-    })();-    match result {-        Ok(()) => 0,-        Err(error) => {-            crate::cli::output::error_prefix();-            println!("git materialize failed: {error}");-            1-        }-    }-}--pub fn export(root: &Path) -> i32 {-    match export_inner(root) {-        Ok(()) => 0,-        Err(error) => {-            crate::cli::output::error_prefix();-            println!("git export failed: {error}");-            1-        }-    }-}--fn export_inner(root: &Path) -> Result<()> {-    let mirror = mirror_dir(root);-    if !mirror.is_dir() {-        std::fs::create_dir_all(&mirror)?;-        run_git(-            &["init", "--bare", mirror.to_str().unwrap_or("")],-            None,-            None,-        )?;-    }-    let mut store = Store::open(root)?;-    let view = ops::current_view(root, &mut store)?.unwrap_or_default();-    let commits = graph::collect_commits(&mut store, &graph::view_roots(&view))?;-    let nodes: Vec<graph::LogNode> = {-        let mut output = Vec::new();-        for id in &commits {-            if let Some(commit) = graph::load_commit(&mut store, *id)? {-                output.push(graph::LogNode {-                    id: *id,-                    seconds: commit.committer.seconds,-                    parents: commit.parents,-                });-            }-        }-        output-    };-    let order = graph::order_log_nodes(&nodes);-    let mut ordered = Vec::new();-    for index in order.into_iter().rev() {-        ordered.push(nodes[index].id);-    }-    let mut stream: Vec<u8> = Vec::new();-    let mut marks: HashMap<Id, usize> = HashMap::new();-    let mut blob_marks: HashMap<Id, usize> = HashMap::new();-    let mut next_mark = 1usize;-    let mut next_blob = 1_000_000usize;-    for id in &ordered {-        let Some(commit) = graph::load_commit(&mut store, *id)? else {-            continue;-        };-        let entries = tree::flatten(&mut store, commit.root_tree)?;-        let mut file_lines = Vec::new();-        for entry in &entries {-            if matches!(entry.kind, tree::KIND_CONFLICT | tree::KIND_SUBMODULE) {-                continue;-            }-            let mark = if let Some(mark) = blob_marks.get(&entry.target) {-                *mark-            } else {-                let Some(data) = graph::read_blob(&mut store, entry.target)? else {-                    continue;-                };-                let mark = next_blob;-                next_blob += 1;-                blob_marks.insert(entry.target, mark);-                stream.extend_from_slice(-                    format!("blob\nmark :{mark}\ndata {}\n", data.len()).as_bytes(),-                );-                stream.extend_from_slice(&data);-                stream.push(b'\n');-                mark-            };-            let mode = match entry.kind {-                tree::KIND_EXECUTABLE => "100755",-                tree::KIND_SYMLINK => "120000",-                _ => "100644",-            };-            let mut line = format!("M {mode} :{mark} ").into_bytes();-            line.extend_from_slice(&entry.path);-            line.push(b'\n');-            file_lines.push(line);-        }-        let mark = next_mark;-        next_mark += 1;-        marks.insert(*id, mark);-        stream.extend_from_slice(b"commit refs/veins/export\n");-        stream.extend_from_slice(format!("mark :{mark}\n").as_bytes());-        stream.extend_from_slice(-            format!(-                "author {} <{}> {} {}\n",-                String::from_utf8_lossy(&commit.author.name),-                String::from_utf8_lossy(&commit.author.email),-                commit.author.seconds,-                format_tz(commit.author.tz_min)-            )-            .as_bytes(),-        );-        stream.extend_from_slice(-            format!(-                "committer {} <{}> {} {}\n",-                String::from_utf8_lossy(&commit.committer.name),-                String::from_utf8_lossy(&commit.committer.email),-                commit.committer.seconds,-                format_tz(commit.committer.tz_min)-            )-            .as_bytes(),-        );-        stream.extend_from_slice(format!("data {}\n", commit.message.len()).as_bytes());-        stream.extend_from_slice(&commit.message);-        stream.push(b'\n');-        if let Some(parent) = commit.parents.first()-            && let Some(parent_mark) = marks.get(parent)-        {-            stream.extend_from_slice(format!("from :{parent_mark}\n").as_bytes());-        }-        for parent in commit.parents.iter().skip(1) {-            if let Some(parent_mark) = marks.get(parent) {-                stream.extend_from_slice(format!("merge :{parent_mark}\n").as_bytes());-            }-        }-        stream.extend_from_slice(b"deleteall\n");-        for line in file_lines {-            stream.extend_from_slice(&line);-        }-        stream.push(b'\n');-    }-    for bookmark in &view.bookmarks {-        if let Some(target) = bookmark.targets.adds.first().copied().flatten()-            && let Some(mark) = marks.get(&target)-        {-            stream.extend_from_slice(b"reset refs/heads/");-            stream.extend_from_slice(&bookmark.name);-            stream.extend_from_slice(format!("\nfrom :{mark}\n\n").as_bytes());-        }-    }-    for tag in &view.tags {-        if let Some(mark) = marks.get(&tag.target) {-            stream.extend_from_slice(b"reset refs/tags/");-            stream.extend_from_slice(&tag.name);-            stream.extend_from_slice(format!("\nfrom :{mark}\n\n").as_bytes());-        }-    }-    git_dir_command(-        &["fast-import", "--quiet", "--force"],-        &mirror,-        Some(&stream),-    )?;-    sync_mirror_refs(&mirror, &view)?;-    Ok(())-}--fn sync_mirror_refs(mirror: &Path, view: &crate::object::view::View) -> Result<()> {-    let output = git_dir_command(&["for-each-ref", "--format=%(refname)"], mirror, None)?;-    let text = String::from_utf8_lossy(&output);-    for line in text.lines() {-        let name = line.trim();-        if let Some(tag) = name.strip_prefix("refs/tags/") {-            if ops::find_tag(view, tag.as_bytes()).is_none() {-                let _ = git_dir_command(&["update-ref", "-d", name], mirror, None);-            }-        } else if let Some(bookmark) = name.strip_prefix("refs/heads/") {-            if ops::find_bookmark(view, bookmark.as_bytes()).is_none() {-                let _ = git_dir_command(&["update-ref", "-d", name], mirror, None);-            }-        }-    }-    Ok(())-}--fn format_tz(minutes: i16) -> String {-    let sign = if minutes < 0 { '-' } else { '+' };-    let value = minutes.abs();-    format!("{sign}{:02}{:02}", value / 60, value % 60)-}--pub fn fetch(root: &Path, remote: &str) -> i32 {-    let mirror = mirror_dir(root);-    if !mirror.is_dir() {-        std::fs::create_dir_all(&mirror).ok();-        let _ = run_git(-            &["init", "--bare", mirror.to_str().unwrap_or("")],-            None,-            None,-        );-    }-    let remote_name = if remote.is_empty() { "origin" } else { remote };-    if run_git(-        &[-            "--git-dir",-            mirror.to_str().unwrap_or(""),-            "config",-            "remote.real.url",-        ],-        None,-        None,-    )-    .is_err()-    {-        let _ = remote_name;-    }-    match git_dir_command(&["fetch", "--prune", remote_name], &mirror, None) {-        Ok(_) => import(root),-        Err(_) => 1,-    }-}--pub fn push(root: &Path, remote: &str, bookmark: &str) -> i32 {-    if export(root) != 0 {-        return 1;-    }-    let mirror = mirror_dir(root);-    let status = run_git(-        &[-            "--git-dir",-            mirror.to_str().unwrap_or(""),-            "push",-            remote,-            &format!("refs/heads/{bookmark}:refs/heads/{bookmark}"),-        ],-        None,-        None,-    );-    if status.is_err() {-        return 1;-    }-    0-}--pub struct MirrorOptions {-    pub force: bool,-    pub prune: bool,-    pub dry_run: bool,-}--pub fn mirror_push(root: &Path, remote: &str, options: &MirrorOptions) -> i32 {-    if export(root) != 0 {-        return 1;-    }-    let mirror = mirror_dir(root);-    let mut arguments = vec!["--git-dir", mirror.to_str().unwrap_or(""), "push"];-    if options.prune {-        arguments.push("--mirror");-        arguments.push("--prune");-    }-    if options.force {-        arguments.push("--force");-    }-    if options.dry_run {-        arguments.push("--dry-run");-    }-    arguments.push(remote);-    if !options.prune {-        arguments.push("refs/heads/*:refs/heads/*");-        arguments.push("refs/tags/*:refs/tags/*");-    }-    if run_git(&arguments, None, None).is_err() {-        return 1;-    }-    0-}--pub fn mirror_tag(root: &Path, remote: &str, tag: &str, options: &MirrorOptions) -> i32 {-    if export(root) != 0 {-        return 1;-    }-    let mirror = mirror_dir(root);-    let mut arguments = vec!["--git-dir", mirror.to_str().unwrap_or(""), "push"];-    if options.force {-        arguments.push("--force");-    }-    if options.dry_run {-        arguments.push("--dry-run");-    }-    let reference = format!("refs/tags/{tag}:refs/tags/{tag}");-    arguments.push(remote);-    arguments.push(&reference);-    if run_git(&arguments, None, None).is_err() {-        return 1;-    }-    0-}--pub fn mirror_remote(root: &Path, sub: &str, name: &str, url: &str) -> i32 {-    let mirror = mirror_dir(root);-    if !mirror.is_dir() {-        std::fs::create_dir_all(&mirror).ok();-        let _ = run_git(-            &["init", "--bare", mirror.to_str().unwrap_or("")],-            None,-            None,-        );-    }-    let result = match sub {-        "add" => git_dir_command(&["remote", "add", name, url], &mirror, None),-        "remove" | "rm" => git_dir_command(&["remote", "remove", name], &mirror, None),-        _ => Ok(Vec::new()),-    };-    if result.is_err() { 1 } else { 0 }-}--pub fn mirror_remote_list(root: &Path) -> Vec<String> {-    let mirror = mirror_dir(root);-    git_dir_command(&["remote"], &mirror, None)-        .map(|data| {-            String::from_utf8_lossy(&data)-                .lines()-                .map(|line| line.trim().to_string())-                .filter(|line| !line.is_empty())-                .collect()-        })-        .unwrap_or_default()-}--pub fn read_lazy_blob(_root: &Path, _id: Id) -> Option<Vec<u8>> {-    None-}--- a/veinsrs/src/identity.rs+++ /dev/null@@ -1,46 +0,0 @@-use std::env;-use std::path::Path;--use crate::core;-use crate::object::commit::Sig;-use crate::time;--fn first_value(root: &Path, key: &str, name: bool, first: &str, second: &str) -> String {-    if let Some(value) = core::repo_config_value(root, key) {-        return value;-    }-    let user = if name {-        core::user_config_author_name()-    } else {-        core::user_config_author_email()-    };-    if let Some(value) = user {-        return value;-    }-    for variable in [first, second] {-        if let Ok(value) = env::var(variable)-            && !value.is_empty()-        {-            return value;-        }-    }-    "unknown".to_string()-}--pub fn signature(root: &Path) -> Sig {-    Sig {-        name: first_value(root, "user.name", true, "GIT_AUTHOR_NAME", "USER").into_bytes(),-        email: first_value(root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL").into_bytes(),-        seconds: time::now_seconds(),-        tz_min: 0,-    }-}--pub fn random_change_id() -> [u8; 16] {-    let first = core::random_u64().to_le_bytes();-    let second = core::random_u64().to_le_bytes();-    let mut value = [0u8; 16];-    value[..8].copy_from_slice(&first);-    value[8..].copy_from_slice(&second);-    value-}--- a/veinsrs/src/lib.rs+++ /dev/null@@ -1,17 +0,0 @@-pub mod cli;-pub mod core;-pub mod crypto;-pub mod encoding;-pub mod error;-pub mod git;-pub mod identity;-pub mod merge;-pub mod object;-pub mod platform;-pub mod protocol;-pub mod server;-pub mod store;-pub mod time;-pub mod worktree;--pub use error::{Error, Result};--- a/veinsrs/src/main.rs+++ /dev/null@@ -1,12 +0,0 @@-use std::process::ExitCode;--fn main() -> ExitCode {-    // `std::env::args()` panics on non-UTF-8 arguments; use the lossy OS form so-    // arbitrary commit messages and revision names degrade to text instead of-    // aborting the process.-    let args: Vec<String> = std::env::args_os()-        .skip(1)-        .map(|argument| argument.to_string_lossy().into_owned())-        .collect();-    ExitCode::from(veins_rust::cli::run(&args))-}--- a/veinsrs/src/merge/engine.rs+++ /dev/null@@ -1,1814 +0,0 @@-use std::path::Path;--use crate::core;-use crate::error::{Error, Result};-use crate::identity;-use crate::object::blob::{self, BlobForm};-use crate::object::commit::{self, Commit, Rename, Sig};-use crate::object::conflict::{self, Conflict, ConflictValue};-use crate::object::id::{Id, object_id};-use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry};-use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};-use crate::store::Txn;-use crate::store::graph;-use crate::store::reader::Store;-use crate::store::writer::Writer;-use crate::worktree::snapshot;--fn same(left: Id, right: Id) -> bool {-    left == right-}--fn read_any(-    store: &mut Store,-    writer: Option<&Writer>,-    kind: u8,-    id: Id,-) -> Result<Option<Vec<u8>>> {-    if let Some(writer) = writer-        && let Some(body) = writer.find_cached(kind, id)-    {-        return Ok(Some(body.to_vec()));-    }-    store.body(id, kind)-}--fn append_blob(-    store: &mut Store,-    writer: Option<&Writer>,-    id: Id,-    output: &mut Vec<u8>,-    depth: usize,-) -> Result<bool> {-    if depth > 64 {-        return Ok(false);-    }-    let Some(body) = read_any(store, writer, TYPE_BLOB, id)? else {-        return Ok(false);-    };-    let blob = blob::decode(&body)?;-    match blob.form {-        BlobForm::Inline => output.extend_from_slice(&blob.data),-        BlobForm::Leaf => {-            for entry in blob.entries {-                let Some(chunk) = read_any(store, writer, TYPE_CHUNK, entry.id)? else {-                    return Ok(false);-                };-                output.extend_from_slice(&chunk);-            }-        }-        BlobForm::Interior => {-            for entry in blob.entries {-                if !append_blob(store, writer, entry.id, output, depth + 1)? {-                    return Ok(false);-                }-            }-        }-    }-    Ok(true)-}--pub fn read_blob_any(-    store: &mut Store,-    writer: Option<&Writer>,-    id: Id,-) -> Result<Option<Vec<u8>>> {-    let mut output = Vec::new();-    if append_blob(store, writer, id, &mut output, 0)? {-        Ok(Some(output))-    } else {-        Ok(None)-    }-}--fn collect_chunks(-    store: &mut Store,-    writer: Option<&Writer>,-    id: Id,-    output: &mut Vec<Id>,-    depth: usize,-) -> Result<bool> {-    if depth > 64 {-        return Ok(false);-    }-    let Some(body) = read_any(store, writer, TYPE_BLOB, id)? else {-        return Ok(false);-    };-    let blob = blob::decode(&body)?;-    match blob.form {-        BlobForm::Leaf => {-            for entry in blob.entries {-                output.push(entry.id);-            }-        }-        BlobForm::Interior => {-            for entry in blob.entries {-                if !collect_chunks(store, writer, entry.id, output, depth + 1)? {-                    return Ok(false);-                }-            }-        }-        BlobForm::Inline => {}-    }-    Ok(true)-}--fn flatten_into(-    store: &mut Store,-    writer: Option<&Writer>,-    tree_id: Id,-    prefix: &mut Vec<u8>,-    output: &mut Vec<FlatEntry>,-    depth: usize,-) -> Result<bool> {-    if depth > crate::object::MAX_TREE_DEPTH {-        return Ok(false);-    }-    let Some(body) = read_any(store, writer, TYPE_TREE, tree_id)? else {-        return Ok(false);-    };-    let tree = tree::decode(&body)?;-    for entry in tree.entries {-        let old_length = prefix.len();-        if !prefix.is_empty() {-            prefix.push(b'/');-        }-        prefix.extend_from_slice(&entry.name);-        if entry.kind == KIND_SUBTREE {-            let ok = flatten_into(store, writer, entry.target, prefix, output, depth + 1)?;-            prefix.truncate(old_length);-            if !ok {-                return Ok(false);-            }-        } else {-            output.push(FlatEntry {-                path: prefix.clone(),-                kind: entry.kind,-                target: entry.target,-            });-            prefix.truncate(old_length);-        }-    }-    Ok(true)-}--pub fn flatten_sorted(-    store: &mut Store,-    writer: Option<&Writer>,-    tree: Option<Id>,-) -> Result<Vec<FlatEntry>> {-    let Some(tree) = tree else {-        return Ok(Vec::new());-    };-    let mut output = Vec::new();-    flatten_into(store, writer, tree, &mut Vec::new(), &mut output, 0)?;-    output.sort_by(|left, right| left.path.cmp(&right.path));-    Ok(output)-}--fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {-    entries-        .binary_search_by(|entry| entry.path.as_slice().cmp(path))-        .ok()-        .map(|index| &entries[index])-}--fn tree_empty(store: &mut Store, writer: Option<&Writer>, id: Id) -> Result<bool> {-    match read_any(store, writer, TYPE_TREE, id)? {-        Some(body) => Ok(tree::decode(&body)-            .map(|tree| tree.entries.is_empty())-            .unwrap_or(true)),-        None => Ok(true),-    }-}--fn add_tree(txn: &mut Txn, entries: &[TreeEntry]) -> Result<Id> {-    Ok(txn.add_object(TYPE_TREE, tree::encode(entries)?))-}--fn add_empty_tree(txn: &mut Txn) -> Result<Id> {-    add_tree(txn, &[])-}--fn add_blob(txn: &mut Txn, data: &[u8]) -> Id {-    let build = blob::build(data);-    for object in build.objects {-        txn.add_known(object.kind, object.id, object.body);-    }-    build.root-}--fn hash_line(line: &[u8]) -> u64 {-    let mut hash = 1_469_598_103_934_665_603u64;-    for byte in line {-        hash = (hash ^ *byte as u64).wrapping_mul(1_099_511_628_211);-    }-    hash-}--fn line_similarity(left: &[u8], right: &[u8]) -> u32 {-    fn lines(data: &[u8]) -> Vec<u64> {-        let mut output = Vec::new();-        let mut start = 0;-        for index in 0..=data.len() {-            if index == data.len() || data[index] == b'\n' {-                output.push(hash_line(&data[start..index]));-                start = index + 1;-            }-        }-        output.sort_unstable();-        output-    }-    let a = lines(left);-    let b = lines(right);-    let mut ia = 0;-    let mut ib = 0;-    let mut intersection = 0;-    while ia < a.len() && ib < b.len() {-        if a[ia] == b[ib] {-            intersection += 1;-            ia += 1;-            ib += 1;-        } else if a[ia] < b[ib] {-            ia += 1;-        } else {-            ib += 1;-        }-    }-    let total = a.len() + b.len() - intersection;-    if total == 0 {-        100-    } else {-        (intersection * 100 / total) as u32-    }-}--fn chunk_similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> {-    let mut left = Vec::new();-    let mut right = Vec::new();-    if !collect_chunks(store, writer, a, &mut left, 0)?-        || !collect_chunks(store, writer, b, &mut right, 0)?-    {-        return Ok(0);-    }-    let mut intersection = 0;-    for item in &left {-        if right.contains(item) {-            intersection += 1;-        }-    }-    let total = left.len() + right.len() - intersection;-    Ok(if total == 0 {-        0-    } else {-        (intersection * 100 / total) as u32-    })-}--fn similarity(store: &mut Store, writer: Option<&Writer>, a: Id, b: Id) -> Result<u32> {-    if same(a, b) {-        return Ok(100);-    }-    let Some(left) = read_blob_any(store, writer, a)? else {-        return Ok(0);-    };-    let Some(right) = read_blob_any(store, writer, b)? else {-        return Ok(0);-    };-    let mut result = 0;-    if left.len() >= 131_072 && right.len() >= 131_072 {-        result = chunk_similarity(store, writer, a, b)?;-    }-    if result == 0 {-        result = line_similarity(&left, &right);-    }-    Ok(result)-}--pub fn detect(-    store: &mut Store,-    writer: Option<&Writer>,-    old_tree: Option<Id>,-    new_tree: Option<Id>,-    similar_pct: u32,-    parent_index: u64,-) -> Result<Vec<Rename>> {-    let old_entries = flatten_sorted(store, writer, old_tree)?;-    let new_entries = flatten_sorted(store, writer, new_tree)?;-    let deleted: Vec<&FlatEntry> = old_entries-        .iter()-        .filter(|entry| find_flat(&new_entries, &entry.path).is_none())-        .collect();-    let added: Vec<&FlatEntry> = new_entries-        .iter()-        .filter(|entry| find_flat(&old_entries, &entry.path).is_none())-        .collect();-    let mut used_old = vec![false; deleted.len()];-    let mut used_new = vec![false; added.len()];-    let mut output = Vec::new();-    for (old_index, old) in deleted.iter().enumerate() {-        if used_old[old_index] {-            continue;-        }-        for (new_index, new) in added.iter().enumerate() {-            if used_new[new_index] {-                continue;-            }-            if old.target == new.target {-                output.push(Rename {-                    parent_index,-                    kind: 0,-                    from_path: old.path.clone(),-                    to_path: new.path.clone(),-                });-                used_old[old_index] = true;-                used_new[new_index] = true;-                break;-            }-        }-    }-    if similar_pct > 0 {-        let mut pairs = Vec::new();-        for (old_index, old) in deleted.iter().enumerate() {-            if used_old[old_index] || !matches!(old.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE) {-                continue;-            }-            for (new_index, new) in added.iter().enumerate() {-                if used_new[new_index]-                    || !matches!(new.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE)-                {-                    continue;-                }-                pairs.push((-                    old_index,-                    new_index,-                    similarity(store, writer, old.target, new.target)?,-                ));-            }-        }-        loop {-            let mut best = None;-            for (old_index, new_index, score) in &pairs {-                if used_old[*old_index] || used_new[*new_index] {-                    continue;-                }-                if best.is_none_or(|(_, _, current): (usize, usize, u32)| *score > current) {-                    best = Some((*old_index, *new_index, *score));-                }-            }-            let Some((old_index, new_index, score)) = best else {-                break;-            };-            if score < similar_pct {-                break;-            }-            used_old[old_index] = true;-            used_new[new_index] = true;-            output.push(Rename {-                parent_index,-                kind: 0,-                from_path: deleted[old_index].path.clone(),-                to_path: added[new_index].path.clone(),-            });-        }-    }-    output.sort_by(|left, right| {-        left.parent_index-            .cmp(&right.parent_index)-            .then_with(|| left.to_path.cmp(&right.to_path))-    });-    Ok(output)-}--pub fn rename_similar_pct(root: &Path) -> u32 {-    match core::repo_config_value(root, "rename.autodetect").as_deref() {-        Some("off") => 0,-        _ => 60,-    }-}--fn split_lines(data: &[u8]) -> Vec<Vec<u8>> {-    let mut output = Vec::new();-    let mut start = 0;-    for index in 0..data.len() {-        if data[index] == b'\n' {-            output.push(data[start..=index].to_vec());-            start = index + 1;-        }-    }-    if start < data.len() {-        output.push(data[start..].to_vec());-    }-    output-}--#[derive(Clone, Copy)]-struct Op {-    tag: u8,-    bi: usize,-}--fn fallback_ops(a: &[Vec<u8>], b: &[Vec<u8>]) -> Vec<Op> {-    let mut prefix = 0;-    while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] {-        prefix += 1;-    }-    let mut suffix = 0;-    while suffix < a.len() - prefix-        && suffix < b.len() - prefix-        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]-    {-        suffix += 1;-    }-    let mut output = Vec::new();-    for index in 0..prefix {-        output.push(Op {-            tag: b' ',-            bi: index,-        });-    }-    for _index in prefix..a.len() - suffix {-        output.push(Op { tag: b'-', bi: 0 });-    }-    for index in prefix..b.len() - suffix {-        output.push(Op {-            tag: b'+',-            bi: index,-        });-    }-    for index in 0..suffix {-        output.push(Op {-            tag: b' ',-            bi: b.len() - suffix + index,-        });-    }-    output-}--fn build_ops(a: &[Vec<u8>], b: &[Vec<u8>]) -> Vec<Op> {-    let cells = (a.len() as u64 + 1) * (b.len() as u64 + 1);-    if cells > 8_000_000 {-        return fallback_ops(a, b);-    }-    let columns = b.len() + 1;-    let mut dp = vec![0u32; cells as usize];-    for i in 1..=a.len() {-        for j in 1..=b.len() {-            dp[i * columns + j] = if a[i - 1] == b[j - 1] {-                dp[(i - 1) * columns + j - 1] + 1-            } else {-                dp[(i - 1) * columns + j].max(dp[i * columns + j - 1])-            };-        }-    }-    let mut output = Vec::new();-    let mut i = a.len();-    let mut j = b.len();-    while i > 0 || j > 0 {-        if i > 0 && j > 0 && a[i - 1] == b[j - 1] {-            output.push(Op {-                tag: b' ',-                bi: j - 1,-            });-            i -= 1;-            j -= 1;-        } else if j > 0 && (i == 0 || dp[i * columns + j - 1] >= dp[(i - 1) * columns + j]) {-            output.push(Op {-                tag: b'+',-                bi: j - 1,-            });-            j -= 1;-        } else {-            output.push(Op { tag: b'-', bi: 0 });-            i -= 1;-        }-    }-    output.reverse();-    output-}--#[derive(Clone)]-struct Hunk {-    start: usize,-    end: usize,-    lines: Vec<Vec<u8>>,-}--fn diff_hunks(base: &[Vec<u8>], side: &[Vec<u8>]) -> Vec<Hunk> {-    let ops = build_ops(base, side);-    let mut output = Vec::new();-    let mut base_position = 0;-    let mut index = 0;-    while index < ops.len() {-        if ops[index].tag == b' ' {-            base_position += 1;-            index += 1;-            continue;-        }-        let mut hunk = Hunk {-            start: base_position,-            end: 0,-            lines: Vec::new(),-        };-        while index < ops.len() && ops[index].tag != b' ' {-            if ops[index].tag == b'-' {-                base_position += 1;-            } else {-                hunk.lines.push(side[ops[index].bi].clone());-            }-            index += 1;-        }-        hunk.end = base_position;-        output.push(hunk);-    }-    output-}--#[derive(Clone, Copy)]-pub struct MergeRange {-    pub base_start: usize,-    pub base_end: usize,-    pub ours_start: usize,-    pub ours_end: usize,-    pub theirs_start: usize,-    pub theirs_end: usize,-}--pub struct EditResult {-    pub conflicted: bool,-    pub data: Vec<u8>,-    pub ranges: Vec<MergeRange>,-}--fn append_lines(output: &mut Vec<u8>, lines: &[Vec<u8>], start: usize, end: usize) {-    for index in start..end.min(lines.len()) {-        output.extend_from_slice(&lines[index]);-    }-}--fn apply_hunks(-    output: &mut Vec<u8>,-    base: &[Vec<u8>],-    from: usize,-    to: usize,-    hunks: &[Hunk],-    first: usize,-    last: usize,-) {-    let mut position = from;-    for hunk in &hunks[first..last] {-        if hunk.start > position && hunk.start <= to {-            append_lines(output, base, position, hunk.start);-        }-        for line in &hunk.lines {-            output.extend_from_slice(line);-        }-        if hunk.end > position {-            position = hunk.end;-        }-    }-    if position < to {-        append_lines(output, base, position, to);-    }-}--fn map_position(hunks: &[Hunk], position: usize) -> usize {-    let mut output = position as i64;-    for hunk in hunks {-        if hunk.end <= position {-            output += hunk.lines.len() as i64 - (hunk.end - hunk.start) as i64;-        } else if hunk.start < position {-            output += hunk.lines.len() as i64 - (position - hunk.start) as i64;-            break;-        } else {-            break;-        }-    }-    output.max(0) as usize-}--fn same_hunks(ours: &[Hunk], of: usize, ol: usize, theirs: &[Hunk], tf: usize, tl: usize) -> bool {-    let mut left = Vec::new();-    let mut right = Vec::new();-    for hunk in &ours[of..ol] {-        for line in &hunk.lines {-            left.extend_from_slice(line);-        }-    }-    for hunk in &theirs[tf..tl] {-        for line in &hunk.lines {-            right.extend_from_slice(line);-        }-    }-    left == right-}--pub fn merge_lines(base: &[u8], ours: &[u8], theirs: &[u8], adjacent: bool) -> EditResult {-    let base = split_lines(base);-    let ours = split_lines(ours);-    let theirs = split_lines(theirs);-    let ours_hunks = diff_hunks(&base, &ours);-    let theirs_hunks = diff_hunks(&base, &theirs);-    let mut result = EditResult {-        conflicted: false,-        data: Vec::new(),-        ranges: Vec::new(),-    };-    let mut oi = 0;-    let mut ti = 0;-    let mut position = 0;-    while oi < ours_hunks.len() || ti < theirs_hunks.len() {-        let have_ours = oi < ours_hunks.len();-        let have_theirs = ti < theirs_hunks.len();-        let ours_start = if have_ours { ours_hunks[oi].start } else { 0 };-        let theirs_start = if have_theirs {-            theirs_hunks[ti].start-        } else {-            0-        };-        let take_ours = have_ours && (!have_theirs || ours_start <= theirs_start);-        let cluster_start = if take_ours { ours_start } else { theirs_start };-        let of = oi;-        let tf = ti;-        let mut o_last = of;-        let mut t_last = tf;-        let mut end = cluster_start;-        let mut seen_ours = false;-        let mut seen_theirs = false;-        loop {-            let mut progress = false;-            if o_last < ours_hunks.len() {-                let hunk = &ours_hunks[o_last];-                let include = if o_last == of {-                    hunk.start <= end-                } else if adjacent {-                    hunk.start < end-                } else {-                    hunk.start <= end-                };-                if include {-                    seen_ours = true;-                    o_last += 1;-                    end = end.max(hunk.end);-                    progress = true;-                }-            }-            if t_last < theirs_hunks.len() {-                let hunk = &theirs_hunks[t_last];-                let include = if t_last == tf {-                    hunk.start <= end-                } else if adjacent {-                    hunk.start < end-                } else {-                    hunk.start <= end-                };-                if include {-                    seen_theirs = true;-                    t_last += 1;-                    end = end.max(hunk.end);-                    progress = true;-                }-            }-            if !progress {-                break;-            }-        }-        end = end.max(cluster_start);-        if seen_ours && !seen_theirs {-            apply_hunks(-                &mut result.data,-                &base,-                position,-                end,-                &ours_hunks,-                of,-                o_last,-            );-            position = end;-            oi = o_last;-            ti = t_last;-        } else if seen_theirs && !seen_ours {-            apply_hunks(-                &mut result.data,-                &base,-                position,-                end,-                &theirs_hunks,-                tf,-                t_last,-            );-            position = end;-            oi = o_last;-            ti = t_last;-        } else {-            if same_hunks(&ours_hunks, of, o_last, &theirs_hunks, tf, t_last) {-                apply_hunks(-                    &mut result.data,-                    &base,-                    position,-                    end,-                    &ours_hunks,-                    of,-                    o_last,-                );-                position = end;-            } else {-                result.conflicted = true;-                apply_hunks(-                    &mut result.data,-                    &base,-                    position,-                    end,-                    &ours_hunks,-                    of,-                    o_last,-                );-                result.ranges.push(MergeRange {-                    base_start: cluster_start,-                    base_end: end,-                    ours_start: map_position(&ours_hunks, cluster_start),-                    ours_end: map_position(&ours_hunks, end),-                    theirs_start: map_position(&theirs_hunks, cluster_start),-                    theirs_end: map_position(&theirs_hunks, end),-                });-                position = end;-            }-            oi = o_last;-            ti = t_last;-        }-    }-    if position < base.len() {-        append_lines(&mut result.data, &base, position, base.len());-    }-    result-}--fn merge_blobs(-    store: &mut Store,-    writer: Option<&Writer>,-    base: Id,-    ours: Id,-    theirs: Id,-    adjacent: bool,-) -> Result<Option<EditResult>> {-    let Some(base) = read_blob_any(store, writer, base)? else {-        return Ok(None);-    };-    let Some(ours) = read_blob_any(store, writer, ours)? else {-        return Ok(None);-    };-    let Some(theirs) = read_blob_any(store, writer, theirs)? else {-        return Ok(None);-    };-    Ok(Some(merge_lines(&base, &ours, &theirs, adjacent)))-}--fn value_equal(left: &ConflictValue, right: &ConflictValue) -> bool {-    left.kind == right.kind && (left.kind == 0 || left.target == right.target)-}--fn flatten_values(-    store: &mut Store,-    values: &[ConflictValue],-    positive: bool,-    adds: &mut Vec<ConflictValue>,-    removes: &mut Vec<ConflictValue>,-    depth: usize,-) -> Result<()> {-    for value in values {-        if value.kind == KIND_CONFLICT-            && let Some(target) = value.target-            && depth < 64-            && let Some(body) = store.body(target, TYPE_CONFLICT)?-            && let Ok(child) = conflict::decode(&body)-        {-            flatten_values(store, &child.adds, positive, adds, removes, depth + 1)?;-            flatten_values(store, &child.removes, !positive, adds, removes, depth + 1)?;-            continue;-        }-        if positive {-            adds.push(value.clone());-        } else {-            removes.push(value.clone());-        }-    }-    Ok(())-}--pub fn simplify(-    store: &mut Store,-    adds: &[ConflictValue],-    removes: &[ConflictValue],-) -> Result<Conflict> {-    let mut flat_adds = Vec::new();-    let mut flat_removes = Vec::new();-    flatten_values(store, adds, true, &mut flat_adds, &mut flat_removes, 0)?;-    flatten_values(store, removes, false, &mut flat_adds, &mut flat_removes, 0)?;-    let mut used_adds = vec![false; flat_adds.len()];-    let mut used_removes = vec![false; flat_removes.len()];-    for (remove_index, remove) in flat_removes.iter().enumerate() {-        for (add_index, add) in flat_adds.iter().enumerate() {-            if !used_adds[add_index] && value_equal(add, remove) {-                used_adds[add_index] = true;-                used_removes[remove_index] = true;-                break;-            }-        }-    }-    Ok(Conflict {-        adds: flat_adds-            .into_iter()-            .enumerate()-            .filter(|(index, _)| !used_adds[*index])-            .map(|(_, value)| value)-            .collect(),-        removes: flat_removes-            .into_iter()-            .enumerate()-            .filter(|(index, _)| !used_removes[*index])-            .map(|(_, value)| value)-            .collect(),-    })-}--pub fn resolved(conflict: &Conflict) -> Option<ConflictValue> {-    let first = conflict.adds.first()?;-    if conflict.adds.iter().all(|value| value_equal(value, first)) {-        Some(first.clone())-    } else {-        None-    }-}--fn all_files(conflict: &Conflict) -> bool {-    conflict-        .adds-        .iter()-        .chain(conflict.removes.iter())-        .all(|value| matches!(value.kind, 0 | tree::KIND_FILE | tree::KIND_EXECUTABLE))-}--fn merge_mode(conflict: &Conflict) -> i32 {-    if conflict.adds.len() != 2 || conflict.removes.len() != 1 {-        return -1;-    }-    let mode = |value: &ConflictValue| -> i32 {-        if value.kind == 0 {-            return -1;-        }-        if value.kind == tree::KIND_EXECUTABLE {-            1-        } else {-            0-        }-    };-    let zero = mode(&conflict.adds[0]);-    let one = mode(&conflict.adds[1]);-    let remove = mode(&conflict.removes[0]);-    if zero < 0 || one < 0 {-        return -1;-    }-    if zero == one {-        return zero;-    }-    if remove >= 0 && zero == remove {-        return one;-    }-    if remove >= 0 && one == remove {-        return zero;-    }-    -1-}--fn merge_binary(repo: &Path, path: &[u8]) -> bool {-    let Some(data) = core::read_file_opt(&repo.join(".vnmergedata"), 0) else {-        return false;-    };-    let text = String::from_utf8_lossy(&data);-    let path = String::from_utf8_lossy(path);-    let mut result = false;-    for raw in text.lines() {-        let line = core::trim_str(raw);-        if line.is_empty() || line.starts_with('#') {-            continue;-        }-        let mut parts = line.split_whitespace();-        let Some(glob) = parts.next() else {-            continue;-        };-        let base = glob.rsplit('/').next().unwrap_or(glob);-        if !core::glob_match(glob, &path) && !(!glob.contains('/') && core::glob_match(base, &path))-        {-            continue;-        }-        for token in parts {-            if let Some(value) = token.strip_prefix("merge=") {-                if value == "binary" {-                    result = true;-                } else if value == "text" {-                    result = false;-                }-            }-        }-    }-    result-}--fn resolution_lookup(repo: &Path, body: &[u8]) -> Option<Id> {-    let key = crate::object::id::hash_bytes(body);-    let data = core::read_file_opt(-        &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),-        0,-    )?;-    if data.len() < 64 {-        return None;-    }-    Id::from_hex(std::str::from_utf8(&data[..64]).ok()?).ok()-}--fn resolution_record(repo: &Path, body: &[u8], blob: Id) {-    let key = crate::object::id::hash_bytes(body);-    let _ = core::write_file(-        &crate::store::layout::resolutions_dir(repo).join(Id(key).to_hex()),-        blob.to_hex().as_bytes(),-    );-}--type RenameMap = Vec<(Vec<u8>, Vec<u8>)>;--fn rename_lookup(map: &RenameMap, path: &[u8]) -> Option<Vec<u8>> {-    map.iter()-        .find(|(from, _)| from == path)-        .map(|(_, to)| to.clone())-}--fn rename_apply(map: &mut RenameMap, from: &[u8], to: &[u8]) {-    for (_, destination) in map.iter_mut() {-        if destination == from {-            *destination = to.to_vec();-            return;-        }-    }-    for (source, _) in map.iter_mut() {-        if source == from {-            return;-        }-    }-    map.push((from.to_vec(), to.to_vec()));-}--fn tree_of(store: &mut Store, commit: Id) -> Result<Option<Id>> {-    Ok(graph::load_commit(store, commit)?.map(|commit| commit.root_tree))-}--fn first_parent(store: &mut Store, commit: Id) -> Result<Option<Id>> {-    Ok(graph::load_commit(store, commit)?.and_then(|commit| commit.parents.first().copied()))-}--fn map_from(store: &mut Store, base: Id, side: Id) -> Result<RenameMap> {-    let mut map = RenameMap::new();-    if base == side {-        return Ok(map);-    }-    let mut chain = Vec::new();-    let mut current = side;-    let mut reached = false;-    for _ in 0..100_000 {-        if current == base {-            reached = true;-            break;-        }-        chain.push(current);-        let Some(parent) = first_parent(store, current)? else {-            break;-        };-        current = parent;-    }-    if !reached {-        return Ok(map);-    }-    for commit_id in chain.iter().rev() {-        let Some(loaded) = graph::load_commit(store, *commit_id)? else {-            continue;-        };-        if loaded.renames_state == commit::RENAMES_RECORDED {-            for rename in &loaded.renames {-                if rename.parent_index == 0 {-                    rename_apply(&mut map, &rename.from_path, &rename.to_path);-                }-            }-        } else {-            let Some(parent) = first_parent(store, *commit_id)? else {-                continue;-            };-            let old_tree = tree_of(store, parent)?;-            let new_tree = Some(loaded.root_tree);-            for rename in detect(store, None, old_tree, new_tree, 50, 0)? {-                rename_apply(&mut map, &rename.from_path, &rename.to_path);-            }-        }-    }-    Ok(map)-}--#[derive(Clone, Copy)]-struct TreeTerm {-    positive: bool,-    present: bool,-    id: Id,-}--#[derive(Clone)]-struct EntryTerm {-    positive: bool,-    present: bool,-    kind: u8,-    target: Option<Id>,-}--#[derive(Clone)]-struct OrigEntry {-    term: usize,-    path: Vec<u8>,-    kind: u8,-    target: Id,-}--#[derive(Clone)]-struct OutEntry {-    path: Vec<u8>,-    kind: u8,-    target: Id,-}--pub struct MergeOutcome {-    pub tree: Id,-    pub rerere: usize,-}--fn build_level(-    txn: &mut Txn,-    entries: &[OutEntry],-    start: usize,-    end: usize,-    prefix: usize,-) -> Result<Id> {-    let mut output = Vec::new();-    let mut index = start;-    while index < end {-        let entry = &entries[index];-        let cut = entry.path[prefix..]-            .iter()-            .position(|byte| *byte == b'/')-            .map(|offset| prefix + offset)-            .unwrap_or(entry.path.len());-        let name = entry.path[prefix..cut].to_vec();-        if cut == entry.path.len() {-            output.push(TreeEntry {-                name,-                kind: entry.kind,-                target: entry.target,-            });-            index += 1;-        } else {-            let mut next = index + 1;-            while next < end {-                let other = &entries[next];-                let other_cut = other.path[prefix..]-                    .iter()-                    .position(|byte| *byte == b'/')-                    .map(|offset| prefix + offset)-                    .unwrap_or(other.path.len());-                if other_cut != cut || other.path[prefix..cut] != entry.path[prefix..cut] {-                    break;-                }-                next += 1;-            }-            let child = build_level(txn, entries, index, next, cut + 1)?;-            output.push(TreeEntry {-                name,-                kind: KIND_SUBTREE,-                target: child,-            });-            index = next;-        }-    }-    add_tree(txn, &output)-}--fn build_from_entries(txn: &mut Txn, entries: &mut [OutEntry]) -> Result<Id> {-    if entries.is_empty() {-        return add_empty_tree(txn);-    }-    entries.sort_by(|left, right| left.path.cmp(&right.path));-    build_level(txn, entries, 0, entries.len(), 0)-}--fn build_subtree(txn: &mut Txn, canon: &[OrigEntry], term: usize, prefix: &[u8]) -> Result<Id> {-    let mut entries = Vec::new();-    for entry in canon {-        if entry.term == term && has_prefix(&entry.path, prefix) {-            entries.push(OutEntry {-                path: entry.path[prefix.len() + 1..].to_vec(),-                kind: entry.kind,-                target: entry.target,-            });-        }-    }-    build_from_entries(txn, &mut entries)-}--fn has_prefix(path: &[u8], prefix: &[u8]) -> bool {-    path.len() > prefix.len() && path.starts_with(prefix) && path[prefix.len()] == b'/'-}--fn merge_entry(-    repo: &Path,-    txn: &mut Txn,-    store: &mut Store,-    path: &[u8],-    terms: &[EntryTerm],-    adjacent: bool,-    rerere: &mut usize,-) -> Result<Option<OutEntry>> {-    let mut adds = Vec::new();-    let mut removes = Vec::new();-    for term in terms {-        let value = ConflictValue {-            kind: if term.present { term.kind } else { 0 },-            target: term.target,-        };-        if term.positive {-            adds.push(value);-        } else {-            removes.push(value);-        }-    }-    let sum = simplify(store, &adds, &removes)?;-    if let Some(value) = resolved(&sum) {-        if value.kind == 0 {-            return Ok(None);-        }-        return Ok(Some(OutEntry {-            path: path.to_vec(),-            kind: value.kind,-            target: value-                .target-                .ok_or_else(|| Error::new("missing conflict target"))?,-        }));-    }-    if all_files(&sum)-        && sum.adds.len() == 2-        && sum.removes.len() == 1-        && sum.adds[0].kind != 0-        && sum.adds[1].kind != 0-        && sum.removes[0].kind != 0-        && !merge_binary(repo, path)-        && let (Some(base), Some(ours), Some(theirs)) = (-            sum.removes[0].target,-            sum.adds[0].target,-            sum.adds[1].target,-        )-    {-        if let Some(merged) = merge_blobs(store, Some(txn.writer()), base, ours, theirs, adjacent)?-        {-            if !merged.conflicted {-                let blob = add_blob(txn, &merged.data);-                let mode = merge_mode(&sum);-                if mode >= 0 {-                    return Ok(Some(OutEntry {-                        path: path.to_vec(),-                        kind: if mode == 1 {-                            tree::KIND_EXECUTABLE-                        } else {-                            tree::KIND_FILE-                        },-                        target: blob,-                    }));-                }-            }-        }-    }-    let body = conflict::encode(&sum);-    if all_files(&sum)-        && let Some(blob) = resolution_lookup(repo, &body)-    {-        *rerere += 1;-        return Ok(Some(OutEntry {-            path: path.to_vec(),-            kind: tree::KIND_FILE,-            target: blob,-        }));-    }-    let id = txn.add_object(TYPE_CONFLICT, body);-    Ok(Some(OutEntry {-        path: path.to_vec(),-        kind: KIND_CONFLICT,-        target: id,-    }))-}--fn treemerge(-    repo: &Path,-    txn: &mut Txn,-    store: &mut Store,-    terms: &[TreeTerm],-    maps: &[RenameMap],-    adjacent: bool,-) -> Result<MergeOutcome> {-    let mut orig = Vec::new();-    for (term_index, term) in terms.iter().enumerate() {-        if !term.present {-            continue;-        }-        for entry in flatten_sorted(store, Some(txn.writer()), Some(term.id))? {-            orig.push(OrigEntry {-                term: term_index,-                path: entry.path,-                kind: entry.kind,-                target: entry.target,-            });-        }-    }-    let canonical_targets = |path: &[u8]| -> Vec<(usize, Vec<u8>)> {-        let mut output: Vec<(usize, Vec<u8>)> = Vec::new();-        for (index, map) in maps.iter().enumerate() {-            if let Some(destination) = rename_lookup(map, path) {-                if !output.iter().any(|(_, value)| value == &destination) {-                    output.push((index, destination));-                }-            }-        }-        output-    };-    let mut canon = Vec::new();-    let mut special = Vec::new();-    let mut consumed: Vec<Vec<u8>> = Vec::new();-    for entry in &orig {-        let targets = canonical_targets(&entry.path);-        if targets.len() > 1 && !special.contains(&entry.path) {-            special.push(entry.path.clone());-        }-        let canonical = if targets.len() == 1 {-            targets[0].1.clone()-        } else {-            entry.path.clone()-        };-        canon.push(OrigEntry {-            term: entry.term,-            path: canonical,-            kind: entry.kind,-            target: entry.target,-        });-    }-    let find_orig = |term: usize, path: &[u8]| -> Option<&OrigEntry> {-        orig.iter()-            .find(|entry| entry.term == term && entry.path == path)-    };-    let find_canon = |term: usize, path: &[u8]| -> Option<&OrigEntry> {-        canon-            .iter()-            .find(|entry| entry.term == term && entry.path == path)-    };-    let mut output = Vec::new();-    let mut rerere = 0;-    for path in &special {-        let targets = canonical_targets(path);-        let mut entries = Vec::new();-        for (term, destination) in &targets {-            let mut value = EntryTerm {-                positive: true,-                present: false,-                kind: 0,-                target: None,-            };-            if let Some(found) = find_orig(*term, destination) {-                value.present = true;-                value.kind = found.kind;-                value.target = Some(found.target);-            }-            entries.push(value);-            if !consumed.contains(destination) {-                consumed.push(destination.clone());-            }-        }-        if let Some(base_term) = terms.iter().position(|term| !term.positive) {-            let mut value = EntryTerm {-                positive: false,-                present: false,-                kind: 0,-                target: None,-            };-            if let Some(found) = find_orig(base_term, path) {-                value.present = true;-                value.kind = found.kind;-                value.target = Some(found.target);-            }-            entries.push(value);-        }-        if let Some(merged) = merge_entry(repo, txn, store, path, &entries, adjacent, &mut rerere)?-        {-            output.push(merged);-        }-        if !consumed.contains(path) {-            consumed.push(path.clone());-        }-    }-    let mut paths: Vec<Vec<u8>> = Vec::new();-    for entry in &canon {-        if !paths.contains(&entry.path) {-            paths.push(entry.path.clone());-        }-    }-    paths.sort();-    for path in paths {-        if consumed.contains(&path) {-            continue;-        }-        let mut any_exact = false;-        let mut any_children = false;-        for term in 0..terms.len() {-            if find_canon(term, &path).is_some() {-                any_exact = true;-            }-            if canon-                .iter()-                .any(|entry| entry.term == term && has_prefix(&entry.path, &path))-            {-                any_children = true;-            }-        }-        if !any_exact {-            continue;-        }-        let mixed = any_children;-        let mut entries = Vec::new();-        for term in 0..terms.len() {-            let mut value = EntryTerm {-                positive: terms[term].positive,-                present: false,-                kind: 0,-                target: None,-            };-            if let Some(exact) = find_canon(term, &path) {-                value.present = true;-                value.kind = exact.kind;-                value.target = Some(exact.target);-            } else if mixed-                && canon-                    .iter()-                    .any(|entry| entry.term == term && has_prefix(&entry.path, &path))-            {-                value.present = true;-                value.kind = KIND_SUBTREE;-                value.target = Some(build_subtree(txn, &canon, term, &path)?);-            }-            entries.push(value);-        }-        if let Some(merged) = merge_entry(repo, txn, store, &path, &entries, adjacent, &mut rerere)?-        {-            output.push(merged);-        }-        if mixed {-            for entry in &canon {-                if has_prefix(&entry.path, &path) && !consumed.contains(&entry.path) {-                    consumed.push(entry.path.clone());-                }-            }-        }-    }-    Ok(MergeOutcome {-        tree: build_from_entries(txn, &mut output)?,-        rerere,-    })-}--pub fn merge_bases(store: &mut Store, a: Id, b: Id) -> Result<Vec<Id>> {-    let left = graph::collect_commits(store, &[a])?;-    let right = graph::collect_commits(store, &[b])?;-    let common: Vec<Id> = left.into_iter().filter(|id| right.contains(id)).collect();-    let mut output = Vec::new();-    for candidate in &common {-        let mut dominated = false;-        for other in &common {-            if candidate == other {-                continue;-            }-            let descendants = graph::collect_commits(store, &[*candidate])?;-            if descendants.contains(other) {-                dominated = true;-                break;-            }-        }-        if !dominated {-            output.push(*candidate);-        }-    }-    Ok(output)-}--pub fn is_ancestor(store: &mut Store, ancestor: Id, descendant: Id) -> Result<bool> {-    if ancestor == descendant {-        return Ok(true);-    }-    Ok(graph::collect_commits(store, &[descendant])?.contains(&ancestor))-}--fn base_tree(-    repo: &Path,-    txn: &mut Txn,-    store: &mut Store,-    bases: &[Id],-    adjacent: bool,-) -> Result<Option<Id>> {-    if bases.is_empty() {-        return Ok(None);-    }-    if bases.len() == 1 {-        return tree_of(store, bases[0]);-    }-    let t0 = tree_of(store, bases[0])?;-    let t1 = tree_of(store, bases[1])?;-    let lcas = merge_bases(store, bases[0], bases[1])?;-    let mut terms = vec![-        TreeTerm {-            positive: true,-            present: t0.is_some(),-            id: t0.unwrap_or_default(),-        },-        TreeTerm {-            positive: true,-            present: t1.is_some(),-            id: t1.unwrap_or_default(),-        },-    ];-    if let Some(first) = lcas.first() {-        let tree = tree_of(store, *first)?;-        terms.push(TreeTerm {-            positive: false,-            present: tree.is_some(),-            id: tree.unwrap_or_default(),-        });-    } else {-        terms.push(TreeTerm {-            positive: false,-            present: false,-            id: Id::default(),-        });-    }-    Ok(Some(-        treemerge(-            repo,-            txn,-            store,-            &terms,-            &[RenameMap::new(), RenameMap::new(), RenameMap::new()],-            adjacent,-        )?-        .tree,-    ))-}--pub fn merge_many(-    repo: &Path,-    txn: &mut Txn,-    store: &mut Store,-    heads: &[Id],-    adjacent: bool,-) -> Result<MergeOutcome> {-    if heads.len() == 1 {-        let tree = tree_of(store, heads[0])?;-        return treemerge(-            repo,-            txn,-            store,-            &[TreeTerm {-                positive: true,-                present: tree.is_some(),-                id: tree.unwrap_or_default(),-            }],-            &[RenameMap::new()],-            adjacent,-        );-    }-    let mut terms = Vec::new();-    let mut maps = Vec::new();-    let map_base = if heads.len() > 1 {-        merge_bases(store, heads[0], heads[1])?.first().copied()-    } else {-        None-    };-    for head in heads {-        let tree = tree_of(store, *head)?;-        terms.push(TreeTerm {-            positive: true,-            present: tree.is_some(),-            id: tree.unwrap_or_default(),-        });-        maps.push(match map_base {-            Some(base) => map_from(store, base, *head)?,-            None => RenameMap::new(),-        });-    }-    for head in &heads[1..] {-        let bases = merge_bases(store, heads[0], *head)?;-        let tree = base_tree(repo, txn, store, &bases, adjacent)?;-        terms.push(TreeTerm {-            positive: false,-            present: tree.is_some(),-            id: tree.unwrap_or_default(),-        });-        maps.push(RenameMap::new());-    }-    treemerge(repo, txn, store, &terms, &maps, adjacent)-}--pub fn rewrite_tree(-    repo: &Path,-    txn: &mut Txn,-    store: &mut Store,-    old_commit: Id,-    commit_tree: Id,-    old_parents: &[Id],-    new_parents: &[Id],-    new_parent_trees: &[Id],-    adjacent: bool,-) -> Result<MergeOutcome> {-    let mut terms = vec![TreeTerm {-        positive: true,-        present: true,-        id: commit_tree,-    }];-    let mut maps = Vec::new();-    maps.push(if let Some(parent) = old_parents.first() {-        map_from(store, *parent, old_commit)?-    } else {-        RenameMap::new()-    });-    if old_parents.is_empty() {-        for tree in new_parent_trees {-            terms.push(TreeTerm {-                positive: true,-                present: true,-                id: *tree,-            });-            maps.push(RenameMap::new());-        }-        terms.push(TreeTerm {-            positive: false,-            present: false,-            id: Id::default(),-        });-        maps.push(RenameMap::new());-    } else {-        for (index, parent) in old_parents.iter().enumerate() {-            let old_tree = tree_of(store, *parent)?;-            let new_tree = new_parent_trees.get(index).copied().unwrap_or_default();-            terms.push(TreeTerm {-                positive: true,-                present: true,-                id: new_tree,-            });-            terms.push(TreeTerm {-                positive: false,-                present: old_tree.is_some(),-                id: old_tree.unwrap_or_default(),-            });-            maps.push(if let Some(new_parent) = new_parents.get(index) {-                map_from(store, *parent, *new_parent)?-            } else {-                RenameMap::new()-            });-            maps.push(RenameMap::new());-        }-    }-    treemerge(repo, txn, store, &terms, &maps, adjacent)-}--pub fn make_commit(-    txn: &mut Txn,-    store: &mut Store,-    repo: &Path,-    parents: &[Id],-    root: Id,-    change: [u8; 16],-    author: Sig,-    message: &str,-    renames_state: u8,-    extra: &[(Vec<u8>, Vec<u8>)],-) -> Result<Id> {-    let mut renames = Vec::new();-    if renames_state == commit::RENAMES_RECORDED {-        for (index, parent) in parents.iter().enumerate() {-            let parent_tree = tree_of(store, *parent)?;-            let detected = detect(-                store,-                Some(txn.writer()),-                parent_tree,-                Some(root),-                0,-                index as u64,-            )?;-            renames.extend(detected);-        }-    }-    let commit = Commit {-        version: 1,-        parents: parents.to_vec(),-        root_tree: root,-        change_id: change,-        author,-        committer: identity::signature(repo),-        message: message.as_bytes().to_vec(),-        renames_state,-        renames,-        extra: extra.to_vec(),-    };-    Ok(txn.add_object(TYPE_COMMIT, commit::encode(&commit)))-}--fn adjacent_config(root: &Path) -> bool {-    core::repo_config_value(root, "merge.adjacent").as_deref() == Some("merge")-}--pub fn conflict_kind_label(conflict: &Conflict) -> &'static str {-    if conflict-        .adds-        .iter()-        .chain(conflict.removes.iter())-        .any(|value| value.kind == KIND_SUBTREE)-    {-        return "tree";-    }-    if conflict-        .adds-        .iter()-        .chain(conflict.removes.iter())-        .any(|value| value.kind == 0)-    {-        return "delete/modify";-    }-    "text"-}--pub fn conflict_ranges(-    store: &mut Store,-    conflict: &Conflict,-    adjacent: bool,-) -> Result<Option<EditResult>> {-    if conflict.adds.len() != 2 || conflict.removes.len() != 1 {-        return Ok(None);-    }-    let ours = &conflict.adds[0];-    let theirs = &conflict.adds[1];-    let base = &conflict.removes[0];-    if ours.kind == 0 || theirs.kind == 0 || base.kind == 0 {-        return Ok(None);-    }-    if ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE || base.kind == KIND_SUBTREE {-        return Ok(None);-    }-    let (Some(base_id), Some(ours_id), Some(theirs_id)) =-        (base.target, ours.target, theirs.target)-    else {-        return Ok(None);-    };-    merge_blobs(-        store,-        None,-        base_id,-        ours_id,-        theirs_id,-        adjacent,-    )-}--pub fn edit_tree(-    txn: &mut Txn,-    store: &mut Store,-    tree_id: Id,-    path: &[u8],-    present: bool,-    kind: u8,-    target: Id,-) -> Result<Option<Id>> {-    edit_tree_into(txn, store, tree_id, path, present, kind, target, 0)-}--fn edit_tree_into(-    txn: &mut Txn,-    store: &mut Store,-    tree_id: Id,-    path: &[u8],-    present: bool,-    kind: u8,-    target: Id,-    depth: usize,-) -> Result<Option<Id>> {-    if depth > crate::object::MAX_TREE_DEPTH {-        return Ok(None);-    }-    let Some(body) = read_any(store, Some(txn.writer()), TYPE_TREE, tree_id)? else {-        return Ok(None);-    };-    let tree = tree::decode(&body)?;-    let cut = path-        .iter()-        .position(|byte| *byte == b'/')-        .unwrap_or(path.len());-    let name = &path[..cut];-    let mut entries = Vec::new();-    let mut found = false;-    for entry in tree.entries {-        if entry.name != name {-            entries.push(entry);-            continue;-        }-        found = true;-        if cut == path.len() {-            if present {-                entries.push(TreeEntry {-                    name: entry.name,-                    kind,-                    target,-                });-            }-        } else if entry.kind == KIND_SUBTREE {-            if let Some(child) = edit_tree_into(-                txn,-                store,-                entry.target,-                &path[cut + 1..],-                present,-                kind,-                target,-                depth + 1,-            )? {-                if !tree_empty(store, Some(txn.writer()), child)? {-                    entries.push(TreeEntry {-                        name: entry.name,-                        kind: KIND_SUBTREE,-                        target: child,-                    });-                }-            } else {-                entries.push(entry);-            }-        } else {-            entries.push(entry);-        }-    }-    if !found && cut == path.len() && present {-        entries.push(TreeEntry {-            name: name.to_vec(),-            kind,-            target,-        });-    }-    Ok(Some(add_tree(txn, &entries)?))-}--pub fn snapshot_run(root: &Path) -> Result<()> {-    snapshot::run(root)?;-    Ok(())-}--pub fn add_blob_data(txn: &mut Txn, data: &[u8]) -> Id {-    add_blob(txn, data)-}--pub fn object_id_of(kind: u8, body: &[u8]) -> Id {-    object_id(kind, body)-}--pub fn rename_from_map(map: &RenameMap, path: &[u8]) -> Option<Vec<u8>> {-    rename_lookup(map, path)-}--pub fn adjacent(root: &Path) -> bool {-    adjacent_config(root)-}--pub fn resolution_store(repo: &Path, body: &[u8], blob: Id) {-    resolution_record(repo, body, blob);-}--pub fn maps_empty() -> RenameMap {-    RenameMap::new()-}--pub fn apply_rename(map: &mut RenameMap, from: &[u8], to: &[u8]) {-    rename_apply(map, from, to);-}--pub fn first_parent_of(store: &mut Store, id: Id) -> Result<Option<Id>> {-    first_parent(store, id)-}--pub fn tree_of_commit(store: &mut Store, id: Id) -> Result<Option<Id>> {-    tree_of(store, id)-}--pub fn merge_binary_path(repo: &Path, path: &[u8]) -> bool {-    merge_binary(repo, path)-}--- a/veinsrs/src/merge/mod.rs+++ /dev/null@@ -1,2 +0,0 @@-pub mod engine;-pub mod rename;--- a/veinsrs/src/merge/rename.rs+++ /dev/null@@ -1,21 +0,0 @@-use crate::error::Result;-use crate::object::commit::Rename;-use crate::object::id::Id;-use crate::store::reader::Store;-use crate::store::writer::Writer;--pub fn detect(-    store: &mut Store,-    writer: &Writer,-    old_tree: Id,-    new_tree: Id,-) -> Result<Option<Vec<Rename>>> {-    Ok(Some(super::engine::detect(-        store,-        Some(writer),-        Some(old_tree),-        Some(new_tree),-        60,-        0,-    )?))-}--- a/veinsrs/src/object/blob.rs+++ /dev/null@@ -1,159 +0,0 @@-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::chunker::next_chunk;-use crate::object::id::{Id, object_id};-use crate::object::{-    INLINE_THRESHOLD, MAX_CHUNK_LEN, MAX_MANIFEST_ENTRIES, RawObject, TYPE_BLOB, TYPE_CHUNK,-};--#[derive(Clone, Copy, PartialEq, Eq)]-pub enum BlobForm {-    Inline,-    Leaf,-    Interior,-}--#[derive(Clone)]-pub struct BlobEntry {-    pub id: Id,-    pub length: u64,-}--#[derive(Clone)]-pub struct Blob {-    pub form: BlobForm,-    pub data: Vec<u8>,-    pub entries: Vec<BlobEntry>,-}--pub struct BlobBuild {-    pub root: Id,-    pub objects: Vec<RawObject>,-}--pub fn encode_inline(data: &[u8]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(data.len() + 8);-    writer.u8(0);-    writer.bytes(data);-    writer.into_vec()-}--pub fn decode(body: &[u8]) -> Result<Blob> {-    let mut reader = Reader::new(body);-    let form = match reader.u8()? {-        0 => BlobForm::Inline,-        1 => BlobForm::Leaf,-        2 => BlobForm::Interior,-        _ => return Err(Error::new("invalid blob form")),-    };-    if form == BlobForm::Inline {-        let data = reader.bytes(INLINE_THRESHOLD)?.to_vec();-        reader.finish()?;-        return Ok(Blob {-            form,-            data,-            entries: Vec::new(),-        });-    }-    let count = reader.varint()?;-    let count = usize::try_from(count).map_err(|_| Error::new("manifest too large"))?;-    if count == 0 || count > MAX_MANIFEST_ENTRIES {-        return Err(Error::new("invalid manifest entry count"));-    }-    let mut entries = Vec::with_capacity(count);-    let mut total = 0u64;-    for _ in 0..count {-        let id = reader.id()?;-        let length = reader.varint()?;-        if length == 0 {-            return Err(Error::new("invalid manifest entry length"));-        }-        if form == BlobForm::Leaf && length > MAX_CHUNK_LEN as u64 {-            return Err(Error::new("chunk exceeds maximum size"));-        }-        total = total-            .checked_add(length)-            .ok_or_else(|| Error::new("manifest length overflow"))?;-        entries.push(BlobEntry { id, length });-    }-    reader.finish()?;-    Ok(Blob {-        form,-        data: Vec::new(),-        entries,-    })-}--fn cut_after(id: Id, current_length: usize) -> bool {-    current_length >= MAX_MANIFEST_ENTRIES || (current_length >= 16 && id.0[0] == 0)-}--struct NodeRef {-    id: Id,-    length: u64,-}--pub fn build(data: &[u8]) -> BlobBuild {-    if data.len() <= INLINE_THRESHOLD {-        let body = encode_inline(data);-        let root = object_id(TYPE_BLOB, &body);-        return BlobBuild {-            root,-            objects: vec![RawObject::known(TYPE_BLOB, root, body)],-        };-    }--    let mut objects = Vec::new();-    let mut level = Vec::new();-    let mut offset = 0;-    while offset < data.len() {-        let length = next_chunk(&data[offset..]);-        let chunk = &data[offset..offset + length];-        let id = object_id(TYPE_CHUNK, chunk);-        objects.push(RawObject::known(TYPE_CHUNK, id, chunk.to_vec()));-        level.push(NodeRef {-            id,-            length: length as u64,-        });-        offset += length;-    }--    let mut leaf_level = true;-    let root = loop {-        let mut groups = Vec::new();-        let mut start = 0;-        for index in 0..level.len() {-            let current = index - start + 1;-            if cut_after(level[index].id, current) || index + 1 == level.len() {-                groups.push((start, current));-                start = index + 1;-            }-        }--        let mut next = Vec::with_capacity(groups.len());-        for (start, count) in groups {-            let mut writer = Writer::with_capacity(count * 40 + 8);-            writer.u8(if leaf_level { 1 } else { 2 });-            writer.varint(count as u64);-            let mut total = 0u64;-            for index in 0..count {-                let node = &level[start + index];-                writer.id(node.id);-                writer.varint(node.length);-                total += node.length;-            }-            let body = writer.into_vec();-            let id = object_id(TYPE_BLOB, &body);-            objects.push(RawObject::known(TYPE_BLOB, id, body));-            next.push(NodeRef { id, length: total });-        }--        if next.len() == 1 {-            break next[0].id;-        }-        level = next;-        leaf_level = false;-    };--    BlobBuild { root, objects }-}--- a/veinsrs/src/object/chunker.rs+++ /dev/null@@ -1,58 +0,0 @@-use std::sync::OnceLock;--static GEAR: OnceLock<[u64; 256]> = OnceLock::new();--fn build_gear() -> [u64; 256] {-    let mut table = [0u64; 256];-    for (index, slot) in table.iter_mut().enumerate() {-        let mut hasher = blake3::Hasher::new();-        hasher.update(b"veins/fastcdc/gear/v1");-        hasher.update(&[index as u8]);-        let digest = hasher.finalize();-        let mut value = [0u8; 8];-        value.copy_from_slice(&digest.as_bytes()[..8]);-        *slot = u64::from_le_bytes(value);-    }-    table-}--pub fn gear_table() -> &'static [u64; 256] {-    GEAR.get_or_init(build_gear)-}--pub fn next_chunk(data: &[u8]) -> usize {-    const MIN_SIZE: usize = 16 * 1024;-    const AVG_SIZE: usize = 64 * 1024;-    const MAX_SIZE: usize = 256 * 1024;-    const MASK_SMALL: u64 = 0x3ffff;-    const MASK_LARGE: u64 = 0x3fff;--    let length = data.len();-    if length <= MIN_SIZE {-        return length;-    }-    let limit = length.min(MAX_SIZE);-    let normal = AVG_SIZE.min(limit);-    let gear = gear_table();-    let mut fingerprint = 0u64;-    let mut index = MIN_SIZE;-    unsafe {-        while index < normal {-            let byte = *data.get_unchecked(index);-            fingerprint = (fingerprint >> 1).wrapping_add(gear[byte as usize]);-            if fingerprint & MASK_SMALL == 0 {-                return index + 1;-            }-            index += 1;-        }-        while index < limit {-            let byte = *data.get_unchecked(index);-            fingerprint = (fingerprint >> 1).wrapping_add(gear[byte as usize]);-            if fingerprint & MASK_LARGE == 0 {-                return index + 1;-            }-            index += 1;-        }-    }-    limit-}--- a/veinsrs/src/object/commit.rs+++ /dev/null@@ -1,197 +0,0 @@-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::id::Id;-use crate::object::{MAX_MESSAGE_LEN, MAX_NAME_LEN};--pub const RENAMES_UNKNOWN: u8 = 0;-pub const RENAMES_RECORDED: u8 = 1;--#[derive(Clone, Default)]-pub struct Sig {-    pub name: Vec<u8>,-    pub email: Vec<u8>,-    pub seconds: i64,-    pub tz_min: i16,-}--#[derive(Clone)]-pub struct Rename {-    pub parent_index: u64,-    pub kind: u8,-    pub from_path: Vec<u8>,-    pub to_path: Vec<u8>,-}--#[derive(Clone)]-pub struct Commit {-    pub version: u8,-    pub parents: Vec<Id>,-    pub root_tree: Id,-    pub change_id: [u8; 16],-    pub author: Sig,-    pub committer: Sig,-    pub message: Vec<u8>,-    pub renames_state: u8,-    pub renames: Vec<Rename>,-    pub extra: Vec<(Vec<u8>, Vec<u8>)>,-}--impl Commit {-    pub fn empty(change_id: [u8; 16], root_tree: Id, sig: Sig) -> Self {-        Self {-            version: 1,-            parents: Vec::new(),-            root_tree,-            change_id,-            author: sig.clone(),-            committer: sig,-            message: Vec::new(),-            renames_state: RENAMES_RECORDED,-            renames: Vec::new(),-            extra: Vec::new(),-        }-    }-}--fn write_sig(writer: &mut Writer, sig: &Sig) {-    writer.bytes(&sig.name);-    writer.bytes(&sig.email);-    writer.i64le(sig.seconds);-    writer.i16le(sig.tz_min);-}--fn read_sig(reader: &mut Reader<'_>) -> Result<Sig> {-    Ok(Sig {-        name: reader.bytes(MAX_NAME_LEN)?.to_vec(),-        email: reader.bytes(MAX_NAME_LEN)?.to_vec(),-        seconds: reader.i64le()?,-        tz_min: reader.i16le()?,-    })-}--pub fn encode(commit: &Commit) -> Vec<u8> {-    let mut writer = Writer::with_capacity(256);-    writer.u8(commit.version);-    writer.varint(commit.parents.len() as u64);-    for parent in &commit.parents {-        writer.id(*parent);-    }-    writer.id(commit.root_tree);-    writer.raw(&commit.change_id);-    write_sig(&mut writer, &commit.author);-    write_sig(&mut writer, &commit.committer);-    writer.bytes(&commit.message);-    writer.u8(commit.renames_state);-    writer.varint(commit.renames.len() as u64);-    for rename in &commit.renames {-        writer.varint(rename.parent_index);-        writer.u8(rename.kind);-        writer.bytes(&rename.from_path);-        writer.bytes(&rename.to_path);-    }-    writer.varint(commit.extra.len() as u64);-    for (key, value) in &commit.extra {-        writer.bytes(key);-        writer.bytes(value);-    }-    writer.into_vec()-}--pub fn decode(body: &[u8]) -> Result<Commit> {-    let mut reader = Reader::new(body);-    let version = reader.u8()?;-    if version != 1 {-        return Err(Error::new("unsupported commit version"));-    }-    let parent_count = reader.varint()?;-    let parent_count = usize::try_from(parent_count).map_err(|_| Error::new("too many parents"))?;-    if parent_count > 1024 {-        return Err(Error::new("too many parents"));-    }-    let mut parents = Vec::with_capacity(parent_count);-    for _ in 0..parent_count {-        parents.push(reader.id()?);-    }-    let root_tree = reader.id()?;-    let mut change_id = [0u8; 16];-    change_id.copy_from_slice(reader.raw(16)?);-    let author = read_sig(&mut reader)?;-    let committer = read_sig(&mut reader)?;-    let message = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();-    let renames_state = reader.u8()?;-    if renames_state > 1 {-        return Err(Error::new("invalid rename state"));-    }-    let rename_count = reader.varint()?;-    let rename_count = usize::try_from(rename_count).map_err(|_| Error::new("too many renames"))?;-    if rename_count > 1_000_000 {-        return Err(Error::new("rename limit exceeded"));-    }-    if renames_state == RENAMES_UNKNOWN && rename_count != 0 {-        return Err(Error::new("unknown rename state carries renames"));-    }-    let mut renames = Vec::with_capacity(rename_count);-    let mut previous_parent = 0u64;-    let mut previous_path: Option<Vec<u8>> = None;-    for _ in 0..rename_count {-        let parent_index = reader.varint()?;-        if parent_index >= parent_count as u64 {-            return Err(Error::new("rename parent index out of range"));-        }-        let kind = reader.u8()?;-        if kind > 1 {-            return Err(Error::new("invalid rename kind"));-        }-        let from_path = reader.bytes(crate::object::MAX_PATH_LEN)?.to_vec();-        let to_path = reader.bytes(crate::object::MAX_PATH_LEN)?.to_vec();-        if !crate::object::path::valid_path(&from_path)-            || !crate::object::path::valid_path(&to_path)-        {-            return Err(Error::new("invalid rename path"));-        }-        if let Some(previous) = &previous_path {-            if parent_index < previous_parent {-                return Err(Error::new("renames are not sorted"));-            }-            if parent_index == previous_parent && previous.as_slice() >= to_path.as_slice() {-                return Err(Error::new("renames are not sorted"));-            }-        }-        previous_parent = parent_index;-        previous_path = Some(to_path.clone());-        renames.push(Rename {-            parent_index,-            kind,-            from_path,-            to_path,-        });-    }-    let extra_count = reader.varint()?;-    let extra_count =-        usize::try_from(extra_count).map_err(|_| Error::new("too many extra headers"))?;-    if extra_count > 1024 {-        return Err(Error::new("too many extra headers"));-    }-    let mut extra = Vec::with_capacity(extra_count);-    for _ in 0..extra_count {-        let key = reader.bytes(MAX_NAME_LEN)?.to_vec();-        let value = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();-        if key.is_empty() {-            return Err(Error::new("empty extra header key"));-        }-        extra.push((key, value));-    }-    reader.finish()?;-    Ok(Commit {-        version,-        parents,-        root_tree,-        change_id,-        author,-        committer,-        message,-        renames_state,-        renames,-        extra,-    })-}--- a/veinsrs/src/object/conflict.rs+++ /dev/null@@ -1,94 +0,0 @@-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::id::Id;-use crate::object::tree::KIND_CONFLICT;--pub const MAX_CONFLICT_TERMS: usize = 64;--#[derive(Clone, PartialEq, Eq)]-pub struct ConflictValue {-    pub kind: u8,-    pub target: Option<Id>,-}--#[derive(Clone, Default)]-pub struct Conflict {-    pub adds: Vec<ConflictValue>,-    pub removes: Vec<ConflictValue>,-}--fn value_kind_valid(kind: u8) -> bool {-    kind == 0 || (1..=KIND_CONFLICT).contains(&kind)-}--fn read_value(reader: &mut Reader<'_>) -> Result<ConflictValue> {-    let kind = reader.u8()?;-    if !value_kind_valid(kind) {-        return Err(Error::new("invalid conflict value kind"));-    }-    if kind == 0 {-        return Ok(ConflictValue { kind, target: None });-    }-    Ok(ConflictValue {-        kind,-        target: Some(reader.id()?),-    })-}--fn read_values(reader: &mut Reader<'_>) -> Result<Vec<ConflictValue>> {-    let count = reader.varint()?;-    let count = usize::try_from(count).map_err(|_| Error::new("conflict term count overflow"))?;-    if count > MAX_CONFLICT_TERMS {-        return Err(Error::new("conflict term limit exceeded"));-    }-    let mut values = Vec::with_capacity(count);-    for _ in 0..count {-        values.push(read_value(reader)?);-    }-    Ok(values)-}--pub fn decode(body: &[u8]) -> Result<Conflict> {-    let mut reader = Reader::new(body);-    let adds = read_values(&mut reader)?;-    let removes = read_values(&mut reader)?;-    reader.finish()?;-    if removes.is_empty() {-        return Err(Error::new("conflict has no removed terms"));-    }-    if adds.len() != removes.len() + 1 {-        return Err(Error::new("conflict terms are unbalanced"));-    }-    if adds.len() + removes.len() > MAX_CONFLICT_TERMS {-        return Err(Error::new("conflict term limit exceeded"));-    }-    for add in &adds {-        if removes.contains(add) {-            return Err(Error::new("conflict terms are not simplified"));-        }-    }-    if adds.len() > 1 && adds.iter().all(|value| value == &adds[0]) {-        return Err(Error::new("conflict terms are not simplified"));-    }-    Ok(Conflict { adds, removes })-}--fn write_values(writer: &mut Writer, values: &[ConflictValue]) {-    writer.varint(values.len() as u64);-    for value in values {-        writer.u8(value.kind);-        if value.kind != 0-            && let Some(target) = value.target-        {-            writer.id(target);-        }-    }-}--pub fn encode(conflict: &Conflict) -> Vec<u8> {-    let mut writer =-        Writer::with_capacity((conflict.adds.len() + conflict.removes.len()) * 40 + 16);-    write_values(&mut writer, &conflict.adds);-    write_values(&mut writer, &conflict.removes);-    writer.into_vec()-}--- a/veinsrs/src/object/id.rs+++ /dev/null@@ -1,76 +0,0 @@-use crate::error::{Error, Result};--#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct Id(pub [u8; 32]);--const HEX: &[u8; 16] = b"0123456789abcdef";--impl Id {-    pub fn to_hex(self) -> String {-        let mut text = String::with_capacity(64);-        for byte in self.0 {-            text.push(HEX[(byte >> 4) as usize] as char);-            text.push(HEX[(byte & 0x0f) as usize] as char);-        }-        text-    }--    pub fn short(self) -> String {-        self.to_hex()[..12].to_string()-    }--    pub fn from_hex(text: &str) -> Result<Self> {-        if text.len() != 64 {-            return Err(Error::new("object id must contain 64 hex digits"));-        }-        let bytes = text.as_bytes();-        let mut value = [0u8; 32];-        for index in 0..32 {-            let high = hex_value(bytes[index * 2])?;-            let low = hex_value(bytes[index * 2 + 1])?;-            value[index] = (high << 4) | low;-        }-        Ok(Self(value))-    }-}--impl std::fmt::Debug for Id {-    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {-        formatter.write_str(&self.to_hex())-    }-}--fn hex_value(byte: u8) -> Result<u8> {-    match byte {-        b'0'..=b'9' => Ok(byte - b'0'),-        b'a'..=b'f' => Ok(byte - b'a' + 10),-        b'A'..=b'F' => Ok(byte - b'A' + 10),-        _ => Err(Error::new("invalid hex digit")),-    }-}--pub fn hash_bytes(data: &[u8]) -> [u8; 32] {-    *blake3::hash(data).as_bytes()-}--pub fn object_id(kind: u8, body: &[u8]) -> Id {-    let mut hasher = blake3::Hasher::new();-    hasher.update(b"veins/1\0");-    hasher.update(&[kind]);-    hasher.update(body);-    Id(*hasher.finalize().as_bytes())-}--pub fn prefix_matches(full: &str, prefix: &str) -> bool {-    if prefix.is_empty() || prefix.len() > full.len() {-        return false;-    }-    full.as_bytes()-        .iter()-        .zip(prefix.as_bytes())-        .all(|(left, right)| left.eq_ignore_ascii_case(right))-}--pub fn is_hex_prefix(text: &str) -> bool {-    (4..=64).contains(&text.len()) && text.bytes().all(|byte| byte.is_ascii_hexdigit())-}--- a/veinsrs/src/object/mod.rs+++ /dev/null@@ -1,51 +0,0 @@-pub mod blob;-pub mod chunker;-pub mod commit;-pub mod conflict;-pub mod id;-pub mod path;-pub mod tree;-pub mod view;--use id::Id;--pub const TYPE_CHUNK: u8 = 1;-pub const TYPE_BLOB: u8 = 2;-pub const TYPE_TREE: u8 = 3;-pub const TYPE_COMMIT: u8 = 4;-pub const TYPE_CONFLICT: u8 = 5;-pub const TYPE_OPERATION: u8 = 6;-pub const TYPE_VIEW: u8 = 7;--pub const INLINE_THRESHOLD: usize = 16 * 1024;-pub const MAX_CHUNK_LEN: usize = 256 * 1024;-pub const MAX_MANIFEST_ENTRIES: usize = 1024;-pub const MAX_TREE_ENTRIES: usize = 1_000_000;-pub const MAX_TREE_DEPTH: usize = 512;-pub const MAX_NAME_LEN: usize = 4096;-pub const MAX_PATH_LEN: usize = 65_536;-pub const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024;-pub const MAX_OBJECT_BODY: usize = 64 * 1024 * 1024;-pub const MAX_STORE_PACK_BYTES: u64 = 8 * 1024 * 1024 * 1024;--#[derive(Clone)]-pub struct RawObject {-    pub kind: u8,-    pub body: Vec<u8>,-    pub id: Id,-}--impl RawObject {-    pub fn new(kind: u8, body: Vec<u8>) -> Self {-        let id = id::object_id(kind, &body);-        Self { kind, body, id }-    }--    pub fn known(kind: u8, id: Id, body: Vec<u8>) -> Self {-        Self { kind, body, id }-    }-}--pub fn type_valid(kind: u8) -> bool {-    (TYPE_CHUNK..=TYPE_VIEW).contains(&kind)-}--- a/veinsrs/src/object/path.rs+++ /dev/null@@ -1,48 +0,0 @@-use crate::object::{MAX_NAME_LEN, MAX_PATH_LEN};--pub fn valid_component(component: &[u8]) -> bool {-    if component.is_empty() || component.len() > MAX_NAME_LEN {-        return false;-    }-    if component == b"." || component == b".." {-        return false;-    }-    component.iter().all(|byte| *byte != 0 && *byte != b'/')-}--pub fn valid_name(name: &[u8]) -> bool {-    valid_component(name) && !name.eq_ignore_ascii_case(b".veins")-}--pub fn valid_path(path: &[u8]) -> bool {-    if path.is_empty() || path.len() > MAX_PATH_LEN {-        return false;-    }-    if path[0] == b'/' {-        return false;-    }-    path.split(|byte| *byte == b'/').all(valid_component)-}--pub fn valid_checkout_component(component: &[u8]) -> bool {-    valid_name(component) && !component.eq_ignore_ascii_case(b".git")-}--pub fn valid_checkout_path(path: &[u8]) -> bool {-    if !valid_path(path) {-        return false;-    }-    path.split(|byte| *byte == b'/')-        .all(valid_checkout_component)-}--pub fn join(base: &[u8], name: &[u8]) -> Vec<u8> {-    if base.is_empty() {-        return name.to_vec();-    }-    let mut path = Vec::with_capacity(base.len() + 1 + name.len());-    path.extend_from_slice(base);-    path.push(b'/');-    path.extend_from_slice(name);-    path-}--- a/veinsrs/src/object/tree.rs+++ /dev/null@@ -1,188 +0,0 @@-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::id::Id;-use crate::object::path::valid_name;-use crate::object::{MAX_NAME_LEN, MAX_TREE_DEPTH, MAX_TREE_ENTRIES, TYPE_TREE};-use crate::store::reader::Store;--pub const KIND_FILE: u8 = 1;-pub const KIND_EXECUTABLE: u8 = 2;-pub const KIND_SYMLINK: u8 = 3;-pub const KIND_SUBTREE: u8 = 4;-pub const KIND_SUBMODULE: u8 = 5;-pub const KIND_CONFLICT: u8 = 6;-pub const KIND_MISSING: u8 = 0;--#[derive(Clone)]-pub struct TreeEntry {-    pub name: Vec<u8>,-    pub kind: u8,-    pub target: Id,-}--#[derive(Clone)]-pub struct Tree {-    pub entries: Vec<TreeEntry>,-}--#[derive(Clone)]-pub struct FlatEntry {-    pub path: Vec<u8>,-    pub kind: u8,-    pub target: Id,-}--fn valid_kind(kind: u8) -> bool {-    (KIND_FILE..=KIND_CONFLICT).contains(&kind)-}--fn valid_submodule_target(id: Id) -> bool {-    id.0[20..].iter().all(|byte| *byte == 0)-}--pub fn encode(entries: &[TreeEntry]) -> Result<Vec<u8>> {-    let mut writer = Writer::with_capacity(entries.len() * 48 + 8);-    writer.varint(entries.len() as u64);-    let mut previous: Option<&[u8]> = None;-    for entry in entries {-        if !valid_name(&entry.name) {-            return Err(Error::new("invalid tree entry name"));-        }-        if previous.is_some_and(|name| name >= entry.name.as_slice()) {-            return Err(Error::new("tree entries are not sorted"));-        }-        if !valid_kind(entry.kind) {-            return Err(Error::new("invalid tree entry kind"));-        }-        if entry.kind == KIND_SUBMODULE && !valid_submodule_target(entry.target) {-            return Err(Error::new("invalid submodule target"));-        }-        writer.bytes(&entry.name);-        writer.u8(entry.kind);-        writer.id(entry.target);-        previous = Some(&entry.name);-    }-    Ok(writer.into_vec())-}--pub fn decode(body: &[u8]) -> Result<Tree> {-    let mut reader = Reader::new(body);-    let count = reader.varint()?;-    let count = usize::try_from(count).map_err(|_| Error::new("tree too large"))?;-    if count > MAX_TREE_ENTRIES {-        return Err(Error::new("tree entry limit exceeded"));-    }-    let mut entries: Vec<TreeEntry> = Vec::with_capacity(count);-    for _ in 0..count {-        let name = reader.bytes(MAX_NAME_LEN)?;-        if !valid_name(name) {-            return Err(Error::new("invalid tree entry name"));-        }-        if entries-            .last()-            .is_some_and(|previous| previous.name.as_slice() >= name)-        {-            return Err(Error::new("tree entries are not sorted"));-        }-        let kind = reader.u8()?;-        if !valid_kind(kind) {-            return Err(Error::new("invalid tree entry kind"));-        }-        let target = reader.id()?;-        if kind == KIND_SUBMODULE && !valid_submodule_target(target) {-            return Err(Error::new("invalid submodule target"));-        }-        entries.push(TreeEntry {-            name: name.to_vec(),-            kind,-            target,-        });-    }-    reader.finish()?;-    Ok(Tree { entries })-}--/// Visit every entry of an encoded tree without copying names.-pub fn scan(body: &[u8], mut visit: impl FnMut(&[u8], u8, Id) -> Result<()>) -> Result<()> {-    let mut reader = Reader::new(body);-    let count = reader.varint()?;-    let count = usize::try_from(count).map_err(|_| Error::new("tree too large"))?;-    if count > MAX_TREE_ENTRIES {-        return Err(Error::new("tree entry limit exceeded"));-    }-    let mut previous: Option<&[u8]> = None;-    for _ in 0..count {-        let name = reader.bytes(MAX_NAME_LEN)?;-        if !valid_name(name) {-            return Err(Error::new("invalid tree entry name"));-        }-        if previous.is_some_and(|value| value >= name) {-            return Err(Error::new("tree entries are not sorted"));-        }-        let kind = reader.u8()?;-        if !valid_kind(kind) {-            return Err(Error::new("invalid tree entry kind"));-        }-        let target = reader.id()?;-        if kind == KIND_SUBMODULE && !valid_submodule_target(target) {-            return Err(Error::new("invalid submodule target"));-        }-        visit(name, kind, target)?;-        previous = Some(name);-    }-    reader.finish()-}--fn flatten_into(-    store: &mut Store,-    tree_id: Id,-    prefix: &mut Vec<u8>,-    output: &mut Vec<FlatEntry>,-    depth: usize,-) -> Result<()> {-    if depth > MAX_TREE_DEPTH {-        return Err(Error::new("tree nesting too deep"));-    }-    let body = store-        .body(tree_id, TYPE_TREE)?-        .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?;-    scan(&body, |name, kind, target| {-        let old_length = prefix.len();-        if !prefix.is_empty() {-            prefix.push(b'/');-        }-        prefix.extend_from_slice(name);-        if kind == KIND_SUBTREE {-            flatten_into(store, target, prefix, output, depth + 1)?;-        } else {-            output.push(FlatEntry {-                path: prefix.clone(),-                kind,-                target,-            });-        }-        prefix.truncate(old_length);-        Ok(())-    })-}--pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {-    let mut output = Vec::new();-    let mut prefix = Vec::new();-    flatten_into(store, tree_id, &mut prefix, &mut output, 0)?;-    output.sort_by(|left, right| left.path.cmp(&right.path));-    Ok(output)-}--pub fn find_flat<'a>(entries: &'a [FlatEntry], path: &[u8]) -> Option<&'a FlatEntry> {-    entries-        .binary_search_by(|entry| entry.path.as_slice().cmp(path))-        .ok()-        .map(|index| &entries[index])-}--pub fn find_entry(tree: &Tree, name: &[u8]) -> Option<usize> {-    tree.entries-        .binary_search_by(|entry| entry.name.as_slice().cmp(name))-        .ok()-}--- a/veinsrs/src/object/view.rs+++ /dev/null@@ -1,341 +0,0 @@-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::id::Id;-use crate::object::{MAX_MESSAGE_LEN, MAX_NAME_LEN};--#[derive(Clone, Default)]-pub struct TargetSet {-    pub adds: Vec<Option<Id>>,-    pub removes: Vec<Option<Id>>,-}--#[derive(Clone, Default)]-pub struct Bookmark {-    pub name: Vec<u8>,-    pub targets: TargetSet,-}--#[derive(Clone, Default)]-pub struct TagRef {-    pub name: Vec<u8>,-    pub target: Id,-}--#[derive(Clone, Default)]-pub struct RemoteRef {-    pub remote: Vec<u8>,-    pub name: Vec<u8>,-    pub target: Id,-}--#[derive(Clone, Default)]-pub struct WorkspaceRef {-    pub workspace: Vec<u8>,-    pub target: Id,-}--#[derive(Clone, Default)]-pub struct View {-    pub heads: Vec<Id>,-    pub bookmarks: Vec<Bookmark>,-    pub tags: Vec<TagRef>,-    pub remote_refs: Vec<RemoteRef>,-    pub working_copies: Vec<WorkspaceRef>,-}--#[derive(Clone, Default)]-pub struct TimeMs {-    pub millis: i64,-    pub tz_min: i16,-}--#[derive(Clone, Default)]-pub struct Operation {-    pub parents: Vec<Id>,-    pub view: Id,-    pub start: TimeMs,-    pub end: TimeMs,-    pub hostname: Vec<u8>,-    pub username: Vec<u8>,-    pub description: Vec<u8>,-    pub tags: Vec<(Vec<u8>, Vec<u8>)>,-}--fn read_opt_ids(reader: &mut Reader<'_>, maximum: usize) -> Result<Vec<Option<Id>>> {-    let count = reader.varint()?;-    let count = usize::try_from(count).map_err(|_| Error::new("list too large"))?;-    if count > maximum {-        return Err(Error::new("list limit exceeded"));-    }-    let mut ids = Vec::with_capacity(count);-    for _ in 0..count {-        ids.push(reader.opt_id()?);-    }-    Ok(ids)-}--fn write_opt_ids(writer: &mut Writer, ids: &[Option<Id>]) {-    writer.varint(ids.len() as u64);-    for id in ids {-        writer.opt_id(*id);-    }-}--fn read_target_set(reader: &mut Reader<'_>) -> Result<TargetSet> {-    let adds = read_opt_ids(reader, 64)?;-    let removes = read_opt_ids(reader, 64)?;-    if adds.is_empty() {-        return Err(Error::new("bookmark target set has no adds"));-    }-    if adds.len() != removes.len() + 1 {-        return Err(Error::new("bookmark target set is unbalanced"));-    }-    if adds.len() + removes.len() > 64 {-        return Err(Error::new("bookmark target set limit exceeded"));-    }-    for add in &adds {-        if opt_id_contains(&removes, *add) {-            return Err(Error::new("bookmark target set is not simplified"));-        }-    }-    if adds.len() > 1 && adds.iter().all(|id| id == &adds[0]) {-        return Err(Error::new("bookmark target set has duplicate adds"));-    }-    Ok(TargetSet { adds, removes })-}--fn write_target_set(writer: &mut Writer, targets: &TargetSet) {-    write_opt_ids(writer, &targets.adds);-    write_opt_ids(writer, &targets.removes);-}--fn read_name(reader: &mut Reader<'_>) -> Result<Vec<u8>> {-    let name = reader.bytes(MAX_NAME_LEN)?.to_vec();-    if name.is_empty() || name.contains(&0) {-        return Err(Error::new("invalid view name"));-    }-    Ok(name)-}--fn opt_id_contains(ids: &[Option<Id>], value: Option<Id>) -> bool {-    ids.contains(&value)-}--pub fn encode_view(view: &View) -> Vec<u8> {-    let mut writer = Writer::with_capacity(256);-    writer.varint(view.heads.len() as u64);-    for head in &view.heads {-        writer.id(*head);-    }-    writer.varint(view.bookmarks.len() as u64);-    for bookmark in &view.bookmarks {-        writer.bytes(&bookmark.name);-        write_target_set(&mut writer, &bookmark.targets);-    }-    writer.varint(view.tags.len() as u64);-    for tag in &view.tags {-        writer.bytes(&tag.name);-        writer.id(tag.target);-    }-    writer.varint(view.remote_refs.len() as u64);-    for reference in &view.remote_refs {-        writer.bytes(&reference.remote);-        writer.bytes(&reference.name);-        writer.id(reference.target);-    }-    writer.varint(view.working_copies.len() as u64);-    for workspace in &view.working_copies {-        writer.bytes(&workspace.workspace);-        writer.id(workspace.target);-    }-    writer.into_vec()-}--pub fn decode_view(body: &[u8]) -> Result<View> {-    let mut reader = Reader::new(body);-    let head_count = reader.varint()?;-    let head_count = usize::try_from(head_count).map_err(|_| Error::new("too many heads"))?;-    if head_count > 1_000_000 {-        return Err(Error::new("head limit exceeded"));-    }-    let mut heads = Vec::with_capacity(head_count);-    let mut previous: Option<Id> = None;-    for _ in 0..head_count {-        let id = reader.id()?;-        if previous.is_some_and(|value| value >= id) {-            return Err(Error::new("heads are not sorted"));-        }-        heads.push(id);-        previous = Some(id);-    }--    let bookmark_count = reader.varint()?;-    let bookmark_count =-        usize::try_from(bookmark_count).map_err(|_| Error::new("too many bookmarks"))?;-    if bookmark_count > 1_000_000 {-        return Err(Error::new("bookmark limit exceeded"));-    }-    let mut bookmarks = Vec::with_capacity(bookmark_count);-    let mut previous_name: Option<Vec<u8>> = None;-    for _ in 0..bookmark_count {-        let name = read_name(&mut reader)?;-        if previous_name.as_ref().is_some_and(|value| value >= &name) {-            return Err(Error::new("bookmarks are not sorted"));-        }-        let targets = read_target_set(&mut reader)?;-        bookmarks.push(Bookmark {-            name: name.clone(),-            targets,-        });-        previous_name = Some(name);-    }--    let tag_count = reader.varint()?;-    let tag_count = usize::try_from(tag_count).map_err(|_| Error::new("too many tags"))?;-    if tag_count > 1_000_000 {-        return Err(Error::new("tag limit exceeded"));-    }-    let mut tags = Vec::with_capacity(tag_count);-    let mut previous_name: Option<Vec<u8>> = None;-    for _ in 0..tag_count {-        let name = read_name(&mut reader)?;-        if previous_name.as_ref().is_some_and(|value| value >= &name) {-            return Err(Error::new("tags are not sorted"));-        }-        let target = reader.id()?;-        tags.push(TagRef {-            name: name.clone(),-            target,-        });-        previous_name = Some(name);-    }--    let remote_count = reader.varint()?;-    let remote_count =-        usize::try_from(remote_count).map_err(|_| Error::new("too many remote refs"))?;-    if remote_count > 1_000_000 {-        return Err(Error::new("remote ref limit exceeded"));-    }-    let mut remote_refs = Vec::with_capacity(remote_count);-    let mut previous_pair: Option<(Vec<u8>, Vec<u8>)> = None;-    for _ in 0..remote_count {-        let remote = read_name(&mut reader)?;-        let name = read_name(&mut reader)?;-        let key = (remote.clone(), name.clone());-        if previous_pair.as_ref().is_some_and(|value| value >= &key) {-            return Err(Error::new("remote refs are not sorted"));-        }-        let target = reader.id()?;-        remote_refs.push(RemoteRef {-            remote,-            name,-            target,-        });-        previous_pair = Some(key);-    }--    let workspace_count = reader.varint()?;-    let workspace_count =-        usize::try_from(workspace_count).map_err(|_| Error::new("too many workspaces"))?;-    if workspace_count > 1_000_000 {-        return Err(Error::new("workspace limit exceeded"));-    }-    let mut working_copies = Vec::with_capacity(workspace_count);-    let mut previous_name: Option<Vec<u8>> = None;-    for _ in 0..workspace_count {-        let workspace = read_name(&mut reader)?;-        if previous_name-            .as_ref()-            .is_some_and(|value| value >= &workspace)-        {-            return Err(Error::new("workspaces are not sorted"));-        }-        let target = reader.id()?;-        working_copies.push(WorkspaceRef {-            workspace: workspace.clone(),-            target,-        });-        previous_name = Some(workspace);-    }--    reader.finish()?;-    Ok(View {-        heads,-        bookmarks,-        tags,-        remote_refs,-        working_copies,-    })-}--pub fn encode_operation(operation: &Operation) -> Vec<u8> {-    let mut writer = Writer::with_capacity(256);-    writer.varint(operation.parents.len() as u64);-    for parent in &operation.parents {-        writer.id(*parent);-    }-    writer.id(operation.view);-    writer.i64le(operation.start.millis);-    writer.i16le(operation.start.tz_min);-    writer.i64le(operation.end.millis);-    writer.i16le(operation.end.tz_min);-    writer.bytes(&operation.hostname);-    writer.bytes(&operation.username);-    writer.bytes(&operation.description);-    writer.varint(operation.tags.len() as u64);-    for (key, value) in &operation.tags {-        writer.bytes(key);-        writer.bytes(value);-    }-    writer.into_vec()-}--pub fn decode_operation(body: &[u8]) -> Result<Operation> {-    let mut reader = Reader::new(body);-    let parent_count = reader.varint()?;-    let parent_count = usize::try_from(parent_count).map_err(|_| Error::new("too many parents"))?;-    if parent_count > 1024 {-        return Err(Error::new("parent limit exceeded"));-    }-    let mut parents = Vec::with_capacity(parent_count);-    for _ in 0..parent_count {-        parents.push(reader.id()?);-    }-    let view = reader.id()?;-    let start = TimeMs {-        millis: reader.i64le()?,-        tz_min: reader.i16le()?,-    };-    let end = TimeMs {-        millis: reader.i64le()?,-        tz_min: reader.i16le()?,-    };-    let hostname = reader.bytes(MAX_NAME_LEN)?.to_vec();-    let username = reader.bytes(MAX_NAME_LEN)?.to_vec();-    let description = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();-    let tag_count = reader.varint()?;-    let tag_count = usize::try_from(tag_count).map_err(|_| Error::new("too many tags"))?;-    if tag_count > 1024 {-        return Err(Error::new("tag limit exceeded"));-    }-    let mut tags = Vec::with_capacity(tag_count);-    for _ in 0..tag_count {-        let key = reader.bytes(MAX_NAME_LEN)?.to_vec();-        if key.is_empty() {-            return Err(Error::new("empty operation tag key"));-        }-        let value = reader.bytes(MAX_MESSAGE_LEN)?.to_vec();-        tags.push((key, value));-    }-    reader.finish()?;-    Ok(Operation {-        parents,-        view,-        start,-        end,-        hostname,-        username,-        description,-        tags,-    })-}--- a/veinsrs/src/platform.rs+++ /dev/null@@ -1,419 +0,0 @@-//! Small cross-platform shims for the OS primitives the store and worktree rely on.--use std::fs::{self, File, Metadata};-use std::io;-use std::path::{Path, PathBuf};-use std::process::Command;--#[cfg(unix)]-mod imp {-    use super::*;-    use std::ffi::OsString;-    use std::os::unix::ffi::{OsStrExt, OsStringExt};-    use std::os::unix::fs::{MetadataExt, PermissionsExt};-    use std::io::IsTerminal;--    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {-        PathBuf::from(OsString::from_vec(bytes.to_vec()))-    }--    pub fn path_to_bytes(path: &Path) -> Vec<u8> {-        path.as_os_str().as_bytes().to_vec()-    }--    pub fn path_display(path: &Path) -> String {-        String::from_utf8_lossy(path.as_os_str().as_bytes()).into_owned()-    }--    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {-        OsString::from_vec(bytes.to_vec())-    }--    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {-        value.into_vec()-    }--    pub fn mtime_ns(metadata: &Metadata) -> u64 {-        (metadata.mtime() as u64)-            .wrapping_mul(1_000_000_000)-            .wrapping_add(metadata.mtime_nsec() as u64)-    }--    pub fn inode(metadata: &Metadata) -> u64 {-        metadata.ino()-    }--    pub fn executable(metadata: &Metadata) -> bool {-        metadata.mode() & 0o111 != 0-    }--    pub fn permissions_mode(metadata: &Metadata) -> u32 {-        metadata.permissions().mode()-    }--    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {-        fs::set_permissions(path, fs::Permissions::from_mode(mode))-    }--    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {-        std::os::unix::fs::symlink(target, link)-    }--    pub fn sync_file(path: &Path) -> io::Result<()> {-        File::open(path)?.sync_all()-    }--    pub fn sync_directory(path: &Path) {-        if let Ok(directory) = File::open(path) {-            let _ = directory.sync_all();-        }-    }--    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {-        use std::os::unix::fs::FileExt;-        file.read_at(buffer, offset)-    }--    pub fn shell(command: &str) -> Command {-        let mut process = Command::new("sh");-        process.arg("-c").arg(command);-        process-    }--    pub fn shell_quote(value: &str) -> String {-        let mut output = String::from("'");-        for character in value.chars() {-            if character == '\'' {-                output.push_str("'\\''");-            } else {-                output.push(character);-            }-        }-        output.push('\'');-        output-    }--    pub fn default_editor() -> &'static str {-        "vi"-    }--    pub fn default_pager() -> &'static str {-        "less -R"-    }--    pub fn stdin_is_terminal() -> bool {-        io::stdin().is_terminal()-    }--    pub fn stdout_is_terminal() -> bool {-        io::stdout().is_terminal()-    }--    pub fn stderr_is_terminal() -> bool {-        io::stderr().is_terminal()-    }-}--#[cfg(windows)]-mod imp {-    use super::*;-    use std::ffi::OsString;--    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {-        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())-    }--    pub fn path_to_bytes(path: &Path) -> Vec<u8> {-        path.as_os_str().to_string_lossy().into_owned().into_bytes()-    }--    pub fn path_display(path: &Path) -> String {-        path.to_string_lossy().into_owned()-    }--    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {-        OsString::from(String::from_utf8_lossy(bytes).into_owned())-    }--    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {-        value.to_string_lossy().into_owned().into_bytes()-    }--    pub fn mtime_ns(metadata: &Metadata) -> u64 {-        use std::time::UNIX_EPOCH;-        metadata-            .modified()-            .ok()-            .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())-            .map(|elapsed| elapsed.as_nanos() as u64)-            .unwrap_or(0)-    }--    pub fn inode(_metadata: &Metadata) -> u64 {-        0-    }--    pub fn executable(_metadata: &Metadata) -> bool {-        false-    }--    pub fn permissions_mode(_metadata: &Metadata) -> u32 {-        0-    }--    pub fn set_mode(path: &Path, mode: u32) -> io::Result<()> {-        let mut permissions = fs::metadata(path)?.permissions();-        permissions.set_readonly(mode & 0o200 == 0);-        fs::set_permissions(path, permissions)-    }--    pub fn create_symlink(target: &Path, link: &Path) -> io::Result<()> {-        std::os::windows::fs::symlink_file(target, link)-            .or_else(|_| std::os::windows::fs::symlink_dir(target, link))-    }--    pub fn sync_file(path: &Path) -> io::Result<()> {-        File::open(path)?.sync_all()-    }--    pub fn sync_directory(_path: &Path) {}--    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {-        use std::os::windows::fs::FileExt;-        file.seek_read(buffer, offset)-    }--    pub fn shell(command: &str) -> Command {-        let mut process = Command::new("cmd");-        process.arg("/C").arg(command);-        process-    }--    pub fn shell_quote(value: &str) -> String {-        let mut output = String::from("\"");-        for character in value.chars() {-            if character == '"' {-                output.push_str("\\\"");-            } else {-                output.push(character);-            }-        }-        output.push('"');-        output-    }--    pub fn default_editor() -> &'static str {-        "notepad"-    }--    pub fn default_pager() -> &'static str {-        "more"-    }--    pub fn stdin_is_terminal() -> bool {-        use std::io::IsTerminal;-        io::stdin().is_terminal()-    }--    pub fn stdout_is_terminal() -> bool {-        use std::io::IsTerminal;-        io::stdout().is_terminal()-    }--    pub fn stderr_is_terminal() -> bool {-        use std::io::IsTerminal;-        io::stderr().is_terminal()-    }-}--#[cfg(not(any(unix, windows)))]-mod imp {-    use super::*;-    use std::ffi::OsString;--    pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {-        PathBuf::from(String::from_utf8_lossy(bytes).into_owned())-    }--    pub fn path_to_bytes(path: &Path) -> Vec<u8> {-        path.to_string_lossy().into_owned().into_bytes()-    }--    pub fn path_display(path: &Path) -> String {-        path.to_string_lossy().into_owned()-    }--    pub fn os_string_from_bytes(bytes: &[u8]) -> OsString {-        OsString::from(String::from_utf8_lossy(bytes).into_owned())-    }--    pub fn os_string_to_bytes(value: OsString) -> Vec<u8> {-        value.to_string_lossy().into_owned().into_bytes()-    }--    pub fn mtime_ns(_metadata: &Metadata) -> u64 {-        0-    }--    pub fn inode(_metadata: &Metadata) -> u64 {-        0-    }--    pub fn executable(_metadata: &Metadata) -> bool {-        false-    }--    pub fn permissions_mode(_metadata: &Metadata) -> u32 {-        0-    }--    pub fn set_mode(_path: &Path, _mode: u32) -> io::Result<()> {-        Ok(())-    }--    pub fn create_symlink(_target: &Path, _link: &Path) -> io::Result<()> {-        Err(io::Error::new(io::ErrorKind::Unsupported, "symlinks unavailable"))-    }--    pub fn sync_file(path: &Path) -> io::Result<()> {-        File::open(path)?.sync_all()-    }--    pub fn sync_directory(_path: &Path) {}--    pub fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {-        use std::io::{Read, Seek, SeekFrom};-        let mut file = file;-        file.seek(SeekFrom::Start(offset))?;-        file.read(buffer)-    }--    pub fn shell(command: &str) -> Command {-        let mut process = Command::new("sh");-        process.arg("-c").arg(command);-        process-    }--    pub fn shell_quote(value: &str) -> String {-        let mut output = String::from("'");-        for character in value.chars() {-            if character == '\'' {-                output.push_str("'\\''");-            } else {-                output.push(character);-            }-        }-        output.push('\'');-        output-    }--    pub fn default_editor() -> &'static str {-        "vi"-    }--    pub fn default_pager() -> &'static str {-        "less -R"-    }--    pub fn stdin_is_terminal() -> bool {-        false-    }--    pub fn stdout_is_terminal() -> bool {-        false-    }--    pub fn stderr_is_terminal() -> bool {-        false-    }-}--pub use imp::*;--/// Read-only memory mapping of a pack file, used to avoid one syscall per record.-///-/// Only Unix maps; other platforms return `None` and the store falls back to-/// positioned reads, matching the C++ implementation's behaviour.-pub struct Mapping {-    #[cfg(unix)]-    ptr: *mut libc::c_void,-    #[cfg(unix)]-    len: usize,-}--#[cfg(unix)]-unsafe impl Send for Mapping {}-#[cfg(unix)]-unsafe impl Sync for Mapping {}--impl Mapping {-    pub fn open(path: &Path) -> Option<Self> {-        #[cfg(unix)]-        {-            use std::os::unix::io::AsRawFd;-            let file = File::open(path).ok()?;-            let len = file.metadata().ok()?.len();-            if len == 0 || len as u128 > usize::MAX as u128 {-                return None;-            }-            let ptr = unsafe {-                libc::mmap(-                    std::ptr::null_mut(),-                    len as usize,-                    libc::PROT_READ,-                    libc::MAP_PRIVATE,-                    file.as_raw_fd(),-                    0,-                )-            };-            if ptr == libc::MAP_FAILED {-                return None;-            }-            Some(Mapping {-                ptr,-                len: len as usize,-            })-        }-        #[cfg(not(unix))]-        {-            let _ = path;-            None-        }-    }--    pub fn as_slice(&self) -> &[u8] {-        #[cfg(unix)]-        {-            unsafe { std::slice::from_raw_parts(self.ptr as *const u8, self.len) }-        }-        #[cfg(not(unix))]-        {-            &[]-        }-    }-}--#[cfg(unix)]-impl Drop for Mapping {-    fn drop(&mut self) {-        unsafe {-            libc::munmap(self.ptr, self.len);-        }-    }-}--/// Read only the requested window of a file into a fresh buffer.-pub fn read_range(file: &File, offset: u64, length: usize) -> Option<Vec<u8>> {-    let mut data = vec![0u8; length];-    let mut done = 0;-    while done < length {-        match read_at(file, &mut data[done..], offset + done as u64) {-            Ok(0) => break,-            Ok(count) => done += count,-            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,-            Err(_) => return None,-        }-    }-    data.truncate(done);-    Some(data)-}--- a/veinsrs/src/protocol/client.rs+++ /dev/null@@ -1,336 +0,0 @@-use std::path::Path;--use crate::crypto;-use crate::error::{Error, Result};-use crate::object::id::{Id, object_id};-use crate::store::reader::Store;-use crate::store::writer::Writer;-use crate::time;--use super::messages::{self, RefInfo, UpdateRef};-use super::wire::{self, Stream};--pub struct Client {-    stream: Stream,-    pub role: u8,-    pub authenticated: bool,-    pub fingerprint: Vec<u8>,-    pub error: String,-}--impl Client {-    pub fn connect(url: &str, key_name: &str, repo_name: &str, pin: &str) -> Result<Self> {-        let parsed = messages::parse_url(url).ok_or_else(|| Error::new("invalid remote URL"))?;-        let stream = if parsed.ssh {-            let remote = [-                "vn".to_string(),-                "serve".to_string(),-                "-stdio".to_string(),-                parsed.path.clone(),-            ]-            .iter()-            .map(|part| crate::core::shell_quote_arg(part))-            .collect::<Vec<_>>()-            .join(" ");-            let mut arguments = Vec::new();-            if parsed.port != 22 {-                arguments.push("-p".to_string());-                arguments.push(parsed.port.to_string());-            }-            arguments.push(parsed.host.clone());-            arguments.push(remote);-            Stream::spawn_program("ssh", &arguments)-                .map_err(|_| Error::new("cannot start the SSH transport"))?-        } else if parsed.tls {-            super::tls::connect(&parsed.host, parsed.port, pin)?-        } else {-            Stream::spawn(&[-                "serve".to_string(),-                "-stdio".to_string(),-                parsed.path.clone(),-            ])?-        };-        let binding = stream.binding().to_vec();-        let mut client = Self {-            stream,-            role: 0,-            authenticated: false,-            fingerprint: Vec::new(),-            error: String::new(),-        };-        let nonce = crypto::secure_random(32);-        if nonce.len() != 32 {-            return Err(Error::new("cannot generate a secure nonce"));-        }-        let hello = messages::Hello {-            min_version: messages::PROTOCOL_VERSION,-            max_version: messages::PROTOCOL_VERSION,-            capabilities: vec![-                "zstd-records".to_string(),-                "lazy-chunks".to_string(),-                "push".to_string(),-                "auth-ed25519".to_string(),-            ],-            repo: repo_name.to_string(),-            client_nonce: nonce.clone(),-        };-        if !client-            .stream-            .write_frame(wire::kind::HELLO, 1, &messages::encode_hello(&hello))-        {-            return Err(Error::new(-                "connection closed during the protocol handshake",-            ));-        }-        let frame = client-            .stream-            .read_frame()-            .ok_or_else(|| Error::new("server rejected the protocol handshake"))?;-        if frame.kind != wire::kind::HELLO_OK {-            return Err(Error::new("server rejected the protocol handshake"));-        }-        let hello_ok = messages::decode_hello_ok(&frame.payload)-            .ok_or_else(|| Error::new("server sent an invalid protocol handshake"))?;-        let selected = if key_name.is_empty() && hello_ok.auth_required != 0 {-            "default"-        } else {-            key_name-        };-        if !selected.is_empty()-            && let Some(key) = crypto::load_key(selected)-        {-            let message = messages::auth_message(-                hello_ok.version,-                repo_name,-                &hello_ok.server_nonce,-                &hello.client_nonce,-                &binding,-            );-            if let Some(signature) = crypto::ed25519_sign(&key.seed, &message) {-                let auth = messages::Auth {-                    public_key: key.public_key.to_vec(),-                    signature: signature.to_vec(),-                };-                if client-                    .stream-                    .write_frame(wire::kind::AUTH, 2, &messages::encode_auth(&auth))-                {-                    if let Some(reply) = client.stream.read_frame()-                        && reply.kind == wire::kind::AUTH_OK-                        && let Some(ok) = messages::decode_auth_ok(&reply.payload)-                    {-                        client.role = ok.role;-                        client.authenticated = true;-                        client.fingerprint = ok.fingerprint;-                    }-                }-            }-        }-        if hello_ok.auth_required != 0 && !client.authenticated {-            return Err(Error::new(if selected.is_empty() {-                "authentication required but no key is configured"-            } else {-                "authentication failed: the key is missing or not authorized"-            }));-        }-        Ok(client)-    }--    fn request(&mut self, kind: u8, payload: &[u8]) -> Result<wire::Frame> {-        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;-        if !self.stream.write_frame(kind, request_id, payload) {-            return Err(Error::new("connection closed while sending request"));-        }-        let frame = self-            .stream-            .read_frame()-            .ok_or_else(|| Error::new("connection closed while waiting for server response"))?;-        if frame.kind == wire::kind::ERROR {-            let code = wire::read_error(&frame.payload);-            let message = wire::error_message(&frame.payload);-            let mut text = format!("server error: {}", wire::error_code_name(code));-            if !message.is_empty() {-                text.push_str(": ");-                text.push_str(&message);-            }-            self.error = text.clone();-            return Err(Error::new(text));-        }-        Ok(frame)-    }--    pub fn list_refs(&mut self) -> Result<Vec<RefInfo>> {-        let frame = self.request(wire::kind::LIST_REFS, &[])?;-        if frame.kind != wire::kind::REFS {-            return Err(Error::new("unexpected response to ref listing"));-        }-        messages::decode_refs(&frame.payload).ok_or_else(|| Error::new("invalid ref listing"))-    }--    pub fn negotiate(&mut self, wants: &[Id], haves: &[Id]) -> Result<()> {-        let frame = self.request(-            wire::kind::NEGOTIATE,-            &messages::encode_negotiate(wants, haves),-        )?;-        if frame.kind != wire::kind::NEGOTIATE_OK {-            return Err(Error::new("unexpected response to negotiation"));-        }-        Ok(())-    }--    fn receive_stream(&mut self, repo: &Path) -> Result<()> {-        let mut hasher = blake3::Hasher::new();-        let mut writer = Writer::default();-        loop {-            let frame = self-                .stream-                .read_frame()-                .ok_or_else(|| Error::new("connection closed while receiving data"))?;-            if frame.kind == wire::kind::END {-                let digest = hasher.finalize();-                if frame.payload.as_slice() != digest.as_bytes() {-                    return Err(Error::new("server sent a corrupt transfer checksum"));-                }-                break;-            }-            if frame.kind == wire::kind::ERROR {-                let code = wire::read_error(&frame.payload);-                let message = wire::error_message(&frame.payload);-                return Err(Error::new(format!(-                    "server error: {}: {message}",-                    wire::error_code_name(code)-                )));-            }-            if frame.kind != wire::kind::RECORDS {-                return Err(Error::new("unexpected message while receiving data"));-            }-            hasher.update(&frame.payload);-            let record = wire::parse_record(&frame.payload)-                .ok_or_else(|| Error::new("invalid transfer record"))?;-            if object_id(record.kind, &record.body) != record.id {-                return Err(Error::new("transfer record hash mismatch"));-            }-            writer.add_known(record.kind, record.id, record.body);-        }-        if writer.finish(repo) != 0 {-            return Err(Error::new("cannot write incoming objects to the store"));-        }-        Ok(())-    }--    pub fn fetch_skeleton(&mut self, repo: &Path, wants: &[Id]) -> Result<()> {-        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;-        if !self.stream.write_frame(-            wire::kind::FETCH_SKELETON,-            request_id,-            &messages::encode_ids(wants),-        ) {-            return Err(Error::new("connection closed while requesting objects"));-        }-        self.receive_stream(repo)-    }--    pub fn get_chunks(&mut self, repo: &Path, ids: &[Id]) -> Result<()> {-        if ids.is_empty() {-            return Ok(());-        }-        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;-        if !self.stream.write_frame(-            wire::kind::GET_CHUNKS,-            request_id,-            &messages::encode_ids(ids),-        ) {-            return Err(Error::new("connection closed while requesting chunks"));-        }-        self.receive_stream(repo)-    }--    pub fn have_query(&mut self, ids: &[Id]) -> Result<Vec<u8>> {-        let frame = self.request(wire::kind::HAVE_QUERY, &messages::encode_ids(ids))?;-        if frame.kind != wire::kind::HAVE_BITMAP {-            return Err(Error::new("unexpected response to object query"));-        }-        messages::decode_bitmap(&frame.payload).ok_or_else(|| Error::new("invalid bitmap"))-    }--    pub fn push_objects(-        &mut self,-        repo: &Path,-        ids: &[Id],-        progress: Option<&crate::core::Progress>,-    ) -> Result<()> {-        let request_id = (time::now_millis() & 0x7fff_ffff) as u32;-        if !self-            .stream-            .write_frame(wire::kind::PUT_RECORDS, request_id, &[])-        {-            return Err(Error::new("connection closed while starting push"));-        }-        let mut store = Store::open(repo)?;-        let mut hasher = blake3::Hasher::new();-        for id in ids {-            let location = store-                .find(*id)-                .ok_or_else(|| Error::new(format!("local object is missing: {}", id.to_hex())))?;-            let body = store-                .body(*id, location.kind)?-                .ok_or_else(|| Error::new(format!("cannot read local object: {}", id.to_hex())))?;-            let record = wire::make_record(*id, location.kind, &body);-            hasher.update(&record);-            if !self-                .stream-                .write_frame(wire::kind::RECORDS, request_id, &record)-            {-                return Err(Error::new("connection closed while sending object"));-            }-            if let Some(progress) = progress {-                progress.advance(1);-            }-        }-        let digest = hasher.finalize();-        if !self-            .stream-            .write_frame(wire::kind::END, request_id, digest.as_bytes())-        {-            return Err(Error::new("connection closed while finishing push"));-        }-        let ack = self-            .stream-            .read_frame()-            .ok_or_else(|| Error::new("server closed the connection before acknowledging"))?;-        if ack.kind == wire::kind::END {-            return Ok(());-        }-        Err(Error::new("push was rejected"))-    }--    pub fn update_refs(&mut self, updates: &[UpdateRef]) -> Result<()> {-        let frame = self.request(-            wire::kind::UPDATE_REFS,-            &messages::encode_update_refs(updates),-        )?;-        if frame.kind != wire::kind::UPDATE_REFS_OK {-            return Err(Error::new("unexpected response to ref update"));-        }-        Ok(())-    }--    pub fn whoami(&mut self) -> Result<(u8, Vec<u8>)> {-        let frame = self.request(wire::kind::WHOAMI, &[])?;-        if frame.kind != wire::kind::WHOAMI_OK {-            return Err(Error::new("unexpected response to whoami"));-        }-        let mut reader = crate::encoding::Reader::new(&frame.payload);-        let role = reader.u8()?;-        let fingerprint = reader.bytes(64)?.to_vec();-        Ok((role, fingerprint))-    }--    pub fn has_connection(&self) -> bool {-        true-    }-}--pub fn same_id(left: Id, right: Id) -> bool {-    left == right-}--- a/veinsrs/src/protocol/messages.rs+++ /dev/null@@ -1,427 +0,0 @@-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::id::Id;--pub const PROTOCOL_VERSION: u16 = 1;--pub struct Hello {-    pub min_version: u16,-    pub max_version: u16,-    pub capabilities: Vec<String>,-    pub repo: String,-    pub client_nonce: Vec<u8>,-}--pub struct HelloOk {-    pub version: u16,-    pub capabilities: Vec<String>,-    pub server_nonce: Vec<u8>,-    pub auth_required: u8,-}--pub struct Auth {-    pub public_key: Vec<u8>,-    pub signature: Vec<u8>,-}--pub struct AuthOk {-    pub role: u8,-    pub fingerprint: Vec<u8>,-}--pub struct RefInfo {-    pub name: String,-    pub target: Id,-    pub change_id: String,-    pub kind: u8,-}--pub struct Negotiate {-    pub wants: Vec<Id>,-    pub haves: Vec<Id>,-}--#[derive(Clone)]-pub struct UpdateRef {-    pub name: String,-    pub expected: Option<Id>,-    pub target: Option<Id>,-}--fn put_u16(writer: &mut Writer, value: u16) {-    writer.u8((value >> 8) as u8);-    writer.u8(value as u8);-}--fn read_u16(reader: &mut Reader<'_>) -> Result<u16> {-    let high = reader.u8()?;-    let low = reader.u8()?;-    Ok(u16::from_be_bytes([high, low]))-}--fn encode_string_list(items: &[String]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(128);-    writer.varint(items.len() as u64);-    for item in items {-        writer.bytes(item.as_bytes());-    }-    writer.into_vec()-}--fn decode_string_list(reader: &mut Reader<'_>, maximum: usize) -> Result<Vec<String>> {-    let count = reader.varint()?;-    let count = usize::try_from(count).map_err(|_| Error::new("string list overflow"))?;-    if count > maximum {-        return Err(Error::new("string list limit exceeded"));-    }-    let mut output = Vec::with_capacity(count);-    for _ in 0..count {-        let value = reader.bytes(4096)?;-        output.push(String::from_utf8_lossy(value).into_owned());-    }-    Ok(output)-}--pub fn encode_hello(hello: &Hello) -> Vec<u8> {-    let mut writer = Writer::with_capacity(128);-    put_u16(&mut writer, hello.min_version);-    put_u16(&mut writer, hello.max_version);-    writer.raw(&encode_string_list(&hello.capabilities));-    writer.bytes(hello.repo.as_bytes());-    writer.bytes(&hello.client_nonce);-    writer.into_vec()-}--pub fn decode_hello(data: &[u8]) -> Option<Hello> {-    let mut reader = Reader::new(data);-    let min_version = read_u16(&mut reader).ok()?;-    let max_version = read_u16(&mut reader).ok()?;-    let capabilities = decode_string_list(&mut reader, 64).ok()?;-    let repo = reader.bytes(4096).ok()?;-    let nonce = reader.bytes(64).ok()?;-    reader.finish().ok()?;-    Some(Hello {-        min_version,-        max_version,-        capabilities,-        repo: String::from_utf8_lossy(repo).into_owned(),-        client_nonce: nonce.to_vec(),-    })-}--pub fn encode_hello_ok(hello: &HelloOk) -> Vec<u8> {-    let mut writer = Writer::with_capacity(128);-    put_u16(&mut writer, hello.version);-    writer.raw(&encode_string_list(&hello.capabilities));-    writer.bytes(&hello.server_nonce);-    writer.u8(hello.auth_required);-    writer.into_vec()-}--pub fn decode_hello_ok(data: &[u8]) -> Option<HelloOk> {-    let mut reader = Reader::new(data);-    let version = read_u16(&mut reader).ok()?;-    let capabilities = decode_string_list(&mut reader, 64).ok()?;-    let nonce = reader.bytes(64).ok()?;-    let auth_required = reader.u8().ok()?;-    reader.finish().ok()?;-    Some(HelloOk {-        version,-        capabilities,-        server_nonce: nonce.to_vec(),-        auth_required,-    })-}--pub fn encode_auth(auth: &Auth) -> Vec<u8> {-    let mut writer = Writer::with_capacity(128);-    writer.bytes(&auth.public_key);-    writer.bytes(&auth.signature);-    writer.into_vec()-}--pub fn decode_auth(data: &[u8]) -> Option<Auth> {-    let mut reader = Reader::new(data);-    let public_key = reader.bytes(64).ok()?;-    let signature = reader.bytes(128).ok()?;-    reader.finish().ok()?;-    Some(Auth {-        public_key: public_key.to_vec(),-        signature: signature.to_vec(),-    })-}--pub fn encode_auth_ok(auth: &AuthOk) -> Vec<u8> {-    let mut writer = Writer::with_capacity(64);-    writer.u8(auth.role);-    writer.bytes(&auth.fingerprint);-    writer.into_vec()-}--pub fn decode_auth_ok(data: &[u8]) -> Option<AuthOk> {-    let mut reader = Reader::new(data);-    let role = reader.u8().ok()?;-    let fingerprint = reader.bytes(64).ok()?;-    reader.finish().ok()?;-    Some(AuthOk {-        role,-        fingerprint: fingerprint.to_vec(),-    })-}--pub fn encode_refs(refs: &[RefInfo]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(256);-    writer.varint(refs.len() as u64);-    for reference in refs {-        writer.bytes(reference.name.as_bytes());-        writer.id(reference.target);-        writer.bytes(reference.change_id.as_bytes());-        writer.u8(reference.kind);-    }-    writer.into_vec()-}--pub fn decode_refs(data: &[u8]) -> Option<Vec<RefInfo>> {-    let mut reader = Reader::new(data);-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > 1_000_000 {-        return None;-    }-    let mut output = Vec::with_capacity(count);-    for _ in 0..count {-        let name = reader.bytes(4096).ok()?;-        let target = reader.id().ok()?;-        let change = reader.bytes(64).ok()?;-        let kind = reader.u8().ok()?;-        output.push(RefInfo {-            name: String::from_utf8_lossy(name).into_owned(),-            target,-            change_id: String::from_utf8_lossy(change).into_owned(),-            kind,-        });-    }-    reader.finish().ok()?;-    Some(output)-}--pub fn encode_ids(ids: &[Id]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(ids.len() * 32 + 8);-    writer.varint(ids.len() as u64);-    for id in ids {-        writer.id(*id);-    }-    writer.into_vec()-}--pub fn decode_ids(data: &[u8], maximum: usize) -> Option<Vec<Id>> {-    let mut reader = Reader::new(data);-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > maximum {-        return None;-    }-    let mut output = Vec::with_capacity(count);-    for _ in 0..count {-        output.push(reader.id().ok()?);-    }-    reader.finish().ok()?;-    Some(output)-}--pub fn encode_negotiate(wants: &[Id], haves: &[Id]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(256);-    writer.raw(&encode_ids(wants));-    writer.raw(&encode_ids(haves));-    writer.into_vec()-}--pub fn decode_negotiate(data: &[u8]) -> Option<Negotiate> {-    let mut reader = Reader::new(data);-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > 1_000_000 {-        return None;-    }-    let mut wants = Vec::with_capacity(count);-    for _ in 0..count {-        wants.push(reader.id().ok()?);-    }-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > 1_000_000 {-        return None;-    }-    let mut haves = Vec::with_capacity(count);-    for _ in 0..count {-        haves.push(reader.id().ok()?);-    }-    reader.finish().ok()?;-    Some(Negotiate { wants, haves })-}--pub fn encode_negotiate_ok(known: &[u8], enough: u8) -> Vec<u8> {-    let mut writer = Writer::with_capacity(known.len() + 16);-    writer.u8(enough);-    writer.varint(known.len() as u64);-    writer.raw(known);-    writer.into_vec()-}--pub fn decode_negotiate_ok(data: &[u8]) -> Option<Vec<u8>> {-    let mut reader = Reader::new(data);-    reader.u8().ok()?;-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > 1_000_000 {-        return None;-    }-    let bits = reader.raw(count).ok()?.to_vec();-    reader.finish().ok()?;-    Some(bits)-}--pub fn encode_bitmap(bits: &[u8]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(bits.len() + 8);-    writer.varint(bits.len() as u64);-    writer.raw(bits);-    writer.into_vec()-}--pub fn decode_bitmap(data: &[u8]) -> Option<Vec<u8>> {-    let mut reader = Reader::new(data);-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > 1_000_000 {-        return None;-    }-    let bits = reader.raw(count).ok()?.to_vec();-    reader.finish().ok()?;-    Some(bits)-}--pub fn encode_update_refs(updates: &[UpdateRef]) -> Vec<u8> {-    let mut writer = Writer::with_capacity(256);-    writer.varint(updates.len() as u64);-    for update in updates {-        writer.bytes(update.name.as_bytes());-        writer.opt_id(update.expected);-        writer.opt_id(update.target);-    }-    writer.into_vec()-}--pub fn decode_update_refs(data: &[u8]) -> Option<Vec<UpdateRef>> {-    let mut reader = Reader::new(data);-    let count = reader.varint().ok()?;-    let count = usize::try_from(count).ok()?;-    if count > 1_000_000 {-        return None;-    }-    let mut output = Vec::with_capacity(count);-    for _ in 0..count {-        let name = reader.bytes(4096).ok()?;-        let expected = reader.opt_id().ok()?;-        let target = reader.opt_id().ok()?;-        output.push(UpdateRef {-            name: String::from_utf8_lossy(name).into_owned(),-            expected,-            target,-        });-    }-    reader.finish().ok()?;-    Some(output)-}--pub fn auth_message(-    version: u16,-    repo: &str,-    server_nonce: &[u8],-    client_nonce: &[u8],-    binding: &[u8],-) -> Vec<u8> {-    let mut writer = Writer::with_capacity(128);-    writer.raw(b"veins-auth/1");-    writer.u8(0);-    put_u16(&mut writer, version);-    writer.bytes(repo.as_bytes());-    writer.raw(server_nonce);-    writer.raw(client_nonce);-    writer.raw(binding);-    writer.into_vec()-}--pub fn role_name(role: u8) -> &'static str {-    match role {-        2 => "write",-        1 => "read",-        _ => "anonymous",-    }-}--pub struct Url {-    pub tls: bool,-    pub ssh: bool,-    pub host: String,-    pub port: i32,-    pub path: String,-}--fn parse_authority(authority: &str, default_port: i32, strip_user: bool) -> (String, i32) {-    let authority = if strip_user {-        authority.rsplit('@').next().unwrap_or(authority)-    } else {-        authority-    };-    let mut host = authority.to_string();-    let mut port = default_port;-    if let Some((name, value)) = authority.rsplit_once(':') {-        host = name.to_string();-        if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {-            port = value.parse().unwrap_or(default_port);-        }-    }-    (host, port)-}--pub fn parse_url(url: &str) -> Option<Url> {-    if let Some(path) = url.strip_prefix("file://") {-        return Some(Url {-            tls: false,-            ssh: false,-            host: String::new(),-            port: 0,-            path: path.to_string(),-        });-    }-    if let Some(rest) = url.strip_prefix("ssh://") {-        let slash = rest.find('/')?;-        let (host, port) = parse_authority(&rest[..slash], 22, true);-        return Some(Url {-            tls: false,-            ssh: true,-            host,-            port,-            path: rest[slash + 1..].to_string(),-        });-    }-    if let Some(rest) = url.strip_prefix("veins://") {-        let slash = rest.find('/')?;-        let (host, port) = parse_authority(&rest[..slash], 7419, false);-        return Some(Url {-            tls: true,-            ssh: false,-            host,-            port,-            path: rest[slash + 1..].to_string(),-        });-    }-    None-}--pub fn url_repo_name(url: &str) -> String {-    match parse_url(url) {-        Some(parsed) if parsed.tls => parsed.path,-        _ => String::new(),-    }-}--- a/veinsrs/src/protocol/mod.rs+++ /dev/null@@ -1,4 +0,0 @@-pub mod client;-pub mod messages;-pub mod tls;-pub mod wire;--- a/veinsrs/src/protocol/tls.rs+++ /dev/null@@ -1,219 +0,0 @@-use std::net::TcpStream;-use std::sync::Arc;--use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};-use rustls::pki_types::pem::PemObject;-use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};-use rustls::{-    ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore, ServerConfig,-    ServerConnection, SignatureScheme, StreamOwned,-};--use crate::error::{Error, Result};--use super::wire::Stream;--const EXPORTER_LABEL: &[u8] = b"EXPORTER-veins-auth/1";--#[derive(Debug)]-struct PinnedVerifier {-    algorithms: rustls::crypto::WebPkiSupportedAlgorithms,-}--impl ServerCertVerifier for PinnedVerifier {-    fn verify_server_cert(-        &self,-        _end_entity: &CertificateDer<'_>,-        _intermediates: &[CertificateDer<'_>],-        _server_name: &ServerName<'_>,-        _ocsp_response: &[u8],-        _now: UnixTime,-    ) -> std::result::Result<ServerCertVerified, rustls::Error> {-        Ok(ServerCertVerified::assertion())-    }--    fn verify_tls12_signature(-        &self,-        message: &[u8],-        cert: &CertificateDer<'_>,-        signature: &DigitallySignedStruct,-    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {-        rustls::crypto::verify_tls12_signature(message, cert, signature, &self.algorithms)-    }--    fn verify_tls13_signature(-        &self,-        message: &[u8],-        cert: &CertificateDer<'_>,-        signature: &DigitallySignedStruct,-    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {-        rustls::crypto::verify_tls13_signature(message, cert, signature, &self.algorithms)-    }--    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {-        self.algorithms.supported_schemes()-    }-}--pub fn client_context(pinned: bool) -> Result<Arc<ClientConfig>> {-    let provider = rustls::crypto::ring::default_provider();-    let builder = ClientConfig::builder_with_provider(Arc::new(provider.clone()))-        .with_protocol_versions(&[&rustls::version::TLS13])-        .map_err(|error| Error::new(error.to_string()))?;-    let config = if pinned {-        builder-            .dangerous()-            .with_custom_certificate_verifier(Arc::new(PinnedVerifier {-                algorithms: provider.signature_verification_algorithms,-            }))-            .with_no_client_auth()-    } else {-        let mut roots = RootCertStore::empty();-        let native = rustls_native_certs::load_native_certs();-        roots.add_parsable_certificates(native.certs);-        if roots.is_empty() {-            roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());-        }-        if roots.is_empty() {-            return Err(Error::new("no trusted TLS roots are available"));-        }-        builder.with_root_certificates(roots).with_no_client_auth()-    };-    Ok(Arc::new(config))-}--pub fn connect(host: &str, port: i32, pin: &str) -> Result<Stream> {-    let pinned = !pin.is_empty();-    let config = client_context(pinned)?;-    let name =-        ServerName::try_from(host.to_string()).map_err(|_| Error::new("invalid TLS host name"))?;-    let mut socket = TcpStream::connect((host, port as u16))-        .map_err(|_| Error::new("cannot connect: host refused the connection or is unreachable"))?;-    let mut connection = ClientConnection::new(config, name)-        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;-    connection-        .complete_io(&mut socket)-        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;-    if pinned {-        let Some(certificate) = connection-            .peer_certificates()-            .and_then(|certs| certs.first())-        else {-            return Err(Error::new("TLS certificate pin mismatch"));-        };-        let digest = ring::digest::digest(&ring::digest::SHA256, certificate.as_ref());-        if !hex_equal(&hex_encode(digest.as_ref()), pin) {-            return Err(Error::new("TLS certificate pin mismatch"));-        }-    }-    let binding = exporter(&connection);-    Ok(Stream::from_duplex(-        Box::new(StreamOwned::new(connection, socket)),-        binding,-    ))-}--pub fn server_context(cert_path: &str, key_path: &str) -> Result<Arc<ServerConfig>> {-    let certificates: Vec<CertificateDer<'static>> = CertificateDer::pem_file_iter(cert_path)-        .map_err(|_| Error::new("cannot read the TLS certificate"))?-        .collect::<std::result::Result<_, _>>()-        .map_err(|_| Error::new("cannot parse the TLS certificate"))?;-    if certificates.is_empty() {-        return Err(Error::new("cannot parse the TLS certificate"));-    }-    let key = PrivateKeyDer::from_pem_file(key_path)-        .map_err(|_| Error::new("cannot read the TLS private key"))?;-    let provider = rustls::crypto::ring::default_provider();-    let config = ServerConfig::builder_with_provider(Arc::new(provider))-        .with_protocol_versions(&[&rustls::version::TLS13])-        .map_err(|error| Error::new(error.to_string()))?-        .with_no_client_auth()-        .with_single_cert(certificates, key)-        .map_err(|_| Error::new("cannot load the TLS certificate or key"))?;-    Ok(Arc::new(config))-}--pub fn accept(socket: TcpStream, config: Arc<ServerConfig>) -> Result<Stream> {-    let mut connection = ServerConnection::new(config)-        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;-    let mut socket = socket;-    connection-        .complete_io(&mut socket)-        .map_err(|error| Error::new(format!("TLS handshake failed: {error}")))?;-    let binding = exporter(&connection);-    Ok(Stream::from_duplex(-        Box::new(StreamOwned::new(connection, socket)),-        binding,-    ))-}--fn exporter(connection: &impl Exportable) -> Vec<u8> {-    let mut output = [0u8; 32];-    if connection-        .export_keying_material(&mut output, EXPORTER_LABEL, None)-        .is_ok()-    {-        output.to_vec()-    } else {-        Vec::new()-    }-}--trait Exportable {-    fn export_keying_material<T: AsMut<[u8]>>(-        &self,-        output: T,-        label: &[u8],-        context: Option<&[u8]>,-    ) -> std::result::Result<T, rustls::Error>;-}--impl Exportable for ClientConnection {-    fn export_keying_material<T: AsMut<[u8]>>(-        &self,-        output: T,-        label: &[u8],-        context: Option<&[u8]>,-    ) -> std::result::Result<T, rustls::Error> {-        ConnectionCommon::export_keying_material(self, output, label, context)-    }-}--impl Exportable for ServerConnection {-    fn export_keying_material<T: AsMut<[u8]>>(-        &self,-        output: T,-        label: &[u8],-        context: Option<&[u8]>,-    ) -> std::result::Result<T, rustls::Error> {-        ConnectionCommon::export_keying_material(self, output, label, context)-    }-}--use rustls::ConnectionCommon;--fn hex_encode(data: &[u8]) -> String {-    const DIGITS: &[u8; 16] = b"0123456789abcdef";-    let mut output = String::with_capacity(data.len() * 2);-    for byte in data {-        output.push(DIGITS[(byte >> 4) as usize] as char);-        output.push(DIGITS[(byte & 0x0f) as usize] as char);-    }-    output-}--fn hex_equal(left: &str, right: &str) -> bool {-    let mut left = left-        .bytes()-        .filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');-    let mut right = right-        .bytes()-        .filter(|byte| !byte.is_ascii_whitespace() && *byte != b':');-    loop {-        match (left.next(), right.next()) {-            (None, None) => return true,-            (Some(a), Some(b)) if a.to_ascii_lowercase() == b.to_ascii_lowercase() => {}-            _ => return false,-        }-    }-}--- a/veinsrs/src/protocol/wire.rs+++ /dev/null@@ -1,298 +0,0 @@-use std::io::{Read, Write};-use std::sync::{Arc, Mutex};--use crate::error::{Error, Result};-use crate::object::MAX_OBJECT_BODY;-use crate::object::id::Id;--pub const MAX_FRAME: usize = 16 * 1024 * 1024;--pub trait Duplex: Read + Write + Send {}-impl<T: Read + Write + Send> Duplex for T {}--struct SharedReader(Arc<Mutex<Box<dyn Duplex>>>);--impl Read for SharedReader {-    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {-        self.0-            .lock()-            .map_err(|_| std::io::Error::other("stream lock poisoned"))?-            .read(buffer)-    }-}--struct SharedWriter(Arc<Mutex<Box<dyn Duplex>>>);--impl Write for SharedWriter {-    fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {-        self.0-            .lock()-            .map_err(|_| std::io::Error::other("stream lock poisoned"))?-            .write(buffer)-    }--    fn flush(&mut self) -> std::io::Result<()> {-        self.0-            .lock()-            .map_err(|_| std::io::Error::other("stream lock poisoned"))?-            .flush()-    }-}--pub mod kind {-    pub const HELLO: u8 = 1;-    pub const HELLO_OK: u8 = 2;-    pub const AUTH: u8 = 3;-    pub const AUTH_OK: u8 = 4;-    pub const WHOAMI: u8 = 5;-    pub const WHOAMI_OK: u8 = 6;-    pub const LIST_REFS: u8 = 7;-    pub const REFS: u8 = 8;-    pub const NEGOTIATE: u8 = 9;-    pub const NEGOTIATE_OK: u8 = 10;-    pub const FETCH_SKELETON: u8 = 11;-    pub const GET_CHUNKS: u8 = 12;-    pub const HAVE_QUERY: u8 = 13;-    pub const HAVE_BITMAP: u8 = 14;-    pub const PUT_RECORDS: u8 = 15;-    pub const UPDATE_REFS: u8 = 16;-    pub const UPDATE_REFS_OK: u8 = 17;-    pub const RECORDS: u8 = 18;-    pub const END: u8 = 19;-    pub const ERROR: u8 = 20;-}--pub mod error_code {-    pub const UNSUPPORTED_VERSION: u8 = 1;-    pub const BAD_FRAME: u8 = 2;-    pub const NOT_FOUND: u8 = 3;-    pub const HASH_MISMATCH: u8 = 4;-    pub const NON_CANONICAL: u8 = 5;-    pub const MISSING_CLOSURE: u8 = 6;-    pub const REF_CONFLICT: u8 = 7;-    pub const REJECTED: u8 = 8;-    pub const INTERNAL: u8 = 9;-    pub const UNAUTHENTICATED: u8 = 10;-    pub const FORBIDDEN: u8 = 11;-    pub const AUTH_FAILED: u8 = 12;-    pub const QUOTA: u8 = 13;-    pub const TOO_LARGE: u8 = 14;-}--pub struct Frame {-    pub kind: u8,-    pub request_id: u32,-    pub payload: Vec<u8>,-}--pub struct Stream {-    reader: Box<dyn Read + Send>,-    writer: Box<dyn Write + Send>,-    child: Option<std::process::Child>,-    binding: Vec<u8>,-}--impl Stream {-    pub fn stdio() -> Self {-        Self {-            reader: Box::new(std::io::stdin()),-            writer: Box::new(std::io::stdout()),-            child: None,-            binding: Vec::new(),-        }-    }--    pub fn spawn(arguments: &[String]) -> Result<Self> {-        let executable = std::env::current_exe().map_err(Error::from)?;-        Self::spawn_program(&executable.to_string_lossy(), arguments)-    }--    pub fn spawn_program(program: &str, arguments: &[String]) -> Result<Self> {-        let mut child = std::process::Command::new(program)-            .args(arguments)-            .stdin(std::process::Stdio::piped())-            .stdout(std::process::Stdio::piped())-            .stderr(std::process::Stdio::inherit())-            .spawn()-            .map_err(Error::from)?;-        let stdin = child-            .stdin-            .take()-            .ok_or_else(|| Error::new("cannot open child stdin"))?;-        let stdout = child-            .stdout-            .take()-            .ok_or_else(|| Error::new("cannot open child stdout"))?;-        Ok(Self {-            reader: Box::new(stdout),-            writer: Box::new(stdin),-            child: Some(child),-            binding: Vec::new(),-        })-    }--    pub fn from_duplex(stream: Box<dyn Duplex>, binding: Vec<u8>) -> Self {-        let shared = Arc::new(Mutex::new(stream));-        Self {-            reader: Box::new(SharedReader(shared.clone())),-            writer: Box::new(SharedWriter(shared)),-            child: None,-            binding,-        }-    }--    pub fn binding(&self) -> &[u8] {-        &self.binding-    }--    fn read_exact(&mut self, buffer: &mut [u8]) -> bool {-        let mut done = 0;-        while done < buffer.len() {-            match self.reader.read(&mut buffer[done..]) {-                Ok(0) => return false,-                Ok(count) => done += count,-                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,-                Err(_) => return false,-            }-        }-        true-    }--    pub fn read_frame(&mut self) -> Option<Frame> {-        let mut head = [0u8; 4];-        if !self.read_exact(&mut head) {-            return None;-        }-        let length = u32::from_be_bytes(head) as usize;-        if !(5..=MAX_FRAME).contains(&length) {-            return None;-        }-        let mut body = vec![0u8; length];-        if !self.read_exact(&mut body) {-            return None;-        }-        Some(Frame {-            kind: body[0],-            request_id: u32::from_be_bytes([body[1], body[2], body[3], body[4]]),-            payload: body[5..].to_vec(),-        })-    }--    pub fn write_frame(&mut self, kind: u8, request_id: u32, payload: &[u8]) -> bool {-        if payload.len() > MAX_FRAME - 5 {-            return false;-        }-        let length = 5 + payload.len();-        let mut head = Vec::with_capacity(9 + payload.len());-        head.extend_from_slice(&(length as u32).to_be_bytes());-        head.push(kind);-        head.extend_from_slice(&request_id.to_be_bytes());-        head.extend_from_slice(payload);-        self.writer.write_all(&head).is_ok() && self.writer.flush().is_ok()-    }--    pub fn write_simple(&mut self, kind: u8, request_id: u32) -> bool {-        self.write_frame(kind, request_id, &[])-    }--    pub fn write_error(&mut self, request_id: u32, code: u8, message: &str) -> bool {-        let mut payload = Vec::with_capacity(message.len() + 8);-        payload.push(code);-        crate::encoding::Writer::varint_into(&mut payload, message.len() as u64);-        payload.extend_from_slice(message.as_bytes());-        self.write_frame(kind::ERROR, request_id, &payload)-    }-}--impl Drop for Stream {-    fn drop(&mut self) {-        if let Some(child) = &mut self.child {-            let _ = child.kill();-            let _ = child.wait();-        }-    }-}--pub fn read_error(payload: &[u8]) -> u8 {-    payload.first().copied().unwrap_or(error_code::INTERNAL)-}--pub fn error_message(payload: &[u8]) -> String {-    if payload.len() < 2 {-        return String::new();-    }-    let mut reader = crate::encoding::Reader::new(&payload[1..]);-    match reader.bytes(4096) {-        Ok(value) => String::from_utf8_lossy(value).into_owned(),-        Err(_) => String::new(),-    }-}--pub fn error_code_name(code: u8) -> &'static str {-    match code {-        error_code::UNSUPPORTED_VERSION => "unsupported protocol version",-        error_code::BAD_FRAME => "bad frame",-        error_code::NOT_FOUND => "object not found",-        error_code::HASH_MISMATCH => "hash mismatch",-        error_code::NON_CANONICAL => "non-canonical object",-        error_code::MISSING_CLOSURE => "missing object closure",-        error_code::REF_CONFLICT => "ref conflict",-        error_code::REJECTED => "request rejected",-        error_code::INTERNAL => "server internal error",-        error_code::UNAUTHENTICATED => "authentication required",-        error_code::FORBIDDEN => "permission denied",-        error_code::AUTH_FAILED => "authentication failed",-        error_code::QUOTA => "storage quota exceeded",-        error_code::TOO_LARGE => "push too large",-        _ => "unknown server error",-    }-}--pub struct IncomingRecord {-    pub id: Id,-    pub kind: u8,-    pub body: Vec<u8>,-}--pub fn parse_record(data: &[u8]) -> Option<IncomingRecord> {-    if data.len() < 35 {-        return None;-    }-    let mut reader = crate::encoding::Reader::new(data);-    let id = reader.id().ok()?;-    let kind = reader.u8().ok()?;-    let compression = reader.u8().ok()?;-    let raw_len = reader.varint().ok()?;-    let stored_len = reader.varint().ok()?;-    if raw_len == 0 || raw_len > MAX_OBJECT_BODY as u64 || stored_len > MAX_FRAME as u64 {-        return None;-    }-    let stored = reader.raw(stored_len as usize).ok()?;-    reader.finish().ok()?;-    if compression == 0 {-        if stored.len() as u64 != raw_len {-            return None;-        }-        return Some(IncomingRecord {-            id,-            kind,-            body: stored.to_vec(),-        });-    }-    let body = zstd::bulk::decompress(stored, raw_len as usize).ok()?;-    if body.len() as u64 != raw_len {-        return None;-    }-    Some(IncomingRecord { id, kind, body })-}--pub fn make_record(id: Id, kind: u8, body: &[u8]) -> Vec<u8> {-    let mut writer = crate::encoding::Writer::with_capacity(body.len() + 64);-    writer.id(id);-    writer.u8(kind);-    writer.u8(0);-    writer.varint(body.len() as u64);-    writer.varint(body.len() as u64);-    writer.raw(body);-    writer.into_vec()-}--- a/veinsrs/src/server.rs+++ /dev/null@@ -1,934 +0,0 @@-use std::path::{Path, PathBuf};-use std::sync::Arc;--use crate::crypto;-use crate::error::Result;-use crate::object::blob::{self, BlobForm};-use crate::object::conflict;-use crate::object::id::{Id, object_id};-use crate::object::tree::{self, KIND_SUBTREE};-use crate::object::view::{Bookmark, TagRef};-use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};-use crate::protocol::messages::{self, RefInfo};-use crate::protocol::wire::{self, Stream};-use crate::store::Txn;-use crate::store::graph;-use crate::store::ops;-use crate::store::reader::Store;-use crate::store::writer::Writer;--const MAX_CHUNKS: usize = 4096;-const MAX_PUSH_RECORDS: usize = 100_000;-const QUOTA_RESERVE: u64 = 1 << 20;-const DRAIN_BYTES: usize = 64 << 20;--struct Session {-    stream: Stream,-    repo: PathBuf,-    repo_present: bool,-    root: PathBuf,-    quota_bytes: u64,-    store: Store,-    access: crypto::Access,-    hello_repo: String,-    client_nonce: Vec<u8>,-    server_nonce: Vec<u8>,-    binding: Vec<u8>,-    version: u16,-    authed: bool,-    role: u8,-    public_key: Option<crypto::PublicKey>,-    fingerprint: Vec<u8>,-    haves: Vec<Id>,-}--fn deny(session: &mut Session, request_id: u32, write: bool) -> bool {-    let role = session.role;-    if write {-        if role == 2 {-            return false;-        }-        let code = if session.authed {-            wire::error_code::FORBIDDEN-        } else {-            wire::error_code::UNAUTHENTICATED-        };-        session-            .stream-            .write_error(request_id, code, "permission denied");-        return true;-    }-    if role == 1 || role == 2 {-        return false;-    }-    let code = if session.authed {-        wire::error_code::FORBIDDEN-    } else {-        wire::error_code::UNAUTHENTICATED-    };-    session-        .stream-        .write_error(request_id, code, "permission denied");-    true-}--fn change_id(store: &mut Store, id: Id) -> String {-    graph::load_commit(store, id)-        .ok()-        .flatten()-        .map(|commit| String::from_utf8_lossy(&commit.change_id).into_owned())-        .unwrap_or_default()-}--fn send_record(-    stream: &mut Stream,-    request_id: u32,-    hasher: &mut blake3::Hasher,-    id: Id,-    kind: u8,-    body: &[u8],-) -> bool {-    let record = wire::make_record(id, kind, body);-    hasher.update(&record);-    stream.write_frame(wire::kind::RECORDS, request_id, &record)-}--fn send_end(stream: &mut Stream, request_id: u32, hasher: &blake3::Hasher) -> bool {-    let digest = hasher.finalize();-    stream.write_frame(wire::kind::END, request_id, digest.as_bytes())-}--fn send_tree(-    session: &mut Session,-    request_id: u32,-    hasher: &mut blake3::Hasher,-    id: Id,-    seen: &mut std::collections::HashSet<Id>,-) -> Result<()> {-    if !seen.insert(id) {-        return Ok(());-    }-    let Some(body) = session.store.body(id, TYPE_TREE)? else {-        return Err(crate::error::Error::new("missing tree"));-    };-    if !send_record(-        &mut session.stream,-        request_id,-        hasher,-        id,-        TYPE_TREE,-        &body,-    ) {-        return Err(crate::error::Error::new("write failed"));-    }-    let tree = tree::decode(&body)?;-    for entry in tree.entries {-        match entry.kind {-            KIND_SUBTREE => send_tree(session, request_id, hasher, entry.target, seen)?,-            tree::KIND_CONFLICT => send_object(-                session,-                request_id,-                hasher,-                entry.target,-                TYPE_CONFLICT,-                seen,-            )?,-            tree::KIND_SUBMODULE => {}-            _ => send_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen)?,-        }-    }-    Ok(())-}--fn send_object(-    session: &mut Session,-    request_id: u32,-    hasher: &mut blake3::Hasher,-    id: Id,-    kind: u8,-    seen: &mut std::collections::HashSet<Id>,-) -> Result<()> {-    if !seen.insert(id) {-        return Ok(());-    }-    let Some(body) = session.store.body(id, kind)? else {-        return Err(crate::error::Error::new("missing object"));-    };-    if !send_record(&mut session.stream, request_id, hasher, id, kind, &body) {-        return Err(crate::error::Error::new("write failed"));-    }-    if kind == TYPE_BLOB {-        let blob = blob::decode(&body)?;-        match blob.form {-            BlobForm::Leaf => {-                for entry in blob.entries {-                    if seen.insert(entry.id)-                        && let Some(chunk) = session.store.body(entry.id, TYPE_CHUNK)?-                        && !send_record(-                            &mut session.stream,-                            request_id,-                            hasher,-                            entry.id,-                            TYPE_CHUNK,-                            &chunk,-                        )-                    {-                        return Err(crate::error::Error::new("write failed"));-                    }-                }-            }-            BlobForm::Interior => {-                for entry in blob.entries {-                    send_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen)?;-                }-            }-            BlobForm::Inline => {}-        }-    } else if kind == TYPE_CONFLICT {-        let value = conflict::decode(&body)?;-        for item in value.adds.iter().chain(value.removes.iter()) {-            let Some(target) = item.target else {-                continue;-            };-            let child = match item.kind {-                4 => TYPE_TREE,-                6 => TYPE_CONFLICT,-                0 | 5 => continue,-                _ => TYPE_BLOB,-            };-            if child == TYPE_TREE {-                send_tree(session, request_id, hasher, target, seen)?;-            } else {-                send_object(session, request_id, hasher, target, child, seen)?;-            }-        }-    }-    Ok(())-}--fn safe_repo_name(name: &str) -> bool {-    if name.is_empty() || name.len() > 4096 {-        return false;-    }-    if name.starts_with('/') || name.contains('\0') || name.contains('\\') {-        return false;-    }-    name.split('/').all(|part| part != "..")-}--fn dir_usage(path: &Path, depth: usize) -> u64 {-    if depth > 64 {-        return 0;-    }-    let Ok(entries) = std::fs::read_dir(path) else {-        return 0;-    };-    let mut total = 0u64;-    for entry in entries.flatten() {-        let Ok(metadata) = entry.metadata() else {-            continue;-        };-        if metadata.is_file() {-            total = total.saturating_add(metadata.len());-        } else if metadata.is_dir() {-            total = total.saturating_add(dir_usage(&entry.path(), depth + 1));-        }-    }-    total-}--fn handle_hello(session: &mut Session, frame: &wire::Frame) -> bool {-    let Some(hello) = messages::decode_hello(&frame.payload) else {-        session-            .stream-            .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad HELLO");-        return false;-    };-    if hello.min_version > messages::PROTOCOL_VERSION-        || hello.max_version < messages::PROTOCOL_VERSION-    {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::UNSUPPORTED_VERSION,-            "no common version",-        );-        return false;-    }-    session.hello_repo = hello.repo;-    session.client_nonce = hello.client_nonce;-    if !session.repo_present {-        if !safe_repo_name(&session.hello_repo) {-            session.stream.write_error(-                frame.request_id,-                wire::error_code::NOT_FOUND,-                "repository not found",-            );-            return false;-        }-        let candidate = session-            .root-            .join(crate::core::path_from_bytes(session.hello_repo.as_bytes()));-        match crate::store::layout::discover(&candidate) {-            Ok(found) => {-                session.repo = found;-                session.repo_present = true;-            }-            Err(_) => {-                session.stream.write_error(-                    frame.request_id,-                    wire::error_code::NOT_FOUND,-                    "repository not found",-                );-                return false;-            }-        }-    }-    if !session.repo_present || !session.repo.join(".veins").join("format").is_file() {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::NOT_FOUND,-            "repository not found",-        );-        return false;-    }-    session.access = crypto::load_access(&session.repo);-    session.role = crypto::role_for(&session.access, None);-    if !session.access.valid {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::INTERNAL,-            "invalid access file",-        );-        return false;-    }-    session.store = match Store::open(&session.repo) {-        Ok(store) => store,-        Err(_) => {-            session.stream.write_error(-                frame.request_id,-                wire::error_code::INTERNAL,-                "cannot open store",-            );-            return false;-        }-    };-    let nonce = crypto::secure_random(32);-    if nonce.len() != 32 {-        return false;-    }-    session.server_nonce = nonce.clone();-    let hello_ok = messages::HelloOk {-        version: messages::PROTOCOL_VERSION,-        capabilities: vec![-            "zstd-records".to_string(),-            "lazy-chunks".to_string(),-            "push".to_string(),-            "auth-ed25519".to_string(),-        ],-        server_nonce: session.server_nonce.clone(),-        auth_required: u8::from(!session.access.anonymous_read),-    };-    session.stream.write_frame(-        wire::kind::HELLO_OK,-        frame.request_id,-        &messages::encode_hello_ok(&hello_ok),-    )-}--fn handle_auth(session: &mut Session, frame: &wire::Frame) -> bool {-    let Some(auth) = messages::decode_auth(&frame.payload) else {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::AUTH_FAILED,-            "authentication failed",-        );-        return true;-    };-    let public_key = if auth.public_key.len() == 32 {-        let mut value = [0u8; 32];-        value.copy_from_slice(&auth.public_key);-        Some(value)-    } else {-        None-    };-    let role = crypto::role_for(&session.access, public_key.as_ref());-    let message = messages::auth_message(-        session.version,-        &session.hello_repo,-        &session.server_nonce,-        &session.client_nonce,-        &session.binding,-    );-    let valid = role != 255-        && public_key.is_some_and(|key| crypto::ed25519_verify(&key, &message, &auth.signature));-    if !valid {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::AUTH_FAILED,-            "authentication failed",-        );-        return true;-    }-    let Some(public_key) = public_key else {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::AUTH_FAILED,-            "authentication failed",-        );-        return true;-    };-    session.authed = true;-    session.role = role;-    session.public_key = Some(public_key);-    session.fingerprint = crypto::key_fingerprint_bytes(&public_key).to_vec();-    let ok = messages::AuthOk {-        role,-        fingerprint: session.fingerprint.clone(),-    };-    session.stream.write_frame(-        wire::kind::AUTH_OK,-        frame.request_id,-        &messages::encode_auth_ok(&ok),-    )-}--fn handle_list_refs(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, false) {-        return Ok(true);-    }-    let view = ops::current_view(&session.repo, &mut session.store)?.unwrap_or_default();-    let mut refs = Vec::new();-    for bookmark in &view.bookmarks {-        if bookmark.targets.adds.len() != 1 {-            continue;-        }-        let Some(target) = bookmark.targets.adds[0] else {-            continue;-        };-        refs.push(RefInfo {-            name: String::from_utf8_lossy(&bookmark.name).into_owned(),-            target,-            change_id: change_id(&mut session.store, target),-            kind: 0,-        });-    }-    for tag in &view.tags {-        refs.push(RefInfo {-            name: String::from_utf8_lossy(&tag.name).into_owned(),-            target: tag.target,-            change_id: change_id(&mut session.store, tag.target),-            kind: 1,-        });-    }-    Ok(session.stream.write_frame(-        wire::kind::REFS,-        frame.request_id,-        &messages::encode_refs(&refs),-    ))-}--fn handle_fetch(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, false) {-        return Ok(true);-    }-    let Some(wants) = messages::decode_ids(&frame.payload, 1_000_000) else {-        session-            .stream-            .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad wants");-        return Ok(true);-    };-    let commits = graph::collect_commits(&mut session.store, &wants)?;-    let mut exclude = std::collections::HashSet::new();-    for have in &session.haves {-        for id in graph::collect_commits(&mut session.store, &[*have])? {-            exclude.insert(id);-        }-    }-    let mut hasher = blake3::Hasher::new();-    let mut seen = std::collections::HashSet::new();-    for id in commits {-        if exclude.contains(&id) {-            continue;-        }-        let Some(commit) = graph::load_commit(&mut session.store, id)? else {-            continue;-        };-        let body = crate::object::commit::encode(&commit);-        if !send_record(-            &mut session.stream,-            frame.request_id,-            &mut hasher,-            id,-            TYPE_COMMIT,-            &body,-        ) {-            return Ok(false);-        }-        send_tree(-            session,-            frame.request_id,-            &mut hasher,-            commit.root_tree,-            &mut seen,-        )?;-    }-    send_end(&mut session.stream, frame.request_id, &hasher);-    Ok(true)-}--fn handle_get_chunks(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, false) {-        return Ok(true);-    }-    let Some(ids) = messages::decode_ids(&frame.payload, MAX_CHUNKS) else {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::BAD_FRAME,-            "bad chunk list",-        );-        return Ok(true);-    };-    let mut hasher = blake3::Hasher::new();-    for id in ids {-        let Some(body) = session.store.body(id, TYPE_CHUNK)? else {-            session.stream.write_error(-                frame.request_id,-                wire::error_code::NOT_FOUND,-                "chunk not found",-            );-            return Ok(true);-        };-        if !send_record(-            &mut session.stream,-            frame.request_id,-            &mut hasher,-            id,-            TYPE_CHUNK,-            &body,-        ) {-            return Ok(false);-        }-    }-    send_end(&mut session.stream, frame.request_id, &hasher);-    Ok(true)-}--fn handle_negotiate(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, false) {-        return Ok(true);-    }-    let Some(negotiate) = messages::decode_negotiate(&frame.payload) else {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::BAD_FRAME,-            "bad NEGOTIATE",-        );-        return Ok(true);-    };-    session.haves = negotiate.haves.clone();-    let mut known = Vec::with_capacity(negotiate.haves.len());-    let mut any = false;-    for id in negotiate.haves {-        let found = session.store.contains(id);-        known.push(u8::from(found));-        any |= found;-    }-    let enough = u8::from(session.haves.is_empty() || any);-    Ok(session.stream.write_frame(-        wire::kind::NEGOTIATE_OK,-        frame.request_id,-        &messages::encode_negotiate_ok(&known, enough),-    ))-}--fn handle_have_query(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, true) {-        return Ok(true);-    }-    let Some(ids) = messages::decode_ids(&frame.payload, 1_000_000) else {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::BAD_FRAME,-            "bad HAVE_QUERY",-        );-        return Ok(true);-    };-    let mut bits = Vec::with_capacity(ids.len());-    for id in ids {-        bits.push(u8::from(session.store.contains(id)));-    }-    Ok(session.stream.write_frame(-        wire::kind::HAVE_BITMAP,-        frame.request_id,-        &messages::encode_bitmap(&bits),-    ))-}--fn drain_push(session: &mut Session) -> bool {-    let mut total = 0usize;-    loop {-        let Some(frame) = session.stream.read_frame() else {-            return false;-        };-        if frame.kind == wire::kind::END {-            return true;-        }-        total = total.saturating_add(frame.payload.len());-        if total > DRAIN_BYTES {-            return false;-        }-    }-}--fn handle_put_records(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, true) {-        return Ok(true);-    }-    let mut limit = 0u64;-    if session.quota_bytes > 0 {-        let used = dir_usage(&session.repo, 0);-        if used.saturating_add(QUOTA_RESERVE) >= session.quota_bytes {-            drain_push(session);-            session.stream.write_error(-                frame.request_id,-                wire::error_code::QUOTA,-                "storage quota exceeded",-            );-            return Ok(true);-        }-        limit = session.quota_bytes - used - QUOTA_RESERVE;-    }-    let mut writer = Writer::default();-    writer.set_limit(limit);-    let mut hasher = blake3::Hasher::new();-    let mut records = 0usize;-    loop {-        let Some(incoming) = session.stream.read_frame() else {-            return Ok(false);-        };-        if incoming.kind == wire::kind::END {-            if incoming.payload.as_slice() != hasher.finalize().as_bytes() {-                session.stream.write_error(-                    frame.request_id,-                    wire::error_code::HASH_MISMATCH,-                    "transfer checksum mismatch",-                );-                return Ok(true);-            }-            break;-        }-        if incoming.kind != wire::kind::RECORDS {-            drain_push(session);-            session-                .stream-                .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record");-            return Ok(true);-        }-        records += 1;-        if records > MAX_PUSH_RECORDS {-            drain_push(session);-            session.stream.write_error(-                frame.request_id,-                wire::error_code::TOO_LARGE,-                "too many objects in one push",-            );-            return Ok(true);-        }-        hasher.update(&incoming.payload);-        let Some(record) = wire::parse_record(&incoming.payload) else {-            drain_push(session);-            session-                .stream-                .write_error(frame.request_id, wire::error_code::BAD_FRAME, "bad record");-            return Ok(true);-        };-        if object_id(record.kind, &record.body) != record.id {-            drain_push(session);-            session.stream.write_error(-                frame.request_id,-                wire::error_code::HASH_MISMATCH,-                "record hash mismatch",-            );-            return Ok(true);-        }-        writer.add_known(record.kind, record.id, record.body);-        if writer.quota_hit() {-            drain_push(session);-            session.stream.write_error(-                frame.request_id,-                wire::error_code::QUOTA,-                "storage quota exceeded",-            );-            return Ok(true);-        }-    }-    let status = writer.finish(&session.repo);-    if status != 0 {-        session.stream.write_error(-            frame.request_id,-            if status == 2 {-                wire::error_code::QUOTA-            } else {-                wire::error_code::INTERNAL-            },-            if status == 2 {-                "storage quota exceeded"-            } else {-                "pack write failed"-            },-        );-        return Ok(true);-    }-    session.store.refresh()?;-    Ok(session-        .stream-        .write_frame(wire::kind::END, frame.request_id, &[]))-}--fn ref_matches(view: &crate::object::view::View, name: &str, expected: Option<Id>) -> bool {-    let current = if let Some(tag) = name.strip_prefix("refs/tags/") {-        ops::find_tag(view, tag.as_bytes()).map(|index| view.tags[index].target)-    } else {-        ops::find_bookmark(view, name.as_bytes())-            .and_then(|index| {-                view.bookmarks[index]-                    .targets-                    .adds-                    .first()-                    .copied()-                    .flatten()-            })-            .or_else(|| ops::find_tag(view, name.as_bytes()).map(|index| view.tags[index].target))-    };-    match expected {-        None => current.is_none(),-        Some(expected) => current == Some(expected),-    }-}--fn apply_ref(view: &mut crate::object::view::View, name: &str, target: Option<Id>) {-    if let Some(tag) = name.strip_prefix("refs/tags/") {-        match (ops::find_tag(view, tag.as_bytes()), target) {-            (Some(index), Some(target)) => view.tags[index].target = target,-            (Some(index), None) => {-                view.tags.remove(index);-            }-            (None, Some(target)) => view.tags.push(TagRef {-                name: tag.as_bytes().to_vec(),-                target,-            }),-            (None, None) => {}-        }-        return;-    }-    if let Some(target) = target {-        if let Some(index) = ops::find_bookmark(view, name.as_bytes()) {-            view.bookmarks[index].targets.adds = vec![Some(target)];-            view.bookmarks[index].targets.removes.clear();-        } else if let Some(index) = ops::find_tag(view, name.as_bytes()) {-            view.tags[index].target = target;-        } else {-            view.bookmarks.push(Bookmark {-                name: name.as_bytes().to_vec(),-                targets: crate::object::view::TargetSet {-                    adds: vec![Some(target)],-                    removes: Vec::new(),-                },-            });-        }-    } else {-        if let Some(index) = ops::find_bookmark(view, name.as_bytes()) {-            view.bookmarks.remove(index);-        }-        if let Some(index) = ops::find_tag(view, name.as_bytes()) {-            view.tags.remove(index);-        }-    }-}--fn valid_ref_name(name: &str) -> bool {-    if name.is_empty()-        || name.len() > crate::object::MAX_NAME_LEN-        || matches!(name, "@" | "." | "..")-    {-        return false;-    }-    if matches!(name.as_bytes()[0], b'-' | b'/')-        || matches!(name.as_bytes()[name.len() - 1], b'/' | b'.')-    {-        return false;-    }-    if name.contains("..") || name.contains("@{") || name.contains("//") || name.ends_with(".lock")-    {-        return false;-    }-    name.bytes().all(|byte| {-        byte >= 32-            && byte != 127-            && byte != b' '-            && !matches!(byte, b'~' | b'^' | b':' | b'?' | b'*' | b'[' | b'\\')-    })-}--fn handle_update_refs(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    if deny(session, frame.request_id, true) {-        return Ok(true);-    }-    let Some(updates) = messages::decode_update_refs(&frame.payload) else {-        session.stream.write_error(-            frame.request_id,-            wire::error_code::BAD_FRAME,-            "bad UPDATE_REFS",-        );-        return Ok(true);-    };-    let mut txn = Txn::begin(&session.repo, &mut session.store)?;-    for update in &updates {-        let ref_name = update-            .name-            .strip_prefix("refs/tags/")-            .unwrap_or(&update.name);-        if update.target.is_some() && !valid_ref_name(ref_name) {-            session.stream.write_error(-                frame.request_id,-                wire::error_code::REJECTED,-                "invalid ref name",-            );-            return Ok(true);-        }-        if !ref_matches(txn.view(), &update.name, update.expected) {-            session.stream.write_error(-                frame.request_id,-                wire::error_code::REF_CONFLICT,-                "ref changed",-            );-            return Ok(true);-        }-    }-    for update in &updates {-        apply_ref(txn.view_mut(), &update.name, update.target);-    }-    ops::rebuild_heads(txn.view_mut());-    txn.finish("remote push")?;-    session.store.refresh()?;-    Ok(session-        .stream-        .write_simple(wire::kind::UPDATE_REFS_OK, frame.request_id))-}--fn dispatch(session: &mut Session, frame: &wire::Frame) -> Result<bool> {-    match frame.kind {-        wire::kind::HELLO => Ok(handle_hello(session, frame)),-        wire::kind::AUTH => Ok(handle_auth(session, frame)),-        wire::kind::WHOAMI => {-            let mut payload = Vec::new();-            payload.push(session.role);-            crate::encoding::Writer::varint_into(&mut payload, session.fingerprint.len() as u64);-            payload.extend_from_slice(&session.fingerprint);-            Ok(session-                .stream-                .write_frame(wire::kind::WHOAMI_OK, frame.request_id, &payload))-        }-        wire::kind::LIST_REFS => handle_list_refs(session, frame),-        wire::kind::NEGOTIATE => handle_negotiate(session, frame),-        wire::kind::FETCH_SKELETON => handle_fetch(session, frame),-        wire::kind::GET_CHUNKS => handle_get_chunks(session, frame),-        wire::kind::HAVE_QUERY => handle_have_query(session, frame),-        wire::kind::PUT_RECORDS => handle_put_records(session, frame),-        wire::kind::UPDATE_REFS => handle_update_refs(session, frame),-        _ => {-            session.stream.write_error(-                frame.request_id,-                wire::error_code::BAD_FRAME,-                "unknown request",-            );-            Ok(true)-        }-    }-}--fn run_session(-    stream: Stream,-    fixed: Option<PathBuf>,-    root: Option<PathBuf>,-    binding: Vec<u8>,-    quota: u64,-) -> Result<()> {-    let repo_present = fixed.is_some();-    let repo = fixed.clone().unwrap_or_default();-    let base = root.clone().unwrap_or_default();-    let open_path = if repo_present { repo.clone() } else { base };-    let access = if repo_present {-        crypto::load_access(&repo)-    } else {-        crypto::empty_access()-    };-    let mut session = Session {-        stream,-        repo,-        repo_present,-        root: root.unwrap_or_default(),-        quota_bytes: quota,-        store: Store::open(&open_path)?,-        access,-        hello_repo: String::new(),-        client_nonce: Vec::new(),-        server_nonce: Vec::new(),-        binding,-        version: messages::PROTOCOL_VERSION,-        authed: false,-        role: 0,-        public_key: None,-        fingerprint: Vec::new(),-        haves: Vec::new(),-    };-    loop {-        let Some(frame) = session.stream.read_frame() else {-            break;-        };-        match dispatch(&mut session, &frame) {-            Ok(true) => {}-            Ok(false) | Err(_) => break,-        }-    }-    Ok(())-}--pub fn serve_stdio(repo: &Path, quota: u64) -> Result<()> {-    run_session(-        Stream::stdio(),-        Some(repo.to_path_buf()),-        None,-        Vec::new(),-        quota,-    )-}--pub fn serve_listen(-    address: &str,-    root: &Path,-    cert_path: &str,-    key_path: &str,-    quota: u64,-) -> Result<()> {-    let config = super::protocol::tls::server_context(cert_path, key_path)?;-    let listener = std::net::TcpListener::bind(address)-        .map_err(|_| crate::error::Error::new(format!("cannot listen on {address}")))?;-    crate::cli::output::info_prefix();-    println!("listening on {address}");-    for incoming in listener.incoming() {-        let Ok(socket) = incoming else {-            break;-        };-        let config = Arc::clone(&config);-        let root = root.to_path_buf();-        std::thread::spawn(move || {-            let Ok(stream) = super::protocol::tls::accept(socket, config) else {-                return;-            };-            let binding = stream.binding().to_vec();-            let _ = run_session(stream, None, Some(root), binding, quota);-        });-    }-    Ok(())-}--- a/veinsrs/src/store/graph.rs+++ /dev/null@@ -1,533 +0,0 @@-use std::collections::{HashMap, HashSet};--use crate::error::{Error, Result};-use crate::object::blob::{self, BlobForm};-use crate::object::commit::{self, Commit};-use crate::object::id::{Id, is_hex_prefix, prefix_matches};-use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_MISSING, KIND_SUBTREE};-use crate::object::view::View;-use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT};-use crate::store::ops;-use crate::store::reader::Store;--pub fn load_commit(store: &mut Store, id: Id) -> Result<Option<Commit>> {-    let Some(body) = store.body(id, TYPE_COMMIT)? else {-        return Ok(None);-    };-    Ok(Some(commit::decode(&body)?))-}--pub fn has_changes(store: &mut Store, commit: &Commit) -> Result<bool> {-    if let Some(parent) = commit.parents.first() {-        let Some(parent) = load_commit(store, *parent)? else {-            return Ok(true);-        };-        return Ok(parent.root_tree != commit.root_tree);-    }-    Ok(!tree::flatten(store, commit.root_tree)?.is_empty())-}--pub fn collect_commits(store: &mut Store, start: &[Id]) -> Result<Vec<Id>> {-    let mut output = Vec::new();-    let mut stack = Vec::new();-    let mut seen = HashSet::new();-    for id in start {-        if seen.insert(*id) {-            stack.push(*id);-        }-    }-    while let Some(id) = stack.pop() {-        output.push(id);-        if let Some(commit) = load_commit(store, id)? {-            for parent in commit.parents {-                if seen.insert(parent) {-                    stack.push(parent);-                }-            }-        }-    }-    Ok(output)-}--pub struct LogNode {-    pub id: Id,-    pub seconds: i64,-    pub parents: Vec<Id>,-}--pub fn order_log_nodes(nodes: &[LogNode]) -> Vec<usize> {-    use std::cmp::Reverse;-    use std::collections::{BinaryHeap, HashMap};-    let mut index = HashMap::new();-    for (position, node) in nodes.iter().enumerate() {-        index.insert(node.id, position);-    }-    let mut unemitted = vec![0usize; nodes.len()];-    for node in nodes {-        for parent in &node.parents {-            if let Some(found) = index.get(parent) {-                unemitted[*found] += 1;-            }-        }-    }-    let mut ready = BinaryHeap::new();-    for (position, node) in nodes.iter().enumerate() {-        if unemitted[position] == 0 {-            ready.push((node.seconds, Reverse(position)));-        }-    }-    let mut emitted = vec![false; nodes.len()];-    let mut order = Vec::with_capacity(nodes.len());-    while let Some((_, Reverse(position))) = ready.pop() {-        if emitted[position] {-            continue;-        }-        emitted[position] = true;-        order.push(position);-        for parent in &nodes[position].parents {-            let Some(found) = index.get(parent).copied() else {-                continue;-            };-            if unemitted[found] > 0 {-                unemitted[found] -= 1;-            }-            if unemitted[found] == 0 {-                ready.push((nodes[found].seconds, Reverse(found)));-            }-        }-    }-    for position in 0..nodes.len() {-        if !emitted[position] {-            order.push(position);-        }-    }-    order-}--pub fn view_roots(view: &View) -> Vec<Id> {-    let mut roots = Vec::new();-    let mut add = |id: Id| {-        if !roots.contains(&id) {-            roots.push(id);-        }-    };-    for head in &view.heads {-        add(*head);-    }-    for bookmark in &view.bookmarks {-        for id in bookmark.targets.adds.iter().flatten() {-            add(*id);-        }-    }-    for tag in &view.tags {-        add(tag.target);-    }-    for workspace in &view.working_copies {-        add(workspace.target);-    }-    roots-}--pub fn all_commits(store: &mut Store, view: &View) -> Result<Vec<Id>> {-    collect_commits(store, &view_roots(view))-}--pub fn bookmark_target(view: &View, name: &[u8]) -> Option<Id> {-    view.bookmarks.iter().find_map(|bookmark| {-        if bookmark.name == name-            && bookmark.targets.adds.len() == 1-            && bookmark.targets.adds[0].is_some()-        {-            bookmark.targets.adds[0]-        } else {-            None-        }-    })-}--fn is_change_id_prefix(text: &str) -> bool {-    if text.is_empty() || text.len() > 26 {-        return false;-    }-    text.bytes().all(|byte| {-        let lower = byte.to_ascii_lowercase();-        lower.is_ascii_lowercase() || (b'2'..=b'7').contains(&lower)-    })-}--pub fn resolve_revision(store: &mut Store, view: &View, revision: &str) -> Result<Option<Id>> {-    if revision.is_empty() || revision == "@" {-        return Ok(ops::working_copy_id(view));-    }-    if let Some(id) = bookmark_target(view, revision.as_bytes()) {-        return Ok(Some(id));-    }-    if let Some(id) = view-        .tags-        .iter()-        .find(|tag| tag.name == revision.as_bytes())-        .map(|tag| tag.target)-    {-        return Ok(Some(id));-    }-    if let Some(id) = view.remote_refs.iter().find_map(|reference| {-        let mut joined = reference.remote.clone();-        joined.push(b'/');-        joined.extend_from_slice(&reference.name);-        (joined == revision.as_bytes()).then_some(reference.target)-    }) {-        return Ok(Some(id));-    }--    if revision.len() == 64 {-        if let Ok(id) = Id::from_hex(revision)-            && load_commit(store, id)?.is_some()-        {-            return Ok(Some(id));-        }-        return Ok(None);-    }--    let hex_prefix = is_hex_prefix(revision);-    let change_prefix = is_change_id_prefix(revision);-    if !hex_prefix && !change_prefix {-        return Ok(None);-    }--    let ids = all_commits(store, view)?;-    let mut matches = Vec::new();-    if hex_prefix {-        for id in &ids {-            if prefix_matches(&id.to_hex(), revision) {-                matches.push(*id);-            }-        }-    }-    if matches.is_empty() && change_prefix {-        for id in &ids {-            if let Some(commit) = load_commit(store, *id)? {-                let encoded = base32_encode(commit.change_id);-                if prefix_matches(&encoded, revision) {-                    matches.push(*id);-                }-            }-        }-    }-    if matches.len() == 1 {-        Ok(Some(matches[0]))-    } else {-        Ok(None)-    }-}--pub fn base32_encode(value: [u8; 16]) -> String {-    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";-    let mut output = String::with_capacity(26);-    let mut buffer = 0u64;-    let mut bits = 0usize;-    for byte in value {-        buffer = (buffer << 8) | u64::from(byte);-        bits += 8;-        while bits >= 5 {-            let shift = bits - 5;-            let index = ((buffer >> shift) & 31) as usize;-            output.push(ALPHABET[index] as char);-            bits = shift;-        }-        if bits == 0 {-            buffer = 0;-        } else {-            buffer &= (1u64 << bits) - 1;-        }-    }-    if bits > 0 {-        output.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);-    }-    output-}--pub fn short_change_id(ids: &[String], index: usize) -> String {-    let target = &ids[index];-    let mut length = 4.min(target.len());-    while length < target.len() {-        let prefix = &target[..length];-        let unique = ids.iter().enumerate().all(|(other_index, other)| {-            other_index == index || other == target || !other.starts_with(prefix)-        });-        if unique {-            break;-        }-        length += 1;-    }-    target[..length].to_string()-}--fn append_blob(store: &Store, id: Id, output: &mut Vec<u8>, depth: usize) -> Result<bool> {-    if depth > 64 {-        return Err(Error::new("blob nesting too deep"));-    }-    let Some(body) = store.body_loaded(id, TYPE_BLOB)? else {-        return Ok(false);-    };-    let blob = blob::decode(&body)?;-    match blob.form {-        BlobForm::Inline => {-            output.extend_from_slice(&blob.data);-        }-        BlobForm::Leaf => {-            let total: u64 = blob.entries.iter().map(|entry| entry.length).sum();-            if let Ok(total) = usize::try_from(total) {-                if total <= crate::object::MAX_OBJECT_BODY {-                    output.reserve(total);-                }-            }-            for entry in blob.entries {-                let Some(chunk) = store.body_raw_loaded(entry.id, TYPE_CHUNK)? else {-                    return Ok(false);-                };-                output.extend_from_slice(&chunk);-            }-        }-        BlobForm::Interior => {-            for entry in blob.entries {-                if !append_blob(store, entry.id, output, depth + 1)? {-                    return Ok(false);-                }-            }-        }-    }-    Ok(true)-}--pub fn read_blob_loaded(store: &Store, id: Id) -> Result<Option<Vec<u8>>> {-    let mut output = Vec::new();-    if append_blob(store, id, &mut output, 0)? {-        Ok(Some(output))-    } else {-        Ok(None)-    }-}--pub fn read_blob(store: &mut Store, id: Id) -> Result<Option<Vec<u8>>> {-    store.preload()?;-    read_blob_loaded(store, id)-}--#[derive(Default)]-pub struct BlobMeasure {-    pub bytes: u64,-    pub lines: u64,-    pub has_nul: bool,-    line_has_content: bool,-}--fn scan_blob_bytes(data: &[u8], out: &mut BlobMeasure) {-    if out.bytes < 8192 {-        let prefix = data.len().min((8192 - out.bytes) as usize);-        if data[..prefix].contains(&0) {-            out.has_nul = true;-        }-    }-    let mut start = 0;-    while start < data.len() {-        let end = data[start..]-            .iter()-            .position(|byte| *byte == b'\n')-            .map(|offset| start + offset)-            .unwrap_or(data.len());-        if !out.line_has_content-            && data[start..end]-                .iter()-                .any(|byte| !matches!(*byte, b' ' | b'\t' | b'\r'))-        {-            out.line_has_content = true;-        }-        if end >= data.len() {-            break;-        }-        if out.line_has_content {-            out.lines += 1;-        }-        out.line_has_content = false;-        start = end + 1;-    }-    out.bytes += data.len() as u64;-}--fn measure_blob_into(-    store: &Store,-    id: Id,-    output: &mut BlobMeasure,-    depth: usize,-) -> Result<bool> {-    if depth > 64 {-        return Err(Error::new("blob nesting too deep"));-    }-    let Some(body) = store.body_raw_loaded(id, TYPE_BLOB)? else {-        return Ok(false);-    };-    let blob = blob::decode(&body)?;-    match blob.form {-        BlobForm::Inline => scan_blob_bytes(&blob.data, output),-        BlobForm::Leaf => {-            for entry in blob.entries {-                let Some(chunk) = store.body_raw_loaded(entry.id, TYPE_CHUNK)? else {-                    return Ok(false);-                };-                scan_blob_bytes(&chunk, output);-            }-        }-        BlobForm::Interior => {-            for entry in blob.entries {-                if !measure_blob_into(store, entry.id, output, depth + 1)? {-                    return Ok(false);-                }-            }-        }-    }-    Ok(true)-}--pub fn measure_blob_loaded(store: &Store, id: Id, output: &mut BlobMeasure) -> Result<bool> {-    if !measure_blob_into(store, id, output, 0)? {-        return Ok(false);-    }-    if output.line_has_content {-        output.lines += 1;-        output.line_has_content = false;-    }-    Ok(true)-}--#[derive(Clone)]-pub struct TreeChange {-    pub path: Vec<u8>,-    pub old_kind: u8,-    pub new_kind: u8,-    pub old_id: Option<Id>,-    pub new_id: Option<Id>,-}--pub fn compare_trees(-    store: &mut Store,-    old_tree: Option<Id>,-    new_tree: Option<Id>,-) -> Result<Vec<TreeChange>> {-    let old_entries = match old_tree {-        Some(id) => tree::flatten(store, id)?,-        None => Vec::new(),-    };-    let new_entries = match new_tree {-        Some(id) => tree::flatten(store, id)?,-        None => Vec::new(),-    };-    let mut changes = Vec::new();-    let mut old_index = 0;-    let mut new_index = 0;-    while old_index < old_entries.len() || new_index < new_entries.len() {-        let ordering = if old_index >= old_entries.len() {-            std::cmp::Ordering::Greater-        } else if new_index >= new_entries.len() {-            std::cmp::Ordering::Less-        } else {-            old_entries[old_index]-                .path-                .cmp(&new_entries[new_index].path)-        };-        match ordering {-            std::cmp::Ordering::Less => {-                let entry = &old_entries[old_index];-                changes.push(TreeChange {-                    path: entry.path.clone(),-                    old_kind: entry.kind,-                    new_kind: KIND_MISSING,-                    old_id: Some(entry.target),-                    new_id: None,-                });-                old_index += 1;-            }-            std::cmp::Ordering::Greater => {-                let entry = &new_entries[new_index];-                changes.push(TreeChange {-                    path: entry.path.clone(),-                    old_kind: KIND_MISSING,-                    new_kind: entry.kind,-                    old_id: None,-                    new_id: Some(entry.target),-                });-                new_index += 1;-            }-            std::cmp::Ordering::Equal => {-                let old = &old_entries[old_index];-                let new = &new_entries[new_index];-                if old.kind != new.kind || old.target != new.target {-                    changes.push(TreeChange {-                        path: old.path.clone(),-                        old_kind: old.kind,-                        new_kind: new.kind,-                        old_id: Some(old.target),-                        new_id: Some(new.target),-                    });-                }-                old_index += 1;-                new_index += 1;-            }-        }-    }-    Ok(changes)-}--pub fn flatten(store: &mut Store, tree_id: Id) -> Result<Vec<FlatEntry>> {-    tree::flatten(store, tree_id)-}--fn conflicted_into(-    store: &mut Store,-    tree_id: Id,-    depth: usize,-    cache: &mut HashMap<Id, bool>,-) -> Result<bool> {-    if depth > crate::object::MAX_TREE_DEPTH {-        return Ok(true);-    }-    if let Some(known) = cache.get(&tree_id) {-        return Ok(*known);-    }-    let Some(body) = store.body(tree_id, crate::object::TYPE_TREE)? else {-        cache.insert(tree_id, true);-        return Ok(true);-    };-    let mut found = false;-    let scanned = tree::scan(&body, |_name, kind, target| {-        if found {-            return Ok(());-        }-        if kind == KIND_CONFLICT {-            found = true;-            return Ok(());-        }-        if kind == KIND_SUBTREE && conflicted_into(store, target, depth + 1, cache)? {-            found = true;-        }-        Ok(())-    });-    if scanned.is_err() {-        cache.insert(tree_id, true);-        return Ok(true);-    }-    cache.insert(tree_id, found);-    Ok(found)-}--pub fn tree_conflicted_with(-    store: &mut Store,-    tree_id: Id,-    cache: &mut std::collections::HashMap<Id, bool>,-) -> Result<bool> {-    conflicted_into(store, tree_id, 0, cache)-}--pub fn tree_conflicted(store: &mut Store, tree_id: Id) -> Result<bool> {-    let mut cache = std::collections::HashMap::new();-    conflicted_into(store, tree_id, 0, &mut cache)-}--- a/veinsrs/src/store/index.rs+++ /dev/null@@ -1,126 +0,0 @@-use crate::encoding::Reader;-use crate::error::{Error, Result};-use crate::object::id::{Id, hash_bytes};--#[derive(Clone)]-pub struct IndexEntry {-    pub id: Id,-    pub offset: u64,-}--#[derive(Clone)]-pub struct Index {-    pub entries: Vec<IndexEntry>,-    pub pack_trailer: [u8; 32],-}--impl Index {-    pub fn find(&self, id: Id) -> Option<usize> {-        self.entries-            .binary_search_by(|entry| entry.id.0.cmp(&id.0))-            .ok()-    }-}--pub fn decode(data: &[u8], expected_pack_trailer: Option<[u8; 32]>) -> Result<Index> {-    const BASE: usize = 1032 + 64;-    if data.len() < BASE {-        return Err(Error::new("index is truncated"));-    }-    if &data[..4] != b"VIX1" {-        return Err(Error::new("invalid index magic"));-    }-    let mut reader = Reader::new(data);-    reader.raw(4)?;-    let version = reader.u32le()?;-    if version != 1 {-        return Err(Error::new("unsupported index version"));-    }-    let mut fanout = [0u32; 256];-    let mut previous = 0u32;-    for slot in &mut fanout {-        let value = reader.u32le()?;-        if value < previous {-            return Err(Error::new("index fanout is not sorted"));-        }-        previous = value;-        *slot = value;-    }-    let body = data.len() - BASE;-    if !body.is_multiple_of(40) {-        return Err(Error::new("index body has an invalid length"));-    }-    let count = body / 40;-    if count != fanout[255] as usize {-        return Err(Error::new("index fanout does not match entry count"));-    }-    let ids_start = 1032;-    let offsets_start = ids_start + count * 32;-    let trailer_offset = data.len() - 32;-    let mut entries: Vec<IndexEntry> = Vec::with_capacity(count);-    let mut counts = [0u32; 256];-    let mut previous: Option<[u8; 32]> = None;-    for (index, chunk) in data[ids_start..offsets_start].chunks_exact(32).enumerate() {-        let mut id = [0u8; 32];-        id.copy_from_slice(chunk);-        if previous.is_some_and(|value| value >= id) {-            return Err(Error::new("index ids are not sorted"));-        }-        previous = Some(id);-        counts[id[0] as usize] += 1;-        let mut offset_bytes = [0u8; 8];-        let start = offsets_start + index * 8;-        offset_bytes.copy_from_slice(&data[start..start + 8]);-        entries.push(IndexEntry {-            id: Id(id),-            offset: u64::from_le_bytes(offset_bytes),-        });-    }-    let mut pack_trailer = [0u8; 32];-    pack_trailer.copy_from_slice(&data[trailer_offset - 32..trailer_offset]);-    if hash_bytes(&data[..trailer_offset])[..] != data[trailer_offset..] {-        return Err(Error::new("index checksum mismatch"));-    }-    if expected_pack_trailer.is_some_and(|value| value != pack_trailer) {-        return Err(Error::new("index pack trailer mismatch"));-    }-    let mut running = 0u32;-    for index in 0..256 {-        running += counts[index];-        if running != fanout[index] {-            return Err(Error::new("index fanout is inconsistent"));-        }-    }-    Ok(Index {-        entries,-        pack_trailer,-    })-}--pub fn encode(entries: &[IndexEntry], pack_trailer: [u8; 32]) -> Vec<u8> {-    use crate::encoding::Writer;--    let mut counts = [0u32; 256];-    for entry in entries {-        counts[entry.id.0[0] as usize] += 1;-    }-    let mut writer = Writer::with_capacity(entries.len() * 40 + 128);-    writer.raw(b"VIX1");-    writer.u32le(1);-    let mut running = 0u32;-    for count in counts {-        running += count;-        writer.u32le(running);-    }-    for entry in entries {-        writer.id(entry.id);-    }-    for entry in entries {-        writer.u64le(entry.offset);-    }-    writer.raw(&pack_trailer);-    let mut data = writer.into_vec();-    let digest = hash_bytes(&data);-    data.extend_from_slice(&digest);-    data-}--- a/veinsrs/src/store/layout.rs+++ /dev/null@@ -1,158 +0,0 @@-use std::fs::{self, File};-use std::io::Write;-use std::path::{Path, PathBuf};--use crate::error::{Error, Result};-use crate::platform;--pub fn veins_dir(root: &Path) -> PathBuf {-    root.join(".veins")-}--pub fn packs_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("store").join("packs")-}--pub fn tmp_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("store").join("tmp")-}--pub fn op_heads_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("op-heads")-}--pub fn git_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("git")-}--pub fn git_map_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("git-map")-}--pub fn working_copy_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("working-copy")-}--pub fn resolutions_dir(root: &Path) -> PathBuf {-    veins_dir(root).join("resolutions")-}--pub fn config_path(root: &Path) -> PathBuf {-    veins_dir(root).join("config")-}--pub fn format_path(root: &Path) -> PathBuf {-    veins_dir(root).join("format")-}--pub fn discover(start: &Path) -> Result<PathBuf> {-    let mut current = fs::canonicalize(start)?;-    loop {-        if format_path(&current).is_file() {-            return Ok(current);-        }-        match current.parent() {-            Some(parent) => current = parent.to_path_buf(),-            None => return Err(Error::new("not a veins repository")),-        }-    }-}--pub fn init(path: &Path) -> Result<PathBuf> {-    let root = if path.as_os_str().is_empty() {-        PathBuf::from(".")-    } else {-        path.to_path_buf()-    };-    fs::create_dir_all(&root)?;-    let format = format_path(&root);-    let expected = b"veins-store 1";-    if format.exists() {-        let data = fs::read(&format)?;-        if data != expected {-            return Err(Error::new("unsupported repository format"));-        }-    }-    ensure_layout(&root)?;-    if !format.exists() {-        fs::write(&format, expected)?;-    }-    if !config_path(&root).exists() {-        fs::write(config_path(&root), [])?;-    }-    Ok(root)-}--fn ensure_layout(root: &Path) -> Result<()> {-    let directories = [-        veins_dir(root),-        veins_dir(root).join("store"),-        packs_dir(root),-        tmp_dir(root),-        op_heads_dir(root),-        git_map_dir(root),-        git_map_dir(root).join("raw"),-        working_copy_dir(root),-        resolutions_dir(root),-    ];-    for directory in directories {-        fs::create_dir_all(directory)?;-    }-    Ok(())-}--pub fn write_atomic(final_path: &Path, data: &[u8]) -> Result<()> {-    if let Some(parent) = final_path.parent() {-        fs::create_dir_all(parent)?;-    }-    let parent = final_path-        .parent()-        .ok_or_else(|| Error::new("path has no parent"))?;-    let name = final_path-        .file_name()-        .ok_or_else(|| Error::new("path has no file name"))?-        .to_string_lossy();-    let temporary = parent.join(format!(".{name}.tmp"));-    {-        let mut file = File::create(&temporary)?;-        file.write_all(data)?;-    }-    sync_file(&temporary)?;-    fs::rename(&temporary, final_path)?;-    sync_directory(parent);-    Ok(())-}--fn sync_file(path: &Path) -> Result<()> {-    Ok(platform::sync_file(path)?)-}--fn sync_directory(path: &Path) {-    platform::sync_directory(path);-}--pub fn read_directory(path: &Path) -> Result<Vec<Vec<u8>>> {-    let mut names = Vec::new();-    for entry in fs::read_dir(path)? {-        let entry = entry?;-        names.push(platform::os_string_to_bytes(entry.file_name()));-    }-    names.sort();-    Ok(names)-}--pub fn os_string(bytes: &[u8]) -> std::ffi::OsString {-    platform::os_string_from_bytes(bytes)-}--pub fn append_file(path: &Path, data: &[u8]) -> Result<()> {-    if let Some(parent) = path.parent() {-        fs::create_dir_all(parent)?;-    }-    let mut file = fs::OpenOptions::new()-        .create(true)-        .append(true)-        .open(path)?;-    file.write_all(data)?;-    Ok(())-}--- a/veinsrs/src/store/mod.rs+++ /dev/null@@ -1,11 +0,0 @@-pub mod graph;-pub mod index;-pub mod layout;-pub mod ops;-pub mod pack;-pub mod reader;-pub mod transaction;-pub mod writer;--pub use reader::{Location, Store, set_promisor_fetcher};-pub use transaction::Txn;--- a/veinsrs/src/store/ops.rs+++ /dev/null@@ -1,228 +0,0 @@-use std::fs;-use std::path::Path;--use crate::error::{Error, Result};-use crate::object::id::Id;-use crate::object::view::{Bookmark, View, WorkspaceRef};-use crate::store::layout;-use crate::store::reader::Store;--pub fn read_heads(root: &Path) -> Result<Vec<Id>> {-    let directory = layout::op_heads_dir(root);-    let mut heads = Vec::new();-    if let Ok(entries) = fs::read_dir(&directory) {-        for entry in entries.flatten() {-            let name = entry.file_name();-            let text = name.to_string_lossy();-            if text.len() == 64-                && let Ok(id) = Id::from_hex(&text)-            {-                heads.push(id);-            }-        }-    }-    heads.sort_by(|left, right| left.0.cmp(&right.0));-    Ok(heads)-}--pub fn write_head(root: &Path, id: Id) -> Result<()> {-    let path = layout::op_heads_dir(root).join(id.to_hex());-    layout::write_atomic(&path, &[])-}--pub fn delete_head(root: &Path, id: Id) -> Result<()> {-    let path = layout::op_heads_dir(root).join(id.to_hex());-    match fs::remove_file(path) {-        Ok(()) => Ok(()),-        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),-        Err(error) => Err(error.into()),-    }-}--pub fn empty_view() -> View {-    View::default()-}--pub fn current_view(root: &Path, store: &mut Store) -> Result<Option<View>> {-    let heads = read_heads(root)?;-    let Some(first) = heads.first() else {-        return Ok(None);-    };-    let mut view =-        load_view_for_head(store, *first)?.ok_or_else(|| Error::new("missing operation state"))?;-    for head in &heads[1..] {-        if let Some(extra) = load_view_for_head(store, *head)? {-            merge_view_into(&mut view, &extra);-        }-    }-    sort_view(&mut view);-    Ok(Some(view))-}--fn load_view_for_head(store: &mut Store, id: Id) -> Result<Option<View>> {-    let Some(operation) = store.operation(id)? else {-        return Ok(None);-    };-    store.view(operation.view)-}--pub fn merge_view_into(target: &mut View, source: &View) {-    for head in &source.heads {-        add_unique_head(target, *head);-    }-    for bookmark in &source.bookmarks {-        match find_bookmark(target, &bookmark.name) {-            None => target.bookmarks.push(bookmark.clone()),-            Some(index) => {-                let existing = &mut target.bookmarks[index];-                let left = existing.targets.adds.first().copied().flatten();-                let right = bookmark.targets.adds.first().copied().flatten();-                if left != right || existing.targets.adds.len() != bookmark.targets.adds.len() {-                    existing.targets.adds = vec![left, right];-                    existing.targets.removes = vec![None];-                }-            }-        }-    }-    for tag in &source.tags {-        if !target.tags.iter().any(|value| value.name == tag.name) {-            target.tags.push(tag.clone());-        }-    }-    for workspace in &source.working_copies {-        if !target-            .working_copies-            .iter()-            .any(|value| value.workspace == workspace.workspace)-        {-            target.working_copies.push(workspace.clone());-        }-    }-}--pub fn working_copy_id(view: &View) -> Option<Id> {-    view.working_copies-        .iter()-        .find(|workspace| workspace.workspace == b"default")-        .map(|workspace| workspace.target)-}--pub fn sort_ids(ids: &mut [Id]) {-    ids.sort_by(|left, right| left.0.cmp(&right.0));-}--pub fn sort_view(view: &mut View) {-    view.heads.sort_by(|left, right| left.0.cmp(&right.0));-    view.bookmarks-        .sort_by(|left, right| left.name.cmp(&right.name));-    view.tags.sort_by(|left, right| left.name.cmp(&right.name));-    view.remote_refs.sort_by(|left, right| {-        left.remote-            .cmp(&right.remote)-            .then_with(|| left.name.cmp(&right.name))-    });-    view.working_copies-        .sort_by(|left, right| left.workspace.cmp(&right.workspace));-}--pub fn add_unique_head(view: &mut View, id: Id) {-    if !view.heads.contains(&id) {-        view.heads.push(id);-    }-}--pub fn rebuild_heads(view: &mut View) {-    view.heads.clear();-    let mut ids = Vec::new();-    for bookmark in &view.bookmarks {-        for id in bookmark.targets.adds.iter().flatten() {-            ids.push(*id);-        }-    }-    for tag in &view.tags {-        ids.push(tag.target);-    }-    for workspace in &view.working_copies {-        ids.push(workspace.target);-    }-    for id in ids {-        add_unique_head(view, id);-    }-    sort_ids(&mut view.heads);-}--pub fn set_workspace(view: &mut View, id: Id) {-    for workspace in &mut view.working_copies {-        if workspace.workspace == b"default" {-            workspace.target = id;-            return;-        }-    }-    view.working_copies.push(WorkspaceRef {-        workspace: b"default".to_vec(),-        target: id,-    });-    view.working_copies-        .sort_by(|left, right| left.workspace.cmp(&right.workspace));-}--pub fn remove_head(view: &mut View, id: Id) {-    view.heads.retain(|head| *head != id);-}--pub fn move_bookmarks(view: &mut View, old_id: Id, new_id: Id) {-    if old_id == new_id {-        return;-    }-    for bookmark in &mut view.bookmarks {-        if bookmark.targets.adds.contains(&Some(old_id)) {-            bookmark.targets.adds = vec![Some(new_id)];-            bookmark.targets.removes.clear();-        }-    }-}--pub fn set_bookmark_target(view: &mut View, name: &[u8], target: Id) {-    if let Some(index) = find_bookmark(view, name) {-        view.bookmarks[index].targets.adds = vec![Some(target)];-        view.bookmarks[index].targets.removes.clear();-        return;-    }-    view.bookmarks.push(Bookmark {-        name: name.to_vec(),-        targets: crate::object::view::TargetSet {-            adds: vec![Some(target)],-            removes: Vec::new(),-        },-    });-}--pub fn find_bookmark(view: &View, name: &[u8]) -> Option<usize> {-    view.bookmarks-        .iter()-        .position(|bookmark| bookmark.name == name)-}--pub fn find_tag(view: &View, name: &[u8]) -> Option<usize> {-    view.tags.iter().position(|tag| tag.name == name)-}--pub fn bookmark_points_at(bookmark: &Bookmark, target: Id) -> bool {-    bookmark.targets.adds.len() == 1 && bookmark.targets.adds[0] == Some(target)-}--pub fn tag_names(view: &View, id: Id) -> Vec<Vec<u8>> {-    view.tags-        .iter()-        .filter(|tag| tag.target == id)-        .map(|tag| tag.name.clone())-        .collect()-}--pub fn bookmark_names(view: &View, id: Id) -> Vec<Vec<u8>> {-    view.bookmarks-        .iter()-        .filter(|bookmark| bookmark.targets.adds.contains(&Some(id)))-        .map(|bookmark| bookmark.name.clone())-        .collect()-}--- a/veinsrs/src/store/pack.rs+++ /dev/null@@ -1,858 +0,0 @@-use std::collections::{HashMap, HashSet};-use std::hash::{BuildHasherDefault, Hasher};-use std::io::{Read, Seek, SeekFrom};-use std::path::Path;--use rayon::prelude::*;--use crate::core;-use crate::encoding::{Reader, Writer};-use crate::error::{Error, Result};-use crate::object::blob::{self, BlobEntry, BlobForm};-use crate::object::id::{Id, hash_bytes};-use crate::object::{-    MAX_CHUNK_LEN, MAX_OBJECT_BODY, MAX_STORE_PACK_BYTES, RawObject, TYPE_BLOB, TYPE_CHUNK,-    type_valid,-};-use crate::store::index::{self, IndexEntry};--/// FNV-1a over the raw bytes of an object id. `Id`'s derived `Hash` writes 32-/// individual bytes through SipHash, which dominates map-heavy pack encoding.-pub struct IdHasher(u64);--impl Default for IdHasher {-    fn default() -> Self {-        Self(0xcbf2_9ce4_8422_2325)-    }-}--impl Hasher for IdHasher {-    fn finish(&self) -> u64 {-        self.0-    }--    fn write(&mut self, bytes: &[u8]) {-        for byte in bytes {-            self.0 ^= u64::from(*byte);-            self.0 = self.0.wrapping_mul(0x100_0000_01b3);-        }-    }-}--pub type IdBuildHasher = BuildHasherDefault<IdHasher>;-pub type IdMap<V> = HashMap<Id, V, IdBuildHasher>;-pub type IdSet = HashSet<Id, IdBuildHasher>;--#[derive(Clone)]-pub struct PackRecord {-    pub id: Id,-    pub kind: u8,-    pub compression: u8,-    pub raw_len: u64,-    pub stored_len: u64,-    pub data_offset: usize,-    pub record_offset: usize,-}--pub struct Pack {-    pub data: Vec<u8>,-    pub records: Vec<PackRecord>,-    pub trailer: [u8; 32],-}--pub fn record_limit(kind: u8) -> usize {-    if kind == TYPE_CHUNK {-        MAX_CHUNK_LEN-    } else {-        MAX_OBJECT_BODY-    }-}--thread_local! {-    static DECOMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Decompressor<'static>>> =-        const { std::cell::RefCell::new(None) };-    static DICT_DECOMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Decompressor<'static>>> =-        const { std::cell::RefCell::new(None) };-}--pub(crate) fn decompress(data: &[u8], raw_len: usize) -> Result<Vec<u8>> {-    DECOMPRESSOR.with(|slot| {-        let mut slot = slot.borrow_mut();-        if slot.is_none() {-            *slot = zstd::bulk::Decompressor::new().ok();-        }-        let decoder = slot-            .as_mut()-            .ok_or_else(|| Error::new("cannot create zstd decoder"))?;-        decoder-            .decompress(data, raw_len)-            .map_err(|error| Error::new(error.to_string()))-    })-}--pub(crate) fn decompress_dict(data: &[u8], raw_len: usize, dictionary: &[u8]) -> Result<Vec<u8>> {-    DICT_DECOMPRESSOR.with(|slot| {-        let mut slot = slot.borrow_mut();-        if slot.is_none() {-            *slot = zstd::bulk::Decompressor::new().ok();-        }-        let decoder = slot-            .as_mut()-            .ok_or_else(|| Error::new("cannot create zstd decoder"))?;-        decoder-            .set_dictionary(dictionary)-            .map_err(|error| Error::new(error.to_string()))?;-        decoder-            .decompress(data, raw_len)-            .map_err(|error| Error::new(error.to_string()))-    })-}--fn get_body(pack: &Pack, index: usize, depth: usize) -> Result<Vec<u8>> {-    if depth > 32 {-        return Err(Error::new("pack delta chain is too deep"));-    }-    let record = pack-        .records-        .get(index)-        .ok_or_else(|| Error::new("pack record out of range"))?;-    if record.raw_len == 0 {-        return Ok(Vec::new());-    }-    let raw_len = usize::try_from(record.raw_len).map_err(|_| Error::new("raw length overflow"))?;-    let stored_len =-        usize::try_from(record.stored_len).map_err(|_| Error::new("stored length overflow"))?;-    let end = record-        .data_offset-        .checked_add(stored_len)-        .ok_or_else(|| Error::new("pack offset overflow"))?;-    if end > pack.data.len() {-        return Err(Error::new("pack record exceeds file"));-    }-    let stored = &pack.data[record.data_offset..end];-    match record.compression {-        0 => Ok(stored.to_vec()),-        1 => decompress(stored, raw_len),-        2 => {-            let mut reader = Reader::new(stored);-            let base_offset = reader.varint()?;-            if base_offset >= record.record_offset as u64 {-                return Err(Error::new("invalid pack delta base"));-            }-            let frame = reader.raw(reader.remaining())?;-            if frame.is_empty() {-                return Err(Error::new("pack delta frame is empty"));-            }-            let base_index = pack-                .find_by_offset(base_offset)-                .ok_or_else(|| Error::new("missing pack delta base"))?;-            let base = get_body(pack, base_index, depth + 1)?;-            decompress_dict(frame, raw_len, &base)-        }-        _ => Err(Error::new("invalid pack compression")),-    }-}--impl Pack {-    pub fn find_by_offset(&self, offset: u64) -> Option<usize> {-        let value = usize::try_from(offset).ok()?;-        self.records-            .binary_search_by(|record| record.record_offset.cmp(&value))-            .ok()-    }--    pub fn get(&self, index: usize) -> Result<Vec<u8>> {-        get_body(self, index, 0)-    }-}--pub fn decode(data: Vec<u8>) -> Result<Pack> {-    const HEADER: usize = 16;-    const RECORD_MINIMUM: usize = 36;-    if data.len() < HEADER + 32 {-        return Err(Error::new("pack is truncated"));-    }-    if &data[..4] != b"VPK1" {-        return Err(Error::new("invalid pack magic"));-    }-    let mut header = Reader::new(&data[..HEADER]);-    header.raw(4)?;-    let version = header.u32le()?;-    if version != 1 {-        return Err(Error::new("unsupported pack version"));-    }-    let count = header.u64le()?;-    let body_end = data.len() - 32;-    if hash_bytes(&data[..body_end])[..] != data[body_end..] {-        return Err(Error::new("pack checksum mismatch"));-    }-    if count > (body_end / RECORD_MINIMUM) as u64 {-        return Err(Error::new("pack record count is impossible"));-    }-    let count = usize::try_from(count).map_err(|_| Error::new("pack record count overflow"))?;-    let mut records = Vec::with_capacity(count);-    {-        let mut reader = Reader::new(&data[..body_end]);-        reader.raw(HEADER)?;-        for _ in 0..count {-            let record_offset = reader.offset();-            let id = reader.id()?;-            let kind = reader.u8()?;-            if !type_valid(kind) {-                return Err(Error::new("invalid pack object type"));-            }-            let compression = reader.u8()?;-            if compression > 2 {-                return Err(Error::new("invalid pack compression"));-            }-            let raw_len = reader.varint()?;-            let stored_len = reader.varint()?;-            if raw_len == 0 || raw_len > record_limit(kind) as u64 {-                return Err(Error::new("invalid pack record length"));-            }-            if compression == 0 && raw_len != stored_len {-                return Err(Error::new("uncompressed pack record length mismatch"));-            }-            if stored_len > reader.remaining() as u64 {-                return Err(Error::new("pack record exceeds body"));-            }-            let data_offset = reader.offset();-            if compression == 2 {-                let stored = reader.raw(stored_len as usize)?;-                let mut delta = Reader::new(stored);-                let base_offset = delta.varint()?;-                if base_offset >= record_offset as u64 || delta.remaining() == 0 {-                    return Err(Error::new("invalid pack delta record"));-                }-            } else {-                reader.raw(stored_len as usize)?;-            }-            records.push(PackRecord {-                id,-                kind,-                compression,-                raw_len,-                stored_len,-                data_offset,-                record_offset,-            });-        }-        if reader.offset() != body_end {-            return Err(Error::new("pack has trailing bytes"));-        }-    }-    let mut trailer = [0u8; 32];-    trailer.copy_from_slice(&data[body_end..]);-    Ok(Pack {-        data,-        records,-        trailer,-    })-}--pub struct PackOutput {-    pub pack: Vec<u8>,-    pub index: Vec<u8>,-    pub name: String,-    pub count: usize,-}--thread_local! {-    static COMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Compressor<'static>>> =-        const { std::cell::RefCell::new(None) };-    static DICT_COMPRESSOR: std::cell::RefCell<Option<zstd::bulk::Compressor<'static>>> =-        const { std::cell::RefCell::new(None) };-}--fn compress(data: &[u8], level: i32) -> Option<Vec<u8>> {-    if data.is_empty() {-        return None;-    }-    COMPRESSOR.with(|slot| {-        let mut slot = slot.borrow_mut();-        if slot.is_none() {-            *slot = zstd::bulk::Compressor::new(level).ok();-        }-        let encoder = slot.as_mut()?;-        encoder.set_compression_level(level).ok()?;-        let mut compressed = encoder.compress(data).ok()?;-        compressed.shrink_to_fit();-        (compressed.len() < data.len()).then_some(compressed)-    })-}--// Candidate selection only needs relative sizes, so probe a prefix at a cheap-// level and re-compress the winner at the requested level. Frames written to-// the pack are always produced at `level`.-fn probe_level(level: i32) -> i32 {-    if level > 1 { 1 } else { level }-}--fn probe_delta_size(target: &[u8], base: &[u8], level: i32) -> Option<usize> {-    let frame = compress_dict(target, base, probe_level(level))?;-    Some(frame.len() + 10)-}--fn compress_dict(data: &[u8], dictionary: &[u8], level: i32) -> Option<Vec<u8>> {-    if data.is_empty() || dictionary.is_empty() {-        return None;-    }-    DICT_COMPRESSOR.with(|slot| {-        let mut slot = slot.borrow_mut();-        if slot.is_none() {-            *slot = zstd::bulk::Compressor::new(level).ok();-        }-        let encoder = slot.as_mut()?;-        encoder.set_dictionary(level, dictionary).ok()?;-        let mut compressed = encoder.compress(data).ok()?;-        compressed.shrink_to_fit();-        (compressed.len() < data.len()).then_some(compressed)-    })-}--struct BlobRoot {-    entries: Vec<BlobEntry>,-    offsets: Vec<u64>,-    length: u64,-}--fn select_pack_deltas(-    ids: &[Id],-    kinds: &[u8],-    bodies: &[&[u8]],-    compression: &mut [u8],-    compressed: &mut [Vec<u8>],-    base: &mut [Option<usize>],-    level: i32,-) {-    let mut blob_index: IdMap<usize> = IdMap::default();-    let mut chunk_index: IdMap<usize> = IdMap::default();-    for index in 0..ids.len() {-        if kinds[index] == TYPE_BLOB {-            blob_index.insert(ids[index], index);-        } else if kinds[index] == TYPE_CHUNK {-            chunk_index.insert(ids[index], index);-        }-    }-    if blob_index.is_empty() || chunk_index.is_empty() {-        return;-    }--    let mut children: IdSet = IdSet::default();-    for index in 0..ids.len() {-        if kinds[index] != TYPE_BLOB {-            continue;-        }-        if let Ok(decoded) = blob::decode(&bodies[index])-            && decoded.form == BlobForm::Interior-        {-            for entry in decoded.entries {-                children.insert(entry.id);-            }-        }-    }--    let mut roots = Vec::new();-    for index in 0..ids.len() {-        if kinds[index] != TYPE_BLOB {-            continue;-        }-        let Ok(decoded) = blob::decode(&bodies[index]) else {-            continue;-        };-        if decoded.form == BlobForm::Inline || children.contains(&ids[index]) {-            continue;-        }-        let mut entries = Vec::new();-        let mut valid = true;-        if decoded.form == BlobForm::Leaf {-            entries.extend(decoded.entries);-        } else {-            fn flatten(-                id: Id,-                depth: usize,-                blob_index: &IdMap<usize>,-                bodies: &[&[u8]],-                output: &mut Vec<BlobEntry>,-            ) -> bool {-                if depth > 64 {-                    return false;-                }-                let Some(index) = blob_index.get(&id).copied() else {-                    return false;-                };-                let Ok(decoded) = blob::decode(&bodies[index]) else {-                    return false;-                };-                match decoded.form {-                    BlobForm::Leaf => {-                        output.extend(decoded.entries);-                        true-                    }-                    BlobForm::Interior => decoded-                        .entries-                        .into_iter()-                        .all(|entry| flatten(entry.id, depth + 1, blob_index, bodies, output)),-                    BlobForm::Inline => false,-                }-            }-            valid = flatten(ids[index], 0, &blob_index, bodies, &mut entries);-        }-        if !valid || entries.is_empty() {-            continue;-        }-        let mut offsets = Vec::with_capacity(entries.len());-        let mut offset = 0u64;-        for entry in &entries {-            offsets.push(offset);-            offset = offset.saturating_add(entry.length);-        }-        roots.push(BlobRoot {-            entries,-            offsets,-            length: offset,-        });-    }-    if roots.len() < 2 {-        return;-    }--    let mut parent = vec![usize::MAX; roots.len()];-    {-        let mut last_root: IdMap<usize> = IdMap::default();-        let mut last_bucket: HashMap<u64, Vec<usize>> = HashMap::new();--        let score = |target: usize, base_root: usize| -> Option<(usize, usize)> {-            let target_root = &roots[target];-            let base = &roots[base_root];-            let count = target_root.entries.len();-            let mut sampled = 0usize;-            let mut delta_sum = 0usize;-            let mut solo_sum = 0usize;-            for sample in 0..3 {-                let selected = (count * (2 * sample + 1)) / 6;-                if selected >= count || count == 0 {-                    continue;-                }-                let Some(chunk) = chunk_index.get(&target_root.entries[selected].id).copied()-                else {-                    continue;-                };-                let solo = if compression[chunk] == 1 {-                    compressed[chunk].len()-                } else {-                    bodies[chunk].len()-                };-                if solo == 0 {-                    continue;-                }-                sampled += 1;-                solo_sum += solo;-                let mut best = solo;-                let position = target_root.offsets[selected];-                let near = base.offsets.partition_point(|value| *value < position);-                for delta in -1i64..=1 {-                    let candidate = near as i64 + delta;-                    if candidate < 0 || candidate as usize >= base.entries.len() {-                        continue;-                    }-                    let candidate = candidate as usize;-                    let Some(base_index) = chunk_index.get(&base.entries[candidate].id).copied()-                    else {-                        continue;-                    };-                    if base_index >= chunk {-                        continue;-                    }-                    if let Some(frame) =-                        compress_dict(bodies[chunk], bodies[base_index], probe_level(level))-                    {-                        best = best.min(frame.len() + 10);-                    }-                }-                delta_sum += best;-            }-            if sampled == 0 {-                None-            } else {-                Some((delta_sum, solo_sum))-            }-        };--        const MAX_CANDIDATES: usize = 16;-        for root_index in 0..roots.len() {-            let mut candidates: Vec<usize> = Vec::new();-            let mut votes: HashMap<usize, usize> = HashMap::new();-            for entry in &roots[root_index].entries {-                let Some(candidate) = last_root.get(&entry.id).copied() else {-                    continue;-                };-                if roots[candidate].length == 0 || roots[root_index].length == 0 {-                    continue;-                }-                let ratio = roots[candidate].length as f64 / roots[root_index].length as f64;-                if ratio < 0.4 || ratio > 2.5 {-                    continue;-                }-                *votes.entry(candidate).or_insert(0) += 1;-            }-            let mut voted = usize::MAX;-            let mut voted_count = 0;-            for (candidate, count) in votes {-                if count > voted_count || (count == voted_count && candidate < voted) {-                    voted_count = count;-                    voted = candidate;-                }-            }-            if voted != usize::MAX {-                candidates.push(voted);-            }--            let low = (roots[root_index].length * 9) / 10;-            let high = (roots[root_index].length * 11) / 10;-            let mut nearby: HashMap<usize, u64> = HashMap::new();-            let mut bucket = low >> 13;-            while bucket <= (high >> 13) {-                if let Some(items) = last_bucket.get(&bucket) {-                    for candidate in items {-                        let other = &roots[*candidate];-                        if other.length == 0 || roots[root_index].length == 0 {-                            continue;-                        }-                        let ratio = other.length as f64 / roots[root_index].length as f64;-                        if ratio < 0.9 || ratio > 1.1 {-                            continue;-                        }-                        let difference = other.length.abs_diff(roots[root_index].length);-                        nearby-                            .entry(*candidate)-                            .and_modify(|value| *value = (*value).min(difference))-                            .or_insert(difference);-                    }-                }-                bucket += 1;-            }-            let mut ranked: Vec<(u64, usize)> = nearby-                .into_iter()-                .map(|(candidate, difference)| (difference, candidate))-                .collect();-            ranked.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| right.1.cmp(&left.1)));-            for (_, candidate) in ranked {-                candidates.push(candidate);-            }-            let mut unique = Vec::new();-            for candidate in candidates {-                if !unique.contains(&candidate) {-                    unique.push(candidate);-                }-            }-            if unique.len() > MAX_CANDIDATES {-                unique.truncate(MAX_CANDIDATES);-            }--            let mut best = usize::MAX;-            let mut best_sum = usize::MAX;-            let mut best_solo = 0usize;-            for candidate in unique {-                if candidate == root_index {-                    continue;-                }-                let Some((sum, solo)) = score(root_index, candidate) else {-                    continue;-                };-                if solo == 0 || sum >= solo {-                    continue;-                }-                if sum < best_sum {-                    best_sum = sum;-                    best_solo = solo;-                    best = candidate;-                }-            }-            if best != usize::MAX && best_solo > 0 {-                parent[root_index] = best;-            }--            for entry in &roots[root_index].entries {-                last_root.insert(entry.id, root_index);-            }-            let bucket = roots[root_index].length >> 13;-            let items = last_bucket.entry(bucket).or_default();-            items.push(root_index);-            if items.len() > 4 {-                items.remove(0);-            }-        }-    }--    for root_index in 0..roots.len() {-        if parent[root_index] == usize::MAX {-            continue;-        }-        let base_root = &roots[parent[root_index]];-        for position in 0..roots[root_index].entries.len() {-            let Some(target_index) = chunk_index-                .get(&roots[root_index].entries[position].id)-                .copied()-            else {-                continue;-            };-            if base[target_index].is_some() || kinds[target_index] != TYPE_CHUNK {-                continue;-            }-            let solo = if compression[target_index] == 1 {-                compressed[target_index].len()-            } else {-                bodies[target_index].len()-            };-            if solo == 0 {-                continue;-            }-            let target_offset = roots[root_index].offsets[position];-            let nearest = base_root-                .offsets-                .partition_point(|value| *value < target_offset);-            let mut best_size = solo;-            let mut best_base = usize::MAX;-            for delta in [0i64, -1, 1] {-                let candidate = nearest as i64 + delta;-                if candidate < 0 || candidate as usize >= base_root.entries.len() {-                    continue;-                }-                let candidate = candidate as usize;-                let Some(base_index) = chunk_index.get(&base_root.entries[candidate].id).copied()-                else {-                    continue;-                };-                if base_index >= target_index-                    || kinds[base_index] != TYPE_CHUNK-                    || bodies[base_index].is_empty()-                    || bodies[target_index].is_empty()-                {-                    continue;-                }-                let ratio = bodies[base_index].len() as f64 / bodies[target_index].len() as f64;-                if ratio < 0.3 || ratio > 3.0 {-                    continue;-                }-                if let Some(estimate) =-                    probe_delta_size(bodies[target_index], bodies[base_index], level)-                {-                    if estimate < best_size {-                        best_size = estimate;-                        best_base = base_index;-                    }-                }-            }-            if best_base != usize::MAX-                && let Some(frame) = compress_dict(&bodies[target_index], &bodies[best_base], level)-                && frame.len() + 10 < solo-            {-                base[target_index] = Some(best_base);-                compression[target_index] = 2;-                compressed[target_index] = frame;-            }-        }-    }--    const MAX_DELTA_DEPTH: usize = 4;-    let mut depth = vec![0usize; ids.len()];-    for index in 0..ids.len() {-        let Some(base_index) = base[index] else {-            continue;-        };-        depth[index] = depth[base_index] + 1;-        if depth[index] <= MAX_DELTA_DEPTH {-            continue;-        }-        base[index] = None;-        compression[index] = 0;-        compressed[index].clear();-        depth[index] = 0;-        if bodies[index].len() >= 64-            && let Some(value) = compress(&bodies[index], level)-        {-            compression[index] = 1;-            compressed[index] = value;-        }-    }-}--pub fn encode(objects: &[RawObject], level: i32) -> PackOutput {-    let mut seen: IdSet = IdSet::default();-    let mut unique = Vec::new();-    for object in objects {-        if type_valid(object.kind) && seen.insert(object.id) {-            unique.push(object);-        }-    }--    let mut ids: Vec<Id> = unique.iter().map(|object| object.id).collect();-    let mut kinds: Vec<u8> = unique.iter().map(|object| object.kind).collect();-    let mut bodies: Vec<&[u8]> = unique.iter().map(|object| object.body.as_slice()).collect();-    let mut compression = vec![0u8; unique.len()];-    let mut compressed: Vec<Vec<u8>> = vec![Vec::new(); unique.len()];-    let mut base: Vec<Option<usize>> = vec![None; unique.len()];--    fn initial_compression(body: &[u8], level: i32) -> (u8, Vec<u8>) {-        if body.len() < 64 {-            (0, Vec::new())-        } else if let Some(value) = compress(body, level) {-            (1, value)-        } else {-            (0, Vec::new())-        }-    }--    let initial: Vec<(u8, Vec<u8>)> =-        if std::thread::available_parallelism().map_or(false, |n| n.get() > 1) {-            bodies-                .par_iter()-                .map(|body| initial_compression(body, level))-                .collect()-        } else {-            bodies-                .iter()-                .map(|body| initial_compression(body, level))-                .collect()-        };-    for (index, (kind, value)) in initial.into_iter().enumerate() {-        compression[index] = kind;-        compressed[index] = value;-    }--    select_pack_deltas(-        &ids,-        &kinds,-        &bodies,-        &mut compression,-        &mut compressed,-        &mut base,-        level,-    );--    let estimate = (0..unique.len())-        .map(|index| {-            let stored = if base[index].is_some() || compression[index] != 0 {-                compressed[index].len() + 10-            } else {-                bodies[index].len()-            };-            stored + 64-        })-        .sum::<usize>()-        + 16;-    let mut writer = Writer::with_capacity(estimate);-    writer.raw(b"VPK1");-    writer.u32le(1);-    writer.u64le(0);-    let mut metas = Vec::with_capacity(unique.len());-    let mut record_offsets = vec![0u64; unique.len()];-    for index in 0..unique.len() {-        let offset = writer.len() as u64;-        record_offsets[index] = offset;-        writer.id(ids[index]);-        writer.u8(kinds[index]);-        if let Some(base_index) = base[index] {-            writer.u8(2);-            let mut stored = Writer::with_capacity(compressed[index].len() + 10);-            stored.varint(record_offsets[base_index]);-            stored.raw(&compressed[index]);-            let stored = stored.into_vec();-            writer.varint(bodies[index].len() as u64);-            writer.varint(stored.len() as u64);-            writer.raw(&stored);-        } else {-            writer.u8(compression[index]);-            let stored: &[u8] = if compression[index] == 1 {-                &compressed[index]-            } else {-                &bodies[index]-            };-            writer.varint(bodies[index].len() as u64);-            writer.varint(stored.len() as u64);-            writer.raw(stored);-        }-        metas.push(IndexEntry {-            id: ids[index],-            offset,-        });-    }-    let mut pack = writer.into_vec();-    pack[8..16].copy_from_slice(&(metas.len() as u64).to_le_bytes());-    let digest = hash_bytes(&pack);-    pack.extend_from_slice(&digest);-    metas.sort_by(|left, right| left.id.0.cmp(&right.id.0));-    let index = index::encode(&metas, digest);-    let name = Id(digest).to_hex();-    ids.clear();-    kinds.clear();-    bodies.clear();-    compressed.clear();-    PackOutput {-        pack,-        index,-        name,-        count: metas.len(),-    }-}--pub fn write_output(root: &Path, output: &PackOutput, limit: u64) -> i32 {-    if output.count == 0 {-        return 0;-    }-    if limit > 0 && (output.pack.len() as u64).saturating_add(output.index.len() as u64) > limit {-        return 2;-    }-    let packs = crate::store::layout::packs_dir(root);-    let temporary = crate::store::layout::tmp_dir(root);-    let pack_final = packs.join(format!("{}.vpack", output.name));-    let index_final = packs.join(format!("{}.vidx", output.name));-    let suffix = format!("{}.tmp", core::random_u64());-    let pack_tmp = temporary.join(format!("{}.vpack.{suffix}", output.name));-    let index_tmp = temporary.join(format!("{}.vidx.{suffix}", output.name));-    if !core::write_atomic(&pack_tmp, &pack_final, &output.pack) {-        return 1;-    }-    if !core::write_atomic(&index_tmp, &index_final, &output.index) {-        let _ = core::remove_file(&pack_final);-        return 1;-    }-    0-}--pub fn write_pack(root: &Path, objects: &[RawObject], limit: u64, level: i32) -> i32 {-    let output = encode(objects, level);-    write_output(root, &output, limit)-}--pub struct RawPackReader {-    file: std::fs::File,-}--impl RawPackReader {-    pub fn open(path: &Path) -> std::io::Result<Self> {-        Ok(Self {-            file: std::fs::File::open(path)?,-        })-    }--    pub fn range(&mut self, offset: u64, length: usize) -> Option<Vec<u8>> {-        if length as u64 > MAX_STORE_PACK_BYTES {-            return None;-        }-        self.file.seek(SeekFrom::Start(offset)).ok()?;-        let mut data = vec![0u8; length];-        let mut done = 0;-        while done < length {-            match self.file.read(&mut data[done..]) {-                Ok(0) => break,-                Ok(count) => done += count,-                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,-                Err(_) => return None,-            }-        }-        data.truncate(done);-        Some(data)-    }-}--- a/veinsrs/src/store/reader.rs+++ /dev/null@@ -1,428 +0,0 @@-use std::fs::{self, File};-use std::path::{Path, PathBuf};-use std::sync::{Mutex, OnceLock};--use crate::encoding::Reader;-use crate::error::{Error, Result};-use crate::object::id::{Id, object_id};-use crate::object::view::{self, Operation, View};-use crate::object::{MAX_STORE_PACK_BYTES, TYPE_CHUNK, type_valid};-use crate::platform::{self, Mapping};-use crate::store::index::{self, Index};-use crate::store::layout;-use crate::store::pack::{self, Pack, record_limit};--type PromisorFetcher = Box<dyn Fn(&Path, Id) -> bool + Send + Sync>;--fn fetcher() -> &'static Mutex<Option<PromisorFetcher>> {-    static FETCHER: OnceLock<Mutex<Option<PromisorFetcher>>> = OnceLock::new();-    FETCHER.get_or_init(|| Mutex::new(None))-}--pub fn set_promisor_fetcher(value: Option<PromisorFetcher>) {-    if let Ok(mut slot) = fetcher().lock() {-        *slot = value;-    }-}--fn fetch_promised(root: &Path, id: Id) -> bool {-    let Ok(slot) = fetcher().lock() else {-        return false;-    };-    slot.as_ref().is_some_and(|fetch| fetch(root, id))-}--#[derive(Clone, Copy)]-pub struct Location {-    pub pack: usize,-    pub kind: u8,-    pub record_offset: u64,-    pub data_offset: u64,-    pub raw_len: u64,-    pub stored_len: u64,-    pub compression: u8,-}--fn read_at_into(file: &File, offset: u64, buffer: &mut [u8]) -> Option<usize> {-    let mut done = 0;-    while done < buffer.len() {-        match platform::read_at(file, &mut buffer[done..], offset + done as u64) {-            Ok(0) => break,-            Ok(count) => done += count,-            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,-            Err(_) => return None,-        }-    }-    Some(done)-}--struct PackFile {-    path: PathBuf,-    mtime_ns: u64,-    index: Option<Index>,-    file: Option<File>,-    map: Option<Mapping>,-}--pub struct Store {-    root: PathBuf,-    packs: Vec<PackFile>,-}--impl Store {-    pub fn open(root: &Path) -> Result<Self> {-        let mut store = Self {-            root: root.to_path_buf(),-            packs: Vec::new(),-        };-        store.refresh()?;-        Ok(store)-    }--    pub fn root(&self) -> &Path {-        &self.root-    }--    pub fn refresh(&mut self) -> Result<()> {-        let directory = layout::packs_dir(&self.root);-        let mut known = std::collections::HashSet::new();-        for pack in &self.packs {-            known.insert(pack.path.clone());-        }-        if let Ok(entries) = fs::read_dir(&directory) {-            for entry in entries.flatten() {-                let path = entry.path();-                if path.extension().and_then(|value| value.to_str()) != Some("vpack") {-                    continue;-                }-                if known.contains(&path) {-                    continue;-                }-                let mtime_ns = entry-                    .metadata()-                    .ok()-                    .map(|metadata| platform::mtime_ns(&metadata))-                    .unwrap_or(0);-                self.packs.push(PackFile {-                    path,-                    mtime_ns,-                    index: None,-                    file: None,-                    map: None,-                });-            }-        }-        self.packs.sort_by(|left, right| {-            right-                .mtime_ns-                .cmp(&left.mtime_ns)-                .then_with(|| left.path.cmp(&right.path))-        });-        Ok(())-    }--    fn ensure_index(&mut self, index: usize) -> bool {-        let pack = &mut self.packs[index];-        if pack.index.is_some() {-            return true;-        }-        let Some(name) = pack.path.file_name().and_then(|value| value.to_str()) else {-            return false;-        };-        if name.len() <= 6 {-            return false;-        }-        let stem = &name[..name.len() - 6];-        let index_path = pack.path.with_file_name(format!("{stem}.vidx"));-        let Some(data) = crate::core::read_file_opt(&index_path, MAX_STORE_PACK_BYTES) else {-            return false;-        };-        let Ok(decoded) = index::decode(&data, None) else {-            return false;-        };-        if stem != Id(decoded.pack_trailer).to_hex() {-            return false;-        }-        pack.index = Some(decoded);-        true-    }--    fn open_file(&mut self, index: usize) -> bool {-        let pack = &mut self.packs[index];-        if pack.file.is_some() {-            return true;-        }-        match File::open(&pack.path) {-            Ok(file) => {-                pack.file = Some(file);-                true-            }-            Err(_) => false,-        }-    }--    fn ensure_mapping(&mut self, index: usize) {-        let pack = &mut self.packs[index];-        if pack.map.is_none() {-            pack.map = Mapping::open(&pack.path);-        }-    }--    fn read_at_shared(-        &self,-        index: usize,-        offset: u64,-        length: usize,-    ) -> Option<std::borrow::Cow<'_, [u8]>> {-        if length as u64 > MAX_STORE_PACK_BYTES {-            return None;-        }-        let pack = self.packs.get(index)?;-        if let Some(map) = &pack.map {-            let data = map.as_slice();-            let start = usize::try_from(offset).ok()?;-            if start >= data.len() {-                return None;-            }-            let end = start.saturating_add(length).min(data.len());-            return Some(std::borrow::Cow::Borrowed(&data[start..end]));-        }-        let file = pack.file.as_ref()?;-        let mut data = vec![0u8; length];-        let done = read_at_into(file, offset, &mut data)?;-        data.truncate(done);-        Some(std::borrow::Cow::Owned(data))-    }--    fn record_at(&self, pack_index: usize, offset: u64, expected: Option<Id>) -> Option<Location> {-        let mut header_buffer = [0u8; 96];-        let header: &[u8] = {-            let pack = self.packs.get(pack_index)?;-            if let Some(map) = &pack.map {-                let data = map.as_slice();-                let start = usize::try_from(offset).ok()?;-                if start >= data.len() {-                    return None;-                }-                let end = start.saturating_add(header_buffer.len()).min(data.len());-                &data[start..end]-            } else {-                let file = pack.file.as_ref()?;-                let length = read_at_into(file, offset, &mut header_buffer)?;-                &header_buffer[..length]-            }-        };-        if header.len() < 34 {-            return None;-        }-        let mut reader = Reader::new(header);-        let id = reader.id().ok()?;-        let kind = reader.u8().ok()?;-        let compression = reader.u8().ok()?;-        let raw_len = reader.varint().ok()?;-        let stored_len = reader.varint().ok()?;-        if expected.is_some_and(|value| value != id) {-            return None;-        }-        if !type_valid(kind) || compression > 2 || raw_len == 0 {-            return None;-        }-        if raw_len > record_limit(kind) as u64 {-            return None;-        }-        if stored_len > record_limit(kind) as u64 + crate::object::MAX_CHUNK_LEN as u64 {-            return None;-        }-        if compression == 0 && raw_len != stored_len {-            return None;-        }-        Some(Location {-            pack: pack_index,-            kind,-            record_offset: offset,-            data_offset: offset + reader.offset() as u64,-            raw_len,-            stored_len,-            compression,-        })-    }--    fn find_loaded(&self, id: Id) -> Option<Location> {-        for index in 0..self.packs.len() {-            let Some(entry) = self.packs[index].index.as_ref() else {-                continue;-            };-            let Some(position) = entry.find(id) else {-                continue;-            };-            let offset = entry.entries[position].offset;-            if let Some(location) = self.record_at(index, offset, Some(id)) {-                return Some(location);-            }-        }-        None-    }--    pub fn find(&mut self, id: Id) -> Option<Location> {-        for index in 0..self.packs.len() {-            if !self.ensure_index(index) {-                continue;-            }-            let offset = {-                let Some(entry) = self.packs[index].index.as_ref() else {-                    continue;-                };-                let Some(position) = entry.find(id) else {-                    continue;-                };-                entry.entries[position].offset-            };-            if !self.open_file(index) {-                continue;-            }-            self.ensure_mapping(index);-            if let Some(location) = self.record_at(index, offset, Some(id)) {-                return Some(location);-            }-        }-        None-    }--    pub fn contains(&mut self, id: Id) -> bool {-        self.find(id).is_some()-    }--    fn get_at(&self, location: Location, depth: usize) -> Result<Vec<u8>> {-        if depth > 32 {-            return Err(Error::new("pack delta chain is too deep"));-        }-        let stored_len = usize::try_from(location.stored_len)-            .map_err(|_| Error::new("stored length overflow"))?;-        let stored = self-            .read_at_shared(location.pack, location.data_offset, stored_len)-            .ok_or_else(|| Error::new("cannot read pack record"))?;-        if stored.len() != stored_len {-            return Err(Error::new("pack record is truncated"));-        }-        let raw_len =-            usize::try_from(location.raw_len).map_err(|_| Error::new("raw length overflow"))?;-        match location.compression {-            0 => Ok(stored.into_owned()),-            1 => crate::store::pack::decompress(stored.as_ref(), raw_len),-            2 => {-                let mut reader = Reader::new(stored.as_ref());-                let base_offset = reader.varint()?;-                if base_offset >= location.record_offset {-                    return Err(Error::new("invalid pack delta base"));-                }-                let frame = reader.raw(reader.remaining())?;-                let base = self-                    .record_at(location.pack, base_offset, None)-                    .ok_or_else(|| Error::new("missing pack delta base"))?;-                let body = self.get_at(base, depth + 1)?;-                crate::store::pack::decompress_dict(frame, raw_len, &body)-            }-            _ => Err(Error::new("invalid pack compression")),-        }-    }--    pub fn get(&mut self, location: Location) -> Result<Vec<u8>> {-        if location.pack >= self.packs.len() {-            return Err(Error::new("pack location out of range"));-        }-        self.open_file(location.pack);-        self.ensure_mapping(location.pack);-        self.get_at(location, 0)-    }--    pub fn body(&mut self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {-        let mut location = self.find(id);-        if location.is_none() && expected == TYPE_CHUNK && fetch_promised(&self.root, id) {-            self.refresh()?;-            location = self.find(id);-        }-        let Some(location) = location else {-            return Ok(None);-        };-        if location.kind != expected {-            return Ok(None);-        }-        let body = self.get(location)?;-        if object_id(expected, &body) != id {-            return Ok(None);-        }-        Ok(Some(body))-    }--    pub fn body_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {-        let Some(location) = self.find_loaded(id) else {-            return Ok(None);-        };-        if location.kind != expected {-            return Ok(None);-        }-        let body = self.get_at(location, 0)?;-        if object_id(expected, &body) != id {-            return Ok(None);-        }-        Ok(Some(body))-    }--    /// Read a body without re-hashing it, for callers that only inspect contents.-    pub fn body_raw_loaded(&self, id: Id, expected: u8) -> Result<Option<Vec<u8>>> {-        let Some(location) = self.find_loaded(id) else {-            return Ok(None);-        };-        if location.kind != expected {-            return Ok(None);-        }-        Ok(Some(self.get_at(location, 0)?))-    }--    pub fn preload(&mut self) -> Result<()> {-        for index in 0..self.packs.len() {-            self.ensure_index(index);-            self.open_file(index);-            self.ensure_mapping(index);-        }-        Ok(())-    }--    pub fn view(&mut self, id: Id) -> Result<Option<View>> {-        let Some(body) = self.body(id, crate::object::TYPE_VIEW)? else {-            return Ok(None);-        };-        Ok(Some(view::decode_view(&body)?))-    }--    pub fn operation(&mut self, id: Id) -> Result<Option<Operation>> {-        let Some(body) = self.body(id, crate::object::TYPE_OPERATION)? else {-            return Ok(None);-        };-        Ok(Some(view::decode_operation(&body)?))-    }--    pub fn has_promisor(&self) -> bool {-        crate::core::read_file_opt(&layout::config_path(&self.root), 0)-            .is_some_and(|data| data.windows(8).any(|window| window == b"promisor"))-    }--    pub fn pack_count(&self) -> usize {-        self.packs.len()-    }--    pub fn pack_paths(&self) -> Vec<PathBuf> {-        self.packs.iter().map(|pack| pack.path.clone()).collect()-    }--    pub fn decode_pack(&self, index: usize) -> Result<Pack> {-        let path = self-            .packs-            .get(index)-            .map(|pack| pack.path.clone())-            .ok_or_else(|| Error::new("pack out of range"))?;-        let data = crate::core::read_file_opt(&path, MAX_STORE_PACK_BYTES)-            .ok_or_else(|| Error::new("cannot read pack"))?;-        pack::decode(data)-    }-}--- a/veinsrs/src/store/transaction.rs+++ /dev/null@@ -1,172 +0,0 @@-use std::path::{Path, PathBuf};--use crate::error::{Error, Result};-use crate::object::id::Id;-use crate::object::view::{Operation, TimeMs, View, encode_operation, encode_view};-use crate::object::{TYPE_OPERATION, TYPE_VIEW};-use crate::store::ops;-use crate::store::reader::Store;-use crate::store::writer::Writer;-use crate::time;--pub struct Txn {-    root: PathBuf,-    view: View,-    parents: Vec<Id>,-    start_ms: i64,-    writer: Writer,-}--impl Txn {-    pub fn begin(root: &Path, store: &mut Store) -> Result<Self> {-        let heads = ops::read_heads(root)?;-        let view = if heads.is_empty() {-            ops::empty_view()-        } else if heads.len() == 1 {-            load_view(store, heads[0])?-        } else {-            let mut merged = load_view(store, heads[0])?;-            for head in &heads[1..] {-                let extra = load_view(store, *head)?;-                merge_view_into(&mut merged, &extra);-            }-            ops::add_unique_head(&mut merged, heads[0]);-            merged-        };-        let mut view = view;-        ops::sort_view(&mut view);-        Ok(Self {-            root: root.to_path_buf(),-            view,-            parents: heads,-            start_ms: time::now_millis(),-            writer: Writer::default(),-        })-    }--    pub fn view(&self) -> &View {-        &self.view-    }--    pub fn view_mut(&mut self) -> &mut View {-        &mut self.view-    }--    pub fn writer(&mut self) -> &mut Writer {-        &mut self.writer-    }--    pub fn add_object(&mut self, kind: u8, body: Vec<u8>) -> Id {-        self.writer.add(kind, body)-    }--    pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {-        self.writer.add_known(kind, id, body)-    }--    pub fn finish(&mut self, description: &str) -> Result<Id> {-        let view = self.view.clone();-        self.finish_chain(vec![(view, description.to_string())])-    }--    pub fn finish_chain(&mut self, operations: Vec<(View, String)>) -> Result<Id> {-        if operations.is_empty() {-            return Err(Error::new("no operations to write"));-        }-        let mut parents = self.parents.clone();-        let mut last = Id::default();-        for (view, description) in operations {-            let mut view = view;-            ops::sort_view(&mut view);-            let view_body = encode_view(&view);-            let view_id = self.writer.add(TYPE_VIEW, view_body);-            let now = time::now_millis();-            let operation = Operation {-                parents,-                view: view_id,-                start: TimeMs {-                    millis: self.start_ms,-                    tz_min: 0,-                },-                end: TimeMs {-                    millis: now,-                    tz_min: 0,-                },-                hostname: host_name(),-                username: user_name(),-                description: description.as_bytes().to_vec(),-                tags: vec![(b"command".to_vec(), description.as_bytes().to_vec())],-            };-            let operation_body = encode_operation(&operation);-            last = self.writer.add(TYPE_OPERATION, operation_body);-            parents = vec![last];-        }-        if self.writer.finish(&self.root) != 0 {-            return Err(Error::new("failed to write object pack"));-        }-        ops::write_head(&self.root, last)?;-        for parent in &self.parents {-            ops::delete_head(&self.root, *parent)?;-        }-        Ok(last)-    }-}--fn load_view(store: &mut Store, head: Id) -> Result<View> {-    let operation = store-        .operation(head)?-        .ok_or_else(|| Error::new("cannot load operation state"))?;-    store-        .view(operation.view)?-        .ok_or_else(|| Error::new("cannot load view state"))-}--fn merge_view_into(target: &mut View, source: &View) {-    for head in &source.heads {-        ops::add_unique_head(target, *head);-    }-    for bookmark in &source.bookmarks {-        match ops::find_bookmark(target, &bookmark.name) {-            None => target.bookmarks.push(bookmark.clone()),-            Some(index) => {-                let existing = &mut target.bookmarks[index];-                let left = existing.targets.adds.first().copied().flatten();-                let right = bookmark.targets.adds.first().copied().flatten();-                if left != right || existing.targets.adds.len() != bookmark.targets.adds.len() {-                    existing.targets.adds = vec![left, right];-                    existing.targets.removes = vec![None];-                }-            }-        }-    }-    for tag in &source.tags {-        if !target.tags.iter().any(|value| value.name == tag.name) {-            target.tags.push(tag.clone());-        }-    }-    for workspace in &source.working_copies {-        if !target-            .working_copies-            .iter()-            .any(|value| value.workspace == workspace.workspace)-        {-            target.working_copies.push(workspace.clone());-        }-    }-}--fn host_name() -> Vec<u8> {-    std::env::var("HOSTNAME")-        .ok()-        .filter(|value| !value.is_empty())-        .unwrap_or_else(|| "localhost".to_string())-        .into_bytes()-}--fn user_name() -> Vec<u8> {-    std::env::var("USER")-        .ok()-        .filter(|value| !value.is_empty())-        .unwrap_or_else(|| "unknown".to_string())-        .into_bytes()-}--- a/veinsrs/src/store/writer.rs+++ /dev/null@@ -1,91 +0,0 @@-use std::collections::HashSet;-use std::path::Path;--use crate::object::id::{Id, object_id};-use crate::object::{RawObject, TYPE_CHUNK};-use crate::store::pack::{self, PackOutput};--// Commits favour latency; `vn repack` re-compresses the history afterwards.-const COMMIT_LEVEL: i32 = 2;--#[derive(Default)]-pub struct Writer {-    objects: Vec<RawObject>,-    cache: std::collections::HashMap<(u8, Id), usize>,-    seen: HashSet<Id>,-    cache_chunks: bool,-    limit: u64,-    raw_bytes: u64,-    quota_hit: bool,-}--impl Writer {-    pub fn enable_chunk_cache(&mut self) {-        self.cache_chunks = true;-    }--    pub fn set_limit(&mut self, limit: u64) {-        self.limit = limit;-    }--    pub fn quota_hit(&self) -> bool {-        self.quota_hit-    }--    pub fn objects(&self) -> &[RawObject] {-        &self.objects-    }--    fn should_accept(&mut self, id: Id, body: &[u8]) -> bool {-        if self.quota_hit || !self.seen.insert(id) {-            return false;-        }-        if self.limit > 0 && self.raw_bytes.saturating_add(body.len() as u64) > self.limit {-            self.quota_hit = true;-            return false;-        }-        self.raw_bytes = self.raw_bytes.saturating_add(body.len() as u64);-        true-    }--    pub fn add(&mut self, kind: u8, body: Vec<u8>) -> Id {-        let id = object_id(kind, &body);-        if !self.should_accept(id, &body) {-            return id;-        }-        if kind != TYPE_CHUNK || self.cache_chunks {-            self.cache.insert((kind, id), self.objects.len());-        }-        self.objects.push(RawObject::known(kind, id, body));-        id-    }--    pub fn add_known(&mut self, kind: u8, id: Id, body: Vec<u8>) -> Id {-        if !self.should_accept(id, &body) {-            return id;-        }-        if kind != TYPE_CHUNK || self.cache_chunks {-            self.cache.insert((kind, id), self.objects.len());-        }-        self.objects.push(RawObject::known(kind, id, body));-        id-    }--    pub fn find_cached(&self, kind: u8, id: Id) -> Option<&[u8]> {-        self.cache-            .get(&(kind, id))-            .and_then(|index| self.objects.get(*index))-            .map(|object| object.body.as_slice())-    }--    pub fn finish(&self, root: &Path) -> i32 {-        if self.quota_hit {-            return 2;-        }-        pack::write_pack(root, &self.objects, self.limit, COMMIT_LEVEL)-    }--    pub fn encode_finish(&self) -> PackOutput {-        pack::encode(&self.objects, COMMIT_LEVEL)-    }-}--- a/veinsrs/src/time.rs+++ /dev/null@@ -1,47 +0,0 @@-use std::time::{SystemTime, UNIX_EPOCH};--pub fn now_millis() -> i64 {-    SystemTime::now()-        .duration_since(UNIX_EPOCH)-        .map(|duration| duration.as_millis() as i64)-        .unwrap_or(0)-}--pub fn now_seconds() -> i64 {-    SystemTime::now()-        .duration_since(UNIX_EPOCH)-        .map(|duration| duration.as_secs() as i64)-        .unwrap_or(0)-}--fn floor_div(value: i64, divisor: i64) -> i64 {-    let quotient = value / divisor;-    let remainder = value % divisor;-    if remainder != 0 && (remainder < 0) != (divisor < 0) {-        quotient - 1-    } else {-        quotient-    }-}--pub fn format_utc(seconds: i64) -> String {-    let days = floor_div(seconds, 86_400);-    let remainder = seconds - days * 86_400;-    let hour = remainder / 3_600;-    let minute = (remainder % 3_600) / 60;-    let second = remainder % 60;--    let z = days + 719_468;-    let era = floor_div(z, 146_097);-    let doe = z - era * 146_097;-    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;-    let y0 = yoe + era * 400;-    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);-    let mp = (5 * doy + 2) / 153;-    let day = doy - (153 * mp + 2) / 5 + 1;-    let month0 = mp + 3;-    let month = if mp >= 10 { mp - 9 } else { month0 };-    let year = if month <= 2 { y0 + 1 } else { y0 };--    format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}")-}--- a/veinsrs/src/worktree/attributes.rs+++ /dev/null@@ -1,223 +0,0 @@-use std::path::Path;--use crate::core;--#[derive(Clone, Copy, PartialEq, Eq)]-pub enum AttributeEol {-    None,-    Lf,-    Crlf,-    Cr,-}--#[derive(Clone, Copy, PartialEq, Eq)]-pub enum AttributeText {-    Auto,-    Text,-    Binary,-}--#[derive(Clone, Copy)]-pub struct PathAttributes {-    pub generated: bool,-    pub text: AttributeText,-    pub eol: AttributeEol,-}--impl Default for PathAttributes {-    fn default() -> Self {-        Self {-            generated: false,-            text: AttributeText::Auto,-            eol: AttributeEol::None,-        }-    }-}--#[derive(Clone)]-struct Rule {-    pattern: String,-    has_slash: bool,-    generated_set: bool,-    generated: bool,-    text_set: bool,-    text: AttributeText,-    eol_set: bool,-    eol: AttributeEol,-}--#[derive(Clone, Default)]-pub struct AttributeRules {-    rules: Vec<Rule>,-    mtime_ns: i64,-}--fn next_token<'a>(text: &'a str, position: &mut usize) -> &'a str {-    while *position < text.len() && matches!(text.as_bytes()[*position], b' ' | b'\t') {-        *position += 1;-    }-    let start = *position;-    while *position < text.len() && !matches!(text.as_bytes()[*position], b' ' | b'\t') {-        *position += 1;-    }-    &text[start..*position]-}--fn basename(path: &str) -> &str {-    path.rsplit_once('/').map(|(_, name)| name).unwrap_or(path)-}--fn rule_matches(pattern: &str, has_slash: bool, path: &str) -> bool {-    core::glob_match(pattern, path) || (!has_slash && core::glob_match(pattern, basename(path)))-}--fn parse_eol(value: &str) -> AttributeEol {-    match value {-        "lf" => AttributeEol::Lf,-        "crlf" => AttributeEol::Crlf,-        "cr" => AttributeEol::Cr,-        _ => AttributeEol::None,-    }-}--impl AttributeRules {-    pub fn load(root: &Path) -> Self {-        let mut rules = Self::default();-        let path = root.join(".vnattribs");-        if let Some(info) = core::stat_path(&path) {-            rules.mtime_ns = info.mtime_ns as i64;-        }-        let Some(data) = core::read_file_opt(&path, 0) else {-            return rules;-        };-        let text = String::from_utf8_lossy(&data);-        for raw in text.lines() {-            let line = core::trim_str(raw);-            if line.is_empty() || line.starts_with('#') {-                continue;-            }-            let mut position = 0;-            let pattern = next_token(line, &mut position);-            if pattern.is_empty() {-                continue;-            }-            let mut rule = Rule {-                pattern: pattern.to_string(),-                has_slash: pattern.contains('/'),-                generated_set: false,-                generated: false,-                text_set: false,-                text: AttributeText::Auto,-                eol_set: false,-                eol: AttributeEol::None,-            };-            while position < line.len() {-                let token = next_token(line, &mut position);-                if token.is_empty() {-                    break;-                }-                match token {-                    "gen" => {-                        rule.generated_set = true;-                        rule.generated = true;-                    }-                    "-gen" => {-                        rule.generated_set = true;-                        rule.generated = false;-                    }-                    "txt" => {-                        rule.text_set = true;-                        rule.text = AttributeText::Text;-                    }-                    "bin" => {-                        rule.text_set = true;-                        rule.text = AttributeText::Binary;-                    }-                    "-txt" | "-bin" => {-                        rule.text_set = true;-                        rule.text = AttributeText::Auto;-                    }-                    "-eol" => {-                        rule.eol_set = true;-                        rule.eol = AttributeEol::None;-                    }-                    value if value.starts_with("eol:") => {-                        let value = &value[4..];-                        if matches!(value, "lf" | "crlf" | "cr") {-                            rule.eol_set = true;-                            rule.eol = parse_eol(value);-                        }-                    }-                    _ => {}-                }-            }-            rules.rules.push(rule);-        }-        rules-    }--    pub fn lookup(&self, path: &str) -> PathAttributes {-        let mut attributes = PathAttributes::default();-        for rule in &self.rules {-            if !rule_matches(&rule.pattern, rule.has_slash, path) {-                continue;-            }-            if rule.generated_set {-                attributes.generated = rule.generated;-            }-            if rule.text_set {-                attributes.text = rule.text;-            }-            if rule.eol_set {-                attributes.eol = rule.eol;-            }-        }-        attributes-    }--    pub fn changed_since(&self, cache_written_ms: i64) -> bool {-        if cache_written_ms <= 0 {-            return true;-        }-        if self.mtime_ns == 0 {-            return false;-        }-        self.mtime_ns > cache_written_ms * 1_000_000-    }-}--pub fn normalize_eol(data: &[u8], eol: AttributeEol) -> Vec<u8> {-    let (first, second) = match eol {-        AttributeEol::None => return data.to_vec(),-        AttributeEol::Lf => (b'\n', 0),-        AttributeEol::Crlf => (b'\r', b'\n'),-        AttributeEol::Cr => (b'\r', 0),-    };-    let mut output = Vec::with_capacity(data.len());-    let mut index = 0;-    while index < data.len() {-        let byte = data[index];-        if byte == b'\r' {-            if index + 1 < data.len() && data[index + 1] == b'\n' {-                index += 1;-            }-            output.push(first);-            if second != 0 {-                output.push(second);-            }-        } else if byte == b'\n' {-            output.push(first);-            if second != 0 {-                output.push(second);-            }-        } else {-            output.push(byte);-        }-        index += 1;-    }-    output-}--pub fn attributes_of<'a>(rules: &'a AttributeRules, path: &[u8]) -> PathAttributes {-    rules.lookup(&String::from_utf8_lossy(path))-}--- a/veinsrs/src/worktree/checkout.rs+++ /dev/null@@ -1,568 +0,0 @@-use std::fs;-use std::path::{Path, PathBuf};--use rayon::prelude::*;--use crate::core;-use crate::error::{Error, Result};-use crate::object::conflict::{self, Conflict, ConflictValue};-use crate::object::id::Id;-use crate::object::path::valid_checkout_path;-use crate::object::tree::{self, FlatEntry};-use crate::platform;-use crate::store::Txn;-use crate::store::graph;-use crate::store::layout;-use crate::store::ops;-use crate::store::reader::Store;-use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText};-use crate::worktree::snapshot;-use crate::worktree::stat_cache::{self, CacheEntry};--pub fn run(root: &Path, revision: &str) -> Result<()> {-    let mut store = Store::open(root)?;-    snapshot::run_with(root, &mut store)?;--    let view = ops::current_view(root, &mut store)?-        .ok_or_else(|| Error::new("no operation state; import a repository first"))?;-    let target = graph::resolve_revision(&mut store, &view, revision)?-        .ok_or_else(|| Error::new(format!("unknown revision: {revision}")))?;-    let target_commit =-        graph::load_commit(&mut store, target)?.ok_or_else(|| Error::new("cannot read commit"))?;--    let bookmark_checkout = !revision.is_empty()-        && revision != "@"-        && ops::find_bookmark(&view, revision.as_bytes()).is_some();-    let detach_bookmark = !revision.is_empty() && revision != "@" && !bookmark_checkout;--    let working_copy = ops::working_copy_id(&view);-    let old_root = match working_copy {-        Some(id) => graph::load_commit(&mut store, id)?.map(|commit| commit.root_tree),-        None => None,-    };--    if old_root != Some(target_commit.root_tree) {-        materialize(root, &mut store, old_root, target_commit.root_tree)?;-    }--    if working_copy != Some(target) {-        let already_empty_child = match working_copy {-            Some(id) => graph::load_commit(&mut store, id)?.is_some_and(|commit| {-                commit.parents.len() == 1-                    && commit.parents[0] == target-                    && commit.root_tree == target_commit.root_tree-                    && commit.message.is_empty()-            }),-            None => false,-        };-        if !already_empty_child {-            let mut txn = Txn::begin(root, &mut store)?;-            if let Some(old_id) = working_copy {-                ops::remove_head(txn.view_mut(), old_id);-            }-            let child = create_working_copy_commit(&mut txn, &mut store, target)?;-            ops::set_workspace(txn.view_mut(), child);-            ops::rebuild_heads(txn.view_mut());-            txn.finish("checkout")?;-        }-    }-    if bookmark_checkout {-        core::set_current_bookmark(root, revision);-    } else if detach_bookmark {-        core::clear_current_bookmark(root);-    }-    Ok(())-}--fn create_working_copy_commit(txn: &mut Txn, store: &mut Store, parent: Id) -> Result<Id> {-    let loaded = graph::load_commit(store, parent)?-        .ok_or_else(|| Error::new("cannot read parent commit"))?;-    let signature = crate::identity::signature(store.root());-    let commit = crate::object::commit::Commit {-        version: 1,-        parents: vec![parent],-        root_tree: loaded.root_tree,-        change_id: crate::identity::random_change_id(),-        author: signature.clone(),-        committer: signature,-        message: Vec::new(),-        renames_state: crate::object::commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    Ok(txn.add_object(-        crate::object::TYPE_COMMIT,-        crate::object::commit::encode(&commit),-    ))-}--fn sidecar_suffixes() -> Vec<String> {-    let mut suffixes = vec![-        ".base".to_string(),-        ".ours".to_string(),-        ".theirs".to_string(),-    ];-    for number in 2..=64 {-        suffixes.push(format!(".base{number}"));-        suffixes.push(format!(".theirs{number}"));-    }-    suffixes-}--fn remove_any(path: &Path) -> Result<()> {-    let metadata = fs::symlink_metadata(path)?;-    if metadata.is_dir() && !metadata.file_type().is_symlink() {-        fs::remove_dir_all(path)?;-    } else {-        fs::remove_file(path)?;-    }-    Ok(())-}--fn prune_empty_parents(root: &Path, relative: &[u8]) -> Result<()> {-    let mut end = relative.len();-    while end > 0 {-        let Some(position) = relative[..end].iter().rposition(|byte| *byte == b'/') else {-            break;-        };-        let path = root.join(core::path_from_bytes(&relative[..position]));-        if fs::remove_dir(&path).is_err() {-            break;-        }-        end = position;-    }-    Ok(())-}--fn remove_tracked_path(root: &Path, relative: &[u8]) -> Result<()> {-    let path = root.join(core::path_from_bytes(relative));-    match fs::symlink_metadata(&path) {-        Ok(_) => {-            remove_any(&path)?;-            prune_empty_parents(root, relative)?;-        }-        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}-        Err(error) => return Err(error.into()),-    }-    Ok(())-}--fn delete_sidecars(root: &Path, path: &[u8]) -> Result<()> {-    for suffix in sidecar_suffixes() {-        let mut full = path.to_vec();-        full.extend_from_slice(suffix.as_bytes());-        remove_tracked_path(root, &full)?;-    }-    Ok(())-}--fn has_symlink_component(root: &Path, relative: &[u8]) -> bool {-    let mut current = root.to_path_buf();-    let mut start = 0;-    for index in 0..relative.len() {-        if relative[index] != b'/' {-            continue;-        }-        if index == start {-            return true;-        }-        current = current.join(core::path_from_bytes(&relative[start..index]));-        if core::stat_path(&current).is_some_and(|info| info.kind == 3) {-            return true;-        }-        start = index + 1;-    }-    false-}--fn ensure_safe_dirs(root: &Path, relative: &[u8]) -> Result<()> {-    if relative.is_empty() {-        return Ok(());-    }-    let mut current = root.to_path_buf();-    let mut start = 0;-    for index in 0..=relative.len() {-        let at_end = index == relative.len();-        if !at_end && relative[index] != b'/' {-            continue;-        }-        let component = &relative[start..index];-        if component.is_empty() {-            return Err(Error::new("empty path component"));-        }-        if at_end {-            break;-        }-        current = current.join(core::path_from_bytes(component));-        match fs::symlink_metadata(&current) {-            Ok(metadata) => {-                if metadata.file_type().is_symlink() || !metadata.is_dir() {-                    return Err(Error::new("unsafe path component"));-                }-            }-            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {-                fs::create_dir(&current)?;-            }-            Err(error) => return Err(error.into()),-        }-        start = index + 1;-    }-    Ok(())-}--fn write_bytes(root: &Path, relative: &[u8], data: &[u8], executable: bool) -> Result<()> {-    if !valid_checkout_path(relative) || has_symlink_component(root, relative) {-        return Err(Error::new(format!(-            "invalid checkout path: {}",-            String::from_utf8_lossy(relative)-        )));-    }-    ensure_safe_dirs(root, relative)?;-    let path = root.join(core::path_from_bytes(relative));-    if let Ok(metadata) = fs::symlink_metadata(&path) {-        if metadata.is_dir() && !metadata.file_type().is_symlink() {-            return Err(Error::new("checkout path collides with a directory"));-        }-        if metadata.file_type().is_symlink() {-            fs::remove_file(&path)?;-        }-    }-    if !core::write_file(&path, data) {-        return Err(Error::new("cannot write checkout file"));-    }-    let mode = if executable { 0o755 } else { 0o644 };-    platform::set_mode(&path, mode)?;-    Ok(())-}--fn write_symlink(root: &Path, relative: &[u8], target: &[u8]) -> Result<()> {-    if !valid_checkout_path(relative) || has_symlink_component(root, relative) {-        return Err(Error::new("invalid checkout path"));-    }-    ensure_safe_dirs(root, relative)?;-    let path = root.join(core::path_from_bytes(relative));-    if let Ok(metadata) = fs::symlink_metadata(&path) {-        if metadata.is_dir() && !metadata.file_type().is_symlink() {-            return Err(Error::new("checkout path collides with a directory"));-        }-        remove_any(&path)?;-    }-    platform::create_symlink(&core::path_from_bytes(target), &path)?;-    Ok(())-}--fn write_entry(-    store: &Store,-    root: &Path,-    entry: &FlatEntry,-    attributes: &AttributeRules,-) -> Result<()> {-    let data =-        graph::read_blob_loaded(store, entry.target)?.ok_or_else(|| Error::new("missing blob"))?;-    if entry.kind == tree::KIND_SYMLINK {-        return write_symlink(root, &entry.path, &data);-    }-    let path_attributes = attributes.lookup(&String::from_utf8_lossy(&entry.path));-    if path_attributes.eol != AttributeEol::None && path_attributes.text != AttributeText::Binary {-        let normalized = attributes::normalize_eol(&data, path_attributes.eol);-        write_bytes(-            root,-            &entry.path,-            &normalized,-            entry.kind == tree::KIND_EXECUTABLE,-        )-    } else {-        write_bytes(-            root,-            &entry.path,-            &data,-            entry.kind == tree::KIND_EXECUTABLE,-        )-    }-}--fn delete_stale(root: &Path, old_entries: &[FlatEntry], new_entries: &[FlatEntry]) -> Result<()> {-    for entry in old_entries {-        if entry.kind == tree::KIND_SUBMODULE {-            continue;-        }-        if tree::find_flat(new_entries, &entry.path).is_some() {-            continue;-        }-        remove_tracked_path(root, &entry.path)?;-        if entry.kind == tree::KIND_CONFLICT {-            delete_sidecars(root, &entry.path)?;-        }-    }-    Ok(())-}--fn load_conflict(store: &mut Store, id: Id) -> Result<Option<Conflict>> {-    let Some(body) = store.body(id, crate::object::TYPE_CONFLICT)? else {-        return Ok(None);-    };-    Ok(Some(conflict::decode(&body)?))-}--fn write_tree_side(-    store: &mut Store,-    root: &Path,-    tree_id: Id,-    prefix: &[u8],-    attributes: &AttributeRules,-) -> Result<()> {-    let entries = tree::flatten(store, tree_id)?;-    for entry in entries {-        if entry.kind == tree::KIND_CONFLICT || entry.kind == tree::KIND_SUBMODULE {-            continue;-        }-        let path = crate::object::path::join(prefix, &entry.path);-        write_entry(store, root, &FlatEntry { path, ..entry }, attributes)?;-    }-    Ok(())-}--fn materialize_value(-    store: &mut Store,-    root: &Path,-    path: &[u8],-    value: &ConflictValue,-    attributes: &AttributeRules,-) -> Result<()> {-    if value.kind == 0 {-        return remove_tracked_path(root, path);-    }-    let target = value-        .target-        .ok_or_else(|| Error::new("conflict value has no target"))?;-    if value.kind == tree::KIND_SUBTREE {-        remove_tracked_path(root, path)?;-        return write_tree_side(store, root, target, path, attributes);-    }-    write_entry(-        store,-        root,-        &FlatEntry {-            path: path.to_vec(),-            kind: value.kind,-            target,-        },-        attributes,-    )-}--fn materialize_conflict(-    store: &mut Store,-    root: &Path,-    path: &[u8],-    target: Id,-    attributes: &AttributeRules,-) -> Result<()> {-    let conflict =-        load_conflict(store, target)?.ok_or_else(|| Error::new("cannot read conflict value"))?;-    for (index, value) in conflict.removes.iter().enumerate() {-        let suffix = if index == 0 {-            ".base".to_string()-        } else {-            format!(".base{}", index + 1)-        };-        let mut full = path.to_vec();-        full.extend_from_slice(suffix.as_bytes());-        materialize_value(store, root, &full, value, attributes)?;-    }-    for (index, value) in conflict.adds.iter().enumerate() {-        let suffix = match index {-            0 => ".ours".to_string(),-            1 => ".theirs".to_string(),-            _ => format!(".theirs{}", index + 1),-        };-        let mut full = path.to_vec();-        full.extend_from_slice(suffix.as_bytes());-        materialize_value(store, root, &full, value, attributes)?;-    }-    if let Some(first) = conflict.adds.first() {-        materialize_value(store, root, path, first, attributes)?;-    } else {-        remove_tracked_path(root, path)?;-    }-    Ok(())-}--fn save_checkout_cache(root: &Path, entries: &[FlatEntry]) -> Result<()> {-    let now_ms = crate::time::now_millis();-    let mut cache = Vec::new();-    for entry in entries {-        if !matches!(-            entry.kind,-            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK-        ) {-            continue;-        }-        let Some(info) = core::stat_path(&root.join(core::path_from_bytes(&entry.path))) else {-            continue;-        };-        cache.push(CacheEntry {-            path: entry.path.clone(),-            size: info.size,-            mtime_ns: info.mtime_ns,-            inode: info.inode,-            kind: info.kind,-            executable: info.executable,-            target: entry.target,-            trusted: true,-        });-    }-    stat_cache::save(root, &mut cache, now_ms)-}--pub fn materialize(-    root: &Path,-    store: &mut Store,-    old_root: Option<Id>,-    new_root: Id,-) -> Result<()> {-    materialize_with_progress(root, store, old_root, new_root, None)-}--pub fn materialize_with_progress(-    root: &Path,-    store: &mut Store,-    old_root: Option<Id>,-    new_root: Id,-    progress: Option<&core::Progress>,-) -> Result<()> {-    if old_root == Some(new_root) {-        return Ok(());-    }-    let old_entries = match old_root {-        Some(id) => tree::flatten(store, id)?,-        None => Vec::new(),-    };-    let attributes = AttributeRules::load(root);-    let new_entries = tree::flatten(store, new_root)?;--    let mut directories: Vec<Vec<u8>> = Vec::new();-    let mut files: Vec<FlatEntry> = Vec::new();-    let mut conflicts: Vec<FlatEntry> = Vec::new();-    for entry in &new_entries {-        if !valid_checkout_path(&entry.path) {-            return Err(Error::new(format!(-                "checkout tree validation failed at: {}",-                String::from_utf8_lossy(&entry.path)-            )));-        }-        let mut start = 0;-        for index in 0..entry.path.len() {-            if entry.path[index] == b'/' {-                directories.push(entry.path[start..index].to_vec());-                start = index + 1;-            }-        }-        match entry.kind {-            tree::KIND_CONFLICT => conflicts.push(entry.clone()),-            tree::KIND_FILE | tree::KIND_EXECUTABLE | tree::KIND_SYMLINK => {-                files.push(entry.clone())-            }-            _ => {}-        }-    }--    let suffixes = sidecar_suffixes();-    for conflict in &conflicts {-        for suffix in &suffixes {-            let mut full = conflict.path.clone();-            full.extend_from_slice(suffix.as_bytes());-            if tree::find_flat(&old_entries, &full).is_some() {-                return Err(Error::new(format!(-                    "conflict sidecar would overwrite a tracked path: {}",-                    String::from_utf8_lossy(&full)-                )));-            }-        }-    }--    for entry in &old_entries {-        if entry.kind == tree::KIND_CONFLICT {-            delete_sidecars(root, &entry.path)?;-        }-    }--    delete_stale(root, &old_entries, &new_entries)?;-    for directory in &directories {-        ensure_safe_dirs(root, directory)?;-    }-    ensure_safe_dirs(root, b"")?;--    store.preload()?;-    if let Some(progress) = progress-        && (!files.is_empty() || !conflicts.is_empty())-    {-        progress.set_total(files.len() + conflicts.len());-    }-    let write_all = |entry: &FlatEntry| -> Result<()> {-        write_entry(store, root, entry, &attributes)?;-        if let Some(progress) = progress {-            progress.advance(1);-        }-        Ok(())-    };-    let written = if std::thread::available_parallelism().map_or(false, |n| n.get() > 1) {-        files.par_iter().try_for_each(write_all)-    } else {-        files.iter().try_for_each(write_all)-    };-    if let Err(error) = written {-        if let Some(progress) = progress {-            progress.clear();-        }-        return Err(error);-    }-    for conflict in &conflicts {-        if let Err(error) =-            materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)-        {-            if let Some(progress) = progress {-                progress.clear();-            }-            return Err(error);-        }-        if let Some(progress) = progress {-            progress.advance(1);-        }-    }--    save_checkout_cache(root, &new_entries)?;-    if let Some(progress) = progress {-        progress.finish();-    }-    println!("info: checked out {} files", files.len());-    Ok(())-}--pub fn materialize_optional(-    root: &Path,-    store: &mut Store,-    old_root: Option<Id>,-    new_root: Option<Id>,-) -> Result<()> {-    match new_root {-        Some(new_root) => materialize(root, store, old_root, new_root),-        None => {-            let old_entries = match old_root {-                Some(id) => tree::flatten(store, id)?,-                None => Vec::new(),-            };-            delete_stale(root, &old_entries, &[])?;-            clear_stat_cache(root);-            Ok(())-        }-    }-}--pub fn clear_stat_cache(root: &Path) {-    let _ = fs::remove_file(layout::working_copy_dir(root).join("stat-cache"));-}--pub fn path_buf(bytes: &[u8]) -> PathBuf {-    core::path_from_bytes(bytes)-}--- a/veinsrs/src/worktree/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod attributes;-pub mod checkout;-pub mod pathspec;-pub mod snapshot;-pub mod stat_cache;--- a/veinsrs/src/worktree/pathspec.rs+++ /dev/null@@ -1,73 +0,0 @@-use std::path::Path;--use crate::core;--pub fn cwd_relative(root: &Path) -> Option<String> {-    let current = std::env::current_dir().ok()?;-    let current = std::fs::canonicalize(current).ok()?;-    let root = std::fs::canonicalize(root).ok()?;-    if current == root {-        return Some(String::new());-    }-    let relative = current.strip_prefix(&root).ok()?;-    Some(String::from_utf8_lossy(&core::path_to_bytes(relative)).into_owned())-}--fn normalize_components(input: &str) -> Option<String> {-    let mut components: Vec<&str> = Vec::new();-    let mut start = 0;-    for index in 0..=input.len() {-        let at_end = index == input.len();-        if !at_end && input.as_bytes()[index] != b'/' {-            continue;-        }-        let component = &input[start..index];-        if !component.is_empty() && component != "." {-            if component == ".." {-                if components.is_empty() {-                    return None;-                }-                components.pop();-            } else {-                components.push(component);-            }-        }-        start = index + 1;-    }-    Some(components.join("/"))-}--fn join_relative(base: &str, argument: &str) -> String {-    if base.is_empty() {-        argument.to_string()-    } else if argument.is_empty() {-        base.to_string()-    } else {-        format!("{base}/{argument}")-    }-}--pub fn pathspec_normalize(root: &Path, cwd_rel: &str, argument: &str) -> Option<String> {-    if argument.is_empty() {-        return None;-    }-    if argument.starts_with('/') {-        let normalized = normalize_components(argument)?;-        let mut root_view = core::path_display(root);-        if root_view.starts_with('/') {-            root_view.remove(0);-        }-        if normalized.len() > root_view.len()-            && normalized.starts_with(&root_view)-            && normalized.as_bytes()[root_view.len()] == b'/'-        {-            return Some(normalized[root_view.len() + 1..].to_string());-        }-        return None;-    }-    normalize_components(&join_relative(cwd_rel, argument))-}--pub fn pathspec_has_glob(value: &str) -> bool {-    value.contains('*') || value.contains('?')-}--- a/veinsrs/src/worktree/snapshot.rs+++ /dev/null@@ -1,624 +0,0 @@-use std::path::{Path, PathBuf};--use rayon::prelude::*;--use crate::core::{self, IgnoreRules};-use crate::error::{Error, Result};-use crate::identity;-use crate::object::blob;-use crate::object::commit::{self, Commit, Rename};-use crate::object::id::Id;-use crate::object::path;-use crate::object::tree::{self, FlatEntry, KIND_CONFLICT, KIND_SUBTREE, TreeEntry};-use crate::object::{TYPE_COMMIT, TYPE_TREE};-use crate::store::Txn;-use crate::store::graph;-use crate::store::ops;-use crate::store::reader::Store;-use crate::store::writer::Writer;-use crate::time;-use crate::worktree::attributes::{self, AttributeEol, AttributeRules, AttributeText};-use crate::worktree::stat_cache::{self, Cache, CacheEntry};--pub fn run(root: &Path) -> Result<bool> {-    let mut store = Store::open(root)?;-    run_with(root, &mut store)-}--fn name_ends_with(name: &[u8], suffix: &[u8]) -> bool {-    name.len() >= suffix.len() && &name[name.len() - suffix.len()..] == suffix-}--fn sidecar_base(name: &[u8]) -> Option<Vec<u8>> {-    if name_ends_with(name, b".base") && name.len() > 5 {-        return Some(name[..name.len() - 5].to_vec());-    }-    if name_ends_with(name, b".ours") && name.len() > 5 {-        return Some(name[..name.len() - 5].to_vec());-    }-    if name_ends_with(name, b".theirs") && name.len() > 7 {-        return Some(name[..name.len() - 7].to_vec());-    }-    let mut digits = 0;-    while digits < name.len() && name[name.len() - 1 - digits].is_ascii_digit() {-        digits += 1;-    }-    if digits > 0 {-        let stem = &name[..name.len() - digits];-        if stem.len() > 5 && name_ends_with(stem, b".base") {-            return Some(stem[..stem.len() - 5].to_vec());-        }-        if stem.len() > 7 && name_ends_with(stem, b".theirs") {-            return Some(stem[..stem.len() - 7].to_vec());-        }-    }-    None-}--fn join_rel(base: &[u8], name: &[u8]) -> Vec<u8> {-    path::join(base, name)-}--struct BuildState {-    failed: bool,-}--enum PlanKind {-    Conflict,-    Directory,-    Symlink,-    File,-}--struct Plan {-    kind: PlanKind,-    name: Vec<u8>,-    rel: Vec<u8>,-    path: PathBuf,-    info: core::StatInfo,-    target: Option<Id>,-    child_old: Option<Id>,-    executable: bool,-    needs_read: bool,-    trusted: bool,-}--fn build_dir(-    txn: &mut Txn,-    store: &mut Store,-    root: &Path,-    base: &[u8],-    old_tree_id: Option<Id>,-    base_rules: &IgnoreRules,-    attributes: &AttributeRules,-    cache_valid: bool,-    cache: &Cache,-    new_cache: &mut Vec<CacheEntry>,-    now_ms: i64,-    state: &mut BuildState,-    depth: usize,-) -> Result<Option<Id>> {-    if depth > crate::object::MAX_TREE_DEPTH {-        state.failed = true;-        return Ok(None);-    }--    let mut local = base_rules.clone();-    let base_text = String::from_utf8_lossy(base);-    core::ignore_load_file(&mut local, root, &base_text, ".vnexclude");-    core::ignore_load_file(&mut local, root, &base_text, ".gitignore");--    let old_tree = match old_tree_id {-        Some(id) => {-            let body = store.body(id, TYPE_TREE)?.ok_or_else(|| {-                Error::new(format!(-                    "missing tree {} at {}",-                    id.to_hex(),-                    String::from_utf8_lossy(base)-                ))-            })?;-            match tree::decode(&body).ok() {-                Some(tree) => Some(tree),-                None => {-                    state.failed = true;-                    return Ok(None);-                }-            }-        }-        None => None,-    };--    let directory = if base.is_empty() {-        root.to_path_buf()-    } else {-        root.join(core::path_from_bytes(base))-    };-    if !directory.is_dir() {-        state.failed = true;-        return Ok(None);-    }--    let mut names = core::list_directory(&directory);-    names.sort();--    let infos: Vec<Option<core::StatInfo>> = if names.len() >= 256 {-        names-            .par_iter()-            .map(|name| core::stat_path(&directory.join(core::path_from_bytes(name))))-            .collect()-    } else {-        names-            .iter()-            .map(|name| core::stat_path(&directory.join(core::path_from_bytes(name))))-            .collect()-    };--    let mut plans: Vec<Plan> = Vec::with_capacity(names.len());-    for (index, name) in names.iter().enumerate() {-        if name == b".veins" || name == b".git" {-            continue;-        }-        let Some(info) = infos[index] else {-            continue;-        };-        if let Some(tree) = &old_tree-            && let Some(sidecar) = sidecar_base(name)-        {-            if let Some(found) = tree::find_entry(tree, &sidecar) {-                if tree.entries[found].kind == KIND_CONFLICT {-                    continue;-                }-            }-        }-        let relative = join_rel(base, name);-        let relative_text = String::from_utf8_lossy(&relative);-        let is_dir = info.kind == 2;-        let ignored = core::ignore_ignored(&local, &relative_text, is_dir);-        let old_index = old_tree-            .as_ref()-            .and_then(|tree| tree::find_entry(tree, name));-        if let (Some(found), Some(tree)) = (old_index, old_tree.as_ref())-            && tree.entries[found].kind == KIND_CONFLICT-        {-            plans.push(Plan {-                kind: PlanKind::Conflict,-                name: name.clone(),-                rel: relative,-                path: directory.join(core::path_from_bytes(name)),-                info,-                target: Some(tree.entries[found].target),-                child_old: None,-                executable: false,-                needs_read: false,-                trusted: false,-            });-            continue;-        }-        if ignored && old_index.is_none() {-            continue;-        }-        let mut plan = Plan {-            kind: if is_dir {-                PlanKind::Directory-            } else if info.kind == 3 {-                PlanKind::Symlink-            } else {-                PlanKind::File-            },-            name: name.clone(),-            rel: relative,-            path: directory.join(core::path_from_bytes(name)),-            info,-            target: None,-            child_old: None,-            executable: info.executable,-            needs_read: false,-            trusted: false,-        };-        if is_dir {-            if let (Some(found), Some(tree)) = (old_index, old_tree.as_ref()) {-                let entry = &tree.entries[found];-                if entry.kind == KIND_SUBTREE {-                    plan.child_old = Some(entry.target);-                }-            }-        } else if info.kind == 1 {-            if cache_valid-                && let Some(entry) = stat_cache::lookup(cache, &plan.rel)-                && stat_cache::matches(entry, &plan.info, plan.executable, now_ms, cache.written_ms)-            {-                plan.target = Some(entry.target);-                plan.trusted = entry.trusted;-            }-            plan.needs_read = plan.target.is_none();-        }-        plans.push(plan);-    }--    let jobs: Vec<usize> = plans-        .iter()-        .enumerate()-        .filter(|(_, plan)| matches!(plan.kind, PlanKind::File) && plan.needs_read)-        .map(|(index, _)| index)-        .collect();-    let job_bytes: u64 = jobs.iter().map(|index| plans[*index].info.size).sum();--    // Spinning up rayon costs more than it saves for the small, common case;-    // only parallelise once there is enough hashing work to amortise it.-    const PARALLEL_HASH_MIN_BYTES: u64 = 32 * 1024 * 1024;-    let built: Vec<Option<(blob::BlobBuild, bool)>> = if job_bytes >= PARALLEL_HASH_MIN_BYTES {-        jobs.par_iter()-            .map(|index| read_build(&plans[*index], attributes))-            .collect()-    } else {-        jobs.iter()-            .map(|index| read_build(&plans[*index], attributes))-            .collect()-    };--    for (job, build) in jobs.iter().zip(built) {-        let Some((build, trusted)) = build else {-            state.failed = true;-            return Ok(None);-        };-        for object in build.objects {-            txn.add_known(object.kind, object.id, object.body);-        }-        plans[*job].target = Some(build.root);-        plans[*job].trusted = plans[*job].trusted || trusted;-    }--    let mut entries = Vec::with_capacity(plans.len());-    for plan in plans {-        match plan.kind {-            PlanKind::Conflict => {-                if let Some(target) = plan.target {-                    entries.push(TreeEntry {-                        name: plan.name,-                        kind: KIND_CONFLICT,-                        target,-                    });-                }-            }-            PlanKind::Directory => {-                let child = build_dir(-                    txn,-                    store,-                    root,-                    &plan.rel,-                    plan.child_old,-                    &local,-                    attributes,-                    cache_valid,-                    cache,-                    new_cache,-                    now_ms,-                    state,-                    depth + 1,-                )?;-                if state.failed {-                    return Ok(None);-                }-                if let Some(child) = child {-                    entries.push(TreeEntry {-                        name: plan.name,-                        kind: KIND_SUBTREE,-                        target: child,-                    });-                }-            }-            PlanKind::Symlink => {-                let Some(target) = core::path_read_symlink(&plan.path) else {-                    state.failed = true;-                    return Ok(None);-                };-                let Some(build) = read_blob_from_bytes(txn, &target) else {-                    state.failed = true;-                    return Ok(None);-                };-                entries.push(TreeEntry {-                    name: plan.name,-                    kind: tree::KIND_SYMLINK,-                    target: build,-                });-                new_cache.push(CacheEntry {-                    path: plan.rel,-                    size: plan.info.size,-                    mtime_ns: plan.info.mtime_ns,-                    inode: plan.info.inode,-                    kind: plan.info.kind,-                    executable: false,-                    target: build,-                    trusted: false,-                });-            }-            PlanKind::File => {-                let Some(target) = plan.target else {-                    state.failed = true;-                    return Ok(None);-                };-                new_cache.push(CacheEntry {-                    path: plan.rel,-                    size: plan.info.size,-                    mtime_ns: plan.info.mtime_ns,-                    inode: plan.info.inode,-                    kind: plan.info.kind,-                    executable: plan.executable,-                    target,-                    trusted: plan.trusted,-                });-                entries.push(TreeEntry {-                    name: plan.name,-                    kind: if plan.executable {-                        tree::KIND_EXECUTABLE-                    } else {-                        tree::KIND_FILE-                    },-                    target,-                });-            }-        }-    }--    if entries.is_empty() {-        return Ok(None);-    }-    Ok(Some(txn.add_object(TYPE_TREE, tree::encode(&entries)?)))-}--fn read_build(plan: &Plan, attributes: &AttributeRules) -> Option<(blob::BlobBuild, bool)> {-    let data = core::read_file_opt(&plan.path, 0)?;-    let path_attributes = attributes.lookup(&String::from_utf8_lossy(&plan.rel));-    let build = if path_attributes.eol != AttributeEol::None-        && path_attributes.text != AttributeText::Binary-    {-        blob::build(&attributes::normalize_eol(&data, path_attributes.eol))-    } else {-        blob::build(&data)-    };-    let trusted = plan.info.mtime_ns % 1_000_000 != 0-        && core::stat_path(&plan.path).is_some_and(|again| {-            again.size == plan.info.size-                && again.mtime_ns == plan.info.mtime_ns-                && again.inode == plan.info.inode-                && again.kind == plan.info.kind-                && again.executable == plan.info.executable-        });-    Some((build, trusted))-}--fn read_blob_from_bytes(txn: &mut Txn, data: &[u8]) -> Option<Id> {-    let build = blob::build(data);-    for object in build.objects {-        txn.add_known(object.kind, object.id, object.body);-    }-    Some(build.root)-}--pub fn run_with(root: &Path, store: &mut Store) -> Result<bool> {-    let mut txn = Txn::begin(root, store)?;-    let working_copy = ops::working_copy_id(txn.view());-    let old_commit = match working_copy {-        Some(id) => Some(-            graph::load_commit(store, id)?-                .ok_or_else(|| Error::new("missing working-copy commit"))?,-        ),-        None => None,-    };-    let old_tree = old_commit.as_ref().map(|commit| commit.root_tree);-    let old_empty = match &old_commit {-        Some(commit) if commit.parents.len() == 1 => graph::load_commit(store, commit.parents[0])?-            .is_some_and(|parent| parent.root_tree == commit.root_tree),-        _ => false,-    };--    let mut rules = core::ignore_empty();-    core::ignore_load_root(&mut rules, root);-    let cache = stat_cache::load(root);-    let attributes = AttributeRules::load(root);-    let cache_valid = !attributes.changed_since(cache.written_ms);-    let now_ms = time::now_millis();-    let mut new_cache = Vec::new();-    let mut state = BuildState { failed: false };-    let built = build_dir(-        &mut txn,-        store,-        root,-        b"",-        old_tree,-        &rules,-        &attributes,-        cache_valid,-        &cache,-        &mut new_cache,-        now_ms,-        &mut state,-        0,-    )?;-    let new_root = match built {-        Some(id) => id,-        None if !state.failed => txn.add_object(TYPE_TREE, tree::encode(&[])?),-        None => return Err(Error::new("failed to build working-copy tree")),-    };--    if old_tree == Some(new_root) {-        stat_cache::save(root, &mut new_cache, now_ms)?;-        return Ok(false);-    }--    let committer = identity::signature(root);-    let (parents, change_id, message, author, extra) = match &old_commit {-        Some(commit) => (-            commit.parents.clone(),-            commit.change_id,-            commit.message.clone(),-            if old_empty {-                committer.clone()-            } else {-                commit.author.clone()-            },-            commit.extra.clone(),-        ),-        None => (-            Vec::new(),-            identity::random_change_id(),-            Vec::new(),-            committer.clone(),-            Vec::new(),-        ),-    };--    let mut renames = old_commit-        .as_ref()-        .map(|commit| commit.renames.clone())-        .unwrap_or_default();-    if let Some(old) = old_tree {-        let mut detected = detect_renames(store, txn.writer(), old, new_root)?;-        renames.append(&mut detected);-    }-    renames.sort_by(|left, right| {-        left.parent_index-            .cmp(&right.parent_index)-            .then_with(|| left.to_path.cmp(&right.to_path))-    });--    let new_commit = Commit {-        version: 1,-        parents,-        root_tree: new_root,-        change_id,-        author,-        committer,-        message,-        renames_state: commit::RENAMES_RECORDED,-        renames,-        extra,-    };-    let encoded = commit::encode(&new_commit);-    let commit_id = txn.add_object(TYPE_COMMIT, encoded);--    if let Some(old_id) = working_copy {-        ops::remove_head(txn.view_mut(), old_id);-        ops::move_bookmarks(txn.view_mut(), old_id, commit_id);-    }-    if let Some(current) = core::current_bookmark_name(root)-        && ops::find_bookmark(txn.view(), current.as_bytes()).is_some()-    {-        ops::set_bookmark_target(txn.view_mut(), current.as_bytes(), commit_id);-    }-    ops::set_workspace(txn.view_mut(), commit_id);-    ops::rebuild_heads(txn.view_mut());-    txn.finish("snapshot")?;-    store.refresh()?;-    mark_native(root, commit_id)?;-    stat_cache::save(root, &mut new_cache, now_ms)?;-    Ok(true)-}--fn flatten_any(-    store: &mut Store,-    writer: Option<&Writer>,-    tree_id: Id,-    prefix: &mut Vec<u8>,-    output: &mut Vec<FlatEntry>,-    depth: usize,-) -> Result<()> {-    if depth > crate::object::MAX_TREE_DEPTH {-        return Err(Error::new("tree nesting too deep"));-    }-    let body = match writer.and_then(|writer| writer.find_cached(TYPE_TREE, tree_id)) {-        Some(body) => body.to_vec(),-        None => store-            .body(tree_id, TYPE_TREE)?-            .ok_or_else(|| Error::new(format!("missing tree {}", tree_id.to_hex())))?,-    };-    let tree = tree::decode(&body)?;-    for entry in tree.entries {-        let old_length = prefix.len();-        if !prefix.is_empty() {-            prefix.push(b'/');-        }-        prefix.extend_from_slice(&entry.name);-        if entry.kind == KIND_SUBTREE {-            flatten_any(store, writer, entry.target, prefix, output, depth + 1)?;-        } else {-            output.push(FlatEntry {-                path: prefix.clone(),-                kind: entry.kind,-                target: entry.target,-            });-        }-        prefix.truncate(old_length);-    }-    Ok(())-}--fn detect_renames(-    store: &mut Store,-    writer: &Writer,-    old_tree: Id,-    new_tree: Id,-) -> Result<Vec<Rename>> {-    if let Some(found) = crate::merge::rename::detect(store, writer, old_tree, new_tree)? {-        return Ok(found);-    }-    let mut old_entries = Vec::new();-    flatten_any(store, None, old_tree, &mut Vec::new(), &mut old_entries, 0)?;-    let mut new_entries = Vec::new();-    flatten_any(-        store,-        Some(writer),-        new_tree,-        &mut Vec::new(),-        &mut new_entries,-        0,-    )?;-    old_entries.sort_by(|left, right| left.path.cmp(&right.path));-    new_entries.sort_by(|left, right| left.path.cmp(&right.path));-    let deleted: Vec<&FlatEntry> = old_entries-        .iter()-        .filter(|entry| tree::find_flat(&new_entries, &entry.path).is_none())-        .collect();-    let added: Vec<&FlatEntry> = new_entries-        .iter()-        .filter(|entry| tree::find_flat(&old_entries, &entry.path).is_none())-        .collect();-    let mut used_old = vec![false; deleted.len()];-    let mut used_new = vec![false; added.len()];-    let mut renames = Vec::new();-    for (old_index, old) in deleted.iter().enumerate() {-        if used_old[old_index] {-            continue;-        }-        for (new_index, new) in added.iter().enumerate() {-            if used_new[new_index] {-                continue;-            }-            if old.target == new.target {-                renames.push(Rename {-                    parent_index: 0,-                    kind: 0,-                    from_path: old.path.clone(),-                    to_path: new.path.clone(),-                });-                used_old[old_index] = true;-                used_new[new_index] = true;-                break;-            }-        }-    }-    Ok(renames)-}--fn mark_native(root: &Path, id: Id) -> Result<()> {-    let path = crate::store::layout::git_map_dir(root).join("native");-    if core::append_file(&path, format!("{}\n", id.to_hex()).as_bytes()) {-        Ok(())-    } else {-        Err(Error::new("cannot write native marker"))-    }-}--pub fn path_to_os_string(bytes: &[u8]) -> PathBuf {-    core::path_from_bytes(bytes)-}--- a/veinsrs/src/worktree/stat_cache.rs+++ /dev/null@@ -1,153 +0,0 @@-use std::fs;-use std::path::Path;--use crate::encoding::{Reader, Writer};-use crate::error::Result;-use crate::object::id::Id;-use crate::store::layout;--#[derive(Clone)]-pub struct CacheEntry {-    pub path: Vec<u8>,-    pub size: u64,-    pub mtime_ns: u64,-    pub inode: u64,-    pub kind: u8,-    pub executable: bool,-    pub target: Id,-    pub trusted: bool,-}--pub struct Cache {-    pub entries: Vec<CacheEntry>,-    pub written_ms: i64,-}--pub fn load(root: &Path) -> Cache {-    let mut cache = Cache {-        entries: Vec::new(),-        written_ms: 0,-    };-    let Ok(data) = fs::read(layout::working_copy_dir(root).join("stat-cache")) else {-        return cache;-    };-    if data.len() < 13 || &data[..4] != b"VST1" {-        return cache;-    }-    let mut reader = Reader::new(&data[4..]);-    let Ok(version) = reader.u8() else {-        return cache;-    };-    if version != 49 && version != 50 {-        return cache;-    }-    let Ok(written) = reader.u64le() else {-        return cache;-    };-    cache.written_ms = written as i64;-    let Ok(count) = reader.varint() else {-        return cache;-    };-    for _ in 0..count {-        let Ok(path) = reader.bytes(65_536) else {-            break;-        };-        let path = path.to_vec();-        let (Ok(size), Ok(mtime), Ok(inode), Ok(kind), Ok(executable)) = (-            reader.u64le(),-            reader.u64le(),-            reader.u64le(),-            reader.u8(),-            reader.u8(),-        ) else {-            break;-        };-        let trusted = if version >= 50 {-            match reader.u8() {-                Ok(value) => value != 0,-                Err(_) => break,-            }-        } else {-            false-        };-        let Ok(target) = reader.id() else {-            break;-        };-        cache.entries.push(CacheEntry {-            path,-            size,-            mtime_ns: mtime,-            inode,-            kind,-            executable: executable != 0,-            target,-            trusted,-        });-    }-    cache-        .entries-        .sort_by(|left, right| left.path.cmp(&right.path));-    cache-}--pub fn save(root: &Path, entries: &mut [CacheEntry], written_ms: i64) -> Result<()> {-    entries.sort_by(|left, right| left.path.cmp(&right.path));-    let mut writer = Writer::with_capacity(4096);-    writer.raw(b"VST1");-    writer.u8(50);-    writer.u64le(written_ms as u64);-    writer.varint(entries.len() as u64);-    for entry in entries {-        writer.bytes(&entry.path);-        writer.u64le(entry.size);-        writer.u64le(entry.mtime_ns);-        writer.u64le(entry.inode);-        writer.u8(entry.kind);-        writer.u8(u8::from(entry.executable));-        writer.u8(u8::from(entry.trusted));-        writer.id(entry.target);-    }-    let path = layout::working_copy_dir(root).join("stat-cache");-    // The stat cache is rebuildable; matching C++, write it without fsync so a-    // cache refresh does not pay two sync barriers.-    crate::core::write_file(&path, &writer.into_vec());-    Ok(())-}--pub fn lookup<'a>(cache: &'a Cache, path: &[u8]) -> Option<&'a CacheEntry> {-    cache-        .entries-        .binary_search_by(|entry| entry.path.as_slice().cmp(path))-        .ok()-        .map(|index| &cache.entries[index])-}--pub fn matches(-    entry: &CacheEntry,-    info: &crate::core::StatInfo,-    executable: bool,-    now_ms: i64,-    written_ms: i64,-) -> bool {-    if entry.size != info.size-        || entry.mtime_ns != info.mtime_ns-        || entry.inode != info.inode-        || entry.executable != executable-        || entry.kind != info.kind-    {-        return false;-    }-    if entry.trusted {-        return true;-    }-    let now_ns = now_ms.saturating_mul(1_000_000);-    let written_ns = written_ms.saturating_mul(1_000_000);-    const WINDOW: i64 = 2_000_000_000;-    if info.mtime_ns as i64 >= written_ns - WINDOW {-        return false;-    }-    if now_ns - (info.mtime_ns as i64) < WINDOW {-        return false;-    }-    true-}--- a/veinsrs/tests/end_to_end.rs+++ /dev/null@@ -1,87 +0,0 @@-use std::fs;-use std::path::{Path, PathBuf};-use std::process::{Command, Output};-use std::time::{SystemTime, UNIX_EPOCH};--struct TempDirectory(PathBuf);--impl TempDirectory {-    fn new() -> Self {-        let stamp = SystemTime::now()-            .duration_since(UNIX_EPOCH)-            .unwrap()-            .as_nanos();-        let path =-            std::env::temp_dir().join(format!("veins-rust-test-{}-{stamp}", std::process::id()));-        fs::create_dir_all(&path).unwrap();-        Self(path)-    }--    fn path(&self) -> &Path {-        &self.0-    }-}--impl Drop for TempDirectory {-    fn drop(&mut self) {-        let _ = fs::remove_dir_all(&self.0);-    }-}--fn vn(directory: &Path, arguments: &[&str]) -> Output {-    Command::new(env!("CARGO_BIN_EXE_vn"))-        .args(arguments)-        .current_dir(directory)-        .env("NO_COLOR", "1")-        .output()-        .unwrap()-}--fn ok(directory: &Path, arguments: &[&str]) -> String {-    let output = vn(directory, arguments);-    assert!(-        output.status.success(),-        "command {:?} failed: {}",-        arguments,-        String::from_utf8_lossy(&output.stderr)-    );-    String::from_utf8(output.stdout).unwrap()-}--#[test]-fn commit_log_checkout_and_bookmarks() {-    let temporary = TempDirectory::new();-    let root = temporary.path();-    ok(root, &["init", "."]);-    fs::write(-        root.join(".veins/config"),-        "user.name = Bench\nuser.email = bench@example.com\n",-    )-    .unwrap();-    fs::write(root.join("a.txt"), "hello\n").unwrap();-    fs::create_dir(root.join("src")).unwrap();-    fs::write(root.join("src/b.txt"), "world\n").unwrap();-    ok(root, &["go", "-m", "first"]);--    fs::write(root.join("a.txt"), "hello again\n").unwrap();-    ok(root, &["go", "-m", "second"]);--    let log = ok(root, &["log", "-no-col-titles"]);-    let first = log-        .lines()-        .find(|line| line.contains("first"))-        .and_then(|line| {-            line.split_whitespace().find(|token| {-                token.len() == 12 && token.bytes().all(|byte| byte.is_ascii_hexdigit())-            })-        })-        .expect("first commit id");-    ok(root, &["co", first]);-    assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "hello\n");--    ok(root, &["status"]);-    ok(root, &["bmk", "set", "main"]);-    let bookmarks = ok(root, &["bmk", "ls"]);-    assert!(bookmarks.contains("main"));-    ok(root, &["self-test"]);-}--- a/veinsrs/tests/format_vectors.rs+++ /dev/null@@ -1,154 +0,0 @@-use veins_rust::object::blob;-use veins_rust::object::chunker::{gear_table, next_chunk};-use veins_rust::object::commit::{self, Commit, Sig};-use veins_rust::object::id::{Id, hash_bytes, object_id};-use veins_rust::object::tree;-use veins_rust::object::view::{self, Bookmark, Operation, TargetSet, TimeMs, View, WorkspaceRef};-use veins_rust::object::{RawObject, TYPE_BLOB, TYPE_CHUNK, TYPE_TREE};-use veins_rust::store::pack;--fn hex(bytes: &[u8]) -> String {-    bytes.iter().map(|byte| format!("{byte:02x}")).collect()-}--#[test]-fn published_vectors_match() {-    assert_eq!(-        hex(&hash_bytes(b"")),-        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262"-    );-    assert_eq!(gear_table()[0], 0xf8447b379cdadcd5);-    assert_eq!(gear_table()[1], 0xbe63d125aec8ca6d);--    let mut input = vec![0u8; 300_000];-    for (index, byte) in input.iter_mut().enumerate() {-        *byte = ((index * 31 + 34) % 251) as u8;-    }-    let first = next_chunk(&input);-    assert_eq!(first, 262_144);-    assert_eq!(next_chunk(&input[first..]), 37_856);-    assert_eq!(-        object_id(TYPE_CHUNK, &input[..first]).to_hex(),-        "c83c67617ae4445631508cc4edba83ba58d9e996cea40c980ec69a8b6da86458"-    );-    assert_eq!(-        object_id(TYPE_CHUNK, &input[first..]).to_hex(),-        "0c91665d423fd704baae9454d24697460c4898fbf16cc6ad498d3f750d073a4b"-    );-    assert_eq!(-        blob::build(&input).root.to_hex(),-        "937fe1a8d674aa28cb9fa074a76ea84cdc1d6c61e209f47bbdebbe4361b698cf"-    );--    let empty_tree = vec![0u8];-    let empty_tree_id = object_id(TYPE_TREE, &empty_tree);-    assert_eq!(-        empty_tree_id.to_hex(),-        "8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb"-    );-    assert!(tree::decode(&empty_tree).unwrap().entries.is_empty());--    assert_eq!(-        object_id(TYPE_BLOB, &blob::encode_inline(b"hello")).to_hex(),-        "f04a7f7324bbb7279471b5c656c893ee51b62ed9f9bad4c8cb8a289101f68240"-    );-}--#[test]-fn objects_round_trip_and_pack_is_canonical() {-    let change_id = [-        0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,-        0x1a,-    ];-    let signature = Sig {-        name: b"Alice".to_vec(),-        email: b"alice@example.com".to_vec(),-        seconds: 1_700_000_000,-        tz_min: 0,-    };-    let empty_tree_id =-        Id::from_hex("8be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb").unwrap();-    let commit = Commit {-        version: 1,-        parents: Vec::new(),-        root_tree: empty_tree_id,-        change_id,-        author: signature.clone(),-        committer: signature,-        message: b"initial commit".to_vec(),-        renames_state: commit::RENAMES_RECORDED,-        renames: Vec::new(),-        extra: Vec::new(),-    };-    let commit_body = commit::encode(&commit);-    let commit_id = object_id(veins_rust::object::TYPE_COMMIT, &commit_body);-    assert_eq!(-        commit_id.to_hex(),-        "7f648b3621402df01985d121888c89c37107274fb8bb54661f12deca6cc72299"-    );-    assert_eq!(-        commit::decode(&commit_body).unwrap().message,-        b"initial commit"-    );--    let view = View {-        heads: vec![commit_id],-        bookmarks: vec![Bookmark {-            name: b"main".to_vec(),-            targets: TargetSet {-                adds: vec![Some(commit_id)],-                removes: Vec::new(),-            },-        }],-        tags: Vec::new(),-        remote_refs: Vec::new(),-        working_copies: vec![WorkspaceRef {-            workspace: b"default".to_vec(),-            target: commit_id,-        }],-    };-    let view_body = view::encode_view(&view);-    let view_id = object_id(veins_rust::object::TYPE_VIEW, &view_body);-    assert_eq!(-        view_id.to_hex(),-        "a2e19569bb3b5c28775bc8503c45c4edce6d51f55303e39bc02eec529324cd11"-    );-    assert_eq!(-        view::decode_view(&view_body).unwrap().heads,-        vec![commit_id]-    );--    let operation = Operation {-        parents: Vec::new(),-        view: view_id,-        start: TimeMs {-            millis: 1_700_000_000_000,-            tz_min: 0,-        },-        end: TimeMs {-            millis: 1_700_000_000_000,-            tz_min: 0,-        },-        hostname: b"host".to_vec(),-        username: b"alice".to_vec(),-        description: b"selftest operation".to_vec(),-        tags: Vec::new(),-    };-    let operation_body = view::encode_operation(&operation);-    assert_eq!(-        object_id(veins_rust::object::TYPE_OPERATION, &operation_body).to_hex(),-        "0a5494529353fb5886870a128139e07d95f40afcd831afc423617808f31dc426"-    );--    let output = pack::encode(&[RawObject::known(TYPE_TREE, empty_tree_id, vec![0])], 3);-    assert_eq!(-        hex(&output.pack),-        "56504b310100000001000000000000008be3caa39b307b2b4a46533174cc7faa49c0ff34317302d188276c9641be35fb030001010072c385a83448a5e16853735a79a212f0377d0e40be777d121271758525dbc911"-    );-    assert_eq!(output.index.len(), 1136);-    assert_eq!(-        hex(&hash_bytes(&output.index)),-        "d5dfb7b2ce4235f87856c12ff2e0b65d817dc29dfedad62ba34e71d74dca0cfc"-    );-    pack::decode(output.pack).unwrap();-}--- a/veinsrs/tests/integration.rs+++ /dev/null@@ -1,929 +0,0 @@-use std::fs;-use std::net::TcpListener;-use std::path::{Path, PathBuf};-use std::process::{Command, Output, Stdio};-use std::time::{Duration, SystemTime, UNIX_EPOCH};--struct Fixture {-    root: PathBuf,-    home: PathBuf,-    repo: PathBuf,-}--impl Fixture {-    fn new() -> Self {-        let stamp = SystemTime::now()-            .duration_since(UNIX_EPOCH)-            .unwrap()-            .as_nanos();-        let root = std::env::temp_dir().join(format!(-            "veins-rust-integration-{}-{stamp}",-            std::process::id()-        ));-        let home = root.join("home");-        let repo = root.join("repo");-        fs::create_dir_all(home.join(".config")).unwrap();-        fs::create_dir_all(&repo).unwrap();-        Self { root, home, repo }-    }--    fn command(&self, arguments: &[&str], cwd: &Path) -> Output {-        let owned: Vec<std::ffi::OsString> =-            arguments.iter().map(std::ffi::OsString::from).collect();-        self.command_os(&owned, cwd)-    }--    fn command_os(&self, arguments: &[std::ffi::OsString], cwd: &Path) -> Output {-        Command::new(env!("CARGO_BIN_EXE_vn"))-            .args(arguments)-            .current_dir(cwd)-            .env("HOME", &self.home)-            .env("XDG_CONFIG_HOME", self.home.join(".config"))-            .env("USER", "tester")-            .env("GIT_AUTHOR_NAME", "Tester")-            .env("GIT_AUTHOR_EMAIL", "tester@example.com")-            .env("GIT_COMMITTER_NAME", "Tester")-            .env("GIT_COMMITTER_EMAIL", "tester@example.com")-            .env("NO_COLOR", "1")-            .env("TZ", "UTC")-            .env("VN_EDITOR", "/bin/true")-            .output()-            .unwrap()-    }--    fn vn(&self, arguments: &[&str]) -> String {-        self.vn_in(&self.repo, arguments)-    }--    fn vn_in(&self, cwd: &Path, arguments: &[&str]) -> String {-        let output = self.command(arguments, cwd);-        assert!(-            output.status.success(),-            "{arguments:?} failed: {}{}",-            String::from_utf8_lossy(&output.stdout),-            String::from_utf8_lossy(&output.stderr)-        );-        String::from_utf8_lossy(&output.stdout).into_owned()-    }--    fn fail(&self, arguments: &[&str]) -> String {-        let output = self.command(arguments, &self.repo);-        assert!(-            !output.status.success(),-            "{arguments:?} unexpectedly passed"-        );-        format!(-            "{}{}",-            String::from_utf8_lossy(&output.stdout),-            String::from_utf8_lossy(&output.stderr)-        )-    }--    fn init(&self) {-        self.vn(&["init", "."]);-    }--    fn write(&self, path: &str, content: &str) {-        self.write_in(&self.repo, path, content);-    }--    fn write_in(&self, root: &Path, path: &str, content: &str) {-        let path = root.join(path);-        if let Some(parent) = path.parent() {-            fs::create_dir_all(parent).unwrap();-        }-        fs::write(path, content).unwrap();-    }--    fn read(&self, path: &str) -> String {-        self.read_in(&self.repo, path)-    }--    fn read_in(&self, root: &Path, path: &str) -> String {-        fs::read_to_string(root.join(path)).unwrap()-    }--    fn exists(&self, path: &str) -> bool {-        self.repo.join(path).exists()-    }--    fn commit(&self, message: &str) {-        self.vn(&["go", "-m", message]);-    }--    fn hash(&self, revision: &str) -> String {-        self.vn(&["hash", revision]).trim().to_string()-    }--    fn log_lines(&self) -> Vec<String> {-        self.vn(&["log", "-a", "-no-col-titles"])-            .lines()-            .map(|line| line.to_string())-            .collect()-    }-}--impl Drop for Fixture {-    fn drop(&mut self) {-        let _ = fs::remove_dir_all(&self.root);-    }-}--#[test]-fn init_status_list_and_diff() {-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "alpha\n");-    f.write("dir/b.txt", "beta\n");-    let status = f.vn(&["stat"]);-    assert!(status.contains("A a.txt"));-    assert!(status.contains("A dir/b.txt"));-    let plain = f.vn(&["ls", "-plain"]);-    assert_eq!(-        plain.lines().collect::<Vec<_>>(),-        vec!["a.txt", "dir/b.txt"]-    );-    let diff = f.vn(&["diff"]);-    assert!(diff.contains("+alpha"));-    assert!(diff.contains("+beta"));-}--#[test]-fn status_paths_are_relative_to_cwd() {-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "alpha\n");-    f.write("dir/b.txt", "beta\n");-    f.write("dir/sub/c.txt", "gamma\n");-    let sub = f.repo.join("dir/sub");-    let status = f.vn_in(&sub, &["stat"]);-    assert!(status.contains("A ../../a.txt"));-    assert!(status.contains("A ../b.txt"));-    assert!(status.contains("A c.txt"));-}--#[test]-fn commit_log_show_and_hash() {-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "one\n");-    f.commit("first commit");-    assert!(f.vn(&["stat"]).contains("working copy clean"));-    let rows = f.log_lines();-    assert!(rows.len() >= 2);-    assert!(rows[0].trim_start().starts_with('@'));-    let commit = f-        .log_lines()-        .iter()-        .find(|line| line.contains("first commit"))-        .and_then(|line| line.split_whitespace().nth(1))-        .unwrap()-        .to_string();-    let shown = f.vn(&["show", &commit]);-    assert!(shown.contains("first commit"));-    assert!(shown.contains("+one"));-    assert_eq!(f.hash(&commit).len(), 64);-    let short = f.vn(&["hash", "-short", &commit]).trim().to_string();-    assert_eq!(short, &f.hash(&commit)[..12]);-}--#[test]-fn log_limits_and_revisions() {-    let f = Fixture::new();-    f.init();-    for index in 0..4 {-        f.write("a.txt", &format!("value {index}\n"));-        f.commit(&format!("commit {index}"));-    }-    assert_eq!(f.log_lines().len(), 5);-    assert_eq!(f.vn(&["log", "-l2", "-no-col-titles"]).lines().count(), 2);-    let oldest: Vec<String> = f-        .vn(&["log", "-f2", "-no-col-titles"])-        .lines()-        .map(|line| line.to_string())-        .collect();-    assert!(oldest[0].contains("commit 0"));-    assert!(oldest[1].contains("commit 1"));-    assert_eq!(f.vn(&["log", "l2", "-no-col-titles"]).lines().count(), 2);-    assert!(f.fail(&["log", "-l0"]).contains("error"));-    assert!(f.fail(&["log", "-bad"]).contains("unknown flag"));-}--#[test]-fn checkout_materializes_and_new() {-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "one\n");-    f.vn(&["bmk", "set", "main"]);-    f.commit("first");-    let first = f.hash("main");-    f.write("a.txt", "two\n");-    f.write("later.txt", "later\n");-    f.commit("second");-    let second = f.hash("main");-    f.vn(&["bmk", "set", "main", "-rev", &first]);-    f.vn(&["bmk", "set", "feature", "-rev", &second]);-    f.vn(&["co", "main"]);-    assert_eq!(f.read("a.txt"), "one\n");-    assert!(!f.exists("later.txt"));-    assert!(f.vn(&["stat"]).contains("working copy clean"));-    f.vn(&["co", "feature"]);-    assert_eq!(f.read("a.txt"), "two\n");-    assert!(f.exists("later.txt"));-    f.vn(&["new"]);-    assert!(f.vn(&["stat"]).contains("working copy clean"));-}--#[test]-fn worktree_rename_delete_exclude_remove() {-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "alpha\n");-    f.write("b.txt", "beta\n");-    f.commit("base");-    f.vn(&["mv", "a.txt", "renamed.txt"]);-    assert!(!f.exists("a.txt"));-    assert_eq!(f.read("renamed.txt"), "alpha\n");-    let status = f.vn(&["stat"]);-    assert!(status.contains("D a.txt"));-    assert!(status.contains("A renamed.txt"));-    f.commit("rename");-    fs::remove_file(f.repo.join("b.txt")).unwrap();-    assert!(f.vn(&["stat"]).contains("D b.txt"));-    f.commit("delete");-    f.write("src/a.c", "a\n");-    f.write("src/b.c", "b\n");-    f.write("docs/readme.md", "docs\n");-    assert!(f.vn(&["rm", "src/*.c"]).contains("will be re-added"));-    f.vn(&["ex", "src/*.c"]);-    assert!(f.read(".vnexclude").contains("src/*.c"));-    f.vn(&["rm", "-delete", "docs/readme.md"]);-    assert!(!f.exists("docs/readme.md"));-}--#[test]-fn ignore_rules_and_attributes() {-    let f = Fixture::new();-    f.init();-    f.write(".gitignore", "*.log\nbuild/\n");-    f.write("debug.log", "ignored\n");-    f.write("build/out.bin", "ignored\n");-    f.write("src/.gitignore", "*.tmp\n");-    f.write("src/notes.tmp", "ignored\n");-    f.write("src/main.c", "kept\n");-    let listing = f.vn(&["ls", "-plain"]);-    let tracked: Vec<&str> = listing.lines().collect();-    assert_eq!(tracked, vec![".gitignore", "src/.gitignore", "src/main.c"]);-    f.write(".vnattribs", "*.txt txt eol:lf\n*.cmd txt eol:crlf\n");-    f.write("a.txt", "a\r\nb\r\n");-    f.write("b.cmd", "x\ny\n");-    f.commit("base");-    fs::remove_file(f.repo.join("a.txt")).unwrap();-    fs::remove_file(f.repo.join("b.cmd")).unwrap();-    let base = f-        .vn(&["log", "-a", "-no-col-titles"])-        .lines()-        .find(|line| line.contains("base"))-        .and_then(|line| line.split_whitespace().nth(1))-        .unwrap()-        .to_string();-    f.vn(&["co", &base]);-    assert_eq!(f.read("a.txt"), "a\nb\n");-    assert_eq!(f.read("b.cmd"), "x\r\ny\r\n");-}--#[test]-fn attributes_command() {-    let f = Fixture::new();-    f.init();-    assert!(-        f.vn(&["attr", "gen", "*.ssa", "*.bin"])-            .contains("updated 2")-    );-    assert_eq!(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n");-    f.vn(&["attr", "txt", "*.c"]);-    f.vn(&["attr", "crlf", "*.c"]);-    assert_eq!(-        f.read(".vnattribs"),-        "*.ssa gen\n*.bin gen\n*.c txt eol:crlf\n"-    );-    f.vn(&["attr", "rm", "crlf", "*.c"]);-    assert_eq!(f.read(".vnattribs"), "*.ssa gen\n*.bin gen\n*.c txt\n");-    assert!(-        f.fail(&["attr", "gen", "bad pattern"])-            .contains("not a valid attribute pattern")-    );-    assert!(f.vn(&["attr", "ls"]).contains("*.c txt"));-}--#[test]-fn bookmarks_and_tags() {-    let f = Fixture::new();-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    f.vn(&["bmk", "set", "main"]);-    f.write("f.txt", "two\n");-    f.commit("two");-    let listing = f.vn(&["bmk", "ls"]);-    assert!(listing.contains("main"));-    f.vn(&["bmk", "rename", "main", "trunk"]);-    let listing = f.vn(&["bmk", "ls"]);-    assert!(listing.contains("trunk"));-    assert!(!listing.contains("main"));-    assert!(-        f.fail(&["bmk", "rename", "trunk", "trunk"])-            .contains("matches the old name")-    );-    assert!(-        f.fail(&["bmk", "rename", "missing", "other"])-            .contains("no such bookmark")-    );-    f.vn(&["tag", "set", "v0.0.9"]);-    f.vn(&["tag", "set", "v0.0.10"]);-    assert_eq!(f.vn(&["tag", "latest"]).trim(), "v0.0.10");-    f.vn(&["tag", "rm", "v0.0.9"]);-    assert!(f.fail(&["tag", "rm", "missing"]).contains("no such tag"));-}--#[test]-fn config_local_global_and_defaults() {-    let f = Fixture::new();-    f.init();-    f.vn(&["cfg", "test.key", "value"]);-    assert_eq!(f.vn(&["cfg", "test.key"]).trim(), "value");-    f.vn(&["cfg", "-global", "user.name", "Global Tester"]);-    f.vn(&["cfg", "-global", "user.email", "global@example.com"]);-    f.write("f.txt", "content\n");-    f.commit("global identity");-    assert!(f.vn(&["show", "@"]).contains("Global Tester"));-    assert!(f.home.join(".local/config/veins/veins.toml").exists());-    let defaults = f.vn(&["cfg", "-d"]);-    assert!(defaults.contains("log.default_amount = 20"));-    assert!(defaults.contains("rename.autodetect = similar"));-}--#[test]-fn amend_and_undo() {-    let f = Fixture::new();-    f.init();-    f.write("f.txt", "one\n");-    f.commit("one");-    let one = f-        .vn(&["log", "-a", "-no-col-titles"])-        .lines()-        .find(|line| line.contains("one"))-        .and_then(|line| line.split_whitespace().nth(1))-        .unwrap()-        .to_string();-    f.write("f.txt", "two\n");-    f.commit("two");-    f.vn(&["amend", &one, "-m", "one renamed"]);-    assert!(f.vn(&["log"]).contains("one renamed"));-    f.vn(&["undo"]);-    assert!(!f.vn(&["log"]).contains("one renamed"));-}--#[test]-fn merge_clean_and_conflict() {-    let f = Fixture::new();-    f.init();-    f.write("f.txt", "base\n");-    f.vn(&["bmk", "set", "master"]);-    f.commit("base");-    f.vn(&["bmk", "set", "left"]);-    f.vn(&["new", "left"]);-    f.write("f.txt", "left\n");-    f.write("left.txt", "left\n");-    f.commit("left");-    f.vn(&["bmk", "set", "right"]);-    f.vn(&["new", "master"]);-    f.write("f.txt", "right\n");-    f.write("right.txt", "right\n");-    f.commit("right");-    f.vn(&["merge", "left"]);-    assert!(f.vn(&["stat"]).contains("C f.txt"));-    assert!(f.exists("f.txt.base"));-    assert!(f.vn(&["xs", "-porcelain"]).contains("f.txt\ttext\t"));-    f.vn(&["resolve", "-take", "theirs", "f.txt"]);-    assert_eq!(f.read("f.txt"), "left\n");-    assert!(f.vn(&["xs"]).contains("no conflicts"));-    f.commit("resolved");-    assert!(f.vn(&["stat"]).contains("working copy clean"));-    assert!(f.vn(&["fsck"]).contains("fsck: clean"));-}--#[test]-fn rebase_changes_parent_and_rewrites_descendants() {-    let f = Fixture::new();-    f.init();-    f.write("base.txt", "base\n");-    f.vn(&["bmk", "set", "master"]);-    f.commit("base");-    f.vn(&["bmk", "set", "side"]);-    f.vn(&["new", "side"]);-    f.write("one.txt", "one\n");-    f.commit("one");-    f.write("two.txt", "two\n");-    f.commit("two");-    f.vn(&["bmk", "set", "target"]);-    f.vn(&["new", "master"]);-    f.write("target.txt", "target\n");-    f.commit("target");-    let target = f.hash("target");-    f.vn(&["rebase", "-s", "side", "-d", "target"]);-    assert!(f.vn(&["log", "-a"]).contains("two"));-    let _ = target;-}--#[test]-fn error_handling_never_panics() {-    let f = Fixture::new();-    f.init();-    f.write("tracked.txt", "one\n");-    f.commit("initial");-    for command in ["stat", "log", "ls", "diff", "show", "hash", "inf", "fsck"] {-        for token in ["", "-", "--", "-x", "..", "/", "999999999999999999999999"] {-            let output = f.command(&[command, token], &f.repo);-            let text = format!(-                "{}{}",-                String::from_utf8_lossy(&output.stdout),-                String::from_utf8_lossy(&output.stderr)-            );-            assert!(!text.contains("panic"), "{command} {token}: {text}");-        }-    }-}--#[cfg(unix)]-#[test]-fn invalid_utf8_arguments_do_not_panic() {-    use std::ffi::OsString;-    use std::os::unix::ffi::OsStringExt;--    let f = Fixture::new();-    f.init();-    f.write("tracked.txt", "one\n");-    f.commit("initial");-    let cases = [-        vec![-            OsString::from("go"),-            OsString::from("-m"),-            OsString::from_vec(b"caf\xe9 raw \xff\xfe".to_vec()),-        ],-        vec![-            OsString::from("co"),-            OsString::from_vec(b"caf\xe9".to_vec()),-        ],-    ];-    for arguments in cases {-        let output = f.command_os(&arguments, &f.repo);-        let text = format!(-            "{}{}",-            String::from_utf8_lossy(&output.stdout),-            String::from_utf8_lossy(&output.stderr)-        );-        assert!(!text.contains("panicked"), "{arguments:?}: {text}");-        assert!(!text.contains("panic"), "{arguments:?}: {text}");-    }-}--#[test]-fn error_prefix_is_colored() {-    let f = Fixture::new();-    f.init();-    let output = Command::new(env!("CARGO_BIN_EXE_vn"))-        .args(["bmk", "rename", "only"])-        .current_dir(&f.repo)-        .env("HOME", &f.home)-        .env("XDG_CONFIG_HOME", f.home.join(".config"))-        .env("FORCE_COLOR", "1")-        .env_remove("NO_COLOR")-        .output()-        .unwrap();-    assert!(!output.status.success());-    assert!(-        String::from_utf8_lossy(&output.stdout)-            .contains("\x1b[1m\x1b[31merror\x1b[0m: bmk rename requires")-    );-}--#[test]-fn inf_reports_breakdown_with_bars() {-    let f = Fixture::new();-    f.init();-    f.write("main.rs", "fn main() {}\n// two\n");-    f.write("notes.txt", "one\ntwo\nthree\n");-    f.commit("initial");-    let output = f.vn(&["inf"]);-    assert!(output.contains("Repository overview"));-    assert!(output.contains("Languages"));-    assert!(output.contains("Authors"));-    assert!(output.contains("Created"));-    assert!(output.contains("Size"));-    assert!(output.contains(".rs"));-    assert!(output.contains("lines"));-    assert!(output.contains('\u{2588}') || output.contains('\u{2591}'));-    let colored = Command::new(env!("CARGO_BIN_EXE_vn"))-        .args(["inf"])-        .current_dir(&f.repo)-        .env("HOME", &f.home)-        .env("XDG_CONFIG_HOME", f.home.join(".config"))-        .env("FORCE_COLOR", "1")-        .env_remove("NO_COLOR")-        .output()-        .unwrap();-    assert!(-        String::from_utf8_lossy(&colored.stdout).contains("\x1b[1m\x1b[96mRepository overview")-    );-}--#[test]-fn tls_clone_and_push() {-    if Command::new("openssl").arg("version").output().is_err() {-        return;-    }-    let f = Fixture::new();-    let source = f.root.join("source");-    fs::create_dir_all(&source).unwrap();-    f.vn_in(&source, &["init", "."]);-    f.write_in(&source, "a.txt", "hello\n");-    f.vn_in(&source, &["bmk", "set", "master"]);-    f.vn_in(&source, &["go", "-m", "initial"]);-    f.vn_in(&source, &["access", "anonymous", "on"]);--    let cert = f.root.join("cert.pem");-    let key = f.root.join("key.pem");-    let generated = Command::new("openssl")-        .args([-            "req",-            "-x509",-            "-newkey",-            "rsa:2048",-            "-nodes",-            "-keyout",-            key.to_str().unwrap(),-            "-out",-            cert.to_str().unwrap(),-            "-days",-            "1",-            "-subj",-            "/CN=localhost",-            "-addext",-            "subjectAltName=DNS:localhost,IP:127.0.0.1",-        ])-        .stdout(Stdio::null())-        .stderr(Stdio::null())-        .status()-        .unwrap();-    if !generated.success() {-        return;-    }-    let fingerprint = Command::new("openssl")-        .args([-            "x509",-            "-in",-            cert.to_str().unwrap(),-            "-noout",-            "-fingerprint",-            "-sha256",-        ])-        .output()-        .unwrap();-    let pin = String::from_utf8_lossy(&fingerprint.stdout)-        .split('=')-        .nth(1)-        .unwrap_or("")-        .trim()-        .to_string();--    let probe = TcpListener::bind("127.0.0.1:0").unwrap();-    let port = probe.local_addr().unwrap().port();-    drop(probe);-    let mut server = Command::new(env!("CARGO_BIN_EXE_vn"))-        .args([-            "serve",-            "-listen",-            &format!("127.0.0.1:{port}"),-            "-root",-            f.root.to_str().unwrap(),-            "-tls-cert",-            cert.to_str().unwrap(),-            "-tls-key",-            key.to_str().unwrap(),-        ])-        .current_dir(&f.root)-        .env("HOME", &f.home)-        .env("XDG_CONFIG_HOME", f.home.join(".config"))-        .env("NO_COLOR", "1")-        .stdout(Stdio::null())-        .stderr(Stdio::null())-        .spawn()-        .unwrap();--    let address = format!("127.0.0.1:{port}");-    let mut ready = false;-    for _ in 0..100 {-        if std::net::TcpStream::connect(&address).is_ok() {-            ready = true;-            break;-        }-        std::thread::sleep(Duration::from_millis(30));-    }-    assert!(ready, "TLS server did not start");--    let clone = f.root.join("clone");-    let url = format!("veins://localhost:{port}/source");-    f.vn_in(-        &f.root,-        &[-            "clone",-            &url,-            clone.to_str().unwrap(),-            &format!("-pin:{pin}"),-        ],-    );-    assert_eq!(f.read_in(&clone, "a.txt"), "hello\n");-    server.kill().ok();-    server.wait().ok();-}--#[test]-fn protocol_clone_push_fetch_pull() {-    let f = Fixture::new();-    let source = f.root.join("source");-    fs::create_dir_all(&source).unwrap();-    f.vn_in(&source, &["init", "."]);-    f.write_in(&source, "a.txt", "hello\n");-    f.vn_in(&source, &["bmk", "set", "master"]);-    f.vn_in(&source, &["go", "-m", "initial"]);-    f.vn_in(&source, &["access", "anonymous", "on"]);-    let key_output = f.vn_in(&source, &["key", "generate", "integration"]);-    let public_key = key_output-        .lines()-        .find_map(|line| line.strip_prefix("public key: "))-        .unwrap()-        .to_string();-    f.vn_in(-        &source,-        &[-            "access",-            "add",-            "-role",-            "write",-            "-key",-            &public_key,-            "-name",-            "integration",-        ],-    );-    let clone_a = f.root.join("clone-a");-    let clone_b = f.root.join("clone-b");-    let url = format!("file://{}", source.display());-    f.vn_in(&f.root, &["clone", &url, clone_a.to_str().unwrap()]);-    f.vn_in(&f.root, &["clone", &url, clone_b.to_str().unwrap()]);-    assert_eq!(f.read_in(&clone_a, "a.txt"), "hello\n");-    f.vn_in(&clone_a, &["cfg", "remote.o.key", "integration"]);-    f.vn_in(&clone_b, &["cfg", "remote.o.key", "integration"]);-    f.write_in(&clone_a, "b.txt", "from a\n");-    f.vn_in(&clone_a, &["go", "-m", "a change"]);-    f.vn_in(&clone_a, &["push", "o", "master"]);-    f.vn_in(&clone_b, &["pull"]);-    assert_eq!(f.read_in(&clone_b, "b.txt"), "from a\n");-    assert!(f.vn_in(&clone_b, &["whoami", "o"]).contains("role: write"));-}--#[test]-fn git_import_materialize_export() {-    if Command::new("git").arg("--version").output().is_err() {-        return;-    }-    let f = Fixture::new();-    let git_repo = f.root.join("gitrepo");-    fs::create_dir_all(&git_repo).unwrap();-    for arguments in [-        vec!["init", "-q"],-        vec!["config", "user.name", "Tester"],-        vec!["config", "user.email", "tester@example.com"],-    ] {-        assert!(-            Command::new("git")-                .args(&arguments)-                .current_dir(&git_repo)-                .status()-                .unwrap()-                .success()-        );-    }-    fs::write(git_repo.join("a.txt"), "one\ntwo\n").unwrap();-    for arguments in [vec!["add", "a.txt"], vec!["commit", "-qm", "git one"]] {-        assert!(-            Command::new("git")-                .args(&arguments)-                .current_dir(&git_repo)-                .status()-                .unwrap()-                .success()-        );-    }-    let vn_repo = f.root.join("vnrepo");-    f.vn_in(-        &f.root,-        &[-            "init",-            vn_repo.to_str().unwrap(),-            &format!("-git-import:{}", git_repo.display()),-        ],-    );-    assert!(f.vn_in(&vn_repo, &["log", "-a"]).contains("git one"));-    assert_eq!(f.read_in(&vn_repo, "a.txt"), "one\ntwo\n");-    f.write_in(&vn_repo, "b.txt", "native\n");-    f.vn_in(&vn_repo, &["go", "-m", "native commit"]);-    f.vn_in(&vn_repo, &["git", "export"]);-    let output = Command::new("git")-        .args([-            "--git-dir",-            vn_repo.join(".veins/git").to_str().unwrap(),-            "log",-            "--format=%s",-            "--all",-        ])-        .output()-        .unwrap();-    assert!(String::from_utf8_lossy(&output.stdout).contains("native commit"));-}--#[test]-fn merge_multiple_parents_and_resolve_current() {-    let f = Fixture::new();-    f.init();-    f.write("f.txt", "base\n");-    f.vn(&["bmk", "set", "master"]);-    f.commit("base");-    f.vn(&["bmk", "set", "left"]);-    f.vn(&["new", "left"]);-    f.write("left.txt", "left\n");-    f.commit("left");-    f.vn(&["bmk", "set", "right"]);-    f.vn(&["new", "master"]);-    f.write("right.txt", "right\n");-    f.commit("right");-    f.vn(&["merge", "left", "right"]);-    let metadata = f.vn(&["show", "@"]);-    let parents = metadata-        .lines()-        .find_map(|line| line.strip_prefix("parents  "))-        .unwrap();-    assert_eq!(parents.split_whitespace().count(), 3);-}--#[test]-fn rebase_conflict_produces_conflicted_commit() {-    let f = Fixture::new();-    f.init();-    f.write("f.txt", "base\n");-    f.vn(&["bmk", "set", "master"]);-    f.commit("base");-    f.vn(&["bmk", "set", "left"]);-    f.vn(&["new", "left"]);-    f.write("f.txt", "left\n");-    f.commit("left");-    f.vn(&["bmk", "set", "right"]);-    f.vn(&["new", "master"]);-    f.write("f.txt", "right\n");-    f.commit("right");-    f.vn(&["rebase", "-s", "left", "-d", "right"]);-    assert!(-        f.log_lines()-            .iter()-            .any(|line| line.contains("(conflicted)"))-    );-    f.vn(&["co", "left"]);-    assert!(f.vn(&["xs"]).contains("f.txt"));-    assert!(f.exists("f.txt.base"));-}--#[test]-fn git_mirror_push_and_tag_prune() {-    if Command::new("git").arg("--version").output().is_err() {-        return;-    }-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "one\n");-    f.vn(&["bmk", "set", "master"]);-    f.commit("first");-    let mirror = f.root.join("mirror.git");-    fs::create_dir_all(&mirror).unwrap();-    assert!(-        Command::new("git")-            .args(["init", "-q", "--bare", mirror.to_str().unwrap()])-            .status()-            .unwrap()-            .success()-    );-    f.vn(&["git", "remote", "add", "mirror", mirror.to_str().unwrap()]);-    assert!(-        f.vn(&["git", "mirror", "psh"])-            .contains("mirrored 1 bookmark(s)")-    );-    f.vn(&["tag", "set", "v0.0.1"]);-    f.vn(&["tag", "set", "v0.0.2"]);-    f.vn(&["git", "mirror", "pt", "v0.0.1", "mirror"]);-    let tags = Command::new("git")-        .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])-        .output()-        .unwrap();-    let tags = String::from_utf8_lossy(&tags.stdout);-    assert!(tags.contains("refs/tags/v0.0.1"));-    assert!(!tags.contains("refs/tags/v0.0.2"));-    f.vn(&["git", "mirror", "push", "mirror"]);-    f.vn(&["tag", "rm", "v0.0.2"]);-    f.vn(&["git", "mirror", "push", "mirror"]);-    let tags = Command::new("git")-        .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])-        .output()-        .unwrap();-    assert!(String::from_utf8_lossy(&tags.stdout).contains("refs/tags/v0.0.2"));-    f.vn(&["git", "mirror", "push", "mirror", "-prune"]);-    let tags = Command::new("git")-        .args(["--git-dir", mirror.to_str().unwrap(), "show-ref", "--tags"])-        .output()-        .unwrap();-    assert!(!String::from_utf8_lossy(&tags.stdout).contains("refs/tags/v0.0.2"));-    assert!(-        f.fail(&["git", "mirror", "pt", "missing", "mirror"])-            .contains("unknown tag")-    );-}--#[test]-fn lazy_checkout_of_old_commit() {-    let f = Fixture::new();-    let source = f.root.join("source");-    fs::create_dir_all(&source).unwrap();-    f.vn_in(&source, &["init", "."]);-    for index in 1..=20 {-        f.write_in(&source, &format!("f{index}.txt"), &format!("old {index}\n"));-    }-    f.write_in(&source, "a.txt", "hello\n");-    f.vn_in(&source, &["bmk", "set", "master"]);-    f.vn_in(&source, &["go", "-m", "initial"]);-    f.vn_in(&source, &["access", "anonymous", "on"]);-    for index in 1..=20 {-        f.write_in(&source, &format!("f{index}.txt"), &format!("new {index}\n"));-    }-    f.write_in(&source, "a.txt", "updated\n");-    f.vn_in(&source, &["go", "-m", "second"]);-    let first = f-        .vn_in(&source, &["log", "-a", "-no-col-titles"])-        .lines()-        .find(|line| line.contains("initial"))-        .and_then(|line| line.split_whitespace().nth(1))-        .map(|value| value.trim_start_matches('@').to_string())-        .unwrap();-    let clone = f.root.join("clone");-    f.vn_in(-        &f.root,-        &[-            "clone",-            &format!("file://{}", source.display()),-            clone.to_str().unwrap(),-        ],-    );-    f.vn_in(&clone, &["co", &first]);-    assert_eq!(f.read_in(&clone, "a.txt"), "hello\n");-    assert_eq!(f.read_in(&clone, "f1.txt"), "old 1\n");-    assert!(f.vn_in(&clone, &["stat"]).contains("working copy clean"));-}--#[test]-fn corrupt_repository_does_not_panic() {-    let f = Fixture::new();-    f.init();-    f.write("a.txt", "one\n");-    f.commit("first");-    fs::write(f.repo.join(".veins/config"), b"bad\0line\n").unwrap();-    let pack = fs::read_dir(f.repo.join(".veins/store/packs"))-        .unwrap()-        .flatten()-        .map(|entry| entry.path())-        .find(|path| path.extension().and_then(|value| value.to_str()) == Some("vpack"));-    if let Some(pack) = pack {-        let mut data = fs::read(&pack).unwrap();-        if !data.is_empty() {-            let middle = data.len() / 2;-            data[middle] ^= 0xff;-            fs::write(&pack, data).unwrap();-        }-    }-    for command in [&["stat"][..], &["log"], &["fsck"], &["show"], &["ls"]] {-        let output = f.command(command, &f.repo);-        let text = format!(-            "{}{}",-            String::from_utf8_lossy(&output.stdout),-            String::from_utf8_lossy(&output.stderr)-        );-        assert!(!text.contains("panic"), "{command:?}: {text}");-    }-}--- a/xveins/.clang-format+++ /dev/null@@ -1,20 +0,0 @@-BasedOnStyle: LLVM-IndentWidth: 4-ContinuationIndentWidth: 4-TabWidth: 4-UseTab: Never-BreakBeforeBraces: Attach-AllowShortBlocksOnASingleLine: Never-AllowShortCaseLabelsOnASingleLine: false-AllowShortIfStatementsOnASingleLine: Never-AllowShortLoopsOnASingleLine: false-AllowShortFunctionsOnASingleLine: Empty-DerivePointerAlignment: false-PointerAlignment: Left-SpaceBeforeParens: ControlStatements-SpacesInParentheses: false-ColumnLimit: 100-Standard: Latest-NamespaceIndentation: None-AccessModifierOffset: -4-SortIncludes: CaseSensitive--- a/xveins/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-/build*/-/.cache/-.net-bench/--- a/xveins/BENCH.md+++ /dev/null@@ -1,72 +0,0 @@-# veins C++ optimization benchmark--Generated 2026-11-28 03:22:02 UTC by `bench/optim_bench.py`.--### Environment--| Binary    | Version                        |-| :-------- | :----------------------------- |-| Baseline  | `veins v0.0.1 (veins-store 1)` |-| Optimized | `veins v0.0.1 (veins-store 1)` |--```-host:        Linux x86_64-cpu:         AMD Ryzen 5 5600 6-Core Processor-repeats:     5 (median reported)-inner runs:  3 per command per repeat-cpu pinning: no-temp dir:    /dev/shm-```--### Workload--- Base snapshot: 2.95 MiB, 42 files.-- 80 edit/commit revisions, 8 checkouts, 5 repeats, median reported.-- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.-- Commit total covers all revision commits in the run.-- Status and log are measured on the full history after the last commit.-- Checkout walks the newest revisions in descending order.--### Results--| Metric             |               Baseline |              Optimized |       Speedup |-| :----------------- | ---------------------: | ---------------------: | ------------: |-| Commit total [s]   | 1.2404 (1.2176-1.2505) | 1.0918 (1.0794-1.1877) |         1.14x |-| Status [ms]        |       49.6 (49.4-50.2) |       14.4 (14.0-15.1) |         3.44x |-| Log [ms]           |       50.6 (50.1-51.7) |       13.3 (13.3-14.1) |         3.79x |-| Log -l 5 [ms]      |       50.4 (49.9-51.6) |       13.2 (13.0-14.6) |         3.81x |-| Checkout total [s] | 0.3880 (0.3791-0.4098) | 0.1667 (0.1650-0.1754) |         2.33x |-| Checkout mean [ms] |       48.5 (47.4-51.2) |       20.8 (20.6-21.9) |         2.33x |-| Store size [MiB]   |    43.01 (43.01-43.31) |    42.92 (42.92-42.92) | 1.00x smaller |--Each cell is the median with the observed min-max range in parentheses.-A speedup above 1 means the optimized binary was faster.--### Repeats--| Repeat | Baseline status [ms] | Optimized status [ms] | Baseline log [ms] | Optimized log [ms] | Baseline checkout [ms] | Optimized checkout [ms] |-| :----- | -------------------: | --------------------: | ----------------: | -----------------: | ---------------------: | ----------------------: |-| 1      |                 50.2 |                  15.1 |              51.7 |               14.1 |                   51.2 |                    21.9 |-| 2      |                 49.6 |                  14.0 |              50.5 |               13.6 |                   49.2 |                    20.7 |-| 3      |                 49.4 |                  14.2 |              51.0 |               13.3 |                   48.5 |                    20.9 |-| 4      |                 50.1 |                  14.5 |              50.6 |               13.3 |                   47.4 |                    20.6 |-| 5      |                 49.6 |                  14.4 |              50.1 |               13.3 |                   48.2 |                    20.8 |--### Notes--- The optimized build reads only the requested record from a pack instead of decoding the whole pack for every lookup.-- Status and log memoize conflict-tree results and avoid flattening trees that are already equal.-- Checkout reuses a single store, preloads indexes only, and skips rewriting files whose target object did not change.-- Commit keeps the same object format, compression level, and operation-log sequence. Its gains come from fewer pack decodes and from writing the describe and new operations in one chained pack.-- The baseline binary is the C++ build from before these changes. Rebuild each binary from its own source snapshot before reproducing.-- This is a single-machine run. Treat differences below roughly 5% as noise.--### Reproduce--```sh-cmake --build build -j-python3 bench/optim_bench.py \-  --baseline /path/to/pre-optimization/vn \-  --optimized build/vn \-  --markdown-out BENCH.md-```--- a/xveins/CMakeLists.txt+++ /dev/null@@ -1,332 +0,0 @@-cmake_minimum_required(VERSION 3.25)--project(veins_cpp-    VERSION 0.0.1-    DESCRIPTION "C++ implementation of the veins version control system"-    LANGUAGES C CXX-)--set(CMAKE_CXX_STANDARD 23)-set(CMAKE_CXX_STANDARD_REQUIRED ON)-set(CMAKE_CXX_EXTENSIONS OFF)-set(CMAKE_C_STANDARD 11)-set(CMAKE_C_STANDARD_REQUIRED ON)--if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)-    set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)-endif()--include(FetchContent)-include(CheckCXXCompilerFlag)--set(BUILD_SHARED_LIBS OFF)--option(VN_STRIP_RELEASE-    "Strip symbols and debug information from Release binaries"-    ON)-option(VN_HARDEN-    "Enable cheap compiler hardening in Release (FORTIFY, stack protector, PIE)"-    OFF)-option(VN_STRICT "Treat compiler warnings as errors" OFF)-set(VN_DEPS_MIRROR "" CACHE STRING-    "Optional base URL for third-party source archives (same filenames as upstream)")--find_package(Threads REQUIRED)--##########################################################################-# OpenSSL: TLS 1.3, Ed25519, and cryptographic randomness for the native-# protocol. This remains a system dependency because building OpenSSL from-# source requires platform-specific toolchains (Perl/NASM on Windows) and is-# substantially slower than the rest of the build. Homebrew keeps OpenSSL-# keg-only on macOS, so try `brew` before the default search when the caller-# did not provide an explicit root.-##########################################################################-if(APPLE AND NOT OPENSSL_ROOT_DIR AND NOT DEFINED ENV{OPENSSL_ROOT_DIR})-    find_program(VN_BREW_EXECUTABLE brew)-    if(VN_BREW_EXECUTABLE)-        foreach(_formula openssl@3 openssl)-            execute_process(-                COMMAND "${VN_BREW_EXECUTABLE}" --prefix "${_formula}"-                OUTPUT_VARIABLE _prefix-                OUTPUT_STRIP_TRAILING_WHITESPACE-                ERROR_QUIET-            )-            if(_prefix AND EXISTS "${_prefix}/include/openssl")-                set(OPENSSL_ROOT_DIR "${_prefix}")-                break()-            endif()-        endforeach()-    endif()-endif()-find_package(OpenSSL 3.0 REQUIRED)--##########################################################################-# Third-party C libraries.-#-# These are fetched from pinned release archives and verified by SHA256, so-# a build never picks up an arbitrary system version (zstd in particular-# changes compressed bytes between releases, which breaks pack-output-# reproducibility). Set VN_DEPS_MIRROR to an internal mirror, or point-# FETCHCONTENT_SOURCE_DIR_<NAME> at an unpacked source tree for offline-# builds.-##########################################################################-set(FETCHCONTENT_UPDATES_DISCONNECTED ON)--if(VN_DEPS_MIRROR)-    set(_vn_zstd_url "${VN_DEPS_MIRROR}/zstd-1.5.6.tar.gz")-    set(_vn_blake3_url "${VN_DEPS_MIRROR}/BLAKE3-1.5.5.tar.gz")-    set(_vn_zlib_url "${VN_DEPS_MIRROR}/zlib-1.3.1.tar.gz")-else()-    set(_vn_zstd_url-        "https://github.com/facebook/zstd/releases/download/v1.5.6/zstd-1.5.6.tar.gz")-    set(_vn_blake3_url-        "https://github.com/BLAKE3-team/BLAKE3/archive/refs/tags/1.5.5.tar.gz")-    set(_vn_zlib_url-        "https://github.com/madler/zlib/releases/download/v1.3.1/zlib-1.3.1.tar.gz")-endif()--set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)-set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)-set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)-set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)-set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)-set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)-set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)-FetchContent_Declare(zstd-    URL "${_vn_zstd_url}"-    URL_HASH SHA256=8c29e06cf42aacc1eafc4077ae2ec6c6fcb96a626157e0593d5e82a34fd403c1-    DOWNLOAD_EXTRACT_TIMESTAMP TRUE-    SOURCE_SUBDIR build/cmake-)-FetchContent_MakeAvailable(zstd)-if(TARGET libzstd_static)-    set(VN_ZSTD_TARGET libzstd_static)-elseif(TARGET libzstd)-    set(VN_ZSTD_TARGET libzstd)-else()-    message(FATAL_ERROR "zstd: no static library target was created")-endif()--FetchContent_Declare(blake3-    URL "${_vn_blake3_url}"-    URL_HASH SHA256=6feba0750efc1a99a79fb9a495e2628b5cd1603e15f56a06b1d6cb13ac55c618-    DOWNLOAD_EXTRACT_TIMESTAMP TRUE-    SOURCE_SUBDIR c-)-FetchContent_MakeAvailable(blake3)-if(TARGET blake3 AND NOT TARGET BLAKE3::blake3)-    add_library(BLAKE3::blake3 ALIAS blake3)-endif()-if(NOT TARGET BLAKE3::blake3)-    message(FATAL_ERROR "BLAKE3: no library target was created")-endif()--set(ZLIB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)-set(ZLIB_BUILD_TESTING OFF CACHE BOOL "" FORCE)-set(ZLIB_INSTALL OFF CACHE BOOL "" FORCE)-FetchContent_Declare(zlib-    URL "${_vn_zlib_url}"-    URL_HASH SHA256=9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23-    DOWNLOAD_EXTRACT_TIMESTAMP TRUE-)-FetchContent_MakeAvailable(zlib)-if(TARGET zlibstatic)-    set(VN_ZLIB_TARGET zlibstatic)-elseif(TARGET zlib)-    set(VN_ZLIB_TARGET zlib)-else()-    message(FATAL_ERROR "zlib: no static library target was created")-endif()--message(STATUS-    "veins dependencies: zstd 1.5.6, BLAKE3 1.5.5, zlib 1.3.1, "-    "OpenSSL ${OPENSSL_VERSION}")--set(VN_CORE_SOURCES-    src/core/common.cpp-    src/object/object.cpp-    src/store/store.cpp-    src/store/oplog.cpp-    src/worktree/worktree.cpp-    src/worktree/attributes.cpp-    src/worktree/pathspec.cpp-    src/worktree/remove.cpp-    src/worktree/exclude.cpp-    src/worktree/attr.cpp-    src/refs/bookmark.cpp-    src/refs/tag.cpp-    src/merge/merge.cpp-    src/cli/cli.cpp-    src/cli/net_commands.cpp-    src/crypto/crypto.cpp-    src/net/net.cpp-    src/protocol/wire.cpp-    src/protocol/protocol.cpp-    src/protocol/promisor.cpp-    src/auth/auth.cpp-    src/server/server.cpp-    src/git/git_object.cpp-    src/git/git.cpp-    src/config/cfg.cpp-)--check_cxx_compiler_flag(-Wconversion VN_HAS_WCONVERSION)-set(VN_VERSION "${PROJECT_VERSION}" CACHE STRING "veins version")--function(vn_configure_target target)-    target_include_directories(${target} PRIVATE src)-    target_link_libraries(${target} PRIVATE-        BLAKE3::blake3-        ${VN_ZSTD_TARGET}-        ${VN_ZLIB_TARGET}-        OpenSSL::SSL-        OpenSSL::Crypto-        Threads::Threads-    )-    if(WIN32)-        target_link_libraries(${target} PRIVATE bcrypt ws2_32 crypt32)-    endif()--    if(MSVC)-        target_compile_options(${target} PRIVATE /W4 /permissive- /EHsc /Zc:__cplusplus)-        target_compile_options(${target} PRIVATE $<$<CONFIG:Release>:/Brepro>)-        target_compile_definitions(${target} PRIVATE-            _CRT_SECURE_NO_WARNINGS NOMINMAX WIN32_LEAN_AND_MEAN-        )-        if(VN_STRICT)-            target_compile_options(${target} PRIVATE /WX)-        endif()-    else()-        target_compile_options(${target} PRIVATE -Wall -Wextra -Wpedantic)-        if(VN_HAS_WCONVERSION)-            target_compile_options(${target} PRIVATE -Wconversion -Wsign-conversion)-        endif()-        # Keep floating-point contraction off: pack delta selection compares-        # ratios, and identical inputs must choose identical bases on every-        # compiler/architecture.-        target_compile_options(${target} PRIVATE -ffp-contract=off)-        target_compile_options(${target} PRIVATE-            $<$<CONFIG:Release>:-g0>-            $<$<CONFIG:Release>:-ffile-prefix-map=${CMAKE_SOURCE_DIR}=.>-        )-        if(VN_STRIP_RELEASE)-            target_link_options(${target} PRIVATE $<$<CONFIG:Release>:-s>)-        endif()-        # Linking the C++ runtime statically avoids loading libstdc++/libgcc-        # at startup. For short-lived commands that is a measurable share of-        # total wall time on every invocation.-        if(UNIX AND NOT APPLE)-            target_link_options(${target} PRIVATE -static-libstdc++ -static-libgcc)-        endif()-        if(VN_HARDEN)-            target_compile_options(${target} PRIVATE-                $<$<CONFIG:Release>:-fstack-protector-strong>-                $<$<CONFIG:Release>:-U_FORTIFY_SOURCE>-                $<$<CONFIG:Release>:-D_FORTIFY_SOURCE=3>-                $<$<CONFIG:Release>:-fPIE>-            )-            target_link_options(${target} PRIVATE $<$<CONFIG:Release>:-pie>)-        endif()-        if(VN_STRICT)-            target_compile_options(${target} PRIVATE -Werror)-        endif()-        target_compile_options(${target} PRIVATE $<$<CONFIG:Debug>:-D_GLIBCXX_ASSERTIONS>)-    endif()-endfunction()--add_library(vn_core STATIC ${VN_CORE_SOURCES})-vn_configure_target(vn_core)--set(VN_GENERATED_DIR "${CMAKE_CURRENT_BINARY_DIR}/generated")--add_executable(vn-bootstrap src/main.cpp src/version/version_bootstrap.cpp)-vn_configure_target(vn-bootstrap)-target_link_libraries(vn-bootstrap PRIVATE vn_core)-target_compile_definitions(vn-bootstrap PRIVATE VN_VERSION="${VN_VERSION}")-set_target_properties(vn-bootstrap PROPERTIES-    EXCLUDE_FROM_ALL TRUE-    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bootstrap"-    OUTPUT_NAME "vn-bootstrap"-)--add_custom_target(vn-commit-    COMMAND ${CMAKE_COMMAND}-        "-DVN_BOOTSTRAP=$<TARGET_FILE:vn-bootstrap>"-        "-DVN_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}"-        "-DVN_OUTPUT_DIR=${VN_GENERATED_DIR}/$<CONFIG>"-        -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/generate_vn_commit.cmake"-    DEPENDS vn-bootstrap-    COMMENT "Generating vn revision header"-    VERBATIM-)--add_library(vn_version STATIC src/version/version.cpp)-vn_configure_target(vn_version)-target_include_directories(vn_version PRIVATE "${VN_GENERATED_DIR}/$<CONFIG>")-target_compile_definitions(vn_version PRIVATE VN_VERSION="${VN_VERSION}")-add_dependencies(vn_version vn-commit)--add_executable(vn src/main.cpp)-vn_configure_target(vn)-target_link_libraries(vn PRIVATE vn_core vn_version)--set_target_properties(vn PROPERTIES-    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"-    OUTPUT_NAME "vn"-)--include(CTest)-if(BUILD_TESTING)-    add_executable(vn-unit-tests-        tests/unit/main.cpp-        tests/unit/core_tests.cpp-        tests/unit/object_tests.cpp-        tests/unit/store_tests.cpp-        tests/unit/worktree_tests.cpp-        tests/unit/protocol_tests.cpp-    )-    vn_configure_target(vn-unit-tests)-    target_include_directories(vn-unit-tests PRIVATE tests)-    target_link_libraries(vn-unit-tests PRIVATE vn_core vn_version)-    add_test(NAME vn-unit-tests COMMAND vn-unit-tests)-    set(VN_UNIT_SUITES core object store worktree protocol)-    foreach(suite IN LISTS VN_UNIT_SUITES)-        add_test(-            NAME "vn-unit-${suite}"-            COMMAND vn-unit-tests --suite "unit-${suite}"-        )-    endforeach()--    add_executable(vn-integration-tests-        tests/integration/main.cpp-        tests/integration/support.cpp-        tests/integration/core_tests.cpp-        tests/integration/worktree_tests.cpp-        tests/integration/history_tests.cpp-        tests/integration/refs_tests.cpp-        tests/integration/config_tests.cpp-        tests/integration/merge_tests.cpp-        tests/integration/rebase_tests.cpp-        tests/integration/git_tests.cpp-        tests/integration/protocol_tests.cpp-        tests/integration/errors_tests.cpp-    )-    vn_configure_target(vn-integration-tests)-    target_include_directories(vn-integration-tests PRIVATE tests)-    target_link_libraries(vn-integration-tests PRIVATE vn_core vn_version)--    add_test(NAME vn-self-test COMMAND vn self-test)--    set(VN_INTEGRATION_SUITES-        core worktree history refs config merge rebase git protocol errors-    )-    foreach(suite IN LISTS VN_INTEGRATION_SUITES)-        add_test(-            NAME "vn-integration-${suite}"-            COMMAND vn-integration-tests --suite ${suite}-        )-        set_tests_properties("vn-integration-${suite}" PROPERTIES TIMEOUT 180)-    endforeach()-endif()--install(TARGETS vn RUNTIME DESTINATION bin)--- a/xveins/CMakePresets.json+++ /dev/null@@ -1,97 +0,0 @@-{-  "version": 6,-  "cmakeMinimumRequired": {-    "major": 3,-    "minor": 25,-    "patch": 0-  },-  "configurePresets": [-    {-      "name": "dev",-      "displayName": "Developer (Debug)",-      "binaryDir": "${sourceDir}/build/dev",-      "cacheVariables": {-        "CMAKE_BUILD_TYPE": "Debug",-        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON"-      }-    },-    {-      "name": "release",-      "displayName": "Release (stripped, reproducible flags)",-      "binaryDir": "${sourceDir}/build/release",-      "cacheVariables": {-        "CMAKE_BUILD_TYPE": "Release",-        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",-        "VN_STRIP_RELEASE": "ON"-      }-    },-    {-      "name": "release-harden",-      "displayName": "Release with cheap compiler hardening",-      "inherits": "release",-      "binaryDir": "${sourceDir}/build/release-harden",-      "cacheVariables": {-        "VN_HARDEN": "ON",-        "VN_STRICT": "ON"-      }-    },-    {-      "name": "asan",-      "displayName": "Debug with AddressSanitizer and UndefinedBehaviorSanitizer",-      "binaryDir": "${sourceDir}/build/asan",-      "cacheVariables": {-        "CMAKE_BUILD_TYPE": "Debug",-        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",-        "CMAKE_CXX_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer",-        "CMAKE_C_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer",-        "CMAKE_EXE_LINKER_FLAGS": "-fsanitize=address,undefined"-      }-    },-    {-      "name": "tsan",-      "displayName": "Debug with ThreadSanitizer",-      "binaryDir": "${sourceDir}/build/tsan",-      "cacheVariables": {-        "CMAKE_BUILD_TYPE": "Debug",-        "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",-        "CMAKE_CXX_FLAGS": "-fsanitize=thread -fno-omit-frame-pointer",-        "CMAKE_C_FLAGS": "-fsanitize=thread -fno-omit-frame-pointer",-        "CMAKE_EXE_LINKER_FLAGS": "-fsanitize=thread"-      }-    }-  ],-  "buildPresets": [-    { "name": "dev", "configurePreset": "dev" },-    { "name": "release", "configurePreset": "release" },-    { "name": "release-harden", "configurePreset": "release-harden" },-    { "name": "asan", "configurePreset": "asan" },-    { "name": "tsan", "configurePreset": "tsan" }-  ],-  "testPresets": [-    {-      "name": "dev",-      "configurePreset": "dev",-      "output": { "outputOnFailure": true }-    },-    {-      "name": "release",-      "configurePreset": "release",-      "output": { "outputOnFailure": true }-    },-    {-      "name": "release-harden",-      "configurePreset": "release-harden",-      "output": { "outputOnFailure": true }-    },-    {-      "name": "asan",-      "configurePreset": "asan",-      "output": { "outputOnFailure": true }-    },-    {-      "name": "tsan",-      "configurePreset": "tsan",-      "output": { "outputOnFailure": true }-    }-  ]-}--- a/xveins/bench/bench.py+++ /dev/null@@ -1,190 +0,0 @@-#!/usr/bin/env python3-"""Compare the C++ and Spectre veins binaries on a synthetic edit workload."""--from __future__ import annotations--import argparse-import os-import random-import re-import shutil-import statistics-import subprocess-import sys-import tempfile-import time-from pathlib import Path--HEX12 = re.compile(r"\b[0-9a-f]{12}\b")---def command_prefix() -> list[str]:-    try:-        subprocess.run(-            ["taskset", "-c", "0", "true"],-            stdout=subprocess.DEVNULL,-            stderr=subprocess.DEVNULL,-            check=True,-        )-        return ["taskset", "-c", "0"]-    except Exception:-        return []---PREFIX: list[str] = []---def run(cmd: list[str], cwd: Path) -> str:-    env = os.environ.copy()-    env["LC_ALL"] = "C"-    env["NO_COLOR"] = "1"-    result = subprocess.run(-        [str(part) for part in PREFIX + cmd],-        cwd=str(cwd),-        env=env,-        stdout=subprocess.PIPE,-        stderr=subprocess.PIPE,-        check=True,-        text=True,-    )-    return result.stdout---def timed(cmd: list[str], cwd: Path) -> float:-    start = time.perf_counter()-    run(cmd, cwd)-    return time.perf_counter() - start---def make_base(root: Path, lines: int, small_files: int) -> None:-    root.mkdir(parents=True)-    (root / "generated.c").write_text(-        "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)),-        encoding="utf-8",-    )-    for i in range(small_files):-        (root / f"module_{i:03d}.c").write_text(-            f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8"-        )-    (root / "sub").mkdir()-    (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8")---def mutate(root: Path, revision: int) -> None:-    path = root / "generated.c"-    lines = path.read_text(encoding="utf-8").splitlines(keepends=True)-    rng = random.Random(revision)-    for _ in range(max(1, len(lines) // 100)):-        index = rng.randrange(len(lines))-        lines[index] = f"int changed_{revision}_{index} = {revision};\n"-    path.write_text("".join(lines), encoding="utf-8")-    for i in range(3):-        (root / f"module_{i:03d}.c").write_text(-            f"// module {i}, revision {revision}\n"-            f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n",-            encoding="utf-8",-        )---def tree_bytes(root: Path) -> int:-    return sum(path.stat().st_size for path in root.rglob("*") if path.is_file())---def bench_one(-    binary: Path, work: Path, label: str, revisions: int, checkouts: int-) -> tuple[float, float, int]:-    repo = work / label-    shutil.copytree(work / "base", repo)-    run([str(binary), "init"], repo)-    (repo / ".veins" / "config").write_text(-        "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8"-    )-    mutate(repo, 0)-    run([str(binary), "go", "-m", "warmup"], repo)--    commit_time = 0.0-    for revision in range(1, revisions + 1):-        mutate(repo, revision)-        commit_time += timed([str(binary), "go", "-m", f"revision {revision}"], repo)--    log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()-    ids = [match.group(0) for line in log_lines if (match := HEX12.search(line))]-    targets = ids[: max(1, checkouts)]-    checkout_time = 0.0-    for i in range(checkouts):-        target = targets[min(i, len(targets) - 1)]-        checkout_time += timed([str(binary), "co", target], repo)-    return commit_time, checkout_time, tree_bytes(repo / ".veins")---def main() -> int:-    parser = argparse.ArgumentParser(description=__doc__)-    parser.add_argument(-        "--spectre",-        type=Path,-        default=Path(__file__).resolve().parents[2] / "veins" / "vn",-    )-    parser.add_argument(-        "--cpp", type=Path, default=Path(__file__).resolve().parents[1] / "build" / "vn"-    )-    parser.add_argument("--revisions", type=int, default=20)-    parser.add_argument("--checkouts", type=int, default=8)-    parser.add_argument("--repeats", type=int, default=3)-    parser.add_argument("--large-lines", type=int, default=120000)-    parser.add_argument("--small-files", type=int, default=40)-    parser.add_argument("--no-pin", action="store_true")-    args = parser.parse_args()--    global PREFIX-    PREFIX = [] if args.no_pin else command_prefix()--    if not args.spectre.exists():-        print(f"missing Spectre binary: {args.spectre}", file=sys.stderr)-        return 2-    if not args.cpp.exists():-        print(f"missing C++ binary: {args.cpp}", file=sys.stderr)-        return 2--    work = Path(tempfile.mkdtemp(prefix="veins-bench-"))-    try:-        make_base(work / "base", args.large_lines, args.small_files)-        size = tree_bytes(work / "base")-        print(-            f"workload: {size / (1024 * 1024):.2f} MiB, "-            f"{args.revisions} revisions, {args.checkouts} checkouts, "-            f"{args.repeats} repeats, cpu pinning={'no' if args.no_pin else 'yes'}"-        )-        rows: dict[str, list[tuple[float, float, int]]] = {"spectre": [], "cpp": []}-        for repeat in range(args.repeats):-            print(f"repeat {repeat + 1}/{args.repeats}")-            for label, binary in (("spectre", args.spectre), ("cpp", args.cpp)):-                commit, checkout, store = bench_one(-                    binary, work, f"{label}-{repeat}", args.revisions, args.checkouts-                )-                rows[label].append((commit, checkout, store))-                print(-                    f"  {label}: commit {commit:.3f}s checkout {checkout:.3f}s "-                    f"store {store / (1024 * 1024):.2f} MiB"-                )--        def median(label: str, index: int) -> float:-            return statistics.median(row[index] for row in rows[label])--        spectre_commit = median("spectre", 0)-        cpp_commit = median("cpp", 0)-        spectre_checkout = median("spectre", 1)-        cpp_checkout = median("cpp", 1)-        print()-        print(f"commit speedup C++/Spectre: {spectre_commit / cpp_commit:.2f}x")-        print(f"checkout speedup C++/Spectre: {spectre_checkout / cpp_checkout:.2f}x")-        print(-            f"store size ratio C++/Spectre: "-            f"{median('cpp', 2) / median('spectre', 2):.2f}x"-        )-        return 0-    finally:-        shutil.rmtree(work, ignore_errors=True)---if __name__ == "__main__":-    raise SystemExit(main())--- a/xveins/bench/core_bench.md+++ /dev/null@@ -1,69 +0,0 @@-Generated 2026-11-27 by `bench/core_bench.py`.--### Environment--| Implementation | Binary                              |-| :------------- | :---------------------------------- |-| Rust           | `veins-rust v0.1.0 (veins-store 1)` |-| C++            | `veins v0.0.1 (veins-store 1)`      |-| Spectre        | `veins v0.0.1 (veins-store 1)`      |--```-host:        Darwin arm64-cpu:         Apple M2-repeats:     5 (median reported)-cpu pinning: no-```--### Scope--The Rust binary implements the local-core subset: `init`, `status`, `log`, `go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.-It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache invalidation window as the reference.--The subset does not implement merge/conflict objects, rebase/undo, the git bridge, ignore files, or the network protocol. The workload below contains no renames, ignores, merges, or network traffic, so the measured local operations are directly comparable.--### Workload--- Base snapshot: 2.95 MiB, 42 files.-- 20 edit/commit revisions, 8 checkouts, 5 repeats, median reported.-- Each revision rewrites about 1% of a 120,000-line generated C file and three small module files.-- Each `go` performs the same snapshot, describe, and new-empty-change sequence as the reference, including all operation-log writes.-- Store size includes `.veins` packs, indexes, operation heads, the native commit map, and the stat cache.--### Summary--| Metric             |                Rust |                 C++ |             Spectre | C++ / Rust | Spectre / Rust |-| :----------------- | ------------------: | ------------------: | ------------------: | ---------: | -------------: |-| Commit total [s]   | 0.252 (0.250-0.262) | 0.280 (0.279-0.291) | 0.310 (0.309-0.330) |      1.11x |          1.23x |-| Checkout total [s] | 0.162 (0.161-0.165) | 0.175 (0.172-0.179) | 0.181 (0.179-0.196) |      1.08x |          1.12x |-| Store size [MiB]   |    8.28 (8.28-8.37) |    8.28 (8.28-8.37) | 10.60 (10.60-10.69) |      1.00x |          1.28x |--Each cell is the median with the observed min-max range in parentheses.-A ratio above 1 means the other implementation took longer or used more space than Rust.--### Repeats--| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |-| :----- | --------------: | -------------: | -----------------: | ----------------: | ---------------: | -------------------: |-| 1      |           0.262 |          0.291 |              0.330 |             0.165 |            0.172 |                0.195 |-| 2      |           0.250 |          0.280 |              0.310 |             0.162 |            0.172 |                0.196 |-| 3      |           0.252 |          0.281 |              0.309 |             0.161 |            0.179 |                0.179 |-| 4      |           0.252 |          0.279 |              0.309 |             0.162 |            0.175 |                0.179 |-| 5      |           0.257 |          0.280 |              0.311 |             0.165 |            0.177 |                0.181 |--### Notes--- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, pack/index layout, operation log, and stat-cache racy window.-- Each `go` performs the same snapshot, describe, and new-empty-change sequence in both implementations, including three operation writes.-- The Rust subset omits ignore-file parsing and similarity-based rename detection. This workload has neither ignore files nor renames, so both implementations see the same file set and perform the same exact-rename scan.-- Rust and C++ store sizes are equal at this resolution; Spectre stores the same logical history with a different packing policy.-- This is a single-machine run. Treat differences below roughly 5% as noise.--### Reproduce--```sh-cd veins-rust-cargo build --release-cd ../veins-cpprewrite-python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md-```--- a/xveins/bench/core_bench.py+++ /dev/null@@ -1,340 +0,0 @@-#!/usr/bin/env python3--from __future__ import annotations--import argparse-import os-import platform-import random-import re-import shutil-import statistics-import subprocess-import sys-import tempfile-import time-from datetime import datetime, timezone-from pathlib import Path--HEX12 = re.compile(r"\b[0-9a-f]{12}\b")---def command_prefix() -> list[str]:-    try:-        subprocess.run(-            ["taskset", "-c", "0", "true"],-            stdout=subprocess.DEVNULL,-            stderr=subprocess.DEVNULL,-            check=True,-        )-        return ["taskset", "-c", "0"]-    except Exception:-        return []---PREFIX: list[str] = []---def run(cmd: list[str], cwd: Path) -> str:-    env = os.environ.copy()-    env["LC_ALL"] = "C"-    env["NO_COLOR"] = "1"-    result = subprocess.run(-        [str(part) for part in PREFIX + cmd],-        cwd=str(cwd),-        env=env,-        stdout=subprocess.PIPE,-        stderr=subprocess.PIPE,-        check=True,-        text=True,-    )-    return result.stdout---def timed(cmd: list[str], cwd: Path) -> float:-    start = time.perf_counter()-    run(cmd, cwd)-    return time.perf_counter() - start---def make_base(root: Path, lines: int, small_files: int) -> None:-    root.mkdir(parents=True)-    (root / "generated.c").write_text(-        "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)),-        encoding="utf-8",-    )-    for i in range(small_files):-        (root / f"module_{i:03d}.c").write_text(-            f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8"-        )-    (root / "sub").mkdir()-    (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8")---def mutate(root: Path, revision: int) -> None:-    path = root / "generated.c"-    lines = path.read_text(encoding="utf-8").splitlines(keepends=True)-    rng = random.Random(revision)-    for _ in range(max(1, len(lines) // 100)):-        index = rng.randrange(len(lines))-        lines[index] = f"int changed_{revision}_{index} = {revision};\n"-    path.write_text("".join(lines), encoding="utf-8")-    for i in range(3):-        (root / f"module_{i:03d}.c").write_text(-            f"// module {i}, revision {revision}\n"-            f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n",-            encoding="utf-8",-        )---def tree_bytes(root: Path) -> int:-    return sum(path.stat().st_size for path in root.rglob("*") if path.is_file())---def bench_one(-    binary: Path, work: Path, label: str, revisions: int, checkouts: int-) -> tuple[float, float, int]:-    repo = work / label-    shutil.copytree(work / "base", repo)-    run([str(binary), "init"], repo)-    (repo / ".veins" / "config").write_text(-        "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8"-    )-    mutate(repo, 0)-    run([str(binary), "go", "-m", "warmup"], repo)--    commit_time = 0.0-    for revision in range(1, revisions + 1):-        mutate(repo, revision)-        commit_time += timed([str(binary), "go", "-m", f"revision {revision}"], repo)--    log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()-    ids = [match.group(0) for line in log_lines if (match := HEX12.search(line))]-    targets = ids[: max(1, checkouts)]-    checkout_time = 0.0-    for i in range(checkouts):-        target = targets[min(i, len(targets) - 1)]-        checkout_time += timed([str(binary), "co", target], repo)-    return commit_time, checkout_time, tree_bytes(repo / ".veins")---def environment(binary: Path) -> str:-    try:-        return run([str(binary), "version"], Path.cwd()).strip()-    except Exception:-        return "unknown"---def cpu_name() -> str:-    try:-        return subprocess.run(-            ["sysctl", "-n", "machdep.cpu.brand_string"],-            stdout=subprocess.PIPE,-            stderr=subprocess.DEVNULL,-            check=True,-            text=True,-        ).stdout.strip()-    except Exception:-        return platform.processor() or platform.machine()---def main() -> int:-    parser = argparse.ArgumentParser(description=__doc__)-    root = Path(__file__).resolve().parents[2]-    parser.add_argument("--spectre", type=Path, default=root / "veins" / "vn")-    parser.add_argument(-        "--cpp", type=Path, default=root / "veins-cpprewrite" / "build" / "vn"-    )-    parser.add_argument(-        "--rust", type=Path, default=root / "veins-rust" / "target" / "release" / "vn"-    )-    parser.add_argument("--revisions", type=int, default=20)-    parser.add_argument("--checkouts", type=int, default=8)-    parser.add_argument("--repeats", type=int, default=3)-    parser.add_argument("--large-lines", type=int, default=120000)-    parser.add_argument("--small-files", type=int, default=40)-    parser.add_argument("--no-pin", action="store_true")-    parser.add_argument("--markdown-out", type=Path)-    args = parser.parse_args()--    global PREFIX-    PREFIX = [] if args.no_pin else command_prefix()--    binaries = {-        "rust": args.rust,-        "cpp": args.cpp,-        "spectre": args.spectre,-    }-    for label, binary in binaries.items():-        if not binary.exists():-            print(f"missing {label} binary: {binary}", file=sys.stderr)-            return 2--    work = Path(tempfile.mkdtemp(prefix="veins-core-bench-"))-    try:-        make_base(work / "base", args.large_lines, args.small_files)-        size = tree_bytes(work / "base")-        print(-            f"workload: {size / (1024 * 1024):.2f} MiB, "-            f"{args.revisions} revisions, {args.checkouts} checkouts, "-            f"{args.repeats} repeats, cpu pinning={'yes' if PREFIX else 'no'}"-        )-        rows: dict[str, list[tuple[float, float, int]]] = {-            "rust": [],-            "cpp": [],-            "spectre": [],-        }-        for repeat in range(args.repeats):-            print(f"repeat {repeat + 1}/{args.repeats}")-            for label, binary in binaries.items():-                commit, checkout, store = bench_one(-                    binary, work, f"{label}-{repeat}", args.revisions, args.checkouts-                )-                rows[label].append((commit, checkout, store))-                print(-                    f"  {label}: commit {commit:.3f}s checkout {checkout:.3f}s "-                    f"store {store / (1024 * 1024):.2f} MiB"-                )--        def median(label: str, index: int) -> float:-            return statistics.median(row[index] for row in rows[label])--        def spread(label: str, index: int) -> str:-            values = [row[index] for row in rows[label]]-            return (-                f"{statistics.median(values):.3f} ({min(values):.3f}-{max(values):.3f})"-            )--        def spread_mib(label: str) -> str:-            values = [row[2] / (1024 * 1024) for row in rows[label]]-            return (-                f"{statistics.median(values):.2f} ({min(values):.2f}-{max(values):.2f})"-            )--        values = {-            label: (median(label, 0), median(label, 1), median(label, 2))-            for label in rows-        }-        rust_commit, rust_checkout, rust_store = values["rust"]-        cpp_commit, cpp_checkout, cpp_store = values["cpp"]-        sx_commit, sx_checkout, sx_store = values["spectre"]--        print()-        print(f"commit C++/Rust: {cpp_commit / rust_commit:.2f}x")-        print(f"commit Spectre/Rust: {sx_commit / rust_commit:.2f}x")-        print(f"checkout C++/Rust: {cpp_checkout / rust_checkout:.2f}x")-        print(f"checkout Spectre/Rust: {sx_checkout / rust_checkout:.2f}x")-        print(f"store C++/Rust: {cpp_store / rust_store:.2f}x")-        print(f"store Spectre/Rust: {sx_store / rust_store:.2f}x")--        if args.markdown_out:-            lines = [-                f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by `bench/core_bench.py`.",-                "",-                "### Environment",-                "",-                "| Implementation | Binary |",-                "|:---|:---|",-                f"| Rust | `{environment(args.rust)}` |",-                f"| C++ | `{environment(args.cpp)}` |",-                f"| Spectre | `{environment(args.spectre)}` |",-                "",-                "```",-                f"host:        {platform.system()} {platform.machine()}",-                f"cpu:         {cpu_name()}",-                f"repeats:     {args.repeats} (median reported)",-                f"cpu pinning: {'yes' if PREFIX else 'no'}",-                "```",-                "",-                "### Scope",-                "",-                "The Rust binary implements the local-core subset: `init`, `status`, `log`, "-                "`go`/`commit`, `co`/`checkout`, `bmk set|ls|rm`, `self-test`, and `version`.",-                "It uses the same FastCDC parameters, BLAKE3 object IDs, zstd level 1, "-                "pack/index layout, operation log, and stat-cache invalidation window as "-                "the reference.",-                "",-                "The subset does not implement merge/conflict objects, rebase/undo, the git "-                "bridge, ignore files, or the network protocol. The workload below contains "-                "no renames, ignores, merges, or network traffic, so the measured local "-                "operations are directly comparable.",-                "",-                "### Workload",-                "",-                f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "-                f"{args.small_files + 2} files.",-                f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "-                f"{args.repeats} repeats, median reported.",-                "- Each revision rewrites about 1% of a 120,000-line generated C file "-                "and three small module files.",-                "- Each `go` performs the same snapshot, describe, and new-empty-change "-                "sequence as the reference, including all operation-log writes.",-                "- Store size includes `.veins` packs, indexes, operation heads, the native "-                "commit map, and the stat cache.",-                "",-                "### Summary",-                "",-                "| Metric | Rust | C++ | Spectre | C++ / Rust | Spectre / Rust |",-                "|:---|---:|---:|---:|---:|---:|",-                f"| Commit total [s] | {spread('rust', 0)} | {spread('cpp', 0)} | "-                f"{spread('spectre', 0)} | {cpp_commit / rust_commit:.2f}x | "-                f"{sx_commit / rust_commit:.2f}x |",-                f"| Checkout total [s] | {spread('rust', 1)} | {spread('cpp', 1)} | "-                f"{spread('spectre', 1)} | {cpp_checkout / rust_checkout:.2f}x | "-                f"{sx_checkout / rust_checkout:.2f}x |",-                f"| Store size [MiB] | {spread_mib('rust')} | {spread_mib('cpp')} | "-                f"{spread_mib('spectre')} | {cpp_store / rust_store:.2f}x | "-                f"{sx_store / rust_store:.2f}x |",-                "",-                "Each cell is the median with the observed min-max range in parentheses.",-                "A ratio above 1 means the other implementation took longer or used "-                "more space than Rust.",-                "",-                "### Repeats",-                "",-                "| Repeat | Rust commit [s] | C++ commit [s] | Spectre commit [s] | "-                "Rust checkout [s] | C++ checkout [s] | Spectre checkout [s] |",-                "|:---|---:|---:|---:|---:|---:|---:|",-            ]-            for index in range(args.repeats):-                lines.append(-                    f"| {index + 1} | {rows['rust'][index][0]:.3f} | "-                    f"{rows['cpp'][index][0]:.3f} | {rows['spectre'][index][0]:.3f} | "-                    f"{rows['rust'][index][1]:.3f} | {rows['cpp'][index][1]:.3f} | "-                    f"{rows['spectre'][index][1]:.3f} |"-                )-            lines.extend(-                [-                    "",-                    "### Notes",-                    "",-                    "- Both implementations use the same FastCDC parameters, BLAKE3 object IDs, "-                    "zstd level 1, pack/index layout, operation log, and stat-cache racy window.",-                    "- Each `go` performs the same snapshot, describe, and new-empty-change "-                    "sequence in both implementations, including three operation writes.",-                    "- The Rust subset omits ignore-file parsing and similarity-based rename "-                    "detection. This workload has neither ignore files nor renames, so both "-                    "implementations see the same file set and perform the same exact-rename scan.",-                    "- Rust and C++ store sizes are equal at this resolution; Spectre stores the "-                    "same logical history with a different packing policy.",-                    "- This is a single-machine run. Treat differences below roughly 5% as noise.",-                    "",-                    "### Reproduce",-                    "",-                    "```sh",-                    "cd veins-rust",-                    "cargo build --release",-                    "cd ../veins-cpprewrite",-                    "python3 bench/core_bench.py --repeats 5 --markdown-out bench/core_bench.md",-                    "```",-                    "",-                ]-            )-            args.markdown_out.write_text("\n".join(lines), encoding="utf-8")-        return 0-    finally:-        shutil.rmtree(work, ignore_errors=True)---if __name__ == "__main__":-    raise SystemExit(main())--- a/xveins/bench/net_bench.sh+++ /dev/null@@ -1,482 +0,0 @@-#!/bin/sh-# Compare the C++ rewrite with the Spectre reference over the native protocol.-#-# Requirements: hyperfine, python3, openssl, a built C++ vn, and the Spectre vn-# in ../veins/vn. The script creates a throwaway dataset under bench/.net-bench,-# runs hyperfine, and writes BENCHES.md.-set -eu--SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)-ROOT=$(CDPATH= cd -- "$SCRIPT_DIR/.." && pwd)-REPO=$(CDPATH= cd -- "$ROOT/.." && pwd)--VN_CPP=${VN_CPP:-$ROOT/build/vn}-VN_SPECTRE=${VN_SPECTRE:-$REPO/veins/vn}-HYPERFINE=${HYPERFINE:-hyperfine}-WORK=${WORK:-$ROOT/bench/.net-bench}-OUT=${OUT:-$ROOT/BENCHES.md}-RUNS=${RUNS:-10}-WHOAMI_RUNS=${WHOAMI_RUNS:-20}--SYS_PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"--case "$WORK" in-"" | "/" | ".")-	echo "refusing to use WORK='$WORK'" >&2-	exit 1-	;;-esac--CPP_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_CPP")" && pwd)-SX_DIR=$(CDPATH= cd -- "$(dirname -- "$VN_SPECTRE")" && pwd)-VN_CPP="$CPP_DIR/$(basename -- "$VN_CPP")"-VN_SPECTRE="$SX_DIR/$(basename -- "$VN_SPECTRE")"--for tool in "$VN_CPP" "$VN_SPECTRE"; do-	if [ ! -x "$tool" ]; then-		echo "missing executable: $tool" >&2-		echo "build the C++ rewrite first: cmake --build $ROOT/build" >&2-		exit 1-	fi-done-for tool in "$HYPERFINE" python3 openssl; do-	if ! command -v "$tool" >/dev/null 2>&1; then-		echo "required tool not found: $tool" >&2-		exit 1-	fi-done--rm -rf "$WORK"-mkdir -p "$WORK/config" "$WORK/bench_src" "$WORK/push_pristine" "$WORK/fakebin"--XDG_CONFIG_HOME="$WORK/config"-export XDG_CONFIG_HOME--CPP_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$CPP_DIR:$SYS_PATH' '$VN_CPP'"-SX_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"-CPP_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$CPP_DIR:$SYS_PATH' '$VN_CPP'"-SX_SSH_RUN="env XDG_CONFIG_HOME='$XDG_CONFIG_HOME' PATH='$WORK/fakebin:$SX_DIR:$SYS_PATH' '$VN_SPECTRE'"--run_cpp() {-	env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$CPP_DIR:$SYS_PATH" "$VN_CPP" "$@"-}-run_sx() {-	env XDG_CONFIG_HOME="$XDG_CONFIG_HOME" PATH="$SX_DIR:$SYS_PATH" "$VN_SPECTRE" "$@"-}--wait_port() {-	python3 - "$1" <<'PY'-import socket, sys, time-port = int(sys.argv[1])-for _ in range(100):-    sock = socket.socket()-    sock.settimeout(0.1)-    try:-        sock.connect(("127.0.0.1", port))-        sock.close()-        sys.exit(0)-    except OSError:-        sock.close()-        time.sleep(0.1)-sys.exit(1)-PY-}--generate_small_files() {-	python3 - "$1" "$2" "$3" <<'PY'-import os, sys-root, start, stop = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])-body = ("abcdefghijklmnopqrstuvwxyz" * 70)[:1800]-for d in range(start, stop):-    folder = os.path.join(root, "d%02d" % d)-    os.makedirs(folder, exist_ok=True)-    for f in range(20):-        path = os.path.join(folder, "f%02d.txt" % f)-        with open(path, "w", encoding="utf-8") as handle:-            handle.write("file %d-%d\n" % (d, f))-            handle.write(body)-            handle.write("\n")-PY-}--run_cpp key generate benchkey >"$WORK/key.txt"-PUB=$(awk '/public key:/ {print $3}' "$WORK/key.txt")-if [ -z "$PUB" ]; then-	echo "could not generate the benchmark key" >&2-	exit 1-fi-run_cpp auth use benchkey >/dev/null--grant_access() {-	(cd "$1" && run_cpp access anonymous on &&-		run_cpp access add -role write -key "$PUB" -name bench >/dev/null)-}--(-	cd "$WORK/bench_src"-	run_sx init . >/dev/null-	generate_small_files . 0 12-	python3 - <<'PY'-import os-with open("big_old.bin", "wb") as handle:-    handle.write(os.urandom(2 * 1024 * 1024))-PY-	run_sx go -m "base commit" >/dev/null-	# Point oldbig at the real base commit, not the movable working-copy commit.-	BASE_CHANGE=$(run_sx log | awk '/base commit/ {print $2}' | tail -1)-	if [ -z "$BASE_CHANGE" ]; then-		echo "could not resolve the base commit" >&2-		exit 1-	fi-	run_sx bmk set oldbig -rev "$BASE_CHANGE" >/dev/null-	rm -f big_old.bin-	generate_small_files . 12 18-	python3 - <<'PY'-import os-with open("big_head.bin", "wb") as handle:-    handle.write(os.urandom(1 * 1024 * 1024))-PY-	run_sx go -m "head commit" >/dev/null-	run_sx bmk set main >/dev/null-)-grant_access "$WORK/bench_src"--# A separate small repository for push, so a push does not transfer the large-# dataset. The reference pushes all reachable objects, as does the rewrite.-(-	cd "$WORK/push_pristine"-	run_sx init . >/dev/null-	generate_small_files . 0 1-	run_sx go -m "push base" >/dev/null-	run_sx bmk set main >/dev/null-)-grant_access "$WORK/push_pristine"--run_cpp clone "file://$WORK/bench_src" "$WORK/fetch_pristine_cpp" -blobs:all >/dev/null-run_sx clone "file://$WORK/bench_src" "$WORK/fetch_pristine_sx" -blobs:all >/dev/null-run_cpp clone "file://$WORK/bench_src" "$WORK/lazy_pristine_cpp" -blobs:none >/dev/null-run_sx clone "file://$WORK/bench_src" "$WORK/lazy_pristine_sx" -blobs:none >/dev/null--run_cpp clone "file://$WORK/push_pristine" "$WORK/push_client_cpp" >/dev/null-run_sx clone "file://$WORK/push_pristine" "$WORK/push_client_sx" >/dev/null-(-	cd "$WORK/push_client_cpp"-	printf 'bench push\n' >push.txt-	run_cpp go -m "bench push" >/dev/null-	run_cpp bmk set main >/dev/null-	run_cpp remote set-url origin "file://$WORK/push_srv_cpp"-)-(-	cd "$WORK/push_client_sx"-	printf 'bench push\n' >push.txt-	run_sx go -m "bench push" >/dev/null-	run_sx bmk set main >/dev/null-	run_sx remote set-url origin "file://$WORK/push_srv_sx"-)--cat >"$WORK/fakebin/ssh" <<'SH'-#!/bin/sh-while [ $# -gt 0 ]; do-  case "$1" in-    -p|-l) shift 2 ;;-    -*) shift ;;-    *) break ;;-  esac-done-host=$1-shift-exec /bin/sh -c "$*"-SH-chmod +x "$WORK/fakebin/ssh"--cat >"$WORK/openssl.cnf" <<EOF-[req]-distinguished_name = dn-x509_extensions = v3_req-prompt = no-[dn]-CN = localhost-[v3_req]-subjectAltName = @alt-[alt]-DNS.1 = localhost-IP.1 = 127.0.0.1-EOF-openssl req -x509 -newkey rsa:2048 -nodes \-	-keyout "$WORK/key.pem" -out "$WORK/cert.pem" \-	-days 2 -config "$WORK/openssl.cnf" >/dev/null 2>&1-PIN=$(openssl x509 -in "$WORK/cert.pem" -noout -fingerprint -sha256 |-	sed 's/.*=//;s/://g' | tr 'A-F' 'a-f')--free_port() {-	python3 - <<'PY'-import socket-sock = socket.socket()-sock.bind(("127.0.0.1", 0))-print(sock.getsockname()[1])-sock.close()-PY-}-PORT_CPP=$(free_port)-PORT_SX=$(free_port)-while [ "$PORT_SX" = "$PORT_CPP" ]; do PORT_SX=$(free_port); done--CPP_PID=""-SX_PID=""-cleanup() {-	if [ -n "$CPP_PID" ]; then kill "$CPP_PID" 2>/dev/null || true; fi-	if [ -n "$SX_PID" ]; then kill "$SX_PID" 2>/dev/null || true; fi-	if [ -n "$CPP_PID" ]; then wait "$CPP_PID" 2>/dev/null || true; fi-	if [ -n "$SX_PID" ]; then wait "$SX_PID" 2>/dev/null || true; fi-}-trap cleanup EXIT INT TERM--"$VN_CPP" serve -listen "127.0.0.1:$PORT_CPP" -root "$WORK" \-	-tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \-	>"$WORK/cpp-server.log" 2>&1 &-CPP_PID=$!-"$VN_SPECTRE" serve -listen "127.0.0.1:$PORT_SX" -root "$WORK" \-	-tls-cert "$WORK/cert.pem" -tls-key "$WORK/key.pem" \-	>"$WORK/sx-server.log" 2>&1 &-SX_PID=$!-wait_port "$PORT_CPP"-wait_port "$PORT_SX"--# A tiny repository used only for whoami over TLS.-mkdir -p "$WORK/whoami_repo"-(-	cd "$WORK/whoami_repo"-	run_cpp init . >/dev/null-	run_cpp remote add tls_cpp "veins://localhost:$PORT_CPP/bench_src" \-		-key:benchkey -pin:"$PIN" >/dev/null-	run_cpp remote add tls_sx "veins://localhost:$PORT_SX/bench_src" \-		-key:benchkey -pin:"$PIN" >/dev/null-)--write_prepare() {-	path="$WORK/$1"-	shift-	{-		echo '#!/bin/sh'-		printf '%s\n' "$@"-	} >"$path"-	chmod +x "$path"-}--write_prepare prepare_clone.sh \-	"rm -rf '$WORK/clone_cpp' '$WORK/clone_sx'"-write_prepare prepare_fetch.sh \-	"rm -rf '$WORK/fetch_cpp' '$WORK/fetch_sx'" \-	"cp -R '$WORK/fetch_pristine_cpp' '$WORK/fetch_cpp'" \-	"cp -R '$WORK/fetch_pristine_sx' '$WORK/fetch_sx'"-write_prepare prepare_lazy.sh \-	"rm -rf '$WORK/lazy_cpp' '$WORK/lazy_sx'" \-	"cp -R '$WORK/lazy_pristine_cpp' '$WORK/lazy_cpp'" \-	"cp -R '$WORK/lazy_pristine_sx' '$WORK/lazy_sx'"-write_prepare prepare_push.sh \-	"rm -rf '$WORK/push_srv_cpp' '$WORK/push_srv_sx'" \-	"cp -R '$WORK/push_pristine' '$WORK/push_srv_cpp'" \-	"cp -R '$WORK/push_pristine' '$WORK/push_srv_sx'"-write_prepare prepare_ssh.sh \-	"rm -rf '$WORK/clone_ssh_cpp' '$WORK/clone_ssh_sx'"-write_prepare prepare_tls.sh \-	"rm -rf '$WORK/clone_tls_cpp' '$WORK/clone_tls_sx'"-write_prepare prepare_noop.sh \-	"exit 0"--run_pair() {-	name=$1-	prepare=$2-	runs=$3-	warmup=$4-	cpp_cmd=$5-	sx_cmd=$6-	echo-	echo "== $name =="-	"$HYPERFINE" --style basic --warmup "$warmup" --runs "$runs" \-		--prepare "$prepare" \-		--export-markdown "$WORK/$name.md" \-		--export-json "$WORK/$name.json" \-		-n "C++" "$cpp_cmd" \-		-n "Spectre" "$sx_cmd"-}--SSH_URL="ssh://localhost/$WORK/bench_src"-TLS_CPP_URL="veins://localhost:$PORT_CPP/bench_src"-TLS_SX_URL="veins://localhost:$PORT_SX/bench_src"--run_pair clone-file "$WORK/prepare_clone.sh" "$RUNS" 1 \-	"cd '$WORK' && $CPP_RUN clone 'file://$WORK/bench_src' '$WORK/clone_cpp'" \-	"cd '$WORK' && $SX_RUN clone 'file://$WORK/bench_src' '$WORK/clone_sx'"--run_pair fetch-file "$WORK/prepare_fetch.sh" "$RUNS" 1 \-	"cd '$WORK/fetch_cpp' && $CPP_RUN fetch origin" \-	"cd '$WORK/fetch_sx' && $SX_RUN fetch origin"--run_pair lazy-checkout-file "$WORK/prepare_lazy.sh" "$RUNS" 1 \-	"cd '$WORK/lazy_cpp' && $CPP_RUN co oldbig" \-	"cd '$WORK/lazy_sx' && $SX_RUN co oldbig"--run_pair push-file "$WORK/prepare_push.sh" "$RUNS" 1 \-	"cd '$WORK/push_client_cpp' && $CPP_RUN push origin main" \-	"cd '$WORK/push_client_sx' && $SX_RUN push origin main"--run_pair whoami-file "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \-	"cd '$WORK' && $CPP_RUN whoami 'file://$WORK/bench_src'" \-	"cd '$WORK' && $SX_RUN whoami 'file://$WORK/bench_src'"--run_pair clone-ssh "$WORK/prepare_ssh.sh" "$RUNS" 1 \-	"cd '$WORK' && $CPP_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_cpp'" \-	"cd '$WORK' && $SX_SSH_RUN clone '$SSH_URL' '$WORK/clone_ssh_sx'"--run_pair clone-tls "$WORK/prepare_tls.sh" "$RUNS" 1 \-	"cd '$WORK' && $CPP_RUN clone '$TLS_CPP_URL' '$WORK/clone_tls_cpp' -pin:'$PIN'" \-	"cd '$WORK' && $SX_RUN clone '$TLS_SX_URL' '$WORK/clone_tls_sx' -pin:'$PIN'"--run_pair whoami-tls "$WORK/prepare_noop.sh" "$WHOAMI_RUNS" 2 \-	"cd '$WORK/whoami_repo' && $CPP_RUN whoami tls_cpp" \-	"cd '$WORK/whoami_repo' && $SX_RUN whoami tls_sx"--cleanup-trap - 0 2 15---python3 - "$WORK" >"$WORK/summary.md" <<'PY'-import json, os, sys-work = sys.argv[1]-names = [-    ("clone-file", "Clone file://"),-    ("fetch-file", "Fetch file://"),-    ("lazy-checkout-file", "Lazy checkout file://"),-    ("push-file", "Push file://"),-    ("whoami-file", "Whoami file://"),-    ("clone-ssh", "Clone ssh://"),-    ("clone-tls", "Clone TLS 1.3"),-    ("whoami-tls", "Whoami TLS 1.3"),-]-print("| Benchmark | C++ mean | Spectre mean | Spectre / C++ |")-print("|:---|---:|---:|---:|")-for key, label in names:-    with open(os.path.join(work, key + ".json"), encoding="utf-8") as handle:-        data = json.load(handle)-    means = {r["command"]: r["mean"] for r in data["results"]}-    cpp = means["C++"] * 1000.0-    sx = means["Spectre"] * 1000.0-    ratio = sx / cpp if cpp else float("nan")-    print(f"| {label} | {cpp:.1f} ms | {sx:.1f} ms | {ratio:.2f}x |")-PY--FILE_COUNT=$(find "$WORK/bench_src" -type f -not -path '*/.veins/*' | wc -l | tr -d ' ')-DISK_SIZE=$(du -sh "$WORK/bench_src" | awk '{print $1}')-HOST_TEXT=$(uname -sm)-CPU_TEXT=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m)-HYPERFINE_VERSION=$("$HYPERFINE" --version)-CPP_VERSION=$("$VN_CPP" version)-SX_VERSION=$("$VN_SPECTRE" version)--{-	echo "# veins benchmarks"-	echo-	echo "Two reproducible benchmark sets are kept here: a local-core comparison that includes"-	echo "the Rust subset, and the native network comparison between the C++ rewrite and Spectre."-	echo-	if [ -f "$ROOT/bench/core_bench.md" ]; then-		echo "## Local core: Rust subset vs C++ vs Spectre"-		echo-		cat "$ROOT/bench/core_bench.md"-		echo-	fi-	echo "## Networking: C++ rewrite vs Spectre"-	echo-	echo "Generated $(date -u '+%Y-%m-%d %H:%M:%S UTC') by \`bench/net_bench.sh\`."-	echo-	echo "The Rust subset is not included in this section because it does not implement a"-	echo "network transport."-	echo-	echo "### Environment"-	echo-	echo '```'-	echo "host:        $HOST_TEXT"-	echo "cpu:         $CPU_TEXT"-	echo "hyperfine:   $HYPERFINE_VERSION"-	echo "c++ vn:      $CPP_VERSION"-	echo "spectre vn:  $SX_VERSION"-	echo "runs:        $RUNS (clone/fetch/push/checkout), $WHOAMI_RUNS (whoami)"-	echo "warmup:      1 (clone/fetch/push/checkout), 2 (whoami)"-	echo '```'-	echo-	echo "### Dataset"-	echo-	echo "- \`bench_src\`: $FILE_COUNT working files, $DISK_SIZE on disk including packs."-	echo "  - 360 small text files in 18 directories."-	echo "  - 2 MiB \`big_old.bin\` in the \`oldbig\` history."-	echo "  - 1 MiB \`big_head.bin\` in \`main\`."-	echo "- \`push_pristine\`: a separate 20-file repository, so push does not transfer the large dataset."-	echo-	echo "### What each benchmark does"-	echo-	echo "| Benchmark | Operation |"-	echo "|:---|:---|"-	echo "| \`clone-file\` | Full clone over \`file://\`: handshake, refs, history, head chunks, checkout. Includes spawning one local server per run. |"-	echo "| \`fetch-file\` | \`vn fetch origin\` with no new remote refs. Both clients start from a full \`-blobs:all\` clone. |"-	echo "| \`lazy-checkout-file\` | \`vn co oldbig\` in a \`-blobs:none\` clone, fetching the 2 MiB old blob from the promisor over \`file://\`. |"-	echo "| \`push-file\` | Push one new commit from a prepared client to a freshly reset copy of \`push_pristine\` over \`file://\`. |"-	echo "| \`whoami-file\` | Connect, authenticate, \`WHOAMI\`, close over \`file://\`. |"-	echo "| \`clone-ssh\` | Full clone over \`ssh://\`, using a local \`ssh\` shim that runs the remote \`vn serve -stdio\` command. |"-	echo "| \`clone-tls\` | Full clone over TLS 1.3 with a pinned self-signed certificate. Uses long-running servers. |"-	echo "| \`whoami-tls\` | Connect, authenticate, \`WHOAMI\`, close over TLS 1.3. |"-	echo-	echo "Lower is better. Hyperfine reports wall-clock time; the relative column is against the fastest command."-	echo-	echo "### Summary"-	echo-	cat "$WORK/summary.md"-	echo-	echo "A ratio above 1 means Spectre took longer than C++."-	echo-	echo "### Results"-	echo-	echo "#### Clone over file://"-	cat "$WORK/clone-file.md"-	echo-	echo "#### Fetch over file://"-	cat "$WORK/fetch-file.md"-	echo-	echo "#### Lazy checkout over file://"-	cat "$WORK/lazy-checkout-file.md"-	echo-	echo "#### Push over file://"-	cat "$WORK/push-file.md"-	echo-	echo "#### Whoami over file://"-	cat "$WORK/whoami-file.md"-	echo-	echo "#### Clone over ssh://"-	cat "$WORK/clone-ssh.md"-	echo-	echo "#### Clone over TLS 1.3"-	cat "$WORK/clone-tls.md"-	echo-	echo "#### Whoami over TLS 1.3"-	cat "$WORK/whoami-tls.md"-	echo-	echo "### Notes"-	echo-	echo "- Spectre clone destinations are absolute paths on macOS. The reference checkout hardcodes Linux's \`AT_FDCWD\` value (\`-100\`); with a relative destination it cannot open the working directory on macOS."-	echo "- \`file://\` and \`ssh://\` include server process startup. \`clone-tls\` and \`whoami-tls\` use long-running servers, so they isolate protocol and TLS cost more closely."-	echo "- These runs reproduce the reference's transfer behavior: fetch \`haves\` are operation heads (so metadata is re-sent), and push sends all objects reachable from the bookmark rather than using \`HAVE_QUERY\`."-	echo "- Lazy checkout fetches one missing chunk per promisor connection in both implementations, so it is intentionally a worst-case/read-ahead-free measurement."-	echo "- \`push-file\` is only a few milliseconds of real work; process startup noise can dominate. Read the min/max columns alongside the mean."-	echo "- Treat differences below roughly 10 ms as noise; this is a single-machine run, not a controlled lab measurement."-	echo-	echo "### Reproduce"-	echo-	echo '```sh'-	echo "cd veins-cpprewrite"-	echo "cmake -S . -B build && cmake --build build -j"-	echo "./bench/net_bench.sh"-	echo '```'-} >"$OUT"--echo-echo "wrote $OUT"--- a/xveins/bench/optim_bench.py+++ /dev/null@@ -1,376 +0,0 @@-#!/usr/bin/env python3--"""Compare a pre-optimization vn binary with the current C++ build."""--from __future__ import annotations--import argparse-import os-import platform-import random-import re-import shutil-import statistics-import subprocess-import tempfile-import time-from datetime import datetime, timezone-from pathlib import Path--HEX12 = re.compile(r"\b[0-9a-f]{12}\b")---def command_prefix() -> list[str]:-    try:-        subprocess.run(-            ["taskset", "-c", "0", "true"],-            stdout=subprocess.DEVNULL,-            stderr=subprocess.DEVNULL,-            check=True,-        )-        return ["taskset", "-c", "0"]-    except Exception:-        return []---PREFIX: list[str] = []---def run(cmd: list[str], cwd: Path, check: bool = True) -> str:-    env = os.environ.copy()-    env["LC_ALL"] = "C"-    env["NO_COLOR"] = "1"-    result = subprocess.run(-        [str(part) for part in PREFIX + cmd],-        cwd=str(cwd),-        env=env,-        stdout=subprocess.PIPE,-        stderr=subprocess.PIPE,-        check=check,-        text=True,-    )-    return result.stdout---def timed(cmd: list[str], cwd: Path) -> float:-    start = time.perf_counter()-    run(cmd, cwd)-    return time.perf_counter() - start---def make_base(root: Path, lines: int, small_files: int) -> None:-    root.mkdir(parents=True)-    (root / "generated.c").write_text(-        "".join(f"int value_{i} = {i * 3 + 7};\n" for i in range(lines)),-        encoding="utf-8",-    )-    for i in range(small_files):-        (root / f"module_{i:03d}.c").write_text(-            f"// module {i}\nint module_{i}(void) {{ return {i}; }}\n", encoding="utf-8"-        )-    (root / "sub").mkdir()-    (root / "sub" / "nested.txt").write_text("nested\n" * 200, encoding="utf-8")---def mutate(root: Path, revision: int) -> None:-    path = root / "generated.c"-    lines = path.read_text(encoding="utf-8").splitlines(keepends=True)-    rng = random.Random(revision)-    for _ in range(max(1, len(lines) // 100)):-        index = rng.randrange(len(lines))-        lines[index] = f"int changed_{revision}_{index} = {revision};\n"-    path.write_text("".join(lines), encoding="utf-8")-    for i in range(3):-        (root / f"module_{i:03d}.c").write_text(-            f"// module {i}, revision {revision}\n"-            f"int module_{i}(void) {{ return {revision * 1000 + i}; }}\n",-            encoding="utf-8",-        )---def tree_bytes(root: Path) -> int:-    return sum(path.stat().st_size for path in root.rglob("*") if path.is_file())---def bench_one(-    binary: Path,-    work: Path,-    label: str,-    revisions: int,-    checkouts: int,-    inner_runs: int,-) -> dict[str, float]:-    repo = work / label-    shutil.copytree(work / "base", repo)-    run([str(binary), "init"], repo)-    (repo / ".veins" / "config").write_text(-        "user.name = Bench\nuser.email = bench@example.com\n", encoding="utf-8"-    )-    mutate(repo, 0)-    run([str(binary), "go", "-m", "warmup"], repo)--    commit_total = 0.0-    for revision in range(1, revisions + 1):-        mutate(repo, revision)-        commit_total += timed([str(binary), "go", "-m", f"revision {revision}"], repo)--    status_runs = []-    log_runs = []-    limited_runs = []-    for _ in range(inner_runs):-        status_runs.append(timed([str(binary), "status"], repo))-        log_runs.append(timed([str(binary), "log", "-no-col-titles"], repo))-        limited_runs.append(-            timed([str(binary), "log", "-l", "5", "-no-col-titles"], repo)-        )--    log_lines = run([str(binary), "log", "-no-col-titles"], repo).splitlines()-    targets = []-    for line in log_lines:-        parts = line.split()-        if parts and parts[0] == "@":-            if len(parts) < 3:-                continue-            target = parts[2]-        else:-            if len(parts) < 2:-                continue-            target = parts[1]-        if target not in targets:-            targets.append(target)-        if len(targets) >= checkouts:-            break--    checkout_total = 0.0-    for target in targets:-        checkout_total += timed([str(binary), "co", target], repo)--    return {-        "commit_total": commit_total,-        "status": statistics.median(status_runs),-        "log": statistics.median(log_runs),-        "log_limited": statistics.median(limited_runs),-        "checkout_total": checkout_total,-        "checkout_mean": checkout_total / max(1, len(targets)),-        "store_bytes": float(tree_bytes(repo / ".veins")),-    }---def environment(binary: Path) -> str:-    try:-        return run([str(binary), "version"], Path.cwd()).strip()-    except Exception:-        return "unknown"---def cpu_name() -> str:-    try:-        with open("/proc/cpuinfo", encoding="utf-8") as handle:-            for line in handle:-                if line.startswith("model name"):-                    return line.split(":", 1)[1].strip()-    except Exception:-        pass-    return platform.processor() or platform.machine()---def spread(values: list[float], digits: int) -> str:-    return (-        f"{statistics.median(values):.{digits}f} "-        f"({min(values):.{digits}f}-{max(values):.{digits}f})"-    )---def main() -> int:-    parser = argparse.ArgumentParser(description=__doc__)-    root = Path(__file__).resolve().parents[1]-    parser.add_argument("--baseline", type=Path, required=True)-    parser.add_argument("--optimized", type=Path, default=root / "build" / "vn")-    parser.add_argument("--revisions", type=int, default=80)-    parser.add_argument("--checkouts", type=int, default=8)-    parser.add_argument("--repeats", type=int, default=5)-    parser.add_argument("--inner-runs", type=int, default=3)-    parser.add_argument("--large-lines", type=int, default=120000)-    parser.add_argument("--small-files", type=int, default=40)-    parser.add_argument("--no-pin", action="store_true")-    parser.add_argument("--markdown-out", type=Path, default=root / "BENCH.md")-    args = parser.parse_args()--    global PREFIX-    PREFIX = [] if args.no_pin else command_prefix()--    binaries = {-        "baseline": args.baseline.resolve(),-        "optimized": args.optimized.resolve(),-    }-    for label, binary in binaries.items():-        if not binary.exists():-            print(f"missing {label} binary: {binary}")-            return 2--    work = Path(tempfile.mkdtemp(prefix="veins-optim-bench-"))-    try:-        make_base(work / "base", args.large_lines, args.small_files)-        size = tree_bytes(work / "base")-        print(-            f"workload: {size / (1024 * 1024):.2f} MiB, {args.revisions} revisions, "-            f"{args.checkouts} checkouts, {args.repeats} repeats"-        )-        rows: dict[str, list[dict[str, float]]] = {"baseline": [], "optimized": []}-        for repeat in range(args.repeats):-            print(f"repeat {repeat + 1}/{args.repeats}")-            for label, binary in binaries.items():-                row = bench_one(-                    binary,-                    work,-                    f"{label}-{repeat}",-                    args.revisions,-                    args.checkouts,-                    args.inner_runs,-                )-                rows[label].append(row)-                print(-                    f"  {label}: commit {row['commit_total']:.3f}s "-                    f"status {row['status'] * 1000:.1f}ms "-                    f"log {row['log'] * 1000:.1f}ms "-                    f"checkout {row['checkout_mean'] * 1000:.1f}ms"-                )--        def median(label: str, key: str) -> float:-            return statistics.median(row[key] for row in rows[label])--        def values(label: str, key: str) -> list[float]:-            return [row[key] for row in rows[label]]--        metrics = [-            ("Commit total [s]", "commit_total", 1.0, 4),-            ("Status [ms]", "status", 1000.0, 1),-            ("Log [ms]", "log", 1000.0, 1),-            ("Log -l 5 [ms]", "log_limited", 1000.0, 1),-            # store size below is converted with a fractional multiplier-            ("Checkout total [s]", "checkout_total", 1.0, 4),-            ("Checkout mean [ms]", "checkout_mean", 1000.0, 1),-            ("Store size [MiB]", "store_bytes", 1.0 / (1024.0 * 1024.0), 2),-        ]--        lines = [-            "# veins C++ optimization benchmark",-            "",-            f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by "-            "`bench/optim_bench.py`.",-            "",-            "### Environment",-            "",-            "| Binary | Version |",-            "|:---|:---|",-            f"| Baseline | `{environment(args.baseline)}` |",-            f"| Optimized | `{environment(args.optimized)}` |",-            "",-            "```",-            f"host:        {platform.system()} {platform.machine()}",-            f"cpu:         {cpu_name()}",-            f"repeats:     {args.repeats} (median reported)",-            f"inner runs:  {args.inner_runs} per command per repeat",-            f"cpu pinning: {'yes' if PREFIX else 'no'}",-            f"temp dir:    {os.environ.get('TMPDIR', '(system default)')}",-            "```",-            "",-            "### Workload",-            "",-            f"- Base snapshot: {size / (1024 * 1024):.2f} MiB, "-            f"{args.small_files + 2} files.",-            f"- {args.revisions} edit/commit revisions, {args.checkouts} checkouts, "-            f"{args.repeats} repeats, median reported.",-            "- Each revision rewrites about 1% of a 120,000-line generated C file and "-            "three small module files.",-            "- Commit total covers all revision commits in the run.",-            "- Status and log are measured on the full history after the last commit.",-            "- Checkout walks the newest revisions in descending order.",-            "",-            "### Results",-            "",-            "| Metric | Baseline | Optimized | Speedup |",-            "|:---|---:|---:|---:|",-        ]-        for name, key, scale, digits in metrics:-            base_values = [value * scale for value in values("baseline", key)]-            opt_values = [value * scale for value in values("optimized", key)]-            base_med = statistics.median(base_values)-            opt_med = statistics.median(opt_values)-            if key == "store_bytes":-                ratio = base_med / opt_med-                ratio_text = (-                    f"{ratio:.2f}x smaller"-                    if ratio >= 1-                    else f"{1 / ratio:.2f}x larger"-                )-            else:-                ratio = base_med / opt_med-                ratio_text = f"{ratio:.2f}x"-            lines.append(-                f"| {name} | {spread(base_values, digits)} | "-                f"{spread(opt_values, digits)} | {ratio_text} |"-            )--        lines.extend(-            [-                "",-                "Each cell is the median with the observed min-max range in parentheses.",-                "A speedup above 1 means the optimized binary was faster.",-                "",-                "### Repeats",-                "",-                "| Repeat | Baseline status [ms] | Optimized status [ms] | "-                "Baseline log [ms] | Optimized log [ms] | "-                "Baseline checkout [ms] | Optimized checkout [ms] |",-                "|:---|---:|---:|---:|---:|---:|---:|",-            ]-        )-        for index in range(args.repeats):-            base = rows["baseline"][index]-            opt = rows["optimized"][index]-            lines.append(-                f"| {index + 1} | {base['status'] * 1000:.1f} | "-                f"{opt['status'] * 1000:.1f} | {base['log'] * 1000:.1f} | "-                f"{opt['log'] * 1000:.1f} | {base['checkout_mean'] * 1000:.1f} | "-                f"{opt['checkout_mean'] * 1000:.1f} |"-            )--        lines.extend(-            [-                "",-                "### Notes",-                "",-                "- The optimized build reads only the requested record from a pack instead "-                "of decoding the whole pack for every lookup.",-                "- Status and log memoize conflict-tree results and avoid flattening trees "-                "that are already equal.",-                "- Checkout reuses a single store, preloads indexes only, and skips rewriting "-                "files whose target object did not change.",-                "- Commit keeps the same object format, compression level, and operation-log "-                "sequence. Its gains come from fewer pack decodes and from writing the "-                "describe and new operations in one chained pack.",-                "- The baseline binary is the C++ build from before these changes. Rebuild "-                "each binary from its own source snapshot before reproducing.",-                "- This is a single-machine run. Treat differences below roughly 5% as noise.",-                "",-                "### Reproduce",-                "",-                "```sh",-                "cmake --build build -j",-                "python3 bench/optim_bench.py \\",-                "  --baseline /path/to/pre-optimization/vn \\",-                "  --optimized build/vn \\",-                "  --markdown-out BENCH.md",-                "```",-                "",-            ]-        )-        args.markdown_out.write_text("\n".join(lines), encoding="utf-8")-        return 0-    finally:-        shutil.rmtree(work, ignore_errors=True)---if __name__ == "__main__":-    raise SystemExit(main())--- a/xveins/bench/spectre_bench.py+++ /dev/null@@ -1,353 +0,0 @@-#!/usr/bin/env python3--"""Compare a baseline vn binary with the current build on a real repository.--The default repository is ../spectre2, a 2,600-commit veins repository whose-pack index is large enough to make pack lookups the dominant cost of read-only-commands. A git import benchmark can be enabled with --git-source.-"""--from __future__ import annotations--import argparse-import os-import platform-import shutil-import statistics-import subprocess-import tempfile-import time-from datetime import datetime, timezone-from pathlib import Path---def cpu_name() -> str:-    try:-        with open("/proc/cpuinfo", encoding="utf-8") as handle:-            for line in handle:-                if line.startswith("model name"):-                    return line.split(":", 1)[1].strip()-    except Exception:-        pass-    return platform.processor() or platform.machine()---def run(binary: Path, args: list[str], cwd: Path, check: bool = True) -> str:-    env = os.environ.copy()-    env["LC_ALL"] = "C"-    env["NO_COLOR"] = "1"-    env["NO_PROGRESS"] = "1"-    result = subprocess.run(-        [str(binary), *args],-        cwd=str(cwd),-        env=env,-        stdout=subprocess.PIPE,-        stderr=subprocess.PIPE,-        check=check,-        text=True,-    )-    return result.stdout---def timed(binary: Path, args: list[str], cwd: Path) -> float:-    start = time.perf_counter()-    run(binary, args, cwd)-    return time.perf_counter() - start---def spread(values: list[float], digits: int) -> str:-    return (-        f"{statistics.median(values):.{digits}f} "-        f"({min(values):.{digits}f}-{max(values):.{digits}f})"-    )---def command_median(binary: Path, args: list[str], cwd: Path, runs: int) -> float:-    return statistics.median(timed(binary, args, cwd) for _ in range(runs))---def timed_git(args: list[str], cwd: Path) -> float:-    env = os.environ.copy()-    env["LC_ALL"] = "C"-    env["GIT_PAGER"] = "cat"-    start = time.perf_counter()-    subprocess.run(-        ["git", "-C", str(cwd), *args],-        env=env,-        stdout=subprocess.DEVNULL,-        stderr=subprocess.DEVNULL,-        check=True,-    )-    return time.perf_counter() - start---def version(binary: Path) -> str:-    try:-        return run(binary, ["version"], Path.cwd()).strip()-    except Exception:-        return "unknown"---def repo_info(binary: Path, repo: Path) -> tuple[int, int]:-    pack_dir = repo / ".veins" / "store" / "packs"-    pack_bytes = sum(path.stat().st_size for path in pack_dir.glob("*.vpack"))-    try:-        log = run(binary, ["log", "-l", "1000000", "-no-col-titles"], repo)-        commits = max(0, len(log.splitlines()) - 1)-    except Exception:-        commits = 0-    return commits, pack_bytes---def bench_import(binary: Path, git_source: Path, work: Path, label: str) -> float:-    target = work / label-    if target.exists():-        shutil.rmtree(target)-    start = time.perf_counter()-    run(binary, ["init", str(target), f"-git-import:{git_source}"], work)-    elapsed = time.perf_counter() - start-    shutil.rmtree(target, ignore_errors=True)-    return elapsed---def main() -> int:-    parser = argparse.ArgumentParser(description=__doc__)-    root = Path(__file__).resolve().parents[1]-    parser.add_argument(-        "--repo",-        type=Path,-        default=root.parent.parent / "spectre2",-        help="veins repository to benchmark (default: ../spectre2 next to the source tree)",-    )-    parser.add_argument("--baseline", type=Path, required=True)-    parser.add_argument("--optimized", type=Path, default=root / "build" / "vn")-    parser.add_argument("--repeats", type=int, default=7)-    parser.add_argument("--inner-runs", type=int, default=3)-    parser.add_argument(-        "--git-source",-        type=Path,-        default=root.parent.parent / "spectre",-        help="git repository used for the optional import benchmark",-    )-    parser.add_argument("--import-repeats", type=int, default=0)-    parser.add_argument("--markdown-out", type=Path, default=root / "BENCH_SPECTRE.md")-    args = parser.parse_args()--    repo = args.repo.resolve()-    baseline = args.baseline.resolve()-    optimized = args.optimized.resolve()-    for label, binary in (("baseline", baseline), ("optimized", optimized)):-        if not binary.exists():-            print(f"missing {label} binary: {binary}")-            return 2-    if not (repo / ".veins").is_dir():-        print(f"not a veins repository: {repo}")-        return 2--    commands = {-        "log": ["log"],-        "log_l1": ["log", "-l", "1"],-        "log_l1000": ["log", "-l", "1000"],-        "status": ["status"],-        "show": ["show"],-    }--    # Make sure both binaries agree before timing anything.-    for name, command in commands.items():-        reference = run(baseline, command, repo)-        candidate = run(optimized, command, repo)-        if reference != candidate:-            print(f"output mismatch for vn {' '.join(command)} in {repo}")-            return 3--    print(f"repository: {repo}")-    commits, pack_bytes = repo_info(optimized, repo)-    print(f"commits: {commits}, packs: {pack_bytes / (1024 * 1024):.1f} MiB")--    rows: dict[str, dict[str, list[float]]] = {-        name: {"baseline": [], "optimized": []} for name in commands-    }-    for repeat in range(args.repeats):-        print(f"repeat {repeat + 1}/{args.repeats}")-        for name, command in commands.items():-            for label, binary in (("baseline", baseline), ("optimized", optimized)):-                value = command_median(binary, command, repo, args.inner_runs)-                rows[name][label].append(value)-            base_ms = statistics.median(rows[name]["baseline"]) * 1000-            opt_ms = statistics.median(rows[name]["optimized"]) * 1000-            print(f"  {name:<10} baseline {base_ms:7.1f}ms  optimized {opt_ms:7.1f}ms")--    import_rows: dict[str, list[float]] = {"baseline": [], "optimized": []}-    if args.import_repeats > 0:-        if not (args.git_source / ".git").is_dir():-            print(f"--git-source is not a git repository: {args.git_source}")-            return 2-        work = Path(tempfile.mkdtemp(prefix="veins-spectre-import-"))-        try:-            for label, binary in (("baseline", baseline), ("optimized", optimized)):-                print(f"import warmup {label}")-                bench_import(binary, args.git_source.resolve(), work, f"warmup-{label}")-            for repeat in range(args.import_repeats):-                print(f"import repeat {repeat + 1}/{args.import_repeats}")-                order = [("baseline", baseline), ("optimized", optimized)]-                if repeat % 2 == 1:-                    order.reverse()-                for label, binary in order:-                    value = bench_import(-                        binary, args.git_source.resolve(), work, f"{label}-{repeat}"-                    )-                    import_rows[label].append(value)-                    print(f"  import {label:<9} {value:.3f}s")-        finally:-            shutil.rmtree(work, ignore_errors=True)--    git_reference: dict[str, float] = {}-    git_source = args.git_source.resolve()-    if (git_source / ".git").is_dir():-        print("git reference")-        for name, git_args in (-            ("log", ["log", "-n", "20"]),-            ("log_l1", ["log", "-n", "1"]),-            ("log_l1000", ["log", "-n", "1000"]),-            ("log_full", ["log"]),-        ):-            values = [timed_git(git_args, git_source) for _ in range(args.inner_runs)]-            git_reference[name] = statistics.median(values)-            print(f"  git {name:<10} {git_reference[name] * 1000:7.1f}ms")--    names = {-        "log": "Log [ms]",-        "log_l1": "Log -l 1 [ms]",-        "log_l1000": "Log -l 1000 [ms]",-        "status": "Status [ms]",-        "show": "Show [ms]",-    }-    lines = [-        "# veins C++ spectre benchmark",-        "",-        f"Generated {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')} by "-        "`bench/spectre_bench.py`.",-        "",-        "### Environment",-        "",-        "| Binary | Version | Path |",-        "|:---|:---|:---|",-        f"| Baseline | `{version(baseline)}` | `{baseline}` |",-        f"| Optimized | `{version(optimized)}` | `{optimized}` |",-        "",-        "```",-        f"host:        {platform.system()} {platform.machine()}",-        f"cpu:         {cpu_name()}",-        f"repeats:     {args.repeats} (median reported)",-        f"inner runs:  {args.inner_runs} per command per repeat",-        f"repository:  {repo}",-        f"commits:     {commits}",-        f"pack bytes:  {pack_bytes / (1024 * 1024):.1f} MiB",-        "```",-        "",-        "### Workload",-        "",-        "- Read-only commands run against an existing veins repository with a large pack.",-        "- Each cell is the median of the per-repeat command medians.",-        "- Progress output is disabled; both binaries write to a pipe.",-        "- Baseline and optimized outputs are compared byte-for-byte before timing.",-    ]-    if args.import_repeats > 0:-        lines.append(-            f"- Git import runs {args.import_repeats}x from `{args.git_source.resolve()}` "-            "into a fresh temporary repository."-        )-    lines.extend(-        [-            "",-            "### Results",-            "",-            "| Metric | Baseline | Optimized | Speedup |",-            "|:---|---:|---:|---:|",-        ]-    )-    for name in commands:-        base_values = [value * 1000 for value in rows[name]["baseline"]]-        opt_values = [value * 1000 for value in rows[name]["optimized"]]-        base_med = statistics.median(base_values)-        opt_med = statistics.median(opt_values)-        ratio = base_med / opt_med if opt_med > 0 else float("inf")-        lines.append(-            f"| {names[name]} | {spread(base_values, 1)} | "-            f"{spread(opt_values, 1)} | {ratio:.2f}x |"-        )-    if import_rows["baseline"]:-        base_values = import_rows["baseline"]-        opt_values = import_rows["optimized"]-        base_med = statistics.median(base_values)-        opt_med = statistics.median(opt_values)-        ratio = base_med / opt_med if opt_med > 0 else float("inf")-        lines.append(-            f"| Git import [s] | {spread(base_values, 3)} | "-            f"{spread(opt_values, 3)} | {ratio:.2f}x |"-        )--    lines.extend(-        [-            "",-            "Each cell is the median with the observed min-max range in parentheses.",-            "A speedup above 1 means the optimized binary was faster.",-        ]-    )--    if git_reference:-        lines.extend(-            [-                "",-                "### Git reference",-                "",-                f"Timed against `{git_source}` with the same machine and warm cache.",-                "",-                "| Command | Median |",-                "|:---|---:|",-                f"| `git log -n 20` | {git_reference['log'] * 1000:.1f} ms |",-                f"| `git log -n 1` | {git_reference['log_l1'] * 1000:.1f} ms |",-                f"| `git log -n 1000` | {git_reference['log_l1000'] * 1000:.1f} ms |",-                f"| `git log` (all) | {git_reference['log_full'] * 1000:.1f} ms |",-            ]-        )--    lines.extend(-        [-            "",-            "### Notes",-            "",-            "- Pack reads keep one file descriptor per pack and use positional reads. "-            "The baseline reopened and seeked the pack for every record header and body.",-            "- Log no longer computes conflict state for commits outside the requested "-            "window, and divergence detection is linear instead of quadratic.",-            "- `git log -n N` truncates by date after reading N commits. `vn log` still "-            "walks the full reachable graph so every child is printed before its parents; "-            "compare it with full `git log` rather than `git log -n 20`.",-            "- Git import, git materialize, cloning, and push report progress on stderr "-            "when stderr is a terminal. Progress output is suppressed for pipes, so the "-            "timings above are unaffected by it.",-            "- Git import is dominated by copying the mirror and reading git objects, not "-            "by veins pack lookups. It is not part of this optimization; enable it with "-            "`--import-repeats N` when you want a rough import timing.",-            "- This is a single-machine run. Treat differences below roughly 5% as noise.",-            "",-            "### Reproduce",-            "",-            "```sh",-            "cmake --build build -j",-            "python3 bench/spectre_bench.py \\",-            "  --baseline /path/to/pre-optimization/vn \\",-            "  --repo /path/to/spectre2 \\",-            "  --markdown-out BENCH_SPECTRE.md",-            "```",-            "",-        ]-    )-    args.markdown_out.write_text("\n".join(lines), encoding="utf-8")-    print(f"wrote {args.markdown_out}")-    return 0---if __name__ == "__main__":-    raise SystemExit(main())--- a/xveins/cmake/generate_vn_commit.cmake+++ /dev/null@@ -1,58 +0,0 @@-# Compute the revision embedded in the vn binary. The bootstrap vn executable-# is preferred because it reports the current veins working-copy revision and-# works wherever the source tree is a veins checkout. Git is the fallback for-# git-based checkouts and source archives.--set(_commit "")--if(EXISTS "${VN_BOOTSTRAP}")-    execute_process(-        COMMAND "${VN_BOOTSTRAP}" hash -short-        WORKING_DIRECTORY "${VN_SOURCE_DIR}"-        OUTPUT_VARIABLE _output-        OUTPUT_STRIP_TRAILING_WHITESPACE-        ERROR_QUIET-        RESULT_VARIABLE _result-        TIMEOUT 120-    )-    if(_result EQUAL 0)-        string(STRIP "${_output}" _output)-        string(REPLACE "\r" "" _output "${_output}")-        if(_output MATCHES "^[0-9a-fA-F]+$")-            set(_commit "${_output}")-        endif()-    endif()-endif()--if(NOT _commit)-    execute_process(-        COMMAND git rev-parse --short=12 HEAD-        WORKING_DIRECTORY "${VN_SOURCE_DIR}"-        OUTPUT_VARIABLE _output-        OUTPUT_STRIP_TRAILING_WHITESPACE-        ERROR_QUIET-        RESULT_VARIABLE _result-    )-    if(_result EQUAL 0)-        string(STRIP "${_output}" _output)-        string(REPLACE "\r" "" _output "${_output}")-        if(_output MATCHES "^[0-9a-fA-F]+$")-            set(_commit "${_output}")-        endif()-    endif()-endif()--file(MAKE_DIRECTORY "${VN_OUTPUT_DIR}")-set(_header "// Generated at build time. Do not edit.\n")-string(APPEND _header "#define VN_COMMIT \"${_commit}\"\n")--set(_write TRUE)-if(EXISTS "${VN_OUTPUT_DIR}/vn_commit.h")-    file(READ "${VN_OUTPUT_DIR}/vn_commit.h" _existing)-    if(_existing STREQUAL _header)-        set(_write FALSE)-    endif()-endif()-if(_write)-    file(WRITE "${VN_OUTPUT_DIR}/vn_commit.h" "${_header}")-endif()--- a/xveins/src/auth/auth.cpp+++ /dev/null@@ -1,502 +0,0 @@-#include "auth/auth.h"--#include "store/store.h"--#include <algorithm>-#include <cstdlib>-#include <cstring>--#if defined(_WIN32)-#include <io.h>-#else-#include <sys/stat.h>-#include <unistd.h>-#endif--namespace vn::auth {--namespace {--std::optional<std::string> env_value(const char* name) {-    const char* value = std::getenv(name);-    if (!value || !*value)-        return std::nullopt;-    return std::string(value);-}--std::string lower_ascii(std::string_view text) {-    std::string out(text);-    for (char& c : out) {-        if (c >= 'A' && c <= 'Z')-            c = static_cast<char>(c + 32);-    }-    return out;-}--std::string_view trim_view(std::string_view text) {-    std::size_t start = 0;-    std::size_t end = text.size();-    auto blank = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };-    while (start < end && blank(text[start]))-        ++start;-    while (end > start && blank(text[end - 1]))-        --end;-    return text.substr(start, end - start);-}--int file_mode(const fs::path& path) {-#if defined(_WIN32)-    (void)path;-    return 0600;-#else-    struct stat info {};-    if (::stat(path.c_str(), &info) != 0)-        return -1;-    return static_cast<int>(info.st_mode & 07777);-#endif-}--bool set_mode(const fs::path& path, int mode) {-#if defined(_WIN32)-    (void)path;-    (void)mode;-    return true;-#else-    return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0;-#endif-}--bool valid_key_name(std::string_view name) {-    if (name.empty() || name.size() > 128)-        return false;-    for (char c : name) {-        if (c == '/' || c == '\\' || c == '\0')-            return false;-    }-    return true;-}--std::string hex_encode(std::string_view data) {-    static constexpr char digits[] = "0123456789abcdef";-    std::string out;-    out.reserve(data.size() * 2);-    for (char raw : data) {-        const auto c = static_cast<unsigned char>(raw);-        out.push_back(digits[c >> 4]);-        out.push_back(digits[c & 15]);-    }-    return out;-}--std::optional<std::string> hex_decode(std::string_view text) {-    if (text.empty() || text.size() % 2 != 0)-        return std::nullopt;-    auto value = [](char c) -> int {-        if (c >= '0' && c <= '9')-            return c - '0';-        if (c >= 'a' && c <= 'f')-            return c - 'a' + 10;-        return -1;-    };-    std::string out;-    out.reserve(text.size() / 2);-    for (std::size_t i = 0; i < text.size(); i += 2) {-        const int high = value(text[i]);-        const int low = value(text[i + 1]);-        if (high < 0 || low < 0)-            return std::nullopt;-        out.push_back(static_cast<char>((high << 4) | low));-    }-    return out;-}--std::string_view strip_user(std::string_view authority) {-    const auto at = authority.rfind('@');-    if (at != std::string_view::npos)-        return authority.substr(at + 1);-    return authority;-}--std::optional<std::string> authority_of(std::string_view input) {-    std::size_t start = 0;-    const auto scheme = input.find("://");-    if (scheme != std::string_view::npos)-        start = scheme + 3;-    if (start >= input.size())-        return std::nullopt;-    const auto slash = input.find('/', start);-    const std::size_t end = slash == std::string_view::npos ? input.size() : slash;-    if (end <= start)-        return std::nullopt;-    const std::string_view raw = input.substr(start, end - start);-    const std::string_view host = strip_user(raw);-    if (host.empty())-        return std::nullopt;-    return lower_ascii(host);-}--std::optional<std::string> host_without_port(std::string_view host) {-    if (host.empty() || host.front() == '[')-        return std::nullopt;-    const auto colon = host.rfind(':');-    if (colon == std::string_view::npos || colon == 0)-        return std::nullopt;-    return std::string(host.substr(0, colon));-}--fs::path target_path(const fs::path& dir, std::string_view target) {-    return dir / hex_encode(target);-}--std::optional<std::string> read_credential(const fs::path& path) {-    auto data = read_file_opt(path);-    if (!data)-        return std::nullopt;-    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    const std::string_view value = trim_view(text);-    if (value.empty())-        return std::nullopt;-    return std::string(value);-}--std::optional<std::string> lookup_credential(const fs::path& dir, std::string_view target) {-    return read_credential(target_path(dir, target));-}--std::vector<std::string_view> tokenize(std::string_view line) {-    std::vector<std::string_view> out;-    std::size_t start = 0;-    for (std::size_t i = 0; i <= line.size(); ++i) {-        const bool at_end = i == line.size();-        if (at_end || line[i] == ' ' || line[i] == '\t') {-            if (i > start)-                out.push_back(line.substr(start, i - start));-            start = i + 1;-        }-    }-    return out;-}--Access invalid_access(std::int64_t line) {-    Access out;-    out.valid = false;-    out.error_line = line;-    return out;-}--} // namespace--fs::path key_dir() {-    if (auto xdg = env_value("XDG_CONFIG_HOME"))-        return path_from_bytes(*xdg) / "veins" / "keys";-    if (auto home = env_value("HOME"))-        return path_from_bytes(*home) / ".config" / "veins" / "keys";-#if defined(_WIN32)-    if (auto appdata = env_value("APPDATA"))-        return path_from_bytes(*appdata) / "veins" / "keys";-#endif-    return fs::path(".veins-keys");-}--fs::path key_path(std::string_view name) {-    return key_dir() / (std::string(name) + ".key");-}--std::optional<Key> load_key(std::string_view name) {-    if (!valid_key_name(name))-        return std::nullopt;-    const fs::path path = key_path(name);-    const int mode = file_mode(path);-    if (mode < 0 || (mode & 63) != 0)-        return std::nullopt;-    auto data = read_file_opt(path);-    if (!data || data->size() != 33 || (*data)[0] != 1)-        return std::nullopt;-    std::vector<std::uint8_t> seed(data->begin() + 1, data->end());-    auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));-    if (!public_key)-        return std::nullopt;-    Key key;-    key.name = std::string(name);-    key.seed = std::move(seed);-    key.public_key = *public_key;-    key.fingerprint = key_fingerprint(*public_key);-    return key;-}--std::optional<Key> generate_key(std::string_view name) {-    if (!valid_key_name(name))-        return std::nullopt;-    const fs::path dir = key_dir();-    if (!ensure_directory(dir))-        return std::nullopt;-    (void)set_mode(dir, 0700);-    const auto seed = secure_random(32);-    if (seed.size() != 32)-        return std::nullopt;-    auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));-    if (!public_key)-        return std::nullopt;-    std::vector<std::uint8_t> body;-    body.reserve(33);-    body.push_back(1);-    body.insert(body.end(), seed.begin(), seed.end());-    const fs::path path = key_path(name);-    if (!write_file(path, Bytes(body.data(), body.size())))-        return std::nullopt;-    (void)set_mode(path, 0600);-    Key key;-    key.name = std::string(name);-    key.seed = seed;-    key.public_key = *public_key;-    key.fingerprint = key_fingerprint(*public_key);-    return key;-}--std::vector<std::string> list_key_names() {-    std::vector<std::string> out;-    const fs::path dir = key_dir();-    if (!path_is_dir(dir))-        return out;-    for (const auto& name : list_directory(dir)) {-        if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)-            out.push_back(name.substr(0, name.size() - 4));-    }-    return out;-}--fs::path auth_dir() {-    const fs::path dir = key_dir();-    const fs::path parent = dir.parent_path();-    if (parent.empty())-        return fs::path(".veins-auth");-    return parent / "auth";-}--std::string normalize_target(std::string_view input) {-    const std::string_view trimmed = trim_view(input);-    if (trimmed.empty() || trimmed == "default")-        return "default";-    if (auto authority = authority_of(trimmed))-        return *authority;-    const auto slash = trimmed.find('/');-    const std::string_view raw =-        slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);-    const std::string_view host = strip_user(raw);-    if (host.empty())-        return "default";-    return lower_ascii(host);-}--bool set_key(std::string_view target, std::string_view key_name) {-    if (target.empty() || key_name.empty())-        return false;-    const fs::path dir = auth_dir();-    if (!ensure_directory(dir))-        return false;-    return write_file(target_path(dir, target), bytes_of(key_name));-}--bool remove_key(std::string_view target) {-    return remove_file(target_path(auth_dir(), target));-}--std::vector<std::string> list_credential_lines() {-    std::vector<std::string> out;-    const fs::path dir = auth_dir();-    if (!path_is_dir(dir))-        return out;-    for (const auto& name : list_directory(dir)) {-        auto decoded = hex_decode(name);-        if (!decoded)-            continue;-        auto key = read_credential(target_path(dir, *decoded));-        if (!key)-            continue;-        out.push_back(*decoded + ": " + *key + "\n");-    }-    return out;-}--bool local_key_exists(std::string_view name) {-    if (name.empty() || name.starts_with("ed25519:"))-        return false;-    return load_key(name).has_value();-}--std::optional<std::string> key_for_url(std::string_view url) {-    const fs::path dir = auth_dir();-    if (auto host = authority_of(url)) {-        if (auto exact = lookup_credential(dir, *host))-            return exact;-        if (auto base = host_without_port(*host)) {-            if (auto without_port = lookup_credential(dir, *base))-                return without_port;-        }-    }-    return lookup_credential(dir, "default");-}--Access empty_access() {-    return Access{};-}--fs::path access_path(const fs::path& repo_root) {-    return veins_dir(repo_root) / "access";-}--Access load_access(const fs::path& repo_root) {-    const fs::path path = access_path(repo_root);-    const int mode = file_mode(path);-    if (mode >= 0 && (mode & 18) != 0)-        return invalid_access(0);-    auto data = read_file_opt(path);-    if (!data)-        return empty_access();-    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    Access access;-    std::size_t start = 0;-    std::int64_t line_no = 0;-    std::size_t i = 0;-    for (;;) {-        const bool at_end = i >= text.size();-        if (at_end || text[i] == '\n') {-            ++line_no;-            const std::string_view line = trim_view(text.substr(start, i - start));-            if (!line.empty() && line.front() != '#') {-                const auto tokens = tokenize(line);-                bool bad = false;-                if (tokens.size() == 2 && tokens[0] == "anonymous") {-                    if (tokens[1] == "read")-                        access.anonymous_read = true;-                    else-                        bad = true;-                } else if (tokens.size() >= 3 && tokens[0] == "allow") {-                    std::uint8_t role = 0;-                    if (tokens[1] == "read")-                        role = ROLE_READ;-                    else if (tokens[1] == "write")-                        role = ROLE_WRITE;-                    else-                        bad = true;-                    auto public_key = parse_public_key(tokens[2]);-                    if (!public_key)-                        bad = true;-                    if (!bad) {-                        const bool duplicate = std::any_of(-                            access.entries.begin(), access.entries.end(),-                            [&](const AccessEntry& entry) {-                                return std::memcmp(entry.public_key.data(), public_key->data(),-                                                   public_key->size()) == 0;-                            });-                        if (duplicate) {-                            bad = true;-                        } else {-                            AccessEntry entry;-                            entry.public_key = *public_key;-                            entry.role = role;-                            if (tokens.size() >= 4)-                                entry.name = std::string(tokens[3]);-                            access.entries.push_back(std::move(entry));-                        }-                    }-                } else {-                    bad = true;-                }-                if (bad)-                    return invalid_access(line_no);-            }-            start = i + 1;-        }-        if (at_end)-            break;-        ++i;-    }-    return access;-}--bool write_access(const fs::path& repo_root, const Access& access) {-    std::string body = "# veins access policy\n";-    if (access.anonymous_read)-        body += "anonymous read\n";-    for (const auto& entry : access.entries) {-        if (entry.name.size() > 64)-            return false;-        body += "allow ";-        body += entry.role == ROLE_WRITE ? "write" : "read";-        body += " ";-        body += format_public_key(entry.public_key);-        if (!entry.name.empty()) {-            body += " ";-            body += entry.name;-        }-        body += "\n";-    }-    const fs::path path = access_path(repo_root);-    if (!write_file(path, bytes_of(body)))-        return false;-    (void)set_mode(path, 0600);-    return true;-}--std::uint8_t role_for(const Access& access, const PublicKey* public_key) {-    if (!public_key) {-        if (access.anonymous_read)-            return ROLE_READ;-        return ROLE_ANONYMOUS;-    }-    for (const auto& entry : access.entries) {-        if (std::memcmp(entry.public_key.data(), public_key->data(), public_key->size()) == 0) {-            return entry.role;-        }-    }-    return ROLE_UNKNOWN;-}--bool add_access(const fs::path& repo_root, std::uint8_t role, const PublicKey& public_key,-                std::string_view name) {-    Access access = load_access(repo_root);-    if (!access.valid)-        return false;-    for (const auto& entry : access.entries) {-        if (std::memcmp(entry.public_key.data(), public_key.data(), public_key.size()) == 0)-            return false;-    }-    AccessEntry entry;-    entry.public_key = public_key;-    entry.role = role;-    entry.name = std::string(name);-    access.entries.push_back(std::move(entry));-    return write_access(repo_root, access);-}--bool remove_access(const fs::path& repo_root, std::string_view fingerprint, std::string_view name) {-    Access access = load_access(repo_root);-    if (!access.valid)-        return false;-    bool removed = false;-    std::vector<AccessEntry> kept;-    kept.reserve(access.entries.size());-    for (const auto& entry : access.entries) {-        const bool match_fingerprint =-            !fingerprint.empty() && key_fingerprint(entry.public_key) == fingerprint;-        const bool match_name = !name.empty() && entry.name == name;-        if (match_fingerprint || match_name) {-            removed = true;-        } else {-            kept.push_back(entry);-        }-    }-    access.entries = std::move(kept);-    return removed && write_access(repo_root, access);-}--bool set_anonymous(const fs::path& repo_root, bool enabled) {-    Access access = load_access(repo_root);-    if (!access.valid)-        return false;-    access.anonymous_read = enabled;-    return write_access(repo_root, access);-}--} // namespace vn::auth--- a/xveins/src/auth/auth.h+++ /dev/null@@ -1,62 +0,0 @@-#pragma once--#include "crypto/crypto.h"--#include <cstdint>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn::auth {--constexpr std::uint8_t ROLE_ANONYMOUS = 0;-constexpr std::uint8_t ROLE_READ = 1;-constexpr std::uint8_t ROLE_WRITE = 2;-constexpr std::uint8_t ROLE_UNKNOWN = 255;--struct Key {-    std::string name;-    std::vector<std::uint8_t> seed;-    PublicKey public_key{};-    std::string fingerprint;-};--fs::path key_dir();-fs::path key_path(std::string_view name);-std::optional<Key> load_key(std::string_view name);-std::optional<Key> generate_key(std::string_view name);-std::vector<std::string> list_key_names();--fs::path auth_dir();-std::string normalize_target(std::string_view target);-bool set_key(std::string_view target, std::string_view key_name);-bool remove_key(std::string_view target);-std::vector<std::string> list_credential_lines();-bool local_key_exists(std::string_view name);-std::optional<std::string> key_for_url(std::string_view url);--struct AccessEntry {-    PublicKey public_key{};-    std::string name;-    std::uint8_t role = ROLE_READ;-};--struct Access {-    bool valid = true;-    std::int64_t error_line = 0;-    bool anonymous_read = false;-    std::vector<AccessEntry> entries;-};--Access empty_access();-fs::path access_path(const fs::path& repo_root);-Access load_access(const fs::path& repo_root);-bool write_access(const fs::path& repo_root, const Access& access);-bool add_access(const fs::path& repo_root, std::uint8_t role, const PublicKey& public_key,-                std::string_view name);-bool remove_access(const fs::path& repo_root, std::string_view fingerprint, std::string_view name);-bool set_anonymous(const fs::path& repo_root, bool enabled);-std::uint8_t role_for(const Access& access, const PublicKey* public_key);--} // namespace vn::auth--- a/xveins/src/cli/cli.cpp+++ /dev/null@@ -1,3060 +0,0 @@-#include "cli/cli.h"-#include "cli/local_commands.h"-#include "cli/net_commands.h"-#include "git/git.h"-#include "merge/merge.h"-#include "protocol/promisor.h"-#include "store/store.h"-#include "version/version.h"-#include "worktree/attributes.h"-#include "worktree/pathspec.h"-#include "worktree/worktree.h"--#include <algorithm>-#include <atomic>-#include <cstdlib>-#include <cstring>-#include <iostream>-#include <map>-#include <set>-#include <sstream>-#include <thread>-#include <unordered_map>--namespace vn {--namespace {--bool is_flag(std::string_view arg) {-    return !arg.empty() && arg.front() == '-';-}--bool view_ref_named(const View& view, std::string_view name) {-    if (find_bookmark(view, name) || find_tag(view, name))-        return true;-    for (const auto& ref : view.remote_refs) {-        const std::size_t joined = ref.remote.size() + 1 + ref.name.size();-        if (name.size() == joined && name.starts_with(ref.remote) &&-            name[ref.remote.size()] == '/' && name.substr(ref.remote.size() + 1) == ref.name)-            return true;-    }-    return false;-}--bool existing_directory_operand(std::string_view text) {-    if (text.empty() || text.find('\0') != std::string_view::npos)-        return false;-    std::error_code ec;-    fs::path path = path_from_bytes(text);-    if (!path.is_absolute())-        path = fs::current_path(ec) / path;-    if (ec)-        return false;-    return path_is_dir(path);-}--std::optional<fs::path> open_repo() {-    const auto root = discover_repo(".");-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return std::nullopt;-    }-    return root;-}--std::string join_args(const std::vector<std::string>& parts) {-    std::string out;-    for (std::size_t i = 0; i < parts.size(); ++i) {-        if (i != 0)-            out.push_back(' ');-        out += parts[i];-    }-    return out;-}--bool message_is_blank(const std::vector<std::string>& parts) {-    for (const auto& part : parts) {-        for (char c : part) {-            if (c != ' ' && c != '\t' && c != '\n' && c != '\r')-                return false;-        }-    }-    return true;-}--Result<std::vector<std::string>> parse_message(const std::vector<std::string>& args,-                                               std::size_t start) {-    std::vector<std::string> parts;-    bool end_flags = false;-    for (std::size_t i = start; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-m" || arg == "-message")) {-            if (i + 1 < args.size()) {-                parts.push_back(args[++i]);-            } else {-                error_prefix();-                std::cout << arg << " requires a message\n";-                return fail_usage("missing message");-            }-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return fail_usage("unknown flag");-        } else {-            parts.push_back(arg);-        }-    }-    return parts;-}--std::optional<std::string> edit_commit_message(const fs::path& root, std::string_view initial) {-    const fs::path file = tmp_dir(root) / "commit-message.txt";-    std::string body(initial);-    if (!body.empty() && body.back() != '\n')-        body.push_back('\n');-    body += "\n# Enter a commit message. Lines starting with '#' are ignored.\n";-    if (!write_file(file, bytes_of(body))) {-        error_prefix();-        std::cout << "cannot write message file\n";-        return std::nullopt;-    }-    if (!run_editor(root, {}, file)) {-        (void)remove_file(file);-        error_prefix();-        std::cout << "editor exited with an error\n";-        return std::nullopt;-    }-    auto data = read_file_opt(file);-    (void)remove_file(file);-    if (!data)-        return std::nullopt;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::vector<std::string> lines;-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        std::string line(text.substr(start, end - start));-        const auto first = line.find_first_not_of(" \t\r");-        if (first != std::string::npos && line[first] == '#')-            line.clear();-        else if (first == std::string::npos)-            line.clear();-        else-            line.erase(0, first);-        lines.push_back(std::move(line));-        if (end == text.size())-            break;-        start = end + 1;-    }-    while (!lines.empty() && lines.back().empty())-        lines.pop_back();-    while (!lines.empty() && lines.front().empty())-        lines.erase(lines.begin());-    std::string out;-    for (std::size_t i = 0; i < lines.size(); ++i) {-        if (i != 0)-            out.push_back('\n');-        out += lines[i];-    }-    return out;-}--void print_cell(std::string_view text, std::size_t width, Color color, bool dim) {-    if (dim) {-        print_styled(text, color, true, false);-    } else if (color == Color::Default) {-        std::cout << text;-    } else {-        print_colored(text, color, false, false);-    }-    for (std::size_t i = text.size(); i < width; ++i)-        std::cout << ' ';-}--void print_gap() {-    std::cout << "  ";-}--std::string first_line(const std::string& message) {-    const std::size_t newline = message.find('\n');-    return newline == std::string::npos ? message : message.substr(0, newline);-}--std::string short_hex(const Id& id) {-    return hex_encode(id).substr(0, 12);-}--std::string short_change_id(const std::vector<std::string>& ids, std::size_t index) {-    const std::string& target = ids[index];-    std::size_t len = std::min<std::size_t>(4, target.size());-    while (len < target.size()) {-        const std::string_view prefix(target.data(), len);-        bool unique = true;-        for (std::size_t j = 0; j < ids.size(); ++j) {-            if (j == index)-                continue;-            if (ids[j] == target)-                continue;-            if (ids[j].starts_with(prefix)) {-                unique = false;-                break;-            }-        }-        if (unique)-            break;-        ++len;-    }-    return target.substr(0, len);-}--struct DiffOp {-    char tag = ' ';-    std::size_t ai = 0;-    std::size_t bi = 0;-};--std::vector<std::string> split_lines(Bytes data) {-    std::vector<std::string> out;-    std::size_t start = 0;-    for (std::size_t i = 0; i < data.size(); ++i) {-        if (data[i] == '\n') {-            out.emplace_back(reinterpret_cast<const char*>(data.data() + start), i - start);-            start = i + 1;-        }-    }-    if (start < data.size()) {-        out.emplace_back(reinterpret_cast<const char*>(data.data() + start), data.size() - start);-    } else if (!data.empty() && data.back() == '\n') {-        // A trailing newline does not introduce an extra empty line.-    } else if (data.empty()) {-        // No lines.-    }-    return out;-}--std::vector<DiffOp> build_ops_lcs(const std::vector<std::string>& a,-                                  const std::vector<std::string>& b) {-    const std::size_t n = a.size();-    const std::size_t m = b.size();-    const std::size_t cols = m + 1;-    std::vector<std::uint32_t> dp((n + 1) * cols, 0);-    for (std::size_t i = 1; i <= n; ++i) {-        for (std::size_t j = 1; j <= m; ++j) {-            if (a[i - 1] == b[j - 1])-                dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;-            else-                dp[i * cols + j] = std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);-        }-    }-    std::vector<DiffOp> ops;-    std::size_t i = n;-    std::size_t j = m;-    while (i > 0 || j > 0) {-        if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) {-            ops.push_back(DiffOp{' ', i - 1, j - 1});-            --i;-            --j;-        } else if (j > 0 && (i == 0 || dp[i * cols + (j - 1)] >= dp[(i - 1) * cols + j])) {-            ops.push_back(DiffOp{'+', 0, j - 1});-            --j;-        } else {-            ops.push_back(DiffOp{'-', i - 1, 0});-            --i;-        }-    }-    std::reverse(ops.begin(), ops.end());-    return ops;-}--std::vector<DiffOp> build_ops_myers(const std::vector<std::string>& a,-                                    const std::vector<std::string>& b) {-    const int n = static_cast<int>(a.size());-    const int m = static_cast<int>(b.size());-    const int max_d = n + m;-    const int offset = max_d;-    std::vector<int> v(static_cast<std::size_t>(2 * max_d + 1), 0);-    std::vector<std::vector<int>> trace;-    constexpr std::size_t trace_cap = 64u * 1024u * 1024u;-    int found_d = -1;-    for (int d = 0; d <= max_d; ++d) {-        if (static_cast<std::size_t>(trace.size() + 1) * v.size() * sizeof(int) > trace_cap)-            return {};-        trace.push_back(v);-        for (int k = -d; k <= d; k += 2) {-            int x = 0;-            if (k == -d || (k != d && v[static_cast<std::size_t>(offset + k - 1)] <-                                          v[static_cast<std::size_t>(offset + k + 1)]))-                x = v[static_cast<std::size_t>(offset + k + 1)];-            else-                x = v[static_cast<std::size_t>(offset + k - 1)] + 1;-            int y = x - k;-            while (x < n && y < m &&-                   a[static_cast<std::size_t>(x)] == b[static_cast<std::size_t>(y)]) {-                ++x;-                ++y;-            }-            v[static_cast<std::size_t>(offset + k)] = x;-            if (x >= n && y >= m) {-                found_d = d;-                break;-            }-        }-        if (found_d >= 0)-            break;-    }-    if (found_d < 0)-        return {};-    std::vector<DiffOp> ops;-    int x = n;-    int y = m;-    for (int d = found_d; d >= 0; --d) {-        const auto& prev = trace[static_cast<std::size_t>(d)];-        const int k = x - y;-        int prev_k = 0;-        if (k == -d || (k != d && prev[static_cast<std::size_t>(offset + k - 1)] <-                                      prev[static_cast<std::size_t>(offset + k + 1)]))-            prev_k = k + 1;-        else-            prev_k = k - 1;-        const int prev_x = prev[static_cast<std::size_t>(offset + prev_k)];-        const int prev_y = prev_x - prev_k;-        while (x > prev_x && y > prev_y) {-            ops.push_back(-                DiffOp{' ', static_cast<std::size_t>(x - 1), static_cast<std::size_t>(y - 1)});-            --x;-            --y;-        }-        if (d > 0) {-            if (x == prev_x) {-                ops.push_back(DiffOp{'+', 0, static_cast<std::size_t>(y - 1)});-                --y;-            } else {-                ops.push_back(DiffOp{'-', static_cast<std::size_t>(x - 1), 0});-                --x;-            }-        }-    }-    std::reverse(ops.begin(), ops.end());-    return ops;-}--std::vector<DiffOp> build_ops_fallback(const std::vector<std::string>& a,-                                       const std::vector<std::string>& b) {-    std::size_t prefix = 0;-    while (prefix < a.size() && prefix < b.size() && a[prefix] == b[prefix])-        ++prefix;-    std::size_t suffix = 0;-    while (suffix < a.size() - prefix && suffix < b.size() - prefix &&-           a[a.size() - 1 - suffix] == b[b.size() - 1 - suffix])-        ++suffix;-    std::vector<DiffOp> ops;-    for (std::size_t i = 0; i < prefix; ++i)-        ops.push_back(DiffOp{' ', i, i});-    for (std::size_t i = prefix; i < a.size() - suffix; ++i)-        ops.push_back(DiffOp{'-', i, 0});-    for (std::size_t j = prefix; j < b.size() - suffix; ++j)-        ops.push_back(DiffOp{'+', 0, j});-    for (std::size_t k = 0; k < suffix; ++k) {-        const std::size_t i = a.size() - suffix + k;-        const std::size_t j = b.size() - suffix + k;-        ops.push_back(DiffOp{' ', i, j});-    }-    return ops;-}--std::vector<DiffOp> build_ops(const std::vector<std::string>& a,-                              const std::vector<std::string>& b) {-    const std::size_t n = a.size();-    const std::size_t m = b.size();-    if (n == 0 && m == 0)-        return {};-    if (n != 0 && m != 0 && n <= 2048 && m <= 2048)-        return build_ops_lcs(a, b);-    if (n != 0 && m != 0 && n * m <= 4'000'000)-        return build_ops_lcs(a, b);-    auto myers = build_ops_myers(a, b);-    if (!myers.empty())-        return myers;-    return build_ops_fallback(a, b);-}--void render_unified(const std::vector<std::string>& a, const std::vector<std::string>& b) {-    const auto ops = build_ops(a, b);-    std::vector<std::size_t> changes;-    for (std::size_t i = 0; i < ops.size(); ++i) {-        if (ops[i].tag != ' ')-            changes.push_back(i);-    }-    constexpr std::size_t context = 3;-    std::size_t pos = 0;-    std::size_t old_seen = 0;-    std::size_t new_seen = 0;-    std::size_t ci = 0;-    while (ci < changes.size()) {-        const std::size_t first = changes[ci];-        std::size_t start = first > context ? first - context : 0;-        std::size_t last = first;-        ++ci;-        while (ci < changes.size() && changes[ci] <= last + context * 2) {-            last = changes[ci];-            ++ci;-        }-        std::size_t end = std::min(last + context + 1, ops.size());-        while (pos < start) {-            const auto& op = ops[pos];-            if (op.tag == ' ') {-                ++old_seen;-                ++new_seen;-            } else if (op.tag == '-') {-                ++old_seen;-            } else {-                ++new_seen;-            }-            ++pos;-        }-        std::size_t old_count = 0;-        std::size_t new_count = 0;-        for (std::size_t e = start; e < end; ++e) {-            if (ops[e].tag == ' ') {-                ++old_count;-                ++new_count;-            } else if (ops[e].tag == '-') {-                ++old_count;-            } else {-                ++new_count;-            }-        }-        const std::size_t old_start = old_seen + (old_count > 0 ? 1 : 0);-        const std::size_t new_start = new_seen + (new_count > 0 ? 1 : 0);-        std::cout << "@@ -" << old_start << "," << old_count << " +" << new_start << ","-                  << new_count << " @@\n";-        while (pos < end) {-            const auto& op = ops[pos];-            if (op.tag == ' ') {-                std::cout << " " << a[op.ai] << "\n";-                ++old_seen;-                ++new_seen;-            } else if (op.tag == '-') {-                print_colored("-", Color::Red, false, false);-                print_colored(a[op.ai], Color::Red, false, false);-                std::cout << "\n";-                ++old_seen;-            } else {-                print_colored("+", Color::Green, false, false);-                print_colored(b[op.bi], Color::Green, false, false);-                std::cout << "\n";-                ++new_seen;-            }-            ++pos;-        }-    }-}--bool contains_nul(Bytes data) {-    const std::size_t limit = std::min<std::size_t>(data.size(), 8192);-    for (std::size_t i = 0; i < limit; ++i) {-        if (data[i] == 0)-            return true;-    }-    return false;-}--std::size_t render_diff(Store& store, std::optional<Id> old_tree, std::optional<Id> new_tree,-                        bool announce_no_diff, std::string_view path_filter = {}) {-    auto changes = compare_trees(store, old_tree, new_tree);-    if (!path_filter.empty()) {-        changes.erase(std::remove_if(changes.begin(), changes.end(),-                                     [&](const TreeChange& change) {-                                         return change.path != path_filter &&-                                                !(change.path.size() > path_filter.size() &&-                                                  change.path.compare(0, path_filter.size(),-                                                                      path_filter) == 0 &&-                                                  change.path[path_filter.size()] == '/');-                                     }),-                      changes.end());-    }-    for (const auto& change : changes) {-        if (change.new_kind == KIND_CONFLICT) {-            std::cout << "Conflict: " << change.path << "\n";-            continue;-        }-        std::vector<std::uint8_t> old_data;-        std::vector<std::uint8_t> new_data;-        if (change.old_kind != KIND_MISSING && change.old_id) {-            if (auto data = read_blob(store, *change.old_id))-                old_data = std::move(*data);-        }-        if (change.new_kind != KIND_MISSING && change.new_id) {-            if (auto data = read_blob(store, *change.new_id))-                new_data = std::move(*data);-        }-        if (contains_nul(bytes_of(old_data)) || contains_nul(bytes_of(new_data))) {-            std::cout << "Binary files a/" << change.path << " and b/" << change.path-                      << " differ\n";-            continue;-        }-        print_colored("--- ", Color::Red, false, false);-        if (change.old_kind == KIND_MISSING) {-            print_colored("/dev/null", Color::Red, false, false);-        } else {-            print_colored("a/", Color::Red, false, false);-            print_colored(change.path, Color::Red, false, false);-        }-        std::cout << "\n";-        print_colored("+++ ", Color::Green, false, false);-        if (change.new_kind == KIND_MISSING) {-            print_colored("/dev/null", Color::Green, false, false);-        } else {-            print_colored("b/", Color::Green, false, false);-            print_colored(change.path, Color::Green, false, false);-        }-        std::cout << "\n";-        const auto a = split_lines(bytes_of(old_data));-        const auto b = split_lines(bytes_of(new_data));-        render_unified(a, b);-    }-    if (announce_no_diff && changes.empty()) {-        info_prefix();-        std::cout << "no diff to show\n";-    }-    return changes.size();-}--int run_init(const std::vector<std::string>& args) {-    std::string path = ".";-    std::optional<std::string> source;-    std::string remote_url;-    std::string remote_name = "o";-    bool remote_name_given = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && arg.rfind("-git-import:", 0) == 0) {-            source = arg.substr(12);-            if (source->empty()) {-                error_prefix();-                std::cout << "-git-import: requires a path\n";-                return 1;-            }-        } else if (!end_flags && arg.rfind("-remote:", 0) == 0) {-            remote_url = arg.substr(8);-            if (remote_url.empty()) {-                error_prefix();-                std::cout << "-remote: requires a URL\n";-                return 1;-            }-        } else if (!end_flags && arg.rfind("-remote-name:", 0) == 0) {-            remote_name = arg.substr(13);-            if (remote_name.empty()) {-                error_prefix();-                std::cout << "-remote-name: requires a name\n";-                return 1;-            }-            remote_name_given = true;-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            path = arg;-        }-    }-    if (remote_name_given && remote_url.empty()) {-        error_prefix();-        std::cout << "-remote-name: requires -remote:<url>\n";-        return 1;-    }-    if (!source && !remote_url.empty()) {-        error_prefix();-        std::cout << "-remote: requires -git-import:<path>\n";-        return 1;-    }-    const auto initialized = init_repo(path_from_bytes(path));-    if (!initialized) {-        error_prefix();-        std::cout << "init failed with code " << initialized.error().offset << "\n";-        return 1;-    }-    info_prefix();-    std::cout << "initialized veins repository at " << path_display(*initialized) << "\n";-    if (source) {-        const int prepared = git_prepare_mirror(*initialized, *source);-        if (prepared != 0) {-            error_prefix();-            if (prepared == 2) {-                std::cout << "-git-import: " << *source-                          << " is not a git repository root (expected the directory "-                             "containing .git)\n";-            } else {-                std::cout << "cannot prepare git mirror from " << *source << " (code " << prepared-                          << ")\n";-            }-            return 1;-        }-        const int imported = git_import(*initialized);-        if (imported != 0)-            return imported;-        git_import_configure_remote(*initialized, remote_url, remote_name);-    }-    return 0;-}--std::string status_path(std::string_view path, std::string_view cwd_rel) {-    if (cwd_rel.empty())-        return std::string(path);-    constexpr std::string_view parent = "../";-    std::size_t c = 0;-    std::size_t p = 0;-    std::size_t common_end = 0;-    while (c < cwd_rel.size() && p < path.size()) {-        std::size_t ce = cwd_rel.find('/', c);-        if (ce == std::string_view::npos)-            ce = cwd_rel.size();-        std::size_t pe = path.find('/', p);-        if (pe == std::string_view::npos)-            pe = path.size();-        if (cwd_rel.substr(c, ce - c) != path.substr(p, pe - p))-            break;-        common_end = ce;-        c = ce + 1;-        p = pe + 1;-        if (ce == cwd_rel.size() || pe == path.size())-            break;-    }-    std::string_view suffix = path;-    std::size_t parents = 0;-    if (common_end == cwd_rel.size()) {-        if (path.size() == common_end)-            return std::string(path);-        suffix = path.substr(common_end + 1);-    } else if (common_end == 0) {-        parents = 1;-        for (std::size_t i = 1; i < cwd_rel.size(); ++i)-            if (cwd_rel[i] == '/')-                ++parents;-    } else {-        parents = 1;-        for (std::size_t i = common_end + 1; i < cwd_rel.size(); ++i)-            if (cwd_rel[i] == '/')-                ++parents;-        suffix = common_end < path.size() ? path.substr(common_end + 1) : std::string_view{};-    }-    std::string out;-    out.reserve(parents * parent.size() + suffix.size());-    for (std::size_t i = 0; i < parents; ++i)-        out.append(parent);-    out.append(suffix);-    return out;-}--int run_status() {-    const auto root = open_repo();-    if (!root)-        return 1;-    const auto cwd_rel = cwd_relative(*root);-    Store store = Store::open_all(*root);-    const int snap = snapshot_run(*root, store);-    if (snap != 0)-        return snap;-    auto view = current_view(*root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    const auto wc = working_copy_id(*view);-    if (!wc) {-        info_prefix();-        std::cout << "working copy clean\n";-        return 0;-    }-    std::optional<Id> old_tree;-    std::optional<Id> new_tree;-    auto wc_body = store.read_body(*wc, TYPE_COMMIT);-    if (!wc_body) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    auto wc_commit = decode_commit(bytes_of(*wc_body));-    if (!wc_commit) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    new_tree = wc_commit->root_tree;-    if (!wc_commit->parents.empty()) {-        auto parent_body = store.read_body(wc_commit->parents.front(), TYPE_COMMIT);-        if (parent_body) {-            auto parent_commit = decode_commit(bytes_of(*parent_body));-            if (parent_commit)-                old_tree = parent_commit->root_tree;-        }-    }-    const bool trees_equal =-        old_tree && new_tree && std::memcmp(old_tree->data(), new_tree->data(), ID_LEN) == 0;-    const auto changes =-        trees_equal ? std::vector<TreeChange>{} : compare_trees(store, old_tree, new_tree);-    const std::string_view cwd = cwd_rel ? std::string_view(*cwd_rel) : std::string_view{};-    std::size_t conflicts = 0;-    for (const auto& change : changes) {-        const std::string display_path = status_path(change.path, cwd);-        if (change.old_kind == KIND_MISSING) {-            print_colored("A", Color::BrightGreen, false, false);-            std::cout << " " << display_path << "\n";-        } else if (change.new_kind == KIND_MISSING) {-            print_colored("D", Color::Red, false, false);-            std::cout << " " << display_path << "\n";-        } else if (change.new_kind == KIND_CONFLICT) {-            print_colored("C", Color::BrightRed, false, false);-            std::cout << " " << display_path << "\n";-            ++conflicts;-        } else {-            print_colored("M", Color::Cyan, false, false);-            std::cout << " " << display_path << "\n";-        }-    }-    if (changes.empty()) {-        info_prefix();-        std::cout << "working copy clean\n";-    }-    if (conflicts > 0)-        std::cout << conflicts << " conflict(s)\n";--    std::vector<Id> stack{*wc};-    std::set<Id> seen;-    std::size_t conflicted_commits = 0;-    while (!stack.empty()) {-        const Id id = stack.back();-        stack.pop_back();-        if (!seen.insert(id).second)-            continue;-        auto loaded = load_commit(store, id);-        if (!loaded)-            continue;-        if (tree_conflicted(store, loaded->commit.root_tree))-            ++conflicted_commits;-        for (const auto& parent : loaded->commit.parents)-            stack.push_back(parent);-    }-    if (conflicted_commits > 0)-        std::cout << conflicted_commits << " conflicted commit(s) in ancestry\n";-    return 0;-}--int run_log(const std::vector<std::string>& args) {-    std::string rev;-    bool col_titles = true;-    bool end_flags = false;-    bool all = false;-    bool pager = false;-    std::optional<std::size_t> limit;-    bool first = false;-    bool explicit_limit = false;-    auto parse_count = [](std::string_view text, std::size_t& out) -> bool {-        if (text.empty())-            return false;-        std::size_t value = 0;-        for (char c : text) {-            if (c < '0' || c > '9')-                return false;-            value = value * 10 + static_cast<std::size_t>(c - '0');-        }-        if (value == 0)-            return false;-        out = value;-        return true;-    };-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            rev = args[++i];-        } else if (!end_flags && arg == "-no-col-titles") {-            col_titles = false;-        } else if (!end_flags && arg == "-p") {-            pager = true;-        } else if (!end_flags && (arg == "-a" || arg == "-all")) {-            all = true;-        } else if (!end_flags && (arg == "-l" || arg == "-f")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a count\n";-                return 1;-            }-            std::size_t count = 0;-            if (!parse_count(args[++i], count)) {-                error_prefix();-                std::cout << arg << " requires a positive count\n";-                return 1;-            }-            limit = count;-            first = arg == "-f";-            explicit_limit = true;-        } else if (!end_flags && arg.size() > 2 &&-                   (arg[0] == '-' && (arg[1] == 'l' || arg[1] == 'f'))) {-            std::size_t count = 0;-            if (!parse_count(std::string_view(arg).substr(2), count)) {-                error_prefix();-                std::cout << "invalid log count: " << arg << "\n";-                return 1;-            }-            limit = count;-            first = arg[1] == 'f';-            explicit_limit = true;-        } else if (!end_flags && arg.size() > 1 && (arg[0] == 'l' || arg[0] == 'f')) {-            std::size_t count = 0;-            if (parse_count(std::string_view(arg).substr(1), count)) {-                limit = count;-                first = arg[0] == 'f';-                explicit_limit = true;-            } else {-                rev = arg;-            }-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            rev = arg;-        }-    }-    if (all || (pager && !explicit_limit)) {-        limit.reset();-    } else if (!limit) {-        std::size_t amount = 20;-        if (auto configured = user_config_value("log.default_amount")) {-            if (!parse_count(*configured, amount))-                amount = 20;-        }-        limit = amount;-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    Store store = Store::open_all(*root);-    const int snap = snapshot_run(*root, store);-    if (snap != 0)-        return snap;-    auto view = current_view(*root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    const auto wc = working_copy_id(*view);-    std::vector<Id> stack;-    if (rev.empty() || rev == "all()") {-        stack = view_roots(*view);-    } else if (auto one = resolve_revision(store, *view, rev)) {-        stack.push_back(*one);-    }-    std::set<Id> seen(stack.begin(), stack.end());--    struct Rec {-        Id id{};-        Id root_tree{};-        std::vector<Id> parents;-        std::string change;-        std::int64_t seconds = 0;-        std::string message;-        std::string author;-        bool conflicted = false;-        bool has_changes = false;-    };-    std::vector<Rec> recs;-    while (!stack.empty()) {-        const Id id = stack.back();-        stack.pop_back();-        auto loaded = load_commit(store, id);-        if (!loaded)-            continue;-        Rec rec;-        rec.id = id;-        rec.root_tree = loaded->commit.root_tree;-        rec.parents = loaded->commit.parents;-        rec.change = base32_encode(loaded->commit.change_id);-        rec.seconds = loaded->commit.committer.seconds;-        rec.message = first_line(loaded->commit.message);-        rec.author = loaded->commit.author.name;-        if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)-            rec.has_changes = has_changes(store, *loaded);-        recs.push_back(std::move(rec));-        for (const auto& parent : loaded->commit.parents) {-            if (seen.insert(parent).second)-                stack.push_back(parent);-        }-    }-    std::vector<LogOrderNode> nodes;-    nodes.reserve(recs.size());-    for (const auto& rec : recs)-        nodes.push_back(LogOrderNode{rec.id, rec.seconds, rec.parents});-    const auto order = order_log_nodes(nodes);-    std::vector<Rec> ordered;-    ordered.reserve(recs.size());-    for (std::size_t index : order)-        ordered.push_back(std::move(recs[index]));-    recs = std::move(ordered);--    if (limit) {-        if (first) {-            if (recs.size() > *limit)-                recs.erase(recs.begin(), recs.end() - static_cast<std::ptrdiff_t>(*limit));-            std::reverse(recs.begin(), recs.end());-        } else if (recs.size() > *limit) {-            recs.resize(*limit);-        }-    }--    for (auto& rec : recs)-        rec.conflicted = tree_conflicted(store, rec.root_tree);--    std::vector<std::string> change_ids;-    for (const auto& rec : recs)-        change_ids.push_back(rec.change);-    std::size_t w_commit = 12;-    std::size_t w_change = 6;-    std::size_t w_date = 19;-    std::size_t w_author = 6;-    std::unordered_map<std::string, std::size_t> change_counts;-    for (std::size_t i = 0; i < recs.size(); ++i) {-        const auto cid = short_change_id(change_ids, i);-        w_change = std::max(w_change, cid.size());-        w_author = std::max(w_author, recs[i].author.size());-        ++change_counts[recs[i].change];-    }-    std::ostringstream rendered;-    std::streambuf* old_out = nullptr;-    if (pager)-        old_out = std::cout.rdbuf(rendered.rdbuf());-    if (col_titles) {-        print_cell("", 1, Color::Default, false);-        std::cout << " ";-        print_cell("Commit", w_commit, Color::Default, false);-        print_gap();-        print_cell("Change", w_change, Color::Default, false);-        print_gap();-        print_cell("Date", w_date, Color::Default, false);-        print_gap();-        print_cell("Author", w_author, Color::Default, false);-        print_gap();-        std::cout << "Message\n";-    }-    for (std::size_t i = 0; i < recs.size(); ++i) {-        const auto& rec = recs[i];-        const bool is_wc = wc && std::memcmp(wc->data(), rec.id.data(), ID_LEN) == 0;-        std::string marker = is_wc ? "@" : " ";-        Color marker_color = Color::Default;-        if (is_wc)-            marker_color = rec.has_changes ? Color::BrightCyan : Color::Red;-        const auto cid = short_change_id(change_ids, i);-        const auto stamp = format_utc(rec.seconds);-        print_cell(marker, 1, marker_color, false);-        std::cout << " ";-        print_cell(short_hex(rec.id), w_commit, Color::Red, false);-        print_gap();-        print_cell(cid, w_change, Color::Red, false);-        print_gap();-        print_cell(stamp, w_date, Color::Cyan, true);-        print_gap();-        print_cell(rec.author, w_author, Color::Cyan, false);-        print_gap();-        if (!rec.message.empty())-            print_colored(rec.message, Color::Green, false, false);-        else-            print_colored("<unset>", Color::BrightBlack, false, false);-        for (const auto& name : bookmark_names(*view, rec.id))-            std::cout << " [" << name << "]";-        for (const auto& name : tag_names(*view, rec.id))-            std::cout << " <" << name << ">";-        if (rec.conflicted)-            std::cout << " (conflicted)";-        bool divergent = change_counts[rec.change] > 1;-        if (divergent)-            std::cout << " (divergent)";-        std::cout << "\n";-    }-    if (pager) {-        std::cout.rdbuf(old_out);-        (void)run_pager(*root, rendered.str());-    }-    return 0;-}--int run_show(const std::vector<std::string>& args) {-    std::string rev;-    bool col_titles = true;-    bool all = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            rev = args[++i];-        } else if (!end_flags && (arg == "-a" || arg == "-all")) {-            all = true;-        } else if (!end_flags && arg == "-no-col-titles") {-            col_titles = false;-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            rev = arg;-        }-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto view = current_view(*root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    auto target = resolve_revision(store, *view, rev);-    if (!target) {-        error_prefix();-        if (rev.empty())-            std::cout << "no working-copy commit\n";-        else-            std::cout << "unknown revision: " << rev << "\n";-        return 1;-    }-    auto loaded = load_commit(store, *target);-    if (!loaded) {-        error_prefix();-        std::cout << "cannot read commit\n";-        return 1;-    }-    std::ostringstream rendered;-    auto* old_out = std::cout.rdbuf(rendered.rdbuf());-    if (col_titles) {-        std::cout << "commit   " << hex_encode(*target) << "\n";-        std::cout << "change   " << base32_encode(loaded->commit.change_id) << "\n";-        std::cout << "author   " << loaded->commit.author.name << " <"-                  << loaded->commit.author.email << ">\n";-        std::cout << "date     " << format_utc(loaded->commit.committer.seconds) << "\n";-        std::cout << "parents  ";-        if (loaded->commit.parents.empty()) {-            std::cout << "<none>";-        } else {-            for (std::size_t i = 0; i < loaded->commit.parents.size(); ++i) {-                if (i != 0)-                    std::cout << " ";-                std::cout << short_hex(loaded->commit.parents[i]);-            }-        }-        std::cout << "\n";-        const auto names = bookmark_names(*view, *target);-        if (!names.empty()) {-            std::cout << "bookmarks";-            for (const auto& name : names)-                std::cout << " [" << name << "]";-            std::cout << "\n";-        }-        std::cout << "\n";-        if (!loaded->commit.message.empty())-            std::cout << loaded->commit.message << "\n";-        else-            std::cout << "<unset>\n";-        std::cout << "\n";-    }-    std::optional<Id> old_tree;-    if (!loaded->commit.parents.empty()) {-        auto parent = load_commit(store, loaded->commit.parents.front());-        if (parent)-            old_tree = parent->commit.root_tree;-    }-    const std::size_t diff_count = render_diff(store, old_tree, loaded->commit.root_tree, false);-    std::cout.rdbuf(old_out);-    if (diff_count > 0 && !all && stdout_is_terminal())-        (void)run_pager(*root, rendered.str());-    else-        std::cout << rendered.str();-    return 0;-}--int run_hash(const std::vector<std::string>& args) {-    std::string rev;-    bool short_hash = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && arg == "-short") {-            short_hash = true;-        } else if (!end_flags && arg == "-long") {-            short_hash = false;-        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            rev = args[++i];-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            rev = arg;-        }-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto view = current_view(*root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    auto target = resolve_revision(store, *view, rev);-    if (!target) {-        error_prefix();-        if (rev.empty())-            std::cout << "no working-copy commit\n";-        else-            std::cout << "unknown revision: " << rev << "\n";-        return 1;-    }-    const auto hex = hex_encode(*target);-    std::cout << hex.substr(0, short_hash ? 12 : 64) << "\n";-    return 0;-}--bool print_tree(const fs::path& root, Store& store, const Id& tree_id, const std::string& prefix,-                std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return false;-    auto body = store.read_body(tree_id, TYPE_TREE);-    if (!body)-        return false;-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-        return false;-    for (std::size_t i = 0; i < tree->entries.size(); ++i) {-        const auto& entry = tree->entries[i];-        const bool last = i + 1 == tree->entries.size();-        std::cout << prefix << (last ? "`-- " : "|-- ") << entry.name << "\n";-        if (entry.kind == KIND_SUBTREE) {-            if (!print_tree(root, store, entry.target, prefix + (last ? "    " : "|   "),-                            depth + 1))-                return false;-        }-    }-    return true;-}--int run_ls(const std::vector<std::string>& args) {-    std::string rev;-    bool plain = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-plain" || arg == "-p")) {-            plain = true;-        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            rev = args[++i];-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            rev = arg;-        }-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto view = current_view(*root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    auto target = resolve_revision(store, *view, rev);-    if (!target) {-        error_prefix();-        if (rev.empty())-            std::cout << "no working-copy commit\n";-        else-            std::cout << "unknown revision: " << rev << "\n";-        return 1;-    }-    auto loaded = load_commit(store, *target);-    if (!loaded) {-        error_prefix();-        std::cout << "cannot read commit\n";-        return 1;-    }-    bool good = true;-    if (plain) {-        auto entries = flatten_tree_checked(store, loaded->commit.root_tree);-        if (!entries) {-            good = false;-        } else {-            for (const auto& entry : *entries)-                std::cout << entry.path << "\n";-        }-    } else {-        std::cout << ".\n";-        good = print_tree(*root, store, loaded->commit.root_tree, "", 0);-    }-    if (!good) {-        error_prefix();-        std::cout << "cannot read tree\n";-        return 1;-    }-    return 0;-}--int run_diff(const std::vector<std::string>& args) {-    std::vector<std::string> flag_revs;-    std::vector<std::string> operands;-    bool all = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-a" || arg == "-all")) {-            all = true;-        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            flag_revs.push_back(args[++i]);-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            operands.push_back(arg);-        }-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    Store store = Store::open_all(*root);-    auto view = current_view(*root, store);--    std::vector<std::string> revs = flag_revs;-    std::optional<std::string> path_filter;-    if (!operands.empty()) {-        if (!revs.empty()) {-            if (operands.size() > 1) {-                error_prefix();-                std::cout << "too many arguments\n";-                return 1;-            }-            path_filter = operands.front();-        } else if (operands.size() >= 2) {-            if (operands.size() > 2) {-                error_prefix();-                std::cout << "too many revisions\n";-                return 1;-            }-            revs.push_back(operands[0]);-            revs.push_back(operands[1]);-        } else if (existing_directory_operand(operands.front()) &&-                   (!view || !view_ref_named(*view, operands.front()))) {-            path_filter = operands.front();-        } else if (view && resolve_revision(store, *view, operands.front())) {-            revs.push_back(operands.front());-        } else {-            path_filter = operands.front();-        }-    }-    if (revs.size() > 2) {-        error_prefix();-        std::cout << "too many revisions\n";-        return 1;-    }-    if (path_filter) {-        const auto cwd_rel = cwd_relative(*root);-        if (!cwd_rel) {-            error_prefix();-            std::cout << "cannot determine current directory\n";-            return 1;-        }-        auto normalized = pathspec_normalize(*root, *cwd_rel, *path_filter);-        if (!normalized || normalized->empty()) {-            error_prefix();-            std::cout << "path is outside the repository: " << *path_filter << "\n";-            return 1;-        }-        path_filter = std::move(*normalized);-    }--    bool needs_snapshot = revs.empty();-    std::optional<std::vector<std::optional<Id>>> pre_resolved;-    if (!needs_snapshot) {-        if (!view) {-            needs_snapshot = true;-        } else {-            const auto wc = working_copy_id(*view);-            std::vector<std::optional<Id>> resolved;-            resolved.reserve(revs.size());-            for (const auto& rev : revs) {-                if (rev.empty() || rev == "@") {-                    needs_snapshot = true;-                    break;-                }-                auto id = resolve_revision(store, *view, rev);-                if (!id || (wc && std::memcmp(id->data(), wc->data(), ID_LEN) == 0)) {-                    needs_snapshot = true;-                    break;-                }-                resolved.push_back(*id);-            }-            if (!needs_snapshot)-                pre_resolved = std::move(resolved);-        }-    }-    if (needs_snapshot) {-        const int snap = snapshot_run(*root, store);-        if (snap != 0)-            return snap;-        view = current_view(*root, store);-        pre_resolved.reset();-    }-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }--    std::optional<Id> old_tree;-    std::optional<Id> new_tree;-    bool failed = false;-    auto tree_of = [&](const Id& id) -> std::optional<Id> {-        auto loaded = load_commit(store, id);-        if (!loaded)-            return std::nullopt;-        return loaded->commit.root_tree;-    };-    auto parent_tree_of = [&](const Id& id) -> std::optional<Id> {-        auto loaded = load_commit(store, id);-        if (!loaded || loaded->commit.parents.empty())-            return std::nullopt;-        auto parent = load_commit(store, loaded->commit.parents.front());-        if (!parent)-            return std::nullopt;-        return parent->commit.root_tree;-    };-    auto resolve_for_diff = [&](std::size_t index) -> std::optional<Id> {-        if (pre_resolved && index < pre_resolved->size())-            return (*pre_resolved)[index];-        return resolve_revision(store, *view, revs[index]);-    };-    if (revs.size() == 2) {-        auto a = resolve_for_diff(0);-        auto b = resolve_for_diff(1);-        if (!a || !b)-            failed = true;-        else {-            old_tree = tree_of(*a);-            new_tree = tree_of(*b);-        }-    } else if (revs.size() == 1) {-        auto a = resolve_for_diff(0);-        if (!a)-            failed = true;-        else {-            old_tree = parent_tree_of(*a);-            new_tree = tree_of(*a);-        }-    } else {-        const auto wc = working_copy_id(*view);-        if (wc) {-            old_tree = parent_tree_of(*wc);-            new_tree = tree_of(*wc);-        }-    }-    if (failed) {-        error_prefix();-        std::cout << "unknown revision\n";-        return 1;-    }--    const std::string_view filter =-        path_filter ? std::string_view(*path_filter) : std::string_view{};-    std::ostringstream rendered;-    auto* old_out = std::cout.rdbuf(rendered.rdbuf());-    const std::size_t diff_count = render_diff(store, old_tree, new_tree, true, filter);-    std::cout.rdbuf(old_out);-    if (diff_count > 0 && !all && stdout_is_terminal())-        (void)run_pager(*root, rendered.str());-    else-        std::cout << rendered.str();-    return 0;-}--int run_new(const std::vector<std::string>& args) {-    std::vector<std::string> revs;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            revs.push_back(arg);-        }-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto tx = Txn::begin(*root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    const auto wc = working_copy_id(tx->view());-    std::optional<Id> old_root;-    std::vector<Id> parents;-    std::optional<Id> root_tree;-    if (revs.empty()) {-        if (!wc) {-            error_prefix();-            std::cout << "no working-copy commit\n";-            return 1;-        }-        auto loaded = load_commit(store, *wc);-        if (!loaded) {-            error_prefix();-            std::cout << "cannot read working-copy commit\n";-            return 1;-        }-        parents.push_back(*wc);-        root_tree = loaded->commit.root_tree;-        old_root = root_tree;-    } else {-        for (std::size_t i = 0; i < revs.size(); ++i) {-            auto resolved = resolve_revision(store, tx->view(), revs[i]);-            if (!resolved) {-                error_prefix();-                std::cout << "unknown revision\n";-                return 1;-            }-            parents.push_back(*resolved);-            if (i == 0) {-                auto loaded = load_commit(store, *resolved);-                if (!loaded) {-                    error_prefix();-                    std::cout << "unknown revision\n";-                    return 1;-                }-                root_tree = loaded->commit.root_tree;-            }-        }-        if (wc) {-            auto old_loaded = load_commit(store, *wc);-            if (old_loaded)-                old_root = old_loaded->commit.root_tree;-        }-    }-    const Sig sig = identity_signature(*root);-    Commit commit;-    commit.version = 1;-    commit.parents = parents;-    commit.root_tree = *root_tree;-    commit.change_id = random_change_id();-    commit.author = sig;-    commit.committer = sig;-    commit.message = "";-    commit.renames_state = RENAMES_RECORDED;-    const auto encoded = encode_commit(commit);-    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-    if (wc)-        remove_head(tx->view(), *wc);-    set_workspace(tx->view(), new_id);-    rebuild_heads(tx->view());-    const auto status = tx->finish("new");-    if (!status)-        return 1;-    store.refresh(*root);-    (void)mark_native(*root, new_id);-    if (!revs.empty()) {-        const int materialized = checkout_materialize_commit(*root, store, old_root, *root_tree);-        if (materialized != 0)-            return materialized;-    }-    return 0;-}--int describe_impl(const fs::path& root, Store& store, const std::vector<std::string>& parts,-                  bool require_changes, bool start_new = false) {-    const int snap = snapshot_run(root, store);-    if (snap != 0)-        return snap;-    auto tx = Txn::begin(root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    const auto wc = working_copy_id(tx->view());-    if (!wc) {-        error_prefix();-        std::cout << "no working-copy commit\n";-        return 1;-    }-    auto loaded = load_commit(store, *wc);-    if (!loaded) {-        error_prefix();-        std::cout << "cannot read working-copy commit\n";-        return 1;-    }-    const std::string message = join_args(parts);-    const bool changed = has_changes(store, *loaded);-    const bool same_message = message == loaded->commit.message;-    if (!changed && (require_changes || same_message)) {-        if (require_changes) {-            info_prefix();-            std::cout << "nothing to commit, working copy clean\n";-            return 2;-        }-        return 0;-    }-    const Sig sig = identity_signature(root);-    Commit commit = loaded->commit;-    commit.committer = sig;-    if (!changed)-        commit.author = sig;-    commit.message = message;-    const auto encoded = encode_commit(commit);-    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-    remove_head(tx->view(), *wc);-    move_bookmarks(tx->view(), *wc, new_id);-    if (auto current = current_bookmark_name(root)) {-        if (find_bookmark(tx->view(), *current))-            set_bookmark_target(tx->view(), *current, new_id);-    }-    set_workspace(tx->view(), new_id);-    rebuild_heads(tx->view());-    if (start_new) {-        std::vector<ChainedOperation> operations;-        operations.push_back(ChainedOperation{tx->view(), "describe"});-        Commit next;-        next.version = 1;-        next.parents = {new_id};-        next.root_tree = commit.root_tree;-        next.change_id = random_change_id();-        next.author = sig;-        next.committer = sig;-        next.message = "";-        next.renames_state = RENAMES_RECORDED;-        const auto next_encoded = encode_commit(next);-        const Id next_id = tx->add_object(TYPE_COMMIT, next_encoded);-        remove_head(tx->view(), new_id);-        set_workspace(tx->view(), next_id);-        rebuild_heads(tx->view());-        operations.push_back(ChainedOperation{tx->view(), "new"});-        const auto status = tx->finish_chain(std::move(operations));-        if (!status)-            return 1;-        store.refresh(root);-        (void)mark_native(root, new_id);-        (void)mark_native(root, next_id);-        return 0;-    }-    const auto status = tx->finish("describe");-    if (!status)-        return 1;-    store.refresh(root);-    (void)mark_native(root, new_id);-    return 0;-}--int run_describe(const std::vector<std::string>& args) {-    auto parsed = parse_message(args, 2);-    if (!parsed)-        return 1;-    const auto root = open_repo();-    if (!root)-        return 1;-    Store store = Store::open_all(*root);-    return describe_impl(*root, store, *parsed, false);-}--int run_commit(const std::vector<std::string>& args) {-    auto parsed = parse_message(args, 2);-    if (!parsed)-        return 1;-    const auto root = open_repo();-    if (!root)-        return 1;-    if (message_is_blank(*parsed) && stdin_is_terminal()) {-        auto edited = edit_commit_message(*root, join_args(*parsed));-        if (!edited || edited->empty()) {-            error_prefix();-            std::cout << "commit requires a non-empty message (-message)\n";-            return 1;-        }-        *parsed = {*edited};-    }-    if (message_is_blank(*parsed)) {-        error_prefix();-        std::cout << "commit requires a non-empty message (-message)\n";-        return 1;-    }-    Store store = Store::open_all(*root);-    const int described = describe_impl(*root, store, *parsed, true, true);-    if (described == 2)-        return 0;-    return described;-}--std::optional<Id> mapped_id(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,-                            const Id& id) {-    for (std::size_t i = 0; i < old_ids.size(); ++i) {-        if (std::memcmp(old_ids[i].data(), id.data(), ID_LEN) == 0)-            return new_ids[i];-    }-    return std::nullopt;-}--void remap_ids(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,-               std::vector<std::optional<Id>>& ids) {-    for (auto& id : ids) {-        if (!id)-            continue;-        if (auto mapped = mapped_id(old_ids, new_ids, *id))-            id = *mapped;-    }-}--int run_amend(const std::vector<std::string>& args) {-    std::string rev;-    std::vector<std::string> parts;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-m" || arg == "-message")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a message\n";-                return 1;-            }-            parts.push_back(args[++i]);-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else if (rev.empty()) {-            rev = arg;-        } else {-            parts.push_back(arg);-        }-    }-    if (rev.empty()) {-        error_prefix();-        std::cout << "amend requires a revision\n";-        return 1;-    }-    if (message_is_blank(parts)) {-        error_prefix();-        std::cout << "amend requires a non-empty message (-message)\n";-        return 1;-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto tx = Txn::begin(*root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    auto target = resolve_revision(store, tx->view(), rev);-    if (!target) {-        error_prefix();-        std::cout << "unknown revision\n";-        return 1;-    }-    std::vector<Id> pushed_roots;-    for (const auto& ref : tx->view().remote_refs)-        pushed_roots.push_back(ref.target);-    if (!pushed_roots.empty() && contains_id(collect_commits(store, pushed_roots), *target)) {-        error_prefix();-        std::cout << "cannot amend a revision that has been pushed\n";-        return 1;-    }-    auto target_loaded = load_commit(store, *target);-    if (!target_loaded) {-        error_prefix();-        std::cout << "cannot read revision\n";-        return 1;-    }-    const std::string message = join_args(parts);-    if (target_loaded->commit.message == message) {-        info_prefix();-        std::cout << "message unchanged\n";-        return 0;-    }-    auto remaining = all_commits(store, tx->view());-    std::vector<Id> old_ids;-    std::vector<Id> new_ids;-    const Sig sig = identity_signature(*root);-    bool target_rewritten = false;-    bool failed = false;-    while (!remaining.empty() && !failed) {-        std::optional<std::size_t> ready;-        for (std::size_t i = 0; i < remaining.size(); ++i) {-            bool is_ready = std::memcmp(remaining[i].data(), target->data(), ID_LEN) == 0;-            if (!is_ready) {-                auto loaded = load_commit(store, remaining[i]);-                if (loaded) {-                    for (const auto& parent : loaded->commit.parents) {-                        if (contains_id(old_ids, parent)) {-                            is_ready = true;-                            break;-                        }-                    }-                }-            }-            if (is_ready) {-                ready = i;-                break;-            }-        }-        if (!ready)-            break;-        const Id chosen = remaining[*ready];-        auto loaded = load_commit(store, chosen);-        if (!loaded) {-            failed = true;-            break;-        }-        std::vector<Id> new_parents;-        for (const auto& parent : loaded->commit.parents) {-            if (auto mapped = mapped_id(old_ids, new_ids, parent))-                new_parents.push_back(*mapped);-            else-                new_parents.push_back(parent);-        }-        Commit commit = loaded->commit;-        commit.parents = new_parents;-        commit.committer = sig;-        if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)-            commit.message = message;-        const auto encoded = encode_commit(commit);-        const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-        old_ids.push_back(chosen);-        new_ids.push_back(new_id);-        if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)-            target_rewritten = true;-        remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(*ready));-    }-    if (failed || !target_rewritten) {-        error_prefix();-        std::cout << "cannot amend revision\n";-        return 1;-    }-    for (auto& bookmark : tx->view().bookmarks) {-        remap_ids(old_ids, new_ids, bookmark.targets.adds);-        remap_ids(old_ids, new_ids, bookmark.targets.removes);-    }-    for (auto& tag : tx->view().tags) {-        if (auto mapped = mapped_id(old_ids, new_ids, tag.target))-            tag.target = *mapped;-    }-    for (auto& workspace : tx->view().working_copies) {-        if (auto mapped = mapped_id(old_ids, new_ids, workspace.target))-            workspace.target = *mapped;-    }-    for (auto& ref : tx->view().remote_refs) {-        if (auto mapped = mapped_id(old_ids, new_ids, ref.target))-            ref.target = *mapped;-    }-    rebuild_heads(tx->view());-    const auto status = tx->finish("amend " + rev);-    if (!status)-        return 1;-    for (const auto& id : new_ids)-        (void)mark_native(*root, id);-    return 0;-}--int run_checkout(const std::vector<std::string>& args) {-    std::string rev;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else if (rev.empty()) {-            rev = arg;-        }-    }-    const auto root = open_repo();-    if (!root)-        return 1;-    return checkout_run(*root, rev);-}--int run_edit(const std::vector<std::string>& args) {-    std::vector<std::string> paths;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            paths.push_back(arg);-        }-    }-    if (paths.empty())-        paths.push_back(".");-    std::optional<fs::path> root = discover_repo(".");-    fs::path config_root = root ? *root : fs::current_path();-    if (!run_editor(config_root, paths))-        return 1;-    return 0;-}--int run_fsck(const std::vector<std::string>& args) {-    std::string path = ".";-    bool verbose = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {-            verbose = true;-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            path = arg;-        }-    }-    const auto root = discover_repo(path_from_bytes(path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository: " << path << "\n";-        return 1;-    }-    return fsck_repository(*root, verbose);-}--int run_repack(const std::vector<std::string>& args) {-    std::string path = ".";-    bool verbose = false;-    int level = 6;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {-            verbose = true;-        } else if (!end_flags && arg.starts_with("-level:")) {-            const std::string value = arg.substr(7);-            if (value.empty()) {-                error_prefix();-                std::cout << "-level: requires a value (1-19)\n";-                return 1;-            }-            level = std::atoi(value.c_str());-            if (level < 1 || level > 19) {-                error_prefix();-                std::cout << "compression level must be between 1 and 19\n";-                return 1;-            }-        } else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            path = arg;-        }-    }-    const auto root = discover_repo(path_from_bytes(path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository: " << path << "\n";-        return 1;-    }-    return repack_repository(*root, level, verbose);-}--int run_self_test() {-    auto fail = [](std::string_view why) {-        error_prefix();-        std::cout << "self-test: failed: " << why << "\n";-        return 1;-    };-    const auto empty_hash = blake3_hash(Bytes{});-    const std::string expected_empty =-        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";-    if (hex_encode(Bytes(empty_hash.data(), empty_hash.size())) != expected_empty)-        return fail("blake3 vector");-    const auto& gear = fastcdc_gear();-    if (gear[0] != 0xf8447b379cdadcd5ull || gear[1] != 0xbe63d125aec8ca6dull)-        return fail("fastcdc gear table");--    BlobBuild build = build_blob(bytes_of(std::string("hello world")));-    if (!build.objects.empty()) {-        auto body = build.objects.back().body;-        auto decoded = decode_blob(bytes_of(body));-        if (!decoded || decoded->form != BlobForm::Inline)-            return fail("blob round trip");-    }-    Tree tree;-    tree.entries.push_back(TreeEntry{"a.txt", KIND_FILE, build.root});-    auto tree_body = encode_tree(tree.entries);-    if (!tree_body)-        return fail("tree encode");-    auto decoded_tree = decode_tree(bytes_of(*tree_body));-    if (!decoded_tree || decoded_tree->entries.size() != 1)-        return fail("tree round trip");--    std::vector<RawObject> objects;-    objects.push_back(RawObject{TYPE_TREE, *tree_body, object_id(TYPE_TREE, bytes_of(*tree_body))});-    PackOutput pack = encode_pack(objects);-    auto decoded_pack = decode_pack(pack.pack);-    if (!decoded_pack)-        return fail("pack decode");-    auto decoded_index = decode_index(pack.index, decoded_pack->trailer);-    if (!decoded_index)-        return fail("index decode");-    if (decoded_index->ids.size() != 1)-        return fail("index count");--    std::vector<std::uint8_t> left(96 * 1024);-    for (std::size_t i = 0; i < left.size(); ++i)-        left[i] = static_cast<std::uint8_t>((i * 31 + (i / 97) * 7) % 251);-    std::vector<std::uint8_t> right = left;-    for (std::size_t i = 48 * 1024; i < 48 * 1024 + 64; ++i)-        right[i] = static_cast<std::uint8_t>((right[i] + 19) % 251);-    std::vector<RawObject> delta_objects;-    auto append_version = [&](const std::vector<std::uint8_t>& data) {-        BlobBuild version = build_blob(bytes_of(data));-        for (auto& object : version.objects) {-            const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));-            delta_objects.push_back(RawObject{object.type, std::move(object.body), id});-        }-    };-    append_version(left);-    append_version(right);-    PackOutput delta_pack = encode_pack(delta_objects);-    auto delta_decoded = decode_pack(delta_pack.pack);-    if (!delta_decoded)-        return fail("delta pack decode");-    bool saw_delta = false;-    for (std::size_t i = 0; i < delta_decoded->records.size(); ++i) {-        const auto& record = delta_decoded->records[i];-        if (record.compression == 2)-            saw_delta = true;-        auto body = delta_decoded->get(i);-        if (!body)-            return fail("delta pack body");-        const Id computed = object_id(record.type, bytes_of(*body));-        if (std::memcmp(computed.data(), record.id.data(), ID_LEN) != 0)-            return fail("delta pack hash");-    }-    if (!saw_delta)-        return fail("delta pack compression");-    auto delta_index = decode_index(delta_pack.index, delta_decoded->trailer);-    if (!delta_index || delta_index->ids.size() != delta_decoded->records.size())-        return fail("delta index");--    info_prefix();-    std::cout << "self-test: ok\n";-    return 0;-}--struct ExtStat {-    std::string ext;-    std::uint64_t files = 0;-    std::uint64_t lines = 0;-    std::uint64_t bytes = 0;-};--struct AuthorStat {-    std::string name;-    std::uint64_t commits = 0;-};--std::uint64_t percent(std::uint64_t num, std::uint64_t total) {-    if (total == 0)-        return 0;-    return (num * 100 + total / 2) / total;-}--void print_percent(std::uint64_t pct) {-    if (pct < 10)-        std::cout << "  " << pct;-    else if (pct < 100)-        std::cout << " " << pct;-    else-        std::cout << pct;-}--Color color_for(std::size_t i) {-    static const Color colors[] = {Color::BrightCyan,    Color::BrightGreen, Color::BrightYellow,-                                   Color::BrightMagenta, Color::BrightBlue,  Color::BrightRed,-                                   Color::Cyan,          Color::Green};-    return colors[i % 8];-}--void print_bar(std::uint64_t num, std::uint64_t total, Color color) {-    std::uint64_t filled = 0;-    if (total > 0 && num > 0) {-        filled = (num * 24 + total / 2) / total;-        if (filled == 0)-            filled = 1;-        if (filled > 24)-            filled = 24;-    }-    for (std::uint64_t i = 0; i < filled; ++i)-        print_colored("\xe2\x96\x88", color, false, false);-    for (std::uint64_t i = filled; i < 24; ++i)-        print_colored("\xe2\x96\x91", Color::BrightBlack, false, false);-}--void print_left(std::string_view text, std::size_t width, Color color, bool dim) {-    if (dim)-        print_styled(text, color, true, false);-    else if (color == Color::Default)-        std::cout << text;-    else-        print_colored(text, color, false, false);-    for (std::size_t i = text.size(); i < width; ++i)-        std::cout << ' ';-}--void row_value(std::string_view label, std::string_view value) {-    print_left(label, 14, Color::Default, true);-    std::cout << value << "\n";-}--void row_number(std::string_view label, std::uint64_t value) {-    print_left(label, 14, Color::Default, true);-    std::cout << value << "\n";-}--std::string ext_of(std::string_view path) {-    std::size_t base_start = 0;-    for (std::size_t i = 0; i < path.size(); ++i) {-        if (path[i] == '/')-            base_start = i + 1;-    }-    std::optional<std::size_t> dot;-    for (std::size_t i = base_start; i < path.size(); ++i) {-        if (path[i] == '.')-            dot = i;-    }-    if (!dot || *dot <= base_start || *dot + 1 >= path.size())-        return "(none)";-    std::string out(path.substr(*dot));-    for (char& c : out) {-        if (c >= 'A' && c <= 'Z')-            c = static_cast<char>(c + 32);-    }-    return out;-}--std::uint64_t dir_size(const fs::path& path, std::size_t depth) {-    if (depth > 64)-        return 0;-    std::uint64_t total = 0;-    std::error_code ec;-    fs::recursive_directory_iterator it(path, ec);-    if (ec)-        return 0;-    for (const auto& entry : it) {-        if (entry.is_regular_file(ec)) {-            const auto size = entry.file_size(ec);-            if (!ec)-                total += size;-        }-    }-    return total;-}--std::string size_text(std::uint64_t n) {-    if (n >= 1073741824)-        return std::to_string(n / 1073741824) + "." +-               std::to_string(((n % 1073741824) * 10) / 1073741824) + " GiB";-    if (n >= 1048576)-        return std::to_string(n / 1048576) + "." + std::to_string(((n % 1048576) * 10) / 1048576) +-               " MiB";-    if (n >= 1024)-        return std::to_string(n / 1024) + "." + std::to_string(((n % 1024) * 10) / 1024) + " KiB";-    return std::to_string(n) + " B";-}--void print_size(std::uint64_t n) {-    std::cout << size_text(n) << "\n";-}--void show_date(std::string_view label, std::int64_t seconds) {-    const std::string stamp = format_utc(seconds);-    print_left(label, 14, Color::Default, true);-    std::cout << stamp.substr(0, 10) << "\n";-}--int run_inf(const std::vector<std::string>& args) {-    bool include_generated = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--")-            end_flags = true;-        else if (!end_flags &&-                 (arg == "-inc-gen" || arg == "-include-generated" || arg == "--include-generated"))-            include_generated = true;-        else if (!end_flags && is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        }-    }--    const auto root = open_repo();-    if (!root)-        return 1;-    Store store = Store::open_all(*root);-    auto view_opt = current_view(*root, store);-    View view = view_opt ? *view_opt : empty_view();-    const auto wc = working_copy_id(view);-    std::optional<Id> wc_tree;-    if (wc) {-        auto loaded = load_commit(store, *wc);-        if (loaded)-            wc_tree = loaded->commit.root_tree;-    }--    struct FileJob {-        const FlatEntry* entry = nullptr;-        PathAttributes attributes;-    };-    struct FileResult {-        std::string ext;-        std::uint64_t lines = 0;-        std::uint64_t bytes = 0;-    };--    std::vector<ExtStat> exts;-    std::vector<AuthorStat> authors;-    std::uint64_t total_files = 0;-    std::uint64_t total_lines = 0;-    std::uint64_t generated_files = 0;-    std::uint64_t generated_lines = 0;-    std::uint64_t generated_bytes = 0;-    if (wc_tree) {-        const AttributeRules attributes = AttributeRules::load(*root);-        const auto entries = flatten_tree(store, *wc_tree);-        std::vector<FileJob> jobs;-        jobs.reserve(entries.size());-        for (const auto& entry : entries) {-            if (entry.kind != KIND_FILE && entry.kind != KIND_EXECUTABLE)-                continue;-            jobs.push_back(FileJob{&entry, attributes.lookup(entry.path)});-        }--        std::vector<FileResult> results(jobs.size());-        std::atomic<std::size_t> next{0};-        const auto worker = [&]() {-            for (;;) {-                const std::size_t index = next.fetch_add(1);-                if (index >= jobs.size())-                    return;-                const auto& job = jobs[index];-                FileResult result;-                result.ext = ext_of(job.entry->path);-                BlobMeasure measure;-                if (measure_blob(store, job.entry->target, measure)) {-                    result.bytes = measure.bytes;-                    const bool binary = job.attributes.text == AttributeText::Binary ||-                                        (job.attributes.text == AttributeText::Auto &&-                                         measure.has_nul);-                    if (!binary)-                        result.lines = measure.lines;-                }-                results[index] = std::move(result);-            }-        };--        std::size_t workers = std::min<std::size_t>(available_cpu_count(), jobs.size());-        workers = std::min<std::size_t>(workers, 16);-        // Load every pack index up front: the per-chunk lookups below are far-        // cheaper once the store no longer opens indexes lazily.-        store.preload();-        if (workers <= 1) {-            worker();-        } else {-            std::vector<std::thread> threads;-            threads.reserve(workers);-            for (std::size_t w = 0; w < workers; ++w)-                threads.emplace_back(worker);-            for (auto& thread : threads)-                thread.join();-        }--        std::map<std::string, ExtStat> by_ext;-        for (std::size_t i = 0; i < jobs.size(); ++i) {-            const auto& job = jobs[i];-            const auto& result = results[i];-            if (job.attributes.generated) {-                ++generated_files;-                generated_lines += result.lines;-                generated_bytes += result.bytes;-                if (!include_generated)-                    continue;-            }-            ++total_files;-            total_lines += result.lines;-            auto& stat = by_ext[result.ext];-            stat.ext = result.ext;-            ++stat.files;-            stat.lines += result.lines;-            stat.bytes += result.bytes;-        }-        for (auto& [ext, stat] : by_ext) {-            (void)ext;-            exts.push_back(std::move(stat));-        }-    }--    std::uint64_t commits = 0;-    bool has_time = false;-    std::int64_t created = 0;-    std::int64_t last = 0;-    const auto roots = view_roots(view);-    for (const auto& id : collect_commits(store, roots)) {-        auto loaded = load_commit(store, id);-        if (!loaded)-            continue;-        ++commits;-        const auto secs = loaded->commit.committer.seconds;-        if (!has_time) {-            created = secs;-            last = secs;-            has_time = true;-        } else {-            created = std::min(created, secs);-            last = std::max(last, secs);-        }-        std::string name = loaded->commit.author.name;-        if (name.empty())-            name = "(unknown)";-        bool found = false;-        for (auto& author : authors) {-            if (author.name == name) {-                ++author.commits;-                found = true;-                break;-            }-        }-        if (!found)-            authors.push_back(AuthorStat{name, 1});-    }--    std::cout << "\n";-    print_bold("Repository overview", Color::BrightCyan, false);-    std::cout << "\n\n";-    row_value("Project", basename_string(*root));-    print_left("HEAD", 14, Color::Default, true);-    if (wc)-        std::cout << short_hex(*wc) << "\n";-    else-        std::cout << "<none>\n";-    row_number("Changes", commits);-    row_number("Bookmarks", view.bookmarks.size());-    row_number("Tags", view.tags.size());-    row_number("Files", total_files);-    row_number("Lines", total_lines);-    row_number("Authors", authors.size());-    if (has_time) {-        show_date("Created", created);-        show_date("Last change", last);-    }-    print_left("Size", 14, Color::Default, true);-    print_size(dir_size(veins_dir(*root), 0));-    if (generated_files > 0) {-        print_left("Generated", 14, Color::Default, true);-        std::cout << generated_files << " files  " << generated_lines << " lines  "-                  << size_text(generated_bytes);-        if (!include_generated)-            std::cout << "  (excluded; use -inc-gen)";-        std::cout << "\n";-    }-    std::cout << "\n";--    print_bold("Languages", Color::BrightCyan, false);-    std::cout << "\n\n";-    if (exts.empty()) {-        std::cout << "  no tracked files\n";-    } else {-        std::stable_sort(exts.begin(), exts.end(), [](const ExtStat& a, const ExtStat& b) {-            if (a.lines != b.lines)-                return a.lines > b.lines;-            return compare(bytes_of(a.ext), bytes_of(b.ext)) < 0;-        });-        std::size_t w_ext = 6;-        for (const auto& ext : exts)-            w_ext = std::max(w_ext, ext.ext.size());-        for (std::size_t i = 0; i < exts.size(); ++i) {-            const auto& ext = exts[i];-            print_left(ext.ext, w_ext, Color::Default, false);-            std::cout << "  ";-            print_bar(ext.lines, total_lines, color_for(i));-            std::cout << "  ";-            print_percent(percent(ext.lines, total_lines));-            std::cout << "%  " << ext.lines << " lines  " << ext.files << " files\n";-        }-    }-    std::cout << "\n";--    print_bold("Authors", Color::BrightCyan, false);-    std::cout << "\n\n";-    if (authors.empty()) {-        std::cout << "  no commits\n";-    } else {-        std::stable_sort(authors.begin(), authors.end(),-                         [](const AuthorStat& a, const AuthorStat& b) {-                             if (a.commits != b.commits)-                                 return a.commits > b.commits;-                             return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                         });-        std::size_t w_name = 6;-        for (const auto& author : authors)-            w_name = std::max(w_name, author.name.size());-        for (std::size_t i = 0; i < authors.size(); ++i) {-            const auto& author = authors[i];-            print_left(author.name, w_name, Color::Cyan, false);-            std::cout << "  ";-            print_bar(author.commits, commits, color_for(i));-            std::cout << "  ";-            print_percent(percent(author.commits, commits));-            std::cout << "%  " << author.commits << " commits\n";-        }-    }-    std::cout << "\n";-    return 0;-}--void usage() {-    std::cout << "veins is a tool for managing source code\n";-    std::cout << "\n";-    std::cout << "commands:\n";-    std::cout << "  init         create a repository\n";-    std::cout << "  git          import from or export to git\n";-    std::cout << "  remote       manage native remotes\n";-    std::cout << "  clone        clone a repository over the native protocol\n";-    std::cout << "  fetch        fetch from a native remote\n";-    std::cout << "  pull         fetch and fast-forward the current bookmark; alias: pl\n";-    std::cout << "  gg           fetch the active remote, or clone a URL\n";-    std::cout << "  push         push a bookmark to a native remote\n";-    std::cout << "  serve        run the native server over stdio or TLS\n";-    std::cout << "  key          manage local Ed25519 keys\n";-    std::cout << "  auth         remember keys for hosts and set a default\n";-    std::cout << "  access       manage a served repository's access file\n";-    std::cout << "  whoami       report the role granted by a server\n";-    std::cout << "  co           write a revision into the working directory; "-                 "alias: checkout\n";-    std::cout << "  stat         show working-copy changes; alias: status\n";-    std::cout << "  ls           list tracked files\n";-    std::cout << "  inf          show a repository breakdown\n";-    std::cout << "  log          show commit history\n";-    std::cout << "  show         show a commit and its diff\n";-    std::cout << "  hash         print the commit hash for a revision\n";-    std::cout << "  diff         show a unified diff, paged on a terminal\n";-    std::cout << "  merge        create a merge commit; never fails\n";-    std::cout << "  rebase       rewrite changes onto a new parent\n";-    std::cout << "  xs           list conflicted paths\n";-    std::cout << "  resolve      resolve a conflicted path\n";-    std::cout << "  new          start a new change\n";-    std::cout << "  bmk          manage named branch pointers\n";-    std::cout << "  tag          manage named tags\n";-    std::cout << "  cfg          read and write configuration\n";-    std::cout << "  edit         open paths in the configured text editor\n";-    std::cout << "  rm           untrack paths, keeping files on disk by default\n";-    std::cout << "  mv           move a tracked file and record the rename\n";-    std::cout << "  ex           add paths or globs to .vnexclude\n";-    std::cout << "  attr         add or remove .vnattribs rules\n";-    std::cout << "  desc         set the working-copy commit message; alias: "-                 "describe\n";-    std::cout << "  go           describe and start a new change; alias: commit\n";-    std::cout << "  amend        rewrite a revision's message and its descendants\n";-    std::cout << "  undo         restore the previous operation view\n";-    std::cout << "  op           operation log commands\n";-    std::cout << "  fsck         verify repository integrity\n";-    std::cout << "  repack       rewrite packs into one delta-compressed pack; "-                 "alias: gc\n";-    std::cout << "  self-test    run the format self-tests\n";-    std::cout << "  version      print version information\n";-    std::cout << "  bench-import compare lazy import metadata; requires git\n";-    std::cout << "  help         show help for a command\n";-    std::cout << "\n";-    std::cout << "run 'vn help <command>' for details\n";-}--void show_init() {-    std::cout << "usage: vn init [path] [-git-import:<gitdir>] [-remote:<url>] "-                 "[-remote-name:<name>]\n\n";-    std::cout << "create a veins repository, optionally importing an existing "-                 "git repository\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [path]                    directory to create (default: .)\n\n";-    std::cout << "options:\n";-    std::cout << "  -git-import:<gitdir>      import from <gitdir> (a directory "-                 "containing .git)\n";-    std::cout << "  -remote:<url>             configure a native remote after import\n";-    std::cout << "  -remote-name:<name>       remote name to configure (default: o)\n";-    std::cout << "\nwithout -remote:, no native remote is configured and 'vn psh o'\n";-    std::cout << "will fail until one is added with 'vn remote add o <url>'\n";-}--void show_status() {-    std::cout << "usage: vn stat\n\n";-    std::cout << "show working-copy changes relative to the parent commit\n\n";-    std::cout << "aliases: status\n";-}--void show_ls() {-    std::cout << "usage: vn ls [rev] [-plain]\n\n";-    std::cout << "list tracked files as an ASCII tree\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [rev]                     revision to list (default: @)\n\n";-    std::cout << "options:\n";-    std::cout << "  -rev <rev>                revision to list\n";-    std::cout << "  -plain, -p                print one tracked path per line\n";-}--void show_inf() {-    std::cout << "usage: vn inf [-inc-gen]\n\n";-    std::cout << "show a repository overview with a language breakdown by file "-                 "extension,\n";-    std::cout << "line-of-code shares, author commit shares, and repository metadata\n\n";-    std::cout << "options:\n";-    std::cout << "  -inc-gen                  include files marked generated in .vnattribs\n";-}--void show_log() {-    std::cout << "usage: vn log [-a] [-rev <revset>] [-lN | -fN] [-no-col-titles] "-                 "[-p]\n\n";-    std::cout << "show commit history, newest first\n\n";-    std::cout << "options:\n";-    std::cout << "  -a, -all                  show the entire history\n";-    std::cout << "  -rev <revset>             show only the given revision set\n";-    std::cout << "  -lN, -l <N>               show the last N commits (newest N)\n";-    std::cout << "  -fN, -f <N>               show the first N commits (oldest N)\n";-    std::cout << "  -no-col-titles            omit column titles\n";-    std::cout << "  -p                        page the full history through the pager\n\n";-    std::cout << "without -a, -l, -f or -p, the last log.default_amount commits are shown\n";-    std::cout << "(global config, default 20)\n";-}--void show_show() {-    std::cout << "usage: vn show [-a] [rev] [-no-col-titles]\n\n";-    std::cout << "show a commit's metadata and its diff against its first parent,\n";-    std::cout << "paged when stdout is a terminal\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [rev]                     revision to show (default: @)\n\n";-    std::cout << "options:\n";-    std::cout << "  -a, -all                  print the whole output at once\n";-    std::cout << "  -no-col-titles            omit the metadata labels\n";-}--void show_hash() {-    std::cout << "usage: vn hash [rev] [-short|-long]\n\n";-    std::cout << "print the commit hash for a revision\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [rev]                     revision to hash (default: @)\n\n";-    std::cout << "options:\n";-    std::cout << "  -rev <rev>                revision to hash\n";-    std::cout << "  -short                    print the 12-character abbreviated "-                 "hash\n";-    std::cout << "  -long                     print the full 64-character hash "-                 "(default)\n";-}--void show_diff() {-    std::cout << "usage: vn diff [-a] [-rev <rev>] [<rev> <rev>] [<path>]\n\n";-    std::cout << "show a unified diff, paged when stdout is a terminal\n\n";-    std::cout << "options:\n";-    std::cout << "  -a, -all                  print the whole diff at once\n";-    std::cout << "  -rev <rev>                compare a revision with its parent\n";-}--void show_new() {-    std::cout << "usage: vn new [<rev>...]\n\n";-    std::cout << "start a new empty change on top of the working copy or a revision\n";-}--void show_describe() {-    std::cout << "usage: vn desc [-message <message>] [<message>]\n\n";-    std::cout << "set the working-copy commit message\n\n";-    std::cout << "aliases: describe\n";-}--void show_commit() {-    std::cout << "usage: vn go -message <message>\n\n";-    std::cout << "set the message and start a new change\n\n";-    std::cout << "a non-empty commit message is required\n\n";-    std::cout << "aliases: commit\n";-}--void show_amend() {-    std::cout << "usage: vn amend <rev> -m <message>\n\n";-    std::cout << "rewrite a revision's message and update its descendants\n\n";-    std::cout << "options:\n";-    std::cout << "  -m, -message <message>    new commit message\n\n";-    std::cout << "revisions reachable from a remote ref cannot be amended\n";-}--void show_checkout() {-    std::cout << "usage: vn co [rev]\n\n";-    std::cout << "write a revision into the working directory\n\n";-    std::cout << "aliases: checkout\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [rev]                     revision to check out\n";-}--void show_fsck() {-    std::cout << "usage: vn fsck [path] [-verbose]\n\n";-    std::cout << "verify pack, index, object, and operation-log integrity\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [path]                    repository to check (default: .)\n\n";-    std::cout << "options:\n";-    std::cout << "  -v, -verbose              print verbose output\n";-}--void show_repack() {-    std::cout << "usage: vn repack [path] [-level:<n>] [-verbose]\n\n";-    std::cout << "rewrite all packs into one delta-compressed pack\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [path]                    repository to rewrite (default: .)\n\n";-    std::cout << "options:\n";-    std::cout << "  -level:<n>                zstd level, 1-19 (default: 6)\n";-    std::cout << "  -v, -verbose              print the size change\n";-}--void show_selftest() {-    std::cout << "usage: vn self-test\n\n";-    std::cout << "run the format self-tests\n";-}--void show_version() {-    std::cout << "usage: vn version\n\n";-    std::cout << "print version information\n";-}--void show_help() {-    std::cout << "usage: vn help [command]\n\n";-    std::cout << "show help for the program or a command\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [command]                 command to describe\n";-}--void show_bmk() {-    std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n\n";-    std::cout << "manage named, movable pointers to commits (branches)\n\n";-    std::cout << "subcommands:\n";-    std::cout << "  set <name> [-rev <rev>]   create or move a bookmark (default: @)\n";-    std::cout << "  mv <name> [-rev <rev>]    alias of set\n";-    std::cout << "  ls [-no-col-titles]       list bookmarks\n";-    std::cout << "  rm <name>                 delete a bookmark\n\n";-    std::cout << "examples:\n";-    std::cout << "  vn bmk set main\n";-    std::cout << "  vn new main\n";-    std::cout << "  vn co main\n";-}--void show_tag() {-    std::cout << "usage: vn tag <set|ls|rm|latest> ...\n\n";-    std::cout << "manage named pointers to commits (tags)\n\n";-    std::cout << "subcommands:\n";-    std::cout << "  set <name> [-rev <rev>]   create or move a tag (default: @)\n";-    std::cout << "  ls [-no-col-titles]       list tags\n";-    std::cout << "  rm <name>                 delete a tag\n";-    std::cout << "  latest                    print the latest tag name\n\n";-    std::cout << "the latest tag is the one whose target commit has the newest\n";-    std::cout << "committer timestamp; equal timestamps use natural name order\n";-}--void show_cfg() {-    std::cout << "usage: vn cfg [<key>] [<value>]\n";-    std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";-    std::cout << "       vn cfg -list\n";-    std::cout << "       vn cfg -unset <key>\n\n";-    std::cout << "read and write local repository configuration\n\n";-    std::cout << "  vn cfg                      list all keys\n";-    std::cout << "  vn cfg <key>                print a value\n";-    std::cout << "  vn cfg <key> <value>        set a value\n";-    std::cout << "  vn cfg -unset <key>         remove a key\n";-    std::cout << "  vn cfg -global ...          use the user config instead\n\n";-    std::cout << "the global editor command is read from 'editor' or 'core.editor'\n";-    std::cout << "  vn cfg -global editor \"code --wait\"\n";-}--void show_edit() {-    std::cout << "usage: vn edit [<path>...]\n\n";-    std::cout << "open paths in the configured text editor\n\n";-    std::cout << "the editor is read from the global 'editor' or 'core.editor' key,\n";-    std::cout << "then $VN_EDITOR, $VISUAL, and $EDITOR. With no paths, opens '.'.\n";-}--void show_rm() {-    std::cout << "usage: vn rm [-delete] <path>...\n\n";-    std::cout << "remove paths from the working-copy tree\n\n";-    std::cout << "files stay on disk by default. Arguments may be paths or globs "-                 "and are\n";-    std::cout << "resolved relative to the current directory. Supported "-                 "wildcards are\n";-    std::cout << "'*', '?', and '**'; '*' and '?' do not cross directory "-                 "separators.\n\n";-    std::cout << "options:\n";-    std::cout << "  -delete                   delete matching files from disk "-                 "after untracking\n";-}--void show_mv() {-    std::cout << "usage: vn mv <from> <to>\n\n";-    std::cout << "move a tracked file; the following snapshot records the rename\n";-}--void show_ex() {-    std::cout << "usage: vn ex <pattern>...\n\n";-    std::cout << "append ignore patterns to the repository root .vnexclude\n\n";-    std::cout << "patterns use gitignore syntax and are resolved relative to the "-                 "current\n";-    std::cout << "directory. Quote wildcard patterns so the shell does not "-                 "expand them:\n";-    std::cout << "  vn ex '*.dSYM'\n";-}--void show_attr() {-    std::cout << "usage: vn attr <gen|txt|bin|lf|crlf|cr> <glob>...\n";-    std::cout << "       vn attr rm <gen|txt|bin|lf|crlf|cr> <glob>...\n";-    std::cout << "       vn attr ls\n\n";-    std::cout << "set or remove .vnattribs rules for generated files, text/binary\n";-    std::cout << "classification, and line endings\n\n";-    std::cout << "subcommands:\n";-    std::cout << "  gen <glob>...             mark paths as generated\n";-    std::cout << "  txt <glob>...             force text classification\n";-    std::cout << "  bin <glob>...             force binary classification\n";-    std::cout << "  lf|crlf|cr <glob>...      set the checkout line ending\n";-    std::cout << "  rm <attr> <glob>...       remove an attribute from matching rules\n";-    std::cout << "  ls                        list parsed rules\n\n";-    std::cout << "an existing rule for the same glob is updated in place; otherwise "-                 "a new\n";-    std::cout << "rule is appended. Quote globs so the shell does not expand them:\n";-    std::cout << "  vn attr gen '*.ssa' '*.bin'\n";-    std::cout << "  vn attr bin '*.exe'\n";-    std::cout << "  vn attr lf '*.c'\n";-    std::cout << "  vn attr rm lf '*.c'\n";-}--void show_undo() {-    std::cout << "usage: vn undo\n\n";-    std::cout << "record an operation that restores the previous operation view\n";-}--void show_op() {-    std::cout << "usage: vn op <log|restore|revert> [<op>]\n\n";-    std::cout << "inspect and restore operations\n";-}--void show_merge() {-    std::cout << "usage: vn merge <rev>...\n\n";-    std::cout << "create a merge commit from the working-copy commit and the "-                 "revisions\n";-    std::cout << "the merge never fails; conflicts are stored as conflict values\n";-}--void show_rebase() {-    std::cout << "usage: vn rebase -s <rev> -d <rev>\n\n";-    std::cout << "rewrite the source change and its descendants onto the "-                 "destination\n\n";-    std::cout << "options:\n";-    std::cout << "  -s, -source <rev>         first change to rewrite\n";-    std::cout << "  -d, -destination <rev>    new parent\n";-}--void show_xs() {-    std::cout << "usage: vn xs [-porcelain]\n\n";-    std::cout << "list conflicted paths and, for text conflicts, conflicting "-                 "line ranges\n\n";-    std::cout << "porcelain columns (tab-separated):\n";-    std::cout << "  path, kind, base-ranges, ours-ranges, theirs-ranges\n";-}--void show_resolve() {-    std::cout << "usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...\n";-    std::cout << "       vn resolve -list\n\n";-    std::cout << "resolve conflicted paths. Without -take, the current file "-                 "content is\n";-    std::cout << "recorded as the resolution. -tool substitutes $BASE, $OURS, "-                 "$THEIRS,\n";-    std::cout << "and $OUTPUT in the command.\n";-}--void show_git() {-    std::cout << "usage: vn git <subcommand> [arguments]\n\n";-    std::cout << "git bridge commands:\n";-    std::cout << "  import [-source:<gitdir>] [path]\n";-    std::cout << "                            import reachable git commits and refs\n";-    std::cout << "  export [path]             export commits into the git mirror\n";-    std::cout << "  materialize [path]        replace lazy git blobs with stored "-                 "blobs\n";-    std::cout << "  fetch [<remote>] [path]   git fetch into the mirror, then import\n";-    std::cout << "  push [<remote>] <bookmark> [path]\n";-    std::cout << "                            export and git push a bookmark\n";-    std::cout << "  mirror <push|pt> ...      mirror all refs or one tag to a git remote\n";-    std::cout << "  remote <add|list|remove>  manage git remotes\n\n";-    std::cout << "run 'vn help git <subcommand>' for details\n";-}--void show_git_import() {-    std::cout << "usage: vn git import [-source:<gitdir>] [-remote:<url>] "-                 "[-remote-name:<name>] [path]\n\n";-    std::cout << "import commits and refs reachable from a git repository\n\n";-    std::cout << "an empty working tree is checked out to the imported head\n\n";-    std::cout << "arguments:\n";-    std::cout << "  [path]                    veins repository (default: .)\n\n";-    std::cout << "options:\n";-    std::cout << "  -source:<gitdir>          source git root to mirror (a directory "-                 "containing .git)\n";-    std::cout << "  -remote:<url>             configure a native remote after import\n";-    std::cout << "  -remote-name:<name>       remote name to configure (default: o)\n";-    std::cout << "\nwithout -remote:, no native remote is configured and 'vn psh o'\n";-    std::cout << "will fail until one is added with 'vn remote add o <url>'\n";-}--void show_git_export() {-    std::cout << "usage: vn git export [path]\n\n";-    std::cout << "export commits reachable from bookmarks and tags into .veins/git\n";-}--void show_git_materialize() {-    std::cout << "usage: vn git materialize [path]\n\n";-    std::cout << "replace lazy git-backed blobs with canonical stored blobs.\n";-    std::cout << "rewrites affected trees, commits, and refs and records one "-                 "operation\n";-}--void show_git_mirror() {-    std::cout << "usage: vn git mirror <push|pt> ...\n\n";-    std::cout << "mirror Veins refs to a git remote\n\n";-    std::cout << "subcommands:\n";-    std::cout << "  push, psh [<remote>] [path]\n";-    std::cout << "                            export and push all bookmarks and tags\n";-    std::cout << "  pt <tag> [<remote>] [path]\n";-    std::cout << "                            export and push one tag\n\n";-    std::cout << "options:\n";-    std::cout << "  -dry-run                  show what would be pushed\n";-    std::cout << "  -prune                    delete remote refs absent from Veins\n";-    std::cout << "  -strict                   fail if any ref cannot be exported\n";-    std::cout << "  -no-force                 do not force-push\n\n";-    std::cout << "the default remote is git.mirror, then origin, then the only\n";-    std::cout << "configured git remote\n";-}--void show_unimplemented(std::string_view command) {-    std::cout << "usage: vn " << command << "\n\n";-    std::cout << "this command is planned for a later stage of the C++ rewrite\n";-    std::cout << "and is not available in the current local-core build\n";-}--int run_help(const std::vector<std::string>& args) {-    if (args.size() <= 2) {-        usage();-        return 0;-    }-    const std::string& cmd = args[2];-    if (cmd == "init")-        show_init();-    else if (cmd == "stat" || cmd == "status")-        show_status();-    else if (cmd == "ls")-        show_ls();-    else if (cmd == "inf")-        show_inf();-    else if (cmd == "log" || cmd == "l")-        show_log();-    else if (cmd == "show")-        show_show();-    else if (cmd == "hash")-        show_hash();-    else if (cmd == "diff" || cmd == "d")-        show_diff();-    else if (cmd == "new")-        show_new();-    else if (cmd == "desc" || cmd == "describe")-        show_describe();-    else if (cmd == "go" || cmd == "commit")-        show_commit();-    else if (cmd == "amend")-        show_amend();-    else if (cmd == "co" || cmd == "checkout")-        show_checkout();-    else if (cmd == "fsck")-        show_fsck();-    else if (cmd == "repack" || cmd == "gc")-        show_repack();-    else if (cmd == "bmk")-        show_bmk();-    else if (cmd == "tag")-        show_tag();-    else if (cmd == "cfg")-        show_cfg();-    else if (cmd == "edit")-        show_edit();-    else if (cmd == "rm")-        show_rm();-    else if (cmd == "mv")-        show_mv();-    else if (cmd == "ex")-        show_ex();-    else if (cmd == "attr")-        show_attr();-    else if (cmd == "undo")-        show_undo();-    else if (cmd == "op")-        show_op();-    else if (cmd == "merge")-        show_merge();-    else if (cmd == "rebase")-        show_rebase();-    else if (cmd == "xs")-        show_xs();-    else if (cmd == "resolve")-        show_resolve();-    else if (cmd == "self-test")-        show_selftest();-    else if (cmd == "version")-        show_version();-    else if (cmd == "help")-        show_help();-    else if (net_help(cmd)) {-    } else if (cmd == "git") {-        if (args.size() > 3) {-            const std::string& sub = args[3];-            if (sub == "import")-                show_git_import();-            else if (sub == "export")-                show_git_export();-            else if (sub == "materialize")-                show_git_materialize();-            else if (sub == "fetch")-                std::cout << "usage: vn git fetch [<remote>] [path]\n";-            else if (sub == "push")-                std::cout << "usage: vn git push [<remote>] <bookmark> [path]\n";-            else if (sub == "mirror")-                show_git_mirror();-            else if (sub == "remote")-                std::cout << "usage: vn git remote <add|list|remove> ...\n";-            else {-                error_prefix();-                std::cout << "unknown git subcommand: " << sub << "\n";-                return 1;-            }-        } else {-            show_git();-        }-    } else if (cmd == "bench-import")-        show_unimplemented(cmd);-    else {-        usage();-        error_prefix();-        std::cout << "unknown command: " << cmd << "\n";-        return 1;-    }-    return 0;-}--} // namespace--int cli_run(const std::vector<std::string>& args) {-    install_promisor_fetcher();-    if (args.size() < 2) {-        usage();-        return 1;-    }-    const std::string& cmd = args[1];-    if (cmd == "init")-        return run_init(args);-    if (cmd == "stat" || cmd == "status" || cmd == "s")-        return run_status();-    if (cmd == "ls")-        return run_ls(args);-    if (cmd == "inf")-        return run_inf(args);-    if (cmd == "log" || cmd == "l")-        return run_log(args);-    if (cmd == "show")-        return run_show(args);-    if (cmd == "hash")-        return run_hash(args);-    if (cmd == "diff" || cmd == "d")-        return run_diff(args);-    if (cmd == "new")-        return run_new(args);-    if (cmd == "desc" || cmd == "describe")-        return run_describe(args);-    if (cmd == "go" || cmd == "commit")-        return run_commit(args);-    if (cmd == "amend")-        return run_amend(args);-    if (cmd == "co" || cmd == "checkout")-        return run_checkout(args);-    if (cmd == "bmk")-        return bmk_run(args);-    if (cmd == "tag")-        return tag_run(args);-    if (cmd == "cfg" || cmd == "config")-        return cfg_run(args);-    if (cmd == "edit")-        return run_edit(args);-    if (cmd == "rm")-        return rm_run(args);-    if (cmd == "mv")-        return mv_run(args);-    if (cmd == "ex")-        return ex_run(args);-    if (cmd == "attr")-        return attr_run(args);-    if (cmd == "op")-        return op_run(args);-    if (cmd == "undo")-        return undo_run(args);-    if (cmd == "merge")-        return merge_run(args);-    if (cmd == "rebase")-        return rebase_run(args);-    if (cmd == "xs")-        return xs_run(args);-    if (cmd == "resolve")-        return resolve_run(args);-    if (cmd == "fsck")-        return run_fsck(args);-    if (cmd == "repack" || cmd == "gc")-        return run_repack(args);-    if (cmd == "self-test")-        return run_self_test();-    if (cmd == "version" || cmd == "-version" || cmd == "-v") {-        std::cout << "veins v" << vn_version();-        if (vn_commit()[0] != '\0')-            std::cout << " " << vn_commit();-        std::cout << " (store v" << STORE_VERSION << ")\n";-        return 0;-    }-    if (cmd == "help" || cmd == "-help" || cmd == "-h")-        return run_help(args);--    if (cmd == "remote")-        return remote_run(args);-    if (cmd == "clone")-        return clone_run(args);-    if (cmd == "fetch")-        return fetch_run(args);-    if (cmd == "pull" || cmd == "pl")-        return pull_run(args);-    if (cmd == "gg")-        return gg_run(args);-    if (cmd == "push" || cmd == "psh")-        return push_run(args);-    if (cmd == "serve")-        return serve_run(args);-    if (cmd == "key")-        return key_run(args);-    if (cmd == "auth")-        return auth_run(args);-    if (cmd == "access")-        return access_run(args);-    if (cmd == "whoami")-        return whoami_run(args);-    if (cmd == "about") {-        std::cout << "Veins v" << vn_version() << " - Where the source code lives.\n";-        std::cout << "(C) Navid Momtahen - 2026\n";-        std::cout << "https://veins.pages.dev\n";-        std::cout << "https://veinsforge.top/navid/veins";-        return 0;-    }-    if (cmd == "git")-        return git_cli_run(args);-    if (cmd == "bench-import") {-        error_prefix();-        std::cout << "command '" << cmd << "' is not available in this stage\n";-        return 1;-    }-    usage();-    error_prefix();-    std::cout << "unknown command: " << cmd << "\n";-    return 1;-}--} // namespace vn--- a/xveins/src/cli/cli.h+++ /dev/null@@ -1,10 +0,0 @@-#pragma once--#include <string>-#include <vector>--namespace vn {--int cli_run(const std::vector<std::string>& args);--} // namespace vn--- a/xveins/src/cli/local_commands.h+++ /dev/null@@ -1,20 +0,0 @@-#pragma once--#include <string>-#include <vector>--namespace vn {--// Local-only commands. Each receives the full argv-style vector and indexes-// its own arguments (args[0] is the program, args[1] the command).-int bmk_run(const std::vector<std::string>& args);-int tag_run(const std::vector<std::string>& args);-int cfg_run(const std::vector<std::string>& args);-int rm_run(const std::vector<std::string>& args);-int mv_run(const std::vector<std::string>& args);-int ex_run(const std::vector<std::string>& args);-int attr_run(const std::vector<std::string>& args);-int op_run(const std::vector<std::string>& args);-int undo_run(const std::vector<std::string>& args);--} // namespace vn--- a/xveins/src/cli/net_commands.cpp+++ /dev/null@@ -1,1715 +0,0 @@-#include "cli/net_commands.h"--#include "auth/auth.h"-#include "crypto/crypto.h"-#include "protocol/promisor.h"-#include "protocol/protocol.h"-#include "server/server.h"-#include "store/store.h"-#include "worktree/worktree.h"--#include <algorithm>-#include <charconv>-#include <cstddef>-#include <cstring>-#include <functional>-#include <iostream>-#include <optional>-#include <set>-#include <string>-#include <unordered_set>-#include <vector>--namespace vn {--namespace {--bool starts_with(std::string_view text, std::string_view prefix) {-    return text.size() >= prefix.size() && text.substr(0, prefix.size()) == prefix;-}--bool is_flag(std::string_view arg) {-    return !arg.empty() && arg.front() == '-';-}--std::string arg_at(const std::vector<std::string>& args, std::size_t index) {-    return index < args.size() ? args[index] : std::string();-}--void report_connect_failure(std::string_view fallback) {-    error_prefix();-    const std::string& detail = proto::Client::last_connect_error();-    std::cout << (detail.empty() ? std::string(fallback) : detail) << "\n";-}--std::string trim_text(std::string_view text) {-    std::size_t start = 0;-    std::size_t end = text.size();-    auto blank = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };-    while (start < end && blank(text[start]))-        ++start;-    while (end > start && blank(text[end - 1]))-        --end;-    return std::string(text.substr(start, end - start));-}--std::string remote_key(std::string_view remote, std::string_view field) {-    std::string out = "remote.";-    out += remote;-    out.push_back('.');-    out += field;-    return out;-}--std::string last_segment(std::string_view path) {-    while (path.size() > 1 && path.back() == '/')-        path.remove_suffix(1);-    const auto slash = path.rfind('/');-    if (slash != std::string_view::npos && slash + 1 < path.size())-        return std::string(path.substr(slash + 1));-    if (!path.empty() && path != "/")-        return std::string(path);-    return "repo";-}--bool same_id(const Id& a, const Id& b) {-    return std::memcmp(a.data(), b.data(), ID_LEN) == 0;-}--void report_client_error(const proto::Client& client, std::string_view context) {-    error_prefix();-    if (!client.error().empty())-        std::cout << context << ": " << client.error() << "\n";-    else-        std::cout << context << "\n";-}--std::optional<Id> default_target(const std::vector<proto::RefInfo>& refs) {-    for (const auto& ref : refs) {-        if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))-            return ref.target;-    }-    for (const auto& ref : refs) {-        if (ref.kind == 0)-            return ref.target;-    }-    return std::nullopt;-}--std::optional<std::string> default_ref_name(const std::vector<proto::RefInfo>& refs) {-    for (const auto& ref : refs) {-        if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))-            return ref.name;-    }-    for (const auto& ref : refs) {-        if (ref.kind == 0)-            return ref.name;-    }-    return std::nullopt;-}--std::vector<Id> selected_commits(const std::vector<proto::RefInfo>& refs, std::string_view policy) {-    std::vector<Id> out;-    if (policy == "none")-        return out;-    if (policy == "head") {-        if (auto target = default_target(refs))-            out.push_back(*target);-        return out;-    }-    for (const auto& ref : refs)-        out.push_back(ref.target);-    return out;-}--bool set_bookmark(View& view, std::string_view name, const Id& target) {-    if (auto index = find_bookmark(view, name)) {-        view.bookmarks[*index].targets.adds = {target};-        view.bookmarks[*index].targets.removes.clear();-        return true;-    }-    Bookmark bookmark;-    bookmark.name = std::string(name);-    bookmark.targets.adds = {target};-    view.bookmarks.push_back(std::move(bookmark));-    return true;-}--bool set_tag(View& view, std::string_view name, const Id& target) {-    if (auto index = find_tag(view, name)) {-        view.tags[*index].target = target;-        return true;-    }-    view.tags.push_back(TagRef{std::string(name), target});-    return true;-}--bool set_remote_ref(View& view, std::string_view remote, std::string_view name, const Id& target) {-    for (auto& ref : view.remote_refs) {-        if (ref.remote == remote && ref.name == name) {-            ref.target = target;-            return true;-        }-    }-    view.remote_refs.push_back(RemoteRef{std::string(remote), std::string(name), target});-    return true;-}--bool apply_refs(const fs::path& root, const std::vector<proto::RefInfo>& refs,-                std::string_view remote, bool clone) {-    Store store = Store::open_all(root);-    auto tx = Txn::begin(root, store);-    if (!tx)-        return false;-    for (const auto& ref : refs) {-        if (ref.kind == 1) {-            set_tag(tx->view(), ref.name, ref.target);-        } else if (clone) {-            set_bookmark(tx->view(), ref.name, ref.target);-        } else {-            set_remote_ref(tx->view(), remote, ref.name, ref.target);-            if (!find_bookmark(tx->view(), ref.name))-                set_bookmark(tx->view(), ref.name, ref.target);-        }-    }-    rebuild_heads(tx->view());-    if (clone) {-        if (auto target = default_target(refs)) {-            auto child = create_working_copy_commit(*tx, *target);-            if (!child)-                return false;-            set_workspace(tx->view(), *child);-            rebuild_heads(tx->view());-        }-    }-    const bool ok = tx->finish("clone").has_value();-    if (ok && clone) {-        if (auto name = default_ref_name(refs))-            (void)set_current_bookmark(root, *name);-        else-            (void)clear_current_bookmark(root);-    }-    return ok;-}--struct IdHasher {-    std::size_t operator()(const Id& id) const noexcept {-        std::size_t h = 1469598103934665603ull;-        for (auto b : id) {-            h ^= b;-            h *= 1099511628211ull;-        }-        return h;-    }-};--struct IdEqual {-    bool operator()(const Id& a, const Id& b) const noexcept {-        return std::memcmp(a.data(), b.data(), ID_LEN) == 0;-    }-};--using IdSet = std::unordered_set<Id, IdHasher, IdEqual>;--struct Walker {-    Walker(Store& store, bool want_objects) : store(store), want_objects(want_objects) {}--    Store& store;-    bool want_objects = false;-    IdSet blobs;-    IdSet conflicts;-    IdSet chunks;-    IdSet trees;-    IdSet objects;-    std::vector<Id> chunk_out;-    std::vector<Id> object_out;--    void add_object(const Id& id) {-        if (want_objects && objects.insert(id).second)-            object_out.push_back(id);-    }--    void walk_blob(const Id& id) {-        if (!blobs.insert(id).second)-            return;-        add_object(id);-        auto body = store.read_body(id, TYPE_BLOB);-        if (!body)-            return;-        auto blob = decode_blob(bytes_of(*body));-        if (!blob)-            return;-        if (blob->form == BlobForm::Leaf) {-            for (const auto& entry : blob->entries) {-                if (chunks.insert(entry.id).second)-                    chunk_out.push_back(entry.id);-                add_object(entry.id);-            }-        } else if (blob->form == BlobForm::Interior) {-            for (const auto& entry : blob->entries)-                walk_blob(entry.id);-        }-    }--    void walk_conflict(const Id& id) {-        if (!conflicts.insert(id).second)-            return;-        add_object(id);-        auto body = store.read_body(id, TYPE_CONFLICT);-        if (!body)-            return;-        auto conflict = decode_conflict(bytes_of(*body));-        if (!conflict)-            return;-        for (const auto& value : conflict->adds) {-            if (value.target)-                walk_value(value.kind, *value.target);-        }-        for (const auto& value : conflict->removes) {-            if (value.target)-                walk_value(value.kind, *value.target);-        }-    }--    void walk_value(std::uint8_t kind, const Id& id) {-        if (kind == KIND_SUBTREE)-            walk_tree(id);-        else if (kind == KIND_CONFLICT)-            walk_conflict(id);-        else-            walk_blob(id);-    }--    void walk_entry(const TreeEntry& entry) {-        if (entry.kind == KIND_SUBTREE)-            walk_tree(entry.target);-        else if (entry.kind == KIND_CONFLICT)-            walk_conflict(entry.target);-        else if (entry.kind != KIND_SUBMODULE)-            walk_blob(entry.target);-    }--    void walk_tree(const Id& id) {-        if (!trees.insert(id).second)-            return;-        add_object(id);-        auto body = store.read_body(id, TYPE_TREE);-        if (!body)-            return;-        auto tree = decode_tree(bytes_of(*body));-        if (!tree)-            return;-        for (const auto& entry : tree->entries)-            walk_entry(entry);-    }--    void walk_tree_delta(const Id& id, const std::optional<Id>& old_id) {-        if (old_id && same_id(*old_id, id))-            return;-        if (!trees.insert(id).second)-            return;-        add_object(id);-        auto body = store.read_body(id, TYPE_TREE);-        if (!body)-            return;-        auto tree = decode_tree(bytes_of(*body));-        if (!tree)-            return;-        std::optional<Tree> old_tree;-        if (old_id) {-            auto old_body = store.read_body(*old_id, TYPE_TREE);-            if (old_body) {-                auto decoded = decode_tree(bytes_of(*old_body));-                if (decoded)-                    old_tree = std::move(*decoded);-            }-        }-        std::size_t old_index = 0;-        for (const auto& entry : tree->entries) {-            if (!old_tree) {-                walk_entry(entry);-                continue;-            }-            while (old_index < old_tree->entries.size() &&-                   compare(bytes_of(old_tree->entries[old_index].name), bytes_of(entry.name)) < 0)-                ++old_index;-            if (old_index >= old_tree->entries.size() ||-                compare(bytes_of(old_tree->entries[old_index].name), bytes_of(entry.name)) != 0) {-                walk_entry(entry);-                continue;-            }-            const auto& old_entry = old_tree->entries[old_index++];-            if (old_entry.kind == entry.kind && same_id(old_entry.target, entry.target))-                continue;-            if (entry.kind == KIND_SUBTREE && old_entry.kind == KIND_SUBTREE)-                walk_tree_delta(entry.target, old_entry.target);-            else if (entry.kind != KIND_SUBMODULE)-                walk_entry(entry);-        }-    }-};--std::vector<Id> chunks_for_commits(Store& store, const std::vector<Id>& commits) {-    Walker walker{store, false};-    for (const auto& id : commits) {-        auto loaded = load_commit(store, id);-        if (loaded)-            walker.walk_tree(loaded->commit.root_tree);-    }-    return std::move(walker.chunk_out);-}--std::vector<Id> collect_commits_until(Store& store, std::span<const Id> start, const IdSet& stop) {-    std::vector<Id> out;-    std::vector<Id> stack;-    IdSet seen;-    for (const auto& id : start) {-        if (stop.find(id) == stop.end() && seen.insert(id).second)-            stack.push_back(id);-    }-    while (!stack.empty()) {-        const Id id = stack.back();-        stack.pop_back();-        out.push_back(id);-        auto loaded = load_commit(store, id);-        if (!loaded)-            continue;-        for (const auto& parent : loaded->commit.parents) {-            if (stop.find(parent) != stop.end())-                continue;-            if (seen.insert(parent).second)-                stack.push_back(parent);-        }-    }-    return out;-}--std::vector<Id> objects_for_commit_deltas(Store& store, const std::vector<Id>& commits,-                                          const std::function<void(std::size_t)>& progress = {}) {-    Walker walker{store, true};-    std::size_t done = 0;-    for (const auto& id : commits) {-        walker.add_object(id);-        auto loaded = load_commit(store, id);-        if (loaded) {-            std::optional<Id> old_tree;-            bool tree_covered = false;-            for (const auto& parent_id : loaded->commit.parents) {-                auto parent = load_commit(store, parent_id);-                if (!parent)-                    continue;-                if (same_id(parent->commit.root_tree, loaded->commit.root_tree)) {-                    tree_covered = true;-                    break;-                }-                if (!old_tree)-                    old_tree = parent->commit.root_tree;-            }-            if (!tree_covered)-                walker.walk_tree_delta(loaded->commit.root_tree, old_tree);-        }-        if (progress)-            progress(++done);-    }-    return std::move(walker.object_out);-}--/**- * Ask the server which objects it already has, so a push only transfers the difference.- * If a query fails, send everything to preserve correctness.- */-std::vector<Id> missing_objects(proto::Client& client, const std::vector<Id>& objects) {-    constexpr std::size_t BATCH = 100000;-    std::vector<Id> missing;-    missing.reserve(objects.size());-    for (std::size_t offset = 0; offset < objects.size(); offset += BATCH) {-        const std::size_t end = std::min(offset + BATCH, objects.size());-        std::vector<Id> batch(objects.begin() + static_cast<std::ptrdiff_t>(offset),-                              objects.begin() + static_cast<std::ptrdiff_t>(end));-        std::vector<std::uint8_t> bits;-        if (!client.have_query(batch, bits))-            return objects;-        for (std::size_t i = 0; i < batch.size(); ++i) {-            if (i >= bits.size() || bits[i] == 0)-                missing.push_back(batch[i]);-        }-    }-    return missing;-}--bool send_chunks(proto::Client& client, const fs::path& root, const std::vector<Id>& chunks) {-    constexpr std::size_t BATCH = 4096;-    for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {-        const std::size_t end = std::min(offset + BATCH, chunks.size());-        std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),-                              chunks.begin() + static_cast<std::ptrdiff_t>(end));-        if (!client.get_chunks(root, batch))-            return false;-    }-    return true;-}--bool send_missing_chunks(proto::Client& client, const fs::path& root,-                         const std::vector<Id>& chunks) {-    Store store = Store::open_all(root);-    std::vector<Id> missing;-    for (const auto& id : chunks) {-        if (!store.find(id))-            missing.push_back(id);-    }-    return send_chunks(client, root, missing);-}--std::optional<std::string> config_value(const fs::path& root, std::string_view key) {-    return repo_config_value(root, key);-}--std::vector<std::string> list_remote_names(const fs::path& root) {-    std::vector<std::string> out;-    auto data = read_file_opt(config_path(root));-    if (!data)-        return out;-    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::size_t start = 0;-    for (std::size_t i = 0; i <= text.size(); ++i) {-        if (i != text.size() && text[i] != '\n')-            continue;-        const std::string_view line = text.substr(start, i - start);-        if (starts_with(line, "remote.")) {-            const auto dot = line.find(".url", 7);-            if (dot != std::string_view::npos && dot > 7)-                out.emplace_back(line.substr(7, dot - 7));-        }-        start = i + 1;-    }-    return out;-}--std::string active_remote(const fs::path& root) {-    for (const char* key : {"remote.current", "remote.default"}) {-        if (auto name = config_value(root, key)) {-            if (!name->empty() && config_value(root, remote_key(*name, "url")))-                return *name;-        }-    }-    if (config_value(root, remote_key("o", "url")))-        return "o";-    const auto names = list_remote_names(root);-    if (!names.empty())-        return names.front();-    return "o";-}--std::string role_text(std::uint8_t role) {-    if (role == 2)-        return "write";-    if (role == 1)-        return "read";-    return "anonymous";-}--void print_key(const auth::Key& key) {-    std::cout << "name: " << key.name << "\n";-    std::cout << "public key: " << format_public_key(key.public_key) << "\n";-    std::cout << "fingerprint: " << key.fingerprint << "\n";-}--void auth_usage() {-    std::cout << "usage: vn auth <use|list|remove> ...\n";-    std::cout << "  vn auth use <key> [<host|url>]   set the default or host key\n";-    std::cout << "  vn auth list                     show stored key mappings\n";-    std::cout << "  vn auth remove [<host|url>]      remove a mapping (default if "-                 "omitted)\n";-}--std::optional<PublicKey> read_public_key(std::string_view arg) {-    if (starts_with(arg, "ed25519:"))-        return parse_public_key(arg);-    auto data = read_file_opt(path_from_bytes(arg));-    if (!data)-        return std::nullopt;-    const std::string text =-        trim_text(std::string_view(reinterpret_cast<const char*>(data->data()), data->size()));-    return parse_public_key(text);-}--} // namespace--int remote_run(const std::vector<std::string>& args) {-    const std::string sub = arg_at(args, 2);-    if (sub.empty()) {-        error_prefix();-        std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";-        return 1;-    }-    auto repo = discover_repo(".");-    if (!repo) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const fs::path root = *repo;--    if (sub == "add" || sub == "set-url") {-        const bool replace = sub == "set-url";-        std::string name;-        std::string url;-        std::optional<std::string> key;-        std::optional<std::string> pin;-        for (std::size_t i = 3; i < args.size(); ++i) {-            const std::string& arg = args[i];-            if (starts_with(arg, "-key:")) {-                key = arg.substr(5);-            } else if (starts_with(arg, "-pin:")) {-                pin = arg.substr(5);-            } else if (is_flag(arg)) {-                error_prefix();-                std::cout << "unknown flag: " << arg << "\n";-                return 1;-            } else if (name.empty()) {-                name = arg;-            } else if (url.empty()) {-                url = arg;-            } else {-                error_prefix();-                std::cout << "too many arguments\n";-                return 1;-            }-        }-        if (name.empty() || url.empty()) {-            error_prefix();-            std::cout << (replace ? "remote set-url requires a name and URL\n"-                                  : "remote add requires a name and URL\n");-            return 1;-        }-        const std::string url_key = remote_key(name, "url");-        const auto existing = config_value(root, url_key);-        if (existing && !replace) {-            error_prefix();-            std::cout << "remote already exists: " << name << "\n";-            return 1;-        }-        if (!existing && replace) {-            error_prefix();-            std::cout << "unknown remote: " << name << "\n";-            return 1;-        }-        if (!repo_config_set(root, url_key, url)) {-            error_prefix();-            std::cout << "cannot write repository config\n";-            return 1;-        }-        if (key) {-            const std::string field = remote_key(name, "key");-            const bool ok =-                key->empty() ? repo_config_remove(root, field) : repo_config_set(root, field, *key);-            if (!ok) {-                error_prefix();-                std::cout << "cannot write repository config\n";-                return 1;-            }-        }-        if (pin) {-            const std::string field = remote_key(name, "tls-pin");-            const bool ok =-                pin->empty() ? repo_config_remove(root, field) : repo_config_set(root, field, *pin);-            if (!ok) {-                error_prefix();-                std::cout << "cannot write repository config\n";-                return 1;-            }-        }-        return 0;-    }--    if (sub == "list" || sub == "ls") {-        for (const auto& name : list_remote_names(root)) {-            const auto url = config_value(root, remote_key(name, "url"));-            std::cout << name << "\t" << (url ? *url : std::string()) << "\n";-        }-        return 0;-    }--    if (sub == "remove" || sub == "rm") {-        const std::string name = arg_at(args, 3);-        if (name.empty()) {-            error_prefix();-            std::cout << "remote remove requires a name\n";-            return 1;-        }-        if (!config_value(root, remote_key(name, "url"))) {-            error_prefix();-            std::cout << "unknown remote: " << name << "\n";-            return 1;-        }-        (void)repo_config_remove(root, remote_key(name, "url"));-        (void)repo_config_remove(root, remote_key(name, "key"));-        (void)repo_config_remove(root, remote_key(name, "tls-pin"));-        return 0;-    }--    error_prefix();-    std::cout << "unknown remote subcommand: " << sub << "\n";-    return 1;-}--int clone_run(const std::vector<std::string>& args) {-    std::string url;-    std::string path;-    std::string policy = "head";-    std::string key_name;-    bool key_explicit = false;-    std::string tls_pin;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (starts_with(arg, "-blobs:")) {-            policy = arg.substr(7);-        } else if (starts_with(arg, "-key:")) {-            key_name = arg.substr(5);-            if (starts_with(key_name, "ed25519:")) {-                error_prefix();-                std::cout << "-key: expects a local key name, not a public key\n";-                return 1;-            }-            key_explicit = true;-        } else if (starts_with(arg, "-pin:")) {-            tls_pin = arg.substr(5);-        } else if (is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else if (url.empty()) {-            url = arg;-        } else {-            path = arg;-        }-    }-    if (url.empty()) {-        error_prefix();-        std::cout << "clone requires a URL\n";-        return 1;-    }-    const auto parsed = proto::parse_url(url);-    if (!parsed) {-        error_prefix();-        std::cout << "unsupported URL\n";-        return 1;-    }-    if (path.empty())-        path = last_segment(parsed->path);-    const fs::path destination = path_from_bytes(path);-    if (path_exists(destination)) {-        if (!path_is_dir(destination)) {-            error_prefix();-            std::cout << "destination already exists and is not a directory: " << path << "\n";-            return 1;-        }-        if (!list_directory(destination).empty()) {-            error_prefix();-            std::cout << "destination directory is not empty: " << path << "\n";-            return 1;-        }-    }-    auto repo = init_repo(destination);-    if (!repo) {-        error_prefix();-        std::cout << "cannot create repository\n";-        return 1;-    }-    const fs::path root = *repo;--    if (key_name.empty()) {-        if (auto fallback = auth::key_for_url(url))-            key_name = *fallback;-    }-    (void)repo_config_set(root, remote_key("o", "url"), url);-    if (key_explicit && !key_name.empty())-        (void)repo_config_set(root, remote_key("o", "key"), key_name);-    if (!tls_pin.empty())-        (void)repo_config_set(root, remote_key("o", "tls-pin"), tls_pin);-    (void)repo_config_set(root, "remote.default", "o");--    const std::string repo_name = proto::url_repo_name(url);-    auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);-    if (!client) {-        report_connect_failure("cannot connect or authenticate");-        return 1;-    }-    std::vector<proto::RefInfo> refs;-    if (!client->list_refs(refs)) {-        report_client_error(*client, "cannot list remote refs");-        return 1;-    }-    std::vector<Id> wants;-    for (const auto& ref : refs)-        wants.push_back(ref.target);-    if (wants.empty()) {-        info_prefix();-        std::cout << "cloned empty repository into " << path << "\n";-        return 0;-    }-    if (!client->negotiate(wants, {})) {-        report_client_error(*client, "negotiation failed");-        return 1;-    }-    if (!client->fetch_skeleton(root, wants)) {-        report_client_error(*client, "fetch failed");-        return 1;-    }-    {-        Store store = Store::open_all(root);-        const auto commits = selected_commits(refs, policy);-        const auto chunks = chunks_for_commits(store, commits);-        if (!send_chunks(*client, root, chunks)) {-            report_client_error(*client, "chunk fetch failed");-            return 1;-        }-    }-    if (!apply_refs(root, refs, "o", true)) {-        error_prefix();-        std::cout << "cannot write repository state\n";-        return 1;-    }-    (void)repo_config_set(root, "promisor", "o");-    install_promisor_fetcher();-    if (policy == "none") {-        info_prefix();-        std::cout << "cloned metadata only; blobs are promised\n";-    }--    int checkout_status = 1;-    {-        Store store = Store::open_all(root);-        auto view = current_view(root, store);-        if (view) {-            if (auto wc = working_copy_id(*view)) {-                auto body = store.read_body(*wc, TYPE_COMMIT);-                if (body) {-                    auto commit = decode_commit(bytes_of(*body));-                    if (commit) {-                        checkout_status = checkout_materialize_commit(root, store, std::nullopt,-                                                                      commit->root_tree);-                    }-                }-            }-        }-    }-    if (checkout_status != 0) {-        info_prefix();-        std::cout << "cloned; checkout reported " << checkout_status << "\n";-    }-    info_prefix();-    std::cout << "cloned into " << path << "\n";-    return 0;-}--struct FetchOptions {-    std::string remote_name;-    std::string path = ".";-    std::string explicit_key;-    std::string explicit_pin;-    bool have_remote = false;-};--bool parse_fetch_options(const std::vector<std::string>& args, FetchOptions& options) {-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (starts_with(arg, "-key:")) {-            options.explicit_key = arg.substr(5);-            if (starts_with(options.explicit_key, "ed25519:")) {-                error_prefix();-                std::cout << "-key: expects a local key name, not a public key\n";-                return false;-            }-        } else if (starts_with(arg, "-pin:")) {-            options.explicit_pin = arg.substr(5);-        } else if (is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return false;-        } else if (!options.have_remote) {-            options.remote_name = arg;-            options.have_remote = true;-        } else {-            options.path = arg;-        }-    }-    return true;-}--int fetch_command(FetchOptions& options) {-    auto repo = discover_repo(path_from_bytes(options.path));-    if (!repo) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const fs::path root = *repo;-    if (!options.have_remote)-        options.remote_name = active_remote(root);-    auto url = config_value(root, remote_key(options.remote_name, "url"));-    if (!url) {-        error_prefix();-        std::cout << "unknown remote\n";-        return 1;-    }-    std::string key;-    if (!options.explicit_key.empty()) {-        key = options.explicit_key;-    } else {-        auto configured = config_value(root, remote_key(options.remote_name, "key"));-        if (configured && auth::local_key_exists(*configured))-            key = *configured;-        if (key.empty()) {-            if (auto fallback = auth::key_for_url(*url))-                key = *fallback;-        }-    }-    std::string pin;-    if (!options.explicit_pin.empty()) {-        pin = options.explicit_pin;-    } else if (auto configured = config_value(root, remote_key(options.remote_name, "tls-pin"))) {-        pin = *configured;-    }-    const std::string repo_name = proto::url_repo_name(*url);-    auto client = proto::Client::connect(*url, key, repo_name, pin);-    if (!client) {-        report_connect_failure("cannot connect or authenticate");-        return 1;-    }-    std::vector<proto::RefInfo> refs;-    if (!client->list_refs(refs)) {-        report_client_error(*client, "cannot list remote refs");-        return 1;-    }-    std::vector<Id> haves = read_heads(root);-    std::vector<Id> wants;-    for (const auto& ref : refs)-        wants.push_back(ref.target);-    if (wants.empty()) {-        info_prefix();-        std::cout << "no refs to fetch\n";-        return 0;-    }-    if (!client->negotiate(wants, haves)) {-        report_client_error(*client, "negotiation failed");-        return 1;-    }-    if (!client->fetch_skeleton(root, wants)) {-        report_client_error(*client, "fetch failed");-        return 1;-    }-    {-        Store store = Store::open_all(root);-        const auto chunks = chunks_for_commits(store, wants);-        if (!send_missing_chunks(*client, root, chunks)) {-            report_client_error(*client, "chunk fetch failed");-            return 1;-        }-    }-    if (!apply_refs(root, refs, options.remote_name, false)) {-        error_prefix();-        std::cout << "cannot write repository state\n";-        return 1;-    }-    info_prefix();-    std::cout << "fetched from " << options.remote_name << "\n";-    return 0;-}--int fetch_run(const std::vector<std::string>& args) {-    FetchOptions options;-    if (!parse_fetch_options(args, options))-        return 1;-    return fetch_command(options);-}--bool commit_is_ancestor(Store& store, const Id& ancestor, const Id& descendant) {-    if (same_id(ancestor, descendant))-        return true;-    const std::vector<Id> commits = collect_commits(store, std::vector<Id>{descendant});-    for (const auto& id : commits) {-        if (same_id(ancestor, id))-            return true;-    }-    return false;-}--int pull_run(const std::vector<std::string>& args) {-    FetchOptions options;-    if (!parse_fetch_options(args, options))-        return 1;-    if (fetch_command(options) != 0)-        return 1;--    auto repo = discover_repo(path_from_bytes(options.path));-    if (!repo) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const fs::path root = *repo;-    Store store = Store::open_all(root);-    const int snap = snapshot_run(root, store);-    if (snap != 0)-        return snap;--    auto bookmark_name = current_bookmark_name(root);-    if (!bookmark_name) {-        error_prefix();-        std::cout << "no current bookmark; check out a bookmark before pulling\n";-        return 1;-    }-    auto view = current_view(root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    const auto index = find_bookmark(*view, *bookmark_name);-    if (!index) {-        error_prefix();-        std::cout << "current bookmark is missing: " << *bookmark_name << "\n";-        return 1;-    }-    const auto& bookmark = view->bookmarks[*index];-    if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front()) {-        error_prefix();-        std::cout << "current bookmark is conflicted: " << *bookmark_name << "\n";-        return 1;-    }-    const Id local_target = *bookmark.targets.adds.front();--    std::optional<Id> remote_target;-    for (const auto& ref : view->remote_refs) {-        if (ref.remote == options.remote_name && ref.name == *bookmark_name) {-            remote_target = ref.target;-            break;-        }-    }-    const std::string remote_ref = options.remote_name + "/" + *bookmark_name;-    if (!remote_target) {-        error_prefix();-        std::cout << "no " << remote_ref << " on remote " << options.remote_name << "\n";-        return 1;-    }--    if (auto wc = working_copy_id(*view)) {-        auto loaded = load_commit(store, *wc);-        if (!loaded) {-            error_prefix();-            std::cout << "cannot read working-copy commit\n";-            return 1;-        }-        if (tree_conflicted(store, loaded->commit.root_tree)) {-            error_prefix();-            std::cout << "working copy has unresolved conflicts\n";-            return 1;-        }-        if (has_changes(store, *loaded)) {-            error_prefix();-            std::cout << "working copy has uncommitted changes; commit them before pulling\n";-            return 1;-        }-    }--    if (same_id(local_target, *remote_target)) {-        info_prefix();-        std::cout << "already up to date with " << remote_ref << "\n";-        return checkout_run(root, *bookmark_name);-    }-    if (!commit_is_ancestor(store, local_target, *remote_target)) {-        if (commit_is_ancestor(store, *remote_target, local_target)) {-            info_prefix();-            std::cout << "local " << *bookmark_name << " is ahead of " << remote_ref << "\n";-            return 0;-        }-        error_prefix();-        std::cout << "local " << *bookmark_name << " and " << remote_ref-                  << " have diverged; use 'vn merge " << remote_ref << "' or 'vn rebase'\n";-        return 1;-    }--    auto tx = Txn::begin(root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    set_bookmark_target(tx->view(), *bookmark_name, *remote_target);-    rebuild_heads(tx->view());-    const auto status = tx->finish("pull " + *bookmark_name + " from " + options.remote_name);-    if (!status) {-        error_prefix();-        std::cout << "cannot write repository state\n";-        return 1;-    }-    store.refresh(root);--    const int checkout = checkout_run(root, *bookmark_name);-    if (checkout != 0)-        return checkout;-    info_prefix();-    std::cout << "pulled " << *bookmark_name << " from " << options.remote_name << "\n";-    return 0;-}--int gg_run(const std::vector<std::string>& args) {-    std::string first;-    for (std::size_t i = 2; i < args.size(); ++i) {-        if (!is_flag(args[i])) {-            first = args[i];-            break;-        }-    }-    const bool is_url = first.find("://") != std::string::npos;-    if (!first.empty() && is_url)-        return clone_run(args);--    auto repo = discover_repo(".");-    if (!repo) {-        if (!first.empty())-            return clone_run(args);-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }--    std::vector<std::string> forwarded = args;-    if (first.empty()) {-        forwarded.push_back(active_remote(*repo));-    } else {-        const auto names = list_remote_names(*repo);-        if (std::find(names.begin(), names.end(), first) == names.end()) {-            error_prefix();-            std::cout << "unknown remote: " << first << "\n";-            return 1;-        }-    }-    return fetch_run(forwarded);-}--int push_run(const std::vector<std::string>& args) {-    std::string remote_name;-    std::string bookmark;-    std::string explicit_key;-    std::string explicit_pin;-    std::string path = ".";-    bool have_remote = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (starts_with(arg, "-key:")) {-            explicit_key = arg.substr(5);-            if (starts_with(explicit_key, "ed25519:")) {-                error_prefix();-                std::cout << "-key: expects a local key name, not a public key\n";-                return 1;-            }-        } else if (starts_with(arg, "-pin:")) {-            explicit_pin = arg.substr(5);-        } else if (is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else if (!have_remote) {-            remote_name = arg;-            have_remote = true;-        } else if (bookmark.empty()) {-            bookmark = arg;-        } else {-            path = arg;-        }-    }-    auto repo = discover_repo(path_from_bytes(path));-    if (!repo) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const fs::path root = *repo;-    if (!have_remote)-        remote_name = active_remote(root);-    if (bookmark.empty()) {-        if (auto current = current_bookmark_name(root))-            bookmark = *current;-    }-    if (bookmark.empty()) {-        error_prefix();-        std::cout << "push requires a bookmark name (or a current bookmark)\n";-        return 1;-    }-    auto url = config_value(root, remote_key(remote_name, "url"));-    if (!url) {-        error_prefix();-        std::cout << "unknown remote\n";-        return 1;-    }-    std::string key;-    if (!explicit_key.empty()) {-        key = explicit_key;-    } else {-        auto configured = config_value(root, remote_key(remote_name, "key"));-        if (configured && auth::local_key_exists(*configured))-            key = *configured;-        if (key.empty()) {-            if (auto fallback = auth::key_for_url(*url))-                key = *fallback;-        }-    }-    std::string pin;-    if (!explicit_pin.empty()) {-        pin = explicit_pin;-    } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {-        pin = *configured;-    }--    std::optional<Id> target;-    std::vector<std::pair<std::string, Id>> tags;-    Store store = Store::open_all(root);-    {-        auto view = current_view(root, store);-        View empty;-        const View& current = view ? *view : empty;-        const auto bookmark_index = find_bookmark(current, bookmark);-        if (!bookmark_index) {-            error_prefix();-            std::cout << "unknown bookmark: " << bookmark << "\n";-            return 1;-        }-        const auto& bookmark_targets = current.bookmarks[*bookmark_index].targets;-        if (bookmark_targets.adds.size() != 1 || !bookmark_targets.adds.front()) {-            error_prefix();-            std::cout << "bookmark is conflicted: " << bookmark << "\n";-            return 1;-        }-        target = bookmark_targets.adds.front();-        for (const auto& tag : current.tags)-            tags.emplace_back(tag.name, tag.target);-    }-    const std::string repo_name = proto::url_repo_name(*url);-    auto client = proto::Client::connect(*url, key, repo_name, pin);-    if (!client) {-        report_connect_failure("cannot connect or authenticate");-        return 1;-    }-    std::vector<proto::RefInfo> refs;-    if (!client->list_refs(refs)) {-        report_client_error(*client, "cannot list remote refs");-        return 1;-    }-    std::optional<Id> old;-    for (const auto& ref : refs) {-        if (ref.kind == 0 && ref.name == bookmark)-            old = ref.target;-    }-    std::vector<proto::UpdateRef> updates;-    if (!old || !same_id(*old, *target))-        updates.push_back(proto::UpdateRef{bookmark, old, target});-    std::size_t tag_updates = 0;-    for (const auto& [name, tag_target] : tags) {-        std::optional<Id> tag_old;-        for (const auto& ref : refs) {-            if (ref.kind == 1 && ref.name == name) {-                tag_old = ref.target;-                break;-            }-        }-        if (tag_old && same_id(*tag_old, tag_target))-            continue;-        updates.push_back(proto::UpdateRef{"refs/tags/" + name, tag_old, tag_target});-        ++tag_updates;-    }-    if (updates.empty()) {-        info_prefix();-        std::cout << "nothing to push, everything is up to date\n";-        return 0;-    }-    IdSet remote_commits;-    remote_commits.reserve(refs.size());-    for (const auto& ref : refs)-        remote_commits.insert(ref.target);--    std::vector<Id> roots{*target};-    for (const auto& tag : tags)-        roots.push_back(tag.second);-    const std::vector<Id> commits = collect_commits_until(store, roots, remote_commits);-    std::vector<Id> objects;-    if (!commits.empty()) {-        Progress progress("collecting objects", commits.size());-        objects = objects_for_commit_deltas(store, commits,-                                            [&](std::size_t done) { progress.update(done); });-        progress.finish();-    }-    bool pushed = true;-    if (!objects.empty()) {-        const std::vector<Id> missing = missing_objects(*client, objects);-        if (!missing.empty()) {-            Progress progress("pushing objects", missing.size());-            pushed = client->push_objects(root, missing,-                                          [&](std::size_t done) { progress.update(done); });-            if (pushed)-                progress.finish();-        }-    }-    if (!pushed) {-        report_client_error(*client, "push failed");-        return 1;-    }-    if (!client->update_refs(updates)) {-        report_client_error(*client, "ref update rejected");-        return 1;-    }-    info_prefix();-    std::cout << "pushed " << bookmark << " to " << remote_name << "\n";-    if (tag_updates > 0)-        std::cout << "pushed " << tag_updates << " tag(s)\n";-    return 0;-}--int serve_run(const std::vector<std::string>& args) {-    bool stdio_mode = false;-    std::string listen;-    std::string root = ".";-    std::string cert;-    std::string key;-    std::string repo_path = ".";-    std::uint64_t quota_bytes = 0;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (arg == "-stdio") {-            stdio_mode = true;-            if (i + 1 < args.size())-                repo_path = args[++i];-        } else if (arg == "-listen") {-            if (i + 1 < args.size())-                listen = args[++i];-        } else if (arg == "-root") {-            if (i + 1 < args.size())-                root = args[++i];-        } else if (arg == "-tls-cert") {-            if (i + 1 < args.size())-                cert = args[++i];-        } else if (arg == "-tls-key") {-            if (i + 1 < args.size())-                key = args[++i];-        } else if (arg == "-quota") {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << "-quota requires a byte count\n";-                return 1;-            }-            const std::string& value = args[++i];-            std::uint64_t parsed = 0;-            const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);-            if (result.ec != std::errc() || result.ptr != value.data() + value.size()) {-                error_prefix();-                std::cout << "-quota requires a byte count\n";-                return 1;-            }-            quota_bytes = parsed;-        } else {-            error_prefix();-            std::cout << "unknown serve option: " << arg << "\n";-            return 1;-        }-    }-    if (stdio_mode) {-        auto repo = discover_repo(path_from_bytes(repo_path));-        if (!repo) {-            error_prefix();-            std::cout << "not a veins repository\n";-            return 1;-        }-        return server::serve_stdio(*repo, quota_bytes);-    }-    if (listen.empty()) {-        error_prefix();-        std::cout << "serve requires -stdio or -listen\n";-        return 1;-    }-    if (cert.empty() || key.empty()) {-        error_prefix();-        std::cout << "TLS requires -tls-cert and -tls-key\n";-        return 1;-    }-    return server::serve_listen(listen, path_from_bytes(root), cert, key, quota_bytes);-}--int key_run(const std::vector<std::string>& args) {-    const std::string sub = arg_at(args, 2);-    if (sub.empty()) {-        error_prefix();-        std::cout << "expected key subcommand (generate, list, show, import)\n";-        return 1;-    }-    if (sub == "generate") {-        const std::string name = arg_at(args, 3);-        if (name.empty()) {-            error_prefix();-            std::cout << "key generate requires a name\n";-            return 1;-        }-        auto key = auth::generate_key(name);-        if (!key) {-            error_prefix();-            std::cout << "cannot create key\n";-            return 1;-        }-        print_key(*key);-        return 0;-    }-    if (sub == "list") {-        for (const auto& name : auth::list_key_names()) {-            if (auto key = auth::load_key(name))-                print_key(*key);-        }-        return 0;-    }-    if (sub == "show") {-        const std::string name = arg_at(args, 3);-        if (name.empty()) {-            error_prefix();-            std::cout << "key show requires a name\n";-            return 1;-        }-        auto key = auth::load_key(name);-        if (!key) {-            error_prefix();-            std::cout << "key not found or has unsafe permissions\n";-            return 1;-        }-        print_key(*key);-        return 0;-    }-    if (sub == "import") {-        error_prefix();-        std::cout << "OpenSSH key import is not supported\n";-        return 1;-    }-    error_prefix();-    std::cout << "unknown key subcommand: " << sub << "\n";-    return 1;-}--int auth_run(const std::vector<std::string>& args) {-    const std::string sub = arg_at(args, 2);-    if (sub.empty()) {-        auth_usage();-        return 1;-    }-    if (sub == "use") {-        const std::string name = arg_at(args, 3);-        if (name.empty()) {-            auth_usage();-            return 1;-        }-        if (!auth::load_key(name)) {-            error_prefix();-            std::cout << "key not found or has unsafe permissions: " << name << "\n";-            return 1;-        }-        const std::string target = auth::normalize_target(arg_at(args, 4));-        if (!auth::set_key(target, name)) {-            error_prefix();-            std::cout << "cannot write auth configuration\n";-            return 1;-        }-        if (target == "default")-            std::cout << "default key set to " << name << "\n";-        else-            std::cout << "key for " << target << " set to " << name << "\n";-        return 0;-    }-    if (sub == "list") {-        const auto lines = auth::list_credential_lines();-        if (lines.empty())-            std::cout << "no stored credentials\n";-        for (const auto& line : lines)-            std::cout << line;-        return 0;-    }-    if (sub == "remove") {-        const std::string target = auth::normalize_target(arg_at(args, 3));-        if (auth::remove_key(target)) {-            std::cout << "removed " << target << "\n";-            return 0;-        }-        error_prefix();-        std::cout << "no credential for " << target << "\n";-        return 1;-    }-    error_prefix();-    std::cout << "unknown auth subcommand: " << sub << "\n";-    auth_usage();-    return 1;-}--int access_run(const std::vector<std::string>& args) {-    const std::string sub = arg_at(args, 2);-    if (sub.empty()) {-        error_prefix();-        std::cout << "expected access subcommand\n";-        return 1;-    }-    auto repo = discover_repo(".");-    if (!repo) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const fs::path root = *repo;-    if (sub == "add") {-        std::string role;-        std::string key_arg;-        std::string name;-        for (std::size_t i = 3; i < args.size(); ++i) {-            const std::string& arg = args[i];-            if (arg == "-role" && i + 1 < args.size()) {-                role = args[++i];-            } else if (arg == "-key" && i + 1 < args.size()) {-                key_arg = args[++i];-            } else if (arg == "-name" && i + 1 < args.size()) {-                name = args[++i];-            } else {-                error_prefix();-                std::cout << "unknown access add option: " << arg << "\n";-                return 1;-            }-        }-        if (role.empty() || key_arg.empty()) {-            error_prefix();-            std::cout << "access add requires -role and -key\n";-            return 1;-        }-        std::uint8_t role_code = auth::ROLE_READ;-        if (role == "write") {-            role_code = auth::ROLE_WRITE;-        } else if (role != "read") {-            error_prefix();-            std::cout << "role must be read or write\n";-            return 1;-        }-        auto public_key = read_public_key(key_arg);-        if (!public_key) {-            error_prefix();-            std::cout << "invalid public key\n";-            return 1;-        }-        if (!auth::add_access(root, role_code, *public_key, name)) {-            error_prefix();-            std::cout << "cannot add key\n";-            return 1;-        }-        info_prefix();-        std::cout << "access granted\n";-        return 0;-    }-    if (sub == "list") {-        const auth::Access access = auth::load_access(root);-        if (!access.valid) {-            error_prefix();-            std::cout << "invalid access file at line " << access.error_line << "\n";-            return 1;-        }-        std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off") << "\n";-        for (const auto& entry : access.entries) {-            std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "-                      << key_fingerprint(entry.public_key) << " " << entry.name << "\n";-        }-        return 0;-    }-    if (sub == "remove") {-        const std::string arg = arg_at(args, 3);-        if (arg.empty()) {-            error_prefix();-            std::cout << "access remove requires a fingerprint or name\n";-            return 1;-        }-        const bool is_fingerprint = arg.size() == 26;-        const std::string fingerprint = is_fingerprint ? arg : std::string();-        const std::string name = is_fingerprint ? std::string() : arg;-        if (!auth::remove_access(root, fingerprint, name)) {-            error_prefix();-            std::cout << "key not found or cannot write access file\n";-            return 1;-        }-        info_prefix();-        std::cout << "access removed\n";-        return 0;-    }-    if (sub == "anonymous") {-        const bool on = arg_at(args, 3) == "on";-        if (!auth::set_anonymous(root, on)) {-            error_prefix();-            std::cout << "cannot update access file\n";-            return 1;-        }-        return 0;-    }-    error_prefix();-    std::cout << "unknown access subcommand: " << sub << "\n";-    return 1;-}--int whoami_run(const std::vector<std::string>& args) {-    std::string remote;-    std::string url;-    std::string key;-    std::string repo_name;-    std::string pin;-    const std::string arg = arg_at(args, 2);-    if (!arg.empty()) {-        if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||-            starts_with(arg, "veins://")) {-            url = arg;-            repo_name = proto::url_repo_name(url);-        } else {-            remote = arg;-        }-    }-    if (url.empty()) {-        auto repo = discover_repo(".");-        if (!repo) {-            error_prefix();-            std::cout << "not a veins repository\n";-            return 1;-        }-        const fs::path root = *repo;-        if (remote.empty())-            remote = active_remote(root);-        auto configured = config_value(root, remote_key(remote, "url"));-        if (!configured) {-            error_prefix();-            std::cout << "unknown remote\n";-            return 1;-        }-        url = *configured;-        if (auto k = config_value(root, remote_key(remote, "key"))) {-            if (auth::local_key_exists(*k))-                key = *k;-        }-        if (auto p = config_value(root, remote_key(remote, "tls-pin")))-            pin = *p;-        repo_name = proto::url_repo_name(url);-    }-    if (key.empty()) {-        if (auto fallback = auth::key_for_url(url))-            key = *fallback;-    }-    auto client = proto::Client::connect(url, key, repo_name, pin);-    if (!client) {-        report_connect_failure("cannot authenticate");-        return 1;-    }-    std::uint8_t role = 0;-    std::string fingerprint;-    if (!client->whoami(role, fingerprint)) {-        error_prefix();-        std::cout << "cannot authenticate\n";-        return 1;-    }-    std::cout << "role: " << role_text(role) << "\n";-    std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";-    return 0;-}--bool net_help(std::string_view command) {-    if (command == "remote") {-        std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";-        std::cout << "manage native remotes stored in .veins/config\n\n";-        std::cout << "subcommands:\n";-        std::cout << "  add <name> <url> [-key:<name>] [-pin:<hash>]\n";-        std::cout << "                            add a remote\n";-        std::cout << "  set-url <name> <url> [-key:<name>] [-pin:<hash>]\n";-        std::cout << "                            change a remote URL (and "-                     "optionally key/pin)\n";-        std::cout << "  list                      list remotes\n";-        std::cout << "  remove <name>             remove a remote\n\n";-        std::cout << "an empty -key: or -pin: value clears that setting\n\n";-        std::cout << "examples:\n";-        std::cout << "  vn remote add o veins://127.0.0.1:7419/navid-m/veins2\n";-        std::cout << "  vn remote set-url o veins://example/repo -key:my-key\n";-        return true;-    }-    if (command == "clone") {-        std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "-                     "[-pin:<sha256>] [path]\n\n";-        std::cout << "clone a repository over file://, ssh://, or veins://\n\n";-        std::cout << "records the URL as remote 'o' and makes it the active remote\n";-        std::cout << "without -key, the key stored by 'vn auth use' is used when "-                     "available\n";-        return true;-    }-    if (command == "fetch") {-        std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";-        std::cout << "fetch new history and chunks from a configured native "-                     "remote\n\n";-        std::cout << "without <remote>, the active remote is used\n";-        std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";-        return true;-    }-    if (command == "pull" || command == "pl") {-        std::cout << "usage: vn pull [-key:<name>] [<remote>] [path]\n\n";-        std::cout << "fetch the active remote and fast-forward the current "-                     "bookmark\n\n";-        std::cout << "the working copy is checked out after a fast-forward\n";-        std::cout << "when local and remote history have diverged, use 'vn merge' "-                     "or 'vn rebase'\n";-        std::cout << "alias: pl\n";-        return true;-    }-    if (command == "gg") {-        std::cout << "usage: vn gg [<remote>] [path]\n";-        std::cout << "       vn gg <url> [path]\n\n";-        std::cout << "fetch the active remote, or clone when given a URL\n\n";-        std::cout << "the active remote is remote.current, then remote.default,\n";-        std::cout << "then o, then the first configured remote\n";-        return true;-    }-    if (command == "push" || command == "psh") {-        std::cout << "usage: vn push [-key:<name>] [<remote>] [<bookmark>] [path]\n\n";-        std::cout << "push a bookmark to a configured native remote\n\n";-        std::cout << "without <remote>, the active remote is used\n";-        std::cout << "without <bookmark>, the current bookmark is pushed\n";-        std::cout << "tags reachable from the pushed bookmark are pushed too\n";-        std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";-        return true;-    }-    if (command == "serve") {-        std::cout << "usage: vn serve -stdio <repo> [-quota <bytes>]\n";-        std::cout << "       vn serve -listen <addr:port> -root <dir> -tls-cert "-                     "<file> -tls-key <file> [-quota <bytes>]\n\n";-        std::cout << "run the native server over standard input/output or TLS 1.3\n";-        std::cout << "-quota limits stored pack and index bytes per top-level "-                     "namespace\n";-        return true;-    }-    if (command == "key") {-        std::cout << "usage: vn key <generate|list|show> [name]\n\n";-        std::cout << "manage local Ed25519 keys in the user key directory\n";-        return true;-    }-    if (command == "auth") {-        std::cout << "usage: vn auth <use|list|remove> ...\n\n";-        std::cout << "remember which key clone/fetch/push should use\n\n";-        std::cout << "  vn auth use <key> [<host|url>]   set the default or host "-                     "key\n";-        std::cout << "  vn auth list                     show stored key mappings\n";-        std::cout << "  vn auth remove [<host|url>]      remove a mapping\n";-        return true;-    }-    if (command == "access") {-        std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";-        std::cout << "manage a served repository's .veins/access policy\n";-        return true;-    }-    if (command == "whoami") {-        std::cout << "usage: vn whoami [<remote>|<url>]\n\n";-        std::cout << "connect to a server and report the granted role and key "-                     "fingerprint\n";-        return true;-    }-    return false;-}--} // namespace vn--- a/xveins/src/cli/net_commands.h+++ /dev/null@@ -1,25 +0,0 @@-#pragma once--#include <string>-#include <string_view>-#include <vector>--namespace vn {--int remote_run(const std::vector<std::string>& args);-int clone_run(const std::vector<std::string>& args);-int fetch_run(const std::vector<std::string>& args);-int pull_run(const std::vector<std::string>& args);-int gg_run(const std::vector<std::string>& args);-int push_run(const std::vector<std::string>& args);-int serve_run(const std::vector<std::string>& args);-int key_run(const std::vector<std::string>& args);-int auth_run(const std::vector<std::string>& args);-int access_run(const std::vector<std::string>& args);-int whoami_run(const std::vector<std::string>& args);--// Print help for a network command. Returns false when `command` is not one of-// them.-bool net_help(std::string_view command);--} // namespace vn--- a/xveins/src/config/cfg.cpp+++ /dev/null@@ -1,258 +0,0 @@-#include "cli/local_commands.h"-#include "store/store.h"--#include <algorithm>-#include <iostream>-#include <map>-#include <optional>-#include <string>-#include <vector>--namespace vn {--namespace {--std::string_view cfg_trim(std::string_view text) {-    while (!text.empty() && (text.front() == ' ' || text.front() == '\t' || text.front() == '\r' ||-                             text.front() == '\n'))-        text.remove_prefix(1);-    while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' ||-                             text.back() == '\n'))-        text.remove_suffix(1);-    return text;-}--bool cfg_is_flag(std::string_view arg) {-    return !arg.empty() && arg.front() == '-';-}--std::map<std::string, std::string> repo_config_entries(const fs::path& root) {-    std::map<std::string, std::string> out;-    const auto data = read_file_opt(root / ".veins" / "config");-    if (!data)-        return out;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        const std::string_view line = cfg_trim(text.substr(start, end - start));-        if (!line.empty() && line.front() != '#') {-            const std::size_t eq = line.find('=');-            if (eq != std::string_view::npos) {-                const std::string_view key = cfg_trim(line.substr(0, eq));-                if (!key.empty())-                    out[std::string(key)] = std::string(cfg_trim(line.substr(eq + 1)));-            }-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-    return out;-}--void cfg_usage() {-    std::cout << "usage: vn cfg [<key>] [<value>]\n";-    std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";-    std::cout << "       vn cfg -list\n";-    std::cout << "       vn cfg -d [-i]\n";-    std::cout << "       vn cfg -unset <key>\n";-    std::cout << "\n";-    std::cout << "read and write local repository configuration\n";-    std::cout << "\n";-    std::cout << "  vn cfg                      list all keys\n";-    std::cout << "  vn cfg <key>                print a value\n";-    std::cout << "  vn cfg <key> <value>        set a value\n";-    std::cout << "  vn cfg -d                   show defaults and global values\n";-    std::cout << "  vn cfg -i -d                also show internal keys\n";-    std::cout << "  vn cfg -unset <key>         remove a key\n";-    std::cout << "  vn cfg -global ...          use the user config instead\n";-    std::cout << "\nthe global editor command is read from 'editor' or 'core.editor'\n";-    std::cout << "  vn cfg -global editor \"code --wait\"\n";-}--int cfg_defaults(bool internal) {-#if defined(_WIN32)-    const std::string editor_default = "notepad";-    const std::string pager_default = "more";-#else-    const std::string editor_default = "vi";-    const std::string pager_default = "less -R";-#endif-    std::map<std::string, std::string> defaults = {-        {"core.editor", "(unset)"},       {"core.pager", "(unset)"},    {"editor", editor_default},-        {"log.default_amount", "20"},     {"merge.adjacent", "strict"}, {"pager", pager_default},-        {"rename.autodetect", "similar"}, {"user.email", "(unset)"},    {"user.name", "(unset)"},-    };-    if (internal) {-        defaults["bookmark.current"] = "(unset)";-        defaults["promisor"] = "(unset)";-        defaults["remote.<name>.key"] = "(unset)";-        defaults["remote.<name>.tls-pin"] = "(unset)";-        defaults["remote.<name>.url"] = "(unset)";-        defaults["remote.current"] = "(unset)";-        defaults["remote.default"] = "(unset)";-    }-    for (const auto& entry : defaults) {-        std::cout << entry.first << " = " << entry.second;-        if (auto current = user_config_value(entry.first))-            std::cout << " (current: " << *current << ")";-        std::cout << "\n";-    }-    return 0;-}--int cfg_list(const fs::path* root, bool global) {-    std::map<std::string, std::string> entries;-    if (global) {-        entries = user_config_entries();-    } else {-        entries = repo_config_entries(*root);-    }-    for (const auto& entry : entries)-        std::cout << entry.first << " = " << entry.second << "\n";-    return 0;-}--int cfg_get(const fs::path* root, bool global, const std::string& key) {-    std::optional<std::string> value;-    if (global) {-        value = user_config_value(key);-    } else {-        value = repo_config_value(*root, key);-    }-    if (!value) {-        error_prefix();-        std::cout << "unknown config key: " << key << "\n";-        return 1;-    }-    std::cout << *value << "\n";-    return 0;-}--int cfg_set(const fs::path* root, bool global, const std::string& key, const std::string& value) {-    const bool ok = global ? user_config_set(key, value) : repo_config_set(*root, key, value);-    if (!ok) {-        error_prefix();-        std::cout << "cannot write " << (global ? "user" : "repository") << " config\n";-        return 1;-    }-    return 0;-}--int cfg_unset(const fs::path* root, bool global, const std::string& key) {-    const bool ok = global ? user_config_remove(key) : repo_config_remove(*root, key);-    if (!ok) {-        error_prefix();-        std::cout << "cannot write " << (global ? "user" : "repository") << " config\n";-        return 1;-    }-    return 0;-}--} // namespace--int cfg_run(const std::vector<std::string>& args) {-    if (args.size() == 3 && (args[2] == "help" || args[2] == "-h" || args[2] == "-help")) {-        cfg_usage();-        return 0;-    }-    bool global = false;-    bool list = false;-    bool unset = false;-    bool show_defaults = false;-    bool internal = false;-    bool end_flags = false;-    std::vector<std::string> positional;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-global" || arg == "-g")) {-            global = true;-        } else if (!end_flags && (arg == "-list" || arg == "-l")) {-            list = true;-        } else if (!end_flags && (arg == "-unset")) {-            unset = true;-        } else if (!end_flags && (arg == "-d" || arg == "-defaults")) {-            show_defaults = true;-        } else if (!end_flags && (arg == "-i" || arg == "-internal")) {-            internal = true;-        } else if (!end_flags && cfg_is_flag(arg)) {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            positional.push_back(arg);-        }-    }--    if (show_defaults) {-        if (list || unset || !positional.empty()) {-            error_prefix();-            std::cout << "cfg -d takes no operands\n";-            return 1;-        }-        return cfg_defaults(internal);-    }-    if (internal) {-        error_prefix();-        std::cout << "cfg -i requires -d\n";-        return 1;-    }--    if (positional.size() == 1 && (positional[0] == "list" || positional[0] == "ls")) {-        list = true;-        positional.clear();-    } else if (positional.size() == 2 && positional[0] == "get") {-        positional.erase(positional.begin());-    } else if (positional.size() == 3 && positional[0] == "set") {-        positional.erase(positional.begin());-    } else if (positional.size() == 2 &&-               (positional[0] == "unset" || positional[0] == "rm" || positional[0] == "remove")) {-        unset = true;-        positional.erase(positional.begin());-    }--    if (list) {-        if (!positional.empty()) {-            error_prefix();-            std::cout << "cfg list takes no operands\n";-            return 1;-        }-    } else if (unset) {-        if (positional.size() != 1) {-            error_prefix();-            std::cout << "cfg unset requires one key\n";-            return 1;-        }-    } else if (positional.size() > 2) {-        error_prefix();-        std::cout << "cfg accepts a key and one value\n";-        return 1;-    }--    std::optional<fs::path> root;-    if (!global) {-        root = discover_repo(".");-        if (!root) {-            error_prefix();-            std::cout << "not a veins repository\n";-            return 1;-        }-    }--    if (list)-        return cfg_list(root ? &*root : nullptr, global);-    if (unset)-        return cfg_unset(root ? &*root : nullptr, global, positional[0]);-    if (positional.empty())-        return cfg_list(root ? &*root : nullptr, global);-    if (positional.size() == 1)-        return cfg_get(root ? &*root : nullptr, global, positional[0]);-    return cfg_set(root ? &*root : nullptr, global, positional[0], positional[1]);-}--} // namespace vn--- a/xveins/src/core/common.cpp+++ /dev/null@@ -1,2105 +0,0 @@-#include "core/common.h"--#include <algorithm>-#include <cerrno>-#include <cstdlib>-#include <ctime>-#include <fstream>-#include <iostream>-#include <random>-#include <sstream>-#include <thread>--#if defined(_WIN32)-#include <bcrypt.h>-#include <fcntl.h>-#include <io.h>-#include <windows.h>-#else-#include <dirent.h>-#include <fcntl.h>-#include <sys/random.h>-#include <sys/stat.h>-#include <sys/types.h>-#include <unistd.h>-#if defined(__linux__)-#include <sched.h>-#endif-#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) ||   \-    defined(__DragonFly__)-#include <stdlib.h>-#endif-#endif--namespace vn {--std::string_view error_kind_name(ErrorKind kind) {-    switch (kind) {-    case ErrorKind::None:-        return "none";-    case ErrorKind::UnexpectedEnd:-        return "unexpected end of input";-    case ErrorKind::VarintOverflow:-        return "varint overflow";-    case ErrorKind::NonMinimalVarint:-        return "non-minimal varint";-    case ErrorKind::InvalidValue:-        return "invalid value";-    case ErrorKind::LimitExceeded:-        return "format limit exceeded";-    case ErrorKind::InvalidName:-        return "invalid name";-    case ErrorKind::Duplicate:-        return "duplicate entry";-    case ErrorKind::Unsorted:-        return "entries are not sorted";-    case ErrorKind::TrailingBytes:-        return "trailing bytes";-    case ErrorKind::UnsupportedVersion:-        return "unsupported format version";-    case ErrorKind::InvalidMagic:-        return "bad file magic";-    case ErrorKind::HashMismatch:-        return "hash mismatch";-    case ErrorKind::Corrupt:-        return "corrupt data";-    case ErrorKind::Io:-        return "I/O error";-    case ErrorKind::Usage:-        return "usage error";-    }-    return "unknown error";-}--Error Error::decode(ErrorKind kind, std::size_t offset) {-    return Error{kind, offset, std::string(error_kind_name(kind))};-}-Error Error::io(std::string message) {-    return Error{ErrorKind::Io, 0, std::move(message)};-}-Error Error::usage(std::string message) {-    return Error{ErrorKind::Usage, 0, std::move(message)};-}---static char hex_digit(std::uint8_t v) {-    return static_cast<char>(v < 10 ? '0' + v : 'a' + (v - 10));-}--std::string hex_encode(Bytes data) {-    std::string out(data.size() * 2, '0');-    for (std::size_t i = 0; i < data.size(); ++i) {-        out[i * 2] = hex_digit(static_cast<std::uint8_t>(data[i] >> 4));-        out[i * 2 + 1] = hex_digit(static_cast<std::uint8_t>(data[i] & 15));-    }-    return out;-}--std::string hex_encode(const Id& id) {-    return hex_encode(Bytes(id.data(), id.size()));-}--static int hex_value(char c) {-    if (c >= '0' && c <= '9')-        return c - '0';-    if (c >= 'a' && c <= 'f')-        return c - 'a' + 10;-    if (c >= 'A' && c <= 'F')-        return c - 'A' + 10;-    return -1;-}--bool hex_decode(std::string_view text, MutBytes out) {-    if (text.size() != out.size() * 2)-        return false;-    for (std::size_t i = 0; i < out.size(); ++i) {-        const int hi = hex_value(text[i * 2]);-        const int lo = hex_value(text[i * 2 + 1]);-        if (hi < 0 || lo < 0)-            return false;-        out[i] = static_cast<std::uint8_t>((hi << 4) | lo);-    }-    return true;-}--std::optional<Id> parse_id(std::string_view hex) {-    if (hex.size() != ID_LEN * 2)-        return std::nullopt;-    Id id{};-    if (!hex_decode(hex, MutBytes(id.data(), id.size())))-        return std::nullopt;-    return id;-}--std::string base32_encode(const ChangeId& id) {-    static constexpr char alphabet[] = "abcdefghijklmnopqrstuvwxyz234567";-    std::string out;-    out.reserve(26);-    std::uint64_t buffer = 0;-    std::size_t bits = 0;-    for (std::uint8_t c : id) {-        buffer = (buffer << 8) | c;-        bits += 8;-        while (bits >= 5) {-            const std::size_t shift = bits - 5;-            const std::size_t index = (buffer >> shift) & 31u;-            out.push_back(alphabet[index]);-            bits = shift;-        }-        if (bits == 0) {-            buffer = 0;-        } else {-            buffer &= (std::uint64_t{1} << bits) - 1;-        }-    }-    if (bits > 0) {-        out.push_back(alphabet[(buffer << (5 - bits)) & 31u]);-    }-    return out;-}--bool base32_prefix_matches(std::string_view full, std::string_view prefix) {-    if (prefix.empty() || prefix.size() > full.size())-        return false;-    for (std::size_t i = 0; i < prefix.size(); ++i) {-        char c = prefix[i];-        if (c >= 'A' && c <= 'Z')-            c = static_cast<char>(c + 32);-        if (full[i] != c)-            return false;-    }-    return true;-}---std::array<std::uint8_t, 32> blake3_hash(Bytes data) {-    std::array<std::uint8_t, 32> out{};-    blake3_hasher hasher;-    blake3_hasher_init(&hasher);-    if (!data.empty())-        blake3_hasher_update(&hasher, data.data(), data.size());-    blake3_hasher_finalize(&hasher, out.data(), out.size());-    return out;-}--Id object_id(std::uint8_t type_byte, Bytes body) {-    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', '1', 0};-    blake3_hasher hasher;-    blake3_hasher_init(&hasher);-    blake3_hasher_update(&hasher, prefix, sizeof(prefix));-    blake3_hasher_update(&hasher, &type_byte, 1);-    if (!body.empty())-        blake3_hasher_update(&hasher, body.data(), body.size());-    Id out{};-    blake3_hasher_finalize(&hasher, out.data(), out.size());-    return out;-}--static void os_random_bytes(MutBytes out) {-#if defined(_WIN32)-    if (BCryptGenRandom(nullptr, out.data(), static_cast<ULONG>(out.size()),-                        BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0) {-        return;-    }-#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || \-    defined(__DragonFly__)-    arc4random_buf(out.data(), out.size());-    return;-#else-    std::size_t done = 0;-    while (done < out.size()) {-        const ssize_t n = ::getrandom(out.data() + done, out.size() - done, 0);-        if (n > 0) {-            done += static_cast<std::size_t>(n);-            continue;-        }-        if (n < 0 && errno == EINTR)-            continue;-        break;-    }-    if (done == out.size())-        return;-#endif-    std::random_device rd;-    for (std::size_t i = 0; i < out.size(); ++i) {-        out[i] = static_cast<std::uint8_t>(rd());-    }-}--std::array<std::uint8_t, 16> random_change_id() {-    std::array<std::uint8_t, 16> out{};-    os_random_bytes(MutBytes(out.data(), out.size()));-    return out;-}--std::uint64_t random_u64() {-    std::uint64_t value = 0;-    os_random_bytes(MutBytes(reinterpret_cast<std::uint8_t*>(&value), sizeof(value)));-    return value;-}---Result<std::uint8_t> Reader::u8() {-    if (pos_ >= data_.size())-        return fail(ErrorKind::UnexpectedEnd, pos_);-    return data_[pos_++];-}--Result<std::uint16_t> Reader::u16le() {-    if (remaining() < 2)-        return fail(ErrorKind::UnexpectedEnd, pos_);-    const auto v = static_cast<std::uint16_t>(-        static_cast<std::uint16_t>(data_[pos_]) |-        static_cast<std::uint16_t>(static_cast<std::uint16_t>(data_[pos_ + 1]) << 8));-    pos_ += 2;-    return v;-}--Result<std::uint32_t> Reader::u32le() {-    if (remaining() < 4)-        return fail(ErrorKind::UnexpectedEnd, pos_);-    std::uint32_t v = 0;-    for (std::size_t i = 0; i < 4; ++i) {-        v |= static_cast<std::uint32_t>(data_[pos_ + i]) << (i * 8);-    }-    pos_ += 4;-    return v;-}--Result<std::uint64_t> Reader::u64le() {-    if (remaining() < 8)-        return fail(ErrorKind::UnexpectedEnd, pos_);-    std::uint64_t v = 0;-    for (int i = 0; i < 8; ++i) {-        v |= static_cast<std::uint64_t>(data_[pos_ + static_cast<std::size_t>(i)]) << (i * 8);-    }-    pos_ += 8;-    return v;-}--Result<std::int16_t> Reader::i16le() {-    const auto v = u16le();-    if (!v)-        return unexpected(v.error());-    return static_cast<std::int16_t>(*v);-}--Result<std::int64_t> Reader::i64le() {-    const auto v = u64le();-    if (!v)-        return unexpected(v.error());-    return static_cast<std::int64_t>(*v);-}--Result<std::uint64_t> Reader::varint() {-    const std::size_t start = pos_;-    std::uint64_t value = 0;-    unsigned shift = 0;-    for (unsigned i = 0; i < 10; ++i) {-        const auto b = u8();-        if (!b)-            return unexpected(b.error());-        const std::uint64_t low = static_cast<std::uint64_t>(*b & 127u);-        if (shift == 63 && low > 1)-            return fail(ErrorKind::VarintOverflow, start);-        value |= low << shift;-        if ((*b & 128u) == 0) {-            if (i > 0 && low == 0)-                return fail(ErrorKind::NonMinimalVarint, start);-            return value;-        }-        shift += 7;-    }-    return fail(ErrorKind::VarintOverflow, start);-}--Result<Bytes> Reader::raw(std::size_t n) {-    if (n > remaining())-        return fail(ErrorKind::UnexpectedEnd, pos_);-    const Bytes out = data_.subspan(pos_, n);-    pos_ += n;-    return out;-}--Result<Bytes> Reader::bytes(std::size_t max_len) {-    const std::size_t at = pos_;-    const auto n = varint();-    if (!n)-        return unexpected(n.error());-    if (*n > max_len)-        return fail(ErrorKind::LimitExceeded, at);-    if (*n > remaining())-        return fail(ErrorKind::UnexpectedEnd, at);-    return raw(static_cast<std::size_t>(*n));-}--Result<std::string> Reader::string_bytes(std::size_t max_len) {-    const auto b = bytes(max_len);-    if (!b)-        return unexpected(b.error());-    return std::string(str_of(*b));-}--Result<std::size_t> Reader::list_len(std::size_t max) {-    const std::size_t at = pos_;-    const auto n = varint();-    if (!n)-        return unexpected(n.error());-    if (*n > max)-        return fail(ErrorKind::LimitExceeded, at);-    // Every list element occupies at least one byte. Rejecting counts larger-    // than the remaining payload keeps a tiny hostile input from reserving-    // gigabytes before the first element is even read.-    if (*n > remaining())-        return fail(ErrorKind::UnexpectedEnd, at);-    return static_cast<std::size_t>(*n);-}--Result<Id> Reader::id() {-    const auto b = raw(ID_LEN);-    if (!b)-        return unexpected(b.error());-    Id out{};-    std::memcpy(out.data(), b->data(), ID_LEN);-    return out;-}--Result<std::optional<Id>> Reader::opt_id() {-    const std::size_t at = pos_;-    const auto tag = u8();-    if (!tag)-        return unexpected(tag.error());-    if (*tag == 0)-        return std::optional<Id>{};-    if (*tag != 1)-        return fail(ErrorKind::InvalidValue, at);-    const auto value = id();-    if (!value)-        return unexpected(value.error());-    return std::optional<Id>(*value);-}--Result<void> Reader::finish() {-    if (pos_ != data_.size())-        return fail(ErrorKind::TrailingBytes, pos_);-    return {};-}--Result<Reader::Sig> Reader::sig(std::size_t max_name, std::size_t max_email) {-    Sig out;-    const auto name = string_bytes(max_name);-    if (!name)-        return unexpected(name.error());-    const auto email = string_bytes(max_email);-    if (!email)-        return unexpected(email.error());-    const auto secs = i64le();-    if (!secs)-        return unexpected(secs.error());-    const auto tz = i16le();-    if (!tz)-        return unexpected(tz.error());-    out.name = *name;-    out.email = *email;-    out.seconds = *secs;-    out.tz_min = *tz;-    return out;-}--Result<Reader::TimeMs> Reader::time_ms() {-    TimeMs out;-    const auto ms = i64le();-    if (!ms)-        return unexpected(ms.error());-    const auto tz = i16le();-    if (!tz)-        return unexpected(tz.error());-    out.ms = *ms;-    out.tz_min = *tz;-    return out;-}--std::uint64_t Reader::read_u64le_at(Bytes data, std::size_t off) {-    if (off > data.size() || data.size() - off < 8)-        return 0;-    std::uint64_t v = 0;-    for (std::size_t i = 0; i < 8; ++i)-        v |= static_cast<std::uint64_t>(data[off + i]) << (i * 8);-    return v;-}--void ByteWriter::u8(std::uint8_t v) {-    buf_.push_back(v);-}--void ByteWriter::u16le(std::uint16_t v) {-    buf_.push_back(static_cast<std::uint8_t>(v & 255u));-    buf_.push_back(static_cast<std::uint8_t>((v >> 8) & 255u));-}--void ByteWriter::u32le(std::uint32_t v) {-    for (int i = 0; i < 4; ++i)-        buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));-}--void ByteWriter::u64le(std::uint64_t v) {-    for (int i = 0; i < 8; ++i)-        buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));-}--void ByteWriter::i16le(std::int16_t v) {-    u16le(static_cast<std::uint16_t>(v));-}-void ByteWriter::i64le(std::int64_t v) {-    u64le(static_cast<std::uint64_t>(v));-}--void ByteWriter::varint(std::uint64_t v) {-    for (;;) {-        const std::uint8_t low = static_cast<std::uint8_t>(v & 127u);-        v >>= 7;-        if (v == 0) {-            buf_.push_back(low);-            return;-        }-        buf_.push_back(static_cast<std::uint8_t>(low | 128u));-    }-}--void ByteWriter::raw(Bytes data) {-    if (!data.empty()) {-        buf_.insert(buf_.end(), data.begin(), data.end());-    }-}--void ByteWriter::length_prefixed(std::string_view s) {-    length_prefixed(bytes_of(s));-}-void ByteWriter::length_prefixed(Bytes b) {-    varint(b.size());-    raw(b);-}--void ByteWriter::id(const Id& id) {-    raw(Bytes(id.data(), id.size()));-}--void ByteWriter::opt_id(const std::optional<Id>& id) {-    if (!id) {-        u8(0);-        return;-    }-    u8(1);-    this->id(*id);-}--void ByteWriter::sig(const Reader::Sig& s) {-    length_prefixed(s.name);-    length_prefixed(s.email);-    i64le(s.seconds);-    i16le(s.tz_min);-}--void ByteWriter::time_ms(const Reader::TimeMs& t) {-    i64le(t.ms);-    i16le(t.tz_min);-}---std::size_t available_cpu_count() {-#if defined(_WIN32)-    const DWORD count = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);-    return count == 0 ? 1 : static_cast<std::size_t>(count);-#elif defined(__linux__)-    cpu_set_t set;-    CPU_ZERO(&set);-    if (sched_getaffinity(0, sizeof(set), &set) == 0) {-        const auto* bytes = reinterpret_cast<const unsigned char*>(&set);-        std::size_t count = 0;-        for (std::size_t i = 0; i < sizeof(set); ++i) {-            unsigned char value = bytes[i];-            while (value != 0) {-                count += value & 1u;-                value >>= 1;-            }-        }-        if (count != 0)-            return count;-    }-    const long n = sysconf(_SC_NPROCESSORS_ONLN);-    return n > 0 ? static_cast<std::size_t>(n) : 1;-#else-    const long n = sysconf(_SC_NPROCESSORS_ONLN);-    return n > 0 ? static_cast<std::size_t>(n) : 1;-#endif-}--std::int64_t unix_now_seconds() {-    return std::chrono::duration_cast<std::chrono::seconds>(-               std::chrono::system_clock::now().time_since_epoch())-        .count();-}--std::int64_t unix_now_millis() {-    return std::chrono::duration_cast<std::chrono::milliseconds>(-               std::chrono::system_clock::now().time_since_epoch())-        .count();-}--static std::int64_t floor_div(std::int64_t a, std::int64_t b) {-    std::int64_t q = a / b;-    const std::int64_t r = a % b;-    if (r != 0 && ((r < 0) != (b < 0)))-        --q;-    return q;-}--static void append_pad(std::string& out, std::int64_t value, int width) {-    if (value < 0)-        value = 0;-    std::string digits;-    do {-        digits.push_back(static_cast<char>('0' + (value % 10)));-        value /= 10;-    } while (value > 0);-    for (int i = static_cast<int>(digits.size()); i < width; ++i)-        out.push_back('0');-    for (auto it = digits.rbegin(); it != digits.rend(); ++it)-        out.push_back(*it);-}--std::string format_utc(std::int64_t seconds) {-    const std::int64_t days = floor_div(seconds, 86400);-    const std::int64_t rem = seconds - days * 86400;-    const std::int64_t hour = rem / 3600;-    const std::int64_t minute = (rem % 3600) / 60;-    const std::int64_t second = rem % 60;--    const std::int64_t z = days + 719468;-    const std::int64_t era = floor_div(z, 146097);-    const std::int64_t doe = z - era * 146097;-    const std::int64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;-    const std::int64_t y0 = yoe + era * 400;-    const std::int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);-    const std::int64_t mp = (5 * doy + 2) / 153;-    const std::int64_t d = doy - (153 * mp + 2) / 5 + 1;-    const std::int64_t m0 = mp + 3;-    const std::int64_t m = mp >= 10 ? mp - 9 : m0;-    const std::int64_t y = m <= 2 ? y0 + 1 : y0;--    std::string out;-    out.reserve(19);-    append_pad(out, y, 4);-    out.push_back('-');-    append_pad(out, m, 2);-    out.push_back('-');-    append_pad(out, d, 2);-    out.push_back(' ');-    append_pad(out, hour, 2);-    out.push_back(':');-    append_pad(out, minute, 2);-    out.push_back(':');-    append_pad(out, second, 2);-    return out;-}--static bool g_colors = false;-static bool g_colors_checked = false;--bool colors_enabled() {-    if (g_colors_checked)-        return g_colors;-    g_colors_checked = true;-    if (std::getenv("NO_COLOR") != nullptr)-        return false;-#if defined(_WIN32)-    const bool tty = _isatty(_fileno(stdout)) != 0;-    bool ansi = false;-    if (tty) {-        HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);-        DWORD mode = 0;-        if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {-            ansi = SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;-        }-    }-    if (!ansi)-        return false;-#else-    const bool tty = ::isatty(STDOUT_FILENO) != 0;-#endif-    const char* forced = std::getenv("FORCE_COLOR");-    if (forced != nullptr && *forced != '\0' && std::strcmp(forced, "0") != 0) {-        g_colors = true;-        return true;-    }-    if (!tty)-        return false;-    const char* term = std::getenv("TERM");-    if (term != nullptr && std::strcmp(term, "dumb") == 0)-        return false;-    g_colors = true;-    return true;-}--static std::string_view color_code(Color c) {-    switch (c) {-    case Color::Default:-        return "\x1b[39m";-    case Color::Black:-        return "\x1b[30m";-    case Color::Red:-        return "\x1b[31m";-    case Color::Green:-        return "\x1b[32m";-    case Color::Yellow:-        return "\x1b[33m";-    case Color::Blue:-        return "\x1b[34m";-    case Color::Magenta:-        return "\x1b[35m";-    case Color::Cyan:-        return "\x1b[36m";-    case Color::BrightBlack:-        return "\x1b[90m";-    case Color::BrightRed:-        return "\x1b[91m";-    case Color::BrightGreen:-        return "\x1b[92m";-    case Color::BrightYellow:-        return "\x1b[93m";-    case Color::BrightBlue:-        return "\x1b[94m";-    case Color::BrightMagenta:-        return "\x1b[95m";-    case Color::BrightCyan:-        return "\x1b[96m";-    case Color::BrightWhite:-        return "\x1b[97m";-    }-    return "\x1b[39m";-}--void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr) {-    (void)to_stderr;-    auto& stream = std::cout;-    if (!colors_enabled()) {-        stream << text;-        return;-    }-    if (dim)-        stream << "\x1b[2m";-    if (fg != Color::Default)-        stream << color_code(fg);-    stream << text;-    stream << "\x1b[0m";-}--void print_colored(std::string_view text, Color color, bool dim, bool to_stderr) {-    print_styled(text, color, dim, to_stderr);-}--void print_bold(std::string_view text, Color fg, bool to_stderr) {-    (void)to_stderr;-    auto& stream = std::cout;-    if (!colors_enabled()) {-        stream << text;-        return;-    }-    stream << "\x1b[1m";-    if (fg != Color::Default)-        stream << color_code(fg);-    stream << text << "\x1b[0m";-}--void error_prefix() {-    print_bold("error", Color::Red, false);-    std::cout << ": ";-}-void warning_prefix() {-    print_bold("warning", Color::Yellow, false);-    std::cout << ": ";-}-void info_prefix() {-    print_styled("info", Color::Cyan, false, false);-    std::cout << ": ";-}--namespace {--bool progress_enabled() {-    if (const char* value = std::getenv("NO_PROGRESS")) {-        if (value[0] != '\0' && std::strcmp(value, "0") != 0)-            return false;-    }-    if (const char* value = std::getenv("VN_NO_PROGRESS")) {-        if (value[0] != '\0' && std::strcmp(value, "0") != 0)-            return false;-    }-    if (const char* value = std::getenv("VN_PROGRESS")) {-        if (value[0] != '\0' && std::strcmp(value, "0") != 0)-            return true;-    }-    const char* term = std::getenv("TERM");-    if (term != nullptr && std::strcmp(term, "dumb") == 0)-        return false;-    return stderr_is_terminal();-}--std::size_t progress_bar_width() {-    return 24;-}--} // namespace--Progress::Progress(std::string label, std::size_t total)-    : label_(std::move(label)), total_(total), enabled_(progress_enabled()) {}--Progress::~Progress() {-    if (!enabled_ || !drawn_ || finished_)-        return;-    std::cerr << "\r\x1b[2K";-    std::cerr.flush();-}--void Progress::set_total(std::size_t total) {-    std::lock_guard<std::mutex> lock(mutex_);-    total_ = total;-    refresh_locked(true);-}--void Progress::update(std::size_t done, bool force) {-    std::lock_guard<std::mutex> lock(mutex_);-    done_ = done;-    refresh_locked(force);-}--void Progress::advance(std::size_t amount) {-    std::lock_guard<std::mutex> lock(mutex_);-    done_ += amount;-    refresh_locked(false);-}--void Progress::finish() {-    std::lock_guard<std::mutex> lock(mutex_);-    if (!enabled_ || finished_)-        return;-    finished_ = true;-    if (total_ > 0) {-        if (done_ < total_)-            done_ = total_;-        if (!drawn_ || last_done_ != done_ || last_total_ != total_)-            draw_locked();-        std::cerr << "\n";-        std::cerr.flush();-    } else if (drawn_) {-        std::cerr << "\r\x1b[2K";-        std::cerr.flush();-    }-    drawn_ = false;-}--void Progress::clear() {-    std::lock_guard<std::mutex> lock(mutex_);-    if (!enabled_)-        return;-    if (drawn_) {-        std::cerr << "\r\x1b[2K";-        std::cerr.flush();-    }-    drawn_ = false;-    finished_ = true;-}--void Progress::refresh_locked(bool force) {-    if (!enabled_ || finished_)-        return;-    const auto now = std::chrono::steady_clock::now();-    const bool complete = total_ > 0 && done_ >= total_;-    if (!force && !complete && now - last_draw_ < std::chrono::milliseconds(66))-        return;-    last_draw_ = now;-    draw_locked();-    drawn_ = true;-}--void Progress::draw_locked() {-    const bool color = colors_enabled();-    std::ostringstream line;-    if (color)-        line << "\r\x1b[2K\x1b[1m\x1b[36minfo\x1b[0m: ";-    else-        line << "\r\x1b[2Kinfo: ";-    line << label_ << "  ";-    if (total_ > 0) {-        const std::size_t width = progress_bar_width();-        const std::size_t filled = std::min<std::size_t>(-            width,-            static_cast<std::size_t>((static_cast<unsigned long long>(done_) * width) / total_));-        line << "[";-        if (filled >= width) {-            if (color)-                line << "\x1b[32m";-            for (std::size_t i = 0; i < width; ++i)-                line << "=";-        } else {-            const std::size_t head = filled == 0 ? 1 : filled;-            if (color)-                line << "\x1b[32m";-            for (std::size_t i = 0; i + 1 < head; ++i)-                line << "=";-            line << ">";-            if (color)-                line << "\x1b[0m";-            for (std::size_t i = head; i < width; ++i)-                line << " ";-        }-        if (color)-            line << "\x1b[0m";-        line << "]";-        const std::size_t percent = std::min<std::size_t>(-            100, static_cast<std::size_t>((static_cast<unsigned long long>(done_) * 100) / total_));-        if (color)-            line << " \x1b[36m";-        else-            line << " ";-        line << percent << "%";-        if (color)-            line << "\x1b[0m\x1b[2m";-        line << " " << done_ << "/" << total_;-        if (color)-            line << "\x1b[0m";-    } else {-        static constexpr char spin[] = "|/-\\";-        const char frame = spin[done_ % 4];-        if (color)-            line << "\x1b[36m" << frame << "\x1b[0m\x1b[2m";-        else-            line << frame;-        line << " " << done_;-        if (color)-            line << "\x1b[0m";-    }-    last_done_ = done_;-    last_total_ = total_;-    std::cerr << line.str();-    std::cerr.flush();-}---fs::path path_from_bytes(std::string_view bytes) {-#if defined(_WIN32)-    std::u8string u;-    u.reserve(bytes.size());-    for (char c : bytes)-        u.push_back(static_cast<char8_t>(c));-    return fs::path(u);-#else-    return fs::path(std::string(bytes));-#endif-}--std::string path_to_bytes(const fs::path& p) {-#if defined(_WIN32)-    const std::u8string u = p.u8string();-    return std::string(reinterpret_cast<const char*>(u.data()), u.size());-#else-    return p.native();-#endif-}--std::string path_display(const fs::path& p) {-    return path_to_bytes(p);-}--bool path_exists(const fs::path& p) {-    std::error_code ec;-    return fs::exists(p, ec);-}--bool path_is_dir(const fs::path& p) {-    std::error_code ec;-    return fs::is_directory(p, ec);-}--bool path_is_file(const fs::path& p) {-    std::error_code ec;-    return fs::is_regular_file(p, ec);-}--bool path_is_symlink(const fs::path& p) {-    std::error_code ec;-    return fs::is_symlink(fs::symlink_status(p, ec));-}--std::optional<std::uint64_t> path_file_size(const fs::path& p) {-    std::error_code ec;-    const auto n = fs::file_size(p, ec);-    if (ec)-        return std::nullopt;-    return static_cast<std::uint64_t>(n);-}--std::string basename_string(const fs::path& p) {-    return path_to_bytes(p.filename());-}--std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p, std::uint64_t max_size) {-#if defined(_WIN32)-    std::ifstream in(p, std::ios::binary);-    if (!in)-        return std::nullopt;-    in.seekg(0, std::ios::end);-    const std::streamoff n = in.tellg();-    if (n < 0)-        return std::nullopt;-    if (max_size != 0 && static_cast<std::uint64_t>(n) > max_size)-        return std::nullopt;-    in.seekg(0, std::ios::beg);-    std::vector<std::uint8_t> data(static_cast<std::size_t>(n));-    if (n > 0 && !in.read(reinterpret_cast<char*>(data.data()), n)) {-        return std::nullopt;-    }-    return data;-#else-    const int fd = ::open(p.c_str(), O_RDONLY);-    if (fd < 0)-        return std::nullopt;-    struct stat st {};-    if (::fstat(fd, &st) != 0 || st.st_size < 0 ||-        (max_size != 0 && static_cast<std::uint64_t>(st.st_size) > max_size)) {-        ::close(fd);-        return std::nullopt;-    }-    std::vector<std::uint8_t> data(static_cast<std::size_t>(st.st_size));-    std::size_t done = 0;-    while (done < data.size()) {-        const ssize_t n = ::read(fd, data.data() + done, data.size() - done);-        if (n > 0) {-            done += static_cast<std::size_t>(n);-        } else if (n < 0 && errno == EINTR) {-            continue;-        } else {-            ::close(fd);-            return std::nullopt;-        }-    }-    ::close(fd);-    return data;-#endif-}--std::optional<std::vector<std::uint8_t>> read_file_range(const fs::path& p, std::uint64_t offset,-                                                         std::size_t length) {-    std::ifstream in(p, std::ios::binary);-    if (!in)-        return std::nullopt;-    in.seekg(static_cast<std::streamoff>(offset), std::ios::beg);-    if (!in)-        return std::nullopt;-    std::vector<std::uint8_t> data(length);-    if (length > 0) {-        in.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(length));-        data.resize(static_cast<std::size_t>(in.gcount()));-    }-    return data;-}--Result<std::vector<std::uint8_t>> read_file(const fs::path& p, std::uint64_t max_size) {-    auto data = read_file_opt(p, max_size);-    if (!data)-        return fail_io("cannot read " + path_display(p));-    return *data;-}--static bool sync_file_path(const fs::path& p) {-#if defined(_WIN32)-    const int fd = _wopen(p.c_str(), _O_RDWR | _O_BINARY);-    if (fd < 0)-        return false;-    const bool ok = _commit(fd) == 0;-    _close(fd);-    return ok;-#else-    const int fd = ::open(p.c_str(), O_RDONLY);-    if (fd < 0)-        return false;-    const bool ok = ::fsync(fd) == 0;-    ::close(fd);-    return ok;-#endif-}--static void sync_parent_directory(const fs::path& p) {-#if defined(_WIN32)-    (void)p;-#else-    const fs::path parent = p.parent_path();-    if (parent.empty())-        return;-#if defined(__linux__)-    const int fd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY);-#else-    const int fd = ::open(parent.c_str(), O_RDONLY);-#endif-    if (fd >= 0) {-        (void)::fsync(fd);-        ::close(fd);-    }-#endif-}--static bool replace_file(const fs::path& from, const fs::path& to) {-#if defined(_WIN32)-    return MoveFileExW(from.c_str(), to.c_str(),-                       MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;-#else-    return std::rename(from.c_str(), to.c_str()) == 0;-#endif-}--bool write_file(const fs::path& p, Bytes data) {-    std::error_code ec;-    if (!p.parent_path().empty())-        fs::create_directories(p.parent_path(), ec);-#if defined(_WIN32)-    std::ofstream out(p, std::ios::binary | std::ios::trunc);-    if (!out)-        return false;-    if (!data.empty()) {-        out.write(reinterpret_cast<const char*>(data.data()),-                  static_cast<std::streamsize>(data.size()));-    }-    out.flush();-    return static_cast<bool>(out);-#else-    int flags = O_WRONLY | O_CREAT | O_TRUNC;-#if defined(O_NOFOLLOW)-    flags |= O_NOFOLLOW;-#endif-    const int fd = ::open(p.c_str(), flags, 0644);-    if (fd < 0)-        return false;-    std::size_t done = 0;-    while (done < data.size()) {-        const ssize_t n = ::write(fd, data.data() + done, data.size() - done);-        if (n > 0) {-            done += static_cast<std::size_t>(n);-        } else if (n < 0 && errno == EINTR) {-            continue;-        } else {-            ::close(fd);-            return false;-        }-    }-    if (::close(fd) != 0)-        return false;-    return true;-#endif-}--bool append_file(const fs::path& p, Bytes data) {-    std::error_code ec;-    if (!p.parent_path().empty())-        fs::create_directories(p.parent_path(), ec);-#if defined(_WIN32)-    std::ofstream out(p, std::ios::binary | std::ios::app);-    if (!out)-        return false;-    if (!data.empty()) {-        out.write(reinterpret_cast<const char*>(data.data()),-                  static_cast<std::streamsize>(data.size()));-    }-    out.flush();-    return static_cast<bool>(out);-#else-    int flags = O_WRONLY | O_CREAT | O_APPEND;-#if defined(O_NOFOLLOW)-    flags |= O_NOFOLLOW;-#endif-    const int fd = ::open(p.c_str(), flags, 0644);-    if (fd < 0)-        return false;-    std::size_t done = 0;-    while (done < data.size()) {-        const ssize_t n = ::write(fd, data.data() + done, data.size() - done);-        if (n > 0) {-            done += static_cast<std::size_t>(n);-        } else if (n < 0 && errno == EINTR) {-            continue;-        } else {-            ::close(fd);-            return false;-        }-    }-    if (::close(fd) != 0)-        return false;-    return true;-#endif-}--bool write_atomic(const fs::path& tmp_path, const fs::path& final_path, Bytes data) {-    std::error_code ec;-    if (!tmp_path.parent_path().empty())-        fs::create_directories(tmp_path.parent_path(), ec);-    if (!final_path.parent_path().empty())-        fs::create_directories(final_path.parent_path(), ec);-    if (!write_file(tmp_path, data))-        return false;-    if (!sync_file_path(tmp_path)) {-        remove_file(tmp_path);-        return false;-    }-    if (!replace_file(tmp_path, final_path)) {-        remove_file(tmp_path);-        return false;-    }-    sync_parent_directory(final_path);-    return true;-}--bool write_atomic(const fs::path& final_path, Bytes data) {-    const fs::path dir = final_path.parent_path();-    const std::string name = basename_string(final_path);-    const std::string tmp_name =-        "." + name + ".tmp." + std::to_string(static_cast<unsigned long>(random_u64()));-    return write_atomic(dir / tmp_name, final_path, data);-}--bool ensure_directory(const fs::path& p) {-    std::error_code ec;-    fs::create_directories(p, ec);-    return !ec;-}--bool remove_file(const fs::path& p) {-    std::error_code ec;-    return fs::remove(p, ec);-}--bool remove_tree(const fs::path& p) {-    std::error_code ec;-    fs::remove_all(p, ec);-    return !ec;-}--std::vector<std::string> list_directory(const fs::path& p) {-    std::vector<std::string> out;-#if defined(_WIN32)-    std::error_code ec;-    fs::directory_iterator it(p, ec);-    if (ec)-        return out;-    for (const auto& entry : it)-        out.push_back(path_to_bytes(entry.path().filename()));-#else-    DIR* dir = ::opendir(p.c_str());-    if (dir == nullptr)-        return out;-    while (dirent* entry = ::readdir(dir)) {-        const char* name = entry->d_name;-        if (std::strcmp(name, ".") == 0 || std::strcmp(name, "..") == 0)-            continue;-        out.emplace_back(name);-    }-    ::closedir(dir);-#endif-    return out;-}--bool same_or_under(const fs::path& child, const fs::path& parent) {-    std::error_code ec;-    const fs::path c = fs::weakly_canonical(child, ec);-    if (ec)-        return false;-    const fs::path p = fs::weakly_canonical(parent, ec);-    if (ec)-        return false;-    auto ci = c.begin();-    auto pi = p.begin();-    for (; pi != p.end(); ++pi, ++ci) {-        if (ci == c.end() || *ci != *pi)-            return false;-    }-    return true;-}--std::optional<std::string> path_read_symlink(const fs::path& p) {-    std::error_code ec;-    const fs::path target = fs::read_symlink(p, ec);-    if (ec)-        return std::nullopt;-    return path_to_bytes(target);-}--#if defined(_WIN32)-static std::optional<std::uint64_t> mtime_from_file_time(const fs::path& p) {-    std::error_code ec;-    const auto ft = fs::last_write_time(p, ec);-    if (ec)-        return std::nullopt;-    // Convert the filesystem clock value to Unix nanoseconds without assuming-    // a particular epoch offset: compare against a known reference point.-    const auto now_file = fs::file_time_type::clock::now();-    const auto now_sys = std::chrono::system_clock::now();-    const auto delta = std::chrono::duration_cast<std::chrono::nanoseconds>(ft - now_file);-    const auto sys = now_sys + delta;-    return static_cast<std::uint64_t>(-        std::chrono::duration_cast<std::chrono::nanoseconds>(sys.time_since_epoch()).count());-}-#endif--std::optional<StatInfo> stat_path(const fs::path& p) {-#if defined(_WIN32)-    std::error_code ec;-    const auto status = fs::symlink_status(p, ec);-    if (ec || status.type() == fs::file_type::not_found)-        return std::nullopt;-    StatInfo info;-    if (fs::is_symlink(status)) {-        info.kind = 3;-    } else if (fs::is_directory(status)) {-        info.kind = 2;-    } else if (fs::is_regular_file(status)) {-        info.kind = 1;-    } else {-        return std::nullopt;-    }-    if (info.kind == 1) {-        info.size = path_file_size(p).value_or(0);-    }-    info.mtime_ns = mtime_from_file_time(p).value_or(0);-    return info;-#else-    struct stat st {};-    if (::lstat(p.c_str(), &st) != 0)-        return std::nullopt;-    StatInfo info;-    if (S_ISLNK(st.st_mode)) {-        info.kind = 3;-    } else if (S_ISDIR(st.st_mode)) {-        info.kind = 2;-    } else if (S_ISREG(st.st_mode)) {-        info.kind = 1;-    } else {-        return std::nullopt;-    }-    info.executable = (st.st_mode & 0111) != 0;-    info.size = static_cast<std::uint64_t>(st.st_size);-    info.inode = static_cast<std::uint64_t>(st.st_ino);-#if defined(__APPLE__)-    info.mtime_ns = static_cast<std::uint64_t>(st.st_mtimespec.tv_sec) * 1'000'000'000ull +-                    static_cast<std::uint64_t>(st.st_mtimespec.tv_nsec);-#else-    info.mtime_ns = static_cast<std::uint64_t>(st.st_mtim.tv_sec) * 1'000'000'000ull +-                    static_cast<std::uint64_t>(st.st_mtim.tv_nsec);-#endif-    return info;-#endif-}--std::optional<std::uint64_t> file_mtime_ns(const fs::path& p) {-    const auto info = stat_path(p);-    if (!info)-        return std::nullopt;-    return info->mtime_ns;-}--std::optional<std::uint64_t> file_inode(const fs::path& p) {-    const auto info = stat_path(p);-    if (!info)-        return std::nullopt;-    return info->inode;-}--bool is_executable(const fs::path& p) {-    const auto info = stat_path(p);-    return info && info->executable;-}---static std::string_view trim_view(std::string_view s) {-    std::size_t start = 0;-    std::size_t end = s.size();-    while (start < end) {-        const char c = s[start];-        if (c != ' ' && c != '\t' && c != '\r' && c != '\n')-            break;-        ++start;-    }-    while (end > start) {-        const char c = s[end - 1];-        if (c != ' ' && c != '\t' && c != '\r' && c != '\n')-            break;-        --end;-    }-    return s.substr(start, end - start);-}--static std::string trim_copy(std::string_view s) {-    return std::string(trim_view(s));-}--std::optional<std::string> repo_config_value(const fs::path& repo_root, std::string_view key) {-    const auto data = read_file_opt(repo_root / ".veins" / "config");-    if (!data)-        return std::nullopt;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        const std::string_view line = trim_view(text.substr(start, end - start));-        if (!line.empty() && line.front() != '#') {-            const std::size_t eq = line.find('=');-            if (eq != std::string_view::npos) {-                const std::string_view k = trim_view(line.substr(0, eq));-                if (k == key)-                    return trim_copy(line.substr(eq + 1));-            }-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-    return std::nullopt;-}--static std::string strip_comment(std::string_view v) {-    const std::size_t hash = v.find('#');-    if (hash != std::string_view::npos)-        v = v.substr(0, hash);-    return trim_copy(v);-}--bool repo_config_bool(const fs::path& repo_root, std::string_view key, bool fallback) {-    const auto v = repo_config_value(repo_root, key);-    if (!v)-        return fallback;-    const std::string value = strip_comment(*v);-    return value == "true" || value == "1" || value == "yes" || value == "on";-}--bool repo_config_set(const fs::path& repo_root, std::string_view key, std::string_view value) {-    const fs::path path = repo_root / ".veins" / "config";-    const auto data = read_file_opt(path);-    std::string out;-    if (data) {-        std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-        std::size_t start = 0;-        while (start <= text.size()) {-            std::size_t end = text.find('\n', start);-            if (end == std::string_view::npos)-                end = text.size();-            const std::string_view line = text.substr(start, end - start);-            const std::string_view t = trim_view(line);-            const std::size_t eq = t.find('=');-            const bool is_key = eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;-            if (!is_key) {-                out.append(line);-                if (end < text.size())-                    out.push_back('\n');-            }-            if (end == text.size())-                break;-            start = end + 1;-        }-    }-    out.append(key);-    out.append(" = ");-    out.append(value);-    out.push_back('\n');-    return write_file(path, bytes_of(out));-}--bool repo_config_remove(const fs::path& repo_root, std::string_view key) {-    const fs::path path = repo_root / ".veins" / "config";-    const auto data = read_file_opt(path);-    std::string out;-    if (data) {-        std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-        std::size_t start = 0;-        while (start <= text.size()) {-            std::size_t end = text.find('\n', start);-            if (end == std::string_view::npos)-                end = text.size();-            const std::string_view line = text.substr(start, end - start);-            const std::string_view t = trim_view(line);-            const std::size_t eq = t.find('=');-            const bool is_key = eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;-            if (!is_key) {-                out.append(line);-                if (end < text.size())-                    out.push_back('\n');-            }-            if (end == text.size())-                break;-            start = end + 1;-        }-    }-    return write_file(path, bytes_of(out));-}--static fs::path user_config_path() {-#if defined(_WIN32)-    const char* home = std::getenv("USERPROFILE");-#else-    const char* home = std::getenv("HOME");-#endif-    if (home == nullptr || *home == '\0')-        return {};-    return path_from_bytes(home) / ".local" / "config" / "veins" / "veins.toml";-}--static std::optional<std::string> unquote_toml(std::string_view raw) {-    raw = trim_view(raw);-    if (raw.size() >= 2) {-        if ((raw.front() == '\'' && raw.back() == '\'') ||-            (raw.front() == '"' && raw.back() == '"')) {-            const char quote = raw.front();-            std::string out;-            for (std::size_t i = 1; i + 1 < raw.size(); ++i) {-                const char c = raw[i];-                if (quote == '"' && c == '\\' && i + 2 < raw.size()) {-                    const char next = raw[i + 1];-                    if (next == '"')-                        out.push_back('"');-                    else if (next == '\\')-                        out.push_back('\\');-                    else if (next == 'n')-                        out.push_back('\n');-                    else if (next == 'r')-                        out.push_back('\r');-                    else if (next == 't')-                        out.push_back('\t');-                    else {-                        out.push_back('\\');-                        out.push_back(next);-                    }-                    ++i;-                } else {-                    out.push_back(c);-                }-            }-            return out;-        }-    }-    if (raw.empty())-        return std::nullopt;-    return std::string(raw);-}--static std::string user_config_full_key(std::string_view section, std::string_view key) {-    if (section.empty())-        return std::string(key);-    std::string out(section);-    out.push_back('.');-    out.append(key);-    return out;-}--static std::optional<std::string> read_user_config_value(std::string_view wanted) {-    const fs::path path = user_config_path();-    if (path.empty())-        return std::nullopt;-    const auto data = read_file_opt(path);-    if (!data)-        return std::nullopt;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::string section;-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        const std::string_view line = trim_view(text.substr(start, end - start));-        if (!line.empty() && line.front() != '#') {-            if (line.front() == '[') {-                const std::size_t close = line.find(']');-                if (close != std::string_view::npos)-                    section = trim_copy(line.substr(1, close - 1));-            } else {-                const std::size_t eq = line.find('=');-                if (eq != std::string_view::npos) {-                    const std::string_view key = trim_view(line.substr(0, eq));-                    if (user_config_full_key(section, key) == wanted) {-                        std::string_view value = line.substr(eq + 1);-                        std::string value_copy = strip_comment(value);-                        auto decoded = unquote_toml(value_copy);-                        if (decoded && !decoded->empty())-                            return decoded;-                    }-                }-            }-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-    return std::nullopt;-}--std::optional<std::string> user_config_value(std::string_view key) {-    return read_user_config_value(key);-}--std::map<std::string, std::string> user_config_entries() {-    std::map<std::string, std::string> out;-    const fs::path path = user_config_path();-    if (path.empty())-        return out;-    const auto data = read_file_opt(path);-    if (!data)-        return out;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::string section;-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        const std::string_view line = trim_view(text.substr(start, end - start));-        if (!line.empty() && line.front() != '#') {-            if (line.front() == '[') {-                const std::size_t close = line.find(']');-                if (close != std::string_view::npos)-                    section = trim_copy(line.substr(1, close - 1));-            } else {-                const std::size_t eq = line.find('=');-                if (eq != std::string_view::npos) {-                    const std::string_view key = trim_view(line.substr(0, eq));-                    std::string value_copy = strip_comment(line.substr(eq + 1));-                    auto decoded = unquote_toml(value_copy);-                    if (decoded)-                        out[user_config_full_key(section, key)] = *decoded;-                }-            }-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-    return out;-}--std::optional<std::string> user_config_author_name() {-    return user_config_value("user.name");-}-std::optional<std::string> user_config_author_email() {-    return user_config_value("user.email");-}--static std::string toml_quote(std::string_view value) {-    std::string out;-    out.push_back('"');-    for (char c : value) {-        switch (c) {-        case '"':-            out += "\\\"";-            break;-        case '\\':-            out += "\\\\";-            break;-        case '\n':-            out += "\\n";-            break;-        case '\r':-            out += "\\r";-            break;-        case '\t':-            out += "\\t";-            break;-        default:-            out.push_back(c);-            break;-        }-    }-    out.push_back('"');-    return out;-}--static bool update_user_config(std::string_view key, const std::optional<std::string>& value) {-    if (key.empty())-        return false;-    const fs::path path = user_config_path();-    if (path.empty())-        return false;--    std::vector<std::string> lines;-    if (const auto data = read_file_opt(path)) {-        std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-        std::size_t start = 0;-        while (start <= text.size()) {-            std::size_t end = text.find('\n', start);-            if (end == std::string_view::npos)-                end = text.size();-            lines.emplace_back(text.substr(start, end - start));-            if (end == text.size())-                break;-            start = end + 1;-        }-    }--    std::vector<std::string> out;-    out.reserve(lines.size() + 1);-    std::string section;-    for (const auto& line : lines) {-        const std::string_view t = trim_view(line);-        if (!t.empty() && t.front() == '[') {-            const std::size_t close = t.find(']');-            section = close != std::string_view::npos ? trim_copy(t.substr(1, close - 1)) : "";-            out.push_back(line);-            continue;-        }-        std::size_t eq = t.find('=');-        if (t.empty() || t.front() == '#' || eq == std::string_view::npos) {-            out.push_back(line);-            continue;-        }-        const std::string_view k = trim_view(t.substr(0, eq));-        if (user_config_full_key(section, k) != key)-            out.push_back(line);-    }--    if (value) {-        std::string entry(key);-        entry += " = ";-        entry += toml_quote(*value);-        out.insert(out.begin(), std::move(entry));-    } else {-        while (!out.empty() && trim_view(out.back()).empty())-            out.pop_back();-    }--    std::string body;-    for (std::size_t i = 0; i < out.size(); ++i) {-        if (i != 0)-            body.push_back('\n');-        body += out[i];-    }-    if (!out.empty())-        body.push_back('\n');-    return write_file(path, bytes_of(body));-}--bool user_config_set(std::string_view key, std::string_view value) {-    return update_user_config(key, std::string(value));-}--bool user_config_remove(std::string_view key) {-    return update_user_config(key, std::nullopt);-}--static std::string shell_quote_arg(std::string_view value) {-#if defined(_WIN32)-    std::string out = "\"";-    for (char c : value) {-        if (c == '"')-            out.push_back('\\');-        out.push_back(c);-    }-    out.push_back('"');-    return out;-#else-    std::string out = "'";-    for (char c : value) {-        if (c == '\'')-            out += "'\\''";-        else-            out.push_back(c);-    }-    out.push_back('\'');-    return out;-#endif-}--std::string editor_command(const fs::path& repo_root) {-    if (auto value = user_config_value("editor")) {-        if (!value->empty())-            return *value;-    }-    if (auto value = user_config_value("core.editor")) {-        if (!value->empty())-            return *value;-    }-    if (auto value = repo_config_value(repo_root, "editor")) {-        if (!value->empty())-            return *value;-    }-    if (const char* value = std::getenv("VN_EDITOR")) {-        if (value[0] != '\0')-            return value;-    }-    if (const char* value = std::getenv("VISUAL")) {-        if (value[0] != '\0')-            return value;-    }-    if (const char* value = std::getenv("EDITOR")) {-        if (value[0] != '\0')-            return value;-    }-#if defined(_WIN32)-    return "notepad";-#else-    return "vi";-#endif-}--bool run_editor(const fs::path& repo_root, const std::vector<std::string>& paths,-                const std::optional<fs::path>& message_file) {-    std::string command = editor_command(repo_root);-    for (const auto& path : paths) {-        command.push_back(' ');-        command += shell_quote_arg(path);-    }-    if (message_file) {-        command.push_back(' ');-        command += shell_quote_arg(path_to_bytes(*message_file));-    }-    return std::system(command.c_str()) == 0;-}--bool stdin_is_terminal() {-#if defined(_WIN32)-    return _isatty(_fileno(stdin)) != 0;-#else-    return ::isatty(STDIN_FILENO) != 0;-#endif-}--bool stdout_is_terminal() {-#if defined(_WIN32)-    return _isatty(_fileno(stdout)) != 0;-#else-    return ::isatty(STDOUT_FILENO) != 0;-#endif-}--bool stderr_is_terminal() {-#if defined(_WIN32)-    return _isatty(_fileno(stderr)) != 0;-#else-    return ::isatty(STDERR_FILENO) != 0;-#endif-}--std::string pager_command(const fs::path& repo_root) {-    if (auto value = user_config_value("pager")) {-        if (!value->empty())-            return *value;-    }-    if (auto value = user_config_value("core.pager")) {-        if (!value->empty())-            return *value;-    }-    if (auto value = repo_config_value(repo_root, "pager")) {-        if (!value->empty())-            return *value;-    }-    if (const char* value = std::getenv("VN_PAGER")) {-        if (value[0] != '\0')-            return value;-    }-    if (const char* value = std::getenv("PAGER")) {-        if (value[0] != '\0')-            return value;-    }-#if defined(_WIN32)-    return "more";-#else-    return "less -R";-#endif-}--bool run_pager(const fs::path& repo_root, std::string_view text) {-    if (!stdout_is_terminal()) {-        std::cout << text;-        return true;-    }-    const fs::path file =-        fs::temp_directory_path() / ("vn-pager-" + std::to_string(random_u64()) + ".txt");-    if (!write_file(file, bytes_of(text))) {-        std::cout << text;-        return false;-    }-    const std::string command =-        pager_command(repo_root) + " " + shell_quote_arg(path_to_bytes(file));-    const bool ok = std::system(command.c_str()) == 0;-    (void)remove_file(file);-    if (!ok)-        std::cout << text;-    return ok;-}--std::optional<std::string> current_bookmark_name(const fs::path& repo_root) {-    return repo_config_value(repo_root, "bookmark.current");-}--bool set_current_bookmark(const fs::path& repo_root, std::string_view name) {-    if (name.empty())-        return repo_config_remove(repo_root, "bookmark.current");-    return repo_config_set(repo_root, "bookmark.current", name);-}--bool clear_current_bookmark(const fs::path& repo_root) {-    return repo_config_remove(repo_root, "bookmark.current");-}--static std::optional<std::string> env_value(const char* name) {-    const char* v = std::getenv(name);-    if (v == nullptr)-        return std::nullopt;-    return std::string(v);-}--static std::string first_config(const fs::path& repo_root, std::string_view key, bool want_name,-                                const char* env1, const char* env2) {-    if (auto v = repo_config_value(repo_root, key))-        return *v;-    auto user = want_name ? user_config_author_name() : user_config_author_email();-    if (user)-        return *user;-    if (auto v = env_value(env1))-        return *v;-    if (auto v = env_value(env2))-        return *v;-    return "unknown";-}--Sig identity_signature(const fs::path& repo_root) {-    Sig sig;-    sig.name = first_config(repo_root, "user.name", true, "GIT_AUTHOR_NAME", "USER");-    sig.email = first_config(repo_root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL");-#if defined(_WIN32)-    if (sig.name == "unknown") {-        if (auto v = env_value("USERNAME"))-            sig.name = *v;-    }-#endif-    sig.seconds = unix_now_seconds();-    sig.tz_min = 0;-    return sig;-}---IgnoreRules ignore_empty() {-    return {};-}--static std::optional<std::string_view> relative_to(std::string_view base, std::string_view path) {-    if (base.empty())-        return path;-    if (path.size() <= base.size())-        return std::nullopt;-    if (path.substr(0, base.size()) != base)-        return std::nullopt;-    if (path[base.size()] != '/')-        return std::nullopt;-    return path.substr(base.size() + 1);-}--static void add_ignore_line(IgnoreRules& rules, std::string_view base, std::string_view input) {-    std::string_view line = trim_view(input);-    if (line.empty() || line.front() == '#')-        return;-    bool negated = false;-    std::size_t start = 0;-    if (line.front() == '!') {-        negated = true;-        start = 1;-    }-    if (start >= line.size())-        return;-    std::size_t end = line.size();-    bool dir_only = false;-    if (line[end - 1] == '/') {-        dir_only = true;-        --end;-    }-    if (start >= end)-        return;-    bool anchored = false;-    if (line[start] == '/') {-        anchored = true;-        ++start;-    }-    if (start >= end)-        return;-    const std::string_view pattern = line.substr(start, end - start);-    const bool has_slash = pattern.find('/') != std::string_view::npos;-    rules.items.push_back(IgnoreRule{std::string(pattern), negated, dir_only, anchored, has_slash,-                                     std::string(base)});-}--void ignore_load_file(IgnoreRules& rules, const fs::path& repo_root, std::string_view base,-                      std::string_view name) {-    const fs::path dir = base.empty() ? repo_root : repo_root / path_from_bytes(base);-    const auto data = read_file_opt(dir / path_from_bytes(name));-    if (!data)-        return;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        add_ignore_line(rules, base, text.substr(start, end - start));-        if (end == text.size())-            break;-        start = end + 1;-    }-}--void ignore_load_root(IgnoreRules& rules, const fs::path& repo_root) {-    ignore_load_file(rules, repo_root, "", ".vnexclude");-    ignore_load_file(rules, repo_root, "", ".gitignore");-}--struct GlobState {-    std::size_t pi = 0;-    std::size_t ti = 0;-};--// Wildcards backtrack, so the naive implementation recursed once per possible-// match and could exhaust the stack on a hostile pattern. Walk the same state-// graph with an explicit stack and a work budget instead.-static bool glob_here(std::string_view pattern, std::size_t pi, std::string_view text,-                      std::size_t ti) {-    constexpr std::size_t max_work = 1'000'000;-    std::vector<GlobState> stack;-    std::size_t work = 0;-    auto push = [&](GlobState state) -> bool {-        if (work >= max_work)-            return false;-        ++work;-        stack.push_back(state);-        return true;-    };-    if (!push(GlobState{pi, ti}))-        return false;-    while (!stack.empty()) {-        const GlobState state = stack.back();-        stack.pop_back();-        const std::size_t p = state.pi;-        const std::size_t t = state.ti;-        if (p >= pattern.size()) {-            if (t >= text.size())-                return true;-            continue;-        }-        const char pc = pattern[p];-        if (pc == '*') {-            const bool dbl = p + 1 < pattern.size() && pattern[p + 1] == '*';-            if (dbl) {-                const std::size_t next = p + 2;-                if (next < pattern.size() && pattern[next] == '/') {-                    const std::size_t after = next + 1;-                    std::size_t j = t;-                    for (;;) {-                        if (!push(GlobState{after, j}))-                            return false;-                        if (j >= text.size())-                            break;-                        if (text[j] == '/') {-                            ++j;-                            continue;-                        }-                        ++j;-                        while (j < text.size() && text[j] != '/')-                            ++j;-                    }-                } else {-                    for (std::size_t j = t;; ++j) {-                        if (!push(GlobState{next, j}))-                            return false;-                        if (j >= text.size())-                            break;-                    }-                }-            } else {-                for (std::size_t j = t;; ++j) {-                    if (!push(GlobState{p + 1, j}))-                        return false;-                    if (j >= text.size() || text[j] == '/')-                        break;-                }-            }-            continue;-        }-        if (t >= text.size())-            continue;-        if (pc == '?') {-            if (text[t] != '/')-                (void)push(GlobState{p + 1, t + 1});-            continue;-        }-        if (pc == text[t])-            (void)push(GlobState{p + 1, t + 1});-    }-    return false;-}--bool glob_match(std::string_view pattern, std::string_view text) {-    return glob_here(pattern, 0, text, 0);-}--static bool rule_matches(const IgnoreRule& rule, std::string_view path, bool is_dir) {-    const auto rel_opt = relative_to(rule.base, path);-    if (!rel_opt)-        return false;-    const std::string_view rel = *rel_opt;-    if (rel.empty())-        return false;-    if (rule.dir_only && !is_dir)-        return false;-    if (!rule.has_slash && !rule.anchored) {-        std::size_t start = 0;-        for (;;) {-            std::size_t end = rel.find('/', start);-            if (end == std::string_view::npos)-                end = rel.size();-            if (glob_here(rule.pattern, 0, rel.substr(start, end - start), 0))-                return true;-            if (end >= rel.size())-                break;-            start = end + 1;-        }-        return false;-    }-    return glob_here(rule.pattern, 0, rel, 0);-}--bool ignore_ignored(const IgnoreRules& rules, std::string_view path, bool is_dir) {-    bool ignored = false;-    for (const auto& rule : rules.items) {-        if (rule_matches(rule, path, is_dir))-            ignored = !rule.negated;-    }-    return ignored;-}--bool ignore_path_ignored(const fs::path& repo_root, std::string_view path) {-    IgnoreRules rules = ignore_empty();-    ignore_load_root(rules, repo_root);-    for (std::size_t i = 0; i < path.size(); ++i) {-        if (path[i] == '/') {-            const std::string_view base = path.substr(0, i);-            ignore_load_file(rules, repo_root, base, ".vnexclude");-            ignore_load_file(rules, repo_root, base, ".gitignore");-        }-    }-    bool result = false;-    for (std::size_t j = 0; j < path.size(); ++j) {-        if (path[j] == '/') {-            if (ignore_ignored(rules, path.substr(0, j), true)) {-                result = true;-                break;-            }-        }-    }-    if (!result)-        result = ignore_ignored(rules, path, false);-    return result;-}--} // namespace vn--- a/xveins/src/core/common.h+++ /dev/null@@ -1,499 +0,0 @@-#pragma once--#include <array>-#include <chrono>-#include <cstdint>-#include <cstdio>-#include <cstring>-#include <filesystem>-#include <map>-#include <mutex>-#include <optional>-#include <span>-#include <string>-#include <string_view>-#include <system_error>-#include <variant>-#include <vector>--#if __has_include(<expected>)-#include <expected>-#endif--#include <blake3.h>--namespace vn {--namespace fs = std::filesystem;--using Bytes = std::span<const std::uint8_t>;-using MutBytes = std::span<std::uint8_t>;-using Id = std::array<std::uint8_t, 32>;-using ChangeId = std::array<std::uint8_t, 16>;--constexpr std::size_t ID_LEN = 32;-constexpr std::size_t CHANGE_ID_LEN = 16;-constexpr std::size_t MAX_NAME_LEN = 4096;-constexpr std::size_t MAX_PATH_LEN = 65536;-constexpr std::size_t MAX_MESSAGE_LEN = 16u * 1024u * 1024u;-constexpr std::size_t MAX_OBJECT_BODY = 64u * 1024u * 1024u;-constexpr std::size_t MAX_CHUNK_LEN = 256u * 1024u;-constexpr std::size_t MAX_MANIFEST_ENTRIES = 1024;-constexpr std::size_t MAX_TREE_ENTRIES = 1'000'000;-constexpr std::size_t MAX_CONFLICT_TERMS = 64;-constexpr std::size_t INLINE_THRESHOLD = 16u * 1024u;-// Bound recursive tree walks so a hostile tree cannot exhaust the stack.-constexpr std::size_t MAX_TREE_DEPTH = 512;-// Packs are read into memory; refuse absurdly large ones instead of relying on-// an allocation failure.-constexpr std::uint64_t MAX_STORE_PACK_BYTES = 8ull * 1024ull * 1024ull * 1024ull;--enum class ErrorKind {-    None,-    UnexpectedEnd,-    VarintOverflow,-    NonMinimalVarint,-    InvalidValue,-    LimitExceeded,-    InvalidName,-    Duplicate,-    Unsorted,-    TrailingBytes,-    UnsupportedVersion,-    InvalidMagic,-    HashMismatch,-    Corrupt,-    Io,-    Usage,-};--std::string_view error_kind_name(ErrorKind kind);--struct Error {-    ErrorKind kind = ErrorKind::None;-    std::size_t offset = 0;-    std::string message;--    Error() = default;-    Error(ErrorKind k, std::size_t off, std::string msg)-        : kind(k), offset(off), message(std::move(msg)) {}--    static Error decode(ErrorKind kind, std::size_t offset);-    static Error io(std::string message);-    static Error usage(std::string message);-};--#if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L-template <typename T> using Result = std::expected<T, Error>;-template <typename E> using Unexpected = std::unexpected<E>;-#else-template <typename E> struct Unexpected {-    E err;-    explicit Unexpected(E value) : err(std::move(value)) {}-};--template <typename T, typename E> class Expected {-public:-    Expected(T&& value) : data_(std::in_place_index<0>, std::move(value)) {}-    Expected(const T& value) : data_(std::in_place_index<0>, value) {}-    Expected(Unexpected<E> value) : data_(std::in_place_index<1>, std::move(value.err)) {}--    [[nodiscard]] bool has_value() const {-        return data_.index() == 0;-    }-    explicit operator bool() const {-        return has_value();-    }-    T& operator*() {-        return std::get<0>(data_);-    }-    const T& operator*() const {-        return std::get<0>(data_);-    }-    T* operator->() {-        return &std::get<0>(data_);-    }-    const T* operator->() const {-        return &std::get<0>(data_);-    }-    T& value() {-        return std::get<0>(data_);-    }-    const T& value() const {-        return std::get<0>(data_);-    }-    E& error() {-        return std::get<1>(data_);-    }-    const E& error() const {-        return std::get<1>(data_);-    }--private:-    std::variant<T, E> data_;-};--template <typename E> class Expected<void, E> {-public:-    Expected() = default;-    Expected(Unexpected<E> value) : error_(std::move(value.err)) {}-    [[nodiscard]] bool has_value() const {-        return !error_.has_value();-    }-    explicit operator bool() const {-        return has_value();-    }-    E& error() {-        return *error_;-    }-    const E& error() const {-        return *error_;-    }--private:-    std::optional<E> error_;-};--template <typename T> using Result = Expected<T, Error>;-#endif--using Status = Result<void>;--inline Unexpected<Error> unexpected(Error error) {-    return Unexpected<Error>(std::move(error));-}-inline Status ok() {-    return {};-}-inline Unexpected<Error> fail(ErrorKind kind, std::size_t offset = 0) {-    return unexpected(Error::decode(kind, offset));-}-inline Unexpected<Error> fail_io(std::string message) {-    return unexpected(Error::io(std::move(message)));-}-inline Unexpected<Error> fail_usage(std::string message) {-    return unexpected(Error::usage(std::move(message)));-}---inline Bytes bytes_of(std::string_view s) {-    return Bytes(reinterpret_cast<const std::uint8_t*>(s.data()), s.size());-}-inline Bytes bytes_of(const std::vector<std::uint8_t>& v) {-    return Bytes(v.data(), v.size());-}-inline std::string_view str_of(Bytes b) {-    return std::string_view(reinterpret_cast<const char*>(b.data()), b.size());-}-inline std::string to_string(Bytes b) {-    return std::string(str_of(b));-}-inline bool equals(Bytes a, Bytes b) {-    return a.size() == b.size() && (a.empty() || std::memcmp(a.data(), b.data(), a.size()) == 0);-}-inline int compare(Bytes a, Bytes b) {-    const std::size_t n = std::min(a.size(), b.size());-    if (n != 0) {-        const int c = std::memcmp(a.data(), b.data(), n);-        if (c != 0)-            return c < 0 ? -1 : 1;-    }-    if (a.size() < b.size())-        return -1;-    if (a.size() > b.size())-        return 1;-    return 0;-}-inline bool ascii_iequals(Bytes a, Bytes b) {-    if (a.size() != b.size())-        return false;-    for (std::size_t i = 0; i < a.size(); ++i) {-        auto lower = [](std::uint8_t c) -> std::uint8_t {-            return (c >= 'A' && c <= 'Z') ? static_cast<std::uint8_t>(c + 32) : c;-        };-        if (lower(a[i]) != lower(b[i]))-            return false;-    }-    return true;-}-inline bool starts_with(Bytes value, Bytes prefix) {-    return value.size() >= prefix.size() && equals(value.first(prefix.size()), prefix);-}--std::string hex_encode(Bytes data);-std::string hex_encode(const Id& id);-bool hex_decode(std::string_view text, MutBytes out);-std::optional<Id> parse_id(std::string_view hex);-std::string base32_encode(const ChangeId& id);-bool base32_prefix_matches(std::string_view full, std::string_view prefix);---std::array<std::uint8_t, 32> blake3_hash(Bytes data);-Id object_id(std::uint8_t type_byte, Bytes body);-std::array<std::uint8_t, 16> random_change_id();-std::uint64_t random_u64();---class Reader {-public:-    explicit Reader(Bytes data) : data_(data) {}--    [[nodiscard]] std::size_t offset() const {-        return pos_;-    }-    [[nodiscard]] std::size_t remaining() const {-        return data_.size() - pos_;-    }-    [[nodiscard]] bool at_end() const {-        return pos_ >= data_.size();-    }--    Result<std::uint8_t> u8();-    Result<std::uint16_t> u16le();-    Result<std::uint32_t> u32le();-    Result<std::uint64_t> u64le();-    Result<std::int16_t> i16le();-    Result<std::int64_t> i64le();-    Result<std::uint64_t> varint();-    Result<Bytes> raw(std::size_t n);-    Result<Bytes> bytes(std::size_t max_len);-    Result<std::string> string_bytes(std::size_t max_len);-    Result<std::size_t> list_len(std::size_t max);-    Result<Id> id();-    Result<std::optional<Id>> opt_id();-    Result<void> finish();--    struct Sig {-        std::string name;-        std::string email;-        std::int64_t seconds = 0;-        std::int16_t tz_min = 0;-    };-    struct TimeMs {-        std::int64_t ms = 0;-        std::int16_t tz_min = 0;-    };--    Result<Sig> sig(std::size_t max_name, std::size_t max_email);-    Result<TimeMs> time_ms();--    static std::uint64_t read_u64le_at(Bytes data, std::size_t off);--private:-    Bytes data_;-    std::size_t pos_ = 0;-};--class ByteWriter {-public:-    explicit ByteWriter(std::size_t reserve = 64) {-        buf_.reserve(reserve);-    }--    void u8(std::uint8_t v);-    void u16le(std::uint16_t v);-    void u32le(std::uint32_t v);-    void u64le(std::uint64_t v);-    void i16le(std::int16_t v);-    void i64le(std::int64_t v);-    void varint(std::uint64_t v);-    void raw(Bytes data);-    void raw(std::string_view s) {-        raw(bytes_of(s));-    }-    void bytes(std::string_view s) {-        raw(s);-    }-    void length_prefixed(std::string_view s);-    void length_prefixed(Bytes b);-    void id(const Id& id);-    void opt_id(const std::optional<Id>& id);-    void sig(const Reader::Sig& s);-    void time_ms(const Reader::TimeMs& t);--    [[nodiscard]] Bytes view() const {-        return Bytes(buf_.data(), buf_.size());-    }-    [[nodiscard]] const std::vector<std::uint8_t>& data() const {-        return buf_;-    }-    [[nodiscard]] std::vector<std::uint8_t> take() {-        return std::move(buf_);-    }-    [[nodiscard]] std::size_t size() const {-        return buf_.size();-    }-    void clear() {-        buf_.clear();-    }-    void append(Bytes b) {-        raw(b);-    }-    void reserve(std::size_t n) {-        buf_.reserve(n);-    }--private:-    std::vector<std::uint8_t> buf_;-};---std::string format_utc(std::int64_t seconds);-std::int64_t unix_now_seconds();-std::int64_t unix_now_millis();-std::size_t available_cpu_count();--enum class Color {-    Default,-    Black,-    Red,-    Green,-    Yellow,-    Blue,-    Magenta,-    Cyan,-    BrightBlack,-    BrightRed,-    BrightGreen,-    BrightYellow,-    BrightBlue,-    BrightMagenta,-    BrightCyan,-    BrightWhite,-};--bool colors_enabled();-void print_colored(std::string_view text, Color color, bool dim = false, bool to_stderr = false);-void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr = false);-void print_bold(std::string_view text, Color fg, bool to_stderr = false);-void error_prefix();-void warning_prefix();-void info_prefix();--// A lightweight, throttled progress bar drawn on stderr. It stays silent when-// stderr is not a terminal, so piped output is unchanged.-class Progress {-public:-    explicit Progress(std::string label, std::size_t total = 0);-    Progress(const Progress&) = delete;-    Progress& operator=(const Progress&) = delete;-    ~Progress();--    void set_total(std::size_t total);-    void update(std::size_t done, bool force = false);-    void advance(std::size_t amount = 1);-    void finish();-    void clear();--private:-    void refresh_locked(bool force);-    void draw_locked();--    std::mutex mutex_;-    std::string label_;-    std::size_t total_ = 0;-    std::size_t done_ = 0;-    std::size_t last_done_ = 0;-    std::size_t last_total_ = 0;-    bool enabled_ = false;-    bool drawn_ = false;-    bool finished_ = false;-    std::chrono::steady_clock::time_point last_draw_{};-};---fs::path path_from_bytes(std::string_view bytes);-std::string path_to_bytes(const fs::path& p);-std::string path_display(const fs::path& p);--Result<std::vector<std::uint8_t>> read_file(const fs::path& p, std::uint64_t max_size = 0);-std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p,-                                                       std::uint64_t max_size = 0);-std::optional<std::vector<std::uint8_t>> read_file_range(const fs::path& p, std::uint64_t offset,-                                                         std::size_t length);-bool write_file(const fs::path& p, Bytes data);-bool append_file(const fs::path& p, Bytes data);-bool write_atomic(const fs::path& final_path, Bytes data);-bool write_atomic(const fs::path& tmp_path, const fs::path& final_path, Bytes data);-bool ensure_directory(const fs::path& p);-bool remove_file(const fs::path& p);-bool remove_tree(const fs::path& p);-bool path_exists(const fs::path& p);-bool path_is_dir(const fs::path& p);-bool path_is_file(const fs::path& p);-bool path_is_symlink(const fs::path& p);-std::optional<std::uint64_t> path_file_size(const fs::path& p);-std::optional<std::uint64_t> file_mtime_ns(const fs::path& p);-std::optional<std::uint64_t> file_inode(const fs::path& p);-bool is_executable(const fs::path& p);-std::optional<std::string> path_read_symlink(const fs::path& p);-std::vector<std::string> list_directory(const fs::path& p);-bool same_or_under(const fs::path& child, const fs::path& parent);-std::string basename_string(const fs::path& p);--struct StatInfo {-    std::uint8_t kind = 0; // 0 missing, 1 file, 2 directory, 3 symlink-    bool executable = false;-    std::uint64_t size = 0;-    std::uint64_t mtime_ns = 0;-    std::uint64_t inode = 0;-};-std::optional<StatInfo> stat_path(const fs::path& p);---std::optional<std::string> repo_config_value(const fs::path& repo_root, std::string_view key);-bool repo_config_set(const fs::path& repo_root, std::string_view key, std::string_view value);-bool repo_config_remove(const fs::path& repo_root, std::string_view key);-bool repo_config_bool(const fs::path& repo_root, std::string_view key, bool fallback);--struct Sig {-    std::string name;-    std::string email;-    std::int64_t seconds = 0;-    std::int16_t tz_min = 0;-};--Sig identity_signature(const fs::path& repo_root);-std::optional<std::string> user_config_author_name();-std::optional<std::string> user_config_author_email();-std::optional<std::string> user_config_value(std::string_view key);-std::map<std::string, std::string> user_config_entries();-bool user_config_set(std::string_view key, std::string_view value);-bool user_config_remove(std::string_view key);--std::string editor_command(const fs::path& repo_root);-bool run_editor(const fs::path& repo_root, const std::vector<std::string>& paths,-                const std::optional<fs::path>& message_file = std::nullopt);-bool stdin_is_terminal();-bool stdout_is_terminal();-bool stderr_is_terminal();-std::string pager_command(const fs::path& repo_root);-bool run_pager(const fs::path& repo_root, std::string_view text);--std::optional<std::string> current_bookmark_name(const fs::path& repo_root);-bool set_current_bookmark(const fs::path& repo_root, std::string_view name);-bool clear_current_bookmark(const fs::path& repo_root);---struct IgnoreRule {-    std::string pattern;-    bool negated = false;-    bool dir_only = false;-    bool anchored = false;-    bool has_slash = false;-    std::string base;-};--struct IgnoreRules {-    std::vector<IgnoreRule> items;-};--IgnoreRules ignore_empty();-void ignore_load_file(IgnoreRules& rules, const fs::path& repo_root, std::string_view base,-                      std::string_view name);-void ignore_load_root(IgnoreRules& rules, const fs::path& repo_root);-bool ignore_ignored(const IgnoreRules& rules, std::string_view path, bool is_dir);-bool ignore_path_ignored(const fs::path& repo_root, std::string_view path);-bool glob_match(std::string_view pattern, std::string_view text);--} // namespace vn--- a/xveins/src/crypto/crypto.cpp+++ /dev/null@@ -1,201 +0,0 @@-#include "crypto/crypto.h"--#include <blake3.h>--#include <openssl/evp.h>-#include <openssl/rand.h>--#include <cstring>--namespace vn {--namespace {--// The reference implementation hashes the NUL terminator as well, so the-// domain is 12 bytes rather than the 11 characters in the specification.-constexpr char FINGERPRINT_DOMAIN[] = "veins/key/1";--PublicKey key_from_span(Bytes seed) {-    PublicKey out{};-    std::memcpy(out.data(), seed.data(), out.size());-    return out;-}--} // namespace--std::optional<PublicKey> ed25519_public_from_seed(Bytes seed) {-    if (seed.size() != 32)-        return std::nullopt;-    EVP_PKEY* pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);-    if (!pkey)-        return std::nullopt;-    PublicKey out{};-    std::size_t len = out.size();-    const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);-    EVP_PKEY_free(pkey);-    if (ok != 1 || len != out.size())-        return std::nullopt;-    return out;-}--std::optional<Signature> ed25519_sign(Bytes seed, Bytes message) {-    if (seed.size() != 32)-        return std::nullopt;-    EVP_PKEY* pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);-    if (!pkey)-        return std::nullopt;-    EVP_MD_CTX* ctx = EVP_MD_CTX_new();-    if (!ctx) {-        EVP_PKEY_free(pkey);-        return std::nullopt;-    }-    Signature out{};-    std::size_t sig_len = out.size();-    bool ok = false;-    if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&-        EVP_DigestSign(ctx, out.data(), &sig_len, message.data(), message.size()) == 1 &&-        sig_len == out.size()) {-        ok = true;-    }-    EVP_MD_CTX_free(ctx);-    EVP_PKEY_free(pkey);-    if (!ok)-        return std::nullopt;-    return out;-}--bool ed25519_verify(const PublicKey& public_key, Bytes message, Bytes signature) {-    if (signature.size() != 64)-        return false;-    EVP_PKEY* pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key.data(),-                                                 public_key.size());-    if (!pkey)-        return false;-    EVP_MD_CTX* ctx = EVP_MD_CTX_new();-    if (!ctx) {-        EVP_PKEY_free(pkey);-        return false;-    }-    bool ok = false;-    if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&-        EVP_DigestVerify(ctx, signature.data(), signature.size(), message.data(), message.size()) ==-            1) {-        ok = true;-    }-    EVP_MD_CTX_free(ctx);-    EVP_PKEY_free(pkey);-    return ok;-}--FingerprintBytes key_fingerprint_bytes(const PublicKey& public_key) {-    blake3_hasher hasher;-    blake3_hasher_init(&hasher);-    blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN, sizeof(FINGERPRINT_DOMAIN));-    blake3_hasher_update(&hasher, public_key.data(), public_key.size());-    std::array<std::uint8_t, 32> digest{};-    blake3_hasher_finalize(&hasher, digest.data(), digest.size());-    FingerprintBytes out{};-    std::memcpy(out.data(), digest.data(), out.size());-    return out;-}--std::string key_fingerprint(const PublicKey& public_key) {-    const auto raw = key_fingerprint_bytes(public_key);-    return base32_text(Bytes(raw.data(), raw.size()));-}--std::string base32_text(Bytes raw) {-    static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";-    std::string out;-    out.reserve((raw.size() * 8) / 5 + 2);-    std::uint64_t bits = 0;-    std::size_t nbits = 0;-    for (std::uint8_t byte : raw) {-        bits = (bits << 8) | byte;-        nbits += 8;-        while (nbits >= 5) {-            nbits -= 5;-            out.push_back(alphabet[(bits >> nbits) & 31u]);-        }-    }-    if (nbits > 0)-        out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);-    return out;-}--std::string base64url_encode(Bytes raw) {-    static constexpr char alphabet[] =-        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";-    std::string out;-    out.reserve((raw.size() * 4) / 3 + 4);-    std::uint32_t acc = 0;-    std::size_t bits = 0;-    for (std::uint8_t byte : raw) {-        acc = (acc << 8) | byte;-        bits += 8;-        while (bits >= 6) {-            bits -= 6;-            out.push_back(alphabet[(acc >> bits) & 63u]);-        }-    }-    if (bits > 0)-        out.push_back(alphabet[(acc << (6 - bits)) & 63u]);-    return out;-}--std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text) {-    if (text.empty())-        return std::nullopt;-    static const auto value_of = [](char c) -> int {-        if (c >= 'A' && c <= 'Z')-            return c - 'A';-        if (c >= 'a' && c <= 'z')-            return c - 'a' + 26;-        if (c >= '0' && c <= '9')-            return c - '0' + 52;-        if (c == '-')-            return 62;-        if (c == '_')-            return 63;-        return -1;-    };-    std::vector<std::uint8_t> out;-    out.reserve((text.size() * 6) / 8);-    std::uint32_t acc = 0;-    std::size_t bits = 0;-    for (char c : text) {-        const int value = value_of(c);-        if (value < 0)-            return std::nullopt;-        acc = (acc << 6) | static_cast<std::uint32_t>(value);-        bits += 6;-        if (bits >= 8) {-            bits -= 8;-            out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));-        }-    }-    return out;-}--std::string format_public_key(const PublicKey& public_key) {-    return "ed25519:" + base64url_encode(Bytes(public_key.data(), public_key.size()));-}--std::optional<PublicKey> parse_public_key(std::string_view text) {-    constexpr std::string_view prefix = "ed25519:";-    if (!text.starts_with(prefix))-        return std::nullopt;-    auto decoded = base64url_decode(text.substr(prefix.size()));-    if (!decoded || decoded->size() != 32)-        return std::nullopt;-    return key_from_span(Bytes(decoded->data(), decoded->size()));-}--std::vector<std::uint8_t> secure_random(std::size_t count) {-    std::vector<std::uint8_t> out(count);-    if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)-        out.clear();-    return out;-}--} // namespace vn--- a/xveins/src/crypto/crypto.h+++ /dev/null@@ -1,35 +0,0 @@-#pragma once--#include "core/common.h"--#include <array>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn {--using PublicKey = std::array<std::uint8_t, 32>;-using Signature = std::array<std::uint8_t, 64>;-using FingerprintBytes = std::array<std::uint8_t, 16>;--std::optional<PublicKey> ed25519_public_from_seed(Bytes seed);-std::optional<Signature> ed25519_sign(Bytes seed, Bytes message);-bool ed25519_verify(const PublicKey& public_key, Bytes message, Bytes signature);--FingerprintBytes key_fingerprint_bytes(const PublicKey& public_key);-std::string key_fingerprint(const PublicKey& public_key);--// RFC 4648 base32 with no padding. The reference implementation emits-// fingerprints in uppercase, so this matches it.-std::string base32_text(Bytes raw);-std::string base64url_encode(Bytes raw);-std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text);--std::string format_public_key(const PublicKey& public_key);-std::optional<PublicKey> parse_public_key(std::string_view text);--std::vector<std::uint8_t> secure_random(std::size_t count);--} // namespace vn--- a/xveins/src/git/git.cpp+++ /dev/null@@ -1,2063 +0,0 @@-#include "git/git.h"--#include "git/git_internal.h"--#include "worktree/worktree.h"--#include <algorithm>-#include <cstdlib>-#include <iostream>-#include <map>-#include <set>-#include <string_view>--#if !defined(_WIN32)-#include <sys/wait.h>-#endif--namespace vn {--namespace {--using git::IdMap;-using git::Kind;-using git::Oid;-using git::OidLess;-using git::ParsedCommit;--struct OidHash {-    std::size_t operator()(const Oid& oid) const {-        std::size_t h = 1469598103934665603ull;-        for (auto b : oid) {-            h ^= b;-            h *= 1099511628211ull;-        }-        return h;-    }-};--struct NamedTarget {-    std::string name;-    Oid oid{};-};--struct CommitRecord {-    Oid oid{};-    std::vector<std::uint8_t> body;-    ParsedCommit parsed;-};--bool working_tree_empty(const fs::path& root) {-    for (const auto& name : list_directory(root)) {-        if (name != ".veins")-            return false;-    }-    return true;-}--ChangeId derive_change_id(const Oid& oid) {-    std::string input = "veins/change";-    input.append(reinterpret_cast<const char*>(oid.data()), oid.size());-    const auto hash = blake3_hash(bytes_of(input));-    ChangeId out{};-    std::memcpy(out.data(), hash.data(), out.size());-    return out;-}--std::optional<Oid> peel_to_commit(git::Repo& repo, const Oid& start) {-    Oid current = start;-    for (std::size_t i = 0; i < 4096; ++i) {-        auto object = git::read_object(repo, current);-        if (!object)-            return std::nullopt;-        if (object->kind == git::KIND_COMMIT)-            return current;-        if (object->kind != git::KIND_TAG)-            return std::nullopt;-        auto tag = git::parse_tag(Bytes(object->body.data(), object->body.size()));-        if (!tag)-            return std::nullopt;-        current = tag->target;-    }-    return std::nullopt;-}--void set_bookmark(View& view, std::string_view name, const Id& id) {-    for (auto& bookmark : view.bookmarks) {-        if (bookmark.name == name) {-            bookmark.targets.adds = {id};-            bookmark.targets.removes.clear();-            return;-        }-    }-    Bookmark bookmark;-    bookmark.name = std::string(name);-    bookmark.targets.adds = {id};-    view.bookmarks.push_back(std::move(bookmark));-}--void set_tag(View& view, std::string_view name, const Id& id) {-    for (auto& tag : view.tags) {-        if (tag.name == name) {-            tag.target = id;-            return;-        }-    }-    view.tags.push_back(TagRef{std::string(name), id});-}--void set_remote_ref(View& view, std::string_view remote, std::string_view name, const Id& id) {-    for (auto& ref : view.remote_refs) {-        if (ref.remote == remote && ref.name == name) {-            ref.target = id;-            return;-        }-    }-    view.remote_refs.push_back(RemoteRef{std::string(remote), std::string(name), id});-}--std::pair<std::string, std::string> split_remote(std::string_view full) {-    const std::size_t slash = full.find('/');-    if (slash == std::string_view::npos)-        return {std::string(full), "main"};-    return {std::string(full.substr(0, slash)), std::string(full.substr(slash + 1))};-}--int create_working_copy(const fs::path& root, const Id& parent) {-    Store store = Store::open_all(root);-    auto tx = Txn::begin(root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    auto loaded = load_commit(tx->store(), parent);-    if (!loaded) {-        error_prefix();-        std::cout << "cannot read imported commit\n";-        return 1;-    }-    Commit commit;-    commit.version = 1;-    commit.parents = {parent};-    commit.root_tree = loaded->commit.root_tree;-    commit.change_id = random_change_id();-    commit.author = identity_signature(root);-    commit.committer = commit.author;-    commit.renames_state = RENAMES_RECORDED;-    const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));-    remove_head(tx->view(), parent);-    set_workspace(tx->view(), new_id);-    rebuild_heads(tx->view());-    auto status = tx->finish("import");-    if (!status)-        return 1;-    store.refresh(root);-    return 0;-}--int materialize_working_copy(const fs::path& root, Store& store) {-    store.refresh(root);-    auto view = current_view(root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    const auto wc = working_copy_id(*view);-    if (!wc)-        return 0;-    auto body = store.read_body(*wc, TYPE_COMMIT);-    if (!body)-        return 1;-    auto commit = decode_commit(bytes_of(*body));-    if (!commit)-        return 1;-    Progress progress("checking out files");-    const int status =-        checkout_materialize_commit(root, store, std::nullopt, commit->root_tree, &progress);-    if (status == 0)-        progress.finish();-    return status;-}--std::vector<Id> ordered_commits(Store& store, const std::vector<Id>& roots) {-    struct Mark {-        Id id{};-        bool expanded = false;-    };-    std::vector<Mark> stack;-    for (const auto& id : roots)-        stack.push_back(Mark{id, false});-    std::set<Id> visited;-    std::vector<Id> ordered;-    while (!stack.empty()) {-        Mark mark = stack.back();-        stack.pop_back();-        if (visited.count(mark.id))-            continue;-        if (!mark.expanded) {-            mark.expanded = true;-            stack.push_back(mark);-            if (auto loaded = load_commit(store, mark.id)) {-                for (auto it = loaded->commit.parents.rbegin(); it != loaded->commit.parents.rend();-                     ++it) {-                    if (!visited.count(*it))-                        stack.push_back(Mark{*it, false});-                }-            }-        } else {-            visited.insert(mark.id);-            ordered.push_back(mark.id);-        }-    }-    return ordered;-}--std::optional<Id> exportable_target(Store& store, const Id& start) {-    Id current = start;-    for (std::size_t steps = 0; steps < 100000; ++steps) {-        auto loaded = load_commit(store, current);-        if (!loaded)-            return std::nullopt;-        if (!tree_conflicted(store, loaded->commit.root_tree))-            return current;-        if (loaded->commit.parents.empty())-            return std::nullopt;-        current = loaded->commit.parents.front();-    }-    return std::nullopt;-}--struct MaterializeCtx {-    const fs::path& root;-    Store& store;-    Writer& writer;-    std::map<Id, Id> trees;-    std::map<Id, Id> blobs;-    std::map<Id, Id> commits;-    std::map<Id, Id> conflicts;-    std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;-    std::size_t new_commits = 0;-    std::size_t new_trees = 0;-    std::size_t new_blobs = 0;-    bool changed = false;-};--std::optional<Id> materialize_blob(MaterializeCtx& ctx, const Id& old_id) {-    auto existing = ctx.blobs.find(old_id);-    if (existing != ctx.blobs.end())-        return existing->second;-    const auto oid = git::lazy_blob_oid(old_id);-    if (!oid) {-        ctx.blobs[old_id] = old_id;-        return old_id;-    }-    auto data = git_read_lazy_blob(ctx.root, old_id);-    if (!data)-        return std::nullopt;-    BlobBuild build = build_blob(bytes_of(*data));-    if (build.root == Id{})-        return std::nullopt;-    for (auto& object : build.objects) {-        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));-        (void)ctx.writer.add_known(object.type, id, std::move(object.body));-    }-    ctx.blobs[old_id] = build.root;-    ++ctx.new_blobs;-    ctx.changed = true;-    return build.root;-}--std::optional<Id> materialize_tree(MaterializeCtx& ctx, const Id& old_id, std::size_t depth);--std::optional<Id> materialize_conflict(MaterializeCtx& ctx, const Id& old_id, std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return std::nullopt;-    auto existing = ctx.conflicts.find(old_id);-    if (existing != ctx.conflicts.end())-        return existing->second;-    auto body = ctx.store.read_body(old_id, TYPE_CONFLICT);-    if (!body)-        return std::nullopt;-    auto conflict = decode_conflict(bytes_of(*body));-    if (!conflict)-        return std::nullopt;-    bool changed = false;-    auto rewire = [&](ConflictValue& value) -> bool {-        if (!value.target)-            return true;-        if (value.kind == KIND_FILE || value.kind == KIND_EXECUTABLE ||-            value.kind == KIND_SYMLINK) {-            if (!is_lazy_blob(*value.target))-                return true;-            auto mapped = materialize_blob(ctx, *value.target);-            if (!mapped)-                return false;-            if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {-                value.target = *mapped;-                changed = true;-            }-            return true;-        }-        if (value.kind == KIND_SUBTREE) {-            auto mapped = materialize_tree(ctx, *value.target, depth + 1);-            if (!mapped)-                return false;-            if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {-                value.target = *mapped;-                changed = true;-            }-            return true;-        }-        if (value.kind == KIND_CONFLICT) {-            auto mapped = materialize_conflict(ctx, *value.target, depth + 1);-            if (!mapped)-                return false;-            if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {-                value.target = *mapped;-                changed = true;-            }-            return true;-        }-        return true;-    };-    for (auto& value : conflict->adds) {-        if (!rewire(value))-            return std::nullopt;-    }-    for (auto& value : conflict->removes) {-        if (!rewire(value))-            return std::nullopt;-    }-    if (!changed) {-        ctx.conflicts[old_id] = old_id;-        return old_id;-    }-    const Id new_id = ctx.writer.add(TYPE_CONFLICT, encode_conflict(*conflict));-    ctx.conflicts[old_id] = new_id;-    ctx.changed = true;-    return new_id;-}--std::optional<Id> materialize_tree(MaterializeCtx& ctx, const Id& old_id, std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return std::nullopt;-    auto existing = ctx.trees.find(old_id);-    if (existing != ctx.trees.end())-        return existing->second;-    auto body = ctx.store.read_body(old_id, TYPE_TREE);-    if (!body)-        return std::nullopt;-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-        return std::nullopt;-    bool changed = false;-    std::vector<TreeEntry> entries = tree->entries;-    for (auto& entry : entries) {-        std::optional<Id> mapped;-        if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||-            entry.kind == KIND_SYMLINK) {-            if (!is_lazy_blob(entry.target))-                continue;-            mapped = materialize_blob(ctx, entry.target);-        } else if (entry.kind == KIND_SUBTREE) {-            mapped = materialize_tree(ctx, entry.target, depth + 1);-        } else if (entry.kind == KIND_CONFLICT) {-            mapped = materialize_conflict(ctx, entry.target, depth + 1);-        } else if (entry.kind == KIND_SUBMODULE) {-            continue;-        } else {-            return std::nullopt;-        }-        if (!mapped)-            return std::nullopt;-        if (std::memcmp(mapped->data(), entry.target.data(), ID_LEN) != 0) {-            entry.target = *mapped;-            changed = true;-        }-    }-    if (!changed) {-        ctx.trees[old_id] = old_id;-        return old_id;-    }-    auto new_body = encode_tree(entries);-    if (!new_body)-        return std::nullopt;-    const Id new_id = ctx.writer.add(TYPE_TREE, *new_body);-    ctx.trees[old_id] = new_id;-    ++ctx.new_trees;-    ctx.changed = true;-    if (auto raw = git::load_raw(ctx.root, old_id))-        ctx.raw_saves.emplace_back(new_id, std::move(*raw));-    return new_id;-}--std::map<Id, git::Oid> reverse_git_map(const git::IdMap& map) {-    std::map<Id, git::Oid> out;-    for (const auto& item : map.items)-        out[item.second] = item.first;-    return out;-}--std::string shell_quote(std::string_view value) {-    std::string out;-    out.push_back('\'');-    for (char c : value) {-        if (c == '\'')-            out += "'\\''";-        else-            out.push_back(c);-    }-    out.push_back('\'');-    return out;-}--int run_git(const fs::path& dir, const std::vector<std::string>& args) {-    std::string command = "git -C ";-    command += shell_quote(path_to_bytes(dir));-    for (const auto& arg : args) {-        command.push_back(' ');-        command += shell_quote(arg);-    }-    const int rc = std::system(command.c_str());-    if (rc == -1)-        return -1;-#if !defined(_WIN32)-    if (WIFEXITED(rc))-        return WEXITSTATUS(rc);-    return 1;-#else-    return rc;-#endif-}--int run_git_capture(const fs::path& dir, const std::vector<std::string>& args, std::string& out) {-    const fs::path capture =-        fs::temp_directory_path() / ("vn-git-" + std::to_string(random_u64()) + ".out");-    std::string command = "git -C ";-    command += shell_quote(path_to_bytes(dir));-    for (const auto& arg : args) {-        command.push_back(' ');-        command += shell_quote(arg);-    }-    command += " > ";-    command += shell_quote(path_to_bytes(capture));-    const int rc = std::system(command.c_str());-    out.clear();-    if (auto data = read_file_opt(capture)) {-        out.assign(reinterpret_cast<const char*>(data->data()), data->size());-    }-    (void)remove_file(capture);-    if (rc == -1)-        return -1;-#if !defined(_WIN32)-    if (WIFEXITED(rc))-        return WEXITSTATUS(rc);-    return 1;-#else-    return rc;-#endif-}--bool configure_mirror(const fs::path& root, std::string_view remote, std::string_view url) {-    const fs::path dir = git_dir(root);-    if (!path_is_dir(dir))-        return false;-    std::string remotes;-    if (run_git_capture(dir, {"remote"}, remotes) != 0)-        return false;-    bool exists = false;-    std::size_t start = 0;-    while (start <= remotes.size()) {-        std::size_t end = remotes.find('\n', start);-        if (end == std::string::npos)-            end = remotes.size();-        std::string_view line(remotes.data() + start, end - start);-        if (!line.empty() && line.back() == '\r')-            line.remove_suffix(1);-        if (line == remote) {-            exists = true;-            break;-        }-        if (end == remotes.size())-            break;-        start = end + 1;-    }-    if (exists)-        return run_git(dir, {"remote", "set-url", std::string(remote), std::string(url)}) == 0;-    return run_git(dir, {"remote", "add", std::string(remote), std::string(url)}) == 0;-}--void add_unique(std::vector<Id>& ids, const Id& id) {-    if (!contains_id(ids, id))-        ids.push_back(id);-}--int import_tree_impl(Writer& writer, git::Repo& repo, IdMap& trees, IdMap& blobs, const Oid& oid,-                     std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,-                     std::size_t& new_trees, std::size_t& new_blobs, std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return 1;-    if (auto existing = trees.get(oid)) {-        (void)existing;-        return 0;-    }-    auto object = git::read_object(repo, oid);-    if (!object || object->kind != git::KIND_TREE)-        return 1;-    auto parsed = git::parse_tree(Bytes(object->body.data(), object->body.size()));-    if (!parsed)-        return 1;-    std::stable_sort(parsed->entries.begin(), parsed->entries.end(),-                     [](const git::RawTreeEntry& a, const git::RawTreeEntry& b) {-                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                     });-    std::vector<TreeEntry> entries;-    entries.reserve(parsed->entries.size());-    for (const auto& raw : parsed->entries) {-        const std::uint8_t kind = git::mode_kind(raw.mode);-        Id target{};-        if (kind == KIND_SUBTREE) {-            if (import_tree_impl(writer, repo, trees, blobs, raw.oid, raw_saves, new_trees,-                                 new_blobs, depth + 1) != 0)-                return 1;-            auto child = trees.get(raw.oid);-            if (!child)-                return 1;-            target = *child;-        } else if (kind == KIND_SUBMODULE) {-            std::memcpy(target.data(), raw.oid.data(), 20);-        } else {-            auto existing = blobs.get(raw.oid);-            if (existing) {-                target = *existing;-            } else {-                target = git::lazy_blob_id(raw.oid);-                blobs.put(raw.oid, target);-                ++new_blobs;-            }-        }-        entries.push_back(TreeEntry{raw.name, kind, target});-    }-    auto body = encode_tree(entries);-    if (!body)-        return 1;-    const Id id = writer.add(TYPE_TREE, *body);-    trees.put(oid, id);-    ++new_trees;-    if (!parsed->canonical)-        raw_saves.emplace_back(id, object->body);-    return 0;-}--} // namespace--namespace git {--std::optional<Id> import_tree(Writer& writer, Repo& repo, IdMap& trees, IdMap& blobs,-                              const Oid& oid,-                              std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,-                              std::size_t& new_trees, std::size_t& new_blobs, std::size_t depth) {-    if (import_tree_impl(writer, repo, trees, blobs, oid, raw_saves, new_trees, new_blobs, depth) !=-        0)-        return std::nullopt;-    return trees.get(oid);-}--bool export_tree(const fs::path& root, Store& store, IdMap& trees, IdMap& blobs, const Id& id,-                 Oid& out, std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return false;-    if (auto existing = trees.reverse(id)) {-        out = *existing;-        return true;-    }-    const fs::path mirror = git_dir(root);-    if (auto raw = load_raw(root, id)) {-        auto oid = object_hash(git::KIND_TREE, Bytes(raw->data(), raw->size()));-        if (!oid || !write_loose(mirror, git::KIND_TREE, *oid, Bytes(raw->data(), raw->size())))-            return false;-        trees.put(*oid, id);-        out = *oid;-        return true;-    }-    auto body = store.read_body(id, TYPE_TREE);-    if (!body)-        return false;-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-        return false;--    struct GitEntry {-        std::string mode;-        std::string name;-        Oid oid{};-        bool dir = false;-    };-    std::vector<GitEntry> entries;-    entries.reserve(tree->entries.size());-    for (const auto& entry : tree->entries) {-        GitEntry out_entry;-        out_entry.name = entry.name;-        out_entry.mode = mode_for_kind(entry.kind);-        out_entry.dir = entry.kind == KIND_SUBTREE;-        if (entry.kind == KIND_SUBTREE) {-            if (!export_tree(root, store, trees, blobs, entry.target, out_entry.oid, depth + 1))-                return false;-        } else if (entry.kind == KIND_SUBMODULE) {-            std::memcpy(out_entry.oid.data(), entry.target.data(), 20);-        } else if (entry.kind == KIND_CONFLICT) {-            return false;-        } else {-            Oid oid{};-            if (auto lazy = lazy_blob_oid(entry.target)) {-                oid = *lazy;-                blobs.put(oid, entry.target);-            } else if (auto existing = blobs.reverse(entry.target)) {-                oid = *existing;-            } else {-                auto data = read_blob(store, entry.target);-                if (!data)-                    return false;-                auto hash = object_hash(git::KIND_BLOB, Bytes(data->data(), data->size()));-                if (!hash ||-                    !write_loose(mirror, git::KIND_BLOB, *hash, Bytes(data->data(), data->size())))-                    return false;-                oid = *hash;-                blobs.put(oid, entry.target);-            }-            out_entry.oid = oid;-        }-        entries.push_back(std::move(out_entry));-    }-    std::stable_sort(entries.begin(), entries.end(), [](const GitEntry& a, const GitEntry& b) {-        std::string ak = a.name;-        std::string bk = b.name;-        if (a.dir)-            ak.push_back('/');-        if (b.dir)-            bk.push_back('/');-        return compare(bytes_of(ak), bytes_of(bk)) < 0;-    });-    std::vector<std::uint8_t> git_body;-    for (const auto& entry : entries) {-        git_body.insert(git_body.end(), entry.mode.begin(), entry.mode.end());-        git_body.push_back(' ');-        git_body.insert(git_body.end(), entry.name.begin(), entry.name.end());-        git_body.push_back(0);-        git_body.insert(git_body.end(), entry.oid.begin(), entry.oid.end());-    }-    auto oid = object_hash(git::KIND_TREE, Bytes(git_body.data(), git_body.size()));-    if (!oid || !write_loose(mirror, git::KIND_TREE, *oid, Bytes(git_body.data(), git_body.size())))-        return false;-    trees.put(*oid, id);-    out = *oid;-    return true;-}--bool export_commit(const fs::path& root, Store& store, IdMap& commits, IdMap& trees, IdMap& blobs,-                   const std::vector<Id>& native, const Id& id, Oid& out, std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return false;-    if (auto existing = commits.reverse(id)) {-        out = *existing;-        return true;-    }-    auto loaded = load_commit(store, id);-    if (!loaded)-        return false;-    Oid tree_oid{};-    if (!export_tree(root, store, trees, blobs, loaded->commit.root_tree, tree_oid, 0))-        return false;-    std::vector<Oid> parents;-    for (const auto& parent : loaded->commit.parents) {-        auto oid = commits.reverse(parent);-        if (!oid)-            return false;-        parents.push_back(*oid);-    }-    const fs::path mirror = git_dir(root);--    std::vector<std::uint8_t> body;-    bool used_raw = false;-    if (auto raw = load_raw(root, id)) {-        if (auto parsed = parse_commit(Bytes(raw->data(), raw->size()))) {-            bool matches =-                std::memcmp(parsed->tree.data(), tree_oid.data(), tree_oid.size()) == 0 &&-                parsed->parents.size() == parents.size();-            for (std::size_t i = 0; matches && i < parents.size(); ++i)-                matches = std::memcmp(parsed->parents[i].data(), parents[i].data(),-                                      parents[i].size()) == 0;-            if (matches) {-                body = *raw;-                used_raw = true;-            }-        }-    }-    if (!used_raw) {-        ParsedCommit parsed;-        parsed.tree = tree_oid;-        parsed.parents = parents;-        parsed.author = loaded->commit.author;-        parsed.committer = loaded->commit.committer;-        parsed.message = loaded->commit.message;-        parsed.extras = loaded->commit.extra;-        if (is_native(native, id)) {-            parsed.extras.push_back(-                KeyValue{"veins-change-id", hex_encode(Bytes(loaded->commit.change_id.data(),-                                                             loaded->commit.change_id.size()))});-        }-        body = serialize_commit(parsed);-    }-    auto oid = object_hash(git::KIND_COMMIT, Bytes(body.data(), body.size()));-    if (!oid || !write_loose(mirror, git::KIND_COMMIT, *oid, Bytes(body.data(), body.size())))-        return false;-    commits.put(*oid, id);-    out = *oid;-    return true;-}--} // namespace git--int git_import(const fs::path& root) {-    const bool checkout_after = working_tree_empty(root);-    const bool view_from_store = !read_heads(root).empty();-    const fs::path mirror = git_dir(root);-    auto repo = git::open_repo(mirror);-    if (!repo) {-        error_prefix();-        std::cout << "cannot open git mirror: " << path_display(mirror) << "\n";-        return 1;-    }-    IdMap commits_map;-    IdMap trees_map;-    IdMap blobs_map;-    if (!git::load_map(root, "commits", commits_map) || !git::load_map(root, "trees", trees_map) ||-        !git::load_map(root, "blobs", blobs_map)) {-        error_prefix();-        std::cout << "corrupt git mapping table\n";-        return 1;-    }--    const auto refset = git::read_refs(mirror);-    Store store = Store::open_all(root);-    auto tx = Txn::begin(root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    View before = tx->view();-    Writer& writer = tx->writer();-    std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;-    std::size_t new_commits = 0;-    std::size_t new_trees = 0;-    std::size_t new_blobs = 0;--    std::vector<NamedTarget> branches;-    std::vector<NamedTarget> tags;-    std::vector<NamedTarget> remotes;-    std::vector<Oid> tips;-    for (const auto& ref : refset.branches) {-        auto peeled = peel_to_commit(*repo, ref.oid);-        if (peeled) {-            branches.push_back(NamedTarget{ref.name, *peeled});-            tips.push_back(*peeled);-        }-    }-    for (const auto& ref : refset.tags) {-        auto peeled = peel_to_commit(*repo, ref.oid);-        if (peeled) {-            tags.push_back(NamedTarget{ref.name, *peeled});-            tips.push_back(*peeled);-        }-    }-    for (const auto& ref : refset.remotes) {-        auto peeled = peel_to_commit(*repo, ref.oid);-        if (peeled) {-            remotes.push_back(NamedTarget{ref.name, *peeled});-            tips.push_back(*peeled);-        }-    }-    std::optional<Oid> head_commit;-    if (refset.head) {-        head_commit = peel_to_commit(*repo, *refset.head);-        if (head_commit)-            tips.push_back(*head_commit);-    }--    std::optional<std::string> current_branch;-    if (head_commit) {-        std::optional<std::string> match;-        for (const auto& branch : branches) {-            if (std::memcmp(branch.oid.data(), head_commit->data(), head_commit->size()) != 0)-                continue;-            if (branch.name == "main" || branch.name == "master")-                match = branch.name;-            else if (!match)-                match = branch.name;-        }-        current_branch = match;-    }-    if (!current_branch) {-        for (const auto& branch : branches) {-            if (branch.name == "main" || branch.name == "master") {-                current_branch = branch.name;-                break;-            }-        }-    }-    if (!current_branch && !branches.empty())-        current_branch = branches.front().name;--    std::vector<CommitRecord> records;-    std::set<Oid, OidLess> seen;-    std::vector<Oid> stack(tips.rbegin(), tips.rend());-    {-        Progress progress("reading git history");-        while (!stack.empty()) {-            const Oid oid = stack.back();-            stack.pop_back();-            if (commits_map.get(oid) || seen.count(oid))-                continue;-            seen.insert(oid);-            auto object = git::read_object(*repo, oid);-            if (!object)-                continue;-            if (object->kind != git::KIND_COMMIT)-                continue;-            auto parsed = git::parse_commit(Bytes(object->body.data(), object->body.size()));-            if (!parsed)-                continue;-            records.push_back(CommitRecord{oid, std::move(object->body), std::move(*parsed)});-            for (const auto& parent : records.back().parsed.parents)-                stack.push_back(parent);-            progress.update(seen.size());-        }-        progress.finish();-    }--    const std::size_t n = records.size();-    std::map<Oid, std::size_t, OidLess> index;-    for (std::size_t i = 0; i < n; ++i)-        index[records[i].oid] = i;-    std::vector<std::size_t> indegree(n, 0);-    std::vector<std::vector<std::size_t>> children(n);-    bool topo_failed = false;-    for (std::size_t i = 0; i < n; ++i) {-        for (const auto& parent : records[i].parsed.parents) {-            if (commits_map.get(parent))-                continue;-            auto it = index.find(parent);-            if (it == index.end()) {-                topo_failed = true;-                continue;-            }-            ++indegree[i];-            children[it->second].push_back(i);-        }-    }-    std::vector<std::size_t> queue;-    for (std::size_t i = 0; i < n; ++i) {-        if (indegree[i] == 0)-            queue.push_back(i);-    }-    std::vector<std::size_t> order;-    for (std::size_t head = 0; head < queue.size(); ++head) {-        const std::size_t current = queue[head];-        order.push_back(current);-        for (std::size_t child : children[current]) {-            if (indegree[child] > 0 && --indegree[child] == 0)-                queue.push_back(child);-        }-    }-    if (topo_failed || order.size() != n) {-        error_prefix();-        std::cout << "git commit graph is incomplete or cyclic\n";-        return 1;-    }--    bool build_failed = false;-    {-        Progress progress("importing trees", order.size());-        for (std::size_t idx : order) {-            auto imported =-                git::import_tree(writer, *repo, trees_map, blobs_map, records[idx].parsed.tree,-                                 raw_saves, new_trees, new_blobs);-            if (!imported) {-                build_failed = true;-                break;-            }-            progress.advance();-        }-        if (!build_failed)-            progress.finish();-    }-    if (!build_failed) {-        Progress progress("importing commits", order.size());-        for (std::size_t idx : order) {-            const auto& record = records[idx];-            auto tree = trees_map.get(record.parsed.tree);-            if (!tree) {-                build_failed = true;-                break;-            }-            Commit commit;-            commit.version = 1;-            for (const auto& parent : record.parsed.parents) {-                auto mapped = commits_map.get(parent);-                if (!mapped) {-                    build_failed = true;-                    break;-                }-                commit.parents.push_back(*mapped);-            }-            if (build_failed)-                break;-            commit.root_tree = *tree;-            commit.change_id =-                record.parsed.change_id ? *record.parsed.change_id : derive_change_id(record.oid);-            commit.author = record.parsed.author;-            commit.committer = record.parsed.committer;-            commit.message = record.parsed.message;-            commit.renames_state = RENAMES_UNKNOWN;-            commit.extra = record.parsed.extras;-            const Id id = writer.add(TYPE_COMMIT, encode_commit(commit));-            commits_map.put(record.oid, id);-            ++new_commits;-            const auto canonical = git::serialize_commit(record.parsed);-            const bool is_canonical =-                record.parsed.canonical && equals(Bytes(canonical.data(), canonical.size()),-                                                  Bytes(record.body.data(), record.body.size()));-            if (!is_canonical)-                raw_saves.emplace_back(id, record.body);-            progress.advance();-        }-        if (!build_failed)-            progress.finish();-    }-    if (build_failed) {-        error_prefix();-        std::cout << "referenced git object is missing\n";-        return 1;-    }--    View& view = tx->view();-    for (const auto& branch : branches) {-        if (auto id = commits_map.get(branch.oid))-            set_bookmark(view, branch.name, *id);-    }-    for (const auto& tag : tags) {-        if (auto id = commits_map.get(tag.oid))-            set_tag(view, tag.name, *id);-    }-    for (const auto& remote : remotes) {-        if (auto id = commits_map.get(remote.oid)) {-            const auto parts = split_remote(remote.name);-            set_remote_ref(view, parts.first, parts.second, *id);-            if (!find_bookmark(view, parts.second))-                set_bookmark(view, parts.second, *id);-        }-    }--    view.heads.clear();-    for (const auto& branch : branches) {-        if (auto id = commits_map.get(branch.oid))-            add_unique(view.heads, *id);-    }-    for (const auto& remote : remotes) {-        if (auto id = commits_map.get(remote.oid))-            add_unique(view.heads, *id);-    }-    if (view.heads.empty()) {-        for (const auto& tag : tags) {-            if (auto id = commits_map.get(tag.oid))-                add_unique(view.heads, *id);-        }-    }-    std::optional<Id> head_id;-    if (head_commit) {-        if (auto id = commits_map.get(*head_commit))-            head_id = *id;-    }-    if (view.heads.empty() && head_id)-        add_unique(view.heads, *head_id);-    sort_ids(view.heads);-    if (checkout_after || !view_from_store) {-        if (head_id)-            set_workspace(view, *head_id);-        else if (!view.heads.empty())-            set_workspace(view, view.heads.front());-    }--    const auto old_encoded = encode_view(before);-    const auto new_encoded = encode_view(view);-    const bool unchanged = equals(bytes_of(old_encoded), bytes_of(new_encoded));-    const bool has_new_objects = new_commits > 0 || new_trees > 0 || new_blobs > 0;-    if (unchanged && !has_new_objects) {-        if (current_branch)-            (void)set_current_bookmark(root, *current_branch);-        else-            (void)clear_current_bookmark(root);-        info_prefix();-        std::cout << "already up to date\n";-        return 0;-    }-    auto status = tx->finish("git import");-    if (!status) {-        error_prefix();-        std::cout << "failed to write object pack\n";-        return 1;-    }-    if (current_branch)-        (void)set_current_bookmark(root, *current_branch);-    else-        (void)clear_current_bookmark(root);-    for (const auto& raw : raw_saves)-        (void)git::save_raw(root, raw.first, Bytes(raw.second.data(), raw.second.size()));-    if (!git::save_map(root, "commits", commits_map) || !git::save_map(root, "trees", trees_map) ||-        !git::save_map(root, "blobs", blobs_map)) {-        error_prefix();-        std::cout << "failed to write git mapping tables\n";-    }-    info_prefix();-    std::cout << "imported " << new_commits << " commits, " << new_trees << " trees, " << new_blobs-              << " blobs\n";--    if (checkout_after && head_id) {-        const int wc_status = create_working_copy(root, *head_id);-        if (wc_status != 0) {-            error_prefix();-            std::cout << "imported history; cannot create working copy (code " << wc_status-                      << ")\n";-            return 1;-        }-        const int checkout_status = materialize_working_copy(root, store);-        if (checkout_status != 0) {-            error_prefix();-            std::cout << "imported history; checkout failed (code " << checkout_status << ")\n";-            return 1;-        }-    }-    return 0;-}--int git_materialize(const fs::path& root) {-    git::IdMap commits_map;-    git::IdMap trees_map;-    git::IdMap blobs_map;-    if (!git::load_map(root, "commits", commits_map) || !git::load_map(root, "trees", trees_map) ||-        !git::load_map(root, "blobs", blobs_map)) {-        error_prefix();-        std::cout << "corrupt git mapping table\n";-        return 1;-    }-    const auto reverse_commits = reverse_git_map(commits_map);-    const auto reverse_trees = reverse_git_map(trees_map);--    Store store = Store::open_all(root);-    auto view = current_view(root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    auto tx = Txn::begin(root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    MaterializeCtx ctx{root, store, tx->writer(), {}, {}, {}, {}, {}, 0, 0, 0, false};-    const auto roots = view_roots(*view);-    const auto ordered = ordered_commits(store, roots);-    {-        Progress progress("materializing commits", ordered.size());-        for (const auto& old_id : ordered) {-            auto body = store.read_body(old_id, TYPE_COMMIT);-            if (!body)-                break;-            auto commit = decode_commit(bytes_of(*body));-            if (!commit)-                break;-            auto mapped_root = materialize_tree(ctx, commit->root_tree, 0);-            if (!mapped_root)-                break;-            bool changed = std::memcmp(mapped_root->data(), commit->root_tree.data(), ID_LEN) != 0;-            std::vector<Id> parents;-            parents.reserve(commit->parents.size());-            bool parents_ok = true;-            for (const auto& parent : commit->parents) {-                auto it = ctx.commits.find(parent);-                if (it == ctx.commits.end()) {-                    parents_ok = false;-                    break;-                }-                parents.push_back(it->second);-                if (std::memcmp(it->second.data(), parent.data(), ID_LEN) != 0)-                    changed = true;-            }-            if (!parents_ok)-                break;-            if (!changed) {-                ctx.commits[old_id] = old_id;-                progress.advance();-                continue;-            }-            commit->root_tree = *mapped_root;-            commit->parents = std::move(parents);-            const Id new_id = ctx.writer.add(TYPE_COMMIT, encode_commit(*commit));-            ctx.commits[old_id] = new_id;-            ++ctx.new_commits;-            ctx.changed = true;-            if (auto raw = git::load_raw(root, old_id))-                ctx.raw_saves.emplace_back(new_id, std::move(*raw));-            progress.advance();-        }-        if (ctx.commits.size() == ordered.size())-            progress.finish();-    }-    if (ctx.commits.size() != ordered.size()) {-        error_prefix();-        std::cout << "git materialize failed (missing or corrupt object)\n";-        return 1;-    }--    View& updated = tx->view();-    auto remap = [&](const Id& id) -> Id {-        auto it = ctx.commits.find(id);-        return it == ctx.commits.end() ? id : it->second;-    };-    for (auto& head : updated.heads)-        head = remap(head);-    for (auto& bookmark : updated.bookmarks) {-        for (auto& target : bookmark.targets.adds) {-            if (target)-                target = remap(*target);-        }-        for (auto& target : bookmark.targets.removes) {-            if (target)-                target = remap(*target);-        }-    }-    for (auto& tag : updated.tags)-        tag.target = remap(tag.target);-    for (auto& ref : updated.remote_refs)-        ref.target = remap(ref.target);-    for (auto& workspace : updated.working_copies)-        workspace.target = remap(workspace.target);-    sort_ids(updated.heads);--    if (!ctx.changed) {-        info_prefix();-        std::cout << "already materialized\n";-        return 0;-    }-    auto status = tx->finish("git materialize");-    if (!status) {-        error_prefix();-        std::cout << "failed to write object pack\n";-        return 1;-    }-    for (const auto& raw : ctx.raw_saves)-        (void)git::save_raw(root, raw.first, Bytes(raw.second.data(), raw.second.size()));-    for (const auto& item : ctx.commits) {-        if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)-            continue;-        auto it = reverse_commits.find(item.first);-        if (it != reverse_commits.end())-            commits_map.put(it->second, item.second);-    }-    for (const auto& item : ctx.trees) {-        if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)-            continue;-        auto it = reverse_trees.find(item.first);-        if (it != reverse_trees.end())-            trees_map.put(it->second, item.second);-    }-    for (const auto& item : ctx.blobs) {-        if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)-            continue;-        if (auto oid = git::lazy_blob_oid(item.first))-            blobs_map.put(*oid, item.second);-    }-    if (!git::save_map(root, "commits", commits_map) || !git::save_map(root, "trees", trees_map) ||-        !git::save_map(root, "blobs", blobs_map)) {-        error_prefix();-        std::cout << "failed to write git mapping tables\n";-    }-    clear_stat_cache(root);-    info_prefix();-    std::cout << "materialized " << ctx.new_commits << " commits, " << ctx.new_trees << " trees, "-              << ctx.new_blobs << " blobs\n";-    return 0;-}--int git_export(const fs::path& root) {-    if (!git::ensure_mirror(root)) {-        error_prefix();-        std::cout << "cannot create git mirror\n";-        return 1;-    }-    IdMap commits;-    IdMap trees;-    IdMap blobs;-    (void)git::load_map(root, "commits", commits);-    (void)git::load_map(root, "trees", trees);-    (void)git::load_map(root, "blobs", blobs);-    const auto native = load_native(root);-    Store store = Store::open_all(root);-    auto view = current_view(root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }--    std::vector<Id> roots;-    struct ResolvedBookmark {-        Bookmark bookmark;-    };-    std::vector<ResolvedBookmark> resolved_bookmarks;-    struct ResolvedTag {-        TagRef tag;-    };-    std::vector<ResolvedTag> resolved_tags;-    std::size_t skipped = 0;-    for (const auto& bookmark : view->bookmarks) {-        if (bookmark.targets.adds.empty() || !bookmark.targets.adds.front())-            continue;-        auto target = exportable_target(store, *bookmark.targets.adds.front());-        if (!target) {-            ++skipped;-            continue;-        }-        add_unique(roots, *target);-        Bookmark resolved;-        resolved.name = bookmark.name;-        resolved.targets.adds = {*target};-        resolved_bookmarks.push_back(ResolvedBookmark{std::move(resolved)});-    }-    for (const auto& tag : view->tags) {-        auto target = exportable_target(store, tag.target);-        if (!target) {-            ++skipped;-            continue;-        }-        add_unique(roots, *target);-        resolved_tags.push_back(ResolvedTag{TagRef{tag.name, *target}});-    }--    const auto ordered = ordered_commits(store, roots);-    std::size_t exported = 0;-    bool failed = false;-    for (const auto& id : ordered) {-        if (commits.reverse(id))-            continue;-        Oid oid{};-        if (!git::export_commit(root, store, commits, trees, blobs, native, id, oid)) {-            failed = true;-            break;-        }-        ++exported;-    }-    int status = 0;-    if (failed) {-        error_prefix();-        std::cout << "git export failed\n";-        status = 1;-    } else {-        for (const auto& item : resolved_bookmarks) {-            if (item.bookmark.targets.adds.empty())-                continue;-            auto oid = commits.reverse(*item.bookmark.targets.adds.front());-            if (oid && !git::write_ref(git_dir(root), "refs/heads/" + item.bookmark.name, *oid))-                status = 1;-        }-        for (const auto& item : resolved_tags) {-            auto oid = commits.reverse(item.tag.target);-            if (oid && !git::write_ref(git_dir(root), "refs/tags/" + item.tag.name, *oid))-                status = 1;-        }-        if (skipped > 0) {-            warning_prefix();-            std::cout << "skipped " << skipped << " conflicted ref(s)\n";-        }-    }-    if (status == 0) {-        if (!git::save_map(root, "commits", commits) || !git::save_map(root, "trees", trees) ||-            !git::save_map(root, "blobs", blobs)) {-            error_prefix();-            std::cout << "failed to write git mapping tables\n";-            status = 1;-        }-    }-    info_prefix();-    std::cout << "exported " << exported << " commits\n";-    return status;-}--int git_fetch(const fs::path& root, std::string_view remote) {-    const auto url = repo_config_value(root, git::remote_key(remote, "url"));-    if (!url) {-        error_prefix();-        std::cout << "unknown remote: " << remote << "\n";-        return 1;-    }-    if (!configure_mirror(root, remote, *url)) {-        error_prefix();-        std::cout << "cannot configure git mirror\n";-        return 1;-    }-    if (run_git(git_dir(root), {"fetch", "--prune", std::string(remote)}) != 0) {-        error_prefix();-        std::cout << "git fetch failed\n";-        return 1;-    }-    return git_import(root);-}--int git_push(const fs::path& root, std::string_view remote, std::string_view bookmark) {-    const auto url = repo_config_value(root, git::remote_key(remote, "url"));-    if (!url) {-        error_prefix();-        std::cout << "unknown remote: " << remote << "\n";-        return 1;-    }-    if (!configure_mirror(root, remote, *url)) {-        error_prefix();-        std::cout << "cannot configure git mirror\n";-        return 1;-    }-    const int exported = git_export(root);-    if (exported != 0)-        return exported;-    const std::string refspec =-        "refs/heads/" + std::string(bookmark) + ":refs/heads/" + std::string(bookmark);-    if (run_git(git_dir(root), {"push", std::string(remote), refspec}) != 0) {-        error_prefix();-        std::cout << "git push failed\n";-        return 1;-    }-    std::cout << "pushed " << bookmark << " to " << remote << "\n";-    return 0;-}--namespace {--void collect_text_lines(std::string_view text, std::set<std::string>& out) {-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        std::string_view line = text.substr(start, end - start);-        if (!line.empty() && line.back() == '\r')-            line.remove_suffix(1);-        if (!line.empty())-            out.emplace(line);-        if (end == text.size())-            break;-        start = end + 1;-    }-}--void collect_remote_refs(std::string_view text, std::set<std::string>& out) {-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        std::string_view line = text.substr(start, end - start);-        if (!line.empty() && line.back() == '\r')-            line.remove_suffix(1);-        const std::size_t tab = line.find('\t');-        if (tab != std::string_view::npos) {-            std::string_view ref = line.substr(tab + 1);-            if (!ref.ends_with("^{}"))-                out.emplace(ref);-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-}--struct MirrorRefs {-    std::vector<std::string> heads;-    std::vector<std::string> tags;-    std::set<std::string> present;-    std::vector<std::string> skipped;-};--MirrorRefs collect_mirror_refs(Store& store, const View& view) {-    MirrorRefs refs;-    for (const auto& bookmark : view.bookmarks) {-        if (bookmark.targets.adds.empty() || !bookmark.targets.adds.front())-            continue;-        const std::string ref = "refs/heads/" + bookmark.name;-        refs.present.insert(ref);-        if (bookmark.targets.adds.size() != 1 ||-            !exportable_target(store, *bookmark.targets.adds.front())) {-            refs.skipped.push_back(ref);-            continue;-        }-        refs.heads.push_back(bookmark.name);-    }-    for (const auto& tag : view.tags) {-        const std::string ref = "refs/tags/" + tag.name;-        refs.present.insert(ref);-        if (!exportable_target(store, tag.target)) {-            refs.skipped.push_back(ref);-            continue;-        }-        refs.tags.push_back(tag.name);-    }-    return refs;-}--bool capture_local_refs(const fs::path& root, std::set<std::string>& out) {-    std::string text;-    if (run_git_capture(git_dir(root),-                        {"for-each-ref", "--format=%(refname)", "refs/heads", "refs/tags"},-                        text) != 0)-        return false;-    collect_text_lines(text, out);-    return true;-}--void report_skipped_refs(const std::vector<std::string>& skipped) {-    for (const auto& ref : skipped) {-        warning_prefix();-        std::cout << "skipped " << ref << " (not exportable)\n";-    }-}--} // namespace--int git_mirror_push(const fs::path& root, std::string_view remote,-                    const GitMirrorOptions& options) {-    const auto url = repo_config_value(root, git::remote_key(remote, "url"));-    if (!url) {-        error_prefix();-        std::cout << "unknown git remote: " << remote << "\n";-        return 1;-    }-    if (!git::ensure_mirror(root)) {-        error_prefix();-        std::cout << "cannot create git mirror\n";-        return 1;-    }-    if (!configure_mirror(root, remote, *url)) {-        error_prefix();-        std::cout << "cannot configure git mirror\n";-        return 1;-    }-    const int exported = git_export(root);-    if (exported != 0)-        return exported;--    Store store = Store::open_all(root);-    auto view = current_view(root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    MirrorRefs refs = collect_mirror_refs(store, *view);-    if (options.strict && !refs.skipped.empty()) {-        report_skipped_refs(refs.skipped);-        error_prefix();-        std::cout << "cannot mirror every ref\n";-        return 1;-    }-    report_skipped_refs(refs.skipped);--    std::set<std::string> local_refs;-    if (!capture_local_refs(root, local_refs)) {-        error_prefix();-        std::cout << "cannot inspect git mirror refs\n";-        return 1;-    }--    std::vector<std::string> missing;-    auto keep_present = [&](std::vector<std::string>& names, std::string_view prefix) {-        names.erase(std::remove_if(names.begin(), names.end(),-                                   [&](const std::string& name) {-                                       if (local_refs.count(std::string(prefix) + name))-                                           return false;-                                       missing.emplace_back(std::string(prefix) + name);-                                       return true;-                                   }),-                    names.end());-    };-    keep_present(refs.heads, "refs/heads/");-    keep_present(refs.tags, "refs/tags/");-    if (options.strict && !missing.empty()) {-        for (const auto& ref : missing) {-            warning_prefix();-            std::cout << "missing " << ref << " in git mirror\n";-        }-        error_prefix();-        std::cout << "cannot mirror every ref\n";-        return 1;-    }-    for (const auto& ref : missing) {-        warning_prefix();-        std::cout << "missing " << ref << " in git mirror\n";-    }--    std::vector<std::string> args{"push"};-    if (options.dry_run)-        args.push_back("--dry-run");-    args.push_back(std::string(remote));-    std::size_t refspecs = 0;-    auto add_refspec = [&](std::string_view ref) {-        std::string spec;-        if (options.force)-            spec.push_back('+');-        spec += ref;-        spec.push_back(':');-        spec += ref;-        args.push_back(std::move(spec));-        ++refspecs;-    };-    for (const auto& name : refs.heads)-        add_refspec("refs/heads/" + name);-    for (const auto& name : refs.tags)-        add_refspec("refs/tags/" + name);--    std::size_t pruned = 0;-    if (options.prune) {-        std::string remote_text;-        if (run_git_capture(git_dir(root), {"ls-remote", "--heads", "--tags", std::string(remote)},-                            remote_text) != 0) {-            error_prefix();-            std::cout << "cannot list refs on git remote: " << remote << "\n";-            return 1;-        }-        std::set<std::string> remote_refs;-        collect_remote_refs(remote_text, remote_refs);-        for (const auto& ref : remote_refs) {-            if (ref.starts_with("refs/heads/") || ref.starts_with("refs/tags/")) {-                if (refs.present.count(ref) != 0)-                    continue;-                args.push_back(":" + ref);-                ++pruned;-            }-        }-    }--    if (refspecs == 0 && pruned == 0) {-        info_prefix();-        std::cout << "nothing to mirror\n";-        return 0;-    }-    std::cout.flush();-    if (run_git(git_dir(root), args) != 0) {-        error_prefix();-        std::cout << "git push failed\n";-        return 1;-    }-    info_prefix();-    if (options.dry_run)-        std::cout << "would mirror ";-    else-        std::cout << "mirrored ";-    std::cout << refs.heads.size() << " bookmark(s) and " << refs.tags.size() << " tag(s) to "-              << remote;-    if (pruned > 0)-        std::cout << ", pruning " << pruned << " ref(s)";-    std::cout << "\n";-    return 0;-}--int git_mirror_tag(const fs::path& root, std::string_view remote, std::string_view tag,-                   const GitMirrorOptions& options) {-    const auto url = repo_config_value(root, git::remote_key(remote, "url"));-    if (!url) {-        error_prefix();-        std::cout << "unknown git remote: " << remote << "\n";-        return 1;-    }-    Store store = Store::open_all(root);-    auto view = current_view(root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    const auto index = find_tag(*view, tag);-    if (!index) {-        error_prefix();-        std::cout << "unknown tag: " << tag << "\n";-        return 1;-    }-    if (!exportable_target(store, view->tags[*index].target)) {-        error_prefix();-        std::cout << "cannot export tag: " << tag << "\n";-        return 1;-    }-    if (!git::ensure_mirror(root)) {-        error_prefix();-        std::cout << "cannot create git mirror\n";-        return 1;-    }-    if (!configure_mirror(root, remote, *url)) {-        error_prefix();-        std::cout << "cannot configure git mirror\n";-        return 1;-    }-    const int exported = git_export(root);-    if (exported != 0)-        return exported;--    std::set<std::string> local_refs;-    if (!capture_local_refs(root, local_refs)) {-        error_prefix();-        std::cout << "cannot inspect git mirror refs\n";-        return 1;-    }-    const std::string ref = "refs/tags/" + std::string(tag);-    if (local_refs.count(ref) == 0) {-        error_prefix();-        std::cout << "tag was not exported: " << tag << "\n";-        return 1;-    }--    std::vector<std::string> args{"push"};-    if (options.dry_run)-        args.push_back("--dry-run");-    args.push_back(std::string(remote));-    std::string spec;-    if (options.force)-        spec.push_back('+');-    spec += ref;-    spec.push_back(':');-    spec += ref;-    args.push_back(std::move(spec));-    std::cout.flush();-    if (run_git(git_dir(root), args) != 0) {-        error_prefix();-        std::cout << "git push failed\n";-        return 1;-    }-    info_prefix();-    std::cout << (options.dry_run ? "would mirror tag " : "mirrored tag ") << tag << " to "-              << remote << "\n";-    return 0;-}--int git_prepare_mirror(const fs::path& root, std::string_view source) {-    return git::prepare_mirror(root, path_from_bytes(source));-}--std::optional<std::vector<std::uint8_t>> git_read_lazy_blob(const fs::path& root, const Id& id) {-    const auto oid = git::lazy_blob_oid(id);-    if (!oid)-        return std::nullopt;-    auto repo = git::cached_repo(git_dir(root));-    if (!repo)-        return std::nullopt;-    auto object = git::read_object(*repo, *oid);-    if (!object || object->kind != git::KIND_BLOB)-        return std::nullopt;-    return std::move(object->body);-}--void git_import_configure_remote(const fs::path& root, std::string_view url,-                                 std::string_view name) {-    if (name.empty())-        name = "o";-    const std::string url_key = git::remote_key(name, "url");-    if (url.empty()) {-        if (!repo_config_value(root, url_key)) {-            warning_prefix();-            std::cout << "no native remote configured; 'vn psh " << name-                      << "' will fail until you add one with 'vn remote add " << name-                      << " <url>'\n";-        }-        return;-    }-    (void)repo_config_set(root, url_key, url);-    (void)repo_config_set(root, "remote.default", name);-}--namespace {--int git_import_cli(const std::vector<std::string>& args) {-    std::string repo_path = ".";-    std::optional<std::string> source;-    std::string remote_url;-    std::string remote_name = "o";-    bool remote_name_given = false;-    for (std::size_t i = 3; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (arg.starts_with("-source:")) {-            if (arg.size() == 8) {-                error_prefix();-                std::cout << "-source: requires a path\n";-                return 1;-            }-            source = arg.substr(8);-        } else if (arg.starts_with("-remote:")) {-            if (arg.size() == 8) {-                error_prefix();-                std::cout << "-remote: requires a URL\n";-                return 1;-            }-            remote_url = arg.substr(8);-        } else if (arg.starts_with("-remote-name:")) {-            if (arg.size() == 13) {-                error_prefix();-                std::cout << "-remote-name: requires a name\n";-                return 1;-            }-            remote_name = arg.substr(13);-            remote_name_given = true;-        } else if (!arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            repo_path = arg;-        }-    }-    if (remote_name_given && remote_url.empty()) {-        error_prefix();-        std::cout << "-remote-name: requires -remote:<url>\n";-        return 1;-    }-    const auto root = discover_repo(path_from_bytes(repo_path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository: " << repo_path << "\n";-        return 1;-    }-    if (source) {-        const int prepared = git_prepare_mirror(*root, *source);-        if (prepared != 0) {-            error_prefix();-            if (prepared == 2) {-                std::cout << "-source: " << *source-                          << " is not a git repository root (expected the directory "-                             "containing .git)\n";-            } else {-                std::cout << "cannot prepare git mirror from " << *source << " (code " << prepared-                          << ")\n";-            }-            return 1;-        }-    }-    const int imported = git_import(*root);-    if (imported != 0)-        return imported;-    git_import_configure_remote(*root, remote_url, remote_name);-    return 0;-}--int git_export_cli(const std::vector<std::string>& args) {-    std::string repo_path = ".";-    for (std::size_t i = 3; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        }-        repo_path = arg;-    }-    const auto root = discover_repo(path_from_bytes(repo_path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository: " << repo_path << "\n";-        return 1;-    }-    return git_export(*root);-}--int git_materialize_cli(const std::vector<std::string>& args) {-    std::string repo_path = ".";-    for (std::size_t i = 3; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        }-        repo_path = arg;-    }-    const auto root = discover_repo(path_from_bytes(repo_path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository: " << repo_path << "\n";-        return 1;-    }-    return git_materialize(*root);-}--int git_fetch_cli(const std::vector<std::string>& args) {-    std::string remote = "origin";-    std::string repo_path = ".";-    bool have_remote = false;-    for (std::size_t i = 3; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        }-        if (!have_remote) {-            remote = arg;-            have_remote = true;-        } else {-            repo_path = arg;-        }-    }-    const auto root = discover_repo(path_from_bytes(repo_path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    return git_fetch(*root, remote);-}--int git_push_cli(const std::vector<std::string>& args) {-    std::string remote = "origin";-    std::optional<std::string> bookmark;-    std::string repo_path = ".";-    bool have_remote = false;-    for (std::size_t i = 3; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        }-        if (!have_remote) {-            remote = arg;-            have_remote = true;-        } else if (!bookmark) {-            bookmark = arg;-        } else {-            repo_path = arg;-        }-    }-    if (!bookmark) {-        error_prefix();-        std::cout << "git push requires a bookmark\n";-        return 1;-    }-    const auto root = discover_repo(path_from_bytes(repo_path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    return git_push(*root, remote, *bookmark);-}--namespace {--std::optional<std::string> resolve_mirror_remote(const fs::path& root,-                                                 const std::string& requested) {-    auto configured = [&](std::string_view name) {-        return repo_config_value(root, git::remote_key(name, "url")).has_value();-    };-    if (!requested.empty()) {-        if (configured(requested))-            return requested;-        error_prefix();-        std::cout << "unknown git remote: " << requested << "\n";-        return std::nullopt;-    }-    if (auto mirror = repo_config_value(root, "git.mirror"); mirror && !mirror->empty()) {-        if (configured(*mirror))-            return *mirror;-        error_prefix();-        std::cout << "git.mirror refers to an unknown remote: " << *mirror << "\n";-        return std::nullopt;-    }-    const auto names = git::list_remotes(root);-    if (std::find(names.begin(), names.end(), "origin") != names.end())-        return std::string("origin");-    if (names.size() == 1)-        return names.front();-    error_prefix();-    if (names.empty()) {-        std::cout << "no git remotes configured; use 'vn git remote add <name> <url>'\n";-    } else {-        std::cout << "multiple git remotes; specify one or set git.mirror\n";-        for (const auto& name : names)-            std::cout << "  " << name << "\n";-    }-    return std::nullopt;-}--void git_mirror_usage() {-    std::cout << "usage: vn git mirror <push|pt> ...\n\n";-    std::cout << "mirror Veins refs to a git remote\n\n";-    std::cout << "subcommands:\n";-    std::cout << "  push, psh [<remote>] [path]\n";-    std::cout << "                            export and push all bookmarks and "-                 "tags\n";-    std::cout << "  pt <tag> [<remote>] [path]\n";-    std::cout << "                            export and push one tag\n\n";-    std::cout << "options:\n";-    std::cout << "  -dry-run                  show what would be pushed\n";-    std::cout << "  -prune                    delete remote refs absent from Veins\n";-    std::cout << "  -strict                   fail if any ref cannot be exported\n";-    std::cout << "  -no-force                 do not force-push\n";-}--} // namespace--int git_mirror_cli(const std::vector<std::string>& args) {-    if (args.size() < 4) {-        git_mirror_usage();-        return 1;-    }-    const std::string& sub = args[3];-    const bool mirror_push = sub == "push" || sub == "psh";-    const bool mirror_tag = sub == "pt";-    if (!mirror_push && !mirror_tag) {-        error_prefix();-        std::cout << "unknown git mirror subcommand: " << sub << "\n";-        return 1;-    }--    GitMirrorOptions options;-    std::string tag;-    std::string remote;-    std::string repo_path = ".";-    bool have_tag = false;-    bool have_remote = false;-    bool end_flags = false;-    for (std::size_t i = 4; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && arg == "-dry-run") {-            options.dry_run = true;-        } else if (!end_flags && arg == "-no-force") {-            options.force = false;-        } else if (!end_flags && mirror_push && arg == "-prune") {-            options.prune = true;-        } else if (!end_flags && mirror_push && arg == "-strict") {-            options.strict = true;-        } else if (!end_flags && !arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else if (mirror_tag && !have_tag) {-            tag = arg;-            have_tag = true;-        } else if (!have_remote) {-            remote = arg;-            have_remote = true;-        } else {-            repo_path = arg;-        }-    }-    if (mirror_tag && tag.empty()) {-        error_prefix();-        std::cout << "git mirror pt requires a tag\n";-        return 1;-    }--    const auto root = discover_repo(path_from_bytes(repo_path));-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const auto resolved = resolve_mirror_remote(*root, remote);-    if (!resolved)-        return 1;-    if (mirror_tag)-        return git_mirror_tag(*root, *resolved, tag, options);-    return git_mirror_push(*root, *resolved, options);-}--int git_remote_cli(const std::vector<std::string>& args) {-    if (args.size() < 4) {-        error_prefix();-        std::cout << "expected remote subcommand (add, list, remove)\n";-        return 1;-    }-    const std::string& sub = args[3];-    const auto root = discover_repo(".");-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    if (sub == "add") {-        if (args.size() < 6) {-            error_prefix();-            std::cout << "remote add requires a name and URL\n";-            return 1;-        }-        if (!repo_config_set(*root, git::remote_key(args[4], "url"), args[5])) {-            error_prefix();-            std::cout << "cannot write repository config\n";-            return 1;-        }-        return 0;-    }-    if (sub == "list" || sub == "ls") {-        for (const auto& name : git::list_remotes(*root)) {-            const auto url = repo_config_value(*root, git::remote_key(name, "url"));-            std::cout << name << '\t' << (url ? *url : std::string()) << '\n';-        }-        return 0;-    }-    if (sub == "remove" || sub == "rm") {-        if (args.size() < 5) {-            error_prefix();-            std::cout << "remote remove requires a name\n";-            return 1;-        }-        const std::string& name = args[4];-        (void)repo_config_remove(*root, git::remote_key(name, "url"));-        (void)repo_config_remove(*root, git::remote_key(name, "key"));-        (void)repo_config_remove(*root, git::remote_key(name, "tls-pin"));-        return 0;-    }-    error_prefix();-    std::cout << "unknown remote subcommand: " << sub << "\n";-    return 1;-}--} // namespace--int git_cli_run(const std::vector<std::string>& args) {-    if (args.size() < 3) {-        error_prefix();-        std::cout << "expected a git subcommand (import, export, materialize, "-                     "fetch, push, remote)\n";-        return 1;-    }-    const std::string& sub = args[2];-    if (sub == "import")-        return git_import_cli(args);-    if (sub == "export")-        return git_export_cli(args);-    if (sub == "materialize")-        return git_materialize_cli(args);-    if (sub == "fetch")-        return git_fetch_cli(args);-    if (sub == "push")-        return git_push_cli(args);-    if (sub == "mirror")-        return git_mirror_cli(args);-    if (sub == "remote")-        return git_remote_cli(args);-    error_prefix();-    std::cout << "unknown git subcommand: " << sub << "\n";-    return 1;-}--} // namespace vn--- a/xveins/src/git/git.h+++ /dev/null@@ -1,34 +0,0 @@-#pragma once--#include "core/common.h"-#include "object/object.h"--#include <optional>-#include <string>-#include <vector>--namespace vn {--int git_import(const fs::path& root);-void git_import_configure_remote(const fs::path& root, std::string_view url, std::string_view name);-int git_export(const fs::path& root);-int git_materialize(const fs::path& root);-int git_fetch(const fs::path& root, std::string_view remote);-int git_push(const fs::path& root, std::string_view remote, std::string_view bookmark);--struct GitMirrorOptions {-    bool force = true;-    bool prune = false;-    bool dry_run = false;-    bool strict = false;-};--int git_mirror_push(const fs::path& root, std::string_view remote, const GitMirrorOptions& options);-int git_mirror_tag(const fs::path& root, std::string_view remote, std::string_view tag,-                   const GitMirrorOptions& options);--int git_prepare_mirror(const fs::path& root, std::string_view source);-std::optional<std::vector<std::uint8_t>> git_read_lazy_blob(const fs::path& root, const Id& id);-int git_cli_run(const std::vector<std::string>& args);--} // namespace vn--- a/xveins/src/git/git_internal.h+++ /dev/null@@ -1,150 +0,0 @@-#pragma once--#include "core/common.h"-#include "object/object.h"-#include "store/store.h"--#include <array>-#include <map>-#include <memory>-#include <optional>-#include <string>-#include <vector>--namespace vn::git {--using Oid = std::array<std::uint8_t, 20>;--// A single git object is materialized in memory during import/export. Bound it-// so a hostile pack or loose object cannot trigger an unbounded allocation.-constexpr std::size_t MAX_GIT_OBJECT_BODY = 1ull * 1024ull * 1024ull * 1024ull;-// Packs are currently read in full. Bound the file size for the same reason.-constexpr std::uint64_t MAX_GIT_PACK_BYTES = 8ull * 1024ull * 1024ull * 1024ull;-constexpr std::size_t MAX_GIT_DELTA_DEPTH = 128;--struct OidLess {-    bool operator()(const Oid& a, const Oid& b) const {-        return std::memcmp(a.data(), b.data(), a.size()) < 0;-    }-};--enum Kind : std::uint8_t {-    KIND_NONE = 0,-    KIND_COMMIT = 1,-    KIND_TREE = 2,-    KIND_BLOB = 3,-    KIND_TAG = 4,-    KIND_OFS_DELTA = 6,-    KIND_REF_DELTA = 7,-};--struct Object {-    std::uint8_t kind = 0;-    std::vector<std::uint8_t> body;-};--struct Pack {-    fs::path path;-    std::vector<std::uint8_t> data;-    std::vector<Oid> oids;-    std::vector<std::uint64_t> offsets;-};--struct Repo {-    fs::path git_dir;-    std::vector<Pack> packs;-};--std::string oid_hex(const Oid& oid);-std::optional<Oid> oid_from_hex(std::string_view hex);-std::optional<Oid> object_hash(std::uint8_t kind, Bytes body);-std::optional<Repo> open_repo(const fs::path& git_dir);-std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify = false,-                                  std::size_t depth = 0);-std::shared_ptr<Repo> cached_repo(const fs::path& git_dir);--struct RawTreeEntry {-    std::string mode;-    std::string name;-    Oid oid{};-};--struct ParsedTree {-    std::vector<RawTreeEntry> entries;-    bool canonical = true;-};--struct ParsedTag {-    Oid target{};-    std::uint8_t target_kind = 0;-};--struct ParsedCommit {-    Oid tree{};-    std::vector<Oid> parents;-    Sig author;-    Sig committer;-    std::string message;-    std::vector<KeyValue> extras;-    std::optional<ChangeId> change_id;-    bool canonical = true;-};--std::optional<Sig> parse_sig(std::string_view value);-std::optional<ParsedCommit> parse_commit(Bytes body);-std::vector<std::uint8_t> serialize_commit(const ParsedCommit& commit);-std::optional<ParsedTree> parse_tree(Bytes body);-std::string mode_for_kind(std::uint8_t kind);-std::uint8_t mode_kind(std::string_view mode);-std::optional<ParsedTag> parse_tag(Bytes body);--struct IdMap {-    std::map<Oid, Id, OidLess> items;--    std::optional<Id> get(const Oid& oid) const;-    void put(const Oid& oid, const Id& id);-    std::optional<Oid> reverse(const Id& id) const;-};--bool load_map(const fs::path& root, std::string_view name, IdMap& out);-bool save_map(const fs::path& root, std::string_view name, const IdMap& map);-bool save_raw(const fs::path& root, const Id& id, Bytes body);-std::optional<std::vector<std::uint8_t>> load_raw(const fs::path& root, const Id& id);--struct Ref {-    std::string name;-    Oid oid{};-};--struct RefSet {-    std::vector<Ref> branches;-    std::vector<Ref> tags;-    std::vector<Ref> remotes;-    std::optional<Oid> head;-};--RefSet read_refs(const fs::path& git_dir);--Id lazy_blob_id(const Oid& oid);-std::optional<Oid> lazy_blob_oid(const Id& id);--bool ensure_mirror(const fs::path& root);-int prepare_mirror(const fs::path& root, const fs::path& source);-bool write_loose(const fs::path& git_dir, std::uint8_t kind, const Oid& oid, Bytes body);-bool write_ref(const fs::path& git_dir, std::string_view name, const Oid& oid);--std::string remote_key(std::string_view remote, std::string_view field);-std::vector<std::string> list_remotes(const fs::path& root);--std::optional<Id> import_tree(Writer& writer, Repo& repo, IdMap& trees, IdMap& blobs,-                              const Oid& oid,-                              std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,-                              std::size_t& new_trees, std::size_t& new_blobs,-                              std::size_t depth = 0);--bool export_tree(const fs::path& root, Store& store, IdMap& trees, IdMap& blobs, const Id& id,-                 Oid& out, std::size_t depth = 0);-bool export_commit(const fs::path& root, Store& store, IdMap& commits, IdMap& trees, IdMap& blobs,-                   const std::vector<Id>& native, const Id& id, Oid& out, std::size_t depth = 0);--} // namespace vn::git--- a/xveins/src/git/git_object.cpp+++ /dev/null@@ -1,1154 +0,0 @@-#include "git/git_internal.h"--#include <openssl/evp.h>-#include <zlib.h>--#include <algorithm>-#include <cstring>-#include <limits>-#include <map>-#include <mutex>-#include <string_view>--namespace vn::git {--namespace {--std::uint32_t be32(Bytes data, std::size_t off) {-    return (static_cast<std::uint32_t>(data[off]) << 24) |-           (static_cast<std::uint32_t>(data[off + 1]) << 16) |-           (static_cast<std::uint32_t>(data[off + 2]) << 8) |-           static_cast<std::uint32_t>(data[off + 3]);-}--std::uint64_t be64(Bytes data, std::size_t off) {-    return (static_cast<std::uint64_t>(be32(data, off)) << 32) |-           static_cast<std::uint64_t>(be32(data, off + 4));-}--Oid sha1(Bytes data) {-    Oid out{};-    unsigned int len = 0;-    static const std::uint8_t empty = 0;-    const std::uint8_t* ptr = data.empty() ? &empty : data.data();-    EVP_Digest(ptr, data.size(), out.data(), &len, EVP_sha1(), nullptr);-    return out;-}--bool bytes_equal(const Oid& a, Bytes b) {-    return b.size() == a.size() && std::memcmp(a.data(), b.data(), a.size()) == 0;-}--std::string kind_name(std::uint8_t kind) {-    switch (kind) {-    case KIND_COMMIT:-        return "commit";-    case KIND_TREE:-        return "tree";-    case KIND_BLOB:-        return "blob";-    case KIND_TAG:-        return "tag";-    default:-        return "unknown";-    }-}--std::uint8_t kind_from_name(std::string_view name) {-    if (name == "commit")-        return KIND_COMMIT;-    if (name == "tree")-        return KIND_TREE;-    if (name == "blob")-        return KIND_BLOB;-    if (name == "tag")-        return KIND_TAG;-    return 0;-}--std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input, std::size_t max_output);--std::optional<std::vector<std::uint8_t>> inflate_exact(Bytes input, std::size_t expected) {-    if (expected > MAX_GIT_OBJECT_BODY)-        return std::nullopt;-    if (expected == 0) {-        auto result = inflate_unknown(input, MAX_GIT_OBJECT_BODY);-        if (!result || !result->empty())-            return std::nullopt;-        return result;-    }-    std::vector<std::uint8_t> out(expected);-    uLongf dest_len = static_cast<uLongf>(expected);-    const int rc =-        uncompress(out.data(), &dest_len, input.data(), static_cast<uLong>(input.size()));-    if (rc != Z_OK || dest_len != expected)-        return std::nullopt;-    out.resize(expected);-    return out;-}--std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input, std::size_t max_output) {-    if (max_output == 0)-        max_output = MAX_GIT_OBJECT_BODY;-    z_stream zs{};-    if (inflateInit(&zs) != Z_OK)-        return std::nullopt;-    std::vector<std::uint8_t> out(std::min<std::size_t>(4096, max_output));-    zs.next_in = const_cast<Bytef*>(input.data());-    zs.avail_in = static_cast<uInt>(input.size());-    int rc = Z_OK;-    for (;;) {-        if (zs.total_out == out.size()) {-            if (out.size() >= max_output) {-                inflateEnd(&zs);-                return std::nullopt;-            }-            const std::size_t grown =-                std::min(max_output, out.size() > max_output / 2 ? max_output : out.size() * 2);-            if (grown <= out.size()) {-                inflateEnd(&zs);-                return std::nullopt;-            }-            out.resize(grown);-        }-        zs.next_out = out.data() + zs.total_out;-        zs.avail_out = static_cast<uInt>(out.size() - zs.total_out);-        rc = inflate(&zs, Z_NO_FLUSH);-        if (rc == Z_STREAM_END)-            break;-        if (rc == Z_BUF_ERROR && zs.avail_in == 0) {-            inflateEnd(&zs);-            return std::nullopt;-        }-        if (rc != Z_OK) {-            inflateEnd(&zs);-            return std::nullopt;-        }-    }-    const std::size_t written = zs.total_out;-    inflateEnd(&zs);-    out.resize(written);-    return out;-}--struct Varint {-    std::uint64_t value = 0;-    std::size_t next = 0;-};--std::optional<Varint> read_be_varint(Bytes data, std::size_t start) {-    if (start >= data.size())-        return std::nullopt;-    const std::uint8_t c0 = data[start];-    std::uint64_t value = c0 & 0x0f;-    std::uint64_t shift = 4;-    std::size_t pos = start + 1;-    bool more = (c0 & 0x80) != 0;-    while (more) {-        if (pos >= data.size() || shift >= 64)-            return std::nullopt;-        const std::uint8_t c = data[pos++];-        if (shift == 63 && (c & 0x7f) > 1)-            return std::nullopt;-        value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);-        shift += 7;-        more = (c & 0x80) != 0;-    }-    return Varint{value, pos};-}--std::optional<Varint> read_delta_varint(Bytes data, std::size_t start) {-    std::uint64_t value = 0;-    std::uint64_t shift = 0;-    std::size_t pos = start;-    for (;;) {-        if (pos >= data.size() || shift > 63)-            return std::nullopt;-        const std::uint8_t c = data[pos++];-        value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);-        shift += 7;-        if ((c & 0x80) == 0)-            return Varint{value, pos};-    }-}--std::optional<std::vector<std::uint8_t>> apply_delta(Bytes base, Bytes delta) {-    const auto src_size = read_delta_varint(delta, 0);-    if (!src_size || src_size->value != base.size())-        return std::nullopt;-    const auto dst_size = read_delta_varint(delta, src_size->next);-    if (!dst_size || dst_size->value > MAX_GIT_OBJECT_BODY)-        return std::nullopt;-    const std::size_t cap = static_cast<std::size_t>(dst_size->value);-    std::vector<std::uint8_t> out(cap);-    std::size_t written = 0;-    std::size_t pos = dst_size->next;-    while (pos < delta.size()) {-        const std::uint8_t op = delta[pos++];-        if ((op & 0x80) != 0) {-            std::uint64_t off = 0;-            std::uint64_t size = 0;-            for (int bit = 0; bit < 4; ++bit) {-                if ((op & (1u << bit)) != 0) {-                    if (pos >= delta.size())-                        return std::nullopt;-                    off |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);-                }-            }-            for (int bit = 0; bit < 3; ++bit) {-                if ((op & (1u << (4 + bit))) != 0) {-                    if (pos >= delta.size())-                        return std::nullopt;-                    size |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);-                }-            }-            if (size == 0)-                size = 65536;-            if (off > base.size() || size > base.size() - off)-                return std::nullopt;-            if (size > cap - written)-                return std::nullopt;-            if (size > 0)-                std::memcpy(out.data() + written, base.data() + off,-                            static_cast<std::size_t>(size));-            written += static_cast<std::size_t>(size);-        } else {-            if (op == 0)-                return std::nullopt;-            const std::size_t n = op;-            if (pos + n > delta.size() || n > cap - written)-                return std::nullopt;-            std::memcpy(out.data() + written, delta.data() + pos, n);-            pos += n;-            written += n;-        }-    }-    if (written != cap)-        return std::nullopt;-    return out;-}--std::optional<std::size_t> find_oid(const Pack& pack, const Oid& oid) {-    auto it = std::lower_bound(pack.oids.begin(), pack.oids.end(), oid, OidLess{});-    if (it == pack.oids.end() || std::memcmp(it->data(), oid.data(), oid.size()) != 0)-        return std::nullopt;-    return static_cast<std::size_t>(it - pack.oids.begin());-}--std::optional<Object> read_at(Repo& repo, Pack& pack, std::uint64_t start, bool verify,-                              std::size_t depth) {-    if (depth > MAX_GIT_DELTA_DEPTH || start >= pack.data.size())-        return std::nullopt;-    Bytes data(pack.data.data(), pack.data.size());-    const std::size_t begin = static_cast<std::size_t>(start);-    const std::uint8_t c0 = data[begin];-    const std::uint8_t kind = static_cast<std::uint8_t>((c0 >> 4) & 7);-    const auto header = read_be_varint(data, begin);-    if (!header || header->value > MAX_GIT_OBJECT_BODY)-        return std::nullopt;-    const std::size_t size = static_cast<std::size_t>(header->value);-    std::size_t pos = header->next;--    Oid base_oid{};-    bool has_base_oid = false;-    std::uint64_t base_off = 0;-    bool has_base_off = false;-    if (kind == KIND_OFS_DELTA) {-        if (pos >= data.size())-            return std::nullopt;-        std::uint8_t c = data[pos++];-        std::uint64_t acc = c & 0x7f;-        bool more = (c & 0x80) != 0;-        while (more) {-            if (pos >= data.size())-                return std::nullopt;-            c = data[pos++];-            acc = ((acc + 1) << 7) | (c & 0x7f);-            more = (c & 0x80) != 0;-        }-        has_base_off = true;-        if (acc > start)-            return std::nullopt;-        base_off = start - acc;-    } else if (kind == KIND_REF_DELTA) {-        if (pos + 20 > data.size())-            return std::nullopt;-        std::memcpy(base_oid.data(), data.data() + pos, 20);-        has_base_oid = true;-        pos += 20;-    }--    if (pos > data.size())-        return std::nullopt;-    auto inflated = inflate_exact(data.subspan(pos), size);-    if (!inflated)-        return std::nullopt;-    if (kind >= KIND_COMMIT && kind <= KIND_TAG)-        return Object{kind, std::move(*inflated)};-    if (kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA)-        return std::nullopt;--    std::optional<Object> base;-    if (has_base_off) {-        if (base_off >= start)-            return std::nullopt;-        base = read_at(repo, pack, base_off, verify, depth + 1);-    } else if (has_base_oid) {-        base = read_object(repo, base_oid, verify, depth + 1);-    }-    if (!base)-        return std::nullopt;-    auto merged = apply_delta(Bytes(base->body.data(), base->body.size()),-                              Bytes(inflated->data(), inflated->size()));-    if (!merged)-        return std::nullopt;-    return Object{base->kind, std::move(*merged)};-}--std::optional<Pack> parse_idx(Bytes data, std::size_t pack_count, Bytes pack_trailer) {-    if (data.size() < 40)-        return std::nullopt;-    const std::size_t trailer_off = data.size() - 20;-    const Oid check = sha1(data.first(trailer_off));-    if (!bytes_equal(check, data.subspan(trailer_off, 20)))-        return std::nullopt;-    if (pack_trailer.size() != 20 ||-        std::memcmp(data.data() + data.size() - 40, pack_trailer.data(), 20) != 0)-        return std::nullopt;--    const bool is_v2 = data.size() >= 4 && data[0] == 0xff && data[1] == 0x74 && data[2] == 0x4f &&-                       data[3] == 0x63;-    const std::size_t fanout_off = is_v2 ? 8 : 0;-    if (is_v2 && be32(data, 4) != 2)-        return std::nullopt;-    if (data.size() < fanout_off + 1024 + 40)-        return std::nullopt;-    const std::size_t n = be32(data, fanout_off + 255 * 4);-    if (n != pack_count)-        return std::nullopt;-    const std::size_t names_off = fanout_off + 1024;-    const std::size_t min_entry = is_v2 ? 28 : 24;-    if (n > (data.size() - 40 - names_off) / min_entry)-        return std::nullopt;--    Pack pack;-    pack.oids.resize(n);-    pack.offsets.resize(n);-    if (is_v2) {-        const std::size_t crcs_off = names_off + n * 20;-        const std::size_t offs_off = crcs_off + n * 4;-        const std::size_t large_off = offs_off + n * 4;-        if (large_off + 40 > data.size())-            return std::nullopt;-        const std::size_t large_bytes = data.size() - 40 - large_off;-        if (large_bytes % 8 != 0)-            return std::nullopt;-        for (std::size_t i = 0; i < n; ++i) {-            std::memcpy(pack.oids[i].data(), data.data() + names_off + i * 20, 20);-            const std::uint32_t raw_off = be32(data, offs_off + i * 4);-            std::uint64_t resolved = raw_off;-            if ((raw_off & 0x80000000u) != 0) {-                const std::size_t idx = raw_off & 0x7fffffffu;-                if (idx * 8 + 8 > large_bytes)-                    return std::nullopt;-                resolved = be64(data, large_off + idx * 8);-            }-            pack.offsets[i] = resolved;-        }-    } else {-        const std::size_t records_off = 1024;-        if (records_off + n * 24 + 40 > data.size())-            return std::nullopt;-        for (std::size_t i = 0; i < n; ++i) {-            const std::size_t rec = records_off + i * 24;-            pack.offsets[i] = be32(data, rec);-            std::memcpy(pack.oids[i].data(), data.data() + rec + 4, 20);-        }-    }-    return pack;-}--std::optional<Pack> open_pack(const fs::path& pack_path, const fs::path& idx_path) {-    auto pdata = read_file_opt(pack_path, MAX_GIT_PACK_BYTES);-    if (!pdata || pdata->size() < 32)-        return std::nullopt;-    if (std::memcmp(pdata->data(), "PACK", 4) != 0)-        return std::nullopt;-    const std::uint32_t version = be32(bytes_of(*pdata), 4);-    if (version != 2 && version != 3)-        return std::nullopt;-    const std::size_t count = be32(bytes_of(*pdata), 8);-    const std::size_t trailer_off = pdata->size() - 20;-    const Oid pack_trailer = sha1(Bytes(pdata->data(), trailer_off));-    if (std::memcmp(pack_trailer.data(), pdata->data() + trailer_off, 20) != 0)-        return std::nullopt;--    auto idata = read_file_opt(idx_path, MAX_GIT_PACK_BYTES);-    if (!idata)-        return std::nullopt;-    auto parsed = parse_idx(bytes_of(*idata), count, Bytes(pdata->data() + trailer_off, 20));-    if (!parsed)-        return std::nullopt;-    parsed->path = pack_path;-    parsed->data = std::move(*pdata);-    return parsed;-}--std::optional<Object> read_loose(const Repo& repo, const Oid& oid, bool verify) {-    const std::string hex = oid_hex(oid);-    const fs::path path = repo.git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) /-                          path_from_bytes(hex.substr(2));-    auto compressed = read_file_opt(path, MAX_GIT_OBJECT_BODY);-    if (!compressed)-        return std::nullopt;-    auto inflated = inflate_unknown(bytes_of(*compressed), MAX_GIT_OBJECT_BODY);-    if (!inflated)-        return std::nullopt;-    Bytes data(inflated->data(), inflated->size());-    const std::size_t space =-        static_cast<std::size_t>(std::find(data.begin(), data.end(), ' ') - data.begin());-    std::size_t nul = space;-    while (nul < data.size() && data[nul] != 0)-        ++nul;-    if (space == 0 || nul >= data.size())-        return std::nullopt;-    const std::uint8_t kind = kind_from_name(str_of(data.first(space)));-    if (kind == 0)-        return std::nullopt;-    std::uint64_t declared = 0;-    for (std::size_t i = space + 1; i < nul; ++i) {-        const std::uint8_t c = data[i];-        if (c < '0' || c > '9')-            return std::nullopt;-        declared = declared * 10 + (c - '0');-    }-    Bytes body = data.subspan(nul + 1);-    if (body.size() != declared)-        return std::nullopt;-    Object object{kind, std::vector<std::uint8_t>(body.begin(), body.end())};-    if (verify) {-        auto hash = object_hash(kind, body);-        if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)-            return std::nullopt;-    }-    return object;-}--std::string trim_line(std::string_view text) {-    while (!text.empty() && (text.back() == '\n' || text.back() == '\r'))-        text.remove_suffix(1);-    return std::string(text);-}--void replace_ref(std::vector<Ref>& refs, std::string name, const Oid& oid) {-    for (auto& ref : refs) {-        if (ref.name == name) {-            ref.oid = oid;-            return;-        }-    }-    refs.push_back(Ref{std::move(name), oid});-}--std::optional<Oid> find_ref(const std::vector<Ref>& refs, std::string_view name) {-    for (const auto& ref : refs) {-        if (ref.name == name)-            return ref.oid;-    }-    return std::nullopt;-}--void read_packed_refs(const fs::path& git_dir, std::vector<Ref>& branches, std::vector<Ref>& tags) {-    auto data = read_file_opt(git_dir / "packed-refs");-    if (!data)-        return;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        std::string_view line = text.substr(start, end - start);-        if (!line.empty() && line.front() != '#' && line.front() != '^') {-            const std::size_t space = line.find(' ');-            if (space != std::string_view::npos && space != 0) {-                auto oid = oid_from_hex(line.substr(0, space));-                std::string_view name = line.substr(space + 1);-                if (oid) {-                    if (name.starts_with("refs/heads/"))-                        replace_ref(branches, std::string(name.substr(11)), *oid);-                    else if (name.starts_with("refs/tags/"))-                        replace_ref(tags, std::string(name.substr(10)), *oid);-                }-            }-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-}--void read_ref_dir(const fs::path& base, std::string_view rel, std::vector<Ref>& refs,-                  std::size_t depth = 0) {-    if (depth > 64)-        return;-    const fs::path dir = rel.empty() ? base : base / path_from_bytes(rel);-    for (const auto& name : list_directory(dir)) {-        std::string child_rel(rel);-        if (!child_rel.empty())-            child_rel.push_back('/');-        child_rel += name;-        const fs::path child = base / path_from_bytes(child_rel);-        std::error_code ec;-        const auto status = fs::symlink_status(child, ec);-        if (ec || fs::is_symlink(status))-            continue;-        if (fs::is_directory(status)) {-            read_ref_dir(base, child_rel, refs, depth + 1);-        } else {-            auto content = read_file_opt(child);-            if (!content)-                continue;-            const std::string line = trim_line(-                std::string_view(reinterpret_cast<const char*>(content->data()), content->size()));-            if (auto oid = oid_from_hex(line))-                replace_ref(refs, child_rel, *oid);-        }-    }-}--std::optional<Oid> resolve_head(const fs::path& git_dir, const std::vector<Ref>& branches,-                                const std::vector<Ref>& tags) {-    auto data = read_file_opt(git_dir / "HEAD");-    if (!data)-        return std::nullopt;-    const std::string line =-        trim_line(std::string_view(reinterpret_cast<const char*>(data->data()), data->size()));-    if (line.starts_with("ref: ")) {-        std::string_view name(line.data() + 5, line.size() - 5);-        if (name.starts_with("refs/heads/"))-            return find_ref(branches, name.substr(11));-        if (name.starts_with("refs/tags/"))-            return find_ref(tags, name.substr(10));-        return std::nullopt;-    }-    return oid_from_hex(line);-}--std::optional<fs::path> resolve_source(const fs::path& source) {-    std::error_code ec;-    const fs::path dotgit = source / ".git";-    if (fs::is_directory(dotgit, ec))-        return dotgit;-    if (fs::is_regular_file(source / "HEAD", ec) && fs::is_directory(source / "objects", ec))-        return source;-    return std::nullopt;-}--bool copy_tree(const fs::path& src, const fs::path& dst, std::size_t depth = 0) {-    if (depth > 64)-        return false;-    std::error_code ec;-    fs::create_directories(dst, ec);-    if (ec)-        return false;-    for (const auto& name : list_directory(src)) {-        const fs::path s = src / path_from_bytes(name);-        const fs::path d = dst / path_from_bytes(name);-        const auto status = fs::symlink_status(s, ec);-        if (ec || fs::is_symlink(status))-            continue;-        if (fs::is_directory(status)) {-            if (!copy_tree(s, d, depth + 1))-                return false;-        } else if (fs::is_regular_file(status)) {-            fs::create_hard_link(s, d, ec);-            if (ec) {-                ec.clear();-                fs::copy_file(s, d, fs::copy_options::overwrite_existing, ec);-                if (ec)-                    return false;-            }-        }-    }-    return true;-}--} // namespace--std::string oid_hex(const Oid& oid) {-    return hex_encode(Bytes(oid.data(), oid.size()));-}--std::optional<Oid> oid_from_hex(std::string_view hex) {-    Oid out{};-    if (!hex_decode(hex, MutBytes(out.data(), out.size())))-        return std::nullopt;-    return out;-}--std::optional<Oid> object_hash(std::uint8_t kind, Bytes body) {-    const std::string name = kind_name(kind);-    if (name == "unknown")-        return std::nullopt;-    std::string header = name;-    header.push_back(' ');-    header += std::to_string(body.size());-    header.push_back('\0');-    std::vector<std::uint8_t> data;-    data.reserve(header.size() + body.size());-    data.insert(data.end(), header.begin(), header.end());-    data.insert(data.end(), body.begin(), body.end());-    return sha1(Bytes(data.data(), data.size()));-}--std::optional<Repo> open_repo(const fs::path& git_dir) {-    Repo repo;-    repo.git_dir = git_dir;-    const fs::path pack_dir = git_dir / "objects" / "pack";-    std::error_code ec;-    if (fs::is_directory(pack_dir, ec)) {-        std::vector<std::string> names = list_directory(pack_dir);-        std::sort(names.begin(), names.end());-        for (const auto& name : names) {-            if (name.size() <= 4 || name.compare(name.size() - 4, 4, ".idx") != 0)-                continue;-            const std::string base = name.substr(0, name.size() - 4);-            const fs::path pack_path = pack_dir / path_from_bytes(base + ".pack");-            const fs::path idx_path = pack_dir / path_from_bytes(name);-            if (!path_is_file(pack_path))-                continue;-            auto pack = open_pack(pack_path, idx_path);-            if (!pack)-                return std::nullopt;-            repo.packs.push_back(std::move(*pack));-        }-    }-    return repo;-}--std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify, std::size_t depth) {-    if (depth > MAX_GIT_DELTA_DEPTH)-        return std::nullopt;-    for (auto& pack : repo.packs) {-        auto idx = find_oid(pack, oid);-        if (!idx)-            continue;-        auto object = read_at(repo, pack, pack.offsets[*idx], verify, depth);-        if (!object)-            return std::nullopt;-        if (verify) {-            auto hash = object_hash(object->kind, Bytes(object->body.data(), object->body.size()));-            if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)-                return std::nullopt;-        }-        return object;-    }-    return read_loose(repo, oid, verify);-}--std::shared_ptr<Repo> cached_repo(const fs::path& git_dir) {-    static std::mutex mutex;-    static std::map<std::string, std::pair<fs::file_time_type, std::shared_ptr<Repo>>> cache;-    std::error_code ec;-    const fs::path pack_dir = git_dir / "objects" / "pack";-    const fs::file_time_type stamp = fs::last_write_time(pack_dir, ec);-    const std::string key = path_to_bytes(git_dir);-    std::lock_guard<std::mutex> lock(mutex);-    auto it = cache.find(key);-    if (it != cache.end() && !ec && it->second.first == stamp)-        return it->second.second;-    auto repo = open_repo(git_dir);-    if (!repo)-        return nullptr;-    auto shared = std::make_shared<Repo>(std::move(*repo));-    cache[key] = {stamp, shared};-    return shared;-}--std::optional<Sig> parse_sig(std::string_view value) {-    const std::size_t tz_space = value.rfind(' ');-    if (tz_space == std::string_view::npos || tz_space == 0)-        return std::nullopt;-    const std::size_t sec_space = value.rfind(' ', tz_space - 1);-    if (sec_space == std::string_view::npos)-        return std::nullopt;-    const std::string_view sec_text = value.substr(sec_space + 1, tz_space - sec_space - 1);-    const std::string_view tz_text = value.substr(tz_space + 1);-    if (sec_text.empty() || tz_text.size() != 5 || (tz_text[0] != '+' && tz_text[0] != '-'))-        return std::nullopt;-    std::uint64_t magnitude = 0;-    bool negative = false;-    std::size_t i = 0;-    if (sec_text[0] == '-') {-        negative = true;-        i = 1;-    }-    if (i >= sec_text.size())-        return std::nullopt;-    for (; i < sec_text.size(); ++i) {-        if (sec_text[i] < '0' || sec_text[i] > '9')-            return std::nullopt;-        const std::uint64_t digit = static_cast<std::uint64_t>(sec_text[i] - '0');-        if (magnitude >-            (static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) - digit) / 10)-            return std::nullopt;-        magnitude = magnitude * 10 + digit;-    }-    std::int64_t seconds = static_cast<std::int64_t>(magnitude);-    if (negative)-        seconds = -seconds;-    std::int64_t hh = 0;-    std::int64_t mm = 0;-    for (std::size_t j = 1; j < 3; ++j) {-        if (tz_text[j] < '0' || tz_text[j] > '9')-            return std::nullopt;-        hh = hh * 10 + (tz_text[j] - '0');-    }-    for (std::size_t j = 3; j < 5; ++j) {-        if (tz_text[j] < '0' || tz_text[j] > '9')-            return std::nullopt;-        mm = mm * 10 + (tz_text[j] - '0');-    }-    std::int64_t tz = hh * 60 + mm;-    if (tz_text[0] == '-')-        tz = -tz;-    if (tz > 32767 || tz < -32768)-        return std::nullopt;--    const std::string_view ident = value.substr(0, sec_space);-    const std::size_t lt = ident.rfind('<');-    const std::size_t gt = ident.rfind('>');-    if (lt == std::string_view::npos || gt == std::string_view::npos || gt <= lt)-        return std::nullopt;-    std::string_view name = ident.substr(0, lt);-    if (!name.empty() && name.back() == ' ')-        name.remove_suffix(1);-    Sig sig;-    sig.name = std::string(name);-    sig.email = std::string(ident.substr(lt + 1, gt - lt - 1));-    sig.seconds = seconds;-    sig.tz_min = static_cast<std::int16_t>(tz);-    return sig;-}--namespace {--void append_sig(std::vector<std::uint8_t>& out, const Sig& sig) {-    auto append = [&](std::string_view text) { out.insert(out.end(), text.begin(), text.end()); };-    append(sig.name);-    append(" <");-    append(sig.email);-    append("> ");-    append(std::to_string(sig.seconds));-    out.push_back(' ');-    const std::int64_t minutes = sig.tz_min;-    const std::int64_t abs_min = minutes < 0 ? -minutes : minutes;-    out.push_back(minutes < 0 ? '-' : '+');-    const std::int64_t hh = abs_min / 60;-    const std::int64_t mm = abs_min % 60;-    out.push_back(static_cast<std::uint8_t>('0' + hh / 10));-    out.push_back(static_cast<std::uint8_t>('0' + hh % 10));-    out.push_back(static_cast<std::uint8_t>('0' + mm / 10));-    out.push_back(static_cast<std::uint8_t>('0' + mm % 10));-}--std::optional<ChangeId> parse_change_id(std::string_view text) {-    if (text.size() != 32)-        return std::nullopt;-    ChangeId id{};-    if (!hex_decode(text, MutBytes(id.data(), id.size())))-        return std::nullopt;-    return id;-}--bool canonical_mode(std::string_view mode) {-    return mode == "100644" || mode == "100755" || mode == "120000" || mode == "40000" ||-           mode == "160000";-}--} // namespace--std::optional<ParsedCommit> parse_commit(Bytes body) {-    const std::string_view text(reinterpret_cast<const char*>(body.data()), body.size());-    const std::size_t blank = text.find("\n\n");-    if (blank == std::string_view::npos)-        return std::nullopt;-    ParsedCommit out;-    out.message = std::string(text.substr(blank + 2));-    const std::size_t header_end = blank;-    std::size_t pos = 0;-    int last_extra = -1;-    std::size_t last_extra_start = 0;-    while (pos < header_end) {-        std::size_t line_end = text.find('\n', pos);-        if (line_end == std::string_view::npos || line_end > header_end)-            line_end = header_end;-        const std::string_view line = text.substr(pos, line_end - pos);-        if (!line.empty() && line.front() == ' ') {-            if (last_extra < 0) {-                out.canonical = false;-            } else {-                out.extras[static_cast<std::size_t>(last_extra)].value =-                    std::string(text.substr(last_extra_start, line_end - last_extra_start));-            }-        } else {-            last_extra = -1;-            const std::size_t space = line.find(' ');-            if (space == std::string_view::npos || space == 0) {-                out.canonical = false;-            } else {-                const std::string_view key = line.substr(0, space);-                const std::string_view value = line.substr(space + 1);-                if (key == "tree") {-                    if (auto oid = oid_from_hex(value))-                        out.tree = *oid;-                    else-                        out.canonical = false;-                } else if (key == "parent") {-                    if (auto oid = oid_from_hex(value))-                        out.parents.push_back(*oid);-                    else-                        out.canonical = false;-                } else if (key == "author") {-                    if (auto sig = parse_sig(value))-                        out.author = *sig;-                    else-                        out.canonical = false;-                } else if (key == "committer") {-                    if (auto sig = parse_sig(value))-                        out.committer = *sig;-                    else-                        out.canonical = false;-                } else if (key == "veins-change-id") {-                    if (auto change = parse_change_id(value))-                        out.change_id = *change;-                    else-                        out.canonical = false;-                } else {-                    out.extras.push_back(KeyValue{std::string(key), std::string(value)});-                    last_extra = static_cast<int>(out.extras.size() - 1);-                    last_extra_start = pos + key.size() + 1;-                }-            }-        }-        pos = line_end + 1;-    }-    return out;-}--std::vector<std::uint8_t> serialize_commit(const ParsedCommit& commit) {-    std::vector<std::uint8_t> out;-    auto append = [&](std::string_view text) { out.insert(out.end(), text.begin(), text.end()); };-    append("tree ");-    append(oid_hex(commit.tree));-    out.push_back('\n');-    for (const auto& parent : commit.parents) {-        append("parent ");-        append(oid_hex(parent));-        out.push_back('\n');-    }-    append("author ");-    append_sig(out, commit.author);-    out.push_back('\n');-    append("committer ");-    append_sig(out, commit.committer);-    out.push_back('\n');-    for (const auto& kv : commit.extras) {-        append(kv.key);-        out.push_back(' ');-        append(kv.value);-        out.push_back('\n');-    }-    out.push_back('\n');-    append(commit.message);-    return out;-}--std::optional<ParsedTree> parse_tree(Bytes body) {-    ParsedTree out;-    std::size_t pos = 0;-    while (pos < body.size()) {-        const std::size_t mode_start = pos;-        while (pos < body.size() && body[pos] != ' ')-            ++pos;-        if (pos >= body.size()) {-            out.canonical = false;-            break;-        }-        const std::string mode(reinterpret_cast<const char*>(body.data() + mode_start),-                               pos - mode_start);-        ++pos;-        const std::size_t name_start = pos;-        while (pos < body.size() && body[pos] != 0)-            ++pos;-        if (pos >= body.size()) {-            out.canonical = false;-            break;-        }-        const std::string name(reinterpret_cast<const char*>(body.data() + name_start),-                               pos - name_start);-        ++pos;-        if (pos + 20 > body.size()) {-            out.canonical = false;-            break;-        }-        RawTreeEntry entry;-        entry.mode = mode;-        entry.name = name;-        std::memcpy(entry.oid.data(), body.data() + pos, 20);-        pos += 20;-        if (!canonical_mode(mode))-            out.canonical = false;-        out.entries.push_back(std::move(entry));-    }-    if (pos != body.size())-        out.canonical = false;-    return out;-}--std::string mode_for_kind(std::uint8_t kind) {-    if (kind == KIND_EXECUTABLE)-        return "100755";-    if (kind == KIND_SYMLINK)-        return "120000";-    if (kind == KIND_SUBTREE)-        return "40000";-    if (kind == KIND_SUBMODULE)-        return "160000";-    return "100644";-}--std::uint8_t mode_kind(std::string_view mode) {-    if (mode == "40000" || mode == "040000")-        return KIND_SUBTREE;-    if (mode == "120000")-        return KIND_SYMLINK;-    if (mode == "160000")-        return KIND_SUBMODULE;-    if (mode == "100755")-        return KIND_EXECUTABLE;-    return KIND_FILE;-}--std::optional<ParsedTag> parse_tag(Bytes body) {-    ParsedTag out;-    const std::string_view text(reinterpret_cast<const char*>(body.data()), body.size());-    std::size_t pos = 0;-    while (pos < text.size()) {-        std::size_t end = text.find('\n', pos);-        if (end == std::string_view::npos)-            end = text.size();-        const std::string_view line = text.substr(pos, end - pos);-        if (line.empty())-            break;-        const std::size_t space = line.find(' ');-        if (space != std::string_view::npos && space != 0) {-            const std::string_view key = line.substr(0, space);-            const std::string_view value = line.substr(space + 1);-            if (key == "object") {-                if (auto oid = oid_from_hex(value))-                    out.target = *oid;-            } else if (key == "type") {-                out.target_kind = kind_from_name(value);-            }-        }-        pos = end + 1;-    }-    return out;-}--std::optional<Id> IdMap::get(const Oid& oid) const {-    auto it = items.find(oid);-    if (it == items.end())-        return std::nullopt;-    return it->second;-}--void IdMap::put(const Oid& oid, const Id& id) {-    items[oid] = id;-}--std::optional<Oid> IdMap::reverse(const Id& id) const {-    for (const auto& item : items) {-        if (item.second == id)-            return item.first;-    }-    return std::nullopt;-}--namespace {--fs::path map_path(const fs::path& root, std::string_view name) {-    return git_map_dir(root) / path_from_bytes(std::string(name) + ".map");-}--} // namespace--bool load_map(const fs::path& root, std::string_view name, IdMap& out) {-    out.items.clear();-    auto data = read_file_opt(map_path(root, name));-    if (!data)-        return true;-    if (data->size() < 9 || std::memcmp(data->data(), "VMAP1", 5) != 0)-        return false;-    const std::uint32_t count = static_cast<std::uint32_t>((*data)[5]) |-                                (static_cast<std::uint32_t>((*data)[6]) << 8) |-                                (static_cast<std::uint32_t>((*data)[7]) << 16) |-                                (static_cast<std::uint32_t>((*data)[8]) << 24);-    if (data->size() != 9 + static_cast<std::size_t>(count) * 52)-        return false;-    for (std::size_t i = 0; i < count; ++i) {-        const std::size_t off = 9 + i * 52;-        Oid oid{};-        std::memcpy(oid.data(), data->data() + off, 20);-        Id id{};-        std::memcpy(id.data(), data->data() + off + 20, 32);-        out.put(oid, id);-    }-    return true;-}--bool save_map(const fs::path& root, std::string_view name, const IdMap& map) {-    std::vector<std::uint8_t> data;-    data.insert(data.end(), {'V', 'M', 'A', 'P', '1'});-    const std::uint32_t count = static_cast<std::uint32_t>(map.items.size());-    data.push_back(static_cast<std::uint8_t>(count & 0xff));-    data.push_back(static_cast<std::uint8_t>((count >> 8) & 0xff));-    data.push_back(static_cast<std::uint8_t>((count >> 16) & 0xff));-    data.push_back(static_cast<std::uint8_t>((count >> 24) & 0xff));-    for (const auto& item : map.items) {-        data.insert(data.end(), item.first.begin(), item.first.end());-        data.insert(data.end(), item.second.begin(), item.second.end());-    }-    return write_atomic(map_path(root, name), Bytes(data.data(), data.size()));-}--bool save_raw(const fs::path& root, const Id& id, Bytes body) {-    const fs::path path = git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id));-    return write_atomic(path, body);-}--std::optional<std::vector<std::uint8_t>> load_raw(const fs::path& root, const Id& id) {-    return read_file_opt(git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id)));-}--RefSet read_refs(const fs::path& git_dir) {-    RefSet out;-    read_packed_refs(git_dir, out.branches, out.tags);-    read_ref_dir(git_dir / "refs" / "heads", "", out.branches);-    read_ref_dir(git_dir / "refs" / "tags", "", out.tags);-    read_ref_dir(git_dir / "refs" / "remotes", "", out.remotes);-    out.head = resolve_head(git_dir, out.branches, out.tags);-    return out;-}--Id lazy_blob_id(const Oid& oid) {-    Id id{};-    std::memcpy(id.data(), "veins-gitoid", 12);-    std::memcpy(id.data() + 12, oid.data(), 20);-    return id;-}--std::optional<Oid> lazy_blob_oid(const Id& id) {-    if (!is_lazy_blob(id))-        return std::nullopt;-    Oid out{};-    std::memcpy(out.data(), id.data() + 12, 20);-    return out;-}--bool ensure_mirror(const fs::path& root) {-    const fs::path dir = git_dir(root);-    if (!ensure_directory(dir) || !ensure_directory(dir / "objects") ||-        !ensure_directory(dir / "refs" / "heads") || !ensure_directory(dir / "refs" / "tags"))-        return false;-    if (!path_is_file(dir / "HEAD")) {-        const std::string body = "ref: refs/heads/main\n";-        if (!write_file(dir / "HEAD", bytes_of(body)))-            return false;-    }-    if (!path_is_file(dir / "config")) {-        const std::string body = "[core]\n\trepositoryformatversion = "-                                 "0\n\tfilemode = true\n\tbare = true\n";-        if (!write_file(dir / "config", bytes_of(body)))-            return false;-    }-    return true;-}--int prepare_mirror(const fs::path& root, const fs::path& source) {-    const fs::path target = git_dir(root);-    if (path_is_file(target / "HEAD"))-        return 0;-    const auto resolved = resolve_source(source);-    if (!resolved)-        return 2;-    if (!copy_tree(*resolved, target))-        return 3;-    return 0;-}--bool write_loose(const fs::path& git_dir, std::uint8_t kind, const Oid& oid, Bytes body) {-    const std::string hex = oid_hex(oid);-    const fs::path final_path =-        git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) / path_from_bytes(hex.substr(2));-    if (path_is_file(final_path))-        return true;-    std::string header = kind_name(kind);-    header.push_back(' ');-    header += std::to_string(body.size());-    header.push_back('\0');-    uLongf bound = compressBound(static_cast<uLong>(header.size() + body.size()));-    std::vector<std::uint8_t> compressed(bound);-    uLongf dest_len = bound;-    std::vector<std::uint8_t> raw;-    raw.reserve(header.size() + body.size());-    raw.insert(raw.end(), header.begin(), header.end());-    raw.insert(raw.end(), body.begin(), body.end());-    const int rc =-        compress2(compressed.data(), &dest_len, raw.data(), static_cast<uLong>(raw.size()), 6);-    if (rc != Z_OK)-        return false;-    compressed.resize(dest_len);-    return write_atomic(final_path, Bytes(compressed.data(), compressed.size()));-}--bool write_ref(const fs::path& git_dir, std::string_view name, const Oid& oid) {-    const std::string line = oid_hex(oid) + "\n";-    return write_atomic(git_dir / path_from_bytes(name), bytes_of(line));-}--std::string remote_key(std::string_view remote, std::string_view field) {-    std::string out = "remote.";-    out += remote;-    out.push_back('.');-    out += field;-    return out;-}--std::vector<std::string> list_remotes(const fs::path& root) {-    std::vector<std::string> out;-    auto data = read_file_opt(root / ".veins" / "config");-    if (!data)-        return out;-    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-        std::size_t end = text.find('\n', start);-        if (end == std::string_view::npos)-            end = text.size();-        const std::string_view line = text.substr(start, end - start);-        if (line.starts_with("remote.")) {-            const std::size_t dot = line.find(".url", 7);-            if (dot != std::string_view::npos && dot > 7)-                out.emplace_back(line.substr(7, dot - 7));-        }-        if (end == text.size())-            break;-        start = end + 1;-    }-    return out;-}--} // namespace vn::git--- a/xveins/src/main.cpp+++ /dev/null@@ -1,22 +0,0 @@-#include "cli/cli.h"--#include <exception>-#include <iostream>-#include <string>-#include <vector>--int main(int argc, char** argv) {-    std::vector<std::string> args;-    args.reserve(static_cast<std::size_t>(argc));-    for (int i = 0; i < argc; ++i)-        args.emplace_back(argv[i]);-    try {-        return vn::cli_run(args);-    } catch (const std::exception& e) {-        std::cout << "error: " << e.what() << "\n";-        return 1;-    } catch (...) {-        std::cout << "error: unexpected failure\n";-        return 1;-    }-}--- a/xveins/src/merge/merge.cpp+++ /dev/null@@ -1,2134 +0,0 @@-#include "merge/merge.h"--#include "worktree/pathspec.h"-#include "worktree/worktree.h"--#include <algorithm>-#include <cstdlib>-#include <cstring>-#include <iostream>-#include <set>-#include <utility>--namespace vn {--namespace {---bool same_id(const Id& a, const Id& b) {-    return std::memcmp(a.data(), b.data(), ID_LEN) == 0;-}--std::optional<std::vector<std::uint8_t>> read_body_any(Store& store, Txn* tx, std::uint8_t type,-                                                       const Id& id) {-    if (tx) {-        if (auto cached = tx->writer().find_cached(type, id))-            return cached;-    }-    return store.read_body(id, type);-}--bool append_blob_any(Store& store, Txn* tx, const Id& id, std::vector<std::uint8_t>& out,-                     std::size_t depth) {-    if (depth > 64)-        return false;-    auto body = read_body_any(store, tx, TYPE_BLOB, id);-    if (!body)-        return false;-    auto blob = decode_blob(bytes_of(*body));-    if (!blob)-        return false;-    if (blob->form == BlobForm::Inline) {-        out.insert(out.end(), blob->data.begin(), blob->data.end());-        return true;-    }-    for (const auto& entry : blob->entries) {-        if (blob->form == BlobForm::Leaf) {-            auto chunk = read_body_any(store, tx, TYPE_CHUNK, entry.id);-            if (!chunk)-                return false;-            out.insert(out.end(), chunk->begin(), chunk->end());-        } else if (!append_blob_any(store, tx, entry.id, out, depth + 1)) {-            return false;-        }-    }-    return true;-}--std::optional<std::vector<std::uint8_t>> read_blob_any(Store& store, Txn* tx, const Id& id) {-    std::vector<std::uint8_t> out;-    if (!append_blob_any(store, tx, id, out, 0))-        return std::nullopt;-    return out;-}--bool collect_chunks_any(Store& store, Txn* tx, const Id& id, std::vector<Id>& out,-                        std::size_t depth) {-    if (depth > 64)-        return false;-    auto body = read_body_any(store, tx, TYPE_BLOB, id);-    if (!body)-        return false;-    auto blob = decode_blob(bytes_of(*body));-    if (!blob)-        return false;-    if (blob->form == BlobForm::Leaf) {-        for (const auto& entry : blob->entries)-            out.push_back(entry.id);-        return true;-    }-    if (blob->form == BlobForm::Interior) {-        for (const auto& entry : blob->entries) {-            if (!collect_chunks_any(store, tx, entry.id, out, depth + 1))-                return false;-        }-    }-    return true;-}--bool flatten_any(Store& store, Txn* tx, const Id& tree_id, std::string& prefix,-                 std::vector<FlatEntry>& out, std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return false;-    auto body = read_body_any(store, tx, TYPE_TREE, tree_id);-    if (!body)-        return false;-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-        return false;-    for (const auto& entry : tree->entries) {-        const std::size_t old_size = prefix.size();-        if (!prefix.empty())-            prefix.push_back('/');-        prefix.append(entry.name);-        if (entry.kind == KIND_SUBTREE) {-            if (!flatten_any(store, tx, entry.target, prefix, out, depth + 1)) {-                prefix.resize(old_size);-                return false;-            }-            prefix.resize(old_size);-        } else {-            out.push_back(FlatEntry{prefix, entry.kind, entry.target});-            prefix.resize(old_size);-        }-    }-    return true;-}--std::vector<FlatEntry> flatten_any_sorted(Store& store, Txn* tx, std::optional<Id> tree) {-    std::vector<FlatEntry> out;-    if (!tree)-        return out;-    std::string prefix;-    (void)flatten_any(store, tx, *tree, prefix, out, 0);-    std::stable_sort(out.begin(), out.end(), [](const FlatEntry& a, const FlatEntry& b) {-        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-    });-    return out;-}--const FlatEntry* find_flat_entry(const std::vector<FlatEntry>& entries, std::string_view path) {-    for (const auto& entry : entries) {-        if (entry.path == path)-            return &entry;-    }-    return nullptr;-}--bool tree_empty_any(Store& store, Txn* tx, const Id& id) {-    auto body = read_body_any(store, tx, TYPE_TREE, id);-    if (!body)-        return true;-    auto tree = decode_tree(bytes_of(*body));-    return !tree || tree->entries.empty();-}--Id add_tree(Txn& tx, const std::vector<TreeEntry>& entries) {-    auto encoded = encode_tree(entries);-    if (!encoded)-        return Id{};-    return tx.add_object(TYPE_TREE, *encoded);-}--Id add_empty_tree(Txn& tx) {-    return add_tree(tx, {});-}--Id add_blob(Txn& tx, Bytes data) {-    BlobBuild build = build_blob(data);-    for (auto& object : build.objects) {-        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));-        (void)tx.add_known(object.type, id, std::move(object.body));-    }-    return build.root;-}---struct DiffOp {-    char tag = ' ';-    std::size_t ai = 0;-    std::size_t bi = 0;-};--std::vector<std::string> split_lines(Bytes data) {-    std::vector<std::string> out;-    std::size_t start = 0;-    for (std::size_t i = 0; i < data.size(); ++i) {-        if (data[i] == '\n') {-            out.emplace_back(reinterpret_cast<const char*>(data.data() + start), i + 1 - start);-            start = i + 1;-        }-    }-    if (start < data.size())-        out.emplace_back(reinterpret_cast<const char*>(data.data() + start), data.size() - start);-    return out;-}--std::vector<DiffOp> fallback_ops(const std::vector<std::string>& a,-                                 const std::vector<std::string>& b) {-    const std::size_t n = a.size();-    const std::size_t m = b.size();-    std::size_t prefix = 0;-    while (prefix < n && prefix < m && a[prefix] == b[prefix])-        ++prefix;-    std::size_t suffix = 0;-    while (suffix < n - prefix && suffix < m - prefix && a[n - 1 - suffix] == b[m - 1 - suffix])-        ++suffix;-    std::vector<DiffOp> ops;-    for (std::size_t i = 0; i < prefix; ++i)-        ops.push_back(DiffOp{' ', i, i});-    for (std::size_t i = prefix; i < n - suffix; ++i)-        ops.push_back(DiffOp{'-', i, 0});-    for (std::size_t j = prefix; j < m - suffix; ++j)-        ops.push_back(DiffOp{'+', 0, j});-    for (std::size_t k = 0; k < suffix; ++k)-        ops.push_back(DiffOp{' ', n - suffix + k, m - suffix + k});-    return ops;-}--std::vector<DiffOp> build_ops(const std::vector<std::string>& a,-                              const std::vector<std::string>& b) {-    const std::size_t n = a.size();-    const std::size_t m = b.size();-    const std::uint64_t cells =-        static_cast<std::uint64_t>(n + 1) * static_cast<std::uint64_t>(m + 1);-    if (cells > 8000000)-        return fallback_ops(a, b);-    const std::size_t cols = m + 1;-    std::vector<std::uint32_t> dp(static_cast<std::size_t>(cells), 0);-    for (std::size_t i = 1; i <= n; ++i) {-        for (std::size_t j = 1; j <= m; ++j) {-            if (a[i - 1] == b[j - 1]) {-                dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;-            } else {-                dp[i * cols + j] = std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);-            }-        }-    }-    std::vector<DiffOp> ops;-    std::size_t oi = n;-    std::size_t oj = m;-    while (oi > 0 || oj > 0) {-        if (oi > 0 && oj > 0 && a[oi - 1] == b[oj - 1]) {-            ops.push_back(DiffOp{' ', oi - 1, oj - 1});-            --oi;-            --oj;-        } else if (oj > 0 && (oi == 0 || dp[oi * cols + (oj - 1)] >= dp[(oi - 1) * cols + oj])) {-            ops.push_back(DiffOp{'+', 0, oj - 1});-            --oj;-        } else {-            ops.push_back(DiffOp{'-', oi - 1, 0});-            --oi;-        }-    }-    std::reverse(ops.begin(), ops.end());-    return ops;-}--struct Hunk {-    std::size_t start = 0;-    std::size_t end = 0;-    std::vector<std::string> lines;-};--std::vector<Hunk> hunks_from_ops(const std::vector<std::string>& side,-                                 const std::vector<DiffOp>& ops) {-    std::vector<Hunk> out;-    std::size_t base_pos = 0;-    std::size_t i = 0;-    while (i < ops.size()) {-        if (ops[i].tag == ' ') {-            ++base_pos;-            ++i;-            continue;-        }-        Hunk hunk;-        hunk.start = base_pos;-        while (i < ops.size() && ops[i].tag != ' ') {-            if (ops[i].tag == '-') {-                ++base_pos;-            } else {-                hunk.lines.push_back(side[ops[i].bi]);-            }-            ++i;-        }-        hunk.end = base_pos;-        out.push_back(std::move(hunk));-    }-    return out;-}--std::vector<Hunk> diff_hunks(const std::vector<std::string>& base,-                             const std::vector<std::string>& side) {-    return hunks_from_ops(side, build_ops(base, side));-}--struct MergeRange {-    std::size_t base_start = 0;-    std::size_t base_end = 0;-    std::size_t ours_start = 0;-    std::size_t ours_end = 0;-    std::size_t theirs_start = 0;-    std::size_t theirs_end = 0;-};--struct EditResult {-    bool conflicted = false;-    std::vector<std::uint8_t> data;-    std::vector<MergeRange> ranges;-};--void append_lines(std::vector<std::uint8_t>& out, const std::vector<std::string>& lines,-                  std::size_t start, std::size_t end) {-    for (std::size_t i = start; i < end && i < lines.size(); ++i)-        out.insert(out.end(), lines[i].begin(), lines[i].end());-}--void apply_hunks(std::vector<std::uint8_t>& out, const std::vector<std::string>& base,-                 std::size_t from, std::size_t to, const std::vector<Hunk>& hunks,-                 std::size_t first, std::size_t last) {-    std::size_t pos = from;-    for (std::size_t k = first; k < last; ++k) {-        const Hunk& h = hunks[k];-        if (h.start > pos && h.start <= to)-            append_lines(out, base, pos, h.start);-        for (const auto& line : h.lines)-            out.insert(out.end(), line.begin(), line.end());-        if (h.end > pos)-            pos = h.end;-    }-    if (pos < to)-        append_lines(out, base, pos, to);-}--std::size_t map_pos(const std::vector<Hunk>& hunks, std::size_t pos) {-    std::ptrdiff_t out = static_cast<std::ptrdiff_t>(pos);-    for (const auto& h : hunks) {-        if (h.end <= pos) {-            const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(h.end - h.start);-            const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());-            out += fresh - old;-        } else if (h.start < pos) {-            const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(pos - h.start);-            const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());-            out += fresh - old;-            break;-        } else {-            break;-        }-    }-    return static_cast<std::size_t>(out);-}--bool same_hunks(const std::vector<Hunk>& ours, std::size_t of, std::size_t ol,-                const std::vector<Hunk>& theirs, std::size_t tf, std::size_t tl) {-    std::string a;-    std::string b;-    for (std::size_t k = of; k < ol; ++k)-        for (const auto& line : ours[k].lines)-            a += line;-    for (std::size_t j = tf; j < tl; ++j)-        for (const auto& line : theirs[j].lines)-            b += line;-    return a == b;-}--EditResult merge_lines(const std::vector<std::string>& base, const std::vector<std::string>& ours,-                       const std::vector<std::string>& theirs, bool adjacent_merge) {-    const auto ours_h = diff_hunks(base, ours);-    const auto theirs_h = diff_hunks(base, theirs);-    EditResult result;-    std::size_t oi = 0;-    std::size_t ti = 0;-    std::size_t pos = 0;-    while (oi < ours_h.size() || ti < theirs_h.size()) {-        const bool have_o = oi < ours_h.size();-        const bool have_t = ti < theirs_h.size();-        const std::size_t o_start = have_o ? ours_h[oi].start : 0;-        const std::size_t t_start = have_t ? theirs_h[ti].start : 0;-        const bool take_ours_cluster = have_o && (!have_t || o_start <= t_start);-        const std::size_t cluster_start = take_ours_cluster ? o_start : t_start;-        const std::size_t of = oi;-        const std::size_t tf = ti;-        std::size_t o_last = of;-        std::size_t t_last = tf;-        std::size_t end = cluster_start;-        bool seen_o = false;-        bool seen_t = false;-        for (;;) {-            bool progress = false;-            if (o_last < ours_h.size()) {-                const Hunk& h = ours_h[o_last];-                bool include = h.start <= end;-                if (o_last != of)-                    include = adjacent_merge ? h.start < end : h.start <= end;-                if (include) {-                    seen_o = true;-                    ++o_last;-                    if (h.end > end)-                        end = h.end;-                    progress = true;-                }-            }-            if (t_last < theirs_h.size()) {-                const Hunk& h = theirs_h[t_last];-                bool include = h.start <= end;-                if (t_last != tf)-                    include = adjacent_merge ? h.start < end : h.start <= end;-                if (include) {-                    seen_t = true;-                    ++t_last;-                    if (h.end > end)-                        end = h.end;-                    progress = true;-                }-            }-            if (!progress)-                break;-        }-        if (end < cluster_start)-            end = cluster_start;-        if (seen_o && !seen_t) {-            apply_hunks(result.data, base, pos, end, ours_h, of, o_last);-            pos = end;-            oi = o_last;-            ti = t_last;-        } else if (seen_t && !seen_o) {-            apply_hunks(result.data, base, pos, end, theirs_h, tf, t_last);-            pos = end;-            oi = o_last;-            ti = t_last;-        } else {-            if (same_hunks(ours_h, of, o_last, theirs_h, tf, t_last)) {-                apply_hunks(result.data, base, pos, end, ours_h, of, o_last);-                pos = end;-            } else {-                result.conflicted = true;-                apply_hunks(result.data, base, pos, end, ours_h, of, o_last);-                MergeRange range;-                range.base_start = cluster_start;-                range.base_end = end;-                range.ours_start = map_pos(ours_h, cluster_start);-                range.ours_end = map_pos(ours_h, end);-                range.theirs_start = map_pos(theirs_h, cluster_start);-                range.theirs_end = map_pos(theirs_h, end);-                result.ranges.push_back(range);-                pos = end;-            }-            oi = o_last;-            ti = t_last;-        }-    }-    if (pos < base.size())-        append_lines(result.data, base, pos, base.size());-    return result;-}--std::optional<EditResult> merge_blobs(Store& store, Txn* tx, const Id& base_id, const Id& ours_id,-                                      const Id& theirs_id, bool adjacent) {-    auto base = read_blob_any(store, tx, base_id);-    auto ours = read_blob_any(store, tx, ours_id);-    auto theirs = read_blob_any(store, tx, theirs_id);-    if (!base || !ours || !theirs)-        return std::nullopt;-    return merge_lines(split_lines(bytes_of(*base)), split_lines(bytes_of(*ours)),-                       split_lines(bytes_of(*theirs)), adjacent);-}---struct RenamePair {-    std::string old_path;-    std::string new_path;-    std::size_t score = 0;-    bool old_used = false;-    bool new_used = false;-};--std::uint64_t hash_line(std::string_view line) {-    std::uint64_t h = 1469598103934665603ull;-    for (char raw : line) {-        const auto c = static_cast<unsigned char>(raw);-        h = (h ^ static_cast<std::uint64_t>(c)) * 1099511628211ull;-    }-    return h;-}--int line_similarity(Bytes a, Bytes b) {-    std::vector<std::uint64_t> la;-    std::vector<std::uint64_t> lb;-    std::size_t start = 0;-    for (std::size_t i = 0; i <= a.size(); ++i) {-        if (i == a.size() || a[i] == '\n') {-            la.push_back(hash_line(str_of(a.subspan(start, i - start))));-            start = i + 1;-        }-    }-    start = 0;-    for (std::size_t j = 0; j <= b.size(); ++j) {-        if (j == b.size() || b[j] == '\n') {-            lb.push_back(hash_line(str_of(b.subspan(start, j - start))));-            start = j + 1;-        }-    }-    std::sort(la.begin(), la.end());-    std::sort(lb.begin(), lb.end());-    std::size_t ia = 0;-    std::size_t ib = 0;-    std::size_t inter = 0;-    while (ia < la.size() && ib < lb.size()) {-        if (la[ia] == lb[ib]) {-            ++inter;-            ++ia;-            ++ib;-        } else if (la[ia] < lb[ib]) {-            ++ia;-        } else {-            ++ib;-        }-    }-    const std::size_t total = la.size() + lb.size() - inter;-    if (total == 0)-        return 100;-    return static_cast<int>((inter * 100) / total);-}--int chunk_similarity(Store& store, Txn* tx, const Id& a, const Id& b) {-    std::vector<Id> ca;-    std::vector<Id> cb;-    if (!collect_chunks_any(store, tx, a, ca, 0) || !collect_chunks_any(store, tx, b, cb, 0))-        return 0;-    std::size_t inter = 0;-    for (const auto& x : ca) {-        for (const auto& y : cb) {-            if (same_id(x, y)) {-                ++inter;-                break;-            }-        }-    }-    const std::size_t total = ca.size() + cb.size() - inter;-    if (total == 0)-        return 0;-    return static_cast<int>((inter * 100) / total);-}--int similarity(Store& store, Txn* tx, const Id& a, const Id& b) {-    if (same_id(a, b))-        return 100;-    auto da = read_blob_any(store, tx, a);-    auto db = read_blob_any(store, tx, b);-    if (!da || !db)-        return 0;-    int result = 0;-    if (da->size() >= 131072 && db->size() >= 131072)-        result = chunk_similarity(store, tx, a, b);-    if (result == 0)-        result = line_similarity(bytes_of(*da), bytes_of(*db));-    return result;-}--} // namespace--std::vector<Rename> detect_renames(Store& store, Txn* tx, std::optional<Id> old_tree,-                                   std::optional<Id> new_tree, int similar_pct,-                                   std::uint64_t parent_index) {-    const auto old_entries = flatten_any_sorted(store, tx, old_tree);-    const auto new_entries = flatten_any_sorted(store, tx, new_tree);-    std::vector<FlatEntry> deleted;-    std::vector<FlatEntry> added;-    for (const auto& entry : old_entries) {-        if (!find_flat_entry(new_entries, entry.path))-            deleted.push_back(entry);-    }-    for (const auto& entry : new_entries) {-        if (!find_flat_entry(old_entries, entry.path))-            added.push_back(entry);-    }-    std::vector<char> used_old(deleted.size(), 0);-    std::vector<char> used_new(added.size(), 0);-    std::vector<Rename> out;-    for (std::size_t di = 0; di < deleted.size(); ++di) {-        if (used_old[di])-            continue;-        for (std::size_t ai = 0; ai < added.size(); ++ai) {-            if (used_new[ai])-                continue;-            if (same_id(deleted[di].target, added[ai].target)) {-                out.push_back(Rename{parent_index, 0, deleted[di].path, added[ai].path});-                used_old[di] = 1;-                used_new[ai] = 1;-                break;-            }-        }-    }-    if (similar_pct > 0) {-        std::vector<RenamePair> pairs;-        constexpr std::size_t candidate_limit = 5000;-        for (std::size_t di = 0; di < deleted.size(); ++di) {-            if (used_old[di] ||-                (deleted[di].kind != KIND_FILE && deleted[di].kind != KIND_EXECUTABLE))-                continue;-            for (std::size_t ai = 0; ai < added.size() && pairs.size() < candidate_limit; ++ai) {-                if (used_new[ai] ||-                    (added[ai].kind != KIND_FILE && added[ai].kind != KIND_EXECUTABLE))-                    continue;-                RenamePair pair;-                pair.old_path = deleted[di].path;-                pair.new_path = added[ai].path;-                pair.score = static_cast<std::size_t>(-                    similarity(store, tx, deleted[di].target, added[ai].target));-                pairs.push_back(std::move(pair));-            }-        }-        for (;;) {-            std::ptrdiff_t best_i = -1;-            std::size_t best = 0;-            for (std::size_t i = 0; i < pairs.size(); ++i) {-                if (!pairs[i].old_used && !pairs[i].new_used && pairs[i].score > best) {-                    best = pairs[i].score;-                    best_i = static_cast<std::ptrdiff_t>(i);-                }-            }-            if (best_i < 0 || best < static_cast<std::size_t>(similar_pct))-                break;-            auto& pair = pairs[static_cast<std::size_t>(best_i)];-            pair.old_used = true;-            pair.new_used = true;-            out.push_back(Rename{parent_index, 0, pair.old_path, pair.new_path});-        }-    }-    std::stable_sort(out.begin(), out.end(), [](const Rename& a, const Rename& b) {-        if (a.parent_index != b.parent_index)-            return a.parent_index < b.parent_index;-        return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;-    });-    return out;-}--int rename_similar_pct(const fs::path& root) {-    if (auto value = repo_config_value(root, "rename.autodetect")) {-        if (*value == "off")-            return 0;-        return 60;-    }-    return 60;-}--namespace {---using RenameMap = std::vector<std::pair<std::string, std::string>>;--std::optional<std::string> rename_lookup(const RenameMap& map, std::string_view path) {-    for (const auto& entry : map) {-        if (entry.first == path)-            return entry.second;-    }-    return std::nullopt;-}--void rename_apply(RenameMap& map, const std::string& from, const std::string& to) {-    for (auto& entry : map) {-        if (entry.second == from) {-            entry.second = to;-            return;-        }-    }-    for (auto& entry : map) {-        if (entry.first == from) {-            entry.second = to;-            return;-        }-    }-    map.emplace_back(from, to);-}--std::optional<Id> tree_of(Store& store, const Id& commit_id) {-    auto loaded = load_commit(store, commit_id);-    if (!loaded)-        return std::nullopt;-    return loaded->commit.root_tree;-}--std::optional<Id> first_parent(Store& store, const Id& commit_id) {-    auto loaded = load_commit(store, commit_id);-    if (!loaded || loaded->commit.parents.empty())-        return std::nullopt;-    return loaded->commit.parents.front();-}--RenameMap map_from(Store& store, const Id& base, const Id& side) {-    RenameMap map;-    if (same_id(base, side))-        return map;-    std::vector<Id> chain;-    Id current = side;-    bool reached = false;-    for (std::size_t depth = 0; depth < 100000; ++depth) {-        if (same_id(current, base)) {-            reached = true;-            break;-        }-        chain.push_back(current);-        auto parent = first_parent(store, current);-        if (!parent)-            break;-        current = *parent;-    }-    if (!reached)-        return map;-    for (std::size_t i = chain.size(); i > 0; --i) {-        auto loaded = load_commit(store, chain[i - 1]);-        if (!loaded)-            continue;-        if (loaded->commit.renames_state == RENAMES_RECORDED) {-            for (const auto& rename : loaded->commit.renames) {-                if (rename.parent_index == 0)-                    rename_apply(map, rename.from_path, rename.to_path);-            }-        } else {-            auto parent = first_parent(store, chain[i - 1]);-            if (!parent)-                continue;-            auto old_tree = tree_of(store, *parent);-            auto new_tree = tree_of(store, chain[i - 1]);-            for (const auto& rename : detect_renames(store, nullptr, old_tree, new_tree, 50, 0))-                rename_apply(map, rename.from_path, rename.to_path);-        }-    }-    return map;-}--struct TreeTerm {-    bool positive = true;-    bool present = false;-    Id id{};-};--struct EntryTerm {-    bool positive = true;-    bool present = false;-    std::uint8_t kind = 0;-    std::optional<Id> target;-};--struct OrigEntry {-    std::size_t term = 0;-    std::string path;-    std::uint8_t kind = 0;-    Id target{};-};--struct OutEntry {-    std::string path;-    std::uint8_t kind = 0;-    Id target{};-};--struct MergeOutcome {-    Id tree{};-    std::size_t rerere = 0;-};--bool value_equal(const ConflictValue& a, const ConflictValue& b) {-    if (a.kind != b.kind)-        return false;-    if (a.kind == 0)-        return true;-    return a.target && b.target && same_id(*a.target, *b.target);-}--void flatten_values(Store& store, const std::vector<ConflictValue>& values, bool positive,-                    std::vector<ConflictValue>& adds, std::vector<ConflictValue>& removes,-                    std::size_t depth) {-    for (const auto& value : values) {-        if (value.kind == KIND_CONFLICT && value.target && depth < 64) {-            auto body = store.read_body(*value.target, TYPE_CONFLICT);-            if (body) {-                auto child = decode_conflict(bytes_of(*body));-                if (child) {-                    flatten_values(store, child->adds, positive, adds, removes, depth + 1);-                    flatten_values(store, child->removes, !positive, adds, removes, depth + 1);-                    continue;-                }-            }-        }-        if (positive)-            adds.push_back(value);-        else-            removes.push_back(value);-    }-}--Conflict simplify(Store& store, const std::vector<ConflictValue>& adds_in,-                  const std::vector<ConflictValue>& removes_in) {-    std::vector<ConflictValue> flat_adds;-    std::vector<ConflictValue> flat_removes;-    flatten_values(store, adds_in, true, flat_adds, flat_removes, 0);-    flatten_values(store, removes_in, false, flat_adds, flat_removes, 0);--    std::vector<char> used(flat_adds.size(), 0);-    std::vector<char> rem_used(flat_removes.size(), 0);-    for (std::size_t r = 0; r < flat_removes.size(); ++r) {-        for (std::size_t a = 0; a < flat_adds.size(); ++a) {-            if (!used[a] && value_equal(flat_adds[a], flat_removes[r])) {-                used[a] = 1;-                rem_used[r] = 1;-                break;-            }-        }-    }-    Conflict out;-    for (std::size_t a = 0; a < flat_adds.size(); ++a) {-        if (!used[a])-            out.adds.push_back(flat_adds[a]);-    }-    for (std::size_t r = 0; r < flat_removes.size(); ++r) {-        if (!rem_used[r])-            out.removes.push_back(flat_removes[r]);-    }-    return out;-}--std::optional<ConflictValue> resolved(const Conflict& conflict) {-    if (conflict.adds.empty())-        return std::nullopt;-    for (std::size_t i = 1; i < conflict.adds.size(); ++i) {-        if (!value_equal(conflict.adds[0], conflict.adds[i]))-            return std::nullopt;-    }-    return conflict.adds[0];-}--bool all_files(const Conflict& conflict) {-    for (const auto& value : conflict.adds) {-        if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE && value.kind != 0)-            return false;-    }-    for (const auto& value : conflict.removes) {-        if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE && value.kind != 0)-            return false;-    }-    return true;-}--int merge_mode(const Conflict& conflict) {-    if (conflict.adds.size() != 2 || conflict.removes.size() != 1)-        return -1;-    auto mode = [](const ConflictValue& value) -> int {-        if (value.kind == 0)-            return -1;-        return value.kind == KIND_EXECUTABLE ? 1 : 0;-    };-    const int m0 = mode(conflict.adds[0]);-    const int m1 = mode(conflict.adds[1]);-    const int mr = mode(conflict.removes[0]);-    if (m0 < 0 || m1 < 0)-        return -1;-    if (m0 == m1)-        return m0;-    if (mr >= 0 && m0 == mr)-        return m1;-    if (mr >= 0 && m1 == mr)-        return m0;-    return -1;-}--bool merge_binary(const fs::path& repo, std::string_view path) {-    auto data = read_file_opt(repo / ".vnmergedata");-    if (!data)-        return false;-    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());-    bool result = false;-    std::size_t start = 0;-    for (std::size_t pos = 0; pos <= text.size(); ++pos) {-        if (pos != text.size() && text[pos] != '\n')-            continue;-        std::string_view line = text.substr(start, pos - start);-        start = pos + 1;-        while (!line.empty() && (line.front() == ' ' || line.front() == '\t' ||-                                 line.front() == '\r' || line.front() == '\n'))-            line.remove_prefix(1);-        while (!line.empty() && (line.back() == ' ' || line.back() == '\t' || line.back() == '\r' ||-                                 line.back() == '\n'))-            line.remove_suffix(1);-        if (line.empty() || line.front() == '#')-            continue;-        std::size_t glob_end = 0;-        while (glob_end < line.size() && line[glob_end] != ' ' && line[glob_end] != '\t')-            ++glob_end;-        const std::string_view glob = line.substr(0, glob_end);-        std::string_view base = glob;-        if (const auto slash = glob.rfind('/'); slash != std::string_view::npos)-            base = glob.substr(slash + 1);-        const bool matched = glob_match(glob, path) ||-                             (glob.find('/') == std::string_view::npos && glob_match(base, path));-        if (!matched)-            continue;-        std::size_t t = glob_end;-        while (t < line.size()) {-            while (t < line.size() && (line[t] == ' ' || line[t] == '\t'))-                ++t;-            const std::size_t tok_start = t;-            while (t < line.size() && line[t] != ' ' && line[t] != '\t')-                ++t;-            const std::string_view token = line.substr(tok_start, t - tok_start);-            const auto eq = token.find('=');-            if (eq != std::string_view::npos) {-                const std::string_view key = token.substr(0, eq);-                const std::string_view value = token.substr(eq + 1);-                if (key == "merge") {-                    if (value == "binary")-                        result = true;-                    else if (value == "text")-                        result = false;-                }-            }-        }-    }-    return result;-}--std::optional<Id> resolution_lookup(const fs::path& repo, Bytes body) {-    const auto digest = blake3_hash(body);-    const std::string key = hex_encode(Bytes(digest.data(), digest.size()));-    auto data = read_file_opt(resolutions_dir(repo) / key);-    if (!data || data->size() < 64)-        return std::nullopt;-    const std::string_view text(reinterpret_cast<const char*>(data->data()), 64);-    Id id{};-    if (!hex_decode(text, MutBytes(id.data(), id.size())))-        return std::nullopt;-    return id;-}--void resolution_record(const fs::path& repo, Bytes body, const Id& blob) {-    const auto digest = blake3_hash(body);-    const std::string key = hex_encode(Bytes(digest.data(), digest.size()));-    (void)write_file(resolutions_dir(repo) / key, bytes_of(hex_encode(blob)));-}--Id build_level(Txn& tx, const std::vector<OutEntry>& entries, std::size_t start, std::size_t end,-               std::size_t prefix_len) {-    std::vector<TreeEntry> out;-    std::size_t i = start;-    while (i < end) {-        const OutEntry& entry = entries[i];-        const std::size_t name_end = entry.path.find('/', prefix_len);-        const std::size_t cut = name_end == std::string::npos ? entry.path.size() : name_end;-        const std::string name = entry.path.substr(prefix_len, cut - prefix_len);-        if (cut == entry.path.size()) {-            out.push_back(TreeEntry{name, entry.kind, entry.target});-            ++i;-        } else {-            std::size_t j = i + 1;-            while (j < end) {-                const std::size_t other_end = entries[j].path.find('/', prefix_len);-                const std::size_t other_cut =-                    other_end == std::string::npos ? entries[j].path.size() : other_end;-                if (other_cut != cut ||-                    entries[j].path.compare(prefix_len, cut - prefix_len, name) != 0)-                    break;-                ++j;-            }-            const Id child = build_level(tx, entries, i, j, cut + 1);-            out.push_back(TreeEntry{name, KIND_SUBTREE, child});-            i = j;-        }-    }-    return add_tree(tx, out);-}--Id build_from_entries(Txn& tx, std::vector<OutEntry>& entries) {-    if (entries.empty())-        return add_empty_tree(tx);-    std::stable_sort(entries.begin(), entries.end(), [](const OutEntry& a, const OutEntry& b) {-        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-    });-    return build_level(tx, entries, 0, entries.size(), 0);-}--Id build_subtree(Txn& tx, const std::vector<OrigEntry>& canon, std::size_t term,-                 std::string_view prefix) {-    std::vector<OutEntry> rels;-    for (const auto& entry : canon) {-        if (entry.term != term)-            continue;-        if (entry.path.size() > prefix.size() &&-            entry.path.compare(0, prefix.size(), prefix) == 0 && entry.path[prefix.size()] == '/')-            rels.push_back(-                OutEntry{entry.path.substr(prefix.size() + 1), entry.kind, entry.target});-    }-    return build_from_entries(tx, rels);-}--bool has_prefix(std::string_view path, std::string_view prefix) {-    return path.size() > prefix.size() && path.compare(0, prefix.size(), prefix) == 0 &&-           path[prefix.size()] == '/';-}--std::optional<OutEntry> merge_entry(const fs::path& repo, Txn& tx, Store& store,-                                    const std::string& path, const std::vector<EntryTerm>& terms,-                                    bool adjacent, std::size_t& rerere) {-    std::vector<ConflictValue> adds;-    std::vector<ConflictValue> removes;-    for (const auto& term : terms) {-        ConflictValue value;-        if (term.present) {-            value.kind = term.kind;-            value.target = term.target;-        }-        if (term.positive)-            adds.push_back(value);-        else-            removes.push_back(value);-    }-    Conflict sum = simplify(store, adds, removes);-    if (auto value = resolved(sum)) {-        if (value->kind == 0)-            return std::nullopt;-        return OutEntry{path, value->kind, *value->target};-    }-    if (all_files(sum) && sum.adds.size() == 2 && sum.removes.size() == 1 &&-        sum.adds[0].kind != 0 && sum.adds[1].kind != 0 && sum.removes[0].kind != 0 &&-        !merge_binary(repo, path)) {-        auto merged = merge_blobs(store, &tx, *sum.removes[0].target, *sum.adds[0].target,-                                  *sum.adds[1].target, adjacent);-        if (merged && !merged->conflicted) {-            const Id blob = add_blob(tx, bytes_of(merged->data));-            const int mode = merge_mode(sum);-            if (mode >= 0)-                return OutEntry{-                    path, static_cast<std::uint8_t>(mode == 1 ? KIND_EXECUTABLE : KIND_FILE), blob};-        }-    }-    const auto body = encode_conflict(sum);-    if (all_files(sum)) {-        if (auto memo = resolution_lookup(repo, bytes_of(body))) {-            ++rerere;-            return OutEntry{path, KIND_FILE, *memo};-        }-    }-    const Id id = tx.add_object(TYPE_CONFLICT, body);-    return OutEntry{path, KIND_CONFLICT, id};-}--MergeOutcome treemerge(const fs::path& repo, Txn& tx, Store& store,-                       const std::vector<TreeTerm>& terms, const std::vector<RenameMap>& maps,-                       bool adjacent) {-    std::vector<OrigEntry> orig;-    for (std::size_t t = 0; t < terms.size(); ++t) {-        if (!terms[t].present)-            continue;-        for (const auto& entry : flatten_any_sorted(store, &tx, terms[t].id))-            orig.push_back(OrigEntry{t, entry.path, entry.kind, entry.target});-    }--    auto canonical_targets =-        [&](const std::string& path) -> std::vector<std::pair<std::size_t, std::string>> {-        std::vector<std::pair<std::size_t, std::string>> out;-        for (std::size_t i = 0; i < maps.size(); ++i) {-            auto dest = rename_lookup(maps[i], path);-            if (!dest)-                continue;-            bool exists = false;-            for (const auto& item : out) {-                if (item.second == *dest) {-                    exists = true;-                    break;-                }-            }-            if (!exists)-                out.emplace_back(i, *dest);-        }-        return out;-    };--    auto find_orig = [&](std::size_t term, const std::string& path) -> const OrigEntry* {-        for (const auto& entry : orig) {-            if (entry.term == term && entry.path == path)-                return &entry;-        }-        return nullptr;-    };--    std::vector<OrigEntry> canon;-    std::vector<std::string> special;-    std::vector<std::string> consumed;-    auto mark_consumed = [&](const std::string& path) {-        for (const auto& item : consumed) {-            if (item == path)-                return;-        }-        consumed.push_back(path);-    };-    for (const auto& entry : orig) {-        auto targets = canonical_targets(entry.path);-        if (targets.size() > 1) {-            bool seen = false;-            for (const auto& item : special) {-                if (item == entry.path) {-                    seen = true;-                    break;-                }-            }-            if (!seen)-                special.push_back(entry.path);-        }-        const std::string& canonical = targets.size() == 1 ? targets[0].second : entry.path;-        canon.push_back(OrigEntry{entry.term, canonical, entry.kind, entry.target});-    }--    std::vector<OutEntry> out;-    std::size_t rerere = 0;--    for (const auto& sp : special) {-        auto targets = canonical_targets(sp);-        std::vector<EntryTerm> ets;-        for (const auto& target : targets) {-            EntryTerm term;-            term.positive = true;-            if (const OrigEntry* found = find_orig(target.first, target.second)) {-                term.present = true;-                term.kind = found->kind;-                term.target = found->target;-            }-            ets.push_back(term);-            mark_consumed(target.second);-        }-        std::ptrdiff_t base_term = -1;-        for (std::size_t ti = 0; ti < terms.size(); ++ti) {-            if (!terms[ti].positive) {-                base_term = static_cast<std::ptrdiff_t>(ti);-                break;-            }-        }-        if (base_term >= 0) {-            EntryTerm term;-            term.positive = false;-            if (const OrigEntry* found = find_orig(static_cast<std::size_t>(base_term), sp)) {-                term.present = true;-                term.kind = found->kind;-                term.target = found->target;-            }-            ets.push_back(term);-        }-        if (auto merged = merge_entry(repo, tx, store, sp, ets, adjacent, rerere))-            out.push_back(std::move(*merged));-        mark_consumed(sp);-    }--    auto find_canon = [&](std::size_t term, const std::string& path) -> const OrigEntry* {-        for (const auto& entry : canon) {-            if (entry.term == term && entry.path == path)-                return &entry;-        }-        return nullptr;-    };--    std::vector<std::string> paths;-    for (const auto& entry : canon) {-        bool seen = false;-        for (const auto& path : paths) {-            if (path == entry.path) {-                seen = true;-                break;-            }-        }-        if (!seen)-            paths.push_back(entry.path);-    }-    std::sort(paths.begin(), paths.end(), [](const std::string& a, const std::string& b) {-        return compare(bytes_of(a), bytes_of(b)) < 0;-    });--    auto is_consumed = [&](const std::string& path) {-        for (const auto& item : consumed) {-            if (item == path)-                return true;-        }-        return false;-    };--    for (const auto& path : paths) {-        if (is_consumed(path))-            continue;-        bool any_exact = false;-        bool any_children = false;-        for (std::size_t t = 0; t < terms.size(); ++t) {-            if (find_canon(t, path))-                any_exact = true;-            for (const auto& entry : canon) {-                if (entry.term == t && has_prefix(entry.path, path)) {-                    any_children = true;-                    break;-                }-            }-        }-        if (!any_exact)-            continue;-        const bool mixed = any_children;-        std::vector<EntryTerm> ets;-        for (std::size_t t = 0; t < terms.size(); ++t) {-            EntryTerm term;-            term.positive = terms[t].positive;-            if (const OrigEntry* exact = find_canon(t, path)) {-                term.present = true;-                term.kind = exact->kind;-                term.target = exact->target;-            } else if (mixed) {-                bool children = false;-                for (const auto& entry : canon) {-                    if (entry.term == t && has_prefix(entry.path, path)) {-                        children = true;-                        break;-                    }-                }-                if (children) {-                    term.present = true;-                    term.kind = KIND_SUBTREE;-                    term.target = build_subtree(tx, canon, t, path);-                }-            }-            ets.push_back(term);-        }-        if (auto merged = merge_entry(repo, tx, store, path, ets, adjacent, rerere))-            out.push_back(std::move(*merged));-        if (mixed) {-            for (const auto& entry : canon) {-                if (has_prefix(entry.path, path))-                    mark_consumed(entry.path);-            }-        }-    }--    return MergeOutcome{build_from_entries(tx, out), rerere};-}---bool contains_id_vec(const std::vector<Id>& ids, const Id& id) {-    for (const auto& candidate : ids) {-        if (same_id(candidate, id))-            return true;-    }-    return false;-}--std::vector<Id> merge_bases(Store& store, const Id& a, const Id& b) {-    const std::vector<Id> aa = collect_commits(store, std::vector<Id>{a});-    const std::vector<Id> bb = collect_commits(store, std::vector<Id>{b});-    std::vector<Id> common;-    for (const auto& x : aa) {-        if (contains_id_vec(bb, x))-            common.push_back(x);-    }-    std::vector<Id> out;-    for (const auto& c : common) {-        bool dominated = false;-        for (const auto& d : common) {-            if (same_id(c, d))-                continue;-            const auto descendants = collect_commits(store, std::vector<Id>{c});-            if (contains_id_vec(descendants, d)) {-                dominated = true;-                break;-            }-        }-        if (!dominated)-            out.push_back(c);-    }-    return out;-}--bool is_ancestor(Store& store, const Id& ancestor, const Id& descendant) {-    if (same_id(ancestor, descendant))-        return true;-    return contains_id_vec(collect_commits(store, std::vector<Id>{descendant}), ancestor);-}--std::optional<Id> base_tree(const fs::path& repo, Txn& tx, Store& store,-                            const std::vector<Id>& bases, bool adjacent);--std::optional<Id> base_tree(const fs::path& repo, Txn& tx, Store& store,-                            const std::vector<Id>& bases, bool adjacent) {-    if (bases.empty())-        return std::nullopt;-    if (bases.size() == 1)-        return tree_of(store, bases.front());-    auto t0 = tree_of(store, bases[0]);-    auto t1 = tree_of(store, bases[1]);-    const auto lcas = merge_bases(store, bases[0], bases[1]);-    std::vector<TreeTerm> terms;-    terms.push_back(TreeTerm{true, t0.has_value(), t0.value_or(Id{})});-    terms.push_back(TreeTerm{true, t1.has_value(), t1.value_or(Id{})});-    if (!lcas.empty()) {-        auto lt = tree_of(store, lcas.front());-        terms.push_back(TreeTerm{false, lt.has_value(), lt.value_or(Id{})});-    } else {-        terms.push_back(TreeTerm{false, false, Id{}});-    }-    std::vector<RenameMap> maps(3);-    return treemerge(repo, tx, store, terms, maps, adjacent).tree;-}--MergeOutcome merge_many(const fs::path& repo, Txn& tx, Store& store, const std::vector<Id>& heads,-                        bool adjacent) {-    if (heads.size() == 1) {-        auto t = tree_of(store, heads.front());-        std::vector<TreeTerm> terms{TreeTerm{true, t.has_value(), t.value_or(Id{})}};-        return treemerge(repo, tx, store, terms, {RenameMap{}}, adjacent);-    }-    std::vector<TreeTerm> terms;-    std::vector<RenameMap> maps;-    std::optional<Id> map_base;-    if (heads.size() > 1) {-        const auto bases = merge_bases(store, heads[0], heads[1]);-        if (!bases.empty())-            map_base = bases.front();-    }-    for (const auto& head : heads) {-        auto t = tree_of(store, head);-        terms.push_back(TreeTerm{true, t.has_value(), t.value_or(Id{})});-        if (map_base)-            maps.push_back(map_from(store, *map_base, head));-        else-            maps.push_back(RenameMap{});-    }-    for (std::size_t i = 1; i < heads.size(); ++i) {-        const auto bases = merge_bases(store, heads[0], heads[i]);-        auto bt = base_tree(repo, tx, store, bases, adjacent);-        if (bt)-            terms.push_back(TreeTerm{false, true, *bt});-        else-            terms.push_back(TreeTerm{false, false, Id{}});-        maps.push_back(RenameMap{});-    }-    return treemerge(repo, tx, store, terms, maps, adjacent);-}--MergeOutcome rewrite_tree(const fs::path& repo, Txn& tx, Store& store, const Id& old_commit,-                          const Id& commit_tree, const std::vector<Id>& old_parents,-                          const std::vector<Id>& new_parents,-                          const std::vector<Id>& new_parent_trees, bool adjacent) {-    std::vector<TreeTerm> terms;-    std::vector<RenameMap> maps;-    terms.push_back(TreeTerm{true, true, commit_tree});-    if (!old_parents.empty())-        maps.push_back(map_from(store, old_parents.front(), old_commit));-    else-        maps.push_back(RenameMap{});--    if (old_parents.empty()) {-        for (const auto& tree : new_parent_trees) {-            terms.push_back(TreeTerm{true, true, tree});-            maps.push_back(RenameMap{});-        }-        terms.push_back(TreeTerm{false, false, Id{}});-        maps.push_back(RenameMap{});-    } else {-        for (std::size_t i = 0; i < old_parents.size(); ++i) {-            auto old_tree = tree_of(store, old_parents[i]);-            const Id new_tree = i < new_parent_trees.size() ? new_parent_trees[i] : Id{};-            terms.push_back(TreeTerm{true, true, new_tree});-            terms.push_back(TreeTerm{false, old_tree.has_value(), old_tree.value_or(Id{})});-            if (i < new_parents.size())-                maps.push_back(map_from(store, old_parents[i], new_parents[i]));-            else-                maps.push_back(RenameMap{});-            maps.push_back(RenameMap{});-        }-    }-    return treemerge(repo, tx, store, terms, maps, adjacent);-}--Id make_commit(Txn& tx, Store& store, const fs::path& repo, const std::vector<Id>& parents,-               const Id& root, const ChangeId& change, const Sig& author,-               const std::string& message, std::uint8_t renames_state,-               const std::vector<KeyValue>& extra) {-    Commit commit;-    commit.version = 1;-    commit.parents = parents;-    commit.root_tree = root;-    commit.change_id = change;-    commit.author = author;-    commit.committer = identity_signature(repo);-    commit.message = message;-    commit.renames_state = renames_state;-    commit.extra = extra;-    if (renames_state == RENAMES_RECORDED) {-        for (std::size_t i = 0; i < parents.size(); ++i) {-            auto parent_tree = tree_of(store, parents[i]);-            auto detected = detect_renames(store, &tx, parent_tree, std::optional<Id>{root}, 0, i);-            for (auto& rename : detected)-                commit.renames.push_back(std::move(rename));-        }-    }-    return tx.add_object(TYPE_COMMIT, encode_commit(commit));-}--std::string rerere_suffix(std::size_t count) {-    if (count == 0)-        return std::string();-    return " (rerere " + std::to_string(count) + ")";-}--std::string join_revs(const std::vector<std::string>& revs) {-    std::string out;-    for (std::size_t i = 0; i < revs.size(); ++i) {-        if (i != 0)-            out.push_back(' ');-        out += revs[i];-    }-    return out;-}--bool adjacent_config(const fs::path& root) {-    auto value = repo_config_value(root, "merge.adjacent");-    return value && *value == "merge";-}---std::optional<Id> tree_edit_into(Txn& tx, Store& store, const Id& tree_id, std::string_view path,-                                 bool present, std::uint8_t kind, const Id& target,-                                 std::size_t depth) {-    if (depth > MAX_TREE_DEPTH)-        return std::nullopt;-    auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);-    if (!body)-        return std::nullopt;-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-        return std::nullopt;-    const std::size_t cut = path.find('/');-    const std::size_t cut_pos = cut == std::string_view::npos ? path.size() : cut;-    const std::string_view name = path.substr(0, cut_pos);-    std::vector<TreeEntry> entries;-    bool found = false;-    for (const auto& entry : tree->entries) {-        if (entry.name != name) {-            entries.push_back(entry);-            continue;-        }-        found = true;-        if (cut_pos == path.size()) {-            if (present)-                entries.push_back(TreeEntry{entry.name, kind, target});-        } else if (entry.kind == KIND_SUBTREE) {-            auto child = tree_edit_into(tx, store, entry.target, path.substr(cut_pos + 1), present,-                                        kind, target, depth + 1);-            if (child && !tree_empty_any(store, &tx, *child))-                entries.push_back(TreeEntry{entry.name, KIND_SUBTREE, *child});-        } else {-            entries.push_back(entry);-        }-    }-    if (!found && cut_pos == path.size() && present)-        entries.push_back(TreeEntry{std::string(name), kind, target});-    return add_tree(tx, entries);-}--std::optional<Id> tree_edit_replace(Txn& tx, Store& store, const Id& root, std::string_view path,-                                    bool present, std::uint8_t kind, const Id& target) {-    auto edited = tree_edit_into(tx, store, root, path, present, kind, target, 0);-    if (!edited)-        return std::nullopt;-    return edited;-}---std::string conflict_kind_label(const Conflict& conflict) {-    for (const auto& value : conflict.adds) {-        if (value.kind == KIND_SUBTREE)-            return "tree";-    }-    for (const auto& value : conflict.removes) {-        if (value.kind == KIND_SUBTREE)-            return "tree";-    }-    for (const auto& value : conflict.adds) {-        if (value.kind == 0)-            return "delete/modify";-    }-    for (const auto& value : conflict.removes) {-        if (value.kind == 0)-            return "delete/modify";-    }-    return "text";-}--void print_range(std::size_t a, std::size_t b) {-    if (a == b)-        std::cout << a + 1;-    else-        std::cout << a + 1 << "-" << b;-}--std::optional<EditResult> conflict_ranges(Store& store, const Conflict& conflict, bool adjacent) {-    if (conflict.adds.size() != 2 || conflict.removes.size() != 1)-        return std::nullopt;-    const auto& ours = conflict.adds[0];-    const auto& theirs = conflict.adds[1];-    const auto& base = conflict.removes[0];-    if (ours.kind == 0 || theirs.kind == 0 || base.kind == 0)-        return std::nullopt;-    if (ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE || base.kind == KIND_SUBTREE)-        return std::nullopt;-    return merge_blobs(store, nullptr, *base.target, *ours.target, *theirs.target, adjacent);-}--std::vector<FlatEntry> flatten_store(Store& store, const Id& tree) {-    return flatten_any_sorted(store, nullptr, std::optional<Id>{tree});-}---int merge_command(const std::vector<std::string>& revs) {-    if (revs.empty()) {-        error_prefix();-        std::cout << "merge requires at least one revision\n";-        return 1;-    }-    const auto root = discover_repo(".");-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;--    Store store = Store::open_all(*root);-    auto tx = Txn::begin(*root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    const auto wc = working_copy_id(tx->view());-    if (!wc) {-        error_prefix();-        std::cout << "no working-copy commit to merge into\n";-        return 1;-    }--    std::vector<Id> parents{*wc};-    bool failed = false;-    for (const auto& rev : revs) {-        auto resolved = resolve_revision(store, tx->view(), rev);-        if (!resolved) {-            failed = true;-            continue;-        }-        if (same_id(*resolved, *wc)) {-            error_prefix();-            std::cout << "cannot merge a commit with itself\n";-            failed = true;-            continue;-        }-        parents.push_back(*resolved);-    }-    if (failed) {-        error_prefix();-        std::cout << "unknown revision\n";-        return 1;-    }--    const auto old_root = tree_of(store, *wc);-    const bool adjacent = adjacent_config(*root);-    MergeOutcome outcome = merge_many(*root, *tx, store, parents, adjacent);-    const Sig author = identity_signature(*root);-    const Id new_id = make_commit(*tx, store, *root, parents, outcome.tree, random_change_id(),-                                  author, "", RENAMES_RECORDED, {});--    remove_head(tx->view(), *wc);-    move_bookmarks(tx->view(), *wc, new_id);-    set_workspace(tx->view(), new_id);-    rebuild_heads(tx->view());-    const std::string description = "merge " + join_revs(revs) + rerere_suffix(outcome.rerere);-    const auto status = tx->finish(description);-    if (!status)-        return 1;-    store.refresh(*root);-    (void)mark_native(*root, new_id);-    if (old_root)-        return checkout_materialize_commit(*root, store, old_root, outcome.tree);-    return 0;-}--int rebase_command(const std::string& source, const std::string& dest) {-    const auto root = discover_repo(".");-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;--    Store store = Store::open_all(*root);-    auto tx = Txn::begin(*root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    auto src = resolve_revision(store, tx->view(), source);-    auto dst = resolve_revision(store, tx->view(), dest);-    if (!src || !dst) {-        error_prefix();-        std::cout << "unknown revision\n";-        return 1;-    }-    const auto wc = working_copy_id(tx->view());-    std::optional<Id> old_wc_root;-    if (wc)-        old_wc_root = tree_of(store, *wc);--    std::vector<Id> set;-    for (const auto& commit : all_commits(store, tx->view())) {-        if (is_ancestor(store, *src, commit))-            set.push_back(commit);-    }--    std::vector<Id> old_ids;-    std::vector<Id> new_ids;-    std::vector<Id> new_tree_ids;-    std::vector<Id> remaining = set;-    std::size_t rerere_total = 0;-    const bool adjacent = adjacent_config(*root);-    const Sig fallback_sig = identity_signature(*root);-    (void)fallback_sig;--    while (!remaining.empty()) {-        std::ptrdiff_t ready_idx = -1;-        for (std::size_t i = 0; i < remaining.size(); ++i) {-            bool ready = true;-            auto loaded = load_commit(store, remaining[i]);-            if (!loaded)-                continue;-            for (const auto& parent : loaded->commit.parents) {-                if (contains_id_vec(set, parent) && !contains_id_vec(old_ids, parent) &&-                    !same_id(remaining[i], *src))-                    ready = false;-            }-            if (ready) {-                ready_idx = static_cast<std::ptrdiff_t>(i);-                break;-            }-        }-        if (ready_idx < 0) {-            error_prefix();-            std::cout << "rebase could not order commits\n";-            break;-        }-        const Id chosen = remaining[static_cast<std::size_t>(ready_idx)];-        auto loaded = load_commit(store, chosen);-        if (!loaded)-            break;--        std::vector<Id> new_parents;-        std::vector<Id> new_parent_trees;-        for (std::size_t pi = 0; pi < loaded->commit.parents.size(); ++pi) {-            const Id parent = loaded->commit.parents[pi];-            if (pi == 0 && same_id(chosen, *src)) {-                new_parents.push_back(*dst);-                new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));-                continue;-            }-            bool mapped = false;-            for (std::size_t mi = 0; mi < old_ids.size(); ++mi) {-                if (same_id(old_ids[mi], parent)) {-                    new_parents.push_back(new_ids[mi]);-                    new_parent_trees.push_back(new_tree_ids[mi]);-                    mapped = true;-                    break;-                }-            }-            if (!mapped) {-                new_parents.push_back(parent);-                new_parent_trees.push_back(tree_of(store, parent).value_or(Id{}));-            }-        }-        if (loaded->commit.parents.empty()) {-            new_parents.push_back(*dst);-            new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));-        }--        MergeOutcome outcome =-            rewrite_tree(*root, *tx, store, chosen, loaded->commit.root_tree,-                         loaded->commit.parents, new_parents, new_parent_trees, adjacent);-        rerere_total += outcome.rerere;-        const Id new_id =-            make_commit(*tx, store, *root, new_parents, outcome.tree, loaded->commit.change_id,-                        loaded->commit.author, loaded->commit.message, loaded->commit.renames_state,-                        loaded->commit.extra);-        old_ids.push_back(chosen);-        new_ids.push_back(new_id);-        new_tree_ids.push_back(outcome.tree);-        remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(ready_idx));-    }--    auto remap = [&](std::optional<Id>& id) {-        if (!id)-            return;-        for (std::size_t i = 0; i < old_ids.size(); ++i) {-            if (same_id(old_ids[i], *id)) {-                id = new_ids[i];-                return;-            }-        }-    };-    for (auto& bookmark : tx->view().bookmarks) {-        for (auto& id : bookmark.targets.adds)-            remap(id);-        for (auto& id : bookmark.targets.removes)-            remap(id);-    }-    for (auto& tag : tx->view().tags) {-        std::optional<Id> target = tag.target;-        remap(target);-        if (target)-            tag.target = *target;-    }-    for (auto& workspace : tx->view().working_copies) {-        std::optional<Id> target = workspace.target;-        remap(target);-        if (target)-            workspace.target = *target;-    }-    rebuild_heads(tx->view());-    const auto status =-        tx->finish("rebase " + source + " onto " + dest + rerere_suffix(rerere_total));-    if (!status)-        return 1;-    for (const auto& id : new_ids)-        (void)mark_native(*root, id);-    if (wc) {-        for (std::size_t i = 0; i < old_ids.size(); ++i) {-            if (same_id(old_ids[i], *wc)) {-                Store refreshed = Store::open_all(*root);-                return checkout_materialize_commit(*root, refreshed, old_wc_root, new_tree_ids[i]);-            }-        }-    }-    return 0;-}--int xs_command(bool porcelain) {-    const auto root = discover_repo(".");-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto view = current_view(*root, store);-    if (!view) {-        error_prefix();-        std::cout << "no operation state\n";-        return 1;-    }-    std::vector<std::pair<std::string, Conflict>> items;-    if (const auto wc = working_copy_id(*view)) {-        auto loaded = load_commit(store, *wc);-        if (loaded) {-            for (const auto& entry : flatten_store(store, loaded->commit.root_tree)) {-                if (entry.kind != KIND_CONFLICT)-                    continue;-                auto body = store.read_body(entry.target, TYPE_CONFLICT);-                if (!body)-                    continue;-                auto conflict = decode_conflict(bytes_of(*body));-                if (!conflict)-                    continue;-                items.emplace_back(entry.path, std::move(*conflict));-            }-        }-    }-    const bool adjacent = adjacent_config(*root);-    bool first = true;-    for (const auto& [path, conflict] : items) {-        const std::string kind = conflict_kind_label(conflict);-        auto ranges = conflict_ranges(store, conflict, adjacent);-        if (porcelain) {-            std::cout << path << "\t" << kind << "\t";-            if (ranges) {-                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-                    if (i > 0)-                        std::cout << ",";-                    print_range(ranges->ranges[i].base_start, ranges->ranges[i].base_end);-                }-                std::cout << "\t";-                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-                    if (i > 0)-                        std::cout << ",";-                    print_range(ranges->ranges[i].ours_start, ranges->ranges[i].ours_end);-                }-                std::cout << "\t";-                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-                    if (i > 0)-                        std::cout << ",";-                    print_range(ranges->ranges[i].theirs_start, ranges->ranges[i].theirs_end);-                }-            } else {-                std::cout << "\t\t";-            }-            std::cout << "\n";-        } else {-            std::cout << path << ": " << kind << " conflict";-            if (ranges && !ranges->ranges.empty()) {-                std::cout << " (";-                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-                    if (i > 0)-                        std::cout << ", ";-                    std::cout << "base ";-                    print_range(ranges->ranges[i].base_start, ranges->ranges[i].base_end);-                    std::cout << ", ours ";-                    print_range(ranges->ranges[i].ours_start, ranges->ranges[i].ours_end);-                    std::cout << ", theirs ";-                    print_range(ranges->ranges[i].theirs_start, ranges->ranges[i].theirs_end);-                }-                std::cout << ")";-            }-            std::cout << "\n";-        }-        first = false;-    }-    if (first) {-        info_prefix();-        std::cout << "no conflicts\n";-    }-    return 0;-}--std::string shell_replace(std::string_view command, std::string_view key,-                          const std::string& value) {-    std::string out;-    std::size_t i = 0;-    while (i < command.size()) {-        if (i + key.size() <= command.size() && command.compare(i, key.size(), key) == 0) {-            out.push_back('\'');-            out += value;-            out.push_back('\'');-            i += key.size();-        } else {-            out.push_back(command[i]);-            ++i;-        }-    }-    return out;-}--bool run_tool(const fs::path& root, std::string_view command, std::string_view path) {-    const std::string base = path_to_bytes(root / path_from_bytes(path));-    std::string expanded(command);-    expanded = shell_replace(expanded, "$BASE", base + ".base");-    expanded = shell_replace(expanded, "$OURS", base + ".ours");-    expanded = shell_replace(expanded, "$THEIRS", base + ".theirs");-    expanded = shell_replace(expanded, "$OUTPUT", base);-    return std::system(expanded.c_str()) == 0;-}--void delete_sidecar(const fs::path& root, std::string_view path, std::string_view suffix) {-    std::string full(path);-    full += suffix;-    (void)remove_file(root / path_from_bytes(full));-}--void delete_sidecars(const fs::path& root, std::string_view path) {-    delete_sidecar(root, path, ".base");-    delete_sidecar(root, path, ".ours");-    delete_sidecar(root, path, ".theirs");-    for (int n = 2; n <= 64; ++n) {-        delete_sidecar(root, path, ".base" + std::to_string(n));-        delete_sidecar(root, path, ".theirs" + std::to_string(n));-    }-}--std::optional<ConflictValue> choose_value(const Conflict& conflict, std::string_view take) {-    if (take == "ours" && !conflict.adds.empty())-        return conflict.adds[0];-    if (take == "theirs" && conflict.adds.size() > 1)-        return conflict.adds[1];-    if (take == "base" && !conflict.removes.empty())-        return conflict.removes[0];-    return std::nullopt;-}--int resolve_command(std::string_view take, std::string_view tool,-                    const std::vector<std::string>& paths) {-    const auto root = discover_repo(".");-    if (!root) {-        error_prefix();-        std::cout << "not a veins repository\n";-        return 1;-    }-    const int snap = snapshot_run(*root);-    if (snap != 0)-        return snap;-    Store store = Store::open_all(*root);-    auto tx = Txn::begin(*root, store);-    if (!tx) {-        error_prefix();-        std::cout << "cannot load repository state\n";-        return 1;-    }-    const auto wc = working_copy_id(tx->view());-    if (!wc) {-        error_prefix();-        std::cout << "no working-copy commit\n";-        return 1;-    }-    auto loaded = load_commit(store, *wc);-    if (!loaded) {-        error_prefix();-        std::cout << "cannot read working-copy commit\n";-        return 1;-    }-    const Id old_root = loaded->commit.root_tree;-    Id mut_root = old_root;-    bool resolved_any = false;-    std::vector<std::string> normalized_paths;--    const auto cwd = cwd_relative(*root);-    for (const auto& arg : paths) {-        auto norm = cwd ? pathspec_normalize(*root, *cwd, arg) : std::nullopt;-        if (!norm || norm->empty()) {-            error_prefix();-            std::cout << "invalid path\n";-            continue;-        }-        normalized_paths.push_back(*norm);-        auto flat = flatten_store(store, mut_root);-        const FlatEntry* entry = find_flat_entry(flat, *norm);-        if (!entry || entry->kind != KIND_CONFLICT) {-            error_prefix();-            std::cout << "not a conflicted path: " << *norm << "\n";-            continue;-        }-        auto body = store.read_body(entry->target, TYPE_CONFLICT);-        if (!body)-            continue;-        auto conflict = decode_conflict(bytes_of(*body));-        if (!conflict)-            continue;--        bool present = false;-        std::uint8_t new_kind = KIND_FILE;-        std::optional<Id> new_target;-        if (auto chosen = choose_value(*conflict, take)) {-            if (chosen->kind != 0) {-                present = true;-                new_kind = chosen->kind;-                new_target = chosen->target;-            }-        } else if (!tool.empty()) {-            if (run_tool(*root, tool, *norm)) {-                if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {-                    new_target = add_blob(*tx, bytes_of(*data));-                    present = true;-                    new_kind = KIND_FILE;-                }-            }-        } else {-            if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {-                new_target = add_blob(*tx, bytes_of(*data));-                present = true;-                new_kind = KIND_FILE;-            }-        }-        if (present) {-            if (auto info = stat_path(*root / path_from_bytes(*norm))) {-                if (info->executable)-                    new_kind = KIND_EXECUTABLE;-            }-            if (new_kind == KIND_FILE || new_kind == KIND_EXECUTABLE) {-                if (auto conflict_body = store.read_body(entry->target, TYPE_CONFLICT)) {-                    resolution_record(*root, bytes_of(*conflict_body), *new_target);-                }-            }-        }-        auto replaced = tree_edit_replace(*tx, store, mut_root, *norm, present, new_kind,-                                          new_target.value_or(Id{}));-        if (replaced) {-            mut_root = *replaced;-            resolved_any = true;-        }-    }--    if (!resolved_any) {-        return 1;-    }--    Commit commit = loaded->commit;-    commit.root_tree = mut_root;-    commit.committer = identity_signature(*root);-    const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));-    remove_head(tx->view(), *wc);-    move_bookmarks(tx->view(), *wc, new_id);-    set_workspace(tx->view(), new_id);-    rebuild_heads(tx->view());-    const auto status = tx->finish("resolve");-    if (!status)-        return 1;-    Store refreshed = Store::open_all(*root);-    const int materialized = checkout_materialize_commit(*root, refreshed, old_root, mut_root);-    if (materialized != 0)-        return materialized;-    for (const auto& path : normalized_paths)-        delete_sidecars(*root, path);-    return 0;-}--} // namespace---int merge_run(const std::vector<std::string>& args) {-    std::vector<std::string> revs;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && !arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            revs.push_back(arg);-        }-    }-    return merge_command(revs);-}--int rebase_run(const std::vector<std::string>& args) {-    std::string source;-    std::string dest;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-s" || arg == "-source")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            source = args[++i];-        } else if (!end_flags && (arg == "-d" || arg == "-destination")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a revision\n";-                return 1;-            }-            dest = args[++i];-        } else if (!end_flags && !arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            error_prefix();-            std::cout << "unexpected argument: " << arg << "\n";-            return 1;-        }-    }-    if (source.empty() || dest.empty()) {-        error_prefix();-        std::cout << "rebase requires -s <rev> and -d <rev>\n";-        return 1;-    }-    return rebase_command(source, dest);-}--int xs_run(const std::vector<std::string>& args) {-    bool porcelain = false;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-porcelain" || arg == "-p")) {-            porcelain = true;-        } else if (!end_flags && !arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            error_prefix();-            std::cout << "unexpected argument: " << arg << "\n";-            return 1;-        }-    }-    return xs_command(porcelain);-}--int resolve_run(const std::vector<std::string>& args) {-    std::string take;-    std::string tool;-    bool list_only = false;-    std::vector<std::string> paths;-    bool end_flags = false;-    for (std::size_t i = 2; i < args.size(); ++i) {-        const std::string& arg = args[i];-        if (!end_flags && arg == "--") {-            end_flags = true;-        } else if (!end_flags && (arg == "-list" || arg == "-l")) {-            list_only = true;-        } else if (!end_flags && (arg == "-take" || arg == "-t")) {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires ours, theirs, or base\n";-                return 1;-            }-            take = args[++i];-        } else if (!end_flags && arg == "-tool") {-            if (i + 1 >= args.size()) {-                error_prefix();-                std::cout << arg << " requires a command\n";-                return 1;-            }-            tool = args[++i];-        } else if (!end_flags && !arg.empty() && arg.front() == '-') {-            error_prefix();-            std::cout << "unknown flag: " << arg << "\n";-            return 1;-        } else {-            paths.push_back(arg);-        }-    }-    if (list_only)-        return xs_command(false);-    if (paths.empty()) {-        error_prefix();-        std::cout << "resolve requires at least one path\n";-        return 1;-    }-    return resolve_command(take, tool, paths);-}--} // namespace vn--- a/xveins/src/merge/merge.h+++ /dev/null@@ -1,26 +0,0 @@-#pragma once--#include "store/store.h"--#include <optional>-#include <string>-#include <vector>--namespace vn {--// Detect renames between two trees. `tx` may be provided so trees and blobs-// that have only been added to the pending transaction are visible. Results are-// sorted by (parent_index, to_path).-std::vector<Rename> detect_renames(Store& store, Txn* tx, std::optional<Id> old_tree,-                                   std::optional<Id> new_tree, int similar_pct,-                                   std::uint64_t parent_index);--// Configured rename similarity threshold (0 disables detection).-int rename_similar_pct(const fs::path& root);--int merge_run(const std::vector<std::string>& args);-int rebase_run(const std::vector<std::string>& args);-int xs_run(const std::vector<std::string>& args);-int resolve_run(const std::vector<std::string>& args);--} // namespace vn--- a/xveins/src/net/net.cpp+++ /dev/null@@ -1,760 +0,0 @@-#include "net/net.h"--#include <algorithm>-#include <cerrno>-#include <climits>-#include <cstring>--#if defined(_WIN32)-#ifndef WIN32_LEAN_AND_MEAN-#define WIN32_LEAN_AND_MEAN-#endif-#ifndef NOMINMAX-#define NOMINMAX-#endif-#include <io.h>-#include <windows.h>-#include <winsock2.h>-#include <ws2tcpip.h>-#endif--#include <openssl/err.h>-#include <openssl/ssl.h>-#include <openssl/x509.h>-#include <openssl/x509_vfy.h>--#if !defined(_WIN32)-#include <arpa/inet.h>-#include <fcntl.h>-#include <limits.h>-#include <netdb.h>-#include <netinet/in.h>-#include <netinet/tcp.h>-#include <signal.h>-#include <sys/socket.h>-#include <sys/types.h>-#include <sys/wait.h>-#include <unistd.h>-#if defined(__APPLE__)-#include <mach-o/dyld.h>-#endif-#endif--namespace vn::net {--namespace {--#if defined(_WIN32)-void ensure_winsock() {-    static const bool initialized = [] {-        WSADATA data{};-        return WSAStartup(MAKEWORD(2, 2), &data) == 0;-    }();-    (void)initialized;-}--std::wstring widen_utf8(std::string_view text) {-    if (text.empty())-        return {};-    const int len =-        MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);-    std::wstring out(static_cast<std::size_t>(len), L'\0');-    MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), out.data(), len);-    return out;-}--// Quote one argument for CreateProcessW's command line.-std::wstring quote_windows_arg(std::wstring_view arg) {-    if (!arg.empty() && arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)-        return std::wstring(arg);-    std::wstring out = L"\"";-    for (std::size_t i = 0; i < arg.size(); ++i) {-        std::size_t backslashes = 0;-        while (i < arg.size() && arg[i] == L'\\') {-            ++backslashes;-            ++i;-        }-        if (i == arg.size()) {-            out.append(backslashes * 2, L'\\');-            break;-        }-        if (arg[i] == L'"') {-            out.append(backslashes * 2 + 1, L'\\');-            out.push_back(L'"');-        } else {-            out.append(backslashes, L'\\');-            out.push_back(arg[i]);-        }-    }-    out.push_back(L'"');-    return out;-}--std::wstring build_windows_command_line(const std::vector<std::string>& argv) {-    std::wstring out;-    for (std::size_t i = 0; i < argv.size(); ++i) {-        if (i != 0)-            out.push_back(L' ');-        out += quote_windows_arg(widen_utf8(argv[i]));-    }-    return out;-}-#endif--void enable_tcp_nodelay(Socket socket) {-    int one = 1;-#if defined(_WIN32)-    (void)setsockopt(static_cast<SOCKET>(socket), IPPROTO_TCP, TCP_NODELAY,-                     reinterpret_cast<const char*>(&one), sizeof(one));-#else-    (void)setsockopt(static_cast<int>(socket), IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));-#endif-}--std::string ssl_error_string() {-    unsigned long code = ERR_get_error();-    if (code == 0)-        return {};-    char buffer[256];-    ERR_error_string_n(code, buffer, sizeof(buffer));-    return std::string(buffer);-}--} // namespace---Stream::Stream(Stream&& other) noexcept {-    *this = std::move(other);-}--Stream& Stream::operator=(Stream&& other) noexcept {-    if (this == &other)-        return *this;-    close();-    kind_ = other.kind_;-    fd_in_ = other.fd_in_;-    fd_out_ = other.fd_out_;-    ssl_ = other.ssl_;-#if defined(_WIN32)-    process_ = other.process_;-    process_id_ = other.process_id_;-#else-    pid_ = other.pid_;-#endif-    open_ = other.open_;-    other.open_ = false;-    other.ssl_ = nullptr;-    other.fd_in_ = 0;-    other.fd_out_ = 0;-#if defined(_WIN32)-    other.process_ = nullptr;-    other.process_id_ = 0;-#else-    other.pid_ = 0;-#endif-    return *this;-}--Stream::~Stream() {-    close();-}--Stream Stream::stdio_stream() {-    Stream stream;-    stream.kind_ = Kind::Stdio;-#if defined(_WIN32)-    stream.fd_in_ = reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));-    stream.fd_out_ = reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE));-#else-    stream.fd_in_ = 0;-    stream.fd_out_ = 1;-#endif-    stream.open_ = true;-    return stream;-}--Stream Stream::fd_stream(Socket fd) {-    Stream stream;-    stream.kind_ = Kind::Fd;-    stream.fd_in_ = fd;-    stream.fd_out_ = fd;-    stream.open_ = true;-    return stream;-}--Stream Stream::tls_stream(Socket fd, void* ssl) {-    Stream stream;-    stream.kind_ = Kind::Tls;-    stream.fd_in_ = fd;-    stream.fd_out_ = fd;-    stream.ssl_ = ssl;-    stream.open_ = true;-    return stream;-}--std::optional<Stream> Stream::spawn_argv(const std::vector<std::string>& argv) {-    return vn::net::spawn_argv(argv);-}--std::int64_t Stream::read(void* buffer, std::size_t count) {-    if (!open_ || count == 0)-        return count == 0 ? 0 : -1;-    if (kind_ == Kind::Tls) {-        const int n = SSL_read(-            static_cast<SSL*>(ssl_), buffer,-            static_cast<int>(std::min<std::size_t>(count, static_cast<std::size_t>(INT_MAX))));-        if (n > 0)-            return n;-        if (n == 0)-            return 0;-        return -1;-    }-#if defined(_WIN32)-    if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {-        DWORD got = 0;-        if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,-                      static_cast<DWORD>(-                          std::min<std::size_t>(count, static_cast<std::size_t>(MAXDWORD))),-                      &got, nullptr))-            return -1;-        return static_cast<std::int64_t>(got);-    }-    const int n =-        recv(static_cast<SOCKET>(fd_in_), static_cast<char*>(buffer),-             static_cast<int>(std::min<std::size_t>(count, static_cast<std::size_t>(INT_MAX))), 0);-    return n;-#else-    const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);-    ssize_t n = 0;-    do {-        n = ::read(fd, buffer, count);-    } while (n < 0 && errno == EINTR);-    return n;-#endif-}--bool Stream::write_all(Bytes data) {-    if (!open_)-        return false;-    std::size_t offset = 0;-    while (offset < data.size()) {-        const std::size_t remaining = data.size() - offset;-        std::int64_t written = -1;-        if (kind_ == Kind::Tls) {-            const int n = SSL_write(static_cast<SSL*>(ssl_), data.data() + offset,-                                    static_cast<int>(std::min<std::size_t>(-                                        remaining, static_cast<std::size_t>(INT_MAX))));-            written = n;-        }-#if defined(_WIN32)-        else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {-            DWORD count = 0;-            if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,-                           static_cast<DWORD>(std::min<std::size_t>(-                               remaining, static_cast<std::size_t>(MAXDWORD))),-                           &count, nullptr))-                return false;-            written = static_cast<std::int64_t>(count);-        } else {-            const int n = send(static_cast<SOCKET>(fd_out_),-                               reinterpret_cast<const char*>(data.data() + offset),-                               static_cast<int>(std::min<std::size_t>(-                                   remaining, static_cast<std::size_t>(INT_MAX))),-                               0);-            written = n;-        }-#else-        else {-            ssize_t n = 0;-            do {-                n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),-                            data.data() + offset, remaining);-            } while (n < 0 && errno == EINTR);-            written = n;-        }-#endif-        if (written <= 0)-            return false;-        offset += static_cast<std::size_t>(written);-    }-    return true;-}--void Stream::close() {-    if (!open_)-        return;-    open_ = false;-    if (kind_ == Kind::Tls) {-        if (ssl_)-            tls_free(ssl_);-        ssl_ = nullptr;-#if defined(_WIN32)-        closesocket(static_cast<SOCKET>(fd_in_));-#else-        if (static_cast<int>(fd_in_) > 2)-            ::close(static_cast<int>(fd_in_));-#endif-        return;-    }-    if (kind_ == Kind::Proc) {-#if defined(_WIN32)-        if (fd_in_ != 0)-            CloseHandle(reinterpret_cast<HANDLE>(fd_in_));-        if (fd_out_ != 0)-            CloseHandle(reinterpret_cast<HANDLE>(fd_out_));-        if (process_) {-            WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);-            CloseHandle(reinterpret_cast<HANDLE>(process_));-            process_ = nullptr;-        }-#else-        if (static_cast<int>(fd_in_) > 2)-            ::close(static_cast<int>(fd_in_));-        if (static_cast<int>(fd_out_) > 2)-            ::close(static_cast<int>(fd_out_));-        if (pid_ > 0) {-            int status = 0;-            while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {-            }-            pid_ = 0;-        }-#endif-        return;-    }-    if (kind_ == Kind::Fd) {-#if defined(_WIN32)-        closesocket(static_cast<SOCKET>(fd_in_));-#else-        if (static_cast<int>(fd_in_) > 2)-            ::close(static_cast<int>(fd_in_));-#endif-    }-}---#if defined(_WIN32)-std::optional<Stream> spawn_argv(const std::vector<std::string>& argv) {-    if (argv.empty())-        return std::nullopt;-    ensure_winsock();-    SECURITY_ATTRIBUTES attributes{};-    attributes.nLength = sizeof(attributes);-    attributes.bInheritHandle = TRUE;-    HANDLE child_stdin_read = nullptr;-    HANDLE child_stdin_write = nullptr;-    HANDLE child_stdout_read = nullptr;-    HANDLE child_stdout_write = nullptr;-    if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||-        !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {-        if (child_stdin_read)-            CloseHandle(child_stdin_read);-        if (child_stdin_write)-            CloseHandle(child_stdin_write);-        return std::nullopt;-    }-    SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);-    SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);-    STARTUPINFOW startup{};-    startup.cb = sizeof(startup);-    startup.dwFlags = STARTF_USESTDHANDLES;-    startup.hStdInput = child_stdin_read;-    startup.hStdOutput = child_stdout_write;-    startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);-    PROCESS_INFORMATION process{};-    std::wstring command_line = build_windows_command_line(argv);-    const BOOL started = CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,-                                        nullptr, nullptr, &startup, &process);-    CloseHandle(child_stdin_read);-    CloseHandle(child_stdout_write);-    if (!started) {-        CloseHandle(child_stdin_write);-        CloseHandle(child_stdout_read);-        return std::nullopt;-    }-    CloseHandle(process.hThread);-    Stream stream;-    stream.kind_ = Stream::Kind::Proc;-    stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);-    stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);-    stream.process_ = process.hProcess;-    stream.process_id_ = process.dwProcessId;-    stream.open_ = true;-    return stream;-}-#else-std::optional<Stream> spawn_argv(const std::vector<std::string>& argv) {-    if (argv.empty())-        return std::nullopt;-    int in_pipe[2];-    int out_pipe[2];-    if (::pipe(in_pipe) != 0)-        return std::nullopt;-    if (::pipe(out_pipe) != 0) {-        ::close(in_pipe[0]);-        ::close(in_pipe[1]);-        return std::nullopt;-    }-    std::vector<char*> raw;-    raw.reserve(argv.size() + 1);-    for (const auto& item : argv)-        raw.push_back(const_cast<char*>(item.c_str()));-    raw.push_back(nullptr);-    const pid_t pid = ::fork();-    if (pid == 0) {-        (void)::dup2(in_pipe[0], 0);-        (void)::dup2(out_pipe[1], 1);-        ::close(in_pipe[0]);-        ::close(in_pipe[1]);-        ::close(out_pipe[0]);-        ::close(out_pipe[1]);-        ::execvp(raw[0], raw.data());-        ::_exit(127);-    }-    ::close(in_pipe[0]);-    ::close(out_pipe[1]);-    if (pid < 0) {-        ::close(in_pipe[1]);-        ::close(out_pipe[0]);-        return std::nullopt;-    }-    Stream stream;-    stream.kind_ = Stream::Kind::Proc;-    stream.fd_in_ = out_pipe[0];-    stream.fd_out_ = in_pipe[1];-    stream.pid_ = pid;-    stream.open_ = true;-    return stream;-}-#endif---std::optional<Socket> tcp_connect(std::string_view host, int port) {-    if (host.empty())-        return std::nullopt;-#if defined(_WIN32)-    ensure_winsock();-#endif-    addrinfo hints{};-    hints.ai_family = AF_UNSPEC;-    hints.ai_socktype = SOCK_STREAM;-    const std::string service = std::to_string(port);-    const std::string host_text(host);-    addrinfo* results = nullptr;-    if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)-        return std::nullopt;-    Socket connected = INVALID_SOCKET_VALUE;-    for (addrinfo* it = results; it != nullptr; it = it->ai_next) {-#if defined(_WIN32)-        SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);-        if (socket == INVALID_SOCKET)-            continue;-        if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {-            connected = static_cast<Socket>(socket);-            break;-        }-        closesocket(socket);-#else-        const int socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);-        if (socket < 0)-            continue;-        if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {-            connected = socket;-            break;-        }-        ::close(socket);-#endif-    }-    freeaddrinfo(results);-    if (connected == INVALID_SOCKET_VALUE)-        return std::nullopt;-    enable_tcp_nodelay(connected);-    set_socket_timeout(connected, 120000);-    return std::optional<Socket>(connected);-}--Socket tcp_listen(int port, int backlog) {-#if defined(_WIN32)-    ensure_winsock();-    SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);-    if (listener == INVALID_SOCKET)-        return INVALID_SOCKET_VALUE;-    BOOL reuse = TRUE;-    setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuse),-               sizeof(reuse));-    sockaddr_in address{};-    address.sin_family = AF_INET;-    address.sin_addr.s_addr = htonl(INADDR_ANY);-    address.sin_port = htons(static_cast<u_short>(port));-    if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == SOCKET_ERROR ||-        ::listen(listener, backlog) == SOCKET_ERROR) {-        closesocket(listener);-        return INVALID_SOCKET_VALUE;-    }-    return static_cast<Socket>(listener);-#else-    const int listener = ::socket(AF_INET, SOCK_STREAM, 0);-    if (listener < 0)-        return INVALID_SOCKET_VALUE;-    int reuse = 1;-    (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));-    sockaddr_in address{};-    address.sin_family = AF_INET;-    address.sin_addr.s_addr = htonl(INADDR_ANY);-    address.sin_port = htons(static_cast<std::uint16_t>(port));-    if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 ||-        ::listen(listener, backlog) != 0) {-        ::close(listener);-        return INVALID_SOCKET_VALUE;-    }-    return listener;-#endif-}--std::optional<Socket> tcp_accept(Socket listener) {-#if defined(_WIN32)-    const SOCKET accepted = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);-    if (accepted == INVALID_SOCKET)-        return std::nullopt;-    const Socket socket = static_cast<Socket>(accepted);-    enable_tcp_nodelay(socket);-    set_socket_timeout(socket, 120000);-    return socket;-#else-    const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);-    if (accepted < 0)-        return std::nullopt;-    enable_tcp_nodelay(accepted);-    set_socket_timeout(accepted, 120000);-    return accepted;-#endif-}--bool set_socket_timeout(Socket socket, std::uint32_t milliseconds) {-#if defined(_WIN32)-    DWORD timeout = milliseconds;-    const bool recv_ok = setsockopt(static_cast<SOCKET>(socket), SOL_SOCKET, SO_RCVTIMEO,-                                    reinterpret_cast<const char*>(&timeout), sizeof(timeout)) == 0;-    const bool send_ok = setsockopt(static_cast<SOCKET>(socket), SOL_SOCKET, SO_SNDTIMEO,-                                    reinterpret_cast<const char*>(&timeout), sizeof(timeout)) == 0;-    return recv_ok && send_ok;-#else-    timeval timeout{};-    timeout.tv_sec = static_cast<time_t>(milliseconds / 1000);-    timeout.tv_usec = static_cast<suseconds_t>((milliseconds % 1000) * 1000);-    const bool recv_ok = setsockopt(static_cast<int>(socket), SOL_SOCKET, SO_RCVTIMEO, &timeout,-                                    sizeof(timeout)) == 0;-    const bool send_ok = setsockopt(static_cast<int>(socket), SOL_SOCKET, SO_SNDTIMEO, &timeout,-                                    sizeof(timeout)) == 0;-    return recv_ok && send_ok;-#endif-}--void close_socket(Socket socket) {-    if (socket == INVALID_SOCKET_VALUE)-        return;-#if defined(_WIN32)-    closesocket(static_cast<SOCKET>(socket));-#else-    if (static_cast<int>(socket) > 2)-        ::close(static_cast<int>(socket));-#endif-}---void ignore_sigpipe() {-#if !defined(_WIN32)-    (void)::signal(SIGPIPE, SIG_IGN);-#endif-}--fs::path self_exe() {-#if defined(_WIN32)-    std::wstring buffer(32768, L'\0');-    const DWORD len = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));-    if (len > 0) {-        buffer.resize(len);-        return fs::path(buffer);-    }-    return fs::path("vn.exe");-#elif defined(__APPLE__)-    std::uint32_t size = 0;-    _NSGetExecutablePath(nullptr, &size);-    std::string buffer(size, '\0');-    if (_NSGetExecutablePath(buffer.data(), &size) == 0) {-        char resolved[PATH_MAX];-        if (::realpath(buffer.c_str(), resolved))-            return fs::path(resolved);-        buffer.resize(std::strlen(buffer.c_str()));-        return fs::path(buffer);-    }-    return fs::path("vn");-#else-    std::string buffer(4096, '\0');-    const ssize_t len = ::readlink("/proc/self/exe", buffer.data(), buffer.size() - 1);-    if (len > 0) {-        buffer.resize(static_cast<std::size_t>(len));-        return fs::path(buffer);-    }-    return fs::path("vn");-#endif-}--std::string quote_shell(std::string_view word) {-    std::string out;-    out.reserve(word.size() + 2);-    out.push_back('\'');-    for (char c : word) {-        if (c == '\'')-            out += "'\\''";-        else-            out.push_back(c);-    }-    out.push_back('\'');-    return out;-}--std::string build_shell_command(const std::vector<std::string>& parts) {-    std::string out;-    for (const auto& part : parts) {-        if (!out.empty())-            out.push_back(' ');-        out += quote_shell(part);-    }-    return out;-}---void* tls_server_ctx(std::string_view cert_path, std::string_view key_path) {-    SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());-    if (!ctx)-        return nullptr;-    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)-        goto fail;-    if (SSL_CTX_use_certificate_chain_file(ctx, std::string(cert_path).c_str()) != 1)-        goto fail;-    if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(), SSL_FILETYPE_PEM) != 1)-        goto fail;-    if (SSL_CTX_check_private_key(ctx) != 1)-        goto fail;-    return ctx;-fail:-    SSL_CTX_free(ctx);-    return nullptr;-}--void* tls_client_ctx(bool pinned) {-    SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());-    if (!ctx)-        return nullptr;-    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {-        SSL_CTX_free(ctx);-        return nullptr;-    }-    if (pinned) {-        SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);-        return ctx;-    }-    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);-    if (SSL_CTX_set_default_verify_paths(ctx) != 1) {-        SSL_CTX_free(ctx);-        return nullptr;-    }-    return ctx;-}--void* tls_accept(void* ctx, Socket fd) {-    SSL* ssl = SSL_new(static_cast<SSL_CTX*>(ctx));-    if (!ssl)-        return nullptr;-    if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 || SSL_accept(ssl) != 1) {-        SSL_free(ssl);-        return nullptr;-    }-    return ssl;-}--void* tls_connect(void* ctx, Socket fd, std::string_view host) {-    SSL* ssl = SSL_new(static_cast<SSL_CTX*>(ctx));-    if (!ssl)-        return nullptr;-    if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {-        SSL_free(ssl);-        return nullptr;-    }-    if (!host.empty()) {-        const std::string text(host);-        SSL_set_tlsext_host_name(ssl, text.c_str());-        X509_VERIFY_PARAM* param = SSL_get0_param(ssl);-        X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);-    }-    if (SSL_connect(ssl) != 1) {-        SSL_free(ssl);-        return nullptr;-    }-    return ssl;-}--bool tls_exporter(void* ssl, std::uint8_t* out, std::size_t len) {-    static constexpr char label[] = "EXPORTER-veins-auth/1";-    return SSL_export_keying_material(static_cast<SSL*>(ssl), out, len, label, sizeof(label) - 1,-                                      nullptr, 0, 0) == 1;-}--bool tls_peer_sha256(void* ssl, std::uint8_t* out) {-    X509* cert = SSL_get1_peer_certificate(static_cast<SSL*>(ssl));-    if (!cert)-        return false;-    unsigned int len = 0;-    const bool ok = X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;-    X509_free(cert);-    return ok;-}--void tls_free(void* ssl) {-    if (!ssl)-        return;-    SSL_shutdown(static_cast<SSL*>(ssl));-    SSL_free(static_cast<SSL*>(ssl));-}--void tls_ctx_free(void* ctx) {-    if (ctx)-        SSL_CTX_free(static_cast<SSL_CTX*>(ctx));-}--std::string tls_error() {-    return ssl_error_string();-}--std::string to_hex(Bytes data) {-    static constexpr char digits[] = "0123456789abcdef";-    std::string out;-    out.reserve(data.size() * 2);-    for (std::uint8_t byte : data) {-        out.push_back(digits[byte >> 4]);-        out.push_back(digits[byte & 15]);-    }-    return out;-}--bool hex_equal(std::string_view a, std::string_view b) {-    auto skip = [](std::string_view text, std::size_t& index) {-        while (index < text.size() && text[index] == ':')-            ++index;-    };-    std::size_t ai = 0;-    std::size_t bi = 0;-    for (;;) {-        skip(a, ai);-        skip(b, bi);-        if (ai >= a.size() || bi >= b.size())-            return ai >= a.size() && bi >= b.size();-        auto lower = [](char c) { return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c); };-        if (lower(a[ai]) != lower(b[bi]))-            return false;-        ++ai;-        ++bi;-    }-}--} // namespace vn::net--- a/xveins/src/net/net.h+++ /dev/null@@ -1,106 +0,0 @@-#pragma once--#include "core/common.h"--#include <cstdint>-#include <optional>-#include <string>-#include <string_view>-#include <vector>--namespace vn::net {--#if defined(_WIN32)-using Socket = std::uintptr_t;-constexpr Socket INVALID_SOCKET_VALUE = static_cast<Socket>(~0ull);-#else-using Socket = int;-constexpr Socket INVALID_SOCKET_VALUE = -1;-#endif--// A reliable, ordered byte stream over stdio, a file descriptor/socket, TLS,-// or a child process.-class Stream {-public:-    enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc };--    Stream() = default;-    ~Stream();--    Stream(Stream&& other) noexcept;-    Stream& operator=(Stream&& other) noexcept;-    Stream(const Stream&) = delete;-    Stream& operator=(const Stream&) = delete;--    static Stream stdio_stream();-    static Stream fd_stream(Socket fd);-    static Stream tls_stream(Socket fd, void* ssl);-    static std::optional<Stream> spawn_argv(const std::vector<std::string>& argv);--    friend std::optional<Stream> spawn_argv(const std::vector<std::string>& argv);--    [[nodiscard]] Kind kind() const {-        return kind_;-    }-    [[nodiscard]] void* ssl() const {-        return ssl_;-    }-    [[nodiscard]] Socket fd() const {-        return fd_in_;-    }-    [[nodiscard]] bool valid() const {-        return open_;-    }--    // Returns the number of bytes read, 0 at clean end of stream, -1 on error.-    std::int64_t read(void* buffer, std::size_t count);-    bool write_all(Bytes data);-    bool write_all(std::string_view text) {-        return write_all(Bytes(reinterpret_cast<const std::uint8_t*>(text.data()), text.size()));-    }-    void close();--private:-    Kind kind_ = Kind::Stdio;-    Socket fd_in_ = 0;-    Socket fd_out_ = 0;-    void* ssl_ = nullptr;-#if defined(_WIN32)-    void* process_ = nullptr;-    std::uint32_t process_id_ = 0;-#else-    int pid_ = 0;-#endif-    bool open_ = false;-};--// Run argv[0] with the given arguments. stdin/stdout are connected to the-// stream; stderr is inherited.-std::optional<Stream> spawn_argv(const std::vector<std::string>& argv);--std::optional<Socket> tcp_connect(std::string_view host, int port);-Socket tcp_listen(int port, int backlog = 64);-std::optional<Socket> tcp_accept(Socket listener);-void close_socket(Socket socket);-bool set_socket_timeout(Socket socket, std::uint32_t milliseconds);--void ignore_sigpipe();-fs::path self_exe();-std::string quote_shell(std::string_view word);-std::string build_shell_command(const std::vector<std::string>& parts);---void* tls_server_ctx(std::string_view cert_path, std::string_view key_path);-void* tls_client_ctx(bool pinned);-void* tls_accept(void* ctx, Socket fd);-void* tls_connect(void* ctx, Socket fd, std::string_view host);-bool tls_exporter(void* ssl, std::uint8_t* out, std::size_t len);-bool tls_peer_sha256(void* ssl, std::uint8_t* out);-void tls_free(void* ssl);-void tls_ctx_free(void* ctx);-std::string tls_error();--std::string to_hex(Bytes data);-bool hex_equal(std::string_view a, std::string_view b);--} // namespace vn::net--- a/xveins/src/object/object.cpp+++ /dev/null@@ -1,993 +0,0 @@-#include "object/object.h"--#include <algorithm>-#include <cstring>--namespace vn {--std::string_view type_name(std::uint8_t type) {-    switch (type) {-    case TYPE_CHUNK:-        return "chunk";-    case TYPE_BLOB:-        return "blob";-    case TYPE_TREE:-        return "tree";-    case TYPE_COMMIT:-        return "commit";-    case TYPE_CONFLICT:-        return "conflict";-    case TYPE_OPERATION:-        return "operation";-    case TYPE_VIEW:-        return "view";-    default:-        return "unknown";-    }-}--bool type_valid(std::uint8_t type) {-    return type >= TYPE_CHUNK && type <= TYPE_VIEW;-}---static bool is_dot_name(std::string_view s) {-    return s == "." || s == "..";-}--bool valid_name(std::string_view name) {-    if (name.empty() || name.size() > MAX_NAME_LEN)-        return false;-    for (char c : name) {-        if (c == '\0' || c == '/')-            return false;-    }-    if (is_dot_name(name))-        return false;-    if (ascii_iequals(bytes_of(name), bytes_of(".veins")))-        return false;-    return true;-}--static bool valid_component(std::string_view component) {-    if (component.empty() || component.size() > MAX_NAME_LEN)-        return false;-    if (is_dot_name(component))-        return false;-    for (char c : component) {-        if (c == '\0' || c == '/')-            return false;-    }-    return true;-}--bool valid_path(std::string_view path) {-    if (path.empty() || path.size() > MAX_PATH_LEN)-        return false;-    if (path.front() == '/')-        return false;-    std::size_t start = 0;-    for (std::size_t i = 0; i <= path.size(); ++i) {-        const bool at_end = i == path.size();-        const bool sep = !at_end && path[i] == '/';-        if (at_end || sep) {-            if (!valid_component(path.substr(start, i - start)))-                return false;-            start = i + 1;-        }-    }-    return true;-}---static std::array<std::uint64_t, 256> make_gear_table() {-    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', 'f', 'a', 's', 't', 'c',-                                              'd', 'c', '/', 'g', 'e', 'a', 'r', '/', 'v', '1'};-    std::array<std::uint64_t, 256> table{};-    for (std::size_t i = 0; i < table.size(); ++i) {-        blake3_hasher hasher;-        blake3_hasher_init(&hasher);-        blake3_hasher_update(&hasher, prefix, sizeof(prefix));-        const auto byte = static_cast<std::uint8_t>(i);-        blake3_hasher_update(&hasher, &byte, 1);-        std::array<std::uint8_t, 32> digest{};-        blake3_hasher_finalize(&hasher, digest.data(), digest.size());-        std::uint64_t value = 0;-        for (int j = 0; j < 8; ++j)-            value |= static_cast<std::uint64_t>(digest[static_cast<std::size_t>(j)]) << (j * 8);-        table[i] = value;-    }-    return table;-}--const std::array<std::uint64_t, 256>& fastcdc_gear() {-    static const auto table = make_gear_table();-    return table;-}--std::size_t fastcdc_next(Bytes data) {-    constexpr std::size_t min_size = 16384;-    constexpr std::size_t avg_size = 65536;-    constexpr std::size_t max_size = 262144;-    constexpr std::uint64_t mask_s = 0x3ffffull;-    constexpr std::uint64_t mask_l = 0x3fffull;-    const std::size_t len = data.size();-    if (len <= min_size)-        return len;-    const std::size_t limit = std::min(len, max_size);-    const std::size_t normal = std::min(avg_size, limit);-    const auto& gear = fastcdc_gear();-    std::uint64_t fp = 0;-    for (std::size_t i = min_size; i < normal; ++i) {-        fp = (fp >> 1) + gear[data[i]];-        if ((fp & mask_s) == 0)-            return i + 1;-    }-    for (std::size_t i = normal; i < limit; ++i) {-        fp = (fp >> 1) + gear[data[i]];-        if ((fp & mask_l) == 0)-            return i + 1;-    }-    return limit;-}---Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data) {-    ByteWriter w(data.size() + 8);-    w.u8(static_cast<std::uint8_t>(BlobForm::Inline));-    w.varint(data.size());-    w.raw(data);-    return w.take();-}--Result<Blob> decode_blob(Bytes body) {-    Reader r(body);-    const auto form = r.u8();-    if (!form)-        return unexpected(form.error());-    if (*form > 2)-        return fail(ErrorKind::InvalidValue, 0);-    Blob blob;-    blob.form = static_cast<BlobForm>(*form);-    if (blob.form == BlobForm::Inline) {-        const auto data = r.bytes(INLINE_THRESHOLD);-        if (!data)-            return unexpected(data.error());-        blob.data.assign(data->begin(), data->end());-        const auto fin = r.finish();-        if (!fin)-            return unexpected(fin.error());-        return blob;-    }-    const auto count = r.list_len(MAX_MANIFEST_ENTRIES);-    if (!count)-        return unexpected(count.error());-    if (*count == 0)-        return fail(ErrorKind::InvalidValue, 1);-    std::uint64_t total = 0;-    blob.entries.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const std::size_t at = r.offset();-        const auto cid = r.id();-        if (!cid)-            return unexpected(cid.error());-        const auto length = r.varint();-        if (!length)-            return unexpected(length.error());-        if (*length == 0)-            return fail(ErrorKind::InvalidValue, at);-        if (blob.form == BlobForm::Leaf && *length > MAX_CHUNK_LEN)-            return fail(ErrorKind::LimitExceeded, at);-        const std::uint64_t next = total + *length;-        if (next < total)-            return fail(ErrorKind::InvalidValue, at);-        total = next;-        blob.entries.push_back(BlobEntry{*cid, *length});-    }-    const auto fin = r.finish();-    if (!fin)-        return unexpected(fin.error());-    return blob;-}--struct NodeRef {-    Id id{};-    std::uint64_t length = 0;-};--struct Group {-    std::size_t start = 0;-    std::size_t count = 0;-};--static bool manifest_cut_after(const Id& id, std::size_t current_len) {-    if (current_len >= MAX_MANIFEST_ENTRIES)-        return true;-    if (current_len < 16)-        return false;-    return id[0] == 0;-}--BlobBuild build_blob(Bytes data) {-    BlobBuild build;-    if (data.size() <= INLINE_THRESHOLD) {-        auto body = encode_inline_blob(data);-        if (!body)-            return build;-        build.root = object_id(TYPE_BLOB, bytes_of(*body));-        RawObject object{TYPE_BLOB, std::move(*body), std::nullopt};-        object.id = build.root;-        build.objects.push_back(std::move(object));-        return build;-    }--    std::vector<NodeRef> level;-    std::size_t off = 0;-    while (off < data.size()) {-        const std::size_t n = fastcdc_next(data.subspan(off));-        const Bytes chunk = data.subspan(off, n);-        const Id cid = object_id(TYPE_CHUNK, chunk);-        RawObject object{TYPE_CHUNK, std::vector<std::uint8_t>(chunk.begin(), chunk.end()),-                         std::nullopt};-        object.id = cid;-        build.objects.push_back(std::move(object));-        level.push_back(NodeRef{cid, static_cast<std::uint64_t>(n)});-        off += n;-    }--    bool leaf_level = true;-    for (;;) {-        std::vector<Group> groups;-        std::size_t start = 0;-        for (std::size_t i = 0; i < level.size(); ++i) {-            const std::size_t current = i - start + 1;-            if (manifest_cut_after(level[i].id, current) || i + 1 == level.size()) {-                groups.push_back(Group{start, current});-                start = i + 1;-            }-        }--        std::vector<NodeRef> next;-        for (const Group& group : groups) {-            ByteWriter w(group.count * 40 + 8);-            w.u8(static_cast<std::uint8_t>(leaf_level ? BlobForm::Leaf : BlobForm::Interior));-            w.varint(group.count);-            std::uint64_t total = 0;-            for (std::size_t i = 0; i < group.count; ++i) {-                const NodeRef& node = level[group.start + i];-                w.id(node.id);-                w.varint(node.length);-                total += node.length;-            }-            auto body = w.take();-            const Id node_id = object_id(TYPE_BLOB, bytes_of(body));-            RawObject object{TYPE_BLOB, std::move(body), std::nullopt};-            object.id = node_id;-            build.objects.push_back(std::move(object));-            next.push_back(NodeRef{node_id, total});-        }--        if (next.size() == 1) {-            build.root = next.front().id;-            break;-        }-        level = std::move(next);-        leaf_level = false;-    }-    return build;-}---static bool valid_tree_kind(std::uint8_t kind) {-    return kind >= KIND_FILE && kind <= KIND_CONFLICT;-}--static bool valid_submodule_target(const Id& id) {-    for (std::size_t i = 20; i < ID_LEN; ++i) {-        if (id[i] != 0)-            return false;-    }-    return true;-}--Result<Tree> decode_tree(Bytes body) {-    Reader r(body);-    const auto count = r.list_len(MAX_TREE_ENTRIES);-    if (!count)-        return unexpected(count.error());-    Tree tree;-    tree.entries.reserve(*count);-    std::optional<std::string> prev;-    for (std::size_t i = 0; i < *count; ++i) {-        const std::size_t at = r.offset();-        auto name = r.string_bytes(MAX_NAME_LEN);-        if (!name)-            return unexpected(name.error());-        if (!valid_name(*name))-            return fail(ErrorKind::InvalidName, at);-        if (prev) {-            const int c = compare(bytes_of(*prev), bytes_of(*name));-            if (c == 0)-                return fail(ErrorKind::Duplicate, at);-            if (c > 0)-                return fail(ErrorKind::Unsorted, at);-        }-        const auto kind = r.u8();-        if (!kind)-            return unexpected(kind.error());-        if (!valid_tree_kind(*kind))-            return fail(ErrorKind::InvalidValue, at);-        const auto target = r.id();-        if (!target)-            return unexpected(target.error());-        if (*kind == KIND_SUBMODULE && !valid_submodule_target(*target))-            return fail(ErrorKind::InvalidValue, at);-        tree.entries.push_back(TreeEntry{std::move(*name), *kind, *target});-        prev = tree.entries.back().name;-    }-    const auto fin = r.finish();-    if (!fin)-        return unexpected(fin.error());-    tree.body.assign(body.begin(), body.end());-    return tree;-}--Result<std::vector<std::uint8_t>> encode_tree(const std::vector<TreeEntry>& entries) {-    ByteWriter w(entries.size() * 48 + 8);-    w.varint(entries.size());-    std::optional<std::string> prev;-    for (std::size_t i = 0; i < entries.size(); ++i) {-        const auto& e = entries[i];-        if (!valid_name(e.name))-            return fail(ErrorKind::InvalidName, i);-        if (prev && compare(bytes_of(*prev), bytes_of(e.name)) >= 0)-            return fail(ErrorKind::Unsorted, i);-        if (!valid_tree_kind(e.kind))-            return fail(ErrorKind::InvalidValue, i);-        w.length_prefixed(e.name);-        w.u8(e.kind);-        w.id(e.target);-        prev = e.name;-    }-    return w.take();-}---static Result<std::vector<Id>> read_parents(Reader& r) {-    const auto n = r.list_len(1024);-    if (!n)-        return unexpected(n.error());-    std::vector<Id> out;-    out.reserve(*n);-    for (std::size_t i = 0; i < *n; ++i) {-        const auto id = r.id();-        if (!id)-            return unexpected(id.error());-        out.push_back(*id);-    }-    return out;-}--static Result<std::vector<Rename>> read_renames(Reader& r, std::size_t parent_count,-                                                std::uint8_t state) {-    const auto n = r.list_len(1'000'000);-    if (!n)-        return unexpected(n.error());-    std::vector<Rename> out;-    if (state == RENAMES_UNKNOWN) {-        if (*n != 0)-            return fail(ErrorKind::InvalidValue, r.offset());-        return out;-    }-    out.reserve(*n);-    std::uint64_t prev_parent = 0;-    std::string prev_path;-    bool have_prev = false;-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        const auto parent = r.varint();-        if (!parent)-            return unexpected(parent.error());-        const auto kind = r.u8();-        if (!kind)-            return unexpected(kind.error());-        auto from = r.string_bytes(MAX_PATH_LEN);-        if (!from)-            return unexpected(from.error());-        auto to = r.string_bytes(MAX_PATH_LEN);-        if (!to)-            return unexpected(to.error());-        if (*parent >= parent_count)-            return fail(ErrorKind::InvalidValue, at);-        if (*kind > 1)-            return fail(ErrorKind::InvalidValue, at);-        if (!valid_path(*from) || !valid_path(*to))-            return fail(ErrorKind::InvalidName, at);-        if (have_prev) {-            if (*parent < prev_parent)-                return fail(ErrorKind::Unsorted, at);-            if (*parent == prev_parent && compare(bytes_of(prev_path), bytes_of(*to)) >= 0)-                return fail(ErrorKind::Unsorted, at);-        }-        out.push_back(Rename{*parent, *kind, std::move(*from), std::move(*to)});-        prev_parent = *parent;-        prev_path = out.back().to_path;-        have_prev = true;-    }-    return out;-}--static Result<std::vector<KeyValue>> read_extra(Reader& r) {-    const auto n = r.list_len(1024);-    if (!n)-        return unexpected(n.error());-    std::vector<KeyValue> out;-    out.reserve(*n);-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        auto key = r.string_bytes(MAX_NAME_LEN);-        if (!key)-            return unexpected(key.error());-        auto value = r.string_bytes(MAX_MESSAGE_LEN);-        if (!value)-            return unexpected(value.error());-        if (key->empty())-            return fail(ErrorKind::InvalidValue, at);-        out.push_back(KeyValue{std::move(*key), std::move(*value)});-    }-    return out;-}--Result<Commit> decode_commit(Bytes body) {-    Reader r(body);-    const auto version = r.u8();-    if (!version)-        return unexpected(version.error());-    if (*version != 1)-        return fail(ErrorKind::UnsupportedVersion, 0);-    Commit commit;-    commit.version = *version;-    auto parents = read_parents(r);-    if (!parents)-        return unexpected(parents.error());-    commit.parents = std::move(*parents);-    const auto root = r.id();-    if (!root)-        return unexpected(root.error());-    commit.root_tree = *root;-    const auto change = r.raw(CHANGE_ID_LEN);-    if (!change)-        return unexpected(change.error());-    std::memcpy(commit.change_id.data(), change->data(), CHANGE_ID_LEN);-    auto author = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);-    if (!author)-        return unexpected(author.error());-    commit.author = Sig{author->name, author->email, author->seconds, author->tz_min};-    auto committer = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);-    if (!committer)-        return unexpected(committer.error());-    commit.committer =-        Sig{committer->name, committer->email, committer->seconds, committer->tz_min};-    auto message = r.string_bytes(MAX_MESSAGE_LEN);-    if (!message)-        return unexpected(message.error());-    commit.message = std::move(*message);-    const auto state = r.u8();-    if (!state)-        return unexpected(state.error());-    if (*state > 1)-        return fail(ErrorKind::InvalidValue, r.offset() - 1);-    commit.renames_state = *state;-    auto renames = read_renames(r, commit.parents.size(), commit.renames_state);-    if (!renames)-        return unexpected(renames.error());-    commit.renames = std::move(*renames);-    auto extra = read_extra(r);-    if (!extra)-        return unexpected(extra.error());-    commit.extra = std::move(*extra);-    const auto fin = r.finish();-    if (!fin)-        return unexpected(fin.error());-    return commit;-}--std::vector<std::uint8_t> encode_commit(const Commit& commit) {-    ByteWriter w(256);-    w.u8(commit.version);-    w.varint(commit.parents.size());-    for (const auto& p : commit.parents)-        w.id(p);-    w.id(commit.root_tree);-    w.raw(Bytes(commit.change_id.data(), commit.change_id.size()));-    w.sig(Reader::Sig{commit.author.name, commit.author.email, commit.author.seconds,-                      commit.author.tz_min});-    w.sig(Reader::Sig{commit.committer.name, commit.committer.email, commit.committer.seconds,-                      commit.committer.tz_min});-    w.length_prefixed(commit.message);-    w.u8(commit.renames_state);-    w.varint(commit.renames.size());-    for (const auto& r : commit.renames) {-        w.varint(r.parent_index);-        w.u8(r.kind);-        w.length_prefixed(r.from_path);-        w.length_prefixed(r.to_path);-    }-    w.varint(commit.extra.size());-    for (const auto& kv : commit.extra) {-        w.length_prefixed(kv.key);-        w.length_prefixed(kv.value);-    }-    return w.take();-}---static bool conflict_kind_valid(std::uint8_t kind) {-    return kind == 0 || (kind >= KIND_FILE && kind <= KIND_CONFLICT);-}--static Result<ConflictValue> read_conflict_value(Reader& r) {-    const std::size_t at = r.offset();-    const auto kind = r.u8();-    if (!kind)-        return unexpected(kind.error());-    if (!conflict_kind_valid(*kind))-        return fail(ErrorKind::InvalidValue, at);-    if (*kind == 0)-        return ConflictValue{0, std::nullopt};-    const auto target = r.id();-    if (!target)-        return unexpected(target.error());-    return ConflictValue{*kind, *target};-}--static Result<std::vector<ConflictValue>> read_conflict_values(Reader& r) {-    const auto n = r.list_len(MAX_CONFLICT_TERMS);-    if (!n)-        return unexpected(n.error());-    std::vector<ConflictValue> out;-    out.reserve(*n);-    for (std::size_t i = 0; i < *n; ++i) {-        auto value = read_conflict_value(r);-        if (!value)-            return unexpected(value.error());-        out.push_back(*value);-    }-    return out;-}--static bool conflict_value_equal(const ConflictValue& a, const ConflictValue& b) {-    if (a.kind != b.kind)-        return false;-    if (a.kind == 0)-        return true;-    return a.target == b.target;-}--Result<Conflict> decode_conflict(Bytes body) {-    Reader r(body);-    Conflict conflict;-    auto adds = read_conflict_values(r);-    if (!adds)-        return unexpected(adds.error());-    conflict.adds = std::move(*adds);-    auto removes = read_conflict_values(r);-    if (!removes)-        return unexpected(removes.error());-    conflict.removes = std::move(*removes);-    const std::size_t at = r.offset();-    const auto fin = r.finish();-    if (!fin)-        return unexpected(fin.error());-    if (conflict.removes.empty())-        return fail(ErrorKind::InvalidValue, at);-    if (conflict.adds.size() != conflict.removes.size() + 1)-        return fail(ErrorKind::InvalidValue, at);-    if (conflict.adds.size() + conflict.removes.size() > MAX_CONFLICT_TERMS)-        return fail(ErrorKind::LimitExceeded, at);-    for (const auto& a : conflict.adds) {-        for (const auto& rem : conflict.removes) {-            if (conflict_value_equal(a, rem))-                return fail(ErrorKind::InvalidValue, at);-        }-    }-    bool all_same = true;-    for (std::size_t i = 1; i < conflict.adds.size(); ++i) {-        if (!conflict_value_equal(conflict.adds[0], conflict.adds[i])) {-            all_same = false;-            break;-        }-    }-    if (all_same)-        return fail(ErrorKind::InvalidValue, at);-    return conflict;-}--std::vector<std::uint8_t> encode_conflict(const Conflict& conflict) {-    ByteWriter w((conflict.adds.size() + conflict.removes.size()) * 40 + 16);-    w.varint(conflict.adds.size());-    for (const auto& v : conflict.adds) {-        w.u8(v.kind);-        if (v.kind != 0 && v.target)-            w.id(*v.target);-    }-    w.varint(conflict.removes.size());-    for (const auto& v : conflict.removes) {-        w.u8(v.kind);-        if (v.kind != 0 && v.target)-            w.id(*v.target);-    }-    return w.take();-}---static bool view_name_valid(std::string_view name) {-    if (name.empty() || name.size() > MAX_NAME_LEN)-        return false;-    return name.find('\0') == std::string_view::npos;-}--static Result<std::vector<Id>> read_view_heads(Reader& r) {-    const auto n = r.list_len(1'000'000);-    if (!n)-        return unexpected(n.error());-    std::vector<Id> out;-    out.reserve(*n);-    std::optional<Id> prev;-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        const auto id = r.id();-        if (!id)-            return unexpected(id.error());-        if (prev) {-            const int c = std::memcmp(prev->data(), id->data(), ID_LEN);-            if (c == 0)-                return fail(ErrorKind::Duplicate, at);-            if (c > 0)-                return fail(ErrorKind::Unsorted, at);-        }-        out.push_back(*id);-        prev = *id;-    }-    return out;-}--static Result<std::vector<std::optional<Id>>> read_opt_id_list(Reader& r, std::size_t max) {-    const auto n = r.list_len(max);-    if (!n)-        return unexpected(n.error());-    std::vector<std::optional<Id>> out;-    out.reserve(*n);-    for (std::size_t i = 0; i < *n; ++i) {-        const auto id = r.opt_id();-        if (!id)-            return unexpected(id.error());-        out.push_back(*id);-    }-    return out;-}--static bool opt_id_contains(const std::vector<std::optional<Id>>& ids,-                            const std::optional<Id>& id) {-    for (const auto& x : ids) {-        if (x.has_value() == id.has_value()) {-            if (!x || std::memcmp(x->data(), id->data(), ID_LEN) == 0)-                return true;-        }-    }-    return false;-}--static Result<TargetSet> read_target_set(Reader& r) {-    const std::size_t at = r.offset();-    TargetSet set;-    auto adds = read_opt_id_list(r, 64);-    if (!adds)-        return unexpected(adds.error());-    set.adds = std::move(*adds);-    auto removes = read_opt_id_list(r, 64);-    if (!removes)-        return unexpected(removes.error());-    set.removes = std::move(*removes);-    if (set.adds.empty())-        return fail(ErrorKind::InvalidValue, at);-    if (set.adds.size() != set.removes.size() + 1)-        return fail(ErrorKind::InvalidValue, at);-    if (set.adds.size() + set.removes.size() > MAX_CONFLICT_TERMS)-        return fail(ErrorKind::LimitExceeded, at);-    for (const auto& a : set.adds) {-        if (opt_id_contains(set.removes, a))-            return fail(ErrorKind::InvalidValue, at);-    }-    bool all_same = true;-    for (std::size_t i = 1; i < set.adds.size(); ++i) {-        const bool same =-            set.adds[0].has_value() == set.adds[i].has_value() &&-            (!set.adds[0] || std::memcmp(set.adds[0]->data(), set.adds[i]->data(), ID_LEN) == 0);-        if (!same) {-            all_same = false;-            break;-        }-    }-    if (all_same && set.adds.size() > 1)-        return fail(ErrorKind::InvalidValue, at);-    return set;-}--static Result<std::vector<Bookmark>> read_bookmarks(Reader& r) {-    const auto n = r.list_len(1'000'000);-    if (!n)-        return unexpected(n.error());-    std::vector<Bookmark> out;-    out.reserve(*n);-    std::optional<std::string> prev;-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        auto name = r.string_bytes(MAX_NAME_LEN);-        if (!name)-            return unexpected(name.error());-        if (!view_name_valid(*name))-            return fail(ErrorKind::InvalidName, at);-        if (prev) {-            const int c = compare(bytes_of(*prev), bytes_of(*name));-            if (c == 0)-                return fail(ErrorKind::Duplicate, at);-            if (c > 0)-                return fail(ErrorKind::Unsorted, at);-        }-        auto targets = read_target_set(r);-        if (!targets)-            return unexpected(targets.error());-        out.push_back(Bookmark{std::move(*name), std::move(*targets)});-        prev = out.back().name;-    }-    return out;-}--static Result<std::vector<TagRef>> read_tags(Reader& r) {-    const auto n = r.list_len(1'000'000);-    if (!n)-        return unexpected(n.error());-    std::vector<TagRef> out;-    out.reserve(*n);-    std::optional<std::string> prev;-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        auto name = r.string_bytes(MAX_NAME_LEN);-        if (!name)-            return unexpected(name.error());-        if (!view_name_valid(*name))-            return fail(ErrorKind::InvalidName, at);-        if (prev) {-            const int c = compare(bytes_of(*prev), bytes_of(*name));-            if (c == 0)-                return fail(ErrorKind::Duplicate, at);-            if (c > 0)-                return fail(ErrorKind::Unsorted, at);-        }-        const auto id = r.id();-        if (!id)-            return unexpected(id.error());-        out.push_back(TagRef{std::move(*name), *id});-        prev = out.back().name;-    }-    return out;-}--static Result<std::vector<RemoteRef>> read_remote_refs(Reader& r) {-    const auto n = r.list_len(1'000'000);-    if (!n)-        return unexpected(n.error());-    std::vector<RemoteRef> out;-    out.reserve(*n);-    std::optional<std::pair<std::string, std::string>> prev;-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        auto remote = r.string_bytes(MAX_NAME_LEN);-        if (!remote)-            return unexpected(remote.error());-        auto name = r.string_bytes(MAX_NAME_LEN);-        if (!name)-            return unexpected(name.error());-        if (!view_name_valid(*remote) || !view_name_valid(*name))-            return fail(ErrorKind::InvalidName, at);-        if (prev) {-            const int c1 = compare(bytes_of(prev->first), bytes_of(*remote));-            const int c2 = c1 != 0 ? 0 : compare(bytes_of(prev->second), bytes_of(*name));-            if (c1 == 0 && c2 == 0)-                return fail(ErrorKind::Duplicate, at);-            if (c1 > 0 || (c1 == 0 && c2 > 0))-                return fail(ErrorKind::Unsorted, at);-        }-        const auto id = r.id();-        if (!id)-            return unexpected(id.error());-        out.push_back(RemoteRef{std::move(*remote), std::move(*name), *id});-        prev = std::make_pair(out.back().remote, out.back().name);-    }-    return out;-}--static Result<std::vector<WorkspaceRef>> read_workspaces(Reader& r) {-    const auto n = r.list_len(1'000'000);-    if (!n)-        return unexpected(n.error());-    std::vector<WorkspaceRef> out;-    out.reserve(*n);-    std::optional<std::string> prev;-    for (std::size_t i = 0; i < *n; ++i) {-        const std::size_t at = r.offset();-        auto workspace = r.string_bytes(MAX_NAME_LEN);-        if (!workspace)-            return unexpected(workspace.error());-        if (!view_name_valid(*workspace))-            return fail(ErrorKind::InvalidName, at);-        if (prev) {-            const int c = compare(bytes_of(*prev), bytes_of(*workspace));-            if (c == 0)-                return fail(ErrorKind::Duplicate, at);-            if (c > 0)-                return fail(ErrorKind::Unsorted, at);-        }-        const auto id = r.id();-        if (!id)-            return unexpected(id.error());-        out.push_back(WorkspaceRef{std::move(*workspace), *id});-        prev = out.back().workspace;-    }-    return out;-}--Result<View> decode_view(Bytes body) {-    Reader r(body);-    View view;-    auto heads = read_view_heads(r);-    if (!heads)-        return unexpected(heads.error());-    view.heads = std::move(*heads);-    auto bookmarks = read_bookmarks(r);-    if (!bookmarks)-        return unexpected(bookmarks.error());-    view.bookmarks = std::move(*bookmarks);-    auto tags = read_tags(r);-    if (!tags)-        return unexpected(tags.error());-    view.tags = std::move(*tags);-    auto remote_refs = read_remote_refs(r);-    if (!remote_refs)-        return unexpected(remote_refs.error());-    view.remote_refs = std::move(*remote_refs);-    auto workspaces = read_workspaces(r);-    if (!workspaces)-        return unexpected(workspaces.error());-    view.working_copies = std::move(*workspaces);-    const auto fin = r.finish();-    if (!fin)-        return unexpected(fin.error());-    return view;-}--static void put_target_set(ByteWriter& w, const TargetSet& set) {-    w.varint(set.adds.size());-    for (const auto& id : set.adds)-        w.opt_id(id);-    w.varint(set.removes.size());-    for (const auto& id : set.removes)-        w.opt_id(id);-}--std::vector<std::uint8_t> encode_view(const View& view) {-    ByteWriter w(256);-    w.varint(view.heads.size());-    for (const auto& id : view.heads)-        w.id(id);-    w.varint(view.bookmarks.size());-    for (const auto& bookmark : view.bookmarks) {-        w.length_prefixed(bookmark.name);-        put_target_set(w, bookmark.targets);-    }-    w.varint(view.tags.size());-    for (const auto& tag : view.tags) {-        w.length_prefixed(tag.name);-        w.id(tag.target);-    }-    w.varint(view.remote_refs.size());-    for (const auto& ref : view.remote_refs) {-        w.length_prefixed(ref.remote);-        w.length_prefixed(ref.name);-        w.id(ref.target);-    }-    w.varint(view.working_copies.size());-    for (const auto& workspace : view.working_copies) {-        w.length_prefixed(workspace.workspace);-        w.id(workspace.target);-    }-    return w.take();-}---Result<Operation> decode_operation(Bytes body) {-    Reader r(body);-    Operation op;-    const auto parent_count = r.list_len(1024);-    if (!parent_count)-        return unexpected(parent_count.error());-    op.parents.reserve(*parent_count);-    for (std::size_t i = 0; i < *parent_count; ++i) {-        const auto id = r.id();-        if (!id)-            return unexpected(id.error());-        op.parents.push_back(*id);-    }-    const auto view = r.id();-    if (!view)-        return unexpected(view.error());-    op.view = *view;-    auto start = r.time_ms();-    if (!start)-        return unexpected(start.error());-    op.start = *start;-    auto end = r.time_ms();-    if (!end)-        return unexpected(end.error());-    op.end = *end;-    auto hostname = r.string_bytes(MAX_NAME_LEN);-    if (!hostname)-        return unexpected(hostname.error());-    op.hostname = std::move(*hostname);-    auto username = r.string_bytes(MAX_NAME_LEN);-    if (!username)-        return unexpected(username.error());-    op.username = std::move(*username);-    auto description = r.string_bytes(MAX_MESSAGE_LEN);-    if (!description)-        return unexpected(description.error());-    op.description = std::move(*description);-    const auto tag_count = r.list_len(1024);-    if (!tag_count)-        return unexpected(tag_count.error());-    op.tags.reserve(*tag_count);-    for (std::size_t i = 0; i < *tag_count; ++i) {-        const std::size_t at = r.offset();-        auto key = r.string_bytes(MAX_NAME_LEN);-        if (!key)-            return unexpected(key.error());-        auto value = r.string_bytes(MAX_MESSAGE_LEN);-        if (!value)-            return unexpected(value.error());-        if (key->empty())-            return fail(ErrorKind::InvalidValue, at);-        op.tags.push_back(KeyValue{std::move(*key), std::move(*value)});-    }-    const auto fin = r.finish();-    if (!fin)-        return unexpected(fin.error());-    return op;-}--std::vector<std::uint8_t> encode_operation(const Operation& op) {-    ByteWriter w(256);-    w.varint(op.parents.size());-    for (const auto& p : op.parents)-        w.id(p);-    w.id(op.view);-    w.time_ms(op.start);-    w.time_ms(op.end);-    w.length_prefixed(op.hostname);-    w.length_prefixed(op.username);-    w.length_prefixed(op.description);-    w.varint(op.tags.size());-    for (const auto& kv : op.tags) {-        w.length_prefixed(kv.key);-        w.length_prefixed(kv.value);-    }-    return w.take();-}--bool is_lazy_blob(const Id& id) {-    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '-',-                                              'g', 'i', 't', 'o', 'i', 'd'};-    return std::memcmp(id.data(), prefix, sizeof(prefix)) == 0;-}--} // namespace vn--- a/xveins/src/object/object.h+++ /dev/null@@ -1,241 +0,0 @@-#pragma once--#include "core/common.h"--#include <optional>-#include <string>-#include <vector>--namespace vn {--class Store;--constexpr std::uint8_t TYPE_CHUNK = 1;-constexpr std::uint8_t TYPE_BLOB = 2;-constexpr std::uint8_t TYPE_TREE = 3;-constexpr std::uint8_t TYPE_COMMIT = 4;-constexpr std::uint8_t TYPE_CONFLICT = 5;-constexpr std::uint8_t TYPE_OPERATION = 6;-constexpr std::uint8_t TYPE_VIEW = 7;--std::string_view type_name(std::uint8_t type);-bool type_valid(std::uint8_t type);--struct RawObject {-    std::uint8_t type = 0;-    std::vector<std::uint8_t> body;-    std::optional<Id> id;-};--struct KeyValue {-    std::string key;-    std::string value;-};---bool valid_name(std::string_view name);-bool valid_path(std::string_view path);---enum class BlobForm : std::uint8_t { Inline = 0, Leaf = 1, Interior = 2 };--struct BlobEntry {-    Id id{};-    std::uint64_t length = 0;-};--struct Blob {-    BlobForm form = BlobForm::Inline;-    std::vector<std::uint8_t> data;-    std::vector<BlobEntry> entries;-};--Result<Blob> decode_blob(Bytes body);-Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data);--std::size_t fastcdc_next(Bytes data);-const std::array<std::uint64_t, 256>& fastcdc_gear();--struct BlobBuild {-    Id root{};-    std::vector<RawObject> objects;-};--BlobBuild build_blob(Bytes data);---constexpr std::uint8_t KIND_FILE = 1;-constexpr std::uint8_t KIND_EXECUTABLE = 2;-constexpr std::uint8_t KIND_SYMLINK = 3;-constexpr std::uint8_t KIND_SUBTREE = 4;-constexpr std::uint8_t KIND_SUBMODULE = 5;-constexpr std::uint8_t KIND_CONFLICT = 6;-constexpr std::uint8_t KIND_MISSING = 0;--struct TreeEntry {-    std::string name;-    std::uint8_t kind = 0;-    Id target{};-};--struct Tree {-    std::vector<TreeEntry> entries;-    std::vector<std::uint8_t> body;-};--Result<Tree> decode_tree(Bytes body);-Result<std::vector<std::uint8_t>> encode_tree(const std::vector<TreeEntry>& entries);---constexpr std::uint8_t RENAMES_UNKNOWN = 0;-constexpr std::uint8_t RENAMES_RECORDED = 1;--struct Rename {-    std::uint64_t parent_index = 0;-    std::uint8_t kind = 0;-    std::string from_path;-    std::string to_path;-};--struct Commit {-    std::uint8_t version = 1;-    std::vector<Id> parents;-    Id root_tree{};-    ChangeId change_id{};-    Sig author;-    Sig committer;-    std::string message;-    std::uint8_t renames_state = RENAMES_RECORDED;-    std::vector<Rename> renames;-    std::vector<KeyValue> extra;-};--Result<Commit> decode_commit(Bytes body);-std::vector<std::uint8_t> encode_commit(const Commit& commit);---struct ConflictValue {-    std::uint8_t kind = 0;-    std::optional<Id> target;-};--struct Conflict {-    std::vector<ConflictValue> adds;-    std::vector<ConflictValue> removes;-};--Result<Conflict> decode_conflict(Bytes body);-std::vector<std::uint8_t> encode_conflict(const Conflict& conflict);---struct TargetSet {-    std::vector<std::optional<Id>> adds;-    std::vector<std::optional<Id>> removes;-};--struct Bookmark {-    std::string name;-    TargetSet targets;-};--struct TagRef {-    std::string name;-    Id target{};-};--struct RemoteRef {-    std::string remote;-    std::string name;-    Id target{};-};--struct WorkspaceRef {-    std::string workspace;-    Id target{};-};--struct View {-    std::vector<Id> heads;-    std::vector<Bookmark> bookmarks;-    std::vector<TagRef> tags;-    std::vector<RemoteRef> remote_refs;-    std::vector<WorkspaceRef> working_copies;-};--struct Operation {-    std::vector<Id> parents;-    Id view{};-    Reader::TimeMs start;-    Reader::TimeMs end;-    std::string hostname;-    std::string username;-    std::string description;-    std::vector<KeyValue> tags;-};--Result<View> decode_view(Bytes body);-std::vector<std::uint8_t> encode_view(const View& view);-Result<Operation> decode_operation(Bytes body);-std::vector<std::uint8_t> encode_operation(const Operation& op);---struct LoadedCommit {-    Commit commit;-    std::vector<std::uint8_t> body;-};--struct LogOrderNode {-    Id id{};-    std::int64_t seconds = 0;-    std::vector<Id> parents;-};--std::optional<LoadedCommit> load_commit(Store& store, const Id& id);-bool has_changes(Store& store, const LoadedCommit& loaded);-std::vector<Id> collect_commits(Store& store, std::span<const Id> start);-std::vector<Id> all_commits(Store& store, const View& view);-std::vector<Id> view_roots(const View& view);-std::vector<std::size_t> order_log_nodes(const std::vector<LogOrderNode>& nodes);-std::optional<Id> resolve_revision(Store& store, const View& view, std::string_view rev);-std::optional<Id> working_copy_id(const View& view);--bool contains_id(const std::vector<Id>& ids, const Id& id);-bool target_contains(const std::vector<std::optional<Id>>& ids, const Id& id);--struct FlatEntry {-    std::string path;-    std::uint8_t kind = 0;-    Id target{};-};--std::vector<FlatEntry> flatten_tree(Store& store, const Id& tree_id);-Result<std::vector<FlatEntry>> flatten_tree_checked(Store& store, const Id& tree_id);-std::vector<FlatEntry> flatten_or_empty(Store& store, std::optional<Id> tree_id);-const FlatEntry* find_flat(const std::vector<FlatEntry>& entries, std::string_view path);-int find_tree_name(const Tree& tree, std::string_view name);-bool tree_conflicted(Store& store, const Id& tree_id);--struct TreeChange {-    std::string path;-    std::uint8_t old_kind = KIND_MISSING;-    std::uint8_t new_kind = KIND_MISSING;-    std::optional<Id> old_id;-    std::optional<Id> new_id;-};--std::vector<TreeChange> compare_trees(Store& store, std::optional<Id> old_tree,-                                      std::optional<Id> new_tree);--std::optional<std::vector<std::uint8_t>> read_blob(Store& store, const Id& id);--struct BlobMeasure {-    std::uint64_t bytes = 0;-    std::uint64_t lines = 0;-    bool line_has_content = false;-    bool has_nul = false;-};--bool measure_blob(Store& store, const Id& id, BlobMeasure& out);-bool is_lazy_blob(const Id& id);--} // namespace vn--- a/xveins/src/protocol/promisor.cpp+++ /dev/null@@ -1,58 +0,0 @@-#include "protocol/promisor.h"--#include "protocol/protocol.h"-#include "store/store.h"--#include <optional>-#include <string>-#include <vector>--namespace vn {--namespace {--std::string remote_field(std::string_view remote, std::string_view field) {-    std::string out = "remote.";-    out += remote;-    out.push_back('.');-    out += field;-    return out;-}--bool fetch_missing_chunk(const fs::path& root, const Id& id) {-    static thread_local bool active = false;-    if (active)-        return false;-    active = true;-    struct Guard {-        bool& flag;-        ~Guard() {-            flag = false;-        }-    } guard{active};--    auto promisor = repo_config_value(root, "promisor");-    if (!promisor || promisor->empty())-        return false;-    auto url = repo_config_value(root, remote_field(*promisor, "url"));-    if (!url || url->empty())-        return false;-    auto key = repo_config_value(root, remote_field(*promisor, "key"));-    auto pin = repo_config_value(root, remote_field(*promisor, "tls-pin"));-    const std::string repo_name = proto::url_repo_name(*url);-    auto client = proto::Client::connect(*url, key ? *key : std::string(), repo_name,-                                         pin ? *pin : std::string());-    if (!client)-        return false;-    const std::vector<Id> ids = {id};-    return client->get_chunks(root, ids);-}--} // namespace--void install_promisor_fetcher() {-    set_promisor_fetcher(-        [](const fs::path& root, const Id& id) { return fetch_missing_chunk(root, id); });-}--} // namespace vn--- a/xveins/src/protocol/promisor.h+++ /dev/null@@ -1,9 +0,0 @@-#pragma once--namespace vn {--// Register the lazy-chunk fetch hook used by the store. Safe to call more than-// once; the last registration wins.-void install_promisor_fetcher();--} // namespace vn--- a/xveins/src/protocol/protocol.cpp+++ /dev/null@@ -1,910 +0,0 @@-#include "protocol/protocol.h"--#include "auth/auth.h"-#include "store/store.h"--#include <blake3.h>--#include <algorithm>-#include <array>-#include <cstring>--namespace vn::proto {--namespace {--std::string connect_error;--void put_u16_be(ByteWriter& writer, std::uint16_t value) {-    writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));-    writer.u8(static_cast<std::uint8_t>(value & 255u));-}--std::optional<std::uint16_t> read_u16_be(Reader& reader) {-    const auto high = reader.u8();-    if (!high)-        return std::nullopt;-    const auto low = reader.u8();-    if (!low)-        return std::nullopt;-    return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) | *low);-}--std::vector<std::uint8_t> encode_string_list(const std::vector<std::string>& items) {-    ByteWriter writer(128);-    writer.varint(items.size());-    for (const auto& item : items)-        writer.length_prefixed(item);-    return writer.take();-}--std::optional<std::vector<std::string>> decode_string_list(Reader& reader, std::size_t max) {-    const auto count = reader.list_len(max);-    if (!count)-        return std::nullopt;-    std::vector<std::string> out;-    out.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const auto value = reader.bytes(4096);-        if (!value)-            return std::nullopt;-        out.emplace_back(str_of(*value));-    }-    return out;-}--std::string bytes_to_string(Bytes data) {-    return std::string(str_of(data));-}--void append_id(ByteWriter& writer, const Id& id) {-    writer.raw(Bytes(id.data(), id.size()));-}--std::optional<Id> read_id(Reader& reader) {-    const auto id = reader.id();-    if (!id)-        return std::nullopt;-    return *id;-}--std::size_t find_char(std::string_view text, char needle) {-    const auto at = text.find(needle);-    return at == std::string_view::npos ? std::string_view::npos : at;-}--struct Authority {-    std::string host;-    int port = 0;-};--Authority parse_authority(std::string_view authority, int default_port, bool strip_user) {-    if (strip_user) {-        const auto at = find_char(authority, '@');-        if (at != std::string_view::npos)-            authority.remove_prefix(at + 1);-    }-    Authority out;-    out.host = std::string(authority);-    out.port = default_port;-    const auto colon = find_char(authority, ':');-    if (colon != std::string_view::npos) {-        out.host = std::string(authority.substr(0, colon));-        const std::string_view port_text = authority.substr(colon + 1);-        if (!port_text.empty()) {-            int port = 0;-            bool numeric = true;-            for (char c : port_text) {-                if (c < '0' || c > '9') {-                    numeric = false;-                    break;-                }-                if (port > 1000000)-                    port = 1000000;-                port = port * 10 + (c - '0');-            }-            if (numeric)-                out.port = port;-        }-    }-    return out;-}--std::optional<net::Stream> connect_stream(const Url& url, std::string_view tls_pin,-                                          std::string& binding) {-    if (url.ssh) {-        std::vector<std::string> remote;-        remote.reserve(4);-        remote.emplace_back("vn");-        remote.emplace_back("serve");-        remote.emplace_back("-stdio");-        remote.emplace_back(url.path);-        const std::string remote_command = net::build_shell_command(remote);-        std::vector<std::string> argv;-        argv.reserve(6);-        argv.emplace_back("ssh");-        if (url.port != 22) {-            argv.emplace_back("-p");-            argv.emplace_back(std::to_string(url.port));-        }-        argv.emplace_back(url.host);-        argv.emplace_back(remote_command);-        auto stream = net::Stream::spawn_argv(argv);-        if (!stream)-            connect_error = "cannot start the SSH transport";-        return stream;-    }-    if (url.tls) {-        auto fd = net::tcp_connect(url.host, url.port);-        if (!fd) {-            connect_error = "cannot connect: host refused the connection or is unreachable";-            return std::nullopt;-        }-        void* ctx = net::tls_client_ctx(!tls_pin.empty());-        if (!ctx) {-            net::close_socket(*fd);-            connect_error = "cannot initialize TLS";-            return std::nullopt;-        }-        void* ssl = net::tls_connect(ctx, *fd, url.host);-        net::tls_ctx_free(ctx);-        if (!ssl) {-            net::close_socket(*fd);-            connect_error = "TLS handshake failed";-            return std::nullopt;-        }-        std::array<std::uint8_t, 32> exported{};-        if (net::tls_exporter(ssl, exported.data(), exported.size()))-            binding.assign(reinterpret_cast<const char*>(exported.data()), exported.size());-        if (!tls_pin.empty()) {-            std::array<std::uint8_t, 32> digest{};-            const bool got = net::tls_peer_sha256(ssl, digest.data());-            const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));-            if (!got || !net::hex_equal(hex, tls_pin)) {-                net::close_socket(*fd);-                net::tls_free(ssl);-                connect_error = "TLS certificate pin mismatch";-                return std::nullopt;-            }-        }-        return net::Stream::tls_stream(*fd, ssl);-    }-    std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve", "-stdio", url.path};-    auto stream = net::Stream::spawn_argv(argv);-    if (!stream)-        connect_error = "cannot start the local vn server";-    return stream;-}--std::string id_text(const Id& id) {-    return hex_encode(id);-}--} // namespace--std::vector<std::uint8_t> encode_hello(const Hello& hello) {-    ByteWriter writer(128);-    put_u16_be(writer, hello.min_version);-    put_u16_be(writer, hello.max_version);-    writer.raw(Bytes(encode_string_list(hello.capabilities)));-    writer.length_prefixed(hello.repo);-    writer.length_prefixed(hello.client_nonce);-    return writer.take();-}--std::optional<Hello> decode_hello(Bytes data) {-    Reader reader(data);-    const auto min_version = read_u16_be(reader);-    if (!min_version)-        return std::nullopt;-    const auto max_version = read_u16_be(reader);-    if (!max_version)-        return std::nullopt;-    auto capabilities = decode_string_list(reader, 64);-    if (!capabilities)-        return std::nullopt;-    const auto repo = reader.bytes(4096);-    if (!repo)-        return std::nullopt;-    const auto nonce = reader.bytes(64);-    if (!nonce)-        return std::nullopt;-    if (!reader.finish())-        return std::nullopt;-    Hello out;-    out.min_version = *min_version;-    out.max_version = *max_version;-    out.capabilities = std::move(*capabilities);-    out.repo = bytes_to_string(*repo);-    out.client_nonce = bytes_to_string(*nonce);-    return out;-}--std::vector<std::uint8_t> encode_hello_ok(const HelloOk& hello) {-    ByteWriter writer(128);-    put_u16_be(writer, hello.version);-    writer.raw(Bytes(encode_string_list(hello.capabilities)));-    writer.length_prefixed(hello.server_nonce);-    writer.u8(hello.auth_required);-    return writer.take();-}--std::optional<HelloOk> decode_hello_ok(Bytes data) {-    Reader reader(data);-    const auto version = read_u16_be(reader);-    if (!version)-        return std::nullopt;-    auto capabilities = decode_string_list(reader, 64);-    if (!capabilities)-        return std::nullopt;-    const auto nonce = reader.bytes(64);-    if (!nonce)-        return std::nullopt;-    const auto auth = reader.u8();-    if (!auth)-        return std::nullopt;-    if (!reader.finish())-        return std::nullopt;-    HelloOk out;-    out.version = *version;-    out.capabilities = std::move(*capabilities);-    out.server_nonce = bytes_to_string(*nonce);-    out.auth_required = *auth;-    return out;-}--std::vector<std::uint8_t> encode_auth(const Auth& auth) {-    ByteWriter writer(128);-    writer.length_prefixed(auth.public_key);-    writer.length_prefixed(auth.signature);-    return writer.take();-}--std::optional<Auth> decode_auth(Bytes data) {-    Reader reader(data);-    const auto public_key = reader.bytes(64);-    if (!public_key)-        return std::nullopt;-    const auto signature = reader.bytes(128);-    if (!signature)-        return std::nullopt;-    if (!reader.finish())-        return std::nullopt;-    return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)};-}--std::vector<std::uint8_t> encode_auth_ok(const AuthOk& auth) {-    ByteWriter writer(64);-    writer.u8(auth.role);-    writer.length_prefixed(auth.fingerprint);-    return writer.take();-}--std::optional<AuthOk> decode_auth_ok(Bytes data) {-    Reader reader(data);-    const auto role = reader.u8();-    if (!role)-        return std::nullopt;-    const auto fingerprint = reader.bytes(64);-    if (!fingerprint)-        return std::nullopt;-    if (!reader.finish())-        return std::nullopt;-    return AuthOk{*role, bytes_to_string(*fingerprint)};-}--std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo>& refs) {-    ByteWriter writer(256);-    writer.varint(refs.size());-    for (const auto& ref : refs) {-        writer.length_prefixed(ref.name);-        append_id(writer, ref.target);-        writer.length_prefixed(ref.change_id);-        writer.u8(ref.kind);-    }-    return writer.take();-}--std::optional<std::vector<RefInfo>> decode_refs(Bytes data) {-    Reader reader(data);-    const auto count = reader.list_len(1000000);-    if (!count)-        return std::nullopt;-    std::vector<RefInfo> out;-    out.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const auto name = reader.bytes(4096);-        if (!name)-            return std::nullopt;-        const auto target = read_id(reader);-        if (!target)-            return std::nullopt;-        const auto change_id = reader.bytes(64);-        if (!change_id)-            return std::nullopt;-        const auto kind = reader.u8();-        if (!kind)-            return std::nullopt;-        RefInfo ref;-        ref.name = bytes_to_string(*name);-        ref.target = *target;-        ref.change_id = bytes_to_string(*change_id);-        ref.kind = *kind;-        out.push_back(std::move(ref));-    }-    if (!reader.finish())-        return std::nullopt;-    return out;-}--std::vector<std::uint8_t> encode_ids(const std::vector<Id>& ids) {-    ByteWriter writer(ids.size() * 32 + 8);-    writer.varint(ids.size());-    for (const auto& id : ids)-        append_id(writer, id);-    return writer.take();-}--std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max) {-    Reader reader(data);-    const auto count = reader.list_len(max);-    if (!count)-        return std::nullopt;-    std::vector<Id> out;-    out.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const auto id = read_id(reader);-        if (!id)-            return std::nullopt;-        out.push_back(*id);-    }-    if (!reader.finish())-        return std::nullopt;-    return out;-}--std::vector<std::uint8_t> encode_negotiate(const std::vector<Id>& wants,-                                           const std::vector<Id>& haves) {-    ByteWriter writer(256);-    writer.varint(wants.size());-    for (const auto& id : wants)-        append_id(writer, id);-    writer.varint(haves.size());-    for (const auto& id : haves)-        append_id(writer, id);-    return writer.take();-}--std::optional<Negotiate> decode_negotiate(Bytes data) {-    Reader reader(data);-    const auto want_count = reader.list_len(1000000);-    if (!want_count)-        return std::nullopt;-    Negotiate out;-    out.wants.reserve(*want_count);-    for (std::size_t i = 0; i < *want_count; ++i) {-        const auto id = read_id(reader);-        if (!id)-            return std::nullopt;-        out.wants.push_back(*id);-    }-    const auto have_count = reader.list_len(1000000);-    if (!have_count)-        return std::nullopt;-    out.haves.reserve(*have_count);-    for (std::size_t i = 0; i < *have_count; ++i) {-        const auto id = read_id(reader);-        if (!id)-            return std::nullopt;-        out.haves.push_back(*id);-    }-    if (!reader.finish())-        return std::nullopt;-    return out;-}--std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t>& known,-                                              std::uint8_t enough) {-    ByteWriter writer(known.size() + 16);-    writer.u8(enough);-    writer.varint(known.size());-    for (std::uint8_t bit : known)-        writer.u8(bit);-    return writer.take();-}--std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data) {-    Reader reader(data);-    const auto enough = reader.u8();-    if (!enough)-        return std::nullopt;-    const auto count = reader.list_len(1000000);-    if (!count)-        return std::nullopt;-    std::vector<std::uint8_t> out;-    out.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const auto bit = reader.u8();-        if (!bit)-            return std::nullopt;-        out.push_back(*bit);-    }-    if (!reader.finish())-        return std::nullopt;-    return out;-}--std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t>& bits) {-    ByteWriter writer(bits.size() + 8);-    writer.varint(bits.size());-    for (std::uint8_t bit : bits)-        writer.u8(bit);-    return writer.take();-}--std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data) {-    Reader reader(data);-    const auto count = reader.list_len(1000000);-    if (!count)-        return std::nullopt;-    std::vector<std::uint8_t> out;-    out.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const auto bit = reader.u8();-        if (!bit)-            return std::nullopt;-        out.push_back(*bit);-    }-    if (!reader.finish())-        return std::nullopt;-    return out;-}--std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef>& updates) {-    ByteWriter writer(256);-    writer.varint(updates.size());-    for (const auto& update : updates) {-        writer.length_prefixed(update.name);-        writer.opt_id(update.expected);-        writer.opt_id(update.target);-    }-    return writer.take();-}--std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data) {-    Reader reader(data);-    const auto count = reader.list_len(1000000);-    if (!count)-        return std::nullopt;-    std::vector<UpdateRef> out;-    out.reserve(*count);-    for (std::size_t i = 0; i < *count; ++i) {-        const auto name = reader.bytes(4096);-        if (!name)-            return std::nullopt;-        const auto expected = reader.opt_id();-        if (!expected)-            return std::nullopt;-        const auto target = reader.opt_id();-        if (!target)-            return std::nullopt;-        UpdateRef update;-        update.name = bytes_to_string(*name);-        update.expected = *expected;-        update.target = *target;-        out.push_back(std::move(update));-    }-    if (!reader.finish())-        return std::nullopt;-    return out;-}--std::string auth_message(std::uint16_t version, std::string_view repo, Bytes server_nonce,-                         Bytes client_nonce, Bytes binding) {-    ByteWriter writer(128);-    writer.raw(std::string_view("veins-auth/1"));-    writer.u8(0);-    writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));-    writer.u8(static_cast<std::uint8_t>(version & 255u));-    writer.length_prefixed(repo);-    writer.raw(server_nonce);-    writer.raw(client_nonce);-    writer.raw(binding);-    return std::string(str_of(writer.view()));-}--std::string_view role_name(std::uint8_t role) {-    if (role == 2)-        return "write";-    if (role == 1)-        return "read";-    return "anonymous";-}--std::optional<Url> parse_url(std::string_view url) {-    constexpr std::string_view file_prefix = "file://";-    constexpr std::string_view ssh_prefix = "ssh://";-    constexpr std::string_view veins_prefix = "veins://";-    if (url.starts_with(file_prefix))-        return Url{false, false, {}, 0, std::string(url.substr(file_prefix.size()))};-    if (url.starts_with(ssh_prefix)) {-        std::string_view rest = url.substr(ssh_prefix.size());-        const auto slash = rest.find('/');-        if (slash == std::string_view::npos)-            return std::nullopt;-        const auto authority = parse_authority(rest.substr(0, slash), 22, true);-        return Url{false, true, authority.host, authority.port,-                   std::string(rest.substr(slash + 1))};-    }-    if (url.starts_with(veins_prefix)) {-        std::string_view rest = url.substr(veins_prefix.size());-        const auto slash = rest.find('/');-        if (slash == std::string_view::npos)-            return std::nullopt;-        const auto authority = parse_authority(rest.substr(0, slash), 7419, false);-        return Url{true, false, authority.host, authority.port,-                   std::string(rest.substr(slash + 1))};-    }-    return std::nullopt;-}--std::string url_repo_name(std::string_view url) {-    auto parsed = parse_url(url);-    if (!parsed || !parsed->tls)-        return {};-    return parsed->path;-}--void Client::set_error(std::string text) {-    last_error_ = std::move(text);-}--void Client::set_error_frame(const wire::Frame& frame) {-    const std::uint8_t code = wire::read_error(frame.payload);-    const std::string_view name = wire::error_code_name(code);-    const std::string message = wire::error_message(frame.payload);-    std::string text = "server error: ";-    text += name;-    if (!message.empty()) {-        text += ": ";-        text += message;-    }-    set_error(std::move(text));-}--std::optional<wire::Frame> Client::request(std::uint8_t kind, Bytes payload) {-    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);-    if (!wire::write_frame(stream_, kind, rid, payload)) {-        set_error("connection closed while sending request");-        return std::nullopt;-    }-    auto frame = wire::read_frame(stream_);-    if (!frame) {-        set_error("connection closed while waiting for server response");-        return std::nullopt;-    }-    if (frame->kind == wire::ERROR) {-        set_error_frame(*frame);-        return std::nullop

Diff truncated at 2 MiB.