navid/veins / commit

a987695cdcf0

Navid M <navidmomtahen@gmail.com> · 2026-11-29 · [impl-rust-ii]

parents: 4d6f82fdba18

Browse files at this commit · Download source

<unset>
--- /dev/null+++ b/veinsrs/.gitignore@@ -0,0 +1,1 @@+/target/--- /dev/null+++ b/veinsrs/Cargo.lock@@ -0,0 +1,315 @@+# 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 = "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 = "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 = "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",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[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",+ "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 = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]++[[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 = "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/veinsrs/Cargo.toml@@ -0,0 +1,21 @@+[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"+zstd = "0.13"++[profile.release]+opt-level = 3+lto = false+codegen-units = 16--- /dev/null+++ b/veinsrs/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/veinsrs/src/cli/commands/bookmark.rs@@ -0,0 +1,221 @@+use std::path::Path;++use crate::cli::args;+use crate::error::{Error, Result};+use crate::object::view::Bookmark;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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/veinsrs/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/veinsrs/src/cli/commands/commit.rs@@ -0,0 +1,104 @@+use std::path::Path;++use crate::cli::args;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::commit::{self, Commit};+use crate::object::id::Id;+use crate::object::TYPE_COMMIT;+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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/veinsrs/src/cli/commands/init.rs@@ -0,0 +1,22 @@+use std::path::Path;++use crate::cli::args;+use crate::error::Result;+use crate::store::layout;++pub fn run(arguments: &[String]) -> Result<u8> {+    let mut path = ".";+    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 {+            path = argument;+        }+    }+    let root = layout::init(Path::new(path))?;+    println!("info: initialized veins repository at {}", root.display());+    Ok(0)+}--- /dev/null+++ b/veinsrs/src/cli/commands/log.rs@@ -0,0 +1,142 @@+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/veinsrs/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/veinsrs/src/cli/commands/selftest.rs@@ -0,0 +1,176 @@+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::{hash_bytes, object_id, 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 manifest = blob::decode(&build.objects.last().unwrap().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/veinsrs/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/veinsrs/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/veinsrs/src/cli/config_cmd.rs@@ -0,0 +1,211 @@+use std::collections::BTreeMap;+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::store::layout;++use super::output;++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/veinsrs/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/veinsrs/src/cli/history.rs@@ -0,0 +1,1262 @@+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::graph::{self, LogNode};+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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,+    has_changes: bool,+    conflicted: 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 has_changes = if working_copy == Some(id) {+            graph::has_changes(&mut store, &commit)?+        } else {+            false+        };+        let message = first_line(&commit.message);+        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(),+            has_changes,+            conflicted: false,+        });+        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);+        }+    }+    for record in &mut records {+        record.conflicted = graph::tree_conflicted(&mut store, record.root_tree)?;+    }++    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 mut rendered = String::new();+    if titles {+        rendered.push(' ');+        rendered.push(' ');+        rendered.push_str(&format!("{:<12}", "Commit"));+        rendered.push_str("  ");+        rendered.push_str(&format!("{:<change_width$}", "Change"));+        rendered.push_str("  ");+        rendered.push_str(&format!("{:<19}", "Date"));+        rendered.push_str("  ");+        rendered.push_str(&format!("{:<author_width$}", "Author"));+        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 { " " };+        rendered.push_str(marker);+        rendered.push(' ');+        rendered.push_str(&format!("{:<12}", record.id.short()));+        rendered.push_str("  ");+        rendered.push_str(&format!("{:<change_width$}", change_ids[position]));+        rendered.push_str("  ");+        rendered.push_str(&format!("{:<19}", crate::time::format_utc(record.seconds)));+        rendered.push_str("  ");+        rendered.push_str(&format!("{:<author_width$}", record.author));+        rendered.push_str("  ");+        if record.message.is_empty() {+            rendered.push_str("<unset>");+        } else {+            rendered.push_str(&record.message);+        }+        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 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 mut difference = String::new();+    {+        let mut buffer = Vec::new();+        let mut collector = Collector::new(&mut buffer);+        collector.render(&mut store, old_tree, Some(commit.root_tree), false, b"")?;+        difference = 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/veinsrs/src/cli/info.rs@@ -0,0 +1,609 @@+use std::collections::HashMap;+use std::path::Path;++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|mv|ls|rm> ...\n\nmanage named branch pointers\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",+        "repack" => "usage: vn repack [path] [-level:N] [-verbose]\n\nrewrite packs\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",+        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 = std::collections::HashSet::new();+    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 = 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 = 0usize;+    let mut total_lines = 0u64;+    let mut generated_files = 0usize;+    let mut generated_lines = 0u64;+    let mut generated_bytes = 0u64;+    let mut by_ext: HashMap<String, (usize, u64, u64)> = HashMap::new();+    if let Some(working) = working+        && let Some(commit) = graph::load_commit(&mut store, working)?+    {+        for entry in tree::flatten(&mut store, commit.root_tree)? {+            if !matches!(entry.kind, tree::KIND_FILE | tree::KIND_EXECUTABLE) {+                continue;+            }+            let attributes = rules.lookup(&String::from_utf8_lossy(&entry.path));+            let data = graph::read_blob(&mut store, entry.target)?.unwrap_or_default();+            let binary = attributes.text == AttributeText::Binary+                || (attributes.text == AttributeText::Auto+                    && data.iter().take(8192).any(|byte| *byte == 0));+            let lines = if binary { 0 } else { count_nonblank(&data) };+            if attributes.generated {+                generated_files += 1;+                generated_lines += lines;+                generated_bytes += data.len() as u64;+                if !include_generated {+                    continue;+                }+            }+            total_files += 1;+            total_lines += lines;+            let ext = extension(&entry.path);+            let stat = by_ext.entry(ext).or_insert((0, 0, 0));+            stat.0 += 1;+            stat.1 += lines;+            stat.2 += data.len() as u64;+        }+    }+    let mut commits = 0usize;+    let mut authors: HashMap<String, usize> = 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 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!();+    println!("Project       {}", root.file_name().unwrap_or_default().to_string_lossy());+    println!(+        "HEAD          {}",+        working.map(|id| id.short()).unwrap_or_else(|| "<none>".to_string())+    );+    println!("Changes       {commits}");+    println!("Bookmarks     {}", view.bookmarks.len());+    println!("Tags          {}", view.tags.len());+    println!("Files         {total_files}");+    println!("Lines         {total_lines}");+    println!("Authors       {}", authors.len());+    if generated_files > 0 {+        print!("Generated     {generated_files} files  {generated_lines} lines  {generated_bytes} B");+        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.cmp(&right.0))+        });+        for (ext, (files, lines, _)) in entries {+            println!("{ext:<8}  {lines} lines  {files} files");+        }+    }+    println!();+    println!("{}", output::bold_cyan("Authors"));+    println!();+    let mut authors: Vec<_> = authors.into_iter().collect();+    authors.sort_by(|left, right| {+        right+            .1+            .cmp(&left.1)+            .then_with(|| left.0.cmp(&right.0))+    });+    for (name, count) in authors {+        println!("{name:<12}  {count} commits");+    }+    println!();+    Ok(0)+}++fn count_nonblank(data: &[u8]) -> u64 {+    let mut count = 0;+    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 data[start..end]+            .iter()+            .any(|byte| !matches!(*byte, b' ' | b'\t' | b'\r'))+        {+            count += 1;+        }+        if end >= data.len() {+            break;+        }+        start = end + 1;+    }+    count+}++fn extension(path: &[u8]) -> String {+    let text = String::from_utf8_lossy(path);+    let base = text.rsplit('/').next().unwrap_or(&text);+    match base.rfind('.') {+        Some(position) if position > 0 && position + 1 < base.len() => {+            base[position..].to_lowercase()+        }+        _ => "(none)".to_string(),+    }+}--- /dev/null+++ b/veinsrs/src/cli/merge_cmd.rs@@ -0,0 +1,617 @@+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::{self, FlatEntry};+use crate::object::{TYPE_COMMIT, TYPE_CONFLICT};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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)+}++pub fn _unused(_entry: &FlatEntry, _store: &mut Store) {}--- /dev/null+++ b/veinsrs/src/cli/mod.rs@@ -0,0 +1,119 @@+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) => {+            eprintln!("error: {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" => info::repack(rest),+        "inf" => info::inf(rest),+        "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");+    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/veinsrs/src/cli/net_cmd.rs@@ -0,0 +1,951 @@+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::conflict;+use crate::object::id::Id;+use crate::object::tree::{self, KIND_SUBTREE};+use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};+use crate::protocol::client::Client;+use crate::protocol::messages::{self, RefInfo, UpdateRef};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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)?;+    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 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 argument.starts_with("-pin:") {+        } 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 mut client = Client::connect(&url, &key, &repo_name)?;+    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::new();+    if have_remote {+        forward.push(remote_name.clone());+    }+    if path != "." {+        forward.push(path.clone());+    }+    // The fetch call is inlined so pull sees the updated view.+    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_objects(+    store: &mut Store,+    commits: &[Id],+    output: &mut Vec<Id>,+    seen: &mut HashSet<Id>,+) -> Result<()> {+    fn walk_tree(+        store: &mut Store,+        id: Id,+        output: &mut Vec<Id>,+        seen: &mut HashSet<Id>,+    ) -> Result<()> {+        if !seen.insert(id) {+            return Ok(());+        }+        output.push(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 {+            if entry.kind == KIND_SUBTREE {+                walk_tree(store, entry.target, output, seen)?;+            } else if entry.kind != tree::KIND_SUBMODULE {+                walk_object(store, entry.target, output, seen)?;+            }+        }+        Ok(())+    }+    fn walk_object(+        store: &mut Store,+        id: Id,+        output: &mut Vec<Id>,+        seen: &mut HashSet<Id>,+    ) -> Result<()> {+        if !seen.insert(id) {+            return Ok(());+        }+        output.push(id);+        let Some(body) = store.body(id, TYPE_BLOB)? else {+            return Ok(());+        };+        if let Ok(blob) = blob::decode(&body) {+            match blob.form {+                BlobForm::Leaf => {+                    for entry in blob.entries {+                        if seen.insert(entry.id) {+                            output.push(entry.id);+                        }+                    }+                }+                BlobForm::Interior => {+                    for entry in blob.entries {+                        walk_object(store, entry.id, output, seen)?;+                    }+                }+                BlobForm::Inline => {}+            }+        }+        Ok(())+    }+    for id in commits {+        if !seen.insert(*id) {+            continue;+        }+        output.push(*id);+        let Some(commit) = graph::load_commit(store, *id)? else {+            continue;+        };+        walk_tree(store, commit.root_tree, output, seen)?;+    }+    Ok(())+}++fn push(arguments: &[String]) -> Result<u8> {+    let mut remote_name = String::new();+    let mut bookmark = String::new();+    let mut path = ".".to_string();+    let mut have_remote = false;+    for argument in arguments {+        if argument.starts_with("-key:") || argument.starts_with("-pin:") {+            continue;+        } 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 = remote_key_name(&root, &remote_name);+    let repo_name = messages::url_repo_name(&url);+    let mut client = Client::connect(&url, &key, &repo_name)?;+    let remote_refs = client.list_refs()?;+    let mut commits = vec![bookmark_target];+    let mut updates = Vec::new();+    let remote_bookmark = remote_refs+        .iter()+        .find(|reference| reference.kind == 0 && reference.name == bookmark)+        .map(|reference| reference.target);+    updates.push(UpdateRef {+        name: bookmark.clone(),+        expected: remote_bookmark,+        target: Some(bookmark_target),+    });+    for tag in &view.tags {+        let name = String::from_utf8_lossy(&tag.name).into_owned();+        commits.push(tag.target);+        let remote = remote_refs+            .iter()+            .find(|reference| reference.kind == 1 && reference.name == name)+            .map(|reference| reference.target);+        updates.push(UpdateRef {+            name: format!("refs/tags/{name}"),+            expected: remote,+            target: Some(tag.target),+        });+    }+    let mut objects = Vec::new();+    let mut seen = HashSet::new();+    collect_objects(&mut store, &commits, &mut objects, &mut seen)?;+    client.push_objects(&root, &objects)?;+    client.update_refs(&updates)?;+    output::info_prefix();+    println!("pushed {bookmark}");+    let tag_count = updates.len() - 1;+    if tag_count > 0 {+        output::info_prefix();+        println!("pushed {tag_count} 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 index = 0;+    while index < arguments.len() {+        let argument = &arguments[index];+        if argument == "-stdio" {+            stdio = true;+        } else if let Some(value) = argument.strip_prefix("-quota:") {+            let _ = value;+        } else if !core::is_flag(argument) {+            repo = argument.clone();+        }+        index += 1;+    }+    if !stdio {+        return Err(Error::new("serve requires -stdio"));+    }+    let root = layout::discover(Path::new(&repo)).map_err(|_| Error::new("not a veins repository"))?;+    crate::server::serve_stdio(&root, 0)?;+    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 mut client = Client::connect(&url, &key, &repo_name)?;+    let (role, _) = client.whoami()?;+    println!("role: {}", messages::role_name(role));+    Ok(0)+}++pub fn git(_arguments: &[String]) -> Result<u8> {+    Err(Error::new("git bridge is not implemented yet"))+}++pub fn _unused(_path: &PathBuf, _blob: u8) {+    let _ = (TYPE_COMMIT, TYPE_CONFLICT);+}--- /dev/null+++ b/veinsrs/src/cli/output.rs@@ -0,0 +1,103 @@+use std::io::IsTerminal;++use crate::core;++pub fn enabled() -> bool {+    std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal()+}++fn style(text: &str, code: &str) -> String {+    if enabled() {+        format!("\x1b[{code}m{text}\x1b[0m")+    } else {+        text.to_string()+    }+}++pub fn error_prefix() {+    print!("{}: ", style("error", "1;31"));+}++pub fn warning_prefix() {+    print!("{}: ", style("warning", "1;33"));+}++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 {+    style(text, "1;36")+}++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> {+    match crate::store::layout::discover(std::path::Path::new(".")) {+        Ok(root) => Some(root),+        Err(_) => {+            error_prefix();+            println!("not a veins repository");+            None+        }+    }+}++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/veinsrs/src/cli/refs.rs@@ -0,0 +1,521 @@+use std::path::Path;++use crate::core;+use crate::error::{Error, Result};+use crate::object::view::{Bookmark, TagRef};+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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..]),+        "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|mv|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!("  ls [-no-col-titles]       list bookmarks");+    println!("  rm <name>                 delete a bookmark");+}++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/veinsrs/src/cli/status.rs@@ -0,0 +1,81 @@+use std::collections::HashSet;++use crate::core;+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 {+            println!("A {path}");+        } else if change.new_kind == crate::object::tree::KIND_MISSING {+            println!("D {path}");+        } else if change.new_kind == KIND_CONFLICT {+            println!("C {path}");+            conflicts += 1;+        } else {+            println!("M {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;+    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(&mut store, commit.root_tree)? {+            conflicted_commits += 1;+        }+        stack.extend(commit.parents);+    }+    if conflicted_commits > 0 {+        println!("{conflicted_commits} conflicted commit(s) in ancestry");+    }+    Ok(0)+}++pub fn _unused() {+    let _ = core::is_flag("-a");+}--- /dev/null+++ b/veinsrs/src/cli/worktree_cmd.rs@@ -0,0 +1,713 @@+use std::collections::HashSet;+use std::fs;+use std::path::{Path, PathBuf};++use crate::core;+use crate::error::{Error, Result};+use crate::identity;+use crate::object::commit::{self, Commit};+use crate::object::path::valid_path;+use crate::object::tree::{self, TreeEntry, KIND_SUBTREE};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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(".")).unwrap_or_else(|_| std::env::current_dir().unwrap());+    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 lines.last().is_some_and(|line| line.eol.is_empty()) {+                lines.last_mut().unwrap().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}"))),+        },+    }+}++pub fn _unused(_path: PathBuf, _commit: Commit) {}--- /dev/null+++ b/veinsrs/src/core.rs@@ -0,0 +1,900 @@+use std::collections::BTreeMap;+use std::env;+use std::fs;+use std::io::{Read, Write};+use std::os::unix::ffi::{OsStrExt, OsStringExt};+use std::os::unix::fs::MetadataExt;+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};++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 {+    PathBuf::from(std::ffi::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 read_file_opt(path: &Path, maximum: u64) -> Option<Vec<u8>> {+    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())))+}++pub fn write_file(path: &Path, data: &[u8]) -> bool {+    if let Some(parent) = path.parent()+        && !parent.as_os_str().is_empty()+        && fs::create_dir_all(parent).is_err()+    {+        return false;+    }+    let mut options = fs::OpenOptions::new();+    options.write(true).create(true).truncate(true);+    let Ok(mut file) = options.open(path) else {+        return false;+    };+    file.write_all(data).is_ok() && file.flush().is_ok()+}++pub fn append_file(path: &Path, data: &[u8]) -> bool {+    if let Some(parent) = path.parent()+        && !parent.as_os_str().is_empty()+        && fs::create_dir_all(parent).is_err()+    {+        return false;+    }+    let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(path) else {+        return false;+    };+    file.write_all(data).is_ok() && file.flush().is_ok()+}++fn sync_file(path: &Path) -> bool {+    use std::os::unix::io::AsRawFd;+    let Ok(file) = fs::File::open(path) else {+        return false;+    };+    unsafe { libc::fsync(file.as_raw_fd()) == 0 }+}++fn sync_directory(path: &Path) {+    use std::os::unix::io::AsRawFd;+    if let Ok(directory) = fs::File::open(path) {+        unsafe {+            libc::fsync(directory.as_raw_fd());+        }+    }+}++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(entry.file_name().into_vec());+    }+    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| target.as_os_str().as_bytes().to_vec())+}++#[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: metadata.mode() & 0o111 != 0,+        size: metadata.size(),+        mtime_ns: (metadata.mtime() as u64)+            .wrapping_mul(1_000_000_000)+            .wrapping_add(metadata.mtime_nsec() as u64),+        inode: metadata.ino(),+    })+}++pub fn repo_config_value(root: &Path, key: &str) -> Option<String> {+    let data = read_file_opt(&root.join(".veins").join("config"), 0)?;+    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 = read_file_opt(&path, 0)+        .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');+    write_file(&path, &output)+}++pub fn repo_config_remove(root: &Path, key: &str) -> bool {+    let path = root.join(".veins").join("config");+    let output = read_file_opt(&path, 0)+        .map(|data| config_without_key(&data, key))+        .unwrap_or_default();+    write_file(&path, &output)+}++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 {+    let mut output = String::from("'");+    for character in value.chars() {+        if character == '\'' {+            output.push_str("'\\''");+        } else {+            output.push(character);+        }+    }+    output.push('\'');+    output+}++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;+        }+    }+    "vi".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)));+    }+    std::process::Command::new("sh")+        .arg("-c")+        .arg(command)+        .status()+        .is_ok_and(|status| status.success())+}++pub fn stdin_is_terminal() -> bool {+    unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }+}++pub fn stdout_is_terminal() -> bool {+    unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 }+}++pub fn stderr_is_terminal() -> bool {+    unsafe { libc::isatty(libc::STDERR_FILENO) == 1 }+}++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;+        }+    }+    "less -R".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 = std::process::Command::new("sh")+        .arg("-c")+        .arg(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,+}++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 Vec<GlobState>, work: &mut usize, state: GlobState) -> bool {+        if *work >= MAX_WORK {+            return false;+        }+        *work += 1;+        stack.push(state);+        true+    }+    let mut stack = Vec::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)+}--- /dev/null+++ b/veinsrs/src/crypto.rs@@ -0,0 +1,579 @@+use std::fs;+use std::os::unix::fs::PermissionsExt;++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 metadata.permissions().mode() & 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 _ = fs::set_permissions(&directory, fs::Permissions::from_mode(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 _ = fs::set_permissions(&path, fs::Permissions::from_mode(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)+        && metadata.permissions().mode() & 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 _ = fs::set_permissions(path, fs::Permissions::from_mode(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/veinsrs/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/veinsrs/src/encoding/reader.rs@@ -0,0 +1,114 @@+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/veinsrs/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/veinsrs/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/veinsrs/src/identity.rs@@ -0,0 +1,53 @@+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/veinsrs/src/lib.rs@@ -0,0 +1,15 @@+pub mod cli;+pub mod core;+pub mod crypto;+pub mod encoding;+pub mod error;+pub mod identity;+pub mod merge;+pub mod object;+pub mod protocol;+pub mod server;+pub mod store;+pub mod time;+pub mod worktree;++pub use error::{Error, Result};--- /dev/null+++ b/veinsrs/src/main.rs@@ -0,0 +1,6 @@+use std::process::ExitCode;++fn main() -> ExitCode {+    let args: Vec<String> = std::env::args().skip(1).collect();+    ExitCode::from(veins_rust::cli::run(&args))+}--- /dev/null+++ b/veinsrs/src/merge/engine.rs@@ -0,0 +1,1726 @@+use std::collections::HashMap;+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::{object_id, Id};+use crate::object::tree::{self, FlatEntry, TreeEntry, KIND_CONFLICT, KIND_SUBTREE};+use crate::object::{TYPE_BLOB, TYPE_CHUNK, TYPE_COMMIT, TYPE_CONFLICT, TYPE_TREE};+use crate::store::graph;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::store::Txn;+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 mut a = lines(left);+    let mut 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,+    ai: usize,+    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' ', ai: index, bi: index });+    }+    for index in prefix..a.len() - suffix {+        output.push(Op { tag: b'-', ai: index, bi: 0 });+    }+    for index in prefix..b.len() - suffix {+        output.push(Op { tag: b'+', ai: 0, bi: index });+    }+    for index in 0..suffix {+        output.push(Op {+            tag: b' ',+            ai: a.len() - suffix + index,+            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' ', 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]) {+            output.push(Op { tag: b'+', ai: 0, bi: j - 1 });+            j -= 1;+        } else {+            output.push(Op { tag: b'-', ai: i - 1, 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 base = sum.removes[0].target.unwrap();+        let ours = sum.adds[0].target.unwrap();+        let theirs = sum.adds[1].target.unwrap();+        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);+    }+    merge_blobs(+        store,+        None,+        base.target.unwrap(),+        ours.target.unwrap(),+        theirs.target.unwrap(),+        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)+}++pub fn _unused(_: &mut Store, _: &mut Txn, _: &mut HashMap<Id, Id>) {}--- /dev/null+++ b/veinsrs/src/merge/mod.rs@@ -0,0 +1,2 @@+pub mod engine;+pub mod rename;--- /dev/null+++ b/veinsrs/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/veinsrs/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::{object_id, Id};+use crate::object::{+    RawObject, INLINE_THRESHOLD, MAX_CHUNK_LEN, MAX_MANIFEST_ENTRIES, 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/veinsrs/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/veinsrs/src/object/commit.rs@@ -0,0 +1,196 @@+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/veinsrs/src/object/conflict.rs@@ -0,0 +1,96 @@+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/veinsrs/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/veinsrs/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/veinsrs/src/object/path.rs@@ -0,0 +1,50 @@+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/veinsrs/src/object/tree.rs@@ -0,0 +1,154 @@+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_ENTRIES, MAX_TREE_DEPTH, 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::with_capacity(count);+    let mut previous: Option<Vec<u8>> = None;+    for _ in 0..count {+        let name = reader.bytes(MAX_NAME_LEN)?.to_vec();+        if !valid_name(&name) {+            return Err(Error::new("invalid tree entry name"));+        }+        if previous.as_ref().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"));+        }+        entries.push(TreeEntry { name, kind, target });+        previous = Some(entries.last().unwrap().name.clone());+    }+    reader.finish()?;+    Ok(Tree { entries })+}++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())))?;+    let 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_into(store, entry.target, prefix, output, depth + 1)?;+        } else {+            output.push(FlatEntry {+                path: prefix.clone(),+                kind: entry.kind,+                target: entry.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/veinsrs/src/object/view.rs@@ -0,0 +1,327 @@+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/veinsrs/src/protocol/client.rs@@ -0,0 +1,304 @@+use std::path::Path;++use crate::core;+use crate::crypto;+use crate::error::{Error, Result};+use crate::object::id::{object_id, Id};+use crate::object::TYPE_CHUNK;+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) -> Result<Self> {+        let parsed = messages::parse_url(url).ok_or_else(|| Error::new("invalid remote URL"))?;+        if parsed.tls || parsed.ssh {+            return Err(Error::new("only file:// transports are supported"));+        }+        let stream = Stream::spawn(&[+            "serve".to_string(),+            "-stdio".to_string(),+            parsed.path.clone(),+        ])?;+        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,+                &[],+            );+            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]) -> 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"));+            }+        }+        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+}++pub fn _unused(_core: &core::StatInfo, _chunk: u8) {+    let _ = TYPE_CHUNK;+}--- /dev/null+++ b/veinsrs/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/veinsrs/src/protocol/mod.rs@@ -0,0 +1,3 @@+pub mod client;+pub mod messages;+pub mod wire;--- /dev/null+++ b/veinsrs/src/protocol/wire.rs@@ -0,0 +1,244 @@+use std::io::{Read, Write};++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::MAX_OBJECT_BODY;++pub const MAX_FRAME: usize = 16 * 1024 * 1024;++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>,+}++impl Stream {+    pub fn stdio() -> Self {+        Self {+            reader: Box::new(std::io::stdin()),+            writer: Box::new(std::io::stdout()),+            child: None,+        }+    }++    pub fn spawn(arguments: &[String]) -> Result<Self> {+        let executable = std::env::current_exe().map_err(Error::from)?;+        let mut child = std::process::Command::new(executable)+            .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),+        })+    }++    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/veinsrs/src/server.rs@@ -0,0 +1,677 @@+use std::path::{Path, PathBuf};++use crate::core;+use crate::crypto;+use crate::error::Result;+use crate::object::blob::{self, BlobForm};+use crate::object::conflict;+use crate::object::id::{object_id, 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::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::store::Txn;++const MAX_CHUNKS: usize = 4096;++struct Session {+    stream: Stream,+    repo: PathBuf,+    store: Store,+    access: crypto::Access,+    hello_repo: String,+    client_nonce: Vec<u8>,+    server_nonce: Vec<u8>,+    version: u16,+    authed: bool,+    role: u8,+    public_key: Option<crypto::PublicKey>,+    fingerprint: Vec<u8>,+    haves: Vec<Id>,+}++fn role_text(role: u8) -> &'static str {+    match role {+        2 => "write",+        1 => "read",+        _ => "anonymous",+    }+}++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 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.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,+        &[],+    );+    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 public_key = public_key.unwrap();+    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 handle_put_records(session: &mut Session, frame: &wire::Frame) -> Result<bool> {+    if deny(session, frame.request_id, true) {+        return Ok(true);+    }+    let mut writer = Writer::default();+    let mut hasher = blake3::Hasher::new();+    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",+                );+            }+            break;+        }+        if incoming.kind != wire::kind::RECORDS {+            return Ok(false);+        }+        hasher.update(&incoming.payload);+        let Some(record) = wire::parse_record(&incoming.payload) else {+            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 {+            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.finish(&session.repo) != 0 {+        session.stream.write_error(+            frame.request_id,+            wire::error_code::INTERNAL,+            "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 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 {+        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)+        }+    }+}++pub fn serve_stdio(repo: &Path, _quota: u64) -> Result<()> {+    let mut session = Session {+        stream: Stream::stdio(),+        repo: repo.to_path_buf(),+        store: Store::open(repo)?,+        access: crypto::empty_access(),+        hello_repo: String::new(),+        client_nonce: Vec::new(),+        server_nonce: Vec::new(),+        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 log_line(session: &Session, outcome: &str) {+    let path = crate::store::layout::veins_dir(&session.repo).join("server.log");+    let line = format!(+        "{} {} {} {}\n",+        crate::time::now_millis(),+        role_text(session.role),+        outcome,+        session.hello_repo+    );+    core::append_file(&path, line.as_bytes());+}--- /dev/null+++ b/veinsrs/src/store/graph.rs@@ -0,0 +1,415 @@+use std::collections::HashSet;++use crate::error::{Error, Result};+use crate::object::blob::{self, BlobForm};+use crate::object::commit::{self, Commit};+use crate::object::id::{is_hex_prefix, prefix_matches, Id};+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 => {+            for entry in blob.entries {+                let Some(chunk) = store.body_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(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) -> Result<bool> {+    if depth > crate::object::MAX_TREE_DEPTH {+        return Ok(true);+    }+    let Some(body) = store.body(tree_id, crate::object::TYPE_TREE)? else {+        return Ok(true);+    };+    let Ok(tree) = tree::decode(&body) else {+        return Ok(true);+    };+    for entry in tree.entries {+        if entry.kind == KIND_CONFLICT {+            return Ok(true);+        }+        if entry.kind == KIND_SUBTREE && conflicted_into(store, entry.target, depth + 1)? {+            return Ok(true);+        }+    }+    Ok(false)+}++pub fn tree_conflicted(store: &mut Store, tree_id: Id) -> Result<bool> {+    conflicted_into(store, tree_id, 0)+}--- /dev/null+++ b/veinsrs/src/store/index.rs@@ -0,0 +1,120 @@+use crate::encoding::Reader;+use crate::error::{Error, Result};+use crate::object::id::{hash_bytes, Id};++#[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 mut entries: Vec<IndexEntry> = Vec::with_capacity(count);+    for index in 0..count {+        let id = reader.id()?;+        if index > 0 && entries[index - 1].id.0 >= id.0 {+            return Err(Error::new("index ids are not sorted"));+        }+        entries.push(IndexEntry { id, offset: 0 });+    }+    for entry in &mut entries {+        entry.offset = reader.u64le()?;+    }+    let mut pack_trailer = [0u8; 32];+    pack_trailer.copy_from_slice(reader.raw(32)?);+    let trailer_offset = data.len() - 32;+    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 counts = [0u32; 256];+    for entry in &entries {+        counts[entry.id.0[0] as usize] += 1;+    }+    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/veinsrs/src/store/layout.rs@@ -0,0 +1,165 @@+use std::fs::{self, File};+use std::io::Write;+use std::os::unix::io::AsRawFd;+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};++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_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<()> {+    let file = File::open(path)?;+    if unsafe { libc::fsync(file.as_raw_fd()) } != 0 {+        return Err(std::io::Error::last_os_error().into());+    }+    Ok(())+}++fn sync_directory(path: &Path) {+    if let Ok(directory) = File::open(path) {+        unsafe {+            libc::fsync(directory.as_raw_fd());+        }+    }+}++pub fn read_directory(path: &Path) -> Result<Vec<Vec<u8>>> {+    use std::os::unix::ffi::OsStringExt;++    let mut names = Vec::new();+    for entry in fs::read_dir(path)? {+        let entry = entry?;+        names.push(entry.file_name().into_vec());+    }+    names.sort();+    Ok(names)+}++pub fn os_string(bytes: &[u8]) -> std::ffi::OsString {+    use std::os::unix::ffi::OsStringExt;+    std::ffi::OsString::from_vec(bytes.to_vec())+}++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/veinsrs/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::{set_promisor_fetcher, Location, Store};+pub use transaction::Txn;--- /dev/null+++ b/veinsrs/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/veinsrs/src/store/pack.rs@@ -0,0 +1,761 @@+use std::collections::{HashMap, HashSet};+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::{hash_bytes, Id};+use crate::object::{+    type_valid, RawObject, MAX_CHUNK_LEN, MAX_OBJECT_BODY, MAX_STORE_PACK_BYTES, TYPE_BLOB,+    TYPE_CHUNK,+};+use crate::store::index::{self, IndexEntry};++#[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+    }+}++fn decompress(data: &[u8], raw_len: usize) -> Result<Vec<u8>> {+    zstd::bulk::decompress(data, raw_len).map_err(|error| Error::new(error.to_string()))+}++fn decompress_dict(data: &[u8], raw_len: usize, dictionary: &[u8]) -> Result<Vec<u8>> {+    let mut decoder = zstd::bulk::Decompressor::with_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,+}++fn compress(data: &[u8], level: i32) -> Option<Vec<u8>> {+    if data.is_empty() {+        return None;+    }+    let compressed = zstd::bulk::compress(data, level).ok()?;+    (compressed.len() < data.len()).then_some(compressed)+}++fn compress_dict(data: &[u8], dictionary: &[u8], level: i32) -> Option<Vec<u8>> {+    if data.is_empty() || dictionary.is_empty() {+        return None;+    }+    let mut encoder = zstd::bulk::Compressor::with_dictionary(level, dictionary).ok()?;+    let compressed = encoder.compress(data).ok()?;+    (compressed.len() < data.len()).then_some(compressed)+}++struct BlobRoot {+    pending_index: usize,+    entries: Vec<BlobEntry>,+    offsets: Vec<u64>,+    length: u64,+}++fn select_pack_deltas(+    ids: &[Id],+    kinds: &[u8],+    bodies: &[Vec<u8>],+    compression: &mut [u8],+    compressed: &mut [Vec<u8>],+    base: &mut [Option<usize>],+    level: i32,+) {+    let mut blob_index: HashMap<Id, usize> = HashMap::new();+    let mut chunk_index: HashMap<Id, usize> = HashMap::new();+    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: HashSet<Id> = HashSet::new();+    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: &HashMap<Id, usize>,+                bodies: &[Vec<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 {+            pending_index: index,+            entries,+            offsets,+            length: offset,+        });+    }+    if roots.len() < 2 {+        return;+    }++    let mut parent = vec![usize::MAX; roots.len()];+    {+        let mut last_root: HashMap<Id, usize> = HashMap::new();+        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], 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;+            let mut best_frame = Vec::new();+            for delta in -2i64..=2 {+                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(frame) =+                    compress_dict(&bodies[target_index], &bodies[base_index], level)+                {+                    let framed = frame.len() + 10;+                    if framed < best_size {+                        best_size = framed;+                        best_base = base_index;+                        best_frame = frame;+                    }+                }+            }+            if best_base != usize::MAX {+                base[target_index] = Some(best_base);+                compression[target_index] = 2;+                compressed[target_index] = best_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 = HashSet::new();+    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<Vec<u8>> = unique.iter().map(|object| object.body.clone()).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()];++    let initial: Vec<(u8, Vec<u8>)> = bodies+        .par_iter()+        .map(|body| {+            if body.len() < 64 {+                (0, Vec::new())+            } else if let Some(value) = compress(body, level) {+                (1, value)+            } else {+                (0, Vec::new())+            }+        })+        .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 = bodies+        .iter()+        .map(|body| body.len() + 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/veinsrs/src/store/reader.rs@@ -0,0 +1,401 @@+use std::fs::{self, File};+use std::os::unix::fs::FileExt;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, OnceLock};++use crate::encoding::Reader;+use crate::error::{Error, Result};+use crate::object::id::{object_id, Id};+use crate::object::view::{self, Operation, View};+use crate::object::{type_valid, MAX_STORE_PACK_BYTES, TYPE_CHUNK};+use crate::store::index::{self, Index};+use crate::store::layout;+use crate::store::pack::{self, record_limit, Pack};++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,+}++struct PackFile {+    path: PathBuf,+    mtime_ns: u64,+    index: Option<Index>,+    file: Option<File>,+}++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| {+                        use std::os::unix::fs::MetadataExt;+                        (metadata.mtime() as u64)+                            .wrapping_mul(1_000_000_000)+                            .wrapping_add(metadata.mtime_nsec() as u64)+                    })+                    .unwrap_or(0);+                self.packs.push(PackFile {+                    path,+                    mtime_ns,+                    index: None,+                    file: 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 read_range(&mut self, index: usize, offset: u64, length: usize) -> Option<Vec<u8>> {+        if length as u64 > MAX_STORE_PACK_BYTES {+            return None;+        }+        if !self.open_file(index) {+            return None;+        }+        let file = self.packs[index].file.as_ref()?;+        let mut data = vec![0u8; length];+        let mut done = 0;+        while done < length {+            match file.read_at(&mut data[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,+            }+        }+        data.truncate(done);+        Some(data)+    }++    fn read_at_shared(&self, index: usize, offset: u64, length: usize) -> Option<Vec<u8>> {+        if length as u64 > MAX_STORE_PACK_BYTES {+            return None;+        }+        let file = self.packs.get(index)?.file.as_ref()?;+        let mut data = vec![0u8; length];+        let mut done = 0;+        while done < length {+            match file.read_at(&mut data[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,+            }+        }+        data.truncate(done);+        Some(data)+    }++    fn record_at(&self, pack_index: usize, offset: u64, expected: Option<Id>) -> Option<Location> {+        let header = self.read_at_shared(pack_index, offset, 96)?;+        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;+            }+            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),+            1 => zstd::bulk::decompress(&stored, raw_len)+                .map_err(|error| Error::new(error.to_string())),+            2 => {+                let mut reader = Reader::new(&stored);+                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)?;+                let mut decoder = zstd::bulk::Decompressor::with_dictionary(&body)+                    .map_err(|error| Error::new(error.to_string()))?;+                decoder+                    .decompress(frame, raw_len)+                    .map_err(|error| Error::new(error.to_string()))+            }+            _ => 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.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))+    }++    pub fn preload(&mut self) -> Result<()> {+        for index in 0..self.packs.len() {+            self.ensure_index(index);+            self.open_file(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/veinsrs/src/store/transaction.rs@@ -0,0 +1,174 @@+use std::path::{Path, PathBuf};++use crate::error::{Error, Result};+use crate::object::id::Id;+use crate::object::view::{+    encode_operation, encode_view, Operation, TimeMs, 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/veinsrs/src/store/writer.rs@@ -0,0 +1,93 @@+use std::collections::HashSet;+use std::path::Path;++use crate::object::id::{object_id, Id};+use crate::object::{RawObject, TYPE_CHUNK};+use crate::store::pack::{self, PackOutput};++#[derive(Default)]+pub struct Writer {+    objects: Vec<RawObject>,+    cache: Vec<RawObject>,+    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.push(RawObject::known(kind, id, body.clone()));+        }+        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.push(RawObject::known(kind, id, body.clone()));+        }+        self.objects.push(RawObject::known(kind, id, body));+        id+    }++    pub fn find_cached(&self, kind: u8, id: Id) -> Option<&[u8]> {+        self.cache+            .iter()+            .find(|object| object.kind == kind && object.id == id)+            .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, 3)+    }++    pub fn encode_finish(&self) -> PackOutput {+        pack::encode(&self.objects, 3)+    }+}--- /dev/null+++ b/veinsrs/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/veinsrs/src/worktree/attributes.rs@@ -0,0 +1,227 @@+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/veinsrs/src/worktree/checkout.rs@@ -0,0 +1,521 @@+use std::fs;+use std::os::unix::fs::PermissionsExt;+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::store::graph;+use crate::store::layout;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::Txn;+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 };+    fs::set_permissions(&path, fs::Permissions::from_mode(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)?;+    }+    std::os::unix::fs::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<()> {+    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()?;+    files.par_iter().try_for_each(|entry| write_entry(store, root, entry, &attributes))?;+    for conflict in &conflicts {+        materialize_conflict(store, root, &conflict.path, conflict.target, &attributes)?;+    }++    save_checkout_cache(root, &new_entries)?;+    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/veinsrs/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/veinsrs/src/worktree/pathspec.rs@@ -0,0 +1,74 @@+use std::os::unix::ffi::OsStrExt;+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(relative.as_os_str().as_bytes()).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/veinsrs/src/worktree/snapshot.rs@@ -0,0 +1,623 @@+use std::fs;+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, TreeEntry, KIND_CONFLICT, KIND_SUBTREE};+use crate::object::{TYPE_COMMIT, TYPE_TREE};+use crate::store::graph;+use crate::store::ops;+use crate::store::reader::Store;+use crate::store::writer::Writer;+use crate::store::Txn;+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) = old_index+            && old_tree.as_ref().unwrap().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(old_tree.as_ref().unwrap().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) = old_index {+                let entry = &old_tree.as_ref().unwrap().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,+                    &fs::symlink_metadata(&plan.path)?,+                    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();++    let built: Vec<Option<blob::BlobBuild>> = if job_bytes >= 1_000_000 {+        jobs.par_iter()+            .map(|index| read_build(&plans[*index].path, &plans[*index].rel, attributes))+            .collect()+    } else {+        jobs.iter()+            .map(|index| read_build(&plans[*index].path, &plans[*index].rel, attributes))+            .collect()+    };++    for (job, build) in jobs.iter().zip(built) {+        let Some(build) = 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);+    }++    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(path: &Path, relative: &[u8], attributes: &AttributeRules) -> Option<blob::BlobBuild> {+    let data = core::read_file_opt(path, 0)?;+    let path_attributes = attributes.lookup(&String::from_utf8_lossy(relative));+    if path_attributes.eol != AttributeEol::None+        && path_attributes.text != AttributeText::Binary+    {+        Some(blob::build(&attributes::normalize_eol(+            &data,+            path_attributes.eol,+        )))+    } else {+        Some(blob::build(&data))+    }+}++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/veinsrs/src/worktree/stat_cache.rs@@ -0,0 +1,175 @@+use std::fs;+use std::os::unix::fs::MetadataExt;+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");+    crate::core::write_atomic_name(&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,+    metadata: &fs::Metadata,+    executable: bool,+    now_ms: i64,+    written_ms: i64,+) -> bool {+    let kind = file_kind(metadata);+    let mtime_ns = mtime_ns(metadata);+    if entry.size != metadata.size()+        || entry.mtime_ns != mtime_ns+        || entry.inode != metadata.ino()+        || entry.executable != executable+        || entry.kind != 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 mtime_ns as i64 >= written_ns - WINDOW {+        return false;+    }+    if now_ns - (mtime_ns as i64) < WINDOW {+        return false;+    }+    true+}++pub fn mtime_ns(metadata: &fs::Metadata) -> u64 {+    let seconds = metadata.mtime();+    let nanoseconds = metadata.mtime_nsec();+    (seconds as u64)+        .wrapping_mul(1_000_000_000)+        .wrapping_add(nanoseconds as u64)+}++pub fn file_kind(metadata: &fs::Metadata) -> u8 {+    let file_type = metadata.file_type();+    if file_type.is_symlink() {+        3+    } else if file_type.is_dir() {+        2+    } else {+        1+    }+}++pub fn executable(metadata: &fs::Metadata) -> bool {+    metadata.mode() & 0o111 != 0+}--- /dev/null+++ b/veinsrs/tests/end_to_end.rs@@ -0,0 +1,85 @@+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/veinsrs/tests/format_vectors.rs@@ -0,0 +1,150 @@+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::{hash_bytes, object_id, 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();+}