navid/veins / commit

0445f6384ea0

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

parents: 8a0ec290e94f

Browse files at this commit · Download source

xveins: reformat solution
--- /dev/null+++ b/xveins/.clang-format@@ -0,0 +1,20 @@+BasedOnStyle: LLVM+IndentWidth: 4+ContinuationIndentWidth: 4+TabWidth: 4+UseTab: Never+BreakBeforeBraces: Attach+AllowShortBlocksOnASingleLine: Never+AllowShortCaseLabelsOnASingleLine: false+AllowShortIfStatementsOnASingleLine: Never+AllowShortLoopsOnASingleLine: false+AllowShortFunctionsOnASingleLine: Empty+DerivePointerAlignment: false+PointerAlignment: Left+SpaceBeforeParens: ControlStatements+SpacesInParentheses: false+ColumnLimit: 100+Standard: Latest+NamespaceIndentation: None+AccessModifierOffset: -4+SortIncludes: CaseSensitive--- a/xveins/src/auth.cpp+++ b/xveins/src/auth.cpp@@ -17,176 +17,171 @@  namespace { -std::optional<std::string> env_value(const char *name) {-  const char *value = std::getenv(name);-  if (!value || !*value)-    return std::nullopt;-  return std::string(value);+std::optional<std::string> env_value(const char* name) {+    const char* value = std::getenv(name);+    if (!value || !*value)+        return std::nullopt;+    return std::string(value); }  std::string lower_ascii(std::string_view text) {-  std::string out(text);-  for (char &c : out) {-    if (c >= 'A' && c <= 'Z')-      c = static_cast<char>(c + 32);-  }-  return out;+    std::string out(text);+    for (char& c : out) {+        if (c >= 'A' && c <= 'Z')+            c = static_cast<char>(c + 32);+    }+    return out; }  std::string_view trim_view(std::string_view text) {-  std::size_t start = 0;-  std::size_t end = text.size();-  auto blank = [](char c) {-    return c == ' ' || c == '\t' || c == '\r' || c == '\n';-  };-  while (start < end && blank(text[start]))-    ++start;-  while (end > start && blank(text[end - 1]))-    --end;-  return text.substr(start, end - start);+    std::size_t start = 0;+    std::size_t end = text.size();+    auto blank = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };+    while (start < end && blank(text[start]))+        ++start;+    while (end > start && blank(text[end - 1]))+        --end;+    return text.substr(start, end - start); } -int file_mode(const fs::path &path) {+int file_mode(const fs::path& path) { #if defined(_WIN32)-  (void)path;-  return 0600;+    (void)path;+    return 0600; #else-  struct stat info {};-  if (::stat(path.c_str(), &info) != 0)-    return -1;-  return static_cast<int>(info.st_mode & 07777);+    struct stat info {};+    if (::stat(path.c_str(), &info) != 0)+        return -1;+    return static_cast<int>(info.st_mode & 07777); #endif } -bool set_mode(const fs::path &path, int mode) {+bool set_mode(const fs::path& path, int mode) { #if defined(_WIN32)-  (void)path;-  (void)mode;-  return true;+    (void)path;+    (void)mode;+    return true; #else-  return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0;+    return ::chmod(path.c_str(), static_cast<mode_t>(mode)) == 0; #endif }  bool valid_key_name(std::string_view name) {-  if (name.empty() || name.size() > 128)-    return false;-  for (char c : name) {-    if (c == '/' || c == '\\' || c == '\0')-      return false;-  }-  return true;+    if (name.empty() || name.size() > 128)+        return false;+    for (char c : name) {+        if (c == '/' || c == '\\' || c == '\0')+            return false;+    }+    return true; }  std::string hex_encode(std::string_view data) {-  static constexpr char digits[] = "0123456789abcdef";-  std::string out;-  out.reserve(data.size() * 2);-  for (char raw : data) {-    const auto c = static_cast<unsigned char>(raw);-    out.push_back(digits[c >> 4]);-    out.push_back(digits[c & 15]);-  }-  return out;+    static constexpr char digits[] = "0123456789abcdef";+    std::string out;+    out.reserve(data.size() * 2);+    for (char raw : data) {+        const auto c = static_cast<unsigned char>(raw);+        out.push_back(digits[c >> 4]);+        out.push_back(digits[c & 15]);+    }+    return out; }  std::optional<std::string> hex_decode(std::string_view text) {-  if (text.empty() || text.size() % 2 != 0)-    return std::nullopt;-  auto value = [](char c) -> int {-    if (c >= '0' && c <= '9')-      return c - '0';-    if (c >= 'a' && c <= 'f')-      return c - 'a' + 10;-    return -1;-  };-  std::string out;-  out.reserve(text.size() / 2);-  for (std::size_t i = 0; i < text.size(); i += 2) {-    const int high = value(text[i]);-    const int low = value(text[i + 1]);-    if (high < 0 || low < 0)-      return std::nullopt;-    out.push_back(static_cast<char>((high << 4) | low));-  }-  return out;+    if (text.empty() || text.size() % 2 != 0)+        return std::nullopt;+    auto value = [](char c) -> int {+        if (c >= '0' && c <= '9')+            return c - '0';+        if (c >= 'a' && c <= 'f')+            return c - 'a' + 10;+        return -1;+    };+    std::string out;+    out.reserve(text.size() / 2);+    for (std::size_t i = 0; i < text.size(); i += 2) {+        const int high = value(text[i]);+        const int low = value(text[i + 1]);+        if (high < 0 || low < 0)+            return std::nullopt;+        out.push_back(static_cast<char>((high << 4) | low));+    }+    return out; }  std::string_view strip_user(std::string_view authority) {-  const auto at = authority.rfind('@');-  if (at != std::string_view::npos)-    return authority.substr(at + 1);-  return authority;+    const auto at = authority.rfind('@');+    if (at != std::string_view::npos)+        return authority.substr(at + 1);+    return authority; }  std::optional<std::string> authority_of(std::string_view input) {-  std::size_t start = 0;-  const auto scheme = input.find("://");-  if (scheme != std::string_view::npos)-    start = scheme + 3;-  if (start >= input.size())-    return std::nullopt;-  const auto slash = input.find('/', start);-  const std::size_t end =-      slash == std::string_view::npos ? input.size() : slash;-  if (end <= start)-    return std::nullopt;-  const std::string_view raw = input.substr(start, end - start);-  const std::string_view host = strip_user(raw);-  if (host.empty())-    return std::nullopt;-  return lower_ascii(host);+    std::size_t start = 0;+    const auto scheme = input.find("://");+    if (scheme != std::string_view::npos)+        start = scheme + 3;+    if (start >= input.size())+        return std::nullopt;+    const auto slash = input.find('/', start);+    const std::size_t end = slash == std::string_view::npos ? input.size() : slash;+    if (end <= start)+        return std::nullopt;+    const std::string_view raw = input.substr(start, end - start);+    const std::string_view host = strip_user(raw);+    if (host.empty())+        return std::nullopt;+    return lower_ascii(host); }  std::optional<std::string> host_without_port(std::string_view host) {-  if (host.empty() || host.front() == '[')-    return std::nullopt;-  const auto colon = host.rfind(':');-  if (colon == std::string_view::npos || colon == 0)-    return std::nullopt;-  return std::string(host.substr(0, colon));+    if (host.empty() || host.front() == '[')+        return std::nullopt;+    const auto colon = host.rfind(':');+    if (colon == std::string_view::npos || colon == 0)+        return std::nullopt;+    return std::string(host.substr(0, colon)); } -fs::path target_path(const fs::path &dir, std::string_view target) {-  return dir / hex_encode(target);+fs::path target_path(const fs::path& dir, std::string_view target) {+    return dir / hex_encode(target); } -std::optional<std::string> read_credential(const fs::path &path) {-  auto data = read_file_opt(path);-  if (!data)-    return std::nullopt;-  const std::string_view text(reinterpret_cast<const char *>(data->data()),-                              data->size());-  const std::string_view value = trim_view(text);-  if (value.empty())-    return std::nullopt;-  return std::string(value);+std::optional<std::string> read_credential(const fs::path& path) {+    auto data = read_file_opt(path);+    if (!data)+        return std::nullopt;+    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    const std::string_view value = trim_view(text);+    if (value.empty())+        return std::nullopt;+    return std::string(value); } -std::optional<std::string> lookup_credential(const fs::path &dir,-                                             std::string_view target) {-  return read_credential(target_path(dir, target));+std::optional<std::string> lookup_credential(const fs::path& dir, std::string_view target) {+    return read_credential(target_path(dir, target)); }  std::vector<std::string_view> tokenize(std::string_view line) {-  std::vector<std::string_view> out;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= line.size(); ++i) {-    const bool at_end = i == line.size();-    if (at_end || line[i] == ' ' || line[i] == '\t') {-      if (i > start)-        out.push_back(line.substr(start, i - start));-      start = i + 1;+    std::vector<std::string_view> out;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= line.size(); ++i) {+        const bool at_end = i == line.size();+        if (at_end || line[i] == ' ' || line[i] == '\t') {+            if (i > start)+                out.push_back(line.substr(start, i - start));+            start = i + 1;+        }     }-  }-  return out;+    return out; }  Access invalid_access(std::int64_t line) {-  Access out;-  out.valid = false;-  out.error_line = line;-  return out;+    Access out;+    out.valid = false;+    out.error_line = line;+    return out; }  } // namespace@@ -196,82 +191,82 @@ // ---------------------------------------------------------------------------  fs::path key_dir() {-  if (auto xdg = env_value("XDG_CONFIG_HOME"))-    return path_from_bytes(*xdg) / "veins" / "keys";-  if (auto home = env_value("HOME"))-    return path_from_bytes(*home) / ".config" / "veins" / "keys";+    if (auto xdg = env_value("XDG_CONFIG_HOME"))+        return path_from_bytes(*xdg) / "veins" / "keys";+    if (auto home = env_value("HOME"))+        return path_from_bytes(*home) / ".config" / "veins" / "keys"; #if defined(_WIN32)-  if (auto appdata = env_value("APPDATA"))-    return path_from_bytes(*appdata) / "veins" / "keys";+    if (auto appdata = env_value("APPDATA"))+        return path_from_bytes(*appdata) / "veins" / "keys"; #endif-  return fs::path(".veins-keys");+    return fs::path(".veins-keys"); }  fs::path key_path(std::string_view name) {-  return key_dir() / (std::string(name) + ".key");+    return key_dir() / (std::string(name) + ".key"); }  std::optional<Key> load_key(std::string_view name) {-  if (!valid_key_name(name))-    return std::nullopt;-  const fs::path path = key_path(name);-  const int mode = file_mode(path);-  if (mode < 0 || (mode & 63) != 0)-    return std::nullopt;-  auto data = read_file_opt(path);-  if (!data || data->size() != 33 || (*data)[0] != 1)-    return std::nullopt;-  std::vector<std::uint8_t> seed(data->begin() + 1, data->end());-  auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));-  if (!public_key)-    return std::nullopt;-  Key key;-  key.name = std::string(name);-  key.seed = std::move(seed);-  key.public_key = *public_key;-  key.fingerprint = key_fingerprint(*public_key);-  return key;+    if (!valid_key_name(name))+        return std::nullopt;+    const fs::path path = key_path(name);+    const int mode = file_mode(path);+    if (mode < 0 || (mode & 63) != 0)+        return std::nullopt;+    auto data = read_file_opt(path);+    if (!data || data->size() != 33 || (*data)[0] != 1)+        return std::nullopt;+    std::vector<std::uint8_t> seed(data->begin() + 1, data->end());+    auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));+    if (!public_key)+        return std::nullopt;+    Key key;+    key.name = std::string(name);+    key.seed = std::move(seed);+    key.public_key = *public_key;+    key.fingerprint = key_fingerprint(*public_key);+    return key; }  std::optional<Key> generate_key(std::string_view name) {-  if (!valid_key_name(name))-    return std::nullopt;-  const fs::path dir = key_dir();-  if (!ensure_directory(dir))-    return std::nullopt;-  (void)set_mode(dir, 0700);-  const auto seed = secure_random(32);-  if (seed.size() != 32)-    return std::nullopt;-  auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));-  if (!public_key)-    return std::nullopt;-  std::vector<std::uint8_t> body;-  body.reserve(33);-  body.push_back(1);-  body.insert(body.end(), seed.begin(), seed.end());-  const fs::path path = key_path(name);-  if (!write_file(path, Bytes(body.data(), body.size())))-    return std::nullopt;-  (void)set_mode(path, 0600);-  Key key;-  key.name = std::string(name);-  key.seed = seed;-  key.public_key = *public_key;-  key.fingerprint = key_fingerprint(*public_key);-  return key;+    if (!valid_key_name(name))+        return std::nullopt;+    const fs::path dir = key_dir();+    if (!ensure_directory(dir))+        return std::nullopt;+    (void)set_mode(dir, 0700);+    const auto seed = secure_random(32);+    if (seed.size() != 32)+        return std::nullopt;+    auto public_key = ed25519_public_from_seed(Bytes(seed.data(), seed.size()));+    if (!public_key)+        return std::nullopt;+    std::vector<std::uint8_t> body;+    body.reserve(33);+    body.push_back(1);+    body.insert(body.end(), seed.begin(), seed.end());+    const fs::path path = key_path(name);+    if (!write_file(path, Bytes(body.data(), body.size())))+        return std::nullopt;+    (void)set_mode(path, 0600);+    Key key;+    key.name = std::string(name);+    key.seed = seed;+    key.public_key = *public_key;+    key.fingerprint = key_fingerprint(*public_key);+    return key; }  std::vector<std::string> list_key_names() {-  std::vector<std::string> out;-  const fs::path dir = key_dir();-  if (!path_is_dir(dir))+    std::vector<std::string> out;+    const fs::path dir = key_dir();+    if (!path_is_dir(dir))+        return out;+    for (const auto& name : list_directory(dir)) {+        if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)+            out.push_back(name.substr(0, name.size() - 4));+    }     return out;-  for (const auto &name : list_directory(dir)) {-    if (name.size() > 4 && name.compare(name.size() - 4, 4, ".key") == 0)-      out.push_back(name.substr(0, name.size() - 4));-  }-  return out; }  // ---------------------------------------------------------------------------@@ -279,75 +274,75 @@ // ---------------------------------------------------------------------------  fs::path auth_dir() {-  const fs::path dir = key_dir();-  const fs::path parent = dir.parent_path();-  if (parent.empty())-    return fs::path(".veins-auth");-  return parent / "auth";+    const fs::path dir = key_dir();+    const fs::path parent = dir.parent_path();+    if (parent.empty())+        return fs::path(".veins-auth");+    return parent / "auth"; }  std::string normalize_target(std::string_view input) {-  const std::string_view trimmed = trim_view(input);-  if (trimmed.empty() || trimmed == "default")-    return "default";-  if (auto authority = authority_of(trimmed))-    return *authority;-  const auto slash = trimmed.find('/');-  const std::string_view raw =-      slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);-  const std::string_view host = strip_user(raw);-  if (host.empty())-    return "default";-  return lower_ascii(host);+    const std::string_view trimmed = trim_view(input);+    if (trimmed.empty() || trimmed == "default")+        return "default";+    if (auto authority = authority_of(trimmed))+        return *authority;+    const auto slash = trimmed.find('/');+    const std::string_view raw =+        slash == std::string_view::npos ? trimmed : trimmed.substr(0, slash);+    const std::string_view host = strip_user(raw);+    if (host.empty())+        return "default";+    return lower_ascii(host); }  bool set_key(std::string_view target, std::string_view key_name) {-  if (target.empty() || key_name.empty())-    return false;-  const fs::path dir = auth_dir();-  if (!ensure_directory(dir))-    return false;-  return write_file(target_path(dir, target), bytes_of(key_name));+    if (target.empty() || key_name.empty())+        return false;+    const fs::path dir = auth_dir();+    if (!ensure_directory(dir))+        return false;+    return write_file(target_path(dir, target), bytes_of(key_name)); }  bool remove_key(std::string_view target) {-  return remove_file(target_path(auth_dir(), target));+    return remove_file(target_path(auth_dir(), target)); }  std::vector<std::string> list_credential_lines() {-  std::vector<std::string> out;-  const fs::path dir = auth_dir();-  if (!path_is_dir(dir))+    std::vector<std::string> out;+    const fs::path dir = auth_dir();+    if (!path_is_dir(dir))+        return out;+    for (const auto& name : list_directory(dir)) {+        auto decoded = hex_decode(name);+        if (!decoded)+            continue;+        auto key = read_credential(target_path(dir, *decoded));+        if (!key)+            continue;+        out.push_back(*decoded + ": " + *key + "\n");+    }     return out;-  for (const auto &name : list_directory(dir)) {-    auto decoded = hex_decode(name);-    if (!decoded)-      continue;-    auto key = read_credential(target_path(dir, *decoded));-    if (!key)-      continue;-    out.push_back(*decoded + ": " + *key + "\n");-  }-  return out; }  bool local_key_exists(std::string_view name) {-  if (name.empty() || name.starts_with("ed25519:"))-    return false;-  return load_key(name).has_value();+    if (name.empty() || name.starts_with("ed25519:"))+        return false;+    return load_key(name).has_value(); }  std::optional<std::string> key_for_url(std::string_view url) {-  const fs::path dir = auth_dir();-  if (auto host = authority_of(url)) {-    if (auto exact = lookup_credential(dir, *host))-      return exact;-    if (auto base = host_without_port(*host)) {-      if (auto without_port = lookup_credential(dir, *base))-        return without_port;+    const fs::path dir = auth_dir();+    if (auto host = authority_of(url)) {+        if (auto exact = lookup_credential(dir, *host))+            return exact;+        if (auto base = host_without_port(*host)) {+            if (auto without_port = lookup_credential(dir, *base))+                return without_port;+        }     }-  }-  return lookup_credential(dir, "default");+    return lookup_credential(dir, "default"); }  // ---------------------------------------------------------------------------@@ -354,170 +349,166 @@ // Server access policy // --------------------------------------------------------------------------- -Access empty_access() { return Access{}; }+Access empty_access() {+    return Access{};+} -fs::path access_path(const fs::path &repo_root) {-  return veins_dir(repo_root) / "access";+fs::path access_path(const fs::path& repo_root) {+    return veins_dir(repo_root) / "access"; } -Access load_access(const fs::path &repo_root) {-  const fs::path path = access_path(repo_root);-  const int mode = file_mode(path);-  if (mode >= 0 && (mode & 18) != 0)-    return invalid_access(0);-  auto data = read_file_opt(path);-  if (!data)-    return empty_access();-  const std::string_view text(reinterpret_cast<const char *>(data->data()),-                              data->size());-  Access access;-  std::size_t start = 0;-  std::int64_t line_no = 0;-  std::size_t i = 0;-  for (;;) {-    const bool at_end = i >= text.size();-    if (at_end || text[i] == '\n') {-      ++line_no;-      const std::string_view line = trim_view(text.substr(start, i - start));-      if (!line.empty() && line.front() != '#') {-        const auto tokens = tokenize(line);-        bool bad = false;-        if (tokens.size() == 2 && tokens[0] == "anonymous") {-          if (tokens[1] == "read")-            access.anonymous_read = true;-          else-            bad = true;-        } else if (tokens.size() >= 3 && tokens[0] == "allow") {-          std::uint8_t role = 0;-          if (tokens[1] == "read")-            role = ROLE_READ;-          else if (tokens[1] == "write")-            role = ROLE_WRITE;-          else-            bad = true;-          auto public_key = parse_public_key(tokens[2]);-          if (!public_key)-            bad = true;-          if (!bad) {-            const bool duplicate =-                std::any_of(access.entries.begin(), access.entries.end(),-                            [&](const AccessEntry &entry) {-                              return std::memcmp(entry.public_key.data(),-                                                 public_key->data(),-                                                 public_key->size()) == 0;+Access load_access(const fs::path& repo_root) {+    const fs::path path = access_path(repo_root);+    const int mode = file_mode(path);+    if (mode >= 0 && (mode & 18) != 0)+        return invalid_access(0);+    auto data = read_file_opt(path);+    if (!data)+        return empty_access();+    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    Access access;+    std::size_t start = 0;+    std::int64_t line_no = 0;+    std::size_t i = 0;+    for (;;) {+        const bool at_end = i >= text.size();+        if (at_end || text[i] == '\n') {+            ++line_no;+            const std::string_view line = trim_view(text.substr(start, i - start));+            if (!line.empty() && line.front() != '#') {+                const auto tokens = tokenize(line);+                bool bad = false;+                if (tokens.size() == 2 && tokens[0] == "anonymous") {+                    if (tokens[1] == "read")+                        access.anonymous_read = true;+                    else+                        bad = true;+                } else if (tokens.size() >= 3 && tokens[0] == "allow") {+                    std::uint8_t role = 0;+                    if (tokens[1] == "read")+                        role = ROLE_READ;+                    else if (tokens[1] == "write")+                        role = ROLE_WRITE;+                    else+                        bad = true;+                    auto public_key = parse_public_key(tokens[2]);+                    if (!public_key)+                        bad = true;+                    if (!bad) {+                        const bool duplicate = std::any_of(+                            access.entries.begin(), access.entries.end(),+                            [&](const AccessEntry& entry) {+                                return std::memcmp(entry.public_key.data(), public_key->data(),+                                                   public_key->size()) == 0;                             });-            if (duplicate) {-              bad = true;-            } else {-              AccessEntry entry;-              entry.public_key = *public_key;-              entry.role = role;-              if (tokens.size() >= 4)-                entry.name = std::string(tokens[3]);-              access.entries.push_back(std::move(entry));+                        if (duplicate) {+                            bad = true;+                        } else {+                            AccessEntry entry;+                            entry.public_key = *public_key;+                            entry.role = role;+                            if (tokens.size() >= 4)+                                entry.name = std::string(tokens[3]);+                            access.entries.push_back(std::move(entry));+                        }+                    }+                } else {+                    bad = true;+                }+                if (bad)+                    return invalid_access(line_no);             }-          }-        } else {-          bad = true;+            start = i + 1;         }-        if (bad)-          return invalid_access(line_no);-      }-      start = i + 1;+        if (at_end)+            break;+        ++i;     }-    if (at_end)-      break;-    ++i;-  }-  return access;+    return access; } -bool write_access(const fs::path &repo_root, const Access &access) {-  std::string body = "# veins access policy\n";-  if (access.anonymous_read)-    body += "anonymous read\n";-  for (const auto &entry : access.entries) {-    if (entry.name.size() > 64)-      return false;-    body += "allow ";-    body += entry.role == ROLE_WRITE ? "write" : "read";-    body += " ";-    body += format_public_key(entry.public_key);-    if (!entry.name.empty()) {-      body += " ";-      body += entry.name;+bool write_access(const fs::path& repo_root, const Access& access) {+    std::string body = "# veins access policy\n";+    if (access.anonymous_read)+        body += "anonymous read\n";+    for (const auto& entry : access.entries) {+        if (entry.name.size() > 64)+            return false;+        body += "allow ";+        body += entry.role == ROLE_WRITE ? "write" : "read";+        body += " ";+        body += format_public_key(entry.public_key);+        if (!entry.name.empty()) {+            body += " ";+            body += entry.name;+        }+        body += "\n";     }-    body += "\n";-  }-  const fs::path path = access_path(repo_root);-  if (!write_file(path, bytes_of(body)))-    return false;-  (void)set_mode(path, 0600);-  return true;+    const fs::path path = access_path(repo_root);+    if (!write_file(path, bytes_of(body)))+        return false;+    (void)set_mode(path, 0600);+    return true; } -std::uint8_t role_for(const Access &access, const PublicKey *public_key) {-  if (!public_key) {-    if (access.anonymous_read)-      return ROLE_READ;-    return ROLE_ANONYMOUS;-  }-  for (const auto &entry : access.entries) {-    if (std::memcmp(entry.public_key.data(), public_key->data(),-                    public_key->size()) == 0) {-      return entry.role;+std::uint8_t role_for(const Access& access, const PublicKey* public_key) {+    if (!public_key) {+        if (access.anonymous_read)+            return ROLE_READ;+        return ROLE_ANONYMOUS;     }-  }-  return ROLE_UNKNOWN;+    for (const auto& entry : access.entries) {+        if (std::memcmp(entry.public_key.data(), public_key->data(), public_key->size()) == 0) {+            return entry.role;+        }+    }+    return ROLE_UNKNOWN; } -bool add_access(const fs::path &repo_root, std::uint8_t role,-                const PublicKey &public_key, std::string_view name) {-  Access access = load_access(repo_root);-  if (!access.valid)-    return false;-  for (const auto &entry : access.entries) {-    if (std::memcmp(entry.public_key.data(), public_key.data(),-                    public_key.size()) == 0)-      return false;-  }-  AccessEntry entry;-  entry.public_key = public_key;-  entry.role = role;-  entry.name = std::string(name);-  access.entries.push_back(std::move(entry));-  return write_access(repo_root, access);+bool add_access(const fs::path& repo_root, std::uint8_t role, const PublicKey& public_key,+                std::string_view name) {+    Access access = load_access(repo_root);+    if (!access.valid)+        return false;+    for (const auto& entry : access.entries) {+        if (std::memcmp(entry.public_key.data(), public_key.data(), public_key.size()) == 0)+            return false;+    }+    AccessEntry entry;+    entry.public_key = public_key;+    entry.role = role;+    entry.name = std::string(name);+    access.entries.push_back(std::move(entry));+    return write_access(repo_root, access); } -bool remove_access(const fs::path &repo_root, std::string_view fingerprint,-                   std::string_view name) {-  Access access = load_access(repo_root);-  if (!access.valid)-    return false;-  bool removed = false;-  std::vector<AccessEntry> kept;-  kept.reserve(access.entries.size());-  for (const auto &entry : access.entries) {-    const bool match_fingerprint =-        !fingerprint.empty() &&-        key_fingerprint(entry.public_key) == fingerprint;-    const bool match_name = !name.empty() && entry.name == name;-    if (match_fingerprint || match_name) {-      removed = true;-    } else {-      kept.push_back(entry);+bool remove_access(const fs::path& repo_root, std::string_view fingerprint, std::string_view name) {+    Access access = load_access(repo_root);+    if (!access.valid)+        return false;+    bool removed = false;+    std::vector<AccessEntry> kept;+    kept.reserve(access.entries.size());+    for (const auto& entry : access.entries) {+        const bool match_fingerprint =+            !fingerprint.empty() && key_fingerprint(entry.public_key) == fingerprint;+        const bool match_name = !name.empty() && entry.name == name;+        if (match_fingerprint || match_name) {+            removed = true;+        } else {+            kept.push_back(entry);+        }     }-  }-  access.entries = std::move(kept);-  return removed && write_access(repo_root, access);+    access.entries = std::move(kept);+    return removed && write_access(repo_root, access); } -bool set_anonymous(const fs::path &repo_root, bool enabled) {-  Access access = load_access(repo_root);-  if (!access.valid)-    return false;-  access.anonymous_read = enabled;-  return write_access(repo_root, access);+bool set_anonymous(const fs::path& repo_root, bool enabled) {+    Access access = load_access(repo_root);+    if (!access.valid)+        return false;+    access.anonymous_read = enabled;+    return write_access(repo_root, access); }  } // namespace vn::auth--- a/xveins/src/auth.h+++ b/xveins/src/auth.h@@ -20,10 +20,10 @@ // ---------------------------------------------------------------------------  struct Key {-  std::string name;-  std::vector<std::uint8_t> seed;-  PublicKey public_key{};-  std::string fingerprint;+    std::string name;+    std::vector<std::uint8_t> seed;+    PublicKey public_key{};+    std::string fingerprint; };  fs::path key_dir();@@ -49,27 +49,26 @@ // ---------------------------------------------------------------------------  struct AccessEntry {-  PublicKey public_key{};-  std::string name;-  std::uint8_t role = ROLE_READ;+    PublicKey public_key{};+    std::string name;+    std::uint8_t role = ROLE_READ; };  struct Access {-  bool valid = true;-  std::int64_t error_line = 0;-  bool anonymous_read = false;-  std::vector<AccessEntry> entries;+    bool valid = true;+    std::int64_t error_line = 0;+    bool anonymous_read = false;+    std::vector<AccessEntry> entries; };  Access empty_access();-fs::path access_path(const fs::path &repo_root);-Access load_access(const fs::path &repo_root);-bool write_access(const fs::path &repo_root, const Access &access);-bool add_access(const fs::path &repo_root, std::uint8_t role,-                const PublicKey &public_key, std::string_view name);-bool remove_access(const fs::path &repo_root, std::string_view fingerprint,-                   std::string_view name);-bool set_anonymous(const fs::path &repo_root, bool enabled);-std::uint8_t role_for(const Access &access, const PublicKey *public_key);+fs::path access_path(const fs::path& repo_root);+Access load_access(const fs::path& repo_root);+bool write_access(const fs::path& repo_root, const Access& access);+bool add_access(const fs::path& repo_root, std::uint8_t role, const PublicKey& public_key,+                std::string_view name);+bool remove_access(const fs::path& repo_root, std::string_view fingerprint, std::string_view name);+bool set_anonymous(const fs::path& repo_root, bool enabled);+std::uint8_t role_for(const Access& access, const PublicKey* public_key);  } // namespace vn::auth--- a/xveins/src/bookmark.cpp+++ b/xveins/src/bookmark.cpp@@ -12,349 +12,343 @@ namespace {  bool bmk_is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';+    return !arg.empty() && arg.front() == '-'; }  bool bmk_contains(std::string_view name, std::string_view needle) {-  return !needle.empty() && name.find(needle) != std::string_view::npos;+    return !needle.empty() && name.find(needle) != std::string_view::npos; }  bool valid_bookmark_name(std::string_view name) {-  if (name.empty() || name.size() > MAX_NAME_LEN)-    return false;-  const auto first = static_cast<unsigned char>(name.front());-  if (first == '-' || first == '/' || first == '.')-    return false;-  const auto last = static_cast<unsigned char>(name.back());-  if (last == '/' || last == '.')-    return false;-  for (char raw : name) {-    const auto c = static_cast<unsigned char>(raw);-    if (c == 0 || c == ' ' || c < 32 || c == 127)-      return false;-    if (c == '~' || c == '^' || c == ':' || c == '?' || c == '*' || c == '[' ||-        c == '\\')-      return false;-  }-  if (bmk_contains(name, "..") || bmk_contains(name, "@{") ||-      bmk_contains(name, "//"))-    return false;-  if (name == "@")-    return false;-  if (name.size() >= 5 && name.substr(name.size() - 5) == ".lock")-    return false;-  return true;+    if (name.empty() || name.size() > MAX_NAME_LEN)+        return false;+    const auto first = static_cast<unsigned char>(name.front());+    if (first == '-' || first == '/' || first == '.')+        return false;+    const auto last = static_cast<unsigned char>(name.back());+    if (last == '/' || last == '.')+        return false;+    for (char raw : name) {+        const auto c = static_cast<unsigned char>(raw);+        if (c == 0 || c == ' ' || c < 32 || c == 127)+            return false;+        if (c == '~' || c == '^' || c == ':' || c == '?' || c == '*' || c == '[' || c == '\\')+            return false;+    }+    if (bmk_contains(name, "..") || bmk_contains(name, "@{") || bmk_contains(name, "//"))+        return false;+    if (name == "@")+        return false;+    if (name.size() >= 5 && name.substr(name.size() - 5) == ".lock")+        return false;+    return true; } -std::string short_commit(const Id &id, std::size_t n = 12) {-  if (n == 0)-    n = 12;-  n = std::min<std::size_t>(n, 64);-  return hex_encode(id).substr(0, n);+std::string short_commit(const Id& id, std::size_t n = 12) {+    if (n == 0)+        n = 12;+    n = std::min<std::size_t>(n, 64);+    return hex_encode(id).substr(0, n); }  void bmk_print_cell(std::string_view text, std::size_t width) {-  std::cout << text;-  for (std::size_t i = text.size(); i < width; ++i)-    std::cout << ' ';+    std::cout << text;+    for (std::size_t i = text.size(); i < width; ++i)+        std::cout << ' '; } -bool bookmark_points_at(const Bookmark &bookmark, const Id &target) {-  return bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front() &&-         std::memcmp(bookmark.targets.adds.front()->data(), target.data(),-                     ID_LEN) == 0;+bool bookmark_points_at(const Bookmark& bookmark, const Id& target) {+    return bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front() &&+           std::memcmp(bookmark.targets.adds.front()->data(), target.data(), ID_LEN) == 0; } -int bmk_set(const std::vector<std::string> &args, std::size_t start) {-  std::string name;-  std::string rev;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {+int bmk_set(const std::vector<std::string>& args, std::size_t start) {+    std::string name;+    std::string rev;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            rev = args[++i];+        } else if (!end_flags && bmk_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (name.empty()) {+            name = arg;+        } else if (rev.empty()) {+            rev = arg;+        } else {+            error_prefix();+            std::cout << "bmk set accepts a name and one revision\n";+            return 1;+        }+    }+    if (name.empty()) {         error_prefix();-        std::cout << arg << " requires a revision\n";+        std::cout << "bmk set requires a name\n";         return 1;-      }-      rev = args[++i];-    } else if (!end_flags && bmk_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (name.empty()) {-      name = arg;-    } else if (rev.empty()) {-      rev = arg;-    } else {-      error_prefix();-      std::cout << "bmk set accepts a name and one revision\n";-      return 1;     }-  }-  if (name.empty()) {-    error_prefix();-    std::cout << "bmk set requires a name\n";-    return 1;-  }-  if (!valid_bookmark_name(name)) {-    error_prefix();-    std::cout << "invalid bookmark name: " << name << "\n";-    return 1;-  }+    if (!valid_bookmark_name(name)) {+        error_prefix();+        std::cout << "invalid bookmark name: " << name << "\n";+        return 1;+    } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap; -  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  auto target = resolve_revision(store, tx->view(), rev);-  if (!target) {-    error_prefix();-    if (rev.empty())-      std::cout << "no working-copy commit\n";-    else-      std::cout << "unknown revision: " << rev << "\n";-    return 1;-  }+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    auto target = resolve_revision(store, tx->view(), rev);+    if (!target) {+        error_prefix();+        if (rev.empty())+            std::cout << "no working-copy commit\n";+        else+            std::cout << "unknown revision: " << rev << "\n";+        return 1;+    } -  bool changed = true;-  if (const auto existing = find_bookmark(tx->view(), name)) {-    auto &bookmark = tx->view().bookmarks[*existing];-    if (bookmark_points_at(bookmark, *target)) {-      changed = false;+    bool changed = true;+    if (const auto existing = find_bookmark(tx->view(), name)) {+        auto& bookmark = tx->view().bookmarks[*existing];+        if (bookmark_points_at(bookmark, *target)) {+            changed = false;+        } else {+            bookmark.targets.adds = {*target};+            bookmark.targets.removes.clear();+        }     } else {-      bookmark.targets.adds = {*target};-      bookmark.targets.removes.clear();+        Bookmark bookmark;+        bookmark.name = name;+        bookmark.targets.adds = {*target};+        tx->view().bookmarks.push_back(std::move(bookmark));     }-  } else {-    Bookmark bookmark;-    bookmark.name = name;-    bookmark.targets.adds = {*target};-    tx->view().bookmarks.push_back(std::move(bookmark));-  } -  if (!changed) {+    if (!changed) {+        (void)set_current_bookmark(*root, name);+        info_prefix();+        std::cout << "bookmark " << name << " is already at " << short_commit(*target) << "\n";+        return 0;+    }++    rebuild_heads(tx->view());+    const auto status = tx->finish("bookmark set " + name);+    if (!status)+        return 1;     (void)set_current_bookmark(*root, name);     info_prefix();-    std::cout << "bookmark " << name << " is already at "-              << short_commit(*target) << "\n";+    std::cout << "bookmark " << name << " set to " << short_commit(*target) << "\n";     return 0;-  }--  rebuild_heads(tx->view());-  const auto status = tx->finish("bookmark set " + name);-  if (!status)-    return 1;-  (void)set_current_bookmark(*root, name);-  info_prefix();-  std::cout << "bookmark " << name << " set to " << short_commit(*target)-            << "\n";-  return 0; } -int bmk_delete(const std::vector<std::string> &args, std::size_t start) {-  std::string name;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && bmk_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (!name.empty()) {-      error_prefix();-      std::cout << "bmk rm accepts exactly one name\n";-      return 1;-    } else {-      name = arg;+int bmk_delete(const std::vector<std::string>& args, std::size_t start) {+    std::string name;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && bmk_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (!name.empty()) {+            error_prefix();+            std::cout << "bmk rm accepts exactly one name\n";+            return 1;+        } else {+            name = arg;+        }     }-  }-  if (name.empty()) {-    error_prefix();-    std::cout << "bmk rm requires a name\n";-    return 1;-  }+    if (name.empty()) {+        error_prefix();+        std::cout << "bmk rm requires a name\n";+        return 1;+    } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto existing = find_bookmark(tx->view(), name);-  if (!existing) {-    error_prefix();-    std::cout << "no such bookmark: " << name << "\n";-    return 1;-  }-  auto &bookmarks = tx->view().bookmarks;-  bookmarks.erase(bookmarks.begin() + static_cast<std::ptrdiff_t>(*existing));-  rebuild_heads(tx->view());-  const auto status = tx->finish("bookmark delete " + name);-  if (!status)-    return 1;-  if (auto current = current_bookmark_name(*root); current && *current == name)-    (void)clear_current_bookmark(*root);-  info_prefix();-  std::cout << "deleted bookmark " << name << "\n";-  return 0;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto existing = find_bookmark(tx->view(), name);+    if (!existing) {+        error_prefix();+        std::cout << "no such bookmark: " << name << "\n";+        return 1;+    }+    auto& bookmarks = tx->view().bookmarks;+    bookmarks.erase(bookmarks.begin() + static_cast<std::ptrdiff_t>(*existing));+    rebuild_heads(tx->view());+    const auto status = tx->finish("bookmark delete " + name);+    if (!status)+        return 1;+    if (auto current = current_bookmark_name(*root); current && *current == name)+        (void)clear_current_bookmark(*root);+    info_prefix();+    std::cout << "deleted bookmark " << name << "\n";+    return 0; } -int bmk_list(const std::vector<std::string> &args, std::size_t start) {-  bool col_titles = true;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && arg == "-no-col-titles") {-      col_titles = false;-    } else if (!end_flags && bmk_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      error_prefix();-      std::cout << "bmk ls takes no operands\n";-      return 1;+int bmk_list(const std::vector<std::string>& args, std::size_t start) {+    bool col_titles = true;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && arg == "-no-col-titles") {+            col_titles = false;+        } else if (!end_flags && bmk_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            error_prefix();+            std::cout << "bmk ls takes no operands\n";+            return 1;+        }     }-  }--  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  const auto wc = working_copy_id(*view); -  constexpr std::size_t w_commit = 12;-  constexpr std::size_t w_change = 8;-  std::size_t w_name = 8;-  for (const auto &bookmark : view->bookmarks)-    w_name = std::max(w_name, bookmark.name.size());+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    const auto wc = working_copy_id(*view); -  if (col_titles) {-    bmk_print_cell("Bookmark", w_name);-    std::cout << "  ";-    bmk_print_cell("Commit", w_commit);-    std::cout << "  ";-    bmk_print_cell("Change", w_change);-    std::cout << "  Target\n";-  }+    constexpr std::size_t w_commit = 12;+    constexpr std::size_t w_change = 8;+    std::size_t w_name = 8;+    for (const auto& bookmark : view->bookmarks)+        w_name = std::max(w_name, bookmark.name.size()); -  for (const auto &bookmark : view->bookmarks) {-    bmk_print_cell(bookmark.name, w_name);-    std::cout << "  ";-    bool have_target = false;-    bool current = false;-    const bool conflicted = bookmark.targets.adds.size() > 1;-    std::string commit_text;-    std::string change_text;-    std::optional<Id> target;-    if (!bookmark.targets.adds.empty() && bookmark.targets.adds.front()) {-      target = bookmark.targets.adds.front();-      have_target = true;-      if (wc && std::memcmp(wc->data(), target->data(), ID_LEN) == 0)-        current = true;-      commit_text = short_commit(*target);-      if (auto loaded = load_commit(store, *target))-        change_text = base32_encode(loaded->commit.change_id).substr(0, 8);-    }-    if (!have_target) {-      bmk_print_cell("<missing>", w_commit);-      std::cout << "  ";-      bmk_print_cell("", w_change);-      std::cout << "  (missing)\n";-      continue;+    if (col_titles) {+        bmk_print_cell("Bookmark", w_name);+        std::cout << "  ";+        bmk_print_cell("Commit", w_commit);+        std::cout << "  ";+        bmk_print_cell("Change", w_change);+        std::cout << "  Target\n";     }-    bmk_print_cell(commit_text, w_commit);-    std::cout << "  ";-    bmk_print_cell(change_text, w_change);-    std::cout << "  ";-    if (current)-      print_colored("@", Color::Red, false, false);-    if (conflicted) {-      if (current)-        std::cout << ' ';-      print_colored("(conflicted)", Color::BrightRed, false, false);++    for (const auto& bookmark : view->bookmarks) {+        bmk_print_cell(bookmark.name, w_name);+        std::cout << "  ";+        bool have_target = false;+        bool current = false;+        const bool conflicted = bookmark.targets.adds.size() > 1;+        std::string commit_text;+        std::string change_text;+        std::optional<Id> target;+        if (!bookmark.targets.adds.empty() && bookmark.targets.adds.front()) {+            target = bookmark.targets.adds.front();+            have_target = true;+            if (wc && std::memcmp(wc->data(), target->data(), ID_LEN) == 0)+                current = true;+            commit_text = short_commit(*target);+            if (auto loaded = load_commit(store, *target))+                change_text = base32_encode(loaded->commit.change_id).substr(0, 8);+        }+        if (!have_target) {+            bmk_print_cell("<missing>", w_commit);+            std::cout << "  ";+            bmk_print_cell("", w_change);+            std::cout << "  (missing)\n";+            continue;+        }+        bmk_print_cell(commit_text, w_commit);+        std::cout << "  ";+        bmk_print_cell(change_text, w_change);+        std::cout << "  ";+        if (current)+            print_colored("@", Color::Red, false, false);+        if (conflicted) {+            if (current)+                std::cout << ' ';+            print_colored("(conflicted)", Color::BrightRed, false, false);+        }+        std::cout << "\n";     }-    std::cout << "\n";-  } -  if (view->bookmarks.empty()) {-    info_prefix();-    std::cout << "no bookmarks\n";-  }-  return 0;+    if (view->bookmarks.empty()) {+        info_prefix();+        std::cout << "no bookmarks\n";+    }+    return 0; }  void bmk_usage() {-  std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n";-  std::cout << "\n";-  std::cout << "manage named, movable pointers to commits (branches)\n";-  std::cout << "\n";-  std::cout << "subcommands:\n";-  std::cout-      << "  set <name> [-rev <rev>]   create or move a bookmark (default: @)\n";-  std::cout << "  mv <name> [-rev <rev>]    alias of set\n";-  std::cout << "  ls [-no-col-titles]       list bookmarks\n";-  std::cout << "  rm <name>                 delete a bookmark\n";+    std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n";+    std::cout << "\n";+    std::cout << "manage named, movable pointers to commits (branches)\n";+    std::cout << "\n";+    std::cout << "subcommands:\n";+    std::cout << "  set <name> [-rev <rev>]   create or move a bookmark (default: @)\n";+    std::cout << "  mv <name> [-rev <rev>]    alias of set\n";+    std::cout << "  ls [-no-col-titles]       list bookmarks\n";+    std::cout << "  rm <name>                 delete a bookmark\n"; }  } // namespace -int bmk_run(const std::vector<std::string> &args) {-  if (args.size() <= 2) {+int bmk_run(const std::vector<std::string>& args) {+    if (args.size() <= 2) {+        bmk_usage();+        return 1;+    }+    const std::string& sub = args[2];+    if (sub == "set" || sub == "mv")+        return bmk_set(args, 3);+    if (sub == "ls")+        return bmk_list(args, 3);+    if (sub == "rm")+        return bmk_delete(args, 3);+    if (sub == "help" || sub == "-h") {+        bmk_usage();+        return 0;+    }+    error_prefix();+    std::cout << "unknown bmk subcommand: " << sub << "\n";     bmk_usage();     return 1;-  }-  const std::string &sub = args[2];-  if (sub == "set" || sub == "mv")-    return bmk_set(args, 3);-  if (sub == "ls")-    return bmk_list(args, 3);-  if (sub == "rm")-    return bmk_delete(args, 3);-  if (sub == "help" || sub == "-h") {-    bmk_usage();-    return 0;-  }-  error_prefix();-  std::cout << "unknown bmk subcommand: " << sub << "\n";-  bmk_usage();-  return 1; }  } // namespace vn--- a/xveins/src/cfg.cpp+++ b/xveins/src/cfg.cpp@@ -14,207 +14,196 @@ namespace {  std::string_view cfg_trim(std::string_view text) {-  while (!text.empty() && (text.front() == ' ' || text.front() == '\t' ||-                           text.front() == '\r' || text.front() == '\n'))-    text.remove_prefix(1);-  while (!text.empty() && (text.back() == ' ' || text.back() == '\t' ||-                           text.back() == '\r' || text.back() == '\n'))-    text.remove_suffix(1);-  return text;+    while (!text.empty() && (text.front() == ' ' || text.front() == '\t' || text.front() == '\r' ||+                             text.front() == '\n'))+        text.remove_prefix(1);+    while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' ||+                             text.back() == '\n'))+        text.remove_suffix(1);+    return text; }  bool cfg_is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';+    return !arg.empty() && arg.front() == '-'; } -std::map<std::string, std::string> repo_config_entries(const fs::path &root) {-  std::map<std::string, std::string> out;-  const auto data = read_file_opt(root / ".veins" / "config");-  if (!data)-    return out;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    const std::string_view line = cfg_trim(text.substr(start, end - start));-    if (!line.empty() && line.front() != '#') {-      const std::size_t eq = line.find('=');-      if (eq != std::string_view::npos) {-        const std::string_view key = cfg_trim(line.substr(0, eq));-        if (!key.empty())-          out[std::string(key)] = std::string(cfg_trim(line.substr(eq + 1)));-      }+std::map<std::string, std::string> repo_config_entries(const fs::path& root) {+    std::map<std::string, std::string> out;+    const auto data = read_file_opt(root / ".veins" / "config");+    if (!data)+        return out;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        const std::string_view line = cfg_trim(text.substr(start, end - start));+        if (!line.empty() && line.front() != '#') {+            const std::size_t eq = line.find('=');+            if (eq != std::string_view::npos) {+                const std::string_view key = cfg_trim(line.substr(0, eq));+                if (!key.empty())+                    out[std::string(key)] = std::string(cfg_trim(line.substr(eq + 1)));+            }+        }+        if (end == text.size())+            break;+        start = end + 1;     }-    if (end == text.size())-      break;-    start = end + 1;-  }-  return out;+    return out; }  void cfg_usage() {-  std::cout << "usage: vn cfg [<key>] [<value>]\n";-  std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";-  std::cout << "       vn cfg -list\n";-  std::cout << "       vn cfg -unset <key>\n";-  std::cout << "\n";-  std::cout << "read and write local repository configuration\n";-  std::cout << "\n";-  std::cout << "  vn cfg                      list all keys\n";-  std::cout << "  vn cfg <key>                print a value\n";-  std::cout << "  vn cfg <key> <value>        set a value\n";-  std::cout << "  vn cfg -unset <key>         remove a key\n";-  std::cout << "  vn cfg -global ...          use the user config instead\n";+    std::cout << "usage: vn cfg [<key>] [<value>]\n";+    std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";+    std::cout << "       vn cfg -list\n";+    std::cout << "       vn cfg -unset <key>\n";+    std::cout << "\n";+    std::cout << "read and write local repository configuration\n";+    std::cout << "\n";+    std::cout << "  vn cfg                      list all keys\n";+    std::cout << "  vn cfg <key>                print a value\n";+    std::cout << "  vn cfg <key> <value>        set a value\n";+    std::cout << "  vn cfg -unset <key>         remove a key\n";+    std::cout << "  vn cfg -global ...          use the user config instead\n"; } -int cfg_list(const fs::path *root, bool global) {-  std::map<std::string, std::string> entries;-  if (global) {-    if (auto name = user_config_author_name())-      entries["user.name"] = *name;-    if (auto email = user_config_author_email())-      entries["user.email"] = *email;-  } else {-    entries = repo_config_entries(*root);-  }-  for (const auto &entry : entries)-    std::cout << entry.first << " = " << entry.second << "\n";-  return 0;+int cfg_list(const fs::path* root, bool global) {+    std::map<std::string, std::string> entries;+    if (global) {+        if (auto name = user_config_author_name())+            entries["user.name"] = *name;+        if (auto email = user_config_author_email())+            entries["user.email"] = *email;+    } else {+        entries = repo_config_entries(*root);+    }+    for (const auto& entry : entries)+        std::cout << entry.first << " = " << entry.second << "\n";+    return 0; } -int cfg_get(const fs::path *root, bool global, const std::string &key) {-  std::optional<std::string> value;-  if (global) {-    if (key == "user.name")-      value = user_config_author_name();-    else if (key == "user.email")-      value = user_config_author_email();-  } else {-    value = repo_config_value(*root, key);-  }-  if (!value) {-    error_prefix();-    std::cout << "unknown config key: " << key << "\n";-    return 1;-  }-  std::cout << *value << "\n";-  return 0;+int cfg_get(const fs::path* root, bool global, const std::string& key) {+    std::optional<std::string> value;+    if (global) {+        if (key == "user.name")+            value = user_config_author_name();+        else if (key == "user.email")+            value = user_config_author_email();+    } else {+        value = repo_config_value(*root, key);+    }+    if (!value) {+        error_prefix();+        std::cout << "unknown config key: " << key << "\n";+        return 1;+    }+    std::cout << *value << "\n";+    return 0; } -int cfg_set(const fs::path *root, bool global, const std::string &key,-            const std::string &value) {-  const bool ok =-      global ? user_config_set(key, value) : repo_config_set(*root, key, value);-  if (!ok) {-    error_prefix();-    std::cout << "cannot write " << (global ? "user" : "repository")-              << " config\n";-    return 1;-  }-  return 0;+int cfg_set(const fs::path* root, bool global, const std::string& key, const std::string& value) {+    const bool ok = global ? user_config_set(key, value) : repo_config_set(*root, key, value);+    if (!ok) {+        error_prefix();+        std::cout << "cannot write " << (global ? "user" : "repository") << " config\n";+        return 1;+    }+    return 0; } -int cfg_unset(const fs::path *root, bool global, const std::string &key) {-  const bool ok =-      global ? user_config_remove(key) : repo_config_remove(*root, key);-  if (!ok) {-    error_prefix();-    std::cout << "cannot write " << (global ? "user" : "repository")-              << " config\n";-    return 1;-  }-  return 0;+int cfg_unset(const fs::path* root, bool global, const std::string& key) {+    const bool ok = global ? user_config_remove(key) : repo_config_remove(*root, key);+    if (!ok) {+        error_prefix();+        std::cout << "cannot write " << (global ? "user" : "repository") << " config\n";+        return 1;+    }+    return 0; }  } // namespace -int cfg_run(const std::vector<std::string> &args) {-  if (args.size() == 3 &&-      (args[2] == "help" || args[2] == "-h" || args[2] == "--help")) {-    cfg_usage();-    return 0;-  }-  bool global = false;-  bool list = false;-  bool unset = false;-  bool end_flags = false;-  std::vector<std::string> positional;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags &&-               (arg == "-global" || arg == "--global" || arg == "-g")) {-      global = true;-    } else if (!end_flags &&-               (arg == "-list" || arg == "--list" || arg == "-l")) {-      list = true;-    } else if (!end_flags && (arg == "-unset" || arg == "--unset")) {-      unset = true;-    } else if (!end_flags && cfg_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      positional.push_back(arg);+int cfg_run(const std::vector<std::string>& args) {+    if (args.size() == 3 && (args[2] == "help" || args[2] == "-h" || args[2] == "--help")) {+        cfg_usage();+        return 0;     }-  }--  if (positional.size() == 1 &&-      (positional[0] == "list" || positional[0] == "ls")) {-    list = true;-    positional.clear();-  } else if (positional.size() == 2 && positional[0] == "get") {-    positional.erase(positional.begin());-  } else if (positional.size() == 3 && positional[0] == "set") {-    positional.erase(positional.begin());-  } else if (positional.size() == 2 &&-             (positional[0] == "unset" || positional[0] == "rm" ||-              positional[0] == "remove")) {-    unset = true;-    positional.erase(positional.begin());-  }+    bool global = false;+    bool list = false;+    bool unset = false;+    bool end_flags = false;+    std::vector<std::string> positional;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-global" || arg == "--global" || arg == "-g")) {+            global = true;+        } else if (!end_flags && (arg == "-list" || arg == "--list" || arg == "-l")) {+            list = true;+        } else if (!end_flags && (arg == "-unset" || arg == "--unset")) {+            unset = true;+        } else if (!end_flags && cfg_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            positional.push_back(arg);+        }+    } -  if (list) {-    if (!positional.empty()) {-      error_prefix();-      std::cout << "cfg list takes no operands\n";-      return 1;+    if (positional.size() == 1 && (positional[0] == "list" || positional[0] == "ls")) {+        list = true;+        positional.clear();+    } else if (positional.size() == 2 && positional[0] == "get") {+        positional.erase(positional.begin());+    } else if (positional.size() == 3 && positional[0] == "set") {+        positional.erase(positional.begin());+    } else if (positional.size() == 2 &&+               (positional[0] == "unset" || positional[0] == "rm" || positional[0] == "remove")) {+        unset = true;+        positional.erase(positional.begin());     }-  } else if (unset) {-    if (positional.size() != 1) {-      error_prefix();-      std::cout << "cfg unset requires one key\n";-      return 1;++    if (list) {+        if (!positional.empty()) {+            error_prefix();+            std::cout << "cfg list takes no operands\n";+            return 1;+        }+    } else if (unset) {+        if (positional.size() != 1) {+            error_prefix();+            std::cout << "cfg unset requires one key\n";+            return 1;+        }+    } else if (positional.size() > 2) {+        error_prefix();+        std::cout << "cfg accepts a key and one value\n";+        return 1;     }-  } else if (positional.size() > 2) {-    error_prefix();-    std::cout << "cfg accepts a key and one value\n";-    return 1;-  } -  std::optional<fs::path> root;-  if (!global) {-    root = discover_repo(".");-    if (!root) {-      error_prefix();-      std::cout << "not a veins repository\n";-      return 1;+    std::optional<fs::path> root;+    if (!global) {+        root = discover_repo(".");+        if (!root) {+            error_prefix();+            std::cout << "not a veins repository\n";+            return 1;+        }     }-  } -  if (list)-    return cfg_list(root ? &*root : nullptr, global);-  if (unset)-    return cfg_unset(root ? &*root : nullptr, global, positional[0]);-  if (positional.empty())-    return cfg_list(root ? &*root : nullptr, global);-  if (positional.size() == 1)-    return cfg_get(root ? &*root : nullptr, global, positional[0]);-  return cfg_set(root ? &*root : nullptr, global, positional[0], positional[1]);+    if (list)+        return cfg_list(root ? &*root : nullptr, global);+    if (unset)+        return cfg_unset(root ? &*root : nullptr, global, positional[0]);+    if (positional.empty())+        return cfg_list(root ? &*root : nullptr, global);+    if (positional.size() == 1)+        return cfg_get(root ? &*root : nullptr, global, positional[0]);+    return cfg_set(root ? &*root : nullptr, global, positional[0], positional[1]); }  } // namespace vn--- a/xveins/src/cli.cpp+++ b/xveins/src/cli.cpp@@ -19,2493 +19,2451 @@ namespace {  bool is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';-}--std::optional<fs::path> open_repo() {-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return std::nullopt;-  }-  return root;-}--std::string join_args(const std::vector<std::string> &parts) {-  std::string out;-  for (std::size_t i = 0; i < parts.size(); ++i) {-    if (i != 0)-      out.push_back(' ');-    out += parts[i];-  }-  return out;-}--bool message_is_blank(const std::vector<std::string> &parts) {-  for (const auto &part : parts) {-    for (char c : part) {-      if (c != ' ' && c != '\t' && c != '\n' && c != '\r')-        return false;-    }-  }-  return true;-}--Result<std::vector<std::string>>-parse_message(const std::vector<std::string> &args, std::size_t start) {-  std::vector<std::string> parts;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-m" || arg == "-message")) {-      if (i + 1 < args.size()) {-        parts.push_back(args[++i]);-      } else {-        error_prefix();-        std::cout << arg << " requires a message\n";-        return fail_usage("missing message");-      }-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return fail_usage("unknown flag");-    } else {-      parts.push_back(arg);-    }-  }-  return parts;-}--void print_cell(std::string_view text, std::size_t width, Color color,-                bool dim) {-  if (dim) {-    print_styled(text, color, true, false);-  } else if (color == Color::Default) {-    std::cout << text;-  } else {-    print_colored(text, color, false, false);-  }-  for (std::size_t i = text.size(); i < width; ++i)-    std::cout << ' ';-}--void print_gap() { std::cout << "  "; }--std::string first_line(const std::string &message) {-  const std::size_t newline = message.find('\n');-  return newline == std::string::npos ? message : message.substr(0, newline);-}--std::string short_hex(const Id &id) { return hex_encode(id).substr(0, 12); }--std::string short_change_id(const std::vector<std::string> &ids,-                            std::size_t index) {-  const std::string &target = ids[index];-  std::size_t len = std::min<std::size_t>(4, target.size());-  while (len < target.size()) {-    const std::string_view prefix(target.data(), len);-    bool unique = true;-    for (std::size_t j = 0; j < ids.size(); ++j) {-      if (j == index)-        continue;-      if (ids[j] == target)-        continue;-      if (ids[j].starts_with(prefix)) {-        unique = false;-        break;-      }-    }-    if (unique)-      break;-    ++len;-  }-  return target.substr(0, len);-}--// ----------------------------------------------------------------------------// Diff rendering-// -----------------------------------------------------------------------------struct DiffOp {-  char tag = ' ';-  std::size_t ai = 0;-  std::size_t bi = 0;-};--std::vector<std::string> split_lines(Bytes data) {-  std::vector<std::string> out;-  std::size_t start = 0;-  for (std::size_t i = 0; i < data.size(); ++i) {-    if (data[i] == '\n') {-      out.emplace_back(reinterpret_cast<const char *>(data.data() + start),-                       i - start);-      start = i + 1;-    }-  }-  if (start < data.size()) {-    out.emplace_back(reinterpret_cast<const char *>(data.data() + start),-                     data.size() - start);-  } else if (!data.empty() && data.back() == '\n') {-    // A trailing newline does not introduce an extra empty line.-  } else if (data.empty()) {-    // No lines.-  }-  return out;-}--std::vector<DiffOp> build_ops_lcs(const std::vector<std::string> &a,-                                  const std::vector<std::string> &b) {-  const std::size_t n = a.size();-  const std::size_t m = b.size();-  const std::size_t cols = m + 1;-  std::vector<std::uint32_t> dp((n + 1) * cols, 0);-  for (std::size_t i = 1; i <= n; ++i) {-    for (std::size_t j = 1; j <= m; ++j) {-      if (a[i - 1] == b[j - 1])-        dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;-      else-        dp[i * cols + j] =-            std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);-    }-  }-  std::vector<DiffOp> ops;-  std::size_t i = n;-  std::size_t j = m;-  while (i > 0 || j > 0) {-    if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) {-      ops.push_back(DiffOp{' ', i - 1, j - 1});-      --i;-      --j;-    } else if (j > 0 &&-               (i == 0 || dp[i * cols + (j - 1)] >= dp[(i - 1) * cols + j])) {-      ops.push_back(DiffOp{'+', 0, j - 1});-      --j;-    } else {-      ops.push_back(DiffOp{'-', i - 1, 0});-      --i;-    }-  }-  std::reverse(ops.begin(), ops.end());-  return ops;-}--std::vector<DiffOp> build_ops_myers(const std::vector<std::string> &a,-                                    const std::vector<std::string> &b) {-  const int n = static_cast<int>(a.size());-  const int m = static_cast<int>(b.size());-  const int max_d = n + m;-  const int offset = max_d;-  std::vector<int> v(static_cast<std::size_t>(2 * max_d + 1), 0);-  std::vector<std::vector<int>> trace;-  constexpr std::size_t trace_cap = 64u * 1024u * 1024u;-  int found_d = -1;-  for (int d = 0; d <= max_d; ++d) {-    if (static_cast<std::size_t>(trace.size() + 1) * v.size() * sizeof(int) >-        trace_cap)-      return {};-    trace.push_back(v);-    for (int k = -d; k <= d; k += 2) {-      int x = 0;-      if (k == -d ||-          (k != d && v[static_cast<std::size_t>(offset + k - 1)] <-                         v[static_cast<std::size_t>(offset + k + 1)]))-        x = v[static_cast<std::size_t>(offset + k + 1)];-      else-        x = v[static_cast<std::size_t>(offset + k - 1)] + 1;-      int y = x - k;-      while (x < n && y < m &&-             a[static_cast<std::size_t>(x)] == b[static_cast<std::size_t>(y)]) {-        ++x;-        ++y;-      }-      v[static_cast<std::size_t>(offset + k)] = x;-      if (x >= n && y >= m) {-        found_d = d;-        break;-      }-    }-    if (found_d >= 0)-      break;-  }-  if (found_d < 0)-    return {};-  std::vector<DiffOp> ops;-  int x = n;-  int y = m;-  for (int d = found_d; d >= 0; --d) {-    const auto &prev = trace[static_cast<std::size_t>(d)];-    const int k = x - y;-    int prev_k = 0;-    if (k == -d ||-        (k != d && prev[static_cast<std::size_t>(offset + k - 1)] <-                       prev[static_cast<std::size_t>(offset + k + 1)]))-      prev_k = k + 1;-    else-      prev_k = k - 1;-    const int prev_x = prev[static_cast<std::size_t>(offset + prev_k)];-    const int prev_y = prev_x - prev_k;-    while (x > prev_x && y > prev_y) {-      ops.push_back(DiffOp{' ', static_cast<std::size_t>(x - 1),-                           static_cast<std::size_t>(y - 1)});-      --x;-      --y;-    }-    if (d > 0) {-      if (x == prev_x) {-        ops.push_back(DiffOp{'+', 0, static_cast<std::size_t>(y - 1)});-        --y;-      } else {-        ops.push_back(DiffOp{'-', static_cast<std::size_t>(x - 1), 0});-        --x;-      }-    }-  }-  std::reverse(ops.begin(), ops.end());-  return ops;-}--std::vector<DiffOp> build_ops_fallback(const std::vector<std::string> &a,-                                       const std::vector<std::string> &b) {-  std::size_t prefix = 0;-  while (prefix < a.size() && prefix < b.size() && a[prefix] == b[prefix])-    ++prefix;-  std::size_t suffix = 0;-  while (suffix < a.size() - prefix && suffix < b.size() - prefix &&-         a[a.size() - 1 - suffix] == b[b.size() - 1 - suffix])-    ++suffix;-  std::vector<DiffOp> ops;-  for (std::size_t i = 0; i < prefix; ++i)-    ops.push_back(DiffOp{' ', i, i});-  for (std::size_t i = prefix; i < a.size() - suffix; ++i)-    ops.push_back(DiffOp{'-', i, 0});-  for (std::size_t j = prefix; j < b.size() - suffix; ++j)-    ops.push_back(DiffOp{'+', 0, j});-  for (std::size_t k = 0; k < suffix; ++k) {-    const std::size_t i = a.size() - suffix + k;-    const std::size_t j = b.size() - suffix + k;-    ops.push_back(DiffOp{' ', i, j});-  }-  return ops;-}--std::vector<DiffOp> build_ops(const std::vector<std::string> &a,-                              const std::vector<std::string> &b) {-  const std::size_t n = a.size();-  const std::size_t m = b.size();-  if (n == 0 && m == 0)-    return {};-  if (n != 0 && m != 0 && n <= 2048 && m <= 2048)-    return build_ops_lcs(a, b);-  if (n != 0 && m != 0 && n * m <= 4'000'000)-    return build_ops_lcs(a, b);-  auto myers = build_ops_myers(a, b);-  if (!myers.empty())-    return myers;-  return build_ops_fallback(a, b);-}--void render_unified(const std::vector<std::string> &a,-                    const std::vector<std::string> &b) {-  const auto ops = build_ops(a, b);-  std::vector<std::size_t> changes;-  for (std::size_t i = 0; i < ops.size(); ++i) {-    if (ops[i].tag != ' ')-      changes.push_back(i);-  }-  constexpr std::size_t context = 3;-  std::size_t pos = 0;-  std::size_t old_seen = 0;-  std::size_t new_seen = 0;-  std::size_t ci = 0;-  while (ci < changes.size()) {-    const std::size_t first = changes[ci];-    std::size_t start = first > context ? first - context : 0;-    std::size_t last = first;-    ++ci;-    while (ci < changes.size() && changes[ci] <= last + context * 2) {-      last = changes[ci];-      ++ci;-    }-    std::size_t end = std::min(last + context + 1, ops.size());-    while (pos < start) {-      const auto &op = ops[pos];-      if (op.tag == ' ') {-        ++old_seen;-        ++new_seen;-      } else if (op.tag == '-') {-        ++old_seen;-      } else {-        ++new_seen;-      }-      ++pos;-    }-    std::size_t old_count = 0;-    std::size_t new_count = 0;-    for (std::size_t e = start; e < end; ++e) {-      if (ops[e].tag == ' ') {-        ++old_count;-        ++new_count;-      } else if (ops[e].tag == '-') {-        ++old_count;-      } else {-        ++new_count;-      }-    }-    const std::size_t old_start = old_seen + (old_count > 0 ? 1 : 0);-    const std::size_t new_start = new_seen + (new_count > 0 ? 1 : 0);-    std::cout << "@@ -" << old_start << "," << old_count << " +" << new_start-              << "," << new_count << " @@\n";-    while (pos < end) {-      const auto &op = ops[pos];-      if (op.tag == ' ') {-        std::cout << " " << a[op.ai] << "\n";-        ++old_seen;-        ++new_seen;-      } else if (op.tag == '-') {-        print_colored("-", Color::Red, false, false);-        print_colored(a[op.ai], Color::Red, false, false);-        std::cout << "\n";-        ++old_seen;-      } else {-        print_colored("+", Color::Green, false, false);-        print_colored(b[op.bi], Color::Green, false, false);-        std::cout << "\n";-        ++new_seen;-      }-      ++pos;-    }-  }-}--bool contains_nul(Bytes data) {-  const std::size_t limit = std::min<std::size_t>(data.size(), 8192);-  for (std::size_t i = 0; i < limit; ++i) {-    if (data[i] == 0)-      return true;-  }-  return false;-}--void render_diff(Store &store, std::optional<Id> old_tree,-                 std::optional<Id> new_tree, bool announce_no_diff) {-  const auto changes = compare_trees(store, old_tree, new_tree);-  for (const auto &change : changes) {-    if (change.new_kind == KIND_CONFLICT) {-      std::cout << "Conflict: " << change.path << "\n";-      continue;-    }-    std::vector<std::uint8_t> old_data;-    std::vector<std::uint8_t> new_data;-    if (change.old_kind != KIND_MISSING && change.old_id) {-      if (auto data = read_blob(store, *change.old_id))-        old_data = std::move(*data);-    }-    if (change.new_kind != KIND_MISSING && change.new_id) {-      if (auto data = read_blob(store, *change.new_id))-        new_data = std::move(*data);-    }-    if (contains_nul(bytes_of(old_data)) || contains_nul(bytes_of(new_data))) {-      std::cout << "Binary files a/" << change.path << " and b/" << change.path-                << " differ\n";-      continue;-    }-    print_colored("--- ", Color::Red, false, false);-    if (change.old_kind == KIND_MISSING) {-      print_colored("/dev/null", Color::Red, false, false);-    } else {-      print_colored("a/", Color::Red, false, false);-      print_colored(change.path, Color::Red, false, false);-    }-    std::cout << "\n";-    print_colored("+++ ", Color::Green, false, false);-    if (change.new_kind == KIND_MISSING) {-      print_colored("/dev/null", Color::Green, false, false);-    } else {-      print_colored("b/", Color::Green, false, false);-      print_colored(change.path, Color::Green, false, false);-    }-    std::cout << "\n";-    const auto a = split_lines(bytes_of(old_data));-    const auto b = split_lines(bytes_of(new_data));-    render_unified(a, b);-  }-  if (announce_no_diff && changes.empty()) {-    info_prefix();-    std::cout << "no diff to show\n";-  }-}--// ----------------------------------------------------------------------------// Commands-// -----------------------------------------------------------------------------int run_init(const std::vector<std::string> &args) {-  std::string path = ".";-  std::optional<std::string> source;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && arg.rfind("-git-import:", 0) == 0) {-      source = arg.substr(12);-      if (source->empty()) {-        error_prefix();-        std::cout << "-git-import: requires a path\n";-        return 1;-      }-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      path = arg;-    }-  }-  const auto initialized = init_repo(path_from_bytes(path));-  if (!initialized) {-    error_prefix();-    std::cout << "init failed with code " << initialized.error().offset << "\n";-    return 1;-  }-  info_prefix();-  std::cout << "initialized veins repository at " << path_display(*initialized)-            << "\n";-  if (source) {-    const int prepared = git_prepare_mirror(*initialized, *source);-    if (prepared != 0) {-      error_prefix();-      if (prepared == 2) {-        std::cout << "-git-import: " << *source-                  << " is not a git repository root (expected the directory "-                     "containing .git)\n";-      } else {-        std::cout << "cannot prepare git mirror from " << *source << " (code "-                  << prepared << ")\n";-      }-      return 1;-    }-    return git_import(*initialized);-  }-  return 0;-}--int run_status() {-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  const auto wc = working_copy_id(*view);-  if (!wc) {-    info_prefix();-    std::cout << "working copy clean\n";-    return 0;-  }-  std::optional<Id> old_tree;-  std::optional<Id> new_tree;-  auto wc_body = store.read_body(*wc, TYPE_COMMIT);-  if (!wc_body) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  auto wc_commit = decode_commit(bytes_of(*wc_body));-  if (!wc_commit) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  new_tree = wc_commit->root_tree;-  if (!wc_commit->parents.empty()) {-    auto parent_body = store.read_body(wc_commit->parents.front(), TYPE_COMMIT);-    if (parent_body) {-      auto parent_commit = decode_commit(bytes_of(*parent_body));-      if (parent_commit)-        old_tree = parent_commit->root_tree;-    }-  }-  const auto changes = compare_trees(store, old_tree, new_tree);-  std::size_t conflicts = 0;-  for (const auto &change : changes) {-    if (change.old_kind == KIND_MISSING) {-      print_colored("A", Color::BrightGreen, false, false);-      std::cout << " " << change.path << "\n";-    } else if (change.new_kind == KIND_MISSING) {-      print_colored("D", Color::Red, false, false);-      std::cout << " " << change.path << "\n";-    } else if (change.new_kind == KIND_CONFLICT) {-      print_colored("C", Color::BrightRed, false, false);-      std::cout << " " << change.path << "\n";-      ++conflicts;-    } else {-      print_colored("M", Color::Cyan, false, false);-      std::cout << " " << change.path << "\n";-    }-  }-  if (changes.empty()) {-    info_prefix();-    std::cout << "working copy clean\n";-  }-  if (conflicts > 0)-    std::cout << conflicts << " conflict(s)\n";--  const std::vector<Id> start{*wc};-  const auto ancestry = collect_commits(store, start);-  std::size_t conflicted_commits = 0;-  for (const auto &id : ancestry) {-    auto loaded = load_commit(store, id);-    if (loaded && tree_conflicted(store, loaded->commit.root_tree))-      ++conflicted_commits;-  }-  if (conflicted_commits > 0)-    std::cout << conflicted_commits << " conflicted commit(s) in ancestry\n";-  return 0;-}--int run_log(const std::vector<std::string> &args) {-  std::string rev;-  bool col_titles = true;-  bool end_flags = false;-  std::optional<std::size_t> limit;-  bool first = false;-  auto parse_count = [](std::string_view text, std::size_t &out) -> bool {-    if (text.empty())-      return false;-    std::size_t value = 0;-    for (char c : text) {-      if (c < '0' || c > '9')-        return false;-      value = value * 10 + static_cast<std::size_t>(c - '0');-    }-    if (value == 0)-      return false;-    out = value;-    return true;-  };-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      rev = args[++i];-    } else if (!end_flags && arg == "-no-col-titles") {-      col_titles = false;-    } else if (!end_flags && (arg == "-l" || arg == "-f")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a count\n";-        return 1;-      }-      std::size_t count = 0;-      if (!parse_count(args[++i], count)) {-        error_prefix();-        std::cout << arg << " requires a positive count\n";-        return 1;-      }-      limit = count;-      first = arg == "-f";-    } else if (!end_flags && arg.size() > 2 &&-               (arg[0] == '-' && (arg[1] == 'l' || arg[1] == 'f'))) {-      std::size_t count = 0;-      if (!parse_count(std::string_view(arg).substr(2), count)) {-        error_prefix();-        std::cout << "invalid log count: " << arg << "\n";-        return 1;-      }-      limit = count;-      first = arg[1] == 'f';-    } else if (!end_flags && arg.size() > 1 &&-               (arg[0] == 'l' || arg[0] == 'f')) {-      std::size_t count = 0;-      if (parse_count(std::string_view(arg).substr(1), count)) {-        limit = count;-        first = arg[0] == 'f';-      } else {-        rev = arg;-      }-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      rev = arg;-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  const auto wc = working_copy_id(*view);-  std::vector<Id> ids;-  if (rev.empty() || rev == "all()") {-    const auto roots = view_roots(*view);-    ids = collect_commits(store, roots);-  } else if (auto one = resolve_revision(store, *view, rev)) {-    const std::vector<Id> start{*one};-    ids = collect_commits(store, start);-  }--  struct Rec {-    Id id{};-    std::string change;-    std::int64_t seconds = 0;-    std::string message;-    std::string author;-    bool conflicted = false;-    bool has_changes = false;-  };-  std::vector<Rec> recs;-  for (const auto &id : ids) {-    auto loaded = load_commit(store, id);-    if (!loaded)-      continue;-    Rec rec;-    rec.id = id;-    rec.change = base32_encode(loaded->commit.change_id);-    rec.seconds = loaded->commit.committer.seconds;-    rec.message = first_line(loaded->commit.message);-    rec.author = loaded->commit.author.name;-    rec.conflicted = tree_conflicted(store, loaded->commit.root_tree);-    if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)-      rec.has_changes = has_changes(store, *loaded);-    recs.push_back(std::move(rec));-  }-  std::stable_sort(recs.begin(), recs.end(), [](const Rec &a, const Rec &b) {-    return a.seconds > b.seconds;-  });--  if (limit) {-    if (first) {-      if (recs.size() > *limit)-        recs.erase(recs.begin(),-                   recs.end() - static_cast<std::ptrdiff_t>(*limit));-      std::reverse(recs.begin(), recs.end());-    } else if (recs.size() > *limit) {-      recs.resize(*limit);-    }-  }--  std::vector<std::string> change_ids;-  for (const auto &rec : recs)-    change_ids.push_back(rec.change);-  std::size_t w_commit = 12;-  std::size_t w_change = 6;-  std::size_t w_date = 19;-  std::size_t w_author = 6;-  for (std::size_t i = 0; i < recs.size(); ++i) {-    const auto cid = short_change_id(change_ids, i);-    w_change = std::max(w_change, cid.size());-    w_author = std::max(w_author, recs[i].author.size());-  }-  if (col_titles) {-    print_cell("", 1, Color::Default, false);-    std::cout << " ";-    print_cell("Commit", w_commit, Color::Default, false);-    print_gap();-    print_cell("Change", w_change, Color::Default, false);-    print_gap();-    print_cell("Date", w_date, Color::Default, false);-    print_gap();-    print_cell("Author", w_author, Color::Default, false);-    print_gap();-    std::cout << "Message\n";-  }-  for (std::size_t i = 0; i < recs.size(); ++i) {-    const auto &rec = recs[i];-    const bool is_wc =-        wc && std::memcmp(wc->data(), rec.id.data(), ID_LEN) == 0;-    std::string marker = is_wc ? "@" : " ";-    Color marker_color = Color::Default;-    if (is_wc)-      marker_color = rec.has_changes ? Color::BrightCyan : Color::Red;-    const auto cid = short_change_id(change_ids, i);-    const auto stamp = format_utc(rec.seconds);-    print_cell(marker, 1, marker_color, false);-    std::cout << " ";-    print_cell(short_hex(rec.id), w_commit, Color::Red, false);-    print_gap();-    print_cell(cid, w_change, Color::Red, false);-    print_gap();-    print_cell(stamp, w_date, Color::Cyan, true);-    print_gap();-    print_cell(rec.author, w_author, Color::Cyan, false);-    print_gap();-    if (!rec.message.empty())-      print_colored(rec.message, Color::Green, false, false);-    else-      print_colored("<unset>", Color::BrightBlack, false, false);-    for (const auto &name : bookmark_names(*view, rec.id))-      std::cout << " [" << name << "]";-    for (const auto &name : tag_names(*view, rec.id))-      std::cout << " <" << name << ">";-    if (rec.conflicted)-      std::cout << " (conflicted)";-    bool divergent = false;-    for (std::size_t j = 0; j < recs.size(); ++j) {-      if (j != i && recs[j].change == rec.change) {-        divergent = true;-        break;-      }-    }-    if (divergent)-      std::cout << " (divergent)";-    std::cout << "\n";-  }-  return 0;-}--int run_show(const std::vector<std::string> &args) {-  std::string rev;-  bool col_titles = true;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      rev = args[++i];-    } else if (!end_flags && arg == "-no-col-titles") {-      col_titles = false;-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      rev = arg;-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  auto target = resolve_revision(store, *view, rev);-  if (!target) {-    error_prefix();-    if (rev.empty())-      std::cout << "no working-copy commit\n";-    else-      std::cout << "unknown revision: " << rev << "\n";-    return 1;-  }-  auto loaded = load_commit(store, *target);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read commit\n";-    return 1;-  }-  if (col_titles) {-    std::cout << "commit   " << hex_encode(*target) << "\n";-    std::cout << "change   " << base32_encode(loaded->commit.change_id) << "\n";-    std::cout << "author   " << loaded->commit.author.name << " <"-              << loaded->commit.author.email << ">\n";-    std::cout << "date     " << format_utc(loaded->commit.committer.seconds)-              << "\n";-    std::cout << "parents  ";-    if (loaded->commit.parents.empty()) {-      std::cout << "<none>";-    } else {-      for (std::size_t i = 0; i < loaded->commit.parents.size(); ++i) {-        if (i != 0)-          std::cout << " ";-        std::cout << short_hex(loaded->commit.parents[i]);-      }-    }-    std::cout << "\n";-    const auto names = bookmark_names(*view, *target);-    if (!names.empty()) {-      std::cout << "bookmarks";-      for (const auto &name : names)-        std::cout << " [" << name << "]";-      std::cout << "\n";-    }-    std::cout << "\n";-    if (!loaded->commit.message.empty())-      std::cout << loaded->commit.message << "\n";-    else-      std::cout << "<unset>\n";-    std::cout << "\n";-  }-  std::optional<Id> old_tree;-  if (!loaded->commit.parents.empty()) {-    auto parent = load_commit(store, loaded->commit.parents.front());-    if (parent)-      old_tree = parent->commit.root_tree;-  }-  render_diff(store, old_tree, loaded->commit.root_tree, false);-  return 0;-}--int run_hash(const std::vector<std::string> &args) {-  std::string rev;-  bool short_hash = false;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && arg == "-short") {-      short_hash = true;-    } else if (!end_flags && arg == "-long") {-      short_hash = false;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      rev = args[++i];-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      rev = arg;-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  auto target = resolve_revision(store, *view, rev);-  if (!target) {-    error_prefix();-    if (rev.empty())-      std::cout << "no working-copy commit\n";-    else-      std::cout << "unknown revision: " << rev << "\n";-    return 1;-  }-  const auto hex = hex_encode(*target);-  std::cout << hex.substr(0, short_hash ? 12 : 64) << "\n";-  return 0;-}--bool print_tree(const fs::path &root, Store &store, const Id &tree_id,-                const std::string &prefix, std::size_t depth) {-  if (depth > 4096)-    return false;-  auto body = store.read_body(tree_id, TYPE_TREE);-  if (!body)-    return false;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return false;-  for (std::size_t i = 0; i < tree->entries.size(); ++i) {-    const auto &entry = tree->entries[i];-    const bool last = i + 1 == tree->entries.size();-    std::cout << prefix << (last ? "`-- " : "|-- ") << entry.name << "\n";-    if (entry.kind == KIND_SUBTREE) {-      if (!print_tree(root, store, entry.target,-                      prefix + (last ? "    " : "|   "), depth + 1))-        return false;-    }-  }-  return true;-}--int run_ls(const std::vector<std::string> &args) {-  std::string rev;-  bool plain = false;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-plain" || arg == "-p")) {-      plain = true;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      rev = args[++i];-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      rev = arg;-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  auto target = resolve_revision(store, *view, rev);-  if (!target) {-    error_prefix();-    if (rev.empty())-      std::cout << "no working-copy commit\n";-    else-      std::cout << "unknown revision: " << rev << "\n";-    return 1;-  }-  auto loaded = load_commit(store, *target);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read commit\n";-    return 1;-  }-  bool good = true;-  if (plain) {-    auto entries = flatten_tree_checked(store, loaded->commit.root_tree);-    if (!entries) {-      good = false;-    } else {-      for (const auto &entry : *entries)-        std::cout << entry.path << "\n";-    }-  } else {-    std::cout << ".\n";-    good = print_tree(*root, store, loaded->commit.root_tree, "", 0);-  }-  if (!good) {-    error_prefix();-    std::cout << "cannot read tree\n";-    return 1;-  }-  return 0;-}--int run_diff(const std::vector<std::string> &args) {-  std::vector<std::string> revs;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      revs.push_back(args[++i]);-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      revs.push_back(arg);-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  std::optional<Id> old_tree;-  std::optional<Id> new_tree;-  bool failed = false;-  auto tree_of = [&](const Id &id) -> std::optional<Id> {-    auto loaded = load_commit(store, id);-    if (!loaded)-      return std::nullopt;-    return loaded->commit.root_tree;-  };-  auto parent_tree_of = [&](const Id &id) -> std::optional<Id> {-    auto loaded = load_commit(store, id);-    if (!loaded || loaded->commit.parents.empty())-      return std::nullopt;-    auto parent = load_commit(store, loaded->commit.parents.front());-    if (!parent)-      return std::nullopt;-    return parent->commit.root_tree;-  };-  if (revs.size() >= 2) {-    auto a = resolve_revision(store, *view, revs[0]);-    auto b = resolve_revision(store, *view, revs[1]);-    if (!a || !b)-      failed = true;-    else {-      old_tree = tree_of(*a);-      new_tree = tree_of(*b);-    }-  } else if (revs.size() == 1) {-    auto a = resolve_revision(store, *view, revs[0]);-    if (!a)-      failed = true;-    else {-      old_tree = parent_tree_of(*a);-      new_tree = tree_of(*a);-    }-  } else {-    const auto wc = working_copy_id(*view);-    if (wc) {-      old_tree = parent_tree_of(*wc);-      new_tree = tree_of(*wc);-    }-  }-  if (failed) {-    error_prefix();-    std::cout << "unknown revision\n";-    return 1;-  }-  render_diff(store, old_tree, new_tree, true);-  return 0;-}--int run_new(const std::vector<std::string> &args) {-  std::vector<std::string> revs;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      revs.push_back(arg);-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  std::optional<Id> old_root;-  std::vector<Id> parents;-  std::optional<Id> root_tree;-  if (revs.empty()) {-    if (!wc) {-      error_prefix();-      std::cout << "no working-copy commit\n";-      return 1;-    }-    auto loaded = load_commit(store, *wc);-    if (!loaded) {-      error_prefix();-      std::cout << "cannot read working-copy commit\n";-      return 1;-    }-    parents.push_back(*wc);-    root_tree = loaded->commit.root_tree;-    old_root = root_tree;-  } else {-    for (std::size_t i = 0; i < revs.size(); ++i) {-      auto resolved = resolve_revision(store, tx->view(), revs[i]);-      if (!resolved) {-        error_prefix();-        std::cout << "unknown revision\n";-        return 1;-      }-      parents.push_back(*resolved);-      if (i == 0) {-        auto loaded = load_commit(store, *resolved);-        if (!loaded) {-          error_prefix();-          std::cout << "unknown revision\n";-          return 1;-        }-        root_tree = loaded->commit.root_tree;-      }-    }-    if (wc) {-      auto old_loaded = load_commit(store, *wc);-      if (old_loaded)-        old_root = old_loaded->commit.root_tree;-    }-  }-  const Sig sig = identity_signature(*root);-  Commit commit;-  commit.version = 1;-  commit.parents = parents;-  commit.root_tree = *root_tree;-  commit.change_id = random_change_id();-  commit.author = sig;-  commit.committer = sig;-  commit.message = "";-  commit.renames_state = RENAMES_RECORDED;-  const auto encoded = encode_commit(commit);-  const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-  if (wc)-    remove_head(tx->view(), *wc);-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());-  const auto status = tx->finish("new");-  if (!status)-    return 1;-  store.refresh(*root);-  (void)mark_native(*root, new_id);-  if (!revs.empty()) {-    const int materialized =-        checkout_materialize_commit(*root, store, old_root, *root_tree);-    if (materialized != 0)-      return materialized;-  }-  return 0;-}--int describe_impl(const fs::path &root, Store &store,-                  const std::vector<std::string> &parts, bool require_changes) {-  const int snap = snapshot_run(root, store);-  if (snap != 0)-    return snap;-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  if (!wc) {-    error_prefix();-    std::cout << "no working-copy commit\n";-    return 1;-  }-  auto loaded = load_commit(store, *wc);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read working-copy commit\n";-    return 1;-  }-  const std::string message = join_args(parts);-  const bool changed = has_changes(store, *loaded);-  const bool same_message = message == loaded->commit.message;-  if (!changed && (require_changes || same_message)) {-    if (require_changes) {-      info_prefix();-      std::cout << "nothing to commit, working copy clean\n";-      return 2;-    }-    return 0;-  }-  const Sig sig = identity_signature(root);-  Commit commit = loaded->commit;-  commit.committer = sig;-  if (!changed)-    commit.author = sig;-  commit.message = message;-  const auto encoded = encode_commit(commit);-  const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-  remove_head(tx->view(), *wc);-  move_bookmarks(tx->view(), *wc, new_id);-  if (auto current = current_bookmark_name(root)) {-    if (find_bookmark(tx->view(), *current))-      set_bookmark_target(tx->view(), *current, new_id);-  }-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());-  const auto status = tx->finish("describe");-  if (!status)-    return 1;-  store.refresh(root);-  (void)mark_native(root, new_id);-  return 0;-}--int run_describe(const std::vector<std::string> &args) {-  auto parsed = parse_message(args, 2);-  if (!parsed)-    return 1;-  const auto root = open_repo();-  if (!root)-    return 1;-  Store store = Store::open_all(*root);-  return describe_impl(*root, store, *parsed, false);-}--int run_commit(const std::vector<std::string> &args) {-  auto parsed = parse_message(args, 2);-  if (!parsed)-    return 1;-  if (message_is_blank(*parsed)) {-    error_prefix();-    std::cout << "commit requires a non-empty message (-message)\n";-    return 1;-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  Store store = Store::open_all(*root);-  const int described = describe_impl(*root, store, *parsed, true);-  if (described == 2)-    return 0;-  if (described != 0)-    return described;--  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  if (!wc) {-    error_prefix();-    std::cout << "no working-copy commit\n";-    return 1;-  }-  auto loaded = load_commit(store, *wc);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read working-copy commit\n";-    return 1;-  }-  const Sig sig = identity_signature(*root);-  Commit commit;-  commit.version = 1;-  commit.parents = {*wc};-  commit.root_tree = loaded->commit.root_tree;-  commit.change_id = random_change_id();-  commit.author = sig;-  commit.committer = sig;-  commit.message = "";-  commit.renames_state = RENAMES_RECORDED;-  const auto encoded = encode_commit(commit);-  const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-  remove_head(tx->view(), *wc);-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());-  const auto status = tx->finish("new");-  if (!status)-    return 1;-  (void)mark_native(*root, new_id);-  return 0;-}--std::optional<Id> mapped_id(const std::vector<Id> &old_ids,-                            const std::vector<Id> &new_ids, const Id &id) {-  for (std::size_t i = 0; i < old_ids.size(); ++i) {-    if (std::memcmp(old_ids[i].data(), id.data(), ID_LEN) == 0)-      return new_ids[i];-  }-  return std::nullopt;-}--void remap_ids(const std::vector<Id> &old_ids, const std::vector<Id> &new_ids,-               std::vector<std::optional<Id>> &ids) {-  for (auto &id : ids) {-    if (!id)-      continue;-    if (auto mapped = mapped_id(old_ids, new_ids, *id))-      id = *mapped;-  }-}--int run_amend(const std::vector<std::string> &args) {-  std::string rev;-  std::vector<std::string> parts;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-m" || arg == "-message")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a message\n";-        return 1;-      }-      parts.push_back(args[++i]);-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (rev.empty()) {-      rev = arg;-    } else {-      parts.push_back(arg);-    }-  }-  if (rev.empty()) {-    error_prefix();-    std::cout << "amend requires a revision\n";-    return 1;-  }-  if (message_is_blank(parts)) {-    error_prefix();-    std::cout << "amend requires a non-empty message (-message)\n";-    return 1;-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  auto target = resolve_revision(store, tx->view(), rev);-  if (!target) {-    error_prefix();-    std::cout << "unknown revision\n";-    return 1;-  }-  std::vector<Id> pushed_roots;-  for (const auto &ref : tx->view().remote_refs)-    pushed_roots.push_back(ref.target);-  if (!pushed_roots.empty() &&-      contains_id(collect_commits(store, pushed_roots), *target)) {-    error_prefix();-    std::cout << "cannot amend a revision that has been pushed\n";-    return 1;-  }-  auto target_loaded = load_commit(store, *target);-  if (!target_loaded) {-    error_prefix();-    std::cout << "cannot read revision\n";-    return 1;-  }-  const std::string message = join_args(parts);-  if (target_loaded->commit.message == message) {-    info_prefix();-    std::cout << "message unchanged\n";-    return 0;-  }-  auto remaining = all_commits(store, tx->view());-  std::vector<Id> old_ids;-  std::vector<Id> new_ids;-  const Sig sig = identity_signature(*root);-  bool target_rewritten = false;-  bool failed = false;-  while (!remaining.empty() && !failed) {-    std::optional<std::size_t> ready;-    for (std::size_t i = 0; i < remaining.size(); ++i) {-      bool is_ready =-          std::memcmp(remaining[i].data(), target->data(), ID_LEN) == 0;-      if (!is_ready) {-        auto loaded = load_commit(store, remaining[i]);-        if (loaded) {-          for (const auto &parent : loaded->commit.parents) {-            if (contains_id(old_ids, parent)) {-              is_ready = true;-              break;-            }-          }-        }-      }-      if (is_ready) {-        ready = i;-        break;-      }-    }-    if (!ready)-      break;-    const Id chosen = remaining[*ready];-    auto loaded = load_commit(store, chosen);-    if (!loaded) {-      failed = true;-      break;-    }-    std::vector<Id> new_parents;-    for (const auto &parent : loaded->commit.parents) {-      if (auto mapped = mapped_id(old_ids, new_ids, parent))-        new_parents.push_back(*mapped);-      else-        new_parents.push_back(parent);-    }-    Commit commit = loaded->commit;-    commit.parents = new_parents;-    commit.committer = sig;-    if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)-      commit.message = message;-    const auto encoded = encode_commit(commit);-    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);-    old_ids.push_back(chosen);-    new_ids.push_back(new_id);-    if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)-      target_rewritten = true;-    remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(*ready));-  }-  if (failed || !target_rewritten) {-    error_prefix();-    std::cout << "cannot amend revision\n";-    return 1;-  }-  for (auto &bookmark : tx->view().bookmarks) {-    remap_ids(old_ids, new_ids, bookmark.targets.adds);-    remap_ids(old_ids, new_ids, bookmark.targets.removes);-  }-  for (auto &tag : tx->view().tags) {-    if (auto mapped = mapped_id(old_ids, new_ids, tag.target))-      tag.target = *mapped;-  }-  for (auto &workspace : tx->view().working_copies) {-    if (auto mapped = mapped_id(old_ids, new_ids, workspace.target))-      workspace.target = *mapped;-  }-  for (auto &ref : tx->view().remote_refs) {-    if (auto mapped = mapped_id(old_ids, new_ids, ref.target))-      ref.target = *mapped;-  }-  rebuild_heads(tx->view());-  const auto status = tx->finish("amend " + rev);-  if (!status)-    return 1;-  for (const auto &id : new_ids)-    (void)mark_native(*root, id);-  return 0;-}--int run_checkout(const std::vector<std::string> &args) {-  std::string rev;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (rev.empty()) {-      rev = arg;-    }-  }-  const auto root = open_repo();-  if (!root)-    return 1;-  return checkout_run(*root, rev);-}--int run_fsck(const std::vector<std::string> &args) {-  std::string path = ".";-  bool verbose = false;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {-      verbose = true;-    } else if (!end_flags && is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      path = arg;-    }-  }-  const auto root = discover_repo(path_from_bytes(path));-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository: " << path << "\n";-    return 1;-  }-  return fsck_repository(*root, verbose);-}--int run_self_test() {-  auto fail = [](std::string_view why) {-    error_prefix();-    std::cout << "self-test: failed: " << why << "\n";-    return 1;-  };-  const auto empty_hash = blake3_hash(Bytes{});-  const std::string expected_empty =-      "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";-  if (hex_encode(Bytes(empty_hash.data(), empty_hash.size())) != expected_empty)-    return fail("blake3 vector");-  const auto &gear = fastcdc_gear();-  if (gear[0] != 0xf8447b379cdadcd5ull || gear[1] != 0xbe63d125aec8ca6dull)-    return fail("fastcdc gear table");--  BlobBuild build = build_blob(bytes_of(std::string("hello world")));-  if (!build.objects.empty()) {-    auto body = build.objects.back().body;-    auto decoded = decode_blob(bytes_of(body));-    if (!decoded || decoded->form != BlobForm::Inline)-      return fail("blob round trip");-  }-  Tree tree;-  tree.entries.push_back(TreeEntry{"a.txt", KIND_FILE, build.root});-  auto tree_body = encode_tree(tree.entries);-  if (!tree_body)-    return fail("tree encode");-  auto decoded_tree = decode_tree(bytes_of(*tree_body));-  if (!decoded_tree || decoded_tree->entries.size() != 1)-    return fail("tree round trip");--  std::vector<RawObject> objects;-  objects.push_back(RawObject{TYPE_TREE, *tree_body,-                              object_id(TYPE_TREE, bytes_of(*tree_body))});-  PackOutput pack = encode_pack(objects);-  auto decoded_pack = decode_pack(pack.pack);-  if (!decoded_pack)-    return fail("pack decode");-  auto decoded_index = decode_index(pack.index, decoded_pack->trailer);-  if (!decoded_index)-    return fail("index decode");-  if (decoded_index->ids.size() != 1)-    return fail("index count");--  info_prefix();-  std::cout << "self-test: ok\n";-  return 0;-}--// ----------------------------------------------------------------------------// inf-// -----------------------------------------------------------------------------struct ExtStat {-  std::string ext;-  std::uint64_t files = 0;-  std::uint64_t lines = 0;-  std::uint64_t bytes = 0;-};--struct AuthorStat {-  std::string name;-  std::uint64_t commits = 0;-};--std::uint64_t percent(std::uint64_t num, std::uint64_t total) {-  if (total == 0)-    return 0;-  return (num * 100 + total / 2) / total;-}--void print_percent(std::uint64_t pct) {-  if (pct < 10)-    std::cout << "  " << pct;-  else if (pct < 100)-    std::cout << " " << pct;-  else-    std::cout << pct;-}--Color color_for(std::size_t i) {-  static const Color colors[] = {Color::BrightCyan,   Color::BrightGreen,-                                 Color::BrightYellow, Color::BrightMagenta,-                                 Color::BrightBlue,   Color::BrightRed,-                                 Color::Cyan,         Color::Green};-  return colors[i % 8];-}--void print_bar(std::uint64_t num, std::uint64_t total, Color color) {-  std::uint64_t filled = 0;-  if (total > 0 && num > 0) {-    filled = (num * 24 + total / 2) / total;-    if (filled == 0)-      filled = 1;-    if (filled > 24)-      filled = 24;-  }-  for (std::uint64_t i = 0; i < filled; ++i)-    print_colored("\xe2\x96\x88", color, false, false);-  for (std::uint64_t i = filled; i < 24; ++i)-    print_colored("\xe2\x96\x91", Color::BrightBlack, false, false);-}--void print_left(std::string_view text, std::size_t width, Color color,-                bool dim) {-  if (dim)-    print_styled(text, color, true, false);-  else if (color == Color::Default)-    std::cout << text;-  else-    print_colored(text, color, false, false);-  for (std::size_t i = text.size(); i < width; ++i)-    std::cout << ' ';-}--void row_value(std::string_view label, std::string_view value) {-  print_left(label, 14, Color::Default, true);-  std::cout << value << "\n";-}--void row_number(std::string_view label, std::uint64_t value) {-  print_left(label, 14, Color::Default, true);-  std::cout << value << "\n";-}--std::string ext_of(std::string_view path) {-  std::size_t base_start = 0;-  for (std::size_t i = 0; i < path.size(); ++i) {-    if (path[i] == '/')-      base_start = i + 1;-  }-  std::optional<std::size_t> dot;-  for (std::size_t i = base_start; i < path.size(); ++i) {-    if (path[i] == '.')-      dot = i;-  }-  if (!dot || *dot <= base_start || *dot + 1 >= path.size())-    return "(none)";-  std::string out(path.substr(*dot));-  for (char &c : out) {-    if (c >= 'A' && c <= 'Z')-      c = static_cast<char>(c + 32);-  }-  return out;-}--bool looks_binary(Bytes data) {-  const std::size_t limit = std::min<std::size_t>(data.size(), 8192);-  for (std::size_t i = 0; i < limit; ++i)-    if (data[i] == 0)-      return true;-  return false;-}--std::uint64_t count_nonblank(Bytes data) {-  std::uint64_t count = 0;-  std::size_t i = 0;-  while (i < data.size()) {-    std::size_t end = i;-    while (end < data.size() && data[end] != '\n')-      ++end;-    bool blank = true;-    for (std::size_t j = i; j < end; ++j) {-      if (data[j] != ' ' && data[j] != '\t' && data[j] != '\r') {-        blank = false;-        break;-      }-    }-    if (!blank)-      ++count;-    i = end >= data.size() ? data.size() : end + 1;-  }-  return count;-}--void add_ext_stat(std::vector<ExtStat> &stats, std::string_view path,-                  std::uint64_t lines, std::uint64_t size) {-  const std::string ext = ext_of(path);-  for (auto &stat : stats) {-    if (stat.ext == ext) {-      ++stat.files;-      stat.lines += lines;-      stat.bytes += size;-      return;-    }-  }-  stats.push_back(ExtStat{ext, 1, lines, size});-}--std::uint64_t dir_size(const fs::path &path, std::size_t depth) {-  if (depth > 64)-    return 0;-  std::uint64_t total = 0;-  std::error_code ec;-  fs::recursive_directory_iterator it(path, ec);-  if (ec)-    return 0;-  for (const auto &entry : it) {-    if (entry.is_regular_file(ec)) {-      const auto size = entry.file_size(ec);-      if (!ec)-        total += size;-    }-  }-  return total;-}--void print_size(std::uint64_t n) {-  if (n >= 1073741824) {-    std::cout << n / 1073741824 << "." << ((n % 1073741824) * 10) / 1073741824-              << " GiB\n";-  } else if (n >= 1048576) {-    std::cout << n / 1048576 << "." << ((n % 1048576) * 10) / 1048576-              << " MiB\n";-  } else if (n >= 1024) {-    std::cout << n / 1024 << "." << ((n % 1024) * 10) / 1024 << " KiB\n";-  } else {-    std::cout << n << " B\n";-  }-}--void show_date(std::string_view label, std::int64_t seconds) {-  const std::string stamp = format_utc(seconds);-  print_left(label, 14, Color::Default, true);-  std::cout << stamp.substr(0, 10) << "\n";-}--int run_inf() {-  const auto root = open_repo();-  if (!root)-    return 1;-  Store store = Store::open_all(*root);-  auto view_opt = current_view(*root, store);-  View view = view_opt ? *view_opt : empty_view();-  const auto wc = working_copy_id(view);-  std::optional<Id> wc_tree;-  if (wc) {-    auto loaded = load_commit(store, *wc);-    if (loaded)-      wc_tree = loaded->commit.root_tree;-  }--  std::vector<ExtStat> exts;-  std::vector<AuthorStat> authors;-  std::uint64_t total_files = 0;-  std::uint64_t total_lines = 0;-  if (wc_tree) {-    for (const auto &entry : flatten_tree(store, *wc_tree)) {-      if (entry.kind != KIND_FILE && entry.kind != KIND_EXECUTABLE)-        continue;-      ++total_files;-      auto data = read_blob(store, entry.target);-      if (!data) {-        add_ext_stat(exts, entry.path, 0, 0);-        continue;-      }-      const std::uint64_t size = data->size();-      std::uint64_t lines = 0;-      if (!looks_binary(bytes_of(*data)))-        lines = count_nonblank(bytes_of(*data));-      total_lines += lines;-      add_ext_stat(exts, entry.path, lines, size);-    }-  }--  std::uint64_t commits = 0;-  bool has_time = false;-  std::int64_t created = 0;-  std::int64_t last = 0;-  const auto roots = view_roots(view);-  for (const auto &id : collect_commits(store, roots)) {-    auto loaded = load_commit(store, id);-    if (!loaded)-      continue;-    ++commits;-    const auto secs = loaded->commit.committer.seconds;-    if (!has_time) {-      created = secs;-      last = secs;-      has_time = true;-    } else {-      created = std::min(created, secs);-      last = std::max(last, secs);-    }-    std::string name = loaded->commit.author.name;-    if (name.empty())-      name = "(unknown)";-    bool found = false;-    for (auto &author : authors) {-      if (author.name == name) {-        ++author.commits;-        found = true;-        break;-      }-    }-    if (!found)-      authors.push_back(AuthorStat{name, 1});-  }--  std::cout << "\n";-  print_bold("Repository overview", Color::BrightCyan, false);-  std::cout << "\n\n";-  row_value("Project", basename_string(*root));-  print_left("HEAD", 14, Color::Default, true);-  if (wc)-    std::cout << short_hex(*wc) << "\n";-  else-    std::cout << "<none>\n";-  row_number("Changes", commits);-  row_number("Bookmarks", view.bookmarks.size());-  row_number("Tags", view.tags.size());-  row_number("Files", total_files);-  row_number("Lines", total_lines);-  row_number("Authors", authors.size());-  if (has_time) {-    show_date("Created", created);-    show_date("Last change", last);-  }-  print_left("Size", 14, Color::Default, true);-  print_size(dir_size(veins_dir(*root), 0));-  std::cout << "\n";--  print_bold("Languages", Color::BrightCyan, false);-  std::cout << "\n\n";-  if (exts.empty()) {-    std::cout << "  no tracked files\n";-  } else {-    std::stable_sort(exts.begin(), exts.end(),-                     [](const ExtStat &a, const ExtStat &b) {-                       if (a.lines != b.lines)-                         return a.lines > b.lines;-                       return compare(bytes_of(a.ext), bytes_of(b.ext)) < 0;-                     });-    std::size_t w_ext = 6;-    for (const auto &ext : exts)-      w_ext = std::max(w_ext, ext.ext.size());-    for (std::size_t i = 0; i < exts.size(); ++i) {-      const auto &ext = exts[i];-      print_left(ext.ext, w_ext, Color::Default, false);-      std::cout << "  ";-      print_bar(ext.lines, total_lines, color_for(i));-      std::cout << "  ";-      print_percent(percent(ext.lines, total_lines));-      std::cout << "%  " << ext.lines << " lines  " << ext.files << " files\n";-    }-  }-  std::cout << "\n";--  print_bold("Authors", Color::BrightCyan, false);-  std::cout << "\n\n";-  if (authors.empty()) {-    std::cout << "  no commits\n";-  } else {-    std::stable_sort(authors.begin(), authors.end(),-                     [](const AuthorStat &a, const AuthorStat &b) {-                       if (a.commits != b.commits)-                         return a.commits > b.commits;-                       return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                     });-    std::size_t w_name = 6;-    for (const auto &author : authors)-      w_name = std::max(w_name, author.name.size());-    for (std::size_t i = 0; i < authors.size(); ++i) {-      const auto &author = authors[i];-      print_left(author.name, w_name, Color::Cyan, false);-      std::cout << "  ";-      print_bar(author.commits, commits, color_for(i));-      std::cout << "  ";-      print_percent(percent(author.commits, commits));-      std::cout << "%  " << author.commits << " commits\n";-    }-  }-  std::cout << "\n";-  return 0;-}--// ----------------------------------------------------------------------------// Help-// -----------------------------------------------------------------------------void usage() {-  std::cout << "veins is a tool for managing source code\n";-  std::cout << "\n";-  std::cout << "subcommands:\n";-  std::cout << "  init         create a repository\n";-  std::cout << "  git          import from or export to git\n";-  std::cout << "  remote       manage native remotes\n";-  std::cout << "  clone        clone a repository over the native protocol\n";-  std::cout << "  fetch        fetch from a native remote\n";-  std::cout << "  push         push a bookmark to a native remote\n";-  std::cout << "  serve        run the native server over stdio or TLS\n";-  std::cout << "  key          manage local Ed25519 keys\n";-  std::cout << "  auth         remember keys for hosts and set a default\n";-  std::cout << "  access       manage a served repository's access file\n";-  std::cout << "  whoami       report the role granted by a server\n";-  std::cout << "  co           write a revision into the working directory; "-               "alias: checkout\n";-  std::cout << "  stat         show working-copy changes; alias: status\n";-  std::cout << "  ls           list tracked files\n";-  std::cout << "  inf          show a repository breakdown\n";-  std::cout << "  log          show commit history\n";-  std::cout << "  show         show a commit and its diff\n";-  std::cout << "  hash         print the commit hash for a revision\n";-  std::cout << "  diff         show a unified diff\n";-  std::cout << "  merge        create a merge commit; never fails\n";-  std::cout << "  rebase       rewrite changes onto a new parent\n";-  std::cout << "  xs           list conflicted paths\n";-  std::cout << "  resolve      resolve a conflicted path\n";-  std::cout << "  new          start a new change\n";-  std::cout << "  bmk          manage named branch pointers\n";-  std::cout << "  tag          manage named tags\n";-  std::cout << "  cfg          read and write configuration\n";-  std::cout-      << "  rm           untrack paths, keeping files on disk by default\n";-  std::cout << "  mv           move a tracked file and record the rename\n";-  std::cout << "  ex           add paths or globs to .vnexclude\n";-  std::cout << "  desc         set the working-copy commit message; alias: "-               "describe\n";-  std::cout-      << "  go           describe and start a new change; alias: commit\n";-  std::cout-      << "  amend        rewrite a revision's message and its descendants\n";-  std::cout << "  undo         restore the previous operation view\n";-  std::cout << "  op           operation log commands\n";-  std::cout << "  fsck         verify repository integrity\n";-  std::cout << "  self-test    run the format self-tests\n";-  std::cout << "  version      print version information\n";-  std::cout << "  bench-import compare lazy import metadata; requires git\n";-  std::cout << "  help         show help for a command\n";-  std::cout << "\n";-  std::cout << "run 'vn help <command>' for details\n";-}--void show_init() {-  std::cout << "usage: vn init [path] [-git-import:<gitdir>]\n\n";-  std::cout << "create a veins repository, optionally importing an existing "-               "git repository\n\n";-  std::cout << "arguments:\n";-  std::cout-      << "  [path]                    directory to create (default: .)\n\n";-  std::cout << "options:\n";-  std::cout << "  -git-import:<gitdir>      import from <gitdir> (a directory "-               "containing .git)\n";-}--void show_status() {-  std::cout << "usage: vn stat\n\n";-  std::cout << "show working-copy changes relative to the parent commit\n\n";-  std::cout << "aliases: status\n";-}--void show_ls() {-  std::cout << "usage: vn ls [rev] [-plain]\n\n";-  std::cout << "list tracked files as an ASCII tree\n\n";-  std::cout << "arguments:\n";-  std::cout << "  [rev]                     revision to list (default: @)\n\n";-  std::cout << "options:\n";-  std::cout << "  -rev <rev>                revision to list\n";-  std::cout << "  -plain, -p                print one tracked path per line\n";-}--void show_inf() {-  std::cout << "usage: vn inf\n\n";-  std::cout << "show a repository overview with a language breakdown by file "-               "extension,\n";-  std::cout-      << "line-of-code shares, author commit shares, and repository metadata\n";-}--void show_log() {-  std::cout << "usage: vn log [-rev <revset>] [-lN | -fN] [-no-col-titles]\n\n";-  std::cout << "show commit history, newest first\n\n";-  std::cout << "options:\n";-  std::cout << "  -rev <revset>             show only the given revision set\n";-  std::cout-      << "  -lN, -l <N>               show the last N commits (newest N)\n";-  std::cout-      << "  -fN, -f <N>               show the first N commits (oldest N)\n";-  std::cout << "  -no-col-titles            omit column titles\n";-}--void show_show() {-  std::cout << "usage: vn show [rev] [-no-col-titles]\n\n";-  std::cout-      << "show a commit's metadata and its diff against its first parent\n\n";-  std::cout << "arguments:\n";-  std::cout << "  [rev]                     revision to show (default: @)\n\n";-  std::cout << "options:\n";-  std::cout << "  -no-col-titles            omit the metadata labels\n";-}--void show_hash() {-  std::cout << "usage: vn hash [rev] [-short|-long]\n\n";-  std::cout << "print the commit hash for a revision\n\n";-  std::cout << "arguments:\n";-  std::cout << "  [rev]                     revision to hash (default: @)\n\n";-  std::cout << "options:\n";-  std::cout << "  -rev <rev>                revision to hash\n";-  std::cout << "  -short                    print the 12-character abbreviated "-               "hash\n";-  std::cout << "  -long                     print the full 64-character hash "-               "(default)\n";-}--void show_diff() {-  std::cout << "usage: vn diff [-rev <rev>] [<rev> <rev>]\n\n";-  std::cout << "show a unified diff\n";-}--void show_new() {-  std::cout << "usage: vn new [<rev>...]\n\n";-  std::cout-      << "start a new empty change on top of the working copy or a revision\n";-}--void show_describe() {-  std::cout << "usage: vn desc [-message <message>] [<message>]\n\n";-  std::cout << "set the working-copy commit message\n\n";-  std::cout << "aliases: describe\n";-}--void show_commit() {-  std::cout << "usage: vn go -message <message>\n\n";-  std::cout << "set the message and start a new change\n\n";-  std::cout << "a non-empty commit message is required\n\n";-  std::cout << "aliases: commit\n";-}--void show_amend() {-  std::cout << "usage: vn amend <rev> -m <message>\n\n";-  std::cout << "rewrite a revision's message and update its descendants\n\n";-  std::cout << "options:\n";-  std::cout << "  -m, -message <message>    new commit message\n\n";-  std::cout << "revisions reachable from a remote ref cannot be amended\n";-}--void show_checkout() {-  std::cout << "usage: vn co [rev]\n\n";-  std::cout << "write a revision into the working directory\n\n";-  std::cout << "aliases: checkout\n\n";-  std::cout << "arguments:\n";-  std::cout << "  [rev]                     revision to check out\n";-}--void show_fsck() {-  std::cout << "usage: vn fsck [path] [-verbose]\n\n";-  std::cout << "verify pack, index, object, and operation-log integrity\n\n";-  std::cout << "arguments:\n";-  std::cout-      << "  [path]                    repository to check (default: .)\n\n";-  std::cout << "options:\n";-  std::cout << "  -v, -verbose              print verbose output\n";-}--void show_selftest() {-  std::cout << "usage: vn self-test\n\n";-  std::cout << "run the format self-tests\n";-}--void show_version() {-  std::cout << "usage: vn version\n\n";-  std::cout << "print version information\n";-}--void show_help() {-  std::cout << "usage: vn help [command]\n\n";-  std::cout << "show help for the program or a command\n\n";-  std::cout << "arguments:\n";-  std::cout << "  [command]                 command to describe\n";-}--void show_bmk() {-  std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n\n";-  std::cout << "manage named, movable pointers to commits (branches)\n\n";-  std::cout << "subcommands:\n";-  std::cout-      << "  set <name> [-rev <rev>]   create or move a bookmark (default: @)\n";-  std::cout << "  mv <name> [-rev <rev>]    alias of set\n";-  std::cout << "  ls [-no-col-titles]       list bookmarks\n";-  std::cout << "  rm <name>                 delete a bookmark\n\n";-  std::cout << "examples:\n";-  std::cout << "  vn bmk set main\n";-  std::cout << "  vn new main\n";-  std::cout << "  vn co main\n";-}--void show_tag() {-  std::cout << "usage: vn tag <set|ls|rm|latest> ...\n\n";-  std::cout << "manage named pointers to commits (tags)\n\n";-  std::cout << "subcommands:\n";-  std::cout-      << "  set <name> [-rev <rev>]   create or move a tag (default: @)\n";-  std::cout << "  ls [-no-col-titles]       list tags\n";-  std::cout << "  rm <name>                 delete a tag\n";-  std::cout << "  latest                    print the latest tag name\n\n";-  std::cout << "the latest tag is the one whose target commit has the newest\n";-  std::cout << "committer timestamp; equal timestamps use natural name order\n";-}--void show_cfg() {-  std::cout << "usage: vn cfg [<key>] [<value>]\n";-  std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";-  std::cout << "       vn cfg -list\n";-  std::cout << "       vn cfg -unset <key>\n\n";-  std::cout << "read and write local repository configuration\n\n";-  std::cout << "  vn cfg                      list all keys\n";-  std::cout << "  vn cfg <key>                print a value\n";-  std::cout << "  vn cfg <key> <value>        set a value\n";-  std::cout << "  vn cfg -unset <key>         remove a key\n";-  std::cout << "  vn cfg -global ...          use the user config instead\n";-}--void show_rm() {-  std::cout << "usage: vn rm [-delete] <path>...\n\n";-  std::cout << "remove paths from the working-copy tree\n\n";-  std::cout << "files stay on disk by default. Arguments may be paths or globs "-               "and are\n";-  std::cout << "resolved relative to the current directory. Supported "-               "wildcards are\n";-  std::cout << "'*', '?', and '**'; '*' and '?' do not cross directory "-               "separators.\n\n";-  std::cout << "options:\n";-  std::cout << "  -delete                   delete matching files from disk "-               "after untracking\n";-}--void show_mv() {-  std::cout << "usage: vn mv <from> <to>\n\n";-  std::cout-      << "move a tracked file; the following snapshot records the rename\n";-}--void show_ex() {-  std::cout << "usage: vn ex <pattern>...\n\n";-  std::cout << "append ignore patterns to the repository root .vnexclude\n\n";-  std::cout << "patterns use gitignore syntax and are resolved relative to the "-               "current\n";-  std::cout << "directory. Quote wildcard patterns so the shell does not "-               "expand them:\n";-  std::cout << "  vn ex '*.dSYM'\n";-}--void show_undo() {-  std::cout << "usage: vn undo\n\n";-  std::cout-      << "record an operation that restores the previous operation view\n";-}--void show_op() {-  std::cout << "usage: vn op <log|restore|revert> [<op>]\n\n";-  std::cout << "inspect and restore operations\n";-}--void show_merge() {-  std::cout << "usage: vn merge <rev>...\n\n";-  std::cout << "create a merge commit from the working-copy commit and the "-               "revisions\n";-  std::cout-      << "the merge never fails; conflicts are stored as conflict values\n";-}--void show_rebase() {-  std::cout << "usage: vn rebase -s <rev> -d <rev>\n\n";-  std::cout << "rewrite the source change and its descendants onto the "-               "destination\n\n";-  std::cout << "options:\n";-  std::cout << "  -s, -source <rev>         first change to rewrite\n";-  std::cout << "  -d, -destination <rev>    new parent\n";-}--void show_xs() {-  std::cout << "usage: vn xs [-porcelain]\n\n";-  std::cout << "list conflicted paths and, for text conflicts, conflicting "-               "line ranges\n\n";-  std::cout << "porcelain columns (tab-separated):\n";-  std::cout << "  path, kind, base-ranges, ours-ranges, theirs-ranges\n";-}--void show_resolve() {-  std::cout-      << "usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...\n";-  std::cout << "       vn resolve -list\n\n";-  std::cout << "resolve conflicted paths. Without -take, the current file "-               "content is\n";-  std::cout << "recorded as the resolution. -tool substitutes $BASE, $OURS, "-               "$THEIRS,\n";-  std::cout << "and $OUTPUT in the command.\n";-}--void show_git() {-  std::cout << "usage: vn git <subcommand> [arguments]\n\n";-  std::cout << "git bridge commands:\n";-  std::cout << "  import [-source:<gitdir>] [path]\n";-  std::cout-      << "                            import reachable git commits and refs\n";-  std::cout-      << "  export [path]             export commits into the git mirror\n";-  std::cout << "  materialize [path]        replace lazy git blobs with stored "-               "blobs\n";-  std::cout-      << "  fetch [<remote>] [path]   git fetch into the mirror, then import\n";-  std::cout << "  push [<remote>] <bookmark> [path]\n";-  std::cout << "                            export and git push a bookmark\n";-  std::cout << "  remote <add|list|remove>  manage git remotes\n\n";-  std::cout << "run 'vn help git <subcommand>' for details\n";-}--void show_git_import() {-  std::cout << "usage: vn git import [-source:<gitdir>] [path]\n\n";-  std::cout << "import commits and refs reachable from a git repository\n\n";-  std::cout << "an empty working tree is checked out to the imported head\n\n";-  std::cout << "arguments:\n";-  std::cout << "  [path]                    veins repository (default: .)\n\n";-  std::cout << "options:\n";-  std::cout-      << "  -source:<gitdir>          source git root to mirror (a directory "-         "containing .git)\n";-}--void show_git_export() {-  std::cout << "usage: vn git export [path]\n\n";-  std::cout-      << "export commits reachable from bookmarks and tags into .veins/git\n";-}--void show_git_materialize() {-  std::cout << "usage: vn git materialize [path]\n\n";-  std::cout << "replace lazy git-backed blobs with canonical stored blobs.\n";-  std::cout << "rewrites affected trees, commits, and refs and records one "-               "operation\n";-}--void show_unimplemented(std::string_view command) {-  std::cout << "usage: vn " << command << "\n\n";-  std::cout << "this command is planned for a later stage of the C++ rewrite\n";-  std::cout << "and is not available in the current local-core build\n";-}--int run_help(const std::vector<std::string> &args) {-  if (args.size() <= 2) {-    usage();-    return 0;-  }-  const std::string &cmd = args[2];-  if (cmd == "init")-    show_init();-  else if (cmd == "stat" || cmd == "status")-    show_status();-  else if (cmd == "ls")-    show_ls();-  else if (cmd == "inf")-    show_inf();-  else if (cmd == "log")-    show_log();-  else if (cmd == "show")-    show_show();-  else if (cmd == "hash")-    show_hash();-  else if (cmd == "diff")-    show_diff();-  else if (cmd == "new")-    show_new();-  else if (cmd == "desc" || cmd == "describe")-    show_describe();-  else if (cmd == "go" || cmd == "commit")-    show_commit();-  else if (cmd == "amend")-    show_amend();-  else if (cmd == "co" || cmd == "checkout")-    show_checkout();-  else if (cmd == "fsck")-    show_fsck();-  else if (cmd == "bmk")-    show_bmk();-  else if (cmd == "tag")-    show_tag();-  else if (cmd == "cfg")-    show_cfg();-  else if (cmd == "rm")-    show_rm();-  else if (cmd == "mv")-    show_mv();-  else if (cmd == "ex")-    show_ex();-  else if (cmd == "undo")-    show_undo();-  else if (cmd == "op")-    show_op();-  else if (cmd == "merge")-    show_merge();-  else if (cmd == "rebase")-    show_rebase();-  else if (cmd == "xs")-    show_xs();-  else if (cmd == "resolve")-    show_resolve();-  else if (cmd == "self-test")-    show_selftest();-  else if (cmd == "version")-    show_version();-  else if (cmd == "help")-    show_help();-  else if (net_help(cmd)) {-  } else if (cmd == "git") {-    if (args.size() > 3) {-      const std::string &sub = args[3];-      if (sub == "import")-        show_git_import();-      else if (sub == "export")-        show_git_export();-      else if (sub == "materialize")-        show_git_materialize();-      else if (sub == "fetch")-        std::cout << "usage: vn git fetch [<remote>] [path]\n";-      else if (sub == "push")-        std::cout << "usage: vn git push [<remote>] <bookmark> [path]\n";-      else if (sub == "remote")-        std::cout << "usage: vn git remote <add|list|remove> ...\n";-      else {-        error_prefix();-        std::cout << "unknown git subcommand: " << sub << "\n";-        return 1;-      }-    } else {-      show_git();-    }-  } else if (cmd == "bench-import")-    show_unimplemented(cmd);-  else {-    usage();-    error_prefix();-    std::cout << "unknown command: " << cmd << "\n";-    return 1;-  }-  return 0;-}--} // namespace--int cli_run(const std::vector<std::string> &args) {-  install_promisor_fetcher();-  if (args.size() < 2) {-    usage();-    return 1;-  }-  const std::string &cmd = args[1];-  if (cmd == "init")-    return run_init(args);-  if (cmd == "stat" || cmd == "status")-    return run_status();-  if (cmd == "ls")-    return run_ls(args);-  if (cmd == "inf")-    return run_inf();-  if (cmd == "log")-    return run_log(args);-  if (cmd == "show")-    return run_show(args);-  if (cmd == "hash")-    return run_hash(args);-  if (cmd == "diff")-    return run_diff(args);-  if (cmd == "new")-    return run_new(args);-  if (cmd == "desc" || cmd == "describe")-    return run_describe(args);-  if (cmd == "go" || cmd == "commit")-    return run_commit(args);-  if (cmd == "amend")-    return run_amend(args);-  if (cmd == "co" || cmd == "checkout")-    return run_checkout(args);-  if (cmd == "bmk")-    return bmk_run(args);-  if (cmd == "tag")-    return tag_run(args);-  if (cmd == "cfg" || cmd == "config")-    return cfg_run(args);-  if (cmd == "rm")-    return rm_run(args);-  if (cmd == "mv")-    return mv_run(args);-  if (cmd == "ex")-    return ex_run(args);-  if (cmd == "op")-    return op_run(args);-  if (cmd == "undo")-    return undo_run(args);-  if (cmd == "merge")-    return merge_run(args);-  if (cmd == "rebase")-    return rebase_run(args);-  if (cmd == "xs")-    return xs_run(args);-  if (cmd == "resolve")-    return resolve_run(args);-  if (cmd == "fsck")-    return run_fsck(args);-  if (cmd == "self-test")-    return run_self_test();-  if (cmd == "version" || cmd == "-version") {-    std::cout << "veins v" << VN_VERSION << " (veins-store 1)\n";-    return 0;-  }-  if (cmd == "help" || cmd == "-help" || cmd == "-h")-    return run_help(args);--  if (cmd == "remote")-    return remote_run(args);-  if (cmd == "clone")-    return clone_run(args);-  if (cmd == "fetch")-    return fetch_run(args);-  if (cmd == "push")-    return push_run(args);-  if (cmd == "serve")-    return serve_run(args);-  if (cmd == "key")-    return key_run(args);-  if (cmd == "auth")-    return auth_run(args);-  if (cmd == "access")-    return access_run(args);-  if (cmd == "whoami")-    return whoami_run(args);--  if (cmd == "git")-    return git_cli_run(args);-  if (cmd == "bench-import") {-    error_prefix();-    std::cout << "command '" << cmd << "' is not available in this stage\n";-    return 1;-  }-  usage();-  error_prefix();-  std::cout << "unknown command: " << cmd << "\n";-  return 1;+    return !arg.empty() && arg.front() == '-';+}++std::optional<fs::path> open_repo() {+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return std::nullopt;+    }+    return root;+}++std::string join_args(const std::vector<std::string>& parts) {+    std::string out;+    for (std::size_t i = 0; i < parts.size(); ++i) {+        if (i != 0)+            out.push_back(' ');+        out += parts[i];+    }+    return out;+}++bool message_is_blank(const std::vector<std::string>& parts) {+    for (const auto& part : parts) {+        for (char c : part) {+            if (c != ' ' && c != '\t' && c != '\n' && c != '\r')+                return false;+        }+    }+    return true;+}++Result<std::vector<std::string>> parse_message(const std::vector<std::string>& args,+                                               std::size_t start) {+    std::vector<std::string> parts;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-m" || arg == "-message")) {+            if (i + 1 < args.size()) {+                parts.push_back(args[++i]);+            } else {+                error_prefix();+                std::cout << arg << " requires a message\n";+                return fail_usage("missing message");+            }+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return fail_usage("unknown flag");+        } else {+            parts.push_back(arg);+        }+    }+    return parts;+}++void print_cell(std::string_view text, std::size_t width, Color color, bool dim) {+    if (dim) {+        print_styled(text, color, true, false);+    } else if (color == Color::Default) {+        std::cout << text;+    } else {+        print_colored(text, color, false, false);+    }+    for (std::size_t i = text.size(); i < width; ++i)+        std::cout << ' ';+}++void print_gap() {+    std::cout << "  ";+}++std::string first_line(const std::string& message) {+    const std::size_t newline = message.find('\n');+    return newline == std::string::npos ? message : message.substr(0, newline);+}++std::string short_hex(const Id& id) {+    return hex_encode(id).substr(0, 12);+}++std::string short_change_id(const std::vector<std::string>& ids, std::size_t index) {+    const std::string& target = ids[index];+    std::size_t len = std::min<std::size_t>(4, target.size());+    while (len < target.size()) {+        const std::string_view prefix(target.data(), len);+        bool unique = true;+        for (std::size_t j = 0; j < ids.size(); ++j) {+            if (j == index)+                continue;+            if (ids[j] == target)+                continue;+            if (ids[j].starts_with(prefix)) {+                unique = false;+                break;+            }+        }+        if (unique)+            break;+        ++len;+    }+    return target.substr(0, len);+}++// ---------------------------------------------------------------------------+// Diff rendering+// ---------------------------------------------------------------------------++struct DiffOp {+    char tag = ' ';+    std::size_t ai = 0;+    std::size_t bi = 0;+};++std::vector<std::string> split_lines(Bytes data) {+    std::vector<std::string> out;+    std::size_t start = 0;+    for (std::size_t i = 0; i < data.size(); ++i) {+        if (data[i] == '\n') {+            out.emplace_back(reinterpret_cast<const char*>(data.data() + start), i - start);+            start = i + 1;+        }+    }+    if (start < data.size()) {+        out.emplace_back(reinterpret_cast<const char*>(data.data() + start), data.size() - start);+    } else if (!data.empty() && data.back() == '\n') {+        // A trailing newline does not introduce an extra empty line.+    } else if (data.empty()) {+        // No lines.+    }+    return out;+}++std::vector<DiffOp> build_ops_lcs(const std::vector<std::string>& a,+                                  const std::vector<std::string>& b) {+    const std::size_t n = a.size();+    const std::size_t m = b.size();+    const std::size_t cols = m + 1;+    std::vector<std::uint32_t> dp((n + 1) * cols, 0);+    for (std::size_t i = 1; i <= n; ++i) {+        for (std::size_t j = 1; j <= m; ++j) {+            if (a[i - 1] == b[j - 1])+                dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;+            else+                dp[i * cols + j] = std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);+        }+    }+    std::vector<DiffOp> ops;+    std::size_t i = n;+    std::size_t j = m;+    while (i > 0 || j > 0) {+        if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) {+            ops.push_back(DiffOp{' ', i - 1, j - 1});+            --i;+            --j;+        } else if (j > 0 && (i == 0 || dp[i * cols + (j - 1)] >= dp[(i - 1) * cols + j])) {+            ops.push_back(DiffOp{'+', 0, j - 1});+            --j;+        } else {+            ops.push_back(DiffOp{'-', i - 1, 0});+            --i;+        }+    }+    std::reverse(ops.begin(), ops.end());+    return ops;+}++std::vector<DiffOp> build_ops_myers(const std::vector<std::string>& a,+                                    const std::vector<std::string>& b) {+    const int n = static_cast<int>(a.size());+    const int m = static_cast<int>(b.size());+    const int max_d = n + m;+    const int offset = max_d;+    std::vector<int> v(static_cast<std::size_t>(2 * max_d + 1), 0);+    std::vector<std::vector<int>> trace;+    constexpr std::size_t trace_cap = 64u * 1024u * 1024u;+    int found_d = -1;+    for (int d = 0; d <= max_d; ++d) {+        if (static_cast<std::size_t>(trace.size() + 1) * v.size() * sizeof(int) > trace_cap)+            return {};+        trace.push_back(v);+        for (int k = -d; k <= d; k += 2) {+            int x = 0;+            if (k == -d || (k != d && v[static_cast<std::size_t>(offset + k - 1)] <+                                          v[static_cast<std::size_t>(offset + k + 1)]))+                x = v[static_cast<std::size_t>(offset + k + 1)];+            else+                x = v[static_cast<std::size_t>(offset + k - 1)] + 1;+            int y = x - k;+            while (x < n && y < m &&+                   a[static_cast<std::size_t>(x)] == b[static_cast<std::size_t>(y)]) {+                ++x;+                ++y;+            }+            v[static_cast<std::size_t>(offset + k)] = x;+            if (x >= n && y >= m) {+                found_d = d;+                break;+            }+        }+        if (found_d >= 0)+            break;+    }+    if (found_d < 0)+        return {};+    std::vector<DiffOp> ops;+    int x = n;+    int y = m;+    for (int d = found_d; d >= 0; --d) {+        const auto& prev = trace[static_cast<std::size_t>(d)];+        const int k = x - y;+        int prev_k = 0;+        if (k == -d || (k != d && prev[static_cast<std::size_t>(offset + k - 1)] <+                                      prev[static_cast<std::size_t>(offset + k + 1)]))+            prev_k = k + 1;+        else+            prev_k = k - 1;+        const int prev_x = prev[static_cast<std::size_t>(offset + prev_k)];+        const int prev_y = prev_x - prev_k;+        while (x > prev_x && y > prev_y) {+            ops.push_back(+                DiffOp{' ', static_cast<std::size_t>(x - 1), static_cast<std::size_t>(y - 1)});+            --x;+            --y;+        }+        if (d > 0) {+            if (x == prev_x) {+                ops.push_back(DiffOp{'+', 0, static_cast<std::size_t>(y - 1)});+                --y;+            } else {+                ops.push_back(DiffOp{'-', static_cast<std::size_t>(x - 1), 0});+                --x;+            }+        }+    }+    std::reverse(ops.begin(), ops.end());+    return ops;+}++std::vector<DiffOp> build_ops_fallback(const std::vector<std::string>& a,+                                       const std::vector<std::string>& b) {+    std::size_t prefix = 0;+    while (prefix < a.size() && prefix < b.size() && a[prefix] == b[prefix])+        ++prefix;+    std::size_t suffix = 0;+    while (suffix < a.size() - prefix && suffix < b.size() - prefix &&+           a[a.size() - 1 - suffix] == b[b.size() - 1 - suffix])+        ++suffix;+    std::vector<DiffOp> ops;+    for (std::size_t i = 0; i < prefix; ++i)+        ops.push_back(DiffOp{' ', i, i});+    for (std::size_t i = prefix; i < a.size() - suffix; ++i)+        ops.push_back(DiffOp{'-', i, 0});+    for (std::size_t j = prefix; j < b.size() - suffix; ++j)+        ops.push_back(DiffOp{'+', 0, j});+    for (std::size_t k = 0; k < suffix; ++k) {+        const std::size_t i = a.size() - suffix + k;+        const std::size_t j = b.size() - suffix + k;+        ops.push_back(DiffOp{' ', i, j});+    }+    return ops;+}++std::vector<DiffOp> build_ops(const std::vector<std::string>& a,+                              const std::vector<std::string>& b) {+    const std::size_t n = a.size();+    const std::size_t m = b.size();+    if (n == 0 && m == 0)+        return {};+    if (n != 0 && m != 0 && n <= 2048 && m <= 2048)+        return build_ops_lcs(a, b);+    if (n != 0 && m != 0 && n * m <= 4'000'000)+        return build_ops_lcs(a, b);+    auto myers = build_ops_myers(a, b);+    if (!myers.empty())+        return myers;+    return build_ops_fallback(a, b);+}++void render_unified(const std::vector<std::string>& a, const std::vector<std::string>& b) {+    const auto ops = build_ops(a, b);+    std::vector<std::size_t> changes;+    for (std::size_t i = 0; i < ops.size(); ++i) {+        if (ops[i].tag != ' ')+            changes.push_back(i);+    }+    constexpr std::size_t context = 3;+    std::size_t pos = 0;+    std::size_t old_seen = 0;+    std::size_t new_seen = 0;+    std::size_t ci = 0;+    while (ci < changes.size()) {+        const std::size_t first = changes[ci];+        std::size_t start = first > context ? first - context : 0;+        std::size_t last = first;+        ++ci;+        while (ci < changes.size() && changes[ci] <= last + context * 2) {+            last = changes[ci];+            ++ci;+        }+        std::size_t end = std::min(last + context + 1, ops.size());+        while (pos < start) {+            const auto& op = ops[pos];+            if (op.tag == ' ') {+                ++old_seen;+                ++new_seen;+            } else if (op.tag == '-') {+                ++old_seen;+            } else {+                ++new_seen;+            }+            ++pos;+        }+        std::size_t old_count = 0;+        std::size_t new_count = 0;+        for (std::size_t e = start; e < end; ++e) {+            if (ops[e].tag == ' ') {+                ++old_count;+                ++new_count;+            } else if (ops[e].tag == '-') {+                ++old_count;+            } else {+                ++new_count;+            }+        }+        const std::size_t old_start = old_seen + (old_count > 0 ? 1 : 0);+        const std::size_t new_start = new_seen + (new_count > 0 ? 1 : 0);+        std::cout << "@@ -" << old_start << "," << old_count << " +" << new_start << ","+                  << new_count << " @@\n";+        while (pos < end) {+            const auto& op = ops[pos];+            if (op.tag == ' ') {+                std::cout << " " << a[op.ai] << "\n";+                ++old_seen;+                ++new_seen;+            } else if (op.tag == '-') {+                print_colored("-", Color::Red, false, false);+                print_colored(a[op.ai], Color::Red, false, false);+                std::cout << "\n";+                ++old_seen;+            } else {+                print_colored("+", Color::Green, false, false);+                print_colored(b[op.bi], Color::Green, false, false);+                std::cout << "\n";+                ++new_seen;+            }+            ++pos;+        }+    }+}++bool contains_nul(Bytes data) {+    const std::size_t limit = std::min<std::size_t>(data.size(), 8192);+    for (std::size_t i = 0; i < limit; ++i) {+        if (data[i] == 0)+            return true;+    }+    return false;+}++void render_diff(Store& store, std::optional<Id> old_tree, std::optional<Id> new_tree,+                 bool announce_no_diff) {+    const auto changes = compare_trees(store, old_tree, new_tree);+    for (const auto& change : changes) {+        if (change.new_kind == KIND_CONFLICT) {+            std::cout << "Conflict: " << change.path << "\n";+            continue;+        }+        std::vector<std::uint8_t> old_data;+        std::vector<std::uint8_t> new_data;+        if (change.old_kind != KIND_MISSING && change.old_id) {+            if (auto data = read_blob(store, *change.old_id))+                old_data = std::move(*data);+        }+        if (change.new_kind != KIND_MISSING && change.new_id) {+            if (auto data = read_blob(store, *change.new_id))+                new_data = std::move(*data);+        }+        if (contains_nul(bytes_of(old_data)) || contains_nul(bytes_of(new_data))) {+            std::cout << "Binary files a/" << change.path << " and b/" << change.path+                      << " differ\n";+            continue;+        }+        print_colored("--- ", Color::Red, false, false);+        if (change.old_kind == KIND_MISSING) {+            print_colored("/dev/null", Color::Red, false, false);+        } else {+            print_colored("a/", Color::Red, false, false);+            print_colored(change.path, Color::Red, false, false);+        }+        std::cout << "\n";+        print_colored("+++ ", Color::Green, false, false);+        if (change.new_kind == KIND_MISSING) {+            print_colored("/dev/null", Color::Green, false, false);+        } else {+            print_colored("b/", Color::Green, false, false);+            print_colored(change.path, Color::Green, false, false);+        }+        std::cout << "\n";+        const auto a = split_lines(bytes_of(old_data));+        const auto b = split_lines(bytes_of(new_data));+        render_unified(a, b);+    }+    if (announce_no_diff && changes.empty()) {+        info_prefix();+        std::cout << "no diff to show\n";+    }+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++int run_init(const std::vector<std::string>& args) {+    std::string path = ".";+    std::optional<std::string> source;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && arg.rfind("-git-import:", 0) == 0) {+            source = arg.substr(12);+            if (source->empty()) {+                error_prefix();+                std::cout << "-git-import: requires a path\n";+                return 1;+            }+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            path = arg;+        }+    }+    const auto initialized = init_repo(path_from_bytes(path));+    if (!initialized) {+        error_prefix();+        std::cout << "init failed with code " << initialized.error().offset << "\n";+        return 1;+    }+    info_prefix();+    std::cout << "initialized veins repository at " << path_display(*initialized) << "\n";+    if (source) {+        const int prepared = git_prepare_mirror(*initialized, *source);+        if (prepared != 0) {+            error_prefix();+            if (prepared == 2) {+                std::cout << "-git-import: " << *source+                          << " is not a git repository root (expected the directory "+                             "containing .git)\n";+            } else {+                std::cout << "cannot prepare git mirror from " << *source << " (code " << prepared+                          << ")\n";+            }+            return 1;+        }+        return git_import(*initialized);+    }+    return 0;+}++int run_status() {+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    const auto wc = working_copy_id(*view);+    if (!wc) {+        info_prefix();+        std::cout << "working copy clean\n";+        return 0;+    }+    std::optional<Id> old_tree;+    std::optional<Id> new_tree;+    auto wc_body = store.read_body(*wc, TYPE_COMMIT);+    if (!wc_body) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    auto wc_commit = decode_commit(bytes_of(*wc_body));+    if (!wc_commit) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    new_tree = wc_commit->root_tree;+    if (!wc_commit->parents.empty()) {+        auto parent_body = store.read_body(wc_commit->parents.front(), TYPE_COMMIT);+        if (parent_body) {+            auto parent_commit = decode_commit(bytes_of(*parent_body));+            if (parent_commit)+                old_tree = parent_commit->root_tree;+        }+    }+    const auto changes = compare_trees(store, old_tree, new_tree);+    std::size_t conflicts = 0;+    for (const auto& change : changes) {+        if (change.old_kind == KIND_MISSING) {+            print_colored("A", Color::BrightGreen, false, false);+            std::cout << " " << change.path << "\n";+        } else if (change.new_kind == KIND_MISSING) {+            print_colored("D", Color::Red, false, false);+            std::cout << " " << change.path << "\n";+        } else if (change.new_kind == KIND_CONFLICT) {+            print_colored("C", Color::BrightRed, false, false);+            std::cout << " " << change.path << "\n";+            ++conflicts;+        } else {+            print_colored("M", Color::Cyan, false, false);+            std::cout << " " << change.path << "\n";+        }+    }+    if (changes.empty()) {+        info_prefix();+        std::cout << "working copy clean\n";+    }+    if (conflicts > 0)+        std::cout << conflicts << " conflict(s)\n";++    const std::vector<Id> start{*wc};+    const auto ancestry = collect_commits(store, start);+    std::size_t conflicted_commits = 0;+    for (const auto& id : ancestry) {+        auto loaded = load_commit(store, id);+        if (loaded && tree_conflicted(store, loaded->commit.root_tree))+            ++conflicted_commits;+    }+    if (conflicted_commits > 0)+        std::cout << conflicted_commits << " conflicted commit(s) in ancestry\n";+    return 0;+}++int run_log(const std::vector<std::string>& args) {+    std::string rev;+    bool col_titles = true;+    bool end_flags = false;+    std::optional<std::size_t> limit;+    bool first = false;+    auto parse_count = [](std::string_view text, std::size_t& out) -> bool {+        if (text.empty())+            return false;+        std::size_t value = 0;+        for (char c : text) {+            if (c < '0' || c > '9')+                return false;+            value = value * 10 + static_cast<std::size_t>(c - '0');+        }+        if (value == 0)+            return false;+        out = value;+        return true;+    };+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            rev = args[++i];+        } else if (!end_flags && arg == "-no-col-titles") {+            col_titles = false;+        } else if (!end_flags && (arg == "-l" || arg == "-f")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a count\n";+                return 1;+            }+            std::size_t count = 0;+            if (!parse_count(args[++i], count)) {+                error_prefix();+                std::cout << arg << " requires a positive count\n";+                return 1;+            }+            limit = count;+            first = arg == "-f";+        } else if (!end_flags && arg.size() > 2 &&+                   (arg[0] == '-' && (arg[1] == 'l' || arg[1] == 'f'))) {+            std::size_t count = 0;+            if (!parse_count(std::string_view(arg).substr(2), count)) {+                error_prefix();+                std::cout << "invalid log count: " << arg << "\n";+                return 1;+            }+            limit = count;+            first = arg[1] == 'f';+        } else if (!end_flags && arg.size() > 1 && (arg[0] == 'l' || arg[0] == 'f')) {+            std::size_t count = 0;+            if (parse_count(std::string_view(arg).substr(1), count)) {+                limit = count;+                first = arg[0] == 'f';+            } else {+                rev = arg;+            }+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            rev = arg;+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    const auto wc = working_copy_id(*view);+    std::vector<Id> ids;+    if (rev.empty() || rev == "all()") {+        const auto roots = view_roots(*view);+        ids = collect_commits(store, roots);+    } else if (auto one = resolve_revision(store, *view, rev)) {+        const std::vector<Id> start{*one};+        ids = collect_commits(store, start);+    }++    struct Rec {+        Id id{};+        std::string change;+        std::int64_t seconds = 0;+        std::string message;+        std::string author;+        bool conflicted = false;+        bool has_changes = false;+    };+    std::vector<Rec> recs;+    for (const auto& id : ids) {+        auto loaded = load_commit(store, id);+        if (!loaded)+            continue;+        Rec rec;+        rec.id = id;+        rec.change = base32_encode(loaded->commit.change_id);+        rec.seconds = loaded->commit.committer.seconds;+        rec.message = first_line(loaded->commit.message);+        rec.author = loaded->commit.author.name;+        rec.conflicted = tree_conflicted(store, loaded->commit.root_tree);+        if (wc && std::memcmp(wc->data(), id.data(), ID_LEN) == 0)+            rec.has_changes = has_changes(store, *loaded);+        recs.push_back(std::move(rec));+    }+    std::stable_sort(recs.begin(), recs.end(),+                     [](const Rec& a, const Rec& b) { return a.seconds > b.seconds; });++    if (limit) {+        if (first) {+            if (recs.size() > *limit)+                recs.erase(recs.begin(), recs.end() - static_cast<std::ptrdiff_t>(*limit));+            std::reverse(recs.begin(), recs.end());+        } else if (recs.size() > *limit) {+            recs.resize(*limit);+        }+    }++    std::vector<std::string> change_ids;+    for (const auto& rec : recs)+        change_ids.push_back(rec.change);+    std::size_t w_commit = 12;+    std::size_t w_change = 6;+    std::size_t w_date = 19;+    std::size_t w_author = 6;+    for (std::size_t i = 0; i < recs.size(); ++i) {+        const auto cid = short_change_id(change_ids, i);+        w_change = std::max(w_change, cid.size());+        w_author = std::max(w_author, recs[i].author.size());+    }+    if (col_titles) {+        print_cell("", 1, Color::Default, false);+        std::cout << " ";+        print_cell("Commit", w_commit, Color::Default, false);+        print_gap();+        print_cell("Change", w_change, Color::Default, false);+        print_gap();+        print_cell("Date", w_date, Color::Default, false);+        print_gap();+        print_cell("Author", w_author, Color::Default, false);+        print_gap();+        std::cout << "Message\n";+    }+    for (std::size_t i = 0; i < recs.size(); ++i) {+        const auto& rec = recs[i];+        const bool is_wc = wc && std::memcmp(wc->data(), rec.id.data(), ID_LEN) == 0;+        std::string marker = is_wc ? "@" : " ";+        Color marker_color = Color::Default;+        if (is_wc)+            marker_color = rec.has_changes ? Color::BrightCyan : Color::Red;+        const auto cid = short_change_id(change_ids, i);+        const auto stamp = format_utc(rec.seconds);+        print_cell(marker, 1, marker_color, false);+        std::cout << " ";+        print_cell(short_hex(rec.id), w_commit, Color::Red, false);+        print_gap();+        print_cell(cid, w_change, Color::Red, false);+        print_gap();+        print_cell(stamp, w_date, Color::Cyan, true);+        print_gap();+        print_cell(rec.author, w_author, Color::Cyan, false);+        print_gap();+        if (!rec.message.empty())+            print_colored(rec.message, Color::Green, false, false);+        else+            print_colored("<unset>", Color::BrightBlack, false, false);+        for (const auto& name : bookmark_names(*view, rec.id))+            std::cout << " [" << name << "]";+        for (const auto& name : tag_names(*view, rec.id))+            std::cout << " <" << name << ">";+        if (rec.conflicted)+            std::cout << " (conflicted)";+        bool divergent = false;+        for (std::size_t j = 0; j < recs.size(); ++j) {+            if (j != i && recs[j].change == rec.change) {+                divergent = true;+                break;+            }+        }+        if (divergent)+            std::cout << " (divergent)";+        std::cout << "\n";+    }+    return 0;+}++int run_show(const std::vector<std::string>& args) {+    std::string rev;+    bool col_titles = true;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            rev = args[++i];+        } else if (!end_flags && arg == "-no-col-titles") {+            col_titles = false;+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            rev = arg;+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    auto target = resolve_revision(store, *view, rev);+    if (!target) {+        error_prefix();+        if (rev.empty())+            std::cout << "no working-copy commit\n";+        else+            std::cout << "unknown revision: " << rev << "\n";+        return 1;+    }+    auto loaded = load_commit(store, *target);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read commit\n";+        return 1;+    }+    if (col_titles) {+        std::cout << "commit   " << hex_encode(*target) << "\n";+        std::cout << "change   " << base32_encode(loaded->commit.change_id) << "\n";+        std::cout << "author   " << loaded->commit.author.name << " <"+                  << loaded->commit.author.email << ">\n";+        std::cout << "date     " << format_utc(loaded->commit.committer.seconds) << "\n";+        std::cout << "parents  ";+        if (loaded->commit.parents.empty()) {+            std::cout << "<none>";+        } else {+            for (std::size_t i = 0; i < loaded->commit.parents.size(); ++i) {+                if (i != 0)+                    std::cout << " ";+                std::cout << short_hex(loaded->commit.parents[i]);+            }+        }+        std::cout << "\n";+        const auto names = bookmark_names(*view, *target);+        if (!names.empty()) {+            std::cout << "bookmarks";+            for (const auto& name : names)+                std::cout << " [" << name << "]";+            std::cout << "\n";+        }+        std::cout << "\n";+        if (!loaded->commit.message.empty())+            std::cout << loaded->commit.message << "\n";+        else+            std::cout << "<unset>\n";+        std::cout << "\n";+    }+    std::optional<Id> old_tree;+    if (!loaded->commit.parents.empty()) {+        auto parent = load_commit(store, loaded->commit.parents.front());+        if (parent)+            old_tree = parent->commit.root_tree;+    }+    render_diff(store, old_tree, loaded->commit.root_tree, false);+    return 0;+}++int run_hash(const std::vector<std::string>& args) {+    std::string rev;+    bool short_hash = false;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && arg == "-short") {+            short_hash = true;+        } else if (!end_flags && arg == "-long") {+            short_hash = false;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            rev = args[++i];+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            rev = arg;+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    auto target = resolve_revision(store, *view, rev);+    if (!target) {+        error_prefix();+        if (rev.empty())+            std::cout << "no working-copy commit\n";+        else+            std::cout << "unknown revision: " << rev << "\n";+        return 1;+    }+    const auto hex = hex_encode(*target);+    std::cout << hex.substr(0, short_hash ? 12 : 64) << "\n";+    return 0;+}++bool print_tree(const fs::path& root, Store& store, const Id& tree_id, const std::string& prefix,+                std::size_t depth) {+    if (depth > 4096)+        return false;+    auto body = store.read_body(tree_id, TYPE_TREE);+    if (!body)+        return false;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return false;+    for (std::size_t i = 0; i < tree->entries.size(); ++i) {+        const auto& entry = tree->entries[i];+        const bool last = i + 1 == tree->entries.size();+        std::cout << prefix << (last ? "`-- " : "|-- ") << entry.name << "\n";+        if (entry.kind == KIND_SUBTREE) {+            if (!print_tree(root, store, entry.target, prefix + (last ? "    " : "|   "),+                            depth + 1))+                return false;+        }+    }+    return true;+}++int run_ls(const std::vector<std::string>& args) {+    std::string rev;+    bool plain = false;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-plain" || arg == "-p")) {+            plain = true;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            rev = args[++i];+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            rev = arg;+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    auto target = resolve_revision(store, *view, rev);+    if (!target) {+        error_prefix();+        if (rev.empty())+            std::cout << "no working-copy commit\n";+        else+            std::cout << "unknown revision: " << rev << "\n";+        return 1;+    }+    auto loaded = load_commit(store, *target);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read commit\n";+        return 1;+    }+    bool good = true;+    if (plain) {+        auto entries = flatten_tree_checked(store, loaded->commit.root_tree);+        if (!entries) {+            good = false;+        } else {+            for (const auto& entry : *entries)+                std::cout << entry.path << "\n";+        }+    } else {+        std::cout << ".\n";+        good = print_tree(*root, store, loaded->commit.root_tree, "", 0);+    }+    if (!good) {+        error_prefix();+        std::cout << "cannot read tree\n";+        return 1;+    }+    return 0;+}++int run_diff(const std::vector<std::string>& args) {+    std::vector<std::string> revs;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            revs.push_back(args[++i]);+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            revs.push_back(arg);+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    std::optional<Id> old_tree;+    std::optional<Id> new_tree;+    bool failed = false;+    auto tree_of = [&](const Id& id) -> std::optional<Id> {+        auto loaded = load_commit(store, id);+        if (!loaded)+            return std::nullopt;+        return loaded->commit.root_tree;+    };+    auto parent_tree_of = [&](const Id& id) -> std::optional<Id> {+        auto loaded = load_commit(store, id);+        if (!loaded || loaded->commit.parents.empty())+            return std::nullopt;+        auto parent = load_commit(store, loaded->commit.parents.front());+        if (!parent)+            return std::nullopt;+        return parent->commit.root_tree;+    };+    if (revs.size() >= 2) {+        auto a = resolve_revision(store, *view, revs[0]);+        auto b = resolve_revision(store, *view, revs[1]);+        if (!a || !b)+            failed = true;+        else {+            old_tree = tree_of(*a);+            new_tree = tree_of(*b);+        }+    } else if (revs.size() == 1) {+        auto a = resolve_revision(store, *view, revs[0]);+        if (!a)+            failed = true;+        else {+            old_tree = parent_tree_of(*a);+            new_tree = tree_of(*a);+        }+    } else {+        const auto wc = working_copy_id(*view);+        if (wc) {+            old_tree = parent_tree_of(*wc);+            new_tree = tree_of(*wc);+        }+    }+    if (failed) {+        error_prefix();+        std::cout << "unknown revision\n";+        return 1;+    }+    render_diff(store, old_tree, new_tree, true);+    return 0;+}++int run_new(const std::vector<std::string>& args) {+    std::vector<std::string> revs;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            revs.push_back(arg);+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    std::optional<Id> old_root;+    std::vector<Id> parents;+    std::optional<Id> root_tree;+    if (revs.empty()) {+        if (!wc) {+            error_prefix();+            std::cout << "no working-copy commit\n";+            return 1;+        }+        auto loaded = load_commit(store, *wc);+        if (!loaded) {+            error_prefix();+            std::cout << "cannot read working-copy commit\n";+            return 1;+        }+        parents.push_back(*wc);+        root_tree = loaded->commit.root_tree;+        old_root = root_tree;+    } else {+        for (std::size_t i = 0; i < revs.size(); ++i) {+            auto resolved = resolve_revision(store, tx->view(), revs[i]);+            if (!resolved) {+                error_prefix();+                std::cout << "unknown revision\n";+                return 1;+            }+            parents.push_back(*resolved);+            if (i == 0) {+                auto loaded = load_commit(store, *resolved);+                if (!loaded) {+                    error_prefix();+                    std::cout << "unknown revision\n";+                    return 1;+                }+                root_tree = loaded->commit.root_tree;+            }+        }+        if (wc) {+            auto old_loaded = load_commit(store, *wc);+            if (old_loaded)+                old_root = old_loaded->commit.root_tree;+        }+    }+    const Sig sig = identity_signature(*root);+    Commit commit;+    commit.version = 1;+    commit.parents = parents;+    commit.root_tree = *root_tree;+    commit.change_id = random_change_id();+    commit.author = sig;+    commit.committer = sig;+    commit.message = "";+    commit.renames_state = RENAMES_RECORDED;+    const auto encoded = encode_commit(commit);+    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+    if (wc)+        remove_head(tx->view(), *wc);+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view());+    const auto status = tx->finish("new");+    if (!status)+        return 1;+    store.refresh(*root);+    (void)mark_native(*root, new_id);+    if (!revs.empty()) {+        const int materialized = checkout_materialize_commit(*root, store, old_root, *root_tree);+        if (materialized != 0)+            return materialized;+    }+    return 0;+}++int describe_impl(const fs::path& root, Store& store, const std::vector<std::string>& parts,+                  bool require_changes) {+    const int snap = snapshot_run(root, store);+    if (snap != 0)+        return snap;+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    if (!wc) {+        error_prefix();+        std::cout << "no working-copy commit\n";+        return 1;+    }+    auto loaded = load_commit(store, *wc);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read working-copy commit\n";+        return 1;+    }+    const std::string message = join_args(parts);+    const bool changed = has_changes(store, *loaded);+    const bool same_message = message == loaded->commit.message;+    if (!changed && (require_changes || same_message)) {+        if (require_changes) {+            info_prefix();+            std::cout << "nothing to commit, working copy clean\n";+            return 2;+        }+        return 0;+    }+    const Sig sig = identity_signature(root);+    Commit commit = loaded->commit;+    commit.committer = sig;+    if (!changed)+        commit.author = sig;+    commit.message = message;+    const auto encoded = encode_commit(commit);+    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+    remove_head(tx->view(), *wc);+    move_bookmarks(tx->view(), *wc, new_id);+    if (auto current = current_bookmark_name(root)) {+        if (find_bookmark(tx->view(), *current))+            set_bookmark_target(tx->view(), *current, new_id);+    }+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view());+    const auto status = tx->finish("describe");+    if (!status)+        return 1;+    store.refresh(root);+    (void)mark_native(root, new_id);+    return 0;+}++int run_describe(const std::vector<std::string>& args) {+    auto parsed = parse_message(args, 2);+    if (!parsed)+        return 1;+    const auto root = open_repo();+    if (!root)+        return 1;+    Store store = Store::open_all(*root);+    return describe_impl(*root, store, *parsed, false);+}++int run_commit(const std::vector<std::string>& args) {+    auto parsed = parse_message(args, 2);+    if (!parsed)+        return 1;+    if (message_is_blank(*parsed)) {+        error_prefix();+        std::cout << "commit requires a non-empty message (-message)\n";+        return 1;+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    Store store = Store::open_all(*root);+    const int described = describe_impl(*root, store, *parsed, true);+    if (described == 2)+        return 0;+    if (described != 0)+        return described;++    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    if (!wc) {+        error_prefix();+        std::cout << "no working-copy commit\n";+        return 1;+    }+    auto loaded = load_commit(store, *wc);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read working-copy commit\n";+        return 1;+    }+    const Sig sig = identity_signature(*root);+    Commit commit;+    commit.version = 1;+    commit.parents = {*wc};+    commit.root_tree = loaded->commit.root_tree;+    commit.change_id = random_change_id();+    commit.author = sig;+    commit.committer = sig;+    commit.message = "";+    commit.renames_state = RENAMES_RECORDED;+    const auto encoded = encode_commit(commit);+    const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+    remove_head(tx->view(), *wc);+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view());+    const auto status = tx->finish("new");+    if (!status)+        return 1;+    (void)mark_native(*root, new_id);+    return 0;+}++std::optional<Id> mapped_id(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,+                            const Id& id) {+    for (std::size_t i = 0; i < old_ids.size(); ++i) {+        if (std::memcmp(old_ids[i].data(), id.data(), ID_LEN) == 0)+            return new_ids[i];+    }+    return std::nullopt;+}++void remap_ids(const std::vector<Id>& old_ids, const std::vector<Id>& new_ids,+               std::vector<std::optional<Id>>& ids) {+    for (auto& id : ids) {+        if (!id)+            continue;+        if (auto mapped = mapped_id(old_ids, new_ids, *id))+            id = *mapped;+    }+}++int run_amend(const std::vector<std::string>& args) {+    std::string rev;+    std::vector<std::string> parts;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-m" || arg == "-message")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a message\n";+                return 1;+            }+            parts.push_back(args[++i]);+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (rev.empty()) {+            rev = arg;+        } else {+            parts.push_back(arg);+        }+    }+    if (rev.empty()) {+        error_prefix();+        std::cout << "amend requires a revision\n";+        return 1;+    }+    if (message_is_blank(parts)) {+        error_prefix();+        std::cout << "amend requires a non-empty message (-message)\n";+        return 1;+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    auto target = resolve_revision(store, tx->view(), rev);+    if (!target) {+        error_prefix();+        std::cout << "unknown revision\n";+        return 1;+    }+    std::vector<Id> pushed_roots;+    for (const auto& ref : tx->view().remote_refs)+        pushed_roots.push_back(ref.target);+    if (!pushed_roots.empty() && contains_id(collect_commits(store, pushed_roots), *target)) {+        error_prefix();+        std::cout << "cannot amend a revision that has been pushed\n";+        return 1;+    }+    auto target_loaded = load_commit(store, *target);+    if (!target_loaded) {+        error_prefix();+        std::cout << "cannot read revision\n";+        return 1;+    }+    const std::string message = join_args(parts);+    if (target_loaded->commit.message == message) {+        info_prefix();+        std::cout << "message unchanged\n";+        return 0;+    }+    auto remaining = all_commits(store, tx->view());+    std::vector<Id> old_ids;+    std::vector<Id> new_ids;+    const Sig sig = identity_signature(*root);+    bool target_rewritten = false;+    bool failed = false;+    while (!remaining.empty() && !failed) {+        std::optional<std::size_t> ready;+        for (std::size_t i = 0; i < remaining.size(); ++i) {+            bool is_ready = std::memcmp(remaining[i].data(), target->data(), ID_LEN) == 0;+            if (!is_ready) {+                auto loaded = load_commit(store, remaining[i]);+                if (loaded) {+                    for (const auto& parent : loaded->commit.parents) {+                        if (contains_id(old_ids, parent)) {+                            is_ready = true;+                            break;+                        }+                    }+                }+            }+            if (is_ready) {+                ready = i;+                break;+            }+        }+        if (!ready)+            break;+        const Id chosen = remaining[*ready];+        auto loaded = load_commit(store, chosen);+        if (!loaded) {+            failed = true;+            break;+        }+        std::vector<Id> new_parents;+        for (const auto& parent : loaded->commit.parents) {+            if (auto mapped = mapped_id(old_ids, new_ids, parent))+                new_parents.push_back(*mapped);+            else+                new_parents.push_back(parent);+        }+        Commit commit = loaded->commit;+        commit.parents = new_parents;+        commit.committer = sig;+        if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)+            commit.message = message;+        const auto encoded = encode_commit(commit);+        const Id new_id = tx->add_object(TYPE_COMMIT, encoded);+        old_ids.push_back(chosen);+        new_ids.push_back(new_id);+        if (std::memcmp(chosen.data(), target->data(), ID_LEN) == 0)+            target_rewritten = true;+        remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(*ready));+    }+    if (failed || !target_rewritten) {+        error_prefix();+        std::cout << "cannot amend revision\n";+        return 1;+    }+    for (auto& bookmark : tx->view().bookmarks) {+        remap_ids(old_ids, new_ids, bookmark.targets.adds);+        remap_ids(old_ids, new_ids, bookmark.targets.removes);+    }+    for (auto& tag : tx->view().tags) {+        if (auto mapped = mapped_id(old_ids, new_ids, tag.target))+            tag.target = *mapped;+    }+    for (auto& workspace : tx->view().working_copies) {+        if (auto mapped = mapped_id(old_ids, new_ids, workspace.target))+            workspace.target = *mapped;+    }+    for (auto& ref : tx->view().remote_refs) {+        if (auto mapped = mapped_id(old_ids, new_ids, ref.target))+            ref.target = *mapped;+    }+    rebuild_heads(tx->view());+    const auto status = tx->finish("amend " + rev);+    if (!status)+        return 1;+    for (const auto& id : new_ids)+        (void)mark_native(*root, id);+    return 0;+}++int run_checkout(const std::vector<std::string>& args) {+    std::string rev;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (rev.empty()) {+            rev = arg;+        }+    }+    const auto root = open_repo();+    if (!root)+        return 1;+    return checkout_run(*root, rev);+}++int run_fsck(const std::vector<std::string>& args) {+    std::string path = ".";+    bool verbose = false;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-v" || arg == "-verbose")) {+            verbose = true;+        } else if (!end_flags && is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            path = arg;+        }+    }+    const auto root = discover_repo(path_from_bytes(path));+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository: " << path << "\n";+        return 1;+    }+    return fsck_repository(*root, verbose);+}++int run_self_test() {+    auto fail = [](std::string_view why) {+        error_prefix();+        std::cout << "self-test: failed: " << why << "\n";+        return 1;+    };+    const auto empty_hash = blake3_hash(Bytes{});+    const std::string expected_empty =+        "af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262";+    if (hex_encode(Bytes(empty_hash.data(), empty_hash.size())) != expected_empty)+        return fail("blake3 vector");+    const auto& gear = fastcdc_gear();+    if (gear[0] != 0xf8447b379cdadcd5ull || gear[1] != 0xbe63d125aec8ca6dull)+        return fail("fastcdc gear table");++    BlobBuild build = build_blob(bytes_of(std::string("hello world")));+    if (!build.objects.empty()) {+        auto body = build.objects.back().body;+        auto decoded = decode_blob(bytes_of(body));+        if (!decoded || decoded->form != BlobForm::Inline)+            return fail("blob round trip");+    }+    Tree tree;+    tree.entries.push_back(TreeEntry{"a.txt", KIND_FILE, build.root});+    auto tree_body = encode_tree(tree.entries);+    if (!tree_body)+        return fail("tree encode");+    auto decoded_tree = decode_tree(bytes_of(*tree_body));+    if (!decoded_tree || decoded_tree->entries.size() != 1)+        return fail("tree round trip");++    std::vector<RawObject> objects;+    objects.push_back(RawObject{TYPE_TREE, *tree_body, object_id(TYPE_TREE, bytes_of(*tree_body))});+    PackOutput pack = encode_pack(objects);+    auto decoded_pack = decode_pack(pack.pack);+    if (!decoded_pack)+        return fail("pack decode");+    auto decoded_index = decode_index(pack.index, decoded_pack->trailer);+    if (!decoded_index)+        return fail("index decode");+    if (decoded_index->ids.size() != 1)+        return fail("index count");++    info_prefix();+    std::cout << "self-test: ok\n";+    return 0;+}++// ---------------------------------------------------------------------------+// inf+// ---------------------------------------------------------------------------++struct ExtStat {+    std::string ext;+    std::uint64_t files = 0;+    std::uint64_t lines = 0;+    std::uint64_t bytes = 0;+};++struct AuthorStat {+    std::string name;+    std::uint64_t commits = 0;+};++std::uint64_t percent(std::uint64_t num, std::uint64_t total) {+    if (total == 0)+        return 0;+    return (num * 100 + total / 2) / total;+}++void print_percent(std::uint64_t pct) {+    if (pct < 10)+        std::cout << "  " << pct;+    else if (pct < 100)+        std::cout << " " << pct;+    else+        std::cout << pct;+}++Color color_for(std::size_t i) {+    static const Color colors[] = {Color::BrightCyan,    Color::BrightGreen, Color::BrightYellow,+                                   Color::BrightMagenta, Color::BrightBlue,  Color::BrightRed,+                                   Color::Cyan,          Color::Green};+    return colors[i % 8];+}++void print_bar(std::uint64_t num, std::uint64_t total, Color color) {+    std::uint64_t filled = 0;+    if (total > 0 && num > 0) {+        filled = (num * 24 + total / 2) / total;+        if (filled == 0)+            filled = 1;+        if (filled > 24)+            filled = 24;+    }+    for (std::uint64_t i = 0; i < filled; ++i)+        print_colored("\xe2\x96\x88", color, false, false);+    for (std::uint64_t i = filled; i < 24; ++i)+        print_colored("\xe2\x96\x91", Color::BrightBlack, false, false);+}++void print_left(std::string_view text, std::size_t width, Color color, bool dim) {+    if (dim)+        print_styled(text, color, true, false);+    else if (color == Color::Default)+        std::cout << text;+    else+        print_colored(text, color, false, false);+    for (std::size_t i = text.size(); i < width; ++i)+        std::cout << ' ';+}++void row_value(std::string_view label, std::string_view value) {+    print_left(label, 14, Color::Default, true);+    std::cout << value << "\n";+}++void row_number(std::string_view label, std::uint64_t value) {+    print_left(label, 14, Color::Default, true);+    std::cout << value << "\n";+}++std::string ext_of(std::string_view path) {+    std::size_t base_start = 0;+    for (std::size_t i = 0; i < path.size(); ++i) {+        if (path[i] == '/')+            base_start = i + 1;+    }+    std::optional<std::size_t> dot;+    for (std::size_t i = base_start; i < path.size(); ++i) {+        if (path[i] == '.')+            dot = i;+    }+    if (!dot || *dot <= base_start || *dot + 1 >= path.size())+        return "(none)";+    std::string out(path.substr(*dot));+    for (char& c : out) {+        if (c >= 'A' && c <= 'Z')+            c = static_cast<char>(c + 32);+    }+    return out;+}++bool looks_binary(Bytes data) {+    const std::size_t limit = std::min<std::size_t>(data.size(), 8192);+    for (std::size_t i = 0; i < limit; ++i)+        if (data[i] == 0)+            return true;+    return false;+}++std::uint64_t count_nonblank(Bytes data) {+    std::uint64_t count = 0;+    std::size_t i = 0;+    while (i < data.size()) {+        std::size_t end = i;+        while (end < data.size() && data[end] != '\n')+            ++end;+        bool blank = true;+        for (std::size_t j = i; j < end; ++j) {+            if (data[j] != ' ' && data[j] != '\t' && data[j] != '\r') {+                blank = false;+                break;+            }+        }+        if (!blank)+            ++count;+        i = end >= data.size() ? data.size() : end + 1;+    }+    return count;+}++void add_ext_stat(std::vector<ExtStat>& stats, std::string_view path, std::uint64_t lines,+                  std::uint64_t size) {+    const std::string ext = ext_of(path);+    for (auto& stat : stats) {+        if (stat.ext == ext) {+            ++stat.files;+            stat.lines += lines;+            stat.bytes += size;+            return;+        }+    }+    stats.push_back(ExtStat{ext, 1, lines, size});+}++std::uint64_t dir_size(const fs::path& path, std::size_t depth) {+    if (depth > 64)+        return 0;+    std::uint64_t total = 0;+    std::error_code ec;+    fs::recursive_directory_iterator it(path, ec);+    if (ec)+        return 0;+    for (const auto& entry : it) {+        if (entry.is_regular_file(ec)) {+            const auto size = entry.file_size(ec);+            if (!ec)+                total += size;+        }+    }+    return total;+}++void print_size(std::uint64_t n) {+    if (n >= 1073741824) {+        std::cout << n / 1073741824 << "." << ((n % 1073741824) * 10) / 1073741824 << " GiB\n";+    } else if (n >= 1048576) {+        std::cout << n / 1048576 << "." << ((n % 1048576) * 10) / 1048576 << " MiB\n";+    } else if (n >= 1024) {+        std::cout << n / 1024 << "." << ((n % 1024) * 10) / 1024 << " KiB\n";+    } else {+        std::cout << n << " B\n";+    }+}++void show_date(std::string_view label, std::int64_t seconds) {+    const std::string stamp = format_utc(seconds);+    print_left(label, 14, Color::Default, true);+    std::cout << stamp.substr(0, 10) << "\n";+}++int run_inf() {+    const auto root = open_repo();+    if (!root)+        return 1;+    Store store = Store::open_all(*root);+    auto view_opt = current_view(*root, store);+    View view = view_opt ? *view_opt : empty_view();+    const auto wc = working_copy_id(view);+    std::optional<Id> wc_tree;+    if (wc) {+        auto loaded = load_commit(store, *wc);+        if (loaded)+            wc_tree = loaded->commit.root_tree;+    }++    std::vector<ExtStat> exts;+    std::vector<AuthorStat> authors;+    std::uint64_t total_files = 0;+    std::uint64_t total_lines = 0;+    if (wc_tree) {+        for (const auto& entry : flatten_tree(store, *wc_tree)) {+            if (entry.kind != KIND_FILE && entry.kind != KIND_EXECUTABLE)+                continue;+            ++total_files;+            auto data = read_blob(store, entry.target);+            if (!data) {+                add_ext_stat(exts, entry.path, 0, 0);+                continue;+            }+            const std::uint64_t size = data->size();+            std::uint64_t lines = 0;+            if (!looks_binary(bytes_of(*data)))+                lines = count_nonblank(bytes_of(*data));+            total_lines += lines;+            add_ext_stat(exts, entry.path, lines, size);+        }+    }++    std::uint64_t commits = 0;+    bool has_time = false;+    std::int64_t created = 0;+    std::int64_t last = 0;+    const auto roots = view_roots(view);+    for (const auto& id : collect_commits(store, roots)) {+        auto loaded = load_commit(store, id);+        if (!loaded)+            continue;+        ++commits;+        const auto secs = loaded->commit.committer.seconds;+        if (!has_time) {+            created = secs;+            last = secs;+            has_time = true;+        } else {+            created = std::min(created, secs);+            last = std::max(last, secs);+        }+        std::string name = loaded->commit.author.name;+        if (name.empty())+            name = "(unknown)";+        bool found = false;+        for (auto& author : authors) {+            if (author.name == name) {+                ++author.commits;+                found = true;+                break;+            }+        }+        if (!found)+            authors.push_back(AuthorStat{name, 1});+    }++    std::cout << "\n";+    print_bold("Repository overview", Color::BrightCyan, false);+    std::cout << "\n\n";+    row_value("Project", basename_string(*root));+    print_left("HEAD", 14, Color::Default, true);+    if (wc)+        std::cout << short_hex(*wc) << "\n";+    else+        std::cout << "<none>\n";+    row_number("Changes", commits);+    row_number("Bookmarks", view.bookmarks.size());+    row_number("Tags", view.tags.size());+    row_number("Files", total_files);+    row_number("Lines", total_lines);+    row_number("Authors", authors.size());+    if (has_time) {+        show_date("Created", created);+        show_date("Last change", last);+    }+    print_left("Size", 14, Color::Default, true);+    print_size(dir_size(veins_dir(*root), 0));+    std::cout << "\n";++    print_bold("Languages", Color::BrightCyan, false);+    std::cout << "\n\n";+    if (exts.empty()) {+        std::cout << "  no tracked files\n";+    } else {+        std::stable_sort(exts.begin(), exts.end(), [](const ExtStat& a, const ExtStat& b) {+            if (a.lines != b.lines)+                return a.lines > b.lines;+            return compare(bytes_of(a.ext), bytes_of(b.ext)) < 0;+        });+        std::size_t w_ext = 6;+        for (const auto& ext : exts)+            w_ext = std::max(w_ext, ext.ext.size());+        for (std::size_t i = 0; i < exts.size(); ++i) {+            const auto& ext = exts[i];+            print_left(ext.ext, w_ext, Color::Default, false);+            std::cout << "  ";+            print_bar(ext.lines, total_lines, color_for(i));+            std::cout << "  ";+            print_percent(percent(ext.lines, total_lines));+            std::cout << "%  " << ext.lines << " lines  " << ext.files << " files\n";+        }+    }+    std::cout << "\n";++    print_bold("Authors", Color::BrightCyan, false);+    std::cout << "\n\n";+    if (authors.empty()) {+        std::cout << "  no commits\n";+    } else {+        std::stable_sort(authors.begin(), authors.end(),+                         [](const AuthorStat& a, const AuthorStat& b) {+                             if (a.commits != b.commits)+                                 return a.commits > b.commits;+                             return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                         });+        std::size_t w_name = 6;+        for (const auto& author : authors)+            w_name = std::max(w_name, author.name.size());+        for (std::size_t i = 0; i < authors.size(); ++i) {+            const auto& author = authors[i];+            print_left(author.name, w_name, Color::Cyan, false);+            std::cout << "  ";+            print_bar(author.commits, commits, color_for(i));+            std::cout << "  ";+            print_percent(percent(author.commits, commits));+            std::cout << "%  " << author.commits << " commits\n";+        }+    }+    std::cout << "\n";+    return 0;+}++// ---------------------------------------------------------------------------+// Help+// ---------------------------------------------------------------------------++void usage() {+    std::cout << "veins is a tool for managing source code\n";+    std::cout << "\n";+    std::cout << "subcommands:\n";+    std::cout << "  init         create a repository\n";+    std::cout << "  git          import from or export to git\n";+    std::cout << "  remote       manage native remotes\n";+    std::cout << "  clone        clone a repository over the native protocol\n";+    std::cout << "  fetch        fetch from a native remote\n";+    std::cout << "  push         push a bookmark to a native remote\n";+    std::cout << "  serve        run the native server over stdio or TLS\n";+    std::cout << "  key          manage local Ed25519 keys\n";+    std::cout << "  auth         remember keys for hosts and set a default\n";+    std::cout << "  access       manage a served repository's access file\n";+    std::cout << "  whoami       report the role granted by a server\n";+    std::cout << "  co           write a revision into the working directory; "+                 "alias: checkout\n";+    std::cout << "  stat         show working-copy changes; alias: status\n";+    std::cout << "  ls           list tracked files\n";+    std::cout << "  inf          show a repository breakdown\n";+    std::cout << "  log          show commit history\n";+    std::cout << "  show         show a commit and its diff\n";+    std::cout << "  hash         print the commit hash for a revision\n";+    std::cout << "  diff         show a unified diff\n";+    std::cout << "  merge        create a merge commit; never fails\n";+    std::cout << "  rebase       rewrite changes onto a new parent\n";+    std::cout << "  xs           list conflicted paths\n";+    std::cout << "  resolve      resolve a conflicted path\n";+    std::cout << "  new          start a new change\n";+    std::cout << "  bmk          manage named branch pointers\n";+    std::cout << "  tag          manage named tags\n";+    std::cout << "  cfg          read and write configuration\n";+    std::cout << "  rm           untrack paths, keeping files on disk by default\n";+    std::cout << "  mv           move a tracked file and record the rename\n";+    std::cout << "  ex           add paths or globs to .vnexclude\n";+    std::cout << "  desc         set the working-copy commit message; alias: "+                 "describe\n";+    std::cout << "  go           describe and start a new change; alias: commit\n";+    std::cout << "  amend        rewrite a revision's message and its descendants\n";+    std::cout << "  undo         restore the previous operation view\n";+    std::cout << "  op           operation log commands\n";+    std::cout << "  fsck         verify repository integrity\n";+    std::cout << "  self-test    run the format self-tests\n";+    std::cout << "  version      print version information\n";+    std::cout << "  bench-import compare lazy import metadata; requires git\n";+    std::cout << "  help         show help for a command\n";+    std::cout << "\n";+    std::cout << "run 'vn help <command>' for details\n";+}++void show_init() {+    std::cout << "usage: vn init [path] [-git-import:<gitdir>]\n\n";+    std::cout << "create a veins repository, optionally importing an existing "+                 "git repository\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [path]                    directory to create (default: .)\n\n";+    std::cout << "options:\n";+    std::cout << "  -git-import:<gitdir>      import from <gitdir> (a directory "+                 "containing .git)\n";+}++void show_status() {+    std::cout << "usage: vn stat\n\n";+    std::cout << "show working-copy changes relative to the parent commit\n\n";+    std::cout << "aliases: status\n";+}++void show_ls() {+    std::cout << "usage: vn ls [rev] [-plain]\n\n";+    std::cout << "list tracked files as an ASCII tree\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [rev]                     revision to list (default: @)\n\n";+    std::cout << "options:\n";+    std::cout << "  -rev <rev>                revision to list\n";+    std::cout << "  -plain, -p                print one tracked path per line\n";+}++void show_inf() {+    std::cout << "usage: vn inf\n\n";+    std::cout << "show a repository overview with a language breakdown by file "+                 "extension,\n";+    std::cout << "line-of-code shares, author commit shares, and repository metadata\n";+}++void show_log() {+    std::cout << "usage: vn log [-rev <revset>] [-lN | -fN] [-no-col-titles]\n\n";+    std::cout << "show commit history, newest first\n\n";+    std::cout << "options:\n";+    std::cout << "  -rev <revset>             show only the given revision set\n";+    std::cout << "  -lN, -l <N>               show the last N commits (newest N)\n";+    std::cout << "  -fN, -f <N>               show the first N commits (oldest N)\n";+    std::cout << "  -no-col-titles            omit column titles\n";+}++void show_show() {+    std::cout << "usage: vn show [rev] [-no-col-titles]\n\n";+    std::cout << "show a commit's metadata and its diff against its first parent\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [rev]                     revision to show (default: @)\n\n";+    std::cout << "options:\n";+    std::cout << "  -no-col-titles            omit the metadata labels\n";+}++void show_hash() {+    std::cout << "usage: vn hash [rev] [-short|-long]\n\n";+    std::cout << "print the commit hash for a revision\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [rev]                     revision to hash (default: @)\n\n";+    std::cout << "options:\n";+    std::cout << "  -rev <rev>                revision to hash\n";+    std::cout << "  -short                    print the 12-character abbreviated "+                 "hash\n";+    std::cout << "  -long                     print the full 64-character hash "+                 "(default)\n";+}++void show_diff() {+    std::cout << "usage: vn diff [-rev <rev>] [<rev> <rev>]\n\n";+    std::cout << "show a unified diff\n";+}++void show_new() {+    std::cout << "usage: vn new [<rev>...]\n\n";+    std::cout << "start a new empty change on top of the working copy or a revision\n";+}++void show_describe() {+    std::cout << "usage: vn desc [-message <message>] [<message>]\n\n";+    std::cout << "set the working-copy commit message\n\n";+    std::cout << "aliases: describe\n";+}++void show_commit() {+    std::cout << "usage: vn go -message <message>\n\n";+    std::cout << "set the message and start a new change\n\n";+    std::cout << "a non-empty commit message is required\n\n";+    std::cout << "aliases: commit\n";+}++void show_amend() {+    std::cout << "usage: vn amend <rev> -m <message>\n\n";+    std::cout << "rewrite a revision's message and update its descendants\n\n";+    std::cout << "options:\n";+    std::cout << "  -m, -message <message>    new commit message\n\n";+    std::cout << "revisions reachable from a remote ref cannot be amended\n";+}++void show_checkout() {+    std::cout << "usage: vn co [rev]\n\n";+    std::cout << "write a revision into the working directory\n\n";+    std::cout << "aliases: checkout\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [rev]                     revision to check out\n";+}++void show_fsck() {+    std::cout << "usage: vn fsck [path] [-verbose]\n\n";+    std::cout << "verify pack, index, object, and operation-log integrity\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [path]                    repository to check (default: .)\n\n";+    std::cout << "options:\n";+    std::cout << "  -v, -verbose              print verbose output\n";+}++void show_selftest() {+    std::cout << "usage: vn self-test\n\n";+    std::cout << "run the format self-tests\n";+}++void show_version() {+    std::cout << "usage: vn version\n\n";+    std::cout << "print version information\n";+}++void show_help() {+    std::cout << "usage: vn help [command]\n\n";+    std::cout << "show help for the program or a command\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [command]                 command to describe\n";+}++void show_bmk() {+    std::cout << "usage: vn bmk <set|mv|ls|rm> ...\n\n";+    std::cout << "manage named, movable pointers to commits (branches)\n\n";+    std::cout << "subcommands:\n";+    std::cout << "  set <name> [-rev <rev>]   create or move a bookmark (default: @)\n";+    std::cout << "  mv <name> [-rev <rev>]    alias of set\n";+    std::cout << "  ls [-no-col-titles]       list bookmarks\n";+    std::cout << "  rm <name>                 delete a bookmark\n\n";+    std::cout << "examples:\n";+    std::cout << "  vn bmk set main\n";+    std::cout << "  vn new main\n";+    std::cout << "  vn co main\n";+}++void show_tag() {+    std::cout << "usage: vn tag <set|ls|rm|latest> ...\n\n";+    std::cout << "manage named pointers to commits (tags)\n\n";+    std::cout << "subcommands:\n";+    std::cout << "  set <name> [-rev <rev>]   create or move a tag (default: @)\n";+    std::cout << "  ls [-no-col-titles]       list tags\n";+    std::cout << "  rm <name>                 delete a tag\n";+    std::cout << "  latest                    print the latest tag name\n\n";+    std::cout << "the latest tag is the one whose target commit has the newest\n";+    std::cout << "committer timestamp; equal timestamps use natural name order\n";+}++void show_cfg() {+    std::cout << "usage: vn cfg [<key>] [<value>]\n";+    std::cout << "       vn cfg [<get|set|unset|list>] [<key>] [<value>]\n";+    std::cout << "       vn cfg -list\n";+    std::cout << "       vn cfg -unset <key>\n\n";+    std::cout << "read and write local repository configuration\n\n";+    std::cout << "  vn cfg                      list all keys\n";+    std::cout << "  vn cfg <key>                print a value\n";+    std::cout << "  vn cfg <key> <value>        set a value\n";+    std::cout << "  vn cfg -unset <key>         remove a key\n";+    std::cout << "  vn cfg -global ...          use the user config instead\n";+}++void show_rm() {+    std::cout << "usage: vn rm [-delete] <path>...\n\n";+    std::cout << "remove paths from the working-copy tree\n\n";+    std::cout << "files stay on disk by default. Arguments may be paths or globs "+                 "and are\n";+    std::cout << "resolved relative to the current directory. Supported "+                 "wildcards are\n";+    std::cout << "'*', '?', and '**'; '*' and '?' do not cross directory "+                 "separators.\n\n";+    std::cout << "options:\n";+    std::cout << "  -delete                   delete matching files from disk "+                 "after untracking\n";+}++void show_mv() {+    std::cout << "usage: vn mv <from> <to>\n\n";+    std::cout << "move a tracked file; the following snapshot records the rename\n";+}++void show_ex() {+    std::cout << "usage: vn ex <pattern>...\n\n";+    std::cout << "append ignore patterns to the repository root .vnexclude\n\n";+    std::cout << "patterns use gitignore syntax and are resolved relative to the "+                 "current\n";+    std::cout << "directory. Quote wildcard patterns so the shell does not "+                 "expand them:\n";+    std::cout << "  vn ex '*.dSYM'\n";+}++void show_undo() {+    std::cout << "usage: vn undo\n\n";+    std::cout << "record an operation that restores the previous operation view\n";+}++void show_op() {+    std::cout << "usage: vn op <log|restore|revert> [<op>]\n\n";+    std::cout << "inspect and restore operations\n";+}++void show_merge() {+    std::cout << "usage: vn merge <rev>...\n\n";+    std::cout << "create a merge commit from the working-copy commit and the "+                 "revisions\n";+    std::cout << "the merge never fails; conflicts are stored as conflict values\n";+}++void show_rebase() {+    std::cout << "usage: vn rebase -s <rev> -d <rev>\n\n";+    std::cout << "rewrite the source change and its descendants onto the "+                 "destination\n\n";+    std::cout << "options:\n";+    std::cout << "  -s, -source <rev>         first change to rewrite\n";+    std::cout << "  -d, -destination <rev>    new parent\n";+}++void show_xs() {+    std::cout << "usage: vn xs [-porcelain]\n\n";+    std::cout << "list conflicted paths and, for text conflicts, conflicting "+                 "line ranges\n\n";+    std::cout << "porcelain columns (tab-separated):\n";+    std::cout << "  path, kind, base-ranges, ours-ranges, theirs-ranges\n";+}++void show_resolve() {+    std::cout << "usage: vn resolve [-take ours|theirs|base] [-tool <cmd>] <path>...\n";+    std::cout << "       vn resolve -list\n\n";+    std::cout << "resolve conflicted paths. Without -take, the current file "+                 "content is\n";+    std::cout << "recorded as the resolution. -tool substitutes $BASE, $OURS, "+                 "$THEIRS,\n";+    std::cout << "and $OUTPUT in the command.\n";+}++void show_git() {+    std::cout << "usage: vn git <subcommand> [arguments]\n\n";+    std::cout << "git bridge commands:\n";+    std::cout << "  import [-source:<gitdir>] [path]\n";+    std::cout << "                            import reachable git commits and refs\n";+    std::cout << "  export [path]             export commits into the git mirror\n";+    std::cout << "  materialize [path]        replace lazy git blobs with stored "+                 "blobs\n";+    std::cout << "  fetch [<remote>] [path]   git fetch into the mirror, then import\n";+    std::cout << "  push [<remote>] <bookmark> [path]\n";+    std::cout << "                            export and git push a bookmark\n";+    std::cout << "  remote <add|list|remove>  manage git remotes\n\n";+    std::cout << "run 'vn help git <subcommand>' for details\n";+}++void show_git_import() {+    std::cout << "usage: vn git import [-source:<gitdir>] [path]\n\n";+    std::cout << "import commits and refs reachable from a git repository\n\n";+    std::cout << "an empty working tree is checked out to the imported head\n\n";+    std::cout << "arguments:\n";+    std::cout << "  [path]                    veins repository (default: .)\n\n";+    std::cout << "options:\n";+    std::cout << "  -source:<gitdir>          source git root to mirror (a directory "+                 "containing .git)\n";+}++void show_git_export() {+    std::cout << "usage: vn git export [path]\n\n";+    std::cout << "export commits reachable from bookmarks and tags into .veins/git\n";+}++void show_git_materialize() {+    std::cout << "usage: vn git materialize [path]\n\n";+    std::cout << "replace lazy git-backed blobs with canonical stored blobs.\n";+    std::cout << "rewrites affected trees, commits, and refs and records one "+                 "operation\n";+}++void show_unimplemented(std::string_view command) {+    std::cout << "usage: vn " << command << "\n\n";+    std::cout << "this command is planned for a later stage of the C++ rewrite\n";+    std::cout << "and is not available in the current local-core build\n";+}++int run_help(const std::vector<std::string>& args) {+    if (args.size() <= 2) {+        usage();+        return 0;+    }+    const std::string& cmd = args[2];+    if (cmd == "init")+        show_init();+    else if (cmd == "stat" || cmd == "status")+        show_status();+    else if (cmd == "ls")+        show_ls();+    else if (cmd == "inf")+        show_inf();+    else if (cmd == "log")+        show_log();+    else if (cmd == "show")+        show_show();+    else if (cmd == "hash")+        show_hash();+    else if (cmd == "diff")+        show_diff();+    else if (cmd == "new")+        show_new();+    else if (cmd == "desc" || cmd == "describe")+        show_describe();+    else if (cmd == "go" || cmd == "commit")+        show_commit();+    else if (cmd == "amend")+        show_amend();+    else if (cmd == "co" || cmd == "checkout")+        show_checkout();+    else if (cmd == "fsck")+        show_fsck();+    else if (cmd == "bmk")+        show_bmk();+    else if (cmd == "tag")+        show_tag();+    else if (cmd == "cfg")+        show_cfg();+    else if (cmd == "rm")+        show_rm();+    else if (cmd == "mv")+        show_mv();+    else if (cmd == "ex")+        show_ex();+    else if (cmd == "undo")+        show_undo();+    else if (cmd == "op")+        show_op();+    else if (cmd == "merge")+        show_merge();+    else if (cmd == "rebase")+        show_rebase();+    else if (cmd == "xs")+        show_xs();+    else if (cmd == "resolve")+        show_resolve();+    else if (cmd == "self-test")+        show_selftest();+    else if (cmd == "version")+        show_version();+    else if (cmd == "help")+        show_help();+    else if (net_help(cmd)) {+    } else if (cmd == "git") {+        if (args.size() > 3) {+            const std::string& sub = args[3];+            if (sub == "import")+                show_git_import();+            else if (sub == "export")+                show_git_export();+            else if (sub == "materialize")+                show_git_materialize();+            else if (sub == "fetch")+                std::cout << "usage: vn git fetch [<remote>] [path]\n";+            else if (sub == "push")+                std::cout << "usage: vn git push [<remote>] <bookmark> [path]\n";+            else if (sub == "remote")+                std::cout << "usage: vn git remote <add|list|remove> ...\n";+            else {+                error_prefix();+                std::cout << "unknown git subcommand: " << sub << "\n";+                return 1;+            }+        } else {+            show_git();+        }+    } else if (cmd == "bench-import")+        show_unimplemented(cmd);+    else {+        usage();+        error_prefix();+        std::cout << "unknown command: " << cmd << "\n";+        return 1;+    }+    return 0;+}++} // namespace++int cli_run(const std::vector<std::string>& args) {+    install_promisor_fetcher();+    if (args.size() < 2) {+        usage();+        return 1;+    }+    const std::string& cmd = args[1];+    if (cmd == "init")+        return run_init(args);+    if (cmd == "stat" || cmd == "status")+        return run_status();+    if (cmd == "ls")+        return run_ls(args);+    if (cmd == "inf")+        return run_inf();+    if (cmd == "log")+        return run_log(args);+    if (cmd == "show")+        return run_show(args);+    if (cmd == "hash")+        return run_hash(args);+    if (cmd == "diff")+        return run_diff(args);+    if (cmd == "new")+        return run_new(args);+    if (cmd == "desc" || cmd == "describe")+        return run_describe(args);+    if (cmd == "go" || cmd == "commit")+        return run_commit(args);+    if (cmd == "amend")+        return run_amend(args);+    if (cmd == "co" || cmd == "checkout")+        return run_checkout(args);+    if (cmd == "bmk")+        return bmk_run(args);+    if (cmd == "tag")+        return tag_run(args);+    if (cmd == "cfg" || cmd == "config")+        return cfg_run(args);+    if (cmd == "rm")+        return rm_run(args);+    if (cmd == "mv")+        return mv_run(args);+    if (cmd == "ex")+        return ex_run(args);+    if (cmd == "op")+        return op_run(args);+    if (cmd == "undo")+        return undo_run(args);+    if (cmd == "merge")+        return merge_run(args);+    if (cmd == "rebase")+        return rebase_run(args);+    if (cmd == "xs")+        return xs_run(args);+    if (cmd == "resolve")+        return resolve_run(args);+    if (cmd == "fsck")+        return run_fsck(args);+    if (cmd == "self-test")+        return run_self_test();+    if (cmd == "version" || cmd == "-version") {+        std::cout << "veins v" << VN_VERSION << " (veins-store 1)\n";+        return 0;+    }+    if (cmd == "help" || cmd == "-help" || cmd == "-h")+        return run_help(args);++    if (cmd == "remote")+        return remote_run(args);+    if (cmd == "clone")+        return clone_run(args);+    if (cmd == "fetch")+        return fetch_run(args);+    if (cmd == "push")+        return push_run(args);+    if (cmd == "serve")+        return serve_run(args);+    if (cmd == "key")+        return key_run(args);+    if (cmd == "auth")+        return auth_run(args);+    if (cmd == "access")+        return access_run(args);+    if (cmd == "whoami")+        return whoami_run(args);++    if (cmd == "git")+        return git_cli_run(args);+    if (cmd == "bench-import") {+        error_prefix();+        std::cout << "command '" << cmd << "' is not available in this stage\n";+        return 1;+    }+    usage();+    error_prefix();+    std::cout << "unknown command: " << cmd << "\n";+    return 1; }  } // namespace vn--- a/xveins/src/cli.h+++ b/xveins/src/cli.h@@ -5,6 +5,6 @@  namespace vn { -int cli_run(const std::vector<std::string> &args);+int cli_run(const std::vector<std::string>& args);  } // namespace vn--- a/xveins/src/common.cpp+++ b/xveins/src/common.cpp@@ -25,8 +25,8 @@ #if defined(__linux__) #include <sched.h> #endif-#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) ||      \-    defined(__NetBSD__) || defined(__DragonFly__)+#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) ||   \+    defined(__DragonFly__) #include <stdlib.h> #endif #endif@@ -34,51 +34,51 @@ namespace vn {  std::string_view error_kind_name(ErrorKind kind) {-  switch (kind) {-  case ErrorKind::None:-    return "none";-  case ErrorKind::UnexpectedEnd:-    return "unexpected end of input";-  case ErrorKind::VarintOverflow:-    return "varint overflow";-  case ErrorKind::NonMinimalVarint:-    return "non-minimal varint";-  case ErrorKind::InvalidValue:-    return "invalid value";-  case ErrorKind::LimitExceeded:-    return "format limit exceeded";-  case ErrorKind::InvalidName:-    return "invalid name";-  case ErrorKind::Duplicate:-    return "duplicate entry";-  case ErrorKind::Unsorted:-    return "entries are not sorted";-  case ErrorKind::TrailingBytes:-    return "trailing bytes";-  case ErrorKind::UnsupportedVersion:-    return "unsupported format version";-  case ErrorKind::InvalidMagic:-    return "bad file magic";-  case ErrorKind::HashMismatch:-    return "hash mismatch";-  case ErrorKind::Corrupt:-    return "corrupt data";-  case ErrorKind::Io:-    return "I/O error";-  case ErrorKind::Usage:-    return "usage error";-  }-  return "unknown error";+    switch (kind) {+    case ErrorKind::None:+        return "none";+    case ErrorKind::UnexpectedEnd:+        return "unexpected end of input";+    case ErrorKind::VarintOverflow:+        return "varint overflow";+    case ErrorKind::NonMinimalVarint:+        return "non-minimal varint";+    case ErrorKind::InvalidValue:+        return "invalid value";+    case ErrorKind::LimitExceeded:+        return "format limit exceeded";+    case ErrorKind::InvalidName:+        return "invalid name";+    case ErrorKind::Duplicate:+        return "duplicate entry";+    case ErrorKind::Unsorted:+        return "entries are not sorted";+    case ErrorKind::TrailingBytes:+        return "trailing bytes";+    case ErrorKind::UnsupportedVersion:+        return "unsupported format version";+    case ErrorKind::InvalidMagic:+        return "bad file magic";+    case ErrorKind::HashMismatch:+        return "hash mismatch";+    case ErrorKind::Corrupt:+        return "corrupt data";+    case ErrorKind::Io:+        return "I/O error";+    case ErrorKind::Usage:+        return "usage error";+    }+    return "unknown error"; }  Error Error::decode(ErrorKind kind, std::size_t offset) {-  return Error{kind, offset, std::string(error_kind_name(kind))};+    return Error{kind, offset, std::string(error_kind_name(kind))}; } Error Error::io(std::string message) {-  return Error{ErrorKind::Io, 0, std::move(message)};+    return Error{ErrorKind::Io, 0, std::move(message)}; } Error Error::usage(std::string message) {-  return Error{ErrorKind::Usage, 0, std::move(message)};+    return Error{ErrorKind::Usage, 0, std::move(message)}; }  // ---------------------------------------------------------------------------@@ -86,92 +86,92 @@ // ---------------------------------------------------------------------------  static char hex_digit(std::uint8_t v) {-  return static_cast<char>(v < 10 ? '0' + v : 'a' + (v - 10));+    return static_cast<char>(v < 10 ? '0' + v : 'a' + (v - 10)); }  std::string hex_encode(Bytes data) {-  std::string out(data.size() * 2, '0');-  for (std::size_t i = 0; i < data.size(); ++i) {-    out[i * 2] = hex_digit(static_cast<std::uint8_t>(data[i] >> 4));-    out[i * 2 + 1] = hex_digit(static_cast<std::uint8_t>(data[i] & 15));-  }-  return out;+    std::string out(data.size() * 2, '0');+    for (std::size_t i = 0; i < data.size(); ++i) {+        out[i * 2] = hex_digit(static_cast<std::uint8_t>(data[i] >> 4));+        out[i * 2 + 1] = hex_digit(static_cast<std::uint8_t>(data[i] & 15));+    }+    return out; } -std::string hex_encode(const Id &id) {-  return hex_encode(Bytes(id.data(), id.size()));+std::string hex_encode(const Id& id) {+    return hex_encode(Bytes(id.data(), id.size())); }  static int hex_value(char c) {-  if (c >= '0' && c <= '9')-    return c - '0';-  if (c >= 'a' && c <= 'f')-    return c - 'a' + 10;-  if (c >= 'A' && c <= 'F')-    return c - 'A' + 10;-  return -1;+    if (c >= '0' && c <= '9')+        return c - '0';+    if (c >= 'a' && c <= 'f')+        return c - 'a' + 10;+    if (c >= 'A' && c <= 'F')+        return c - 'A' + 10;+    return -1; }  bool hex_decode(std::string_view text, MutBytes out) {-  if (text.size() != out.size() * 2)-    return false;-  for (std::size_t i = 0; i < out.size(); ++i) {-    const int hi = hex_value(text[i * 2]);-    const int lo = hex_value(text[i * 2 + 1]);-    if (hi < 0 || lo < 0)-      return false;-    out[i] = static_cast<std::uint8_t>((hi << 4) | lo);-  }-  return true;+    if (text.size() != out.size() * 2)+        return false;+    for (std::size_t i = 0; i < out.size(); ++i) {+        const int hi = hex_value(text[i * 2]);+        const int lo = hex_value(text[i * 2 + 1]);+        if (hi < 0 || lo < 0)+            return false;+        out[i] = static_cast<std::uint8_t>((hi << 4) | lo);+    }+    return true; }  std::optional<Id> parse_id(std::string_view hex) {-  if (hex.size() != ID_LEN * 2)-    return std::nullopt;-  Id id{};-  if (!hex_decode(hex, MutBytes(id.data(), id.size())))-    return std::nullopt;-  return id;+    if (hex.size() != ID_LEN * 2)+        return std::nullopt;+    Id id{};+    if (!hex_decode(hex, MutBytes(id.data(), id.size())))+        return std::nullopt;+    return id; } -std::string base32_encode(const ChangeId &id) {-  static constexpr char alphabet[] = "abcdefghijklmnopqrstuvwxyz234567";-  std::string out;-  out.reserve(26);-  std::uint64_t buffer = 0;-  std::size_t bits = 0;-  for (std::uint8_t c : id) {-    buffer = (buffer << 8) | c;-    bits += 8;-    while (bits >= 5) {-      const std::size_t shift = bits - 5;-      const std::size_t index = (buffer >> shift) & 31u;-      out.push_back(alphabet[index]);-      bits = shift;+std::string base32_encode(const ChangeId& id) {+    static constexpr char alphabet[] = "abcdefghijklmnopqrstuvwxyz234567";+    std::string out;+    out.reserve(26);+    std::uint64_t buffer = 0;+    std::size_t bits = 0;+    for (std::uint8_t c : id) {+        buffer = (buffer << 8) | c;+        bits += 8;+        while (bits >= 5) {+            const std::size_t shift = bits - 5;+            const std::size_t index = (buffer >> shift) & 31u;+            out.push_back(alphabet[index]);+            bits = shift;+        }+        if (bits == 0) {+            buffer = 0;+        } else {+            buffer &= (std::uint64_t{1} << bits) - 1;+        }     }-    if (bits == 0) {-      buffer = 0;-    } else {-      buffer &= (std::uint64_t{1} << bits) - 1;+    if (bits > 0) {+        out.push_back(alphabet[(buffer << (5 - bits)) & 31u]);     }-  }-  if (bits > 0) {-    out.push_back(alphabet[(buffer << (5 - bits)) & 31u]);-  }-  return out;+    return out; }  bool base32_prefix_matches(std::string_view full, std::string_view prefix) {-  if (prefix.empty() || prefix.size() > full.size())-    return false;-  for (std::size_t i = 0; i < prefix.size(); ++i) {-    char c = prefix[i];-    if (c >= 'A' && c <= 'Z')-      c = static_cast<char>(c + 32);-    if (full[i] != c)-      return false;-  }-  return true;+    if (prefix.empty() || prefix.size() > full.size())+        return false;+    for (std::size_t i = 0; i < prefix.size(); ++i) {+        char c = prefix[i];+        if (c >= 'A' && c <= 'Z')+            c = static_cast<char>(c + 32);+        if (full[i] != c)+            return false;+    }+    return true; }  // ---------------------------------------------------------------------------@@ -179,71 +179,69 @@ // ---------------------------------------------------------------------------  std::array<std::uint8_t, 32> blake3_hash(Bytes data) {-  std::array<std::uint8_t, 32> out{};-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  if (!data.empty())-    blake3_hasher_update(&hasher, data.data(), data.size());-  blake3_hasher_finalize(&hasher, out.data(), out.size());-  return out;+    std::array<std::uint8_t, 32> out{};+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    if (!data.empty())+        blake3_hasher_update(&hasher, data.data(), data.size());+    blake3_hasher_finalize(&hasher, out.data(), out.size());+    return out; }  Id object_id(std::uint8_t type_byte, Bytes body) {-  static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n',-                                            's', '/', '1', 0};-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  blake3_hasher_update(&hasher, prefix, sizeof(prefix));-  blake3_hasher_update(&hasher, &type_byte, 1);-  if (!body.empty())-    blake3_hasher_update(&hasher, body.data(), body.size());-  Id out{};-  blake3_hasher_finalize(&hasher, out.data(), out.size());-  return out;+    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', '1', 0};+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    blake3_hasher_update(&hasher, prefix, sizeof(prefix));+    blake3_hasher_update(&hasher, &type_byte, 1);+    if (!body.empty())+        blake3_hasher_update(&hasher, body.data(), body.size());+    Id out{};+    blake3_hasher_finalize(&hasher, out.data(), out.size());+    return out; }  static void os_random_bytes(MutBytes out) { #if defined(_WIN32)-  if (BCryptGenRandom(nullptr, out.data(), static_cast<ULONG>(out.size()),-                      BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0) {+    if (BCryptGenRandom(nullptr, out.data(), static_cast<ULONG>(out.size()),+                        BCRYPT_USE_SYSTEM_PREFERRED_RNG) == 0) {+        return;+    }+#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || \+    defined(__DragonFly__)+    arc4random_buf(out.data(), out.size());     return;-  }-#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) ||    \-    defined(__NetBSD__) || defined(__DragonFly__)-  arc4random_buf(out.data(), out.size());-  return; #else-  std::size_t done = 0;-  while (done < out.size()) {-    const ssize_t n = ::getrandom(out.data() + done, out.size() - done, 0);-    if (n > 0) {-      done += static_cast<std::size_t>(n);-      continue;+    std::size_t done = 0;+    while (done < out.size()) {+        const ssize_t n = ::getrandom(out.data() + done, out.size() - done, 0);+        if (n > 0) {+            done += static_cast<std::size_t>(n);+            continue;+        }+        if (n < 0 && errno == EINTR)+            continue;+        break;     }-    if (n < 0 && errno == EINTR)-      continue;-    break;-  }-  if (done == out.size())-    return;+    if (done == out.size())+        return; #endif-  std::random_device rd;-  for (std::size_t i = 0; i < out.size(); ++i) {-    out[i] = static_cast<std::uint8_t>(rd());-  }+    std::random_device rd;+    for (std::size_t i = 0; i < out.size(); ++i) {+        out[i] = static_cast<std::uint8_t>(rd());+    } }  std::array<std::uint8_t, 16> random_change_id() {-  std::array<std::uint8_t, 16> out{};-  os_random_bytes(MutBytes(out.data(), out.size()));-  return out;+    std::array<std::uint8_t, 16> out{};+    os_random_bytes(MutBytes(out.data(), out.size()));+    return out; }  std::uint64_t random_u64() {-  std::uint64_t value = 0;-  os_random_bytes(-      MutBytes(reinterpret_cast<std::uint8_t *>(&value), sizeof(value)));-  return value;+    std::uint64_t value = 0;+    os_random_bytes(MutBytes(reinterpret_cast<std::uint8_t*>(&value), sizeof(value)));+    return value; }  // ---------------------------------------------------------------------------@@ -251,256 +249,262 @@ // ---------------------------------------------------------------------------  Result<std::uint8_t> Reader::u8() {-  if (pos_ >= data_.size())-    return fail(ErrorKind::UnexpectedEnd, pos_);-  return data_[pos_++];+    if (pos_ >= data_.size())+        return fail(ErrorKind::UnexpectedEnd, pos_);+    return data_[pos_++]; }  Result<std::uint16_t> Reader::u16le() {-  if (remaining() < 2)-    return fail(ErrorKind::UnexpectedEnd, pos_);-  const auto v = static_cast<std::uint16_t>(-      static_cast<std::uint16_t>(data_[pos_]) |-      static_cast<std::uint16_t>(static_cast<std::uint16_t>(data_[pos_ + 1])-                                 << 8));-  pos_ += 2;-  return v;+    if (remaining() < 2)+        return fail(ErrorKind::UnexpectedEnd, pos_);+    const auto v = static_cast<std::uint16_t>(+        static_cast<std::uint16_t>(data_[pos_]) |+        static_cast<std::uint16_t>(static_cast<std::uint16_t>(data_[pos_ + 1]) << 8));+    pos_ += 2;+    return v; }  Result<std::uint32_t> Reader::u32le() {-  if (remaining() < 4)-    return fail(ErrorKind::UnexpectedEnd, pos_);-  std::uint32_t v = 0;-  for (std::size_t i = 0; i < 4; ++i) {-    v |= static_cast<std::uint32_t>(data_[pos_ + i]) << (i * 8);-  }-  pos_ += 4;-  return v;+    if (remaining() < 4)+        return fail(ErrorKind::UnexpectedEnd, pos_);+    std::uint32_t v = 0;+    for (std::size_t i = 0; i < 4; ++i) {+        v |= static_cast<std::uint32_t>(data_[pos_ + i]) << (i * 8);+    }+    pos_ += 4;+    return v; }  Result<std::uint64_t> Reader::u64le() {-  if (remaining() < 8)-    return fail(ErrorKind::UnexpectedEnd, pos_);-  std::uint64_t v = 0;-  for (int i = 0; i < 8; ++i) {-    v |= static_cast<std::uint64_t>(data_[pos_ + static_cast<std::size_t>(i)])-         << (i * 8);-  }-  pos_ += 8;-  return v;+    if (remaining() < 8)+        return fail(ErrorKind::UnexpectedEnd, pos_);+    std::uint64_t v = 0;+    for (int i = 0; i < 8; ++i) {+        v |= static_cast<std::uint64_t>(data_[pos_ + static_cast<std::size_t>(i)]) << (i * 8);+    }+    pos_ += 8;+    return v; }  Result<std::int16_t> Reader::i16le() {-  const auto v = u16le();-  if (!v)-    return unexpected(v.error());-  return static_cast<std::int16_t>(*v);+    const auto v = u16le();+    if (!v)+        return unexpected(v.error());+    return static_cast<std::int16_t>(*v); }  Result<std::int64_t> Reader::i64le() {-  const auto v = u64le();-  if (!v)-    return unexpected(v.error());-  return static_cast<std::int64_t>(*v);+    const auto v = u64le();+    if (!v)+        return unexpected(v.error());+    return static_cast<std::int64_t>(*v); }  Result<std::uint64_t> Reader::varint() {-  const std::size_t start = pos_;-  std::uint64_t value = 0;-  unsigned shift = 0;-  for (unsigned i = 0; i < 10; ++i) {-    const auto b = u8();-    if (!b)-      return unexpected(b.error());-    const std::uint64_t low = static_cast<std::uint64_t>(*b & 127u);-    if (shift == 63 && low > 1)-      return fail(ErrorKind::VarintOverflow, start);-    value |= low << shift;-    if ((*b & 128u) == 0) {-      if (i > 0 && low == 0)-        return fail(ErrorKind::NonMinimalVarint, start);-      return value;+    const std::size_t start = pos_;+    std::uint64_t value = 0;+    unsigned shift = 0;+    for (unsigned i = 0; i < 10; ++i) {+        const auto b = u8();+        if (!b)+            return unexpected(b.error());+        const std::uint64_t low = static_cast<std::uint64_t>(*b & 127u);+        if (shift == 63 && low > 1)+            return fail(ErrorKind::VarintOverflow, start);+        value |= low << shift;+        if ((*b & 128u) == 0) {+            if (i > 0 && low == 0)+                return fail(ErrorKind::NonMinimalVarint, start);+            return value;+        }+        shift += 7;     }-    shift += 7;-  }-  return fail(ErrorKind::VarintOverflow, start);+    return fail(ErrorKind::VarintOverflow, start); }  Result<Bytes> Reader::raw(std::size_t n) {-  if (n > remaining())-    return fail(ErrorKind::UnexpectedEnd, pos_);-  const Bytes out = data_.subspan(pos_, n);-  pos_ += n;-  return out;+    if (n > remaining())+        return fail(ErrorKind::UnexpectedEnd, pos_);+    const Bytes out = data_.subspan(pos_, n);+    pos_ += n;+    return out; }  Result<Bytes> Reader::bytes(std::size_t max_len) {-  const std::size_t at = pos_;-  const auto n = varint();-  if (!n)-    return unexpected(n.error());-  if (*n > max_len)-    return fail(ErrorKind::LimitExceeded, at);-  if (*n > remaining())-    return fail(ErrorKind::UnexpectedEnd, at);-  return raw(static_cast<std::size_t>(*n));+    const std::size_t at = pos_;+    const auto n = varint();+    if (!n)+        return unexpected(n.error());+    if (*n > max_len)+        return fail(ErrorKind::LimitExceeded, at);+    if (*n > remaining())+        return fail(ErrorKind::UnexpectedEnd, at);+    return raw(static_cast<std::size_t>(*n)); }  Result<std::string> Reader::string_bytes(std::size_t max_len) {-  const auto b = bytes(max_len);-  if (!b)-    return unexpected(b.error());-  return std::string(str_of(*b));+    const auto b = bytes(max_len);+    if (!b)+        return unexpected(b.error());+    return std::string(str_of(*b)); }  Result<std::size_t> Reader::list_len(std::size_t max) {-  const std::size_t at = pos_;-  const auto n = varint();-  if (!n)-    return unexpected(n.error());-  if (*n > max)-    return fail(ErrorKind::LimitExceeded, at);-  return static_cast<std::size_t>(*n);+    const std::size_t at = pos_;+    const auto n = varint();+    if (!n)+        return unexpected(n.error());+    if (*n > max)+        return fail(ErrorKind::LimitExceeded, at);+    return static_cast<std::size_t>(*n); }  Result<Id> Reader::id() {-  const auto b = raw(ID_LEN);-  if (!b)-    return unexpected(b.error());-  Id out{};-  std::memcpy(out.data(), b->data(), ID_LEN);-  return out;+    const auto b = raw(ID_LEN);+    if (!b)+        return unexpected(b.error());+    Id out{};+    std::memcpy(out.data(), b->data(), ID_LEN);+    return out; }  Result<std::optional<Id>> Reader::opt_id() {-  const std::size_t at = pos_;-  const auto tag = u8();-  if (!tag)-    return unexpected(tag.error());-  if (*tag == 0)-    return std::optional<Id>{};-  if (*tag != 1)-    return fail(ErrorKind::InvalidValue, at);-  const auto value = id();-  if (!value)-    return unexpected(value.error());-  return std::optional<Id>(*value);+    const std::size_t at = pos_;+    const auto tag = u8();+    if (!tag)+        return unexpected(tag.error());+    if (*tag == 0)+        return std::optional<Id>{};+    if (*tag != 1)+        return fail(ErrorKind::InvalidValue, at);+    const auto value = id();+    if (!value)+        return unexpected(value.error());+    return std::optional<Id>(*value); }  Result<void> Reader::finish() {-  if (pos_ != data_.size())-    return fail(ErrorKind::TrailingBytes, pos_);-  return {};+    if (pos_ != data_.size())+        return fail(ErrorKind::TrailingBytes, pos_);+    return {}; }  Result<Reader::Sig> Reader::sig(std::size_t max_name, std::size_t max_email) {-  Sig out;-  const auto name = string_bytes(max_name);-  if (!name)-    return unexpected(name.error());-  const auto email = string_bytes(max_email);-  if (!email)-    return unexpected(email.error());-  const auto secs = i64le();-  if (!secs)-    return unexpected(secs.error());-  const auto tz = i16le();-  if (!tz)-    return unexpected(tz.error());-  out.name = *name;-  out.email = *email;-  out.seconds = *secs;-  out.tz_min = *tz;-  return out;+    Sig out;+    const auto name = string_bytes(max_name);+    if (!name)+        return unexpected(name.error());+    const auto email = string_bytes(max_email);+    if (!email)+        return unexpected(email.error());+    const auto secs = i64le();+    if (!secs)+        return unexpected(secs.error());+    const auto tz = i16le();+    if (!tz)+        return unexpected(tz.error());+    out.name = *name;+    out.email = *email;+    out.seconds = *secs;+    out.tz_min = *tz;+    return out; }  Result<Reader::TimeMs> Reader::time_ms() {-  TimeMs out;-  const auto ms = i64le();-  if (!ms)-    return unexpected(ms.error());-  const auto tz = i16le();-  if (!tz)-    return unexpected(tz.error());-  out.ms = *ms;-  out.tz_min = *tz;-  return out;+    TimeMs out;+    const auto ms = i64le();+    if (!ms)+        return unexpected(ms.error());+    const auto tz = i16le();+    if (!tz)+        return unexpected(tz.error());+    out.ms = *ms;+    out.tz_min = *tz;+    return out; }  std::uint64_t Reader::read_u64le_at(Bytes data, std::size_t off) {-  std::uint64_t v = 0;-  for (std::size_t i = 0; i < 8; ++i)-    v |= static_cast<std::uint64_t>(data[off + i]) << (i * 8);-  return v;+    std::uint64_t v = 0;+    for (std::size_t i = 0; i < 8; ++i)+        v |= static_cast<std::uint64_t>(data[off + i]) << (i * 8);+    return v; } -void ByteWriter::u8(std::uint8_t v) { buf_.push_back(v); }+void ByteWriter::u8(std::uint8_t v) {+    buf_.push_back(v);+}  void ByteWriter::u16le(std::uint16_t v) {-  buf_.push_back(static_cast<std::uint8_t>(v & 255u));-  buf_.push_back(static_cast<std::uint8_t>((v >> 8) & 255u));+    buf_.push_back(static_cast<std::uint8_t>(v & 255u));+    buf_.push_back(static_cast<std::uint8_t>((v >> 8) & 255u)); }  void ByteWriter::u32le(std::uint32_t v) {-  for (int i = 0; i < 4; ++i)-    buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));+    for (int i = 0; i < 4; ++i)+        buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u)); }  void ByteWriter::u64le(std::uint64_t v) {-  for (int i = 0; i < 8; ++i)-    buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u));+    for (int i = 0; i < 8; ++i)+        buf_.push_back(static_cast<std::uint8_t>((v >> (i * 8)) & 255u)); } -void ByteWriter::i16le(std::int16_t v) { u16le(static_cast<std::uint16_t>(v)); }-void ByteWriter::i64le(std::int64_t v) { u64le(static_cast<std::uint64_t>(v)); }+void ByteWriter::i16le(std::int16_t v) {+    u16le(static_cast<std::uint16_t>(v));+}+void ByteWriter::i64le(std::int64_t v) {+    u64le(static_cast<std::uint64_t>(v));+}  void ByteWriter::varint(std::uint64_t v) {-  for (;;) {-    const std::uint8_t low = static_cast<std::uint8_t>(v & 127u);-    v >>= 7;-    if (v == 0) {-      buf_.push_back(low);-      return;+    for (;;) {+        const std::uint8_t low = static_cast<std::uint8_t>(v & 127u);+        v >>= 7;+        if (v == 0) {+            buf_.push_back(low);+            return;+        }+        buf_.push_back(static_cast<std::uint8_t>(low | 128u));     }-    buf_.push_back(static_cast<std::uint8_t>(low | 128u));-  } }  void ByteWriter::raw(Bytes data) {-  if (!data.empty()) {-    buf_.insert(buf_.end(), data.begin(), data.end());-  }+    if (!data.empty()) {+        buf_.insert(buf_.end(), data.begin(), data.end());+    } }  void ByteWriter::length_prefixed(std::string_view s) {-  length_prefixed(bytes_of(s));+    length_prefixed(bytes_of(s)); } void ByteWriter::length_prefixed(Bytes b) {-  varint(b.size());-  raw(b);+    varint(b.size());+    raw(b); } -void ByteWriter::id(const Id &id) { raw(Bytes(id.data(), id.size())); }+void ByteWriter::id(const Id& id) {+    raw(Bytes(id.data(), id.size()));+} -void ByteWriter::opt_id(const std::optional<Id> &id) {-  if (!id) {-    u8(0);-    return;-  }-  u8(1);-  this->id(*id);+void ByteWriter::opt_id(const std::optional<Id>& id) {+    if (!id) {+        u8(0);+        return;+    }+    u8(1);+    this->id(*id); } -void ByteWriter::sig(const Reader::Sig &s) {-  length_prefixed(s.name);-  length_prefixed(s.email);-  i64le(s.seconds);-  i16le(s.tz_min);+void ByteWriter::sig(const Reader::Sig& s) {+    length_prefixed(s.name);+    length_prefixed(s.email);+    i64le(s.seconds);+    i16le(s.tz_min); } -void ByteWriter::time_ms(const Reader::TimeMs &t) {-  i64le(t.ms);-  i16le(t.tz_min);+void ByteWriter::time_ms(const Reader::TimeMs& t) {+    i64le(t.ms);+    i16le(t.tz_min); }  // ---------------------------------------------------------------------------@@ -509,100 +513,99 @@  std::size_t available_cpu_count() { #if defined(_WIN32)-  const DWORD count = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);-  return count == 0 ? 1 : static_cast<std::size_t>(count);+    const DWORD count = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);+    return count == 0 ? 1 : static_cast<std::size_t>(count); #elif defined(__linux__)-  cpu_set_t set;-  CPU_ZERO(&set);-  if (sched_getaffinity(0, sizeof(set), &set) == 0) {-    const auto *bytes = reinterpret_cast<const unsigned char *>(&set);-    std::size_t count = 0;-    for (std::size_t i = 0; i < sizeof(set); ++i) {-      unsigned char value = bytes[i];-      while (value != 0) {-        count += value & 1u;-        value >>= 1;-      }+    cpu_set_t set;+    CPU_ZERO(&set);+    if (sched_getaffinity(0, sizeof(set), &set) == 0) {+        const auto* bytes = reinterpret_cast<const unsigned char*>(&set);+        std::size_t count = 0;+        for (std::size_t i = 0; i < sizeof(set); ++i) {+            unsigned char value = bytes[i];+            while (value != 0) {+                count += value & 1u;+                value >>= 1;+            }+        }+        if (count != 0)+            return count;     }-    if (count != 0)-      return count;-  }-  const long n = sysconf(_SC_NPROCESSORS_ONLN);-  return n > 0 ? static_cast<std::size_t>(n) : 1;+    const long n = sysconf(_SC_NPROCESSORS_ONLN);+    return n > 0 ? static_cast<std::size_t>(n) : 1; #else-  const long n = sysconf(_SC_NPROCESSORS_ONLN);-  return n > 0 ? static_cast<std::size_t>(n) : 1;+    const long n = sysconf(_SC_NPROCESSORS_ONLN);+    return n > 0 ? static_cast<std::size_t>(n) : 1; #endif }  std::int64_t unix_now_seconds() {-  return std::chrono::duration_cast<std::chrono::seconds>(-             std::chrono::system_clock::now().time_since_epoch())-      .count();+    return std::chrono::duration_cast<std::chrono::seconds>(+               std::chrono::system_clock::now().time_since_epoch())+        .count(); }  std::int64_t unix_now_millis() {-  return std::chrono::duration_cast<std::chrono::milliseconds>(-             std::chrono::system_clock::now().time_since_epoch())-      .count();+    return std::chrono::duration_cast<std::chrono::milliseconds>(+               std::chrono::system_clock::now().time_since_epoch())+        .count(); }  static std::int64_t floor_div(std::int64_t a, std::int64_t b) {-  std::int64_t q = a / b;-  const std::int64_t r = a % b;-  if (r != 0 && ((r < 0) != (b < 0)))-    --q;-  return q;+    std::int64_t q = a / b;+    const std::int64_t r = a % b;+    if (r != 0 && ((r < 0) != (b < 0)))+        --q;+    return q; } -static void append_pad(std::string &out, std::int64_t value, int width) {-  if (value < 0)-    value = 0;-  std::string digits;-  do {-    digits.push_back(static_cast<char>('0' + (value % 10)));-    value /= 10;-  } while (value > 0);-  for (int i = static_cast<int>(digits.size()); i < width; ++i)-    out.push_back('0');-  for (auto it = digits.rbegin(); it != digits.rend(); ++it)-    out.push_back(*it);+static void append_pad(std::string& out, std::int64_t value, int width) {+    if (value < 0)+        value = 0;+    std::string digits;+    do {+        digits.push_back(static_cast<char>('0' + (value % 10)));+        value /= 10;+    } while (value > 0);+    for (int i = static_cast<int>(digits.size()); i < width; ++i)+        out.push_back('0');+    for (auto it = digits.rbegin(); it != digits.rend(); ++it)+        out.push_back(*it); }  std::string format_utc(std::int64_t seconds) {-  const std::int64_t days = floor_div(seconds, 86400);-  const std::int64_t rem = seconds - days * 86400;-  const std::int64_t hour = rem / 3600;-  const std::int64_t minute = (rem % 3600) / 60;-  const std::int64_t second = rem % 60;+    const std::int64_t days = floor_div(seconds, 86400);+    const std::int64_t rem = seconds - days * 86400;+    const std::int64_t hour = rem / 3600;+    const std::int64_t minute = (rem % 3600) / 60;+    const std::int64_t second = rem % 60; -  const std::int64_t z = days + 719468;-  const std::int64_t era = floor_div(z, 146097);-  const std::int64_t doe = z - era * 146097;-  const std::int64_t yoe =-      (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;-  const std::int64_t y0 = yoe + era * 400;-  const std::int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);-  const std::int64_t mp = (5 * doy + 2) / 153;-  const std::int64_t d = doy - (153 * mp + 2) / 5 + 1;-  const std::int64_t m0 = mp + 3;-  const std::int64_t m = mp >= 10 ? mp - 9 : m0;-  const std::int64_t y = m <= 2 ? y0 + 1 : y0;+    const std::int64_t z = days + 719468;+    const std::int64_t era = floor_div(z, 146097);+    const std::int64_t doe = z - era * 146097;+    const std::int64_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+    const std::int64_t y0 = yoe + era * 400;+    const std::int64_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+    const std::int64_t mp = (5 * doy + 2) / 153;+    const std::int64_t d = doy - (153 * mp + 2) / 5 + 1;+    const std::int64_t m0 = mp + 3;+    const std::int64_t m = mp >= 10 ? mp - 9 : m0;+    const std::int64_t y = m <= 2 ? y0 + 1 : y0; -  std::string out;-  out.reserve(19);-  append_pad(out, y, 4);-  out.push_back('-');-  append_pad(out, m, 2);-  out.push_back('-');-  append_pad(out, d, 2);-  out.push_back(' ');-  append_pad(out, hour, 2);-  out.push_back(':');-  append_pad(out, minute, 2);-  out.push_back(':');-  append_pad(out, second, 2);-  return out;+    std::string out;+    out.reserve(19);+    append_pad(out, y, 4);+    out.push_back('-');+    append_pad(out, m, 2);+    out.push_back('-');+    append_pad(out, d, 2);+    out.push_back(' ');+    append_pad(out, hour, 2);+    out.push_back(':');+    append_pad(out, minute, 2);+    out.push_back(':');+    append_pad(out, second, 2);+    return out; }  static bool g_colors = false;@@ -609,122 +612,121 @@ static bool g_colors_checked = false;  bool colors_enabled() {-  if (g_colors_checked)-    return g_colors;-  g_colors_checked = true;-  if (std::getenv("NO_COLOR") != nullptr)-    return false;+    if (g_colors_checked)+        return g_colors;+    g_colors_checked = true;+    if (std::getenv("NO_COLOR") != nullptr)+        return false; #if defined(_WIN32)-  const bool tty = _isatty(_fileno(stdout)) != 0;-  bool ansi = false;-  if (tty) {-    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);-    DWORD mode = 0;-    if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {-      ansi = SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;+    const bool tty = _isatty(_fileno(stdout)) != 0;+    bool ansi = false;+    if (tty) {+        HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);+        DWORD mode = 0;+        if (h != INVALID_HANDLE_VALUE && GetConsoleMode(h, &mode)) {+            ansi = SetConsoleMode(h, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;+        }     }-  }-  if (!ansi)-    return false;+    if (!ansi)+        return false; #else-  const bool tty = ::isatty(STDOUT_FILENO) != 0;+    const bool tty = ::isatty(STDOUT_FILENO) != 0; #endif-  const char *forced = std::getenv("FORCE_COLOR");-  if (forced != nullptr && *forced != '\0' && std::strcmp(forced, "0") != 0) {+    const char* forced = std::getenv("FORCE_COLOR");+    if (forced != nullptr && *forced != '\0' && std::strcmp(forced, "0") != 0) {+        g_colors = true;+        return true;+    }+    if (!tty)+        return false;+    const char* term = std::getenv("TERM");+    if (term != nullptr && std::strcmp(term, "dumb") == 0)+        return false;     g_colors = true;     return true;-  }-  if (!tty)-    return false;-  const char *term = std::getenv("TERM");-  if (term != nullptr && std::strcmp(term, "dumb") == 0)-    return false;-  g_colors = true;-  return true; }  static std::string_view color_code(Color c) {-  switch (c) {-  case Color::Default:+    switch (c) {+    case Color::Default:+        return "\x1b[39m";+    case Color::Black:+        return "\x1b[30m";+    case Color::Red:+        return "\x1b[31m";+    case Color::Green:+        return "\x1b[32m";+    case Color::Yellow:+        return "\x1b[33m";+    case Color::Blue:+        return "\x1b[34m";+    case Color::Magenta:+        return "\x1b[35m";+    case Color::Cyan:+        return "\x1b[36m";+    case Color::BrightBlack:+        return "\x1b[90m";+    case Color::BrightRed:+        return "\x1b[91m";+    case Color::BrightGreen:+        return "\x1b[92m";+    case Color::BrightYellow:+        return "\x1b[93m";+    case Color::BrightBlue:+        return "\x1b[94m";+    case Color::BrightMagenta:+        return "\x1b[95m";+    case Color::BrightCyan:+        return "\x1b[96m";+    case Color::BrightWhite:+        return "\x1b[97m";+    }     return "\x1b[39m";-  case Color::Black:-    return "\x1b[30m";-  case Color::Red:-    return "\x1b[31m";-  case Color::Green:-    return "\x1b[32m";-  case Color::Yellow:-    return "\x1b[33m";-  case Color::Blue:-    return "\x1b[34m";-  case Color::Magenta:-    return "\x1b[35m";-  case Color::Cyan:-    return "\x1b[36m";-  case Color::BrightBlack:-    return "\x1b[90m";-  case Color::BrightRed:-    return "\x1b[91m";-  case Color::BrightGreen:-    return "\x1b[92m";-  case Color::BrightYellow:-    return "\x1b[93m";-  case Color::BrightBlue:-    return "\x1b[94m";-  case Color::BrightMagenta:-    return "\x1b[95m";-  case Color::BrightCyan:-    return "\x1b[96m";-  case Color::BrightWhite:-    return "\x1b[97m";-  }-  return "\x1b[39m"; }  void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr) {-  (void)to_stderr;-  auto &stream = std::cout;-  if (!colors_enabled()) {+    (void)to_stderr;+    auto& stream = std::cout;+    if (!colors_enabled()) {+        stream << text;+        return;+    }+    if (dim)+        stream << "\x1b[2m";+    if (fg != Color::Default)+        stream << color_code(fg);     stream << text;-    return;-  }-  if (dim)-    stream << "\x1b[2m";-  if (fg != Color::Default)-    stream << color_code(fg);-  stream << text;-  stream << "\x1b[0m";+    stream << "\x1b[0m"; } -void print_colored(std::string_view text, Color color, bool dim,-                   bool to_stderr) {-  print_styled(text, color, dim, to_stderr);+void print_colored(std::string_view text, Color color, bool dim, bool to_stderr) {+    print_styled(text, color, dim, to_stderr); }  void print_bold(std::string_view text, Color fg, bool to_stderr) {-  (void)to_stderr;-  auto &stream = std::cout;-  if (!colors_enabled()) {-    stream << text;-    return;-  }-  stream << "\x1b[1m";-  if (fg != Color::Default)-    stream << color_code(fg);-  stream << text << "\x1b[0m";+    (void)to_stderr;+    auto& stream = std::cout;+    if (!colors_enabled()) {+        stream << text;+        return;+    }+    stream << "\x1b[1m";+    if (fg != Color::Default)+        stream << color_code(fg);+    stream << text << "\x1b[0m"; }  void error_prefix() {-  print_bold("error", Color::Red, false);-  std::cout << ": ";+    print_bold("error", Color::Red, false);+    std::cout << ": "; } void warning_prefix() {-  print_bold("warning", Color::Yellow, false);-  std::cout << ": ";+    print_bold("warning", Color::Yellow, false);+    std::cout << ": "; } void info_prefix() {-  print_styled("info", Color::Cyan, false, false);-  std::cout << ": ";+    print_styled("info", Color::Cyan, false, false);+    std::cout << ": "; }  // ---------------------------------------------------------------------------@@ -733,410 +735,405 @@  fs::path path_from_bytes(std::string_view bytes) { #if defined(_WIN32)-  std::u8string u;-  u.reserve(bytes.size());-  for (char c : bytes)-    u.push_back(static_cast<char8_t>(c));-  return fs::path(u);+    std::u8string u;+    u.reserve(bytes.size());+    for (char c : bytes)+        u.push_back(static_cast<char8_t>(c));+    return fs::path(u); #else-  return fs::path(std::string(bytes));+    return fs::path(std::string(bytes)); #endif } -std::string path_to_bytes(const fs::path &p) {+std::string path_to_bytes(const fs::path& p) { #if defined(_WIN32)-  const std::u8string u = p.u8string();-  return std::string(reinterpret_cast<const char *>(u.data()), u.size());+    const std::u8string u = p.u8string();+    return std::string(reinterpret_cast<const char*>(u.data()), u.size()); #else-  return p.native();+    return p.native(); #endif } -std::string path_display(const fs::path &p) { return path_to_bytes(p); }+std::string path_display(const fs::path& p) {+    return path_to_bytes(p);+} -bool path_exists(const fs::path &p) {-  std::error_code ec;-  return fs::exists(p, ec);+bool path_exists(const fs::path& p) {+    std::error_code ec;+    return fs::exists(p, ec); } -bool path_is_dir(const fs::path &p) {-  std::error_code ec;-  return fs::is_directory(p, ec);+bool path_is_dir(const fs::path& p) {+    std::error_code ec;+    return fs::is_directory(p, ec); } -bool path_is_file(const fs::path &p) {-  std::error_code ec;-  return fs::is_regular_file(p, ec);+bool path_is_file(const fs::path& p) {+    std::error_code ec;+    return fs::is_regular_file(p, ec); } -bool path_is_symlink(const fs::path &p) {-  std::error_code ec;-  return fs::is_symlink(fs::symlink_status(p, ec));+bool path_is_symlink(const fs::path& p) {+    std::error_code ec;+    return fs::is_symlink(fs::symlink_status(p, ec)); } -std::optional<std::uint64_t> path_file_size(const fs::path &p) {-  std::error_code ec;-  const auto n = fs::file_size(p, ec);-  if (ec)-    return std::nullopt;-  return static_cast<std::uint64_t>(n);+std::optional<std::uint64_t> path_file_size(const fs::path& p) {+    std::error_code ec;+    const auto n = fs::file_size(p, ec);+    if (ec)+        return std::nullopt;+    return static_cast<std::uint64_t>(n); } -std::string basename_string(const fs::path &p) {-  return path_to_bytes(p.filename());+std::string basename_string(const fs::path& p) {+    return path_to_bytes(p.filename()); } -std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path &p) {+std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p) { #if defined(_WIN32)-  std::ifstream in(p, std::ios::binary);-  if (!in)-    return std::nullopt;-  in.seekg(0, std::ios::end);-  const std::streamoff n = in.tellg();-  if (n < 0)-    return std::nullopt;-  in.seekg(0, std::ios::beg);-  std::vector<std::uint8_t> data(static_cast<std::size_t>(n));-  if (n > 0 && !in.read(reinterpret_cast<char *>(data.data()), n)) {-    return std::nullopt;-  }-  return data;+    std::ifstream in(p, std::ios::binary);+    if (!in)+        return std::nullopt;+    in.seekg(0, std::ios::end);+    const std::streamoff n = in.tellg();+    if (n < 0)+        return std::nullopt;+    in.seekg(0, std::ios::beg);+    std::vector<std::uint8_t> data(static_cast<std::size_t>(n));+    if (n > 0 && !in.read(reinterpret_cast<char*>(data.data()), n)) {+        return std::nullopt;+    }+    return data; #else-  const int fd = ::open(p.c_str(), O_RDONLY);-  if (fd < 0)-    return std::nullopt;-  struct stat st {};-  if (::fstat(fd, &st) != 0 || st.st_size < 0) {-    ::close(fd);-    return std::nullopt;-  }-  std::vector<std::uint8_t> data(static_cast<std::size_t>(st.st_size));-  std::size_t done = 0;-  while (done < data.size()) {-    const ssize_t n = ::read(fd, data.data() + done, data.size() - done);-    if (n > 0) {-      done += static_cast<std::size_t>(n);-    } else if (n < 0 && errno == EINTR) {-      continue;-    } else {-      ::close(fd);-      return std::nullopt;+    const int fd = ::open(p.c_str(), O_RDONLY);+    if (fd < 0)+        return std::nullopt;+    struct stat st {};+    if (::fstat(fd, &st) != 0 || st.st_size < 0) {+        ::close(fd);+        return std::nullopt;     }-  }-  ::close(fd);-  return data;+    std::vector<std::uint8_t> data(static_cast<std::size_t>(st.st_size));+    std::size_t done = 0;+    while (done < data.size()) {+        const ssize_t n = ::read(fd, data.data() + done, data.size() - done);+        if (n > 0) {+            done += static_cast<std::size_t>(n);+        } else if (n < 0 && errno == EINTR) {+            continue;+        } else {+            ::close(fd);+            return std::nullopt;+        }+    }+    ::close(fd);+    return data; #endif } -Result<std::vector<std::uint8_t>> read_file(const fs::path &p) {-  auto data = read_file_opt(p);-  if (!data)-    return fail_io("cannot read " + path_display(p));-  return *data;+Result<std::vector<std::uint8_t>> read_file(const fs::path& p) {+    auto data = read_file_opt(p);+    if (!data)+        return fail_io("cannot read " + path_display(p));+    return *data; } -static bool sync_file_path(const fs::path &p) {+static bool sync_file_path(const fs::path& p) { #if defined(_WIN32)-  const int fd = _wopen(p.c_str(), _O_RDWR | _O_BINARY);-  if (fd < 0)-    return false;-  const bool ok = _commit(fd) == 0;-  _close(fd);-  return ok;+    const int fd = _wopen(p.c_str(), _O_RDWR | _O_BINARY);+    if (fd < 0)+        return false;+    const bool ok = _commit(fd) == 0;+    _close(fd);+    return ok; #else-  const int fd = ::open(p.c_str(), O_RDONLY);-  if (fd < 0)-    return false;-  const bool ok = ::fsync(fd) == 0;-  ::close(fd);-  return ok;+    const int fd = ::open(p.c_str(), O_RDONLY);+    if (fd < 0)+        return false;+    const bool ok = ::fsync(fd) == 0;+    ::close(fd);+    return ok; #endif } -static void sync_parent_directory(const fs::path &p) {+static void sync_parent_directory(const fs::path& p) { #if defined(_WIN32)-  (void)p;+    (void)p; #else-  const fs::path parent = p.parent_path();-  if (parent.empty())-    return;+    const fs::path parent = p.parent_path();+    if (parent.empty())+        return; #if defined(__linux__)-  const int fd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY);+    const int fd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY); #else-  const int fd = ::open(parent.c_str(), O_RDONLY);+    const int fd = ::open(parent.c_str(), O_RDONLY); #endif-  if (fd >= 0) {-    (void)::fsync(fd);-    ::close(fd);-  }+    if (fd >= 0) {+        (void)::fsync(fd);+        ::close(fd);+    } #endif } -static bool replace_file(const fs::path &from, const fs::path &to) {+static bool replace_file(const fs::path& from, const fs::path& to) { #if defined(_WIN32)-  return MoveFileExW(from.c_str(), to.c_str(),-                     MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;+    return MoveFileExW(from.c_str(), to.c_str(),+                       MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; #else-  return std::rename(from.c_str(), to.c_str()) == 0;+    return std::rename(from.c_str(), to.c_str()) == 0; #endif } -bool write_file(const fs::path &p, Bytes data) {-  std::error_code ec;-  if (!p.parent_path().empty())-    fs::create_directories(p.parent_path(), ec);+bool write_file(const fs::path& p, Bytes data) {+    std::error_code ec;+    if (!p.parent_path().empty())+        fs::create_directories(p.parent_path(), ec); #if defined(_WIN32)-  std::ofstream out(p, std::ios::binary | std::ios::trunc);-  if (!out)-    return false;-  if (!data.empty()) {-    out.write(reinterpret_cast<const char *>(data.data()),-              static_cast<std::streamsize>(data.size()));-  }-  out.flush();-  return static_cast<bool>(out);+    std::ofstream out(p, std::ios::binary | std::ios::trunc);+    if (!out)+        return false;+    if (!data.empty()) {+        out.write(reinterpret_cast<const char*>(data.data()),+                  static_cast<std::streamsize>(data.size()));+    }+    out.flush();+    return static_cast<bool>(out); #else-  const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);-  if (fd < 0)-    return false;-  std::size_t done = 0;-  while (done < data.size()) {-    const ssize_t n = ::write(fd, data.data() + done, data.size() - done);-    if (n > 0) {-      done += static_cast<std::size_t>(n);-    } else if (n < 0 && errno == EINTR) {-      continue;-    } else {-      ::close(fd);-      return false;+    const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);+    if (fd < 0)+        return false;+    std::size_t done = 0;+    while (done < data.size()) {+        const ssize_t n = ::write(fd, data.data() + done, data.size() - done);+        if (n > 0) {+            done += static_cast<std::size_t>(n);+        } else if (n < 0 && errno == EINTR) {+            continue;+        } else {+            ::close(fd);+            return false;+        }     }-  }-  if (::close(fd) != 0)-    return false;-  return true;+    if (::close(fd) != 0)+        return false;+    return true; #endif } -bool append_file(const fs::path &p, Bytes data) {-  std::error_code ec;-  if (!p.parent_path().empty())-    fs::create_directories(p.parent_path(), ec);+bool append_file(const fs::path& p, Bytes data) {+    std::error_code ec;+    if (!p.parent_path().empty())+        fs::create_directories(p.parent_path(), ec); #if defined(_WIN32)-  std::ofstream out(p, std::ios::binary | std::ios::app);-  if (!out)-    return false;-  if (!data.empty()) {-    out.write(reinterpret_cast<const char *>(data.data()),-              static_cast<std::streamsize>(data.size()));-  }-  out.flush();-  return static_cast<bool>(out);+    std::ofstream out(p, std::ios::binary | std::ios::app);+    if (!out)+        return false;+    if (!data.empty()) {+        out.write(reinterpret_cast<const char*>(data.data()),+                  static_cast<std::streamsize>(data.size()));+    }+    out.flush();+    return static_cast<bool>(out); #else-  const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);-  if (fd < 0)-    return false;-  std::size_t done = 0;-  while (done < data.size()) {-    const ssize_t n = ::write(fd, data.data() + done, data.size() - done);-    if (n > 0) {-      done += static_cast<std::size_t>(n);-    } else if (n < 0 && errno == EINTR) {-      continue;-    } else {-      ::close(fd);-      return false;+    const int fd = ::open(p.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644);+    if (fd < 0)+        return false;+    std::size_t done = 0;+    while (done < data.size()) {+        const ssize_t n = ::write(fd, data.data() + done, data.size() - done);+        if (n > 0) {+            done += static_cast<std::size_t>(n);+        } else if (n < 0 && errno == EINTR) {+            continue;+        } else {+            ::close(fd);+            return false;+        }     }-  }-  if (::close(fd) != 0)-    return false;-  return true;+    if (::close(fd) != 0)+        return false;+    return true; #endif } -bool write_atomic(const fs::path &tmp_path, const fs::path &final_path,-                  Bytes data) {-  std::error_code ec;-  if (!tmp_path.parent_path().empty())-    fs::create_directories(tmp_path.parent_path(), ec);-  if (!final_path.parent_path().empty())-    fs::create_directories(final_path.parent_path(), ec);-  if (!write_file(tmp_path, data))-    return false;-  if (!sync_file_path(tmp_path)) {-    remove_file(tmp_path);-    return false;-  }-  if (!replace_file(tmp_path, final_path)) {-    remove_file(tmp_path);-    return false;-  }-  sync_parent_directory(final_path);-  return true;+bool write_atomic(const fs::path& tmp_path, const fs::path& final_path, Bytes data) {+    std::error_code ec;+    if (!tmp_path.parent_path().empty())+        fs::create_directories(tmp_path.parent_path(), ec);+    if (!final_path.parent_path().empty())+        fs::create_directories(final_path.parent_path(), ec);+    if (!write_file(tmp_path, data))+        return false;+    if (!sync_file_path(tmp_path)) {+        remove_file(tmp_path);+        return false;+    }+    if (!replace_file(tmp_path, final_path)) {+        remove_file(tmp_path);+        return false;+    }+    sync_parent_directory(final_path);+    return true; } -bool write_atomic(const fs::path &final_path, Bytes data) {-  const fs::path dir = final_path.parent_path();-  const std::string name = basename_string(final_path);-  const std::string tmp_name =-      "." + name + ".tmp." +-      std::to_string(static_cast<unsigned long>(random_u64()));-  return write_atomic(dir / tmp_name, final_path, data);+bool write_atomic(const fs::path& final_path, Bytes data) {+    const fs::path dir = final_path.parent_path();+    const std::string name = basename_string(final_path);+    const std::string tmp_name =+        "." + name + ".tmp." + std::to_string(static_cast<unsigned long>(random_u64()));+    return write_atomic(dir / tmp_name, final_path, data); } -bool ensure_directory(const fs::path &p) {-  std::error_code ec;-  fs::create_directories(p, ec);-  return !ec;+bool ensure_directory(const fs::path& p) {+    std::error_code ec;+    fs::create_directories(p, ec);+    return !ec; } -bool remove_file(const fs::path &p) {-  std::error_code ec;-  return fs::remove(p, ec);+bool remove_file(const fs::path& p) {+    std::error_code ec;+    return fs::remove(p, ec); } -bool remove_tree(const fs::path &p) {-  std::error_code ec;-  fs::remove_all(p, ec);-  return !ec;+bool remove_tree(const fs::path& p) {+    std::error_code ec;+    fs::remove_all(p, ec);+    return !ec; } -std::vector<std::string> list_directory(const fs::path &p) {-  std::vector<std::string> out;+std::vector<std::string> list_directory(const fs::path& p) {+    std::vector<std::string> out; #if defined(_WIN32)-  std::error_code ec;-  fs::directory_iterator it(p, ec);-  if (ec)-    return out;-  for (const auto &entry : it)-    out.push_back(path_to_bytes(entry.path().filename()));+    std::error_code ec;+    fs::directory_iterator it(p, ec);+    if (ec)+        return out;+    for (const auto& entry : it)+        out.push_back(path_to_bytes(entry.path().filename())); #else-  DIR *dir = ::opendir(p.c_str());-  if (dir == nullptr)-    return out;-  while (dirent *entry = ::readdir(dir)) {-    const char *name = entry->d_name;-    if (std::strcmp(name, ".") == 0 || std::strcmp(name, "..") == 0)-      continue;-    out.emplace_back(name);-  }-  ::closedir(dir);+    DIR* dir = ::opendir(p.c_str());+    if (dir == nullptr)+        return out;+    while (dirent* entry = ::readdir(dir)) {+        const char* name = entry->d_name;+        if (std::strcmp(name, ".") == 0 || std::strcmp(name, "..") == 0)+            continue;+        out.emplace_back(name);+    }+    ::closedir(dir); #endif-  return out;+    return out; } -bool same_or_under(const fs::path &child, const fs::path &parent) {-  std::error_code ec;-  const fs::path c = fs::weakly_canonical(child, ec);-  if (ec)-    return false;-  const fs::path p = fs::weakly_canonical(parent, ec);-  if (ec)-    return false;-  auto ci = c.begin();-  auto pi = p.begin();-  for (; pi != p.end(); ++pi, ++ci) {-    if (ci == c.end() || *ci != *pi)-      return false;-  }-  return true;+bool same_or_under(const fs::path& child, const fs::path& parent) {+    std::error_code ec;+    const fs::path c = fs::weakly_canonical(child, ec);+    if (ec)+        return false;+    const fs::path p = fs::weakly_canonical(parent, ec);+    if (ec)+        return false;+    auto ci = c.begin();+    auto pi = p.begin();+    for (; pi != p.end(); ++pi, ++ci) {+        if (ci == c.end() || *ci != *pi)+            return false;+    }+    return true; } -std::optional<std::string> path_read_symlink(const fs::path &p) {-  std::error_code ec;-  const fs::path target = fs::read_symlink(p, ec);-  if (ec)-    return std::nullopt;-  return path_to_bytes(target);+std::optional<std::string> path_read_symlink(const fs::path& p) {+    std::error_code ec;+    const fs::path target = fs::read_symlink(p, ec);+    if (ec)+        return std::nullopt;+    return path_to_bytes(target); }  #if defined(_WIN32)-static std::optional<std::uint64_t> mtime_from_file_time(const fs::path &p) {-  std::error_code ec;-  const auto ft = fs::last_write_time(p, ec);-  if (ec)-    return std::nullopt;-  // Convert the filesystem clock value to Unix nanoseconds without assuming-  // a particular epoch offset: compare against a known reference point.-  const auto now_file = fs::file_time_type::clock::now();-  const auto now_sys = std::chrono::system_clock::now();-  const auto delta =-      std::chrono::duration_cast<std::chrono::nanoseconds>(ft - now_file);-  const auto sys = now_sys + delta;-  return static_cast<std::uint64_t>(-      std::chrono::duration_cast<std::chrono::nanoseconds>(-          sys.time_since_epoch())-          .count());+static std::optional<std::uint64_t> mtime_from_file_time(const fs::path& p) {+    std::error_code ec;+    const auto ft = fs::last_write_time(p, ec);+    if (ec)+        return std::nullopt;+    // Convert the filesystem clock value to Unix nanoseconds without assuming+    // a particular epoch offset: compare against a known reference point.+    const auto now_file = fs::file_time_type::clock::now();+    const auto now_sys = std::chrono::system_clock::now();+    const auto delta = std::chrono::duration_cast<std::chrono::nanoseconds>(ft - now_file);+    const auto sys = now_sys + delta;+    return static_cast<std::uint64_t>(+        std::chrono::duration_cast<std::chrono::nanoseconds>(sys.time_since_epoch()).count()); } #endif -std::optional<StatInfo> stat_path(const fs::path &p) {+std::optional<StatInfo> stat_path(const fs::path& p) { #if defined(_WIN32)-  std::error_code ec;-  const auto status = fs::symlink_status(p, ec);-  if (ec || status.type() == fs::file_type::not_found)-    return std::nullopt;-  StatInfo info;-  if (fs::is_symlink(status)) {-    info.kind = 3;-  } else if (fs::is_directory(status)) {-    info.kind = 2;-  } else if (fs::is_regular_file(status)) {-    info.kind = 1;-  } else {-    return std::nullopt;-  }-  if (info.kind == 1) {-    info.size = path_file_size(p).value_or(0);-  }-  info.mtime_ns = mtime_from_file_time(p).value_or(0);-  return info;+    std::error_code ec;+    const auto status = fs::symlink_status(p, ec);+    if (ec || status.type() == fs::file_type::not_found)+        return std::nullopt;+    StatInfo info;+    if (fs::is_symlink(status)) {+        info.kind = 3;+    } else if (fs::is_directory(status)) {+        info.kind = 2;+    } else if (fs::is_regular_file(status)) {+        info.kind = 1;+    } else {+        return std::nullopt;+    }+    if (info.kind == 1) {+        info.size = path_file_size(p).value_or(0);+    }+    info.mtime_ns = mtime_from_file_time(p).value_or(0);+    return info; #else-  struct stat st {};-  if (::lstat(p.c_str(), &st) != 0)-    return std::nullopt;-  StatInfo info;-  if (S_ISLNK(st.st_mode)) {-    info.kind = 3;-  } else if (S_ISDIR(st.st_mode)) {-    info.kind = 2;-  } else if (S_ISREG(st.st_mode)) {-    info.kind = 1;-  } else {-    return std::nullopt;-  }-  info.executable = (st.st_mode & 0111) != 0;-  info.size = static_cast<std::uint64_t>(st.st_size);-  info.inode = static_cast<std::uint64_t>(st.st_ino);+    struct stat st {};+    if (::lstat(p.c_str(), &st) != 0)+        return std::nullopt;+    StatInfo info;+    if (S_ISLNK(st.st_mode)) {+        info.kind = 3;+    } else if (S_ISDIR(st.st_mode)) {+        info.kind = 2;+    } else if (S_ISREG(st.st_mode)) {+        info.kind = 1;+    } else {+        return std::nullopt;+    }+    info.executable = (st.st_mode & 0111) != 0;+    info.size = static_cast<std::uint64_t>(st.st_size);+    info.inode = static_cast<std::uint64_t>(st.st_ino); #if defined(__APPLE__)-  info.mtime_ns =-      static_cast<std::uint64_t>(st.st_mtimespec.tv_sec) * 1'000'000'000ull +-      static_cast<std::uint64_t>(st.st_mtimespec.tv_nsec);+    info.mtime_ns = static_cast<std::uint64_t>(st.st_mtimespec.tv_sec) * 1'000'000'000ull ++                    static_cast<std::uint64_t>(st.st_mtimespec.tv_nsec); #else-  info.mtime_ns =-      static_cast<std::uint64_t>(st.st_mtim.tv_sec) * 1'000'000'000ull +-      static_cast<std::uint64_t>(st.st_mtim.tv_nsec);+    info.mtime_ns = static_cast<std::uint64_t>(st.st_mtim.tv_sec) * 1'000'000'000ull ++                    static_cast<std::uint64_t>(st.st_mtim.tv_nsec); #endif-  return info;+    return info; #endif } -std::optional<std::uint64_t> file_mtime_ns(const fs::path &p) {-  const auto info = stat_path(p);-  if (!info)-    return std::nullopt;-  return info->mtime_ns;+std::optional<std::uint64_t> file_mtime_ns(const fs::path& p) {+    const auto info = stat_path(p);+    if (!info)+        return std::nullopt;+    return info->mtime_ns; } -std::optional<std::uint64_t> file_inode(const fs::path &p) {-  const auto info = stat_path(p);-  if (!info)-    return std::nullopt;-  return info->inode;+std::optional<std::uint64_t> file_inode(const fs::path& p) {+    const auto info = stat_path(p);+    if (!info)+        return std::nullopt;+    return info->inode; } -bool is_executable(const fs::path &p) {-  const auto info = stat_path(p);-  return info && info->executable;+bool is_executable(const fs::path& p) {+    const auto info = stat_path(p);+    return info && info->executable; }  // ---------------------------------------------------------------------------@@ -1144,399 +1141,384 @@ // ---------------------------------------------------------------------------  static std::string_view trim_view(std::string_view s) {-  std::size_t start = 0;-  std::size_t end = s.size();-  while (start < end) {-    const char c = s[start];-    if (c != ' ' && c != '\t' && c != '\r' && c != '\n')-      break;-    ++start;-  }-  while (end > start) {-    const char c = s[end - 1];-    if (c != ' ' && c != '\t' && c != '\r' && c != '\n')-      break;-    --end;-  }-  return s.substr(start, end - start);+    std::size_t start = 0;+    std::size_t end = s.size();+    while (start < end) {+        const char c = s[start];+        if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+            break;+        ++start;+    }+    while (end > start) {+        const char c = s[end - 1];+        if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+            break;+        --end;+    }+    return s.substr(start, end - start); }  static std::string trim_copy(std::string_view s) {-  return std::string(trim_view(s));+    return std::string(trim_view(s)); } -std::optional<std::string> repo_config_value(const fs::path &repo_root,-                                             std::string_view key) {-  const auto data = read_file_opt(repo_root / ".veins" / "config");-  if (!data)-    return std::nullopt;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    const std::string_view line = trim_view(text.substr(start, end - start));-    if (!line.empty() && line.front() != '#') {-      const std::size_t eq = line.find('=');-      if (eq != std::string_view::npos) {-        const std::string_view k = trim_view(line.substr(0, eq));-        if (k == key)-          return trim_copy(line.substr(eq + 1));-      }+std::optional<std::string> repo_config_value(const fs::path& repo_root, std::string_view key) {+    const auto data = read_file_opt(repo_root / ".veins" / "config");+    if (!data)+        return std::nullopt;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        const std::string_view line = trim_view(text.substr(start, end - start));+        if (!line.empty() && line.front() != '#') {+            const std::size_t eq = line.find('=');+            if (eq != std::string_view::npos) {+                const std::string_view k = trim_view(line.substr(0, eq));+                if (k == key)+                    return trim_copy(line.substr(eq + 1));+            }+        }+        if (end == text.size())+            break;+        start = end + 1;     }-    if (end == text.size())-      break;-    start = end + 1;-  }-  return std::nullopt;+    return std::nullopt; }  static std::string strip_comment(std::string_view v) {-  const std::size_t hash = v.find('#');-  if (hash != std::string_view::npos)-    v = v.substr(0, hash);-  return trim_copy(v);+    const std::size_t hash = v.find('#');+    if (hash != std::string_view::npos)+        v = v.substr(0, hash);+    return trim_copy(v); } -bool repo_config_bool(const fs::path &repo_root, std::string_view key,-                      bool fallback) {-  const auto v = repo_config_value(repo_root, key);-  if (!v)-    return fallback;-  const std::string value = strip_comment(*v);-  return value == "true" || value == "1" || value == "yes" || value == "on";+bool repo_config_bool(const fs::path& repo_root, std::string_view key, bool fallback) {+    const auto v = repo_config_value(repo_root, key);+    if (!v)+        return fallback;+    const std::string value = strip_comment(*v);+    return value == "true" || value == "1" || value == "yes" || value == "on"; } -bool repo_config_set(const fs::path &repo_root, std::string_view key,-                     std::string_view value) {-  const fs::path path = repo_root / ".veins" / "config";-  const auto data = read_file_opt(path);-  std::string out;-  if (data) {-    std::string_view text(reinterpret_cast<const char *>(data->data()),-                          data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-      std::size_t end = text.find('\n', start);-      if (end == std::string_view::npos)-        end = text.size();-      const std::string_view line = text.substr(start, end - start);-      const std::string_view t = trim_view(line);-      const std::size_t eq = t.find('=');-      const bool is_key =-          eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;-      if (!is_key) {-        out.append(line);-        if (end < text.size())-          out.push_back('\n');-      }-      if (end == text.size())-        break;-      start = end + 1;+bool repo_config_set(const fs::path& repo_root, std::string_view key, std::string_view value) {+    const fs::path path = repo_root / ".veins" / "config";+    const auto data = read_file_opt(path);+    std::string out;+    if (data) {+        std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+        std::size_t start = 0;+        while (start <= text.size()) {+            std::size_t end = text.find('\n', start);+            if (end == std::string_view::npos)+                end = text.size();+            const std::string_view line = text.substr(start, end - start);+            const std::string_view t = trim_view(line);+            const std::size_t eq = t.find('=');+            const bool is_key = eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;+            if (!is_key) {+                out.append(line);+                if (end < text.size())+                    out.push_back('\n');+            }+            if (end == text.size())+                break;+            start = end + 1;+        }     }-  }-  out.append(key);-  out.append(" = ");-  out.append(value);-  out.push_back('\n');-  return write_file(path, bytes_of(out));+    out.append(key);+    out.append(" = ");+    out.append(value);+    out.push_back('\n');+    return write_file(path, bytes_of(out)); } -bool repo_config_remove(const fs::path &repo_root, std::string_view key) {-  const fs::path path = repo_root / ".veins" / "config";-  const auto data = read_file_opt(path);-  std::string out;-  if (data) {-    std::string_view text(reinterpret_cast<const char *>(data->data()),-                          data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-      std::size_t end = text.find('\n', start);-      if (end == std::string_view::npos)-        end = text.size();-      const std::string_view line = text.substr(start, end - start);-      const std::string_view t = trim_view(line);-      const std::size_t eq = t.find('=');-      const bool is_key =-          eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;-      if (!is_key) {-        out.append(line);-        if (end < text.size())-          out.push_back('\n');-      }-      if (end == text.size())-        break;-      start = end + 1;+bool repo_config_remove(const fs::path& repo_root, std::string_view key) {+    const fs::path path = repo_root / ".veins" / "config";+    const auto data = read_file_opt(path);+    std::string out;+    if (data) {+        std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+        std::size_t start = 0;+        while (start <= text.size()) {+            std::size_t end = text.find('\n', start);+            if (end == std::string_view::npos)+                end = text.size();+            const std::string_view line = text.substr(start, end - start);+            const std::string_view t = trim_view(line);+            const std::size_t eq = t.find('=');+            const bool is_key = eq != std::string_view::npos && trim_view(t.substr(0, eq)) == key;+            if (!is_key) {+                out.append(line);+                if (end < text.size())+                    out.push_back('\n');+            }+            if (end == text.size())+                break;+            start = end + 1;+        }     }-  }-  return write_file(path, bytes_of(out));+    return write_file(path, bytes_of(out)); }  static fs::path user_config_path() { #if defined(_WIN32)-  const char *home = std::getenv("USERPROFILE");+    const char* home = std::getenv("USERPROFILE"); #else-  const char *home = std::getenv("HOME");+    const char* home = std::getenv("HOME"); #endif-  if (home == nullptr || *home == '\0')-    return {};-  return path_from_bytes(home) / ".local" / "config" / "veins" / "veins.toml";+    if (home == nullptr || *home == '\0')+        return {};+    return path_from_bytes(home) / ".local" / "config" / "veins" / "veins.toml"; }  static std::optional<std::string> unquote_toml(std::string_view raw) {-  raw = trim_view(raw);-  if (raw.size() >= 2) {-    if ((raw.front() == '\'' && raw.back() == '\'') ||-        (raw.front() == '"' && raw.back() == '"')) {-      const char quote = raw.front();-      std::string out;-      for (std::size_t i = 1; i + 1 < raw.size(); ++i) {-        const char c = raw[i];-        if (quote == '"' && c == '\\' && i + 2 < raw.size()) {-          const char next = raw[i + 1];-          if (next == '"')-            out.push_back('"');-          else if (next == '\\')-            out.push_back('\\');-          else if (next == 'n')-            out.push_back('\n');-          else if (next == 'r')-            out.push_back('\r');-          else if (next == 't')-            out.push_back('\t');-          else {-            out.push_back('\\');-            out.push_back(next);-          }-          ++i;-        } else {-          out.push_back(c);+    raw = trim_view(raw);+    if (raw.size() >= 2) {+        if ((raw.front() == '\'' && raw.back() == '\'') ||+            (raw.front() == '"' && raw.back() == '"')) {+            const char quote = raw.front();+            std::string out;+            for (std::size_t i = 1; i + 1 < raw.size(); ++i) {+                const char c = raw[i];+                if (quote == '"' && c == '\\' && i + 2 < raw.size()) {+                    const char next = raw[i + 1];+                    if (next == '"')+                        out.push_back('"');+                    else if (next == '\\')+                        out.push_back('\\');+                    else if (next == 'n')+                        out.push_back('\n');+                    else if (next == 'r')+                        out.push_back('\r');+                    else if (next == 't')+                        out.push_back('\t');+                    else {+                        out.push_back('\\');+                        out.push_back(next);+                    }+                    ++i;+                } else {+                    out.push_back(c);+                }+            }+            return out;         }-      }-      return out;     }-  }-  if (raw.empty())-    return std::nullopt;-  return std::string(raw);+    if (raw.empty())+        return std::nullopt;+    return std::string(raw); }  static std::optional<std::string> user_config_value(bool want_name) {-  const fs::path path = user_config_path();-  if (path.empty())-    return std::nullopt;-  const auto data = read_file_opt(path);-  if (!data)-    return std::nullopt;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  bool in_user = false;-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    const std::string_view line = trim_view(text.substr(start, end - start));-    if (!line.empty() && line.front() != '#') {-      if (line.front() == '[') {-        const std::size_t close = line.find(']');-        if (close != std::string_view::npos) {-          in_user = trim_view(line.substr(1, close - 1)) == "user";-        }-      } else {-        const std::size_t eq = line.find('=');-        if (eq != std::string_view::npos) {-          const std::string_view key = trim_view(line.substr(0, eq));-          const bool matches =-              (in_user && key == (want_name ? "name" : "email")) ||-              (!in_user && key == (want_name ? "user.name" : "user.email"));-          if (matches) {-            std::string_view value = line.substr(eq + 1);-            std::string value_copy = strip_comment(value);-            auto decoded = unquote_toml(value_copy);-            if (decoded && !decoded->empty())-              return decoded;-          }+    const fs::path path = user_config_path();+    if (path.empty())+        return std::nullopt;+    const auto data = read_file_opt(path);+    if (!data)+        return std::nullopt;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    bool in_user = false;+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        const std::string_view line = trim_view(text.substr(start, end - start));+        if (!line.empty() && line.front() != '#') {+            if (line.front() == '[') {+                const std::size_t close = line.find(']');+                if (close != std::string_view::npos) {+                    in_user = trim_view(line.substr(1, close - 1)) == "user";+                }+            } else {+                const std::size_t eq = line.find('=');+                if (eq != std::string_view::npos) {+                    const std::string_view key = trim_view(line.substr(0, eq));+                    const bool matches =+                        (in_user && key == (want_name ? "name" : "email")) ||+                        (!in_user && key == (want_name ? "user.name" : "user.email"));+                    if (matches) {+                        std::string_view value = line.substr(eq + 1);+                        std::string value_copy = strip_comment(value);+                        auto decoded = unquote_toml(value_copy);+                        if (decoded && !decoded->empty())+                            return decoded;+                    }+                }+            }         }-      }+        if (end == text.size())+            break;+        start = end + 1;     }-    if (end == text.size())-      break;-    start = end + 1;-  }-  return std::nullopt;+    return std::nullopt; }  std::optional<std::string> user_config_author_name() {-  return user_config_value(true);+    return user_config_value(true); } std::optional<std::string> user_config_author_email() {-  return user_config_value(false);+    return user_config_value(false); }  static std::string toml_quote(std::string_view value) {-  std::string out;-  out.push_back('"');-  for (char c : value) {-    switch (c) {-    case '"':-      out += "\\\"";-      break;-    case '\\':-      out += "\\\\";-      break;-    case '\n':-      out += "\\n";-      break;-    case '\r':-      out += "\\r";-      break;-    case '\t':-      out += "\\t";-      break;-    default:-      out.push_back(c);-      break;+    std::string out;+    out.push_back('"');+    for (char c : value) {+        switch (c) {+        case '"':+            out += "\\\"";+            break;+        case '\\':+            out += "\\\\";+            break;+        case '\n':+            out += "\\n";+            break;+        case '\r':+            out += "\\r";+            break;+        case '\t':+            out += "\\t";+            break;+        default:+            out.push_back(c);+            break;+        }     }-  }-  out.push_back('"');-  return out;+    out.push_back('"');+    return out; } -static bool update_user_config(std::string_view key,-                               const std::optional<std::string> &value) {-  const bool want_name = key == "user.name";-  const bool want_email = key == "user.email";-  if (!want_name && !want_email)-    return false;-  const fs::path path = user_config_path();-  if (path.empty())-    return false;+static bool update_user_config(std::string_view key, const std::optional<std::string>& value) {+    const bool want_name = key == "user.name";+    const bool want_email = key == "user.email";+    if (!want_name && !want_email)+        return false;+    const fs::path path = user_config_path();+    if (path.empty())+        return false; -  std::vector<std::string> lines;-  if (const auto data = read_file_opt(path)) {-    std::string_view text(reinterpret_cast<const char *>(data->data()),-                          data->size());-    std::size_t start = 0;-    while (start <= text.size()) {-      std::size_t end = text.find('\n', start);-      if (end == std::string_view::npos)-        end = text.size();-      lines.emplace_back(text.substr(start, end - start));-      if (end == text.size())-        break;-      start = end + 1;+    std::vector<std::string> lines;+    if (const auto data = read_file_opt(path)) {+        std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+        std::size_t start = 0;+        while (start <= text.size()) {+            std::size_t end = text.find('\n', start);+            if (end == std::string_view::npos)+                end = text.size();+            lines.emplace_back(text.substr(start, end - start));+            if (end == text.size())+                break;+            start = end + 1;+        }     }-  } -  std::vector<std::string> out;-  out.reserve(lines.size() + 1);-  bool in_user = false;-  for (const auto &line : lines) {-    const std::string_view t = trim_view(line);-    if (!t.empty() && t.front() == '[') {-      const std::size_t close = t.find(']');-      in_user = close != std::string_view::npos &&-                trim_view(t.substr(1, close - 1)) == "user";-      out.push_back(line);-      continue;-    }-    std::size_t eq = t.find('=');-    if (t.empty() || t.front() == '#' || eq == std::string_view::npos) {-      out.push_back(line);-      continue;+    std::vector<std::string> out;+    out.reserve(lines.size() + 1);+    bool in_user = false;+    for (const auto& line : lines) {+        const std::string_view t = trim_view(line);+        if (!t.empty() && t.front() == '[') {+            const std::size_t close = t.find(']');+            in_user =+                close != std::string_view::npos && trim_view(t.substr(1, close - 1)) == "user";+            out.push_back(line);+            continue;+        }+        std::size_t eq = t.find('=');+        if (t.empty() || t.front() == '#' || eq == std::string_view::npos) {+            out.push_back(line);+            continue;+        }+        const std::string_view k = trim_view(t.substr(0, eq));+        const bool remove_name =+            (in_user && want_name && k == "name") || (!in_user && want_name && k == "user.name");+        const bool remove_email = (in_user && want_email && k == "email") ||+                                  (!in_user && want_email && k == "user.email");+        if (!remove_name && !remove_email)+            out.push_back(line);     }-    const std::string_view k = trim_view(t.substr(0, eq));-    const bool remove_name = (in_user && want_name && k == "name") ||-                             (!in_user && want_name && k == "user.name");-    const bool remove_email = (in_user && want_email && k == "email") ||-                              (!in_user && want_email && k == "user.email");-    if (!remove_name && !remove_email)-      out.push_back(line);-  } -  if (value) {-    std::string entry = want_name ? "user.name = " : "user.email = ";-    entry += toml_quote(*value);-    out.insert(out.begin(), std::move(entry));-  } else {-    while (!out.empty() && trim_view(out.back()).empty())-      out.pop_back();-  }+    if (value) {+        std::string entry = want_name ? "user.name = " : "user.email = ";+        entry += toml_quote(*value);+        out.insert(out.begin(), std::move(entry));+    } else {+        while (!out.empty() && trim_view(out.back()).empty())+            out.pop_back();+    } -  std::string body;-  for (std::size_t i = 0; i < out.size(); ++i) {-    if (i != 0)-      body.push_back('\n');-    body += out[i];-  }-  if (!out.empty())-    body.push_back('\n');-  return write_file(path, bytes_of(body));+    std::string body;+    for (std::size_t i = 0; i < out.size(); ++i) {+        if (i != 0)+            body.push_back('\n');+        body += out[i];+    }+    if (!out.empty())+        body.push_back('\n');+    return write_file(path, bytes_of(body)); }  bool user_config_set(std::string_view key, std::string_view value) {-  return update_user_config(key, std::string(value));+    return update_user_config(key, std::string(value)); }  bool user_config_remove(std::string_view key) {-  return update_user_config(key, std::nullopt);+    return update_user_config(key, std::nullopt); } -std::optional<std::string> current_bookmark_name(const fs::path &repo_root) {-  return repo_config_value(repo_root, "bookmark.current");+std::optional<std::string> current_bookmark_name(const fs::path& repo_root) {+    return repo_config_value(repo_root, "bookmark.current"); } -bool set_current_bookmark(const fs::path &repo_root, std::string_view name) {-  if (name.empty())-    return repo_config_remove(repo_root, "bookmark.current");-  return repo_config_set(repo_root, "bookmark.current", name);+bool set_current_bookmark(const fs::path& repo_root, std::string_view name) {+    if (name.empty())+        return repo_config_remove(repo_root, "bookmark.current");+    return repo_config_set(repo_root, "bookmark.current", name); } -bool clear_current_bookmark(const fs::path &repo_root) {-  return repo_config_remove(repo_root, "bookmark.current");+bool clear_current_bookmark(const fs::path& repo_root) {+    return repo_config_remove(repo_root, "bookmark.current"); } -static std::optional<std::string> env_value(const char *name) {-  const char *v = std::getenv(name);-  if (v == nullptr)-    return std::nullopt;-  return std::string(v);+static std::optional<std::string> env_value(const char* name) {+    const char* v = std::getenv(name);+    if (v == nullptr)+        return std::nullopt;+    return std::string(v); } -static std::string first_config(const fs::path &repo_root, std::string_view key,-                                bool want_name, const char *env1,-                                const char *env2) {-  if (auto v = repo_config_value(repo_root, key))-    return *v;-  auto user =-      want_name ? user_config_author_name() : user_config_author_email();-  if (user)-    return *user;-  if (auto v = env_value(env1))-    return *v;-  if (auto v = env_value(env2))-    return *v;-  return "unknown";+static std::string first_config(const fs::path& repo_root, std::string_view key, bool want_name,+                                const char* env1, const char* env2) {+    if (auto v = repo_config_value(repo_root, key))+        return *v;+    auto user = want_name ? user_config_author_name() : user_config_author_email();+    if (user)+        return *user;+    if (auto v = env_value(env1))+        return *v;+    if (auto v = env_value(env2))+        return *v;+    return "unknown"; } -Sig identity_signature(const fs::path &repo_root) {-  Sig sig;-  sig.name =-      first_config(repo_root, "user.name", true, "GIT_AUTHOR_NAME", "USER");-  sig.email =-      first_config(repo_root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL");+Sig identity_signature(const fs::path& repo_root) {+    Sig sig;+    sig.name = first_config(repo_root, "user.name", true, "GIT_AUTHOR_NAME", "USER");+    sig.email = first_config(repo_root, "user.email", false, "GIT_AUTHOR_EMAIL", "EMAIL"); #if defined(_WIN32)-  if (sig.name == "unknown") {-    if (auto v = env_value("USERNAME"))-      sig.name = *v;-  }+    if (sig.name == "unknown") {+        if (auto v = env_value("USERNAME"))+            sig.name = *v;+    } #endif-  sig.seconds = unix_now_seconds();-  sig.tz_min = 0;-  return sig;+    sig.seconds = unix_now_seconds();+    sig.tz_min = 0;+    return sig; }  // ---------------------------------------------------------------------------@@ -1543,203 +1525,199 @@ // Ignore rules // --------------------------------------------------------------------------- -IgnoreRules ignore_empty() { return {}; }+IgnoreRules ignore_empty() {+    return {};+} -static std::optional<std::string_view> relative_to(std::string_view base,-                                                   std::string_view path) {-  if (base.empty())-    return path;-  if (path.size() <= base.size())-    return std::nullopt;-  if (path.substr(0, base.size()) != base)-    return std::nullopt;-  if (path[base.size()] != '/')-    return std::nullopt;-  return path.substr(base.size() + 1);+static std::optional<std::string_view> relative_to(std::string_view base, std::string_view path) {+    if (base.empty())+        return path;+    if (path.size() <= base.size())+        return std::nullopt;+    if (path.substr(0, base.size()) != base)+        return std::nullopt;+    if (path[base.size()] != '/')+        return std::nullopt;+    return path.substr(base.size() + 1); } -static void add_ignore_line(IgnoreRules &rules, std::string_view base,-                            std::string_view input) {-  std::string_view line = trim_view(input);-  if (line.empty() || line.front() == '#')-    return;-  bool negated = false;-  std::size_t start = 0;-  if (line.front() == '!') {-    negated = true;-    start = 1;-  }-  if (start >= line.size())-    return;-  std::size_t end = line.size();-  bool dir_only = false;-  if (line[end - 1] == '/') {-    dir_only = true;-    --end;-  }-  if (start >= end)-    return;-  bool anchored = false;-  if (line[start] == '/') {-    anchored = true;-    ++start;-  }-  if (start >= end)-    return;-  const std::string_view pattern = line.substr(start, end - start);-  const bool has_slash = pattern.find('/') != std::string_view::npos;-  rules.items.push_back(IgnoreRule{std::string(pattern), negated, dir_only,-                                   anchored, has_slash, std::string(base)});+static void add_ignore_line(IgnoreRules& rules, std::string_view base, std::string_view input) {+    std::string_view line = trim_view(input);+    if (line.empty() || line.front() == '#')+        return;+    bool negated = false;+    std::size_t start = 0;+    if (line.front() == '!') {+        negated = true;+        start = 1;+    }+    if (start >= line.size())+        return;+    std::size_t end = line.size();+    bool dir_only = false;+    if (line[end - 1] == '/') {+        dir_only = true;+        --end;+    }+    if (start >= end)+        return;+    bool anchored = false;+    if (line[start] == '/') {+        anchored = true;+        ++start;+    }+    if (start >= end)+        return;+    const std::string_view pattern = line.substr(start, end - start);+    const bool has_slash = pattern.find('/') != std::string_view::npos;+    rules.items.push_back(IgnoreRule{std::string(pattern), negated, dir_only, anchored, has_slash,+                                     std::string(base)}); } -void ignore_load_file(IgnoreRules &rules, const fs::path &repo_root,-                      std::string_view base, std::string_view name) {-  const fs::path dir =-      base.empty() ? repo_root : repo_root / path_from_bytes(base);-  const auto data = read_file_opt(dir / path_from_bytes(name));-  if (!data)-    return;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    add_ignore_line(rules, base, text.substr(start, end - start));-    if (end == text.size())-      break;-    start = end + 1;-  }+void ignore_load_file(IgnoreRules& rules, const fs::path& repo_root, std::string_view base,+                      std::string_view name) {+    const fs::path dir = base.empty() ? repo_root : repo_root / path_from_bytes(base);+    const auto data = read_file_opt(dir / path_from_bytes(name));+    if (!data)+        return;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        add_ignore_line(rules, base, text.substr(start, end - start));+        if (end == text.size())+            break;+        start = end + 1;+    } } -void ignore_load_root(IgnoreRules &rules, const fs::path &repo_root) {-  ignore_load_file(rules, repo_root, "", ".vnexclude");-  ignore_load_file(rules, repo_root, "", ".gitignore");+void ignore_load_root(IgnoreRules& rules, const fs::path& repo_root) {+    ignore_load_file(rules, repo_root, "", ".vnexclude");+    ignore_load_file(rules, repo_root, "", ".gitignore"); } -static bool glob_here(std::string_view pattern, std::size_t pi,-                      std::string_view text, std::size_t ti) {-  if (pi >= pattern.size())-    return ti >= text.size();-  const char pc = pattern[pi];-  if (pc == '*') {-    const bool dbl = pi + 1 < pattern.size() && pattern[pi + 1] == '*';-    if (dbl) {-      const std::size_t next = pi + 2;-      if (next < pattern.size() && pattern[next] == '/') {-        const std::size_t after = next + 1;+static bool glob_here(std::string_view pattern, std::size_t pi, std::string_view text,+                      std::size_t ti) {+    if (pi >= pattern.size())+        return ti >= text.size();+    const char pc = pattern[pi];+    if (pc == '*') {+        const bool dbl = pi + 1 < pattern.size() && pattern[pi + 1] == '*';+        if (dbl) {+            const std::size_t next = pi + 2;+            if (next < pattern.size() && pattern[next] == '/') {+                const std::size_t after = next + 1;+                std::size_t j = ti;+                for (;;) {+                    if (glob_here(pattern, after, text, j))+                        return true;+                    if (j >= text.size())+                        break;+                    if (text[j] == '/') {+                        ++j;+                        continue;+                    }+                    ++j;+                    while (j < text.size() && text[j] != '/')+                        ++j;+                }+                return false;+            }+            std::size_t j = ti;+            for (;;) {+                if (glob_here(pattern, next, text, j))+                    return true;+                if (j >= text.size())+                    break;+                ++j;+            }+            return false;+        }         std::size_t j = ti;         for (;;) {-          if (glob_here(pattern, after, text, j))-            return true;-          if (j >= text.size())-            break;-          if (text[j] == '/') {-            ++j;-            continue;-          }-          ++j;-          while (j < text.size() && text[j] != '/')+            if (glob_here(pattern, pi + 1, text, j))+                return true;+            if (j >= text.size() || text[j] == '/')+                break;             ++j;         }         return false;-      }-      std::size_t j = ti;-      for (;;) {-        if (glob_here(pattern, next, text, j))-          return true;-        if (j >= text.size())-          break;-        ++j;-      }-      return false;     }-    std::size_t j = ti;-    for (;;) {-      if (glob_here(pattern, pi + 1, text, j))-        return true;-      if (j >= text.size() || text[j] == '/')-        break;-      ++j;+    if (ti >= text.size())+        return false;+    if (pc == '?') {+        if (text[ti] == '/')+            return false;+        return glob_here(pattern, pi + 1, text, ti + 1);     }-    return false;-  }-  if (ti >= text.size())-    return false;-  if (pc == '?') {-    if (text[ti] == '/')-      return false;+    if (pc != text[ti])+        return false;     return glob_here(pattern, pi + 1, text, ti + 1);-  }-  if (pc != text[ti])-    return false;-  return glob_here(pattern, pi + 1, text, ti + 1); }  bool glob_match(std::string_view pattern, std::string_view text) {-  return glob_here(pattern, 0, text, 0);+    return glob_here(pattern, 0, text, 0); } -static bool rule_matches(const IgnoreRule &rule, std::string_view path,-                         bool is_dir) {-  const auto rel_opt = relative_to(rule.base, path);-  if (!rel_opt)-    return false;-  const std::string_view rel = *rel_opt;-  if (rel.empty())-    return false;-  if (rule.dir_only && !is_dir)-    return false;-  if (!rule.has_slash && !rule.anchored) {-    std::size_t start = 0;-    for (;;) {-      std::size_t end = rel.find('/', start);-      if (end == std::string_view::npos)-        end = rel.size();-      if (glob_here(rule.pattern, 0, rel.substr(start, end - start), 0))-        return true;-      if (end >= rel.size())-        break;-      start = end + 1;+static bool rule_matches(const IgnoreRule& rule, std::string_view path, bool is_dir) {+    const auto rel_opt = relative_to(rule.base, path);+    if (!rel_opt)+        return false;+    const std::string_view rel = *rel_opt;+    if (rel.empty())+        return false;+    if (rule.dir_only && !is_dir)+        return false;+    if (!rule.has_slash && !rule.anchored) {+        std::size_t start = 0;+        for (;;) {+            std::size_t end = rel.find('/', start);+            if (end == std::string_view::npos)+                end = rel.size();+            if (glob_here(rule.pattern, 0, rel.substr(start, end - start), 0))+                return true;+            if (end >= rel.size())+                break;+            start = end + 1;+        }+        return false;     }-    return false;-  }-  return glob_here(rule.pattern, 0, rel, 0);+    return glob_here(rule.pattern, 0, rel, 0); } -bool ignore_ignored(const IgnoreRules &rules, std::string_view path,-                    bool is_dir) {-  bool ignored = false;-  for (const auto &rule : rules.items) {-    if (rule_matches(rule, path, is_dir))-      ignored = !rule.negated;-  }-  return ignored;+bool ignore_ignored(const IgnoreRules& rules, std::string_view path, bool is_dir) {+    bool ignored = false;+    for (const auto& rule : rules.items) {+        if (rule_matches(rule, path, is_dir))+            ignored = !rule.negated;+    }+    return ignored; } -bool ignore_path_ignored(const fs::path &repo_root, std::string_view path) {-  IgnoreRules rules = ignore_empty();-  ignore_load_root(rules, repo_root);-  for (std::size_t i = 0; i < path.size(); ++i) {-    if (path[i] == '/') {-      const std::string_view base = path.substr(0, i);-      ignore_load_file(rules, repo_root, base, ".vnexclude");-      ignore_load_file(rules, repo_root, base, ".gitignore");+bool ignore_path_ignored(const fs::path& repo_root, std::string_view path) {+    IgnoreRules rules = ignore_empty();+    ignore_load_root(rules, repo_root);+    for (std::size_t i = 0; i < path.size(); ++i) {+        if (path[i] == '/') {+            const std::string_view base = path.substr(0, i);+            ignore_load_file(rules, repo_root, base, ".vnexclude");+            ignore_load_file(rules, repo_root, base, ".gitignore");+        }     }-  }-  bool result = false;-  for (std::size_t j = 0; j < path.size(); ++j) {-    if (path[j] == '/') {-      if (ignore_ignored(rules, path.substr(0, j), true)) {-        result = true;-        break;-      }+    bool result = false;+    for (std::size_t j = 0; j < path.size(); ++j) {+        if (path[j] == '/') {+            if (ignore_ignored(rules, path.substr(0, j), true)) {+                result = true;+                break;+            }+        }     }-  }-  if (!result)-    result = ignore_ignored(rules, path, false);-  return result;+    if (!result)+        result = ignore_ignored(rules, path, false);+    return result; }  } // namespace vn--- a/xveins/src/common.h+++ b/xveins/src/common.h@@ -42,38 +42,38 @@ constexpr std::size_t INLINE_THRESHOLD = 16u * 1024u;  enum class ErrorKind {-  None,-  UnexpectedEnd,-  VarintOverflow,-  NonMinimalVarint,-  InvalidValue,-  LimitExceeded,-  InvalidName,-  Duplicate,-  Unsorted,-  TrailingBytes,-  UnsupportedVersion,-  InvalidMagic,-  HashMismatch,-  Corrupt,-  Io,-  Usage,+    None,+    UnexpectedEnd,+    VarintOverflow,+    NonMinimalVarint,+    InvalidValue,+    LimitExceeded,+    InvalidName,+    Duplicate,+    Unsorted,+    TrailingBytes,+    UnsupportedVersion,+    InvalidMagic,+    HashMismatch,+    Corrupt,+    Io,+    Usage, };  std::string_view error_kind_name(ErrorKind kind);  struct Error {-  ErrorKind kind = ErrorKind::None;-  std::size_t offset = 0;-  std::string message;+    ErrorKind kind = ErrorKind::None;+    std::size_t offset = 0;+    std::string message; -  Error() = default;-  Error(ErrorKind k, std::size_t off, std::string msg)-      : kind(k), offset(off), message(std::move(msg)) {}+    Error() = default;+    Error(ErrorKind k, std::size_t off, std::string msg)+        : kind(k), offset(off), message(std::move(msg)) {} -  static Error decode(ErrorKind kind, std::size_t offset);-  static Error io(std::string message);-  static Error usage(std::string message);+    static Error decode(ErrorKind kind, std::size_t offset);+    static Error io(std::string message);+    static Error usage(std::string message); };  #if defined(__cpp_lib_expected) && __cpp_lib_expected >= 202202L@@ -81,43 +81,70 @@ template <typename E> using Unexpected = std::unexpected<E>; #else template <typename E> struct Unexpected {-  E err;-  explicit Unexpected(E value) : err(std::move(value)) {}+    E err;+    explicit Unexpected(E value) : err(std::move(value)) {} };  template <typename T, typename E> class Expected { public:-  Expected(T &&value) : data_(std::in_place_index<0>, std::move(value)) {}-  Expected(const T &value) : data_(std::in_place_index<0>, value) {}-  Expected(Unexpected<E> value)-      : data_(std::in_place_index<1>, std::move(value.err)) {}+    Expected(T&& value) : data_(std::in_place_index<0>, std::move(value)) {}+    Expected(const T& value) : data_(std::in_place_index<0>, value) {}+    Expected(Unexpected<E> value) : data_(std::in_place_index<1>, std::move(value.err)) {} -  [[nodiscard]] bool has_value() const { return data_.index() == 0; }-  explicit operator bool() const { return has_value(); }-  T &operator*() { return std::get<0>(data_); }-  const T &operator*() const { return std::get<0>(data_); }-  T *operator->() { return &std::get<0>(data_); }-  const T *operator->() const { return &std::get<0>(data_); }-  T &value() { return std::get<0>(data_); }-  const T &value() const { return std::get<0>(data_); }-  E &error() { return std::get<1>(data_); }-  const E &error() const { return std::get<1>(data_); }+    [[nodiscard]] bool has_value() const {+        return data_.index() == 0;+    }+    explicit operator bool() const {+        return has_value();+    }+    T& operator*() {+        return std::get<0>(data_);+    }+    const T& operator*() const {+        return std::get<0>(data_);+    }+    T* operator->() {+        return &std::get<0>(data_);+    }+    const T* operator->() const {+        return &std::get<0>(data_);+    }+    T& value() {+        return std::get<0>(data_);+    }+    const T& value() const {+        return std::get<0>(data_);+    }+    E& error() {+        return std::get<1>(data_);+    }+    const E& error() const {+        return std::get<1>(data_);+    }  private:-  std::variant<T, E> data_;+    std::variant<T, E> data_; };  template <typename E> class Expected<void, E> { public:-  Expected() = default;-  Expected(Unexpected<E> value) : error_(std::move(value.err)) {}-  [[nodiscard]] bool has_value() const { return !error_.has_value(); }-  explicit operator bool() const { return has_value(); }-  E &error() { return *error_; }-  const E &error() const { return *error_; }+    Expected() = default;+    Expected(Unexpected<E> value) : error_(std::move(value.err)) {}+    [[nodiscard]] bool has_value() const {+        return !error_.has_value();+    }+    explicit operator bool() const {+        return has_value();+    }+    E& error() {+        return *error_;+    }+    const E& error() const {+        return *error_;+    }  private:-  std::optional<E> error_;+    std::optional<E> error_; };  template <typename T> using Result = Expected<T, Error>;@@ -126,17 +153,19 @@ using Status = Result<void>;  inline Unexpected<Error> unexpected(Error error) {-  return Unexpected<Error>(std::move(error));+    return Unexpected<Error>(std::move(error)); }-inline Status ok() { return {}; }+inline Status ok() {+    return {};+} inline Unexpected<Error> fail(ErrorKind kind, std::size_t offset = 0) {-  return unexpected(Error::decode(kind, offset));+    return unexpected(Error::decode(kind, offset)); } inline Unexpected<Error> fail_io(std::string message) {-  return unexpected(Error::io(std::move(message)));+    return unexpected(Error::io(std::move(message))); } inline Unexpected<Error> fail_usage(std::string message) {-  return unexpected(Error::usage(std::move(message)));+    return unexpected(Error::usage(std::move(message))); }  // ---------------------------------------------------------------------------@@ -144,54 +173,54 @@ // ---------------------------------------------------------------------------  inline Bytes bytes_of(std::string_view s) {-  return Bytes(reinterpret_cast<const std::uint8_t *>(s.data()), s.size());+    return Bytes(reinterpret_cast<const std::uint8_t*>(s.data()), s.size()); }-inline Bytes bytes_of(const std::vector<std::uint8_t> &v) {-  return Bytes(v.data(), v.size());+inline Bytes bytes_of(const std::vector<std::uint8_t>& v) {+    return Bytes(v.data(), v.size()); } inline std::string_view str_of(Bytes b) {-  return std::string_view(reinterpret_cast<const char *>(b.data()), b.size());+    return std::string_view(reinterpret_cast<const char*>(b.data()), b.size()); }-inline std::string to_string(Bytes b) { return std::string(str_of(b)); }+inline std::string to_string(Bytes b) {+    return std::string(str_of(b));+} inline bool equals(Bytes a, Bytes b) {-  return a.size() == b.size() &&-         (a.empty() || std::memcmp(a.data(), b.data(), a.size()) == 0);+    return a.size() == b.size() && (a.empty() || std::memcmp(a.data(), b.data(), a.size()) == 0); } inline int compare(Bytes a, Bytes b) {-  const std::size_t n = std::min(a.size(), b.size());-  if (n != 0) {-    const int c = std::memcmp(a.data(), b.data(), n);-    if (c != 0)-      return c < 0 ? -1 : 1;-  }-  if (a.size() < b.size())-    return -1;-  if (a.size() > b.size())-    return 1;-  return 0;+    const std::size_t n = std::min(a.size(), b.size());+    if (n != 0) {+        const int c = std::memcmp(a.data(), b.data(), n);+        if (c != 0)+            return c < 0 ? -1 : 1;+    }+    if (a.size() < b.size())+        return -1;+    if (a.size() > b.size())+        return 1;+    return 0; } inline bool ascii_iequals(Bytes a, Bytes b) {-  if (a.size() != b.size())-    return false;-  for (std::size_t i = 0; i < a.size(); ++i) {-    auto lower = [](std::uint8_t c) -> std::uint8_t {-      return (c >= 'A' && c <= 'Z') ? static_cast<std::uint8_t>(c + 32) : c;-    };-    if (lower(a[i]) != lower(b[i]))-      return false;-  }-  return true;+    if (a.size() != b.size())+        return false;+    for (std::size_t i = 0; i < a.size(); ++i) {+        auto lower = [](std::uint8_t c) -> std::uint8_t {+            return (c >= 'A' && c <= 'Z') ? static_cast<std::uint8_t>(c + 32) : c;+        };+        if (lower(a[i]) != lower(b[i]))+            return false;+    }+    return true; } inline bool starts_with(Bytes value, Bytes prefix) {-  return value.size() >= prefix.size() &&-         equals(value.first(prefix.size()), prefix);+    return value.size() >= prefix.size() && equals(value.first(prefix.size()), prefix); }  std::string hex_encode(Bytes data);-std::string hex_encode(const Id &id);+std::string hex_encode(const Id& id); bool hex_decode(std::string_view text, MutBytes out); std::optional<Id> parse_id(std::string_view hex);-std::string base32_encode(const ChangeId &id);+std::string base32_encode(const ChangeId& id); bool base32_prefix_matches(std::string_view full, std::string_view prefix);  // ---------------------------------------------------------------------------@@ -209,79 +238,105 @@  class Reader { public:-  explicit Reader(Bytes data) : data_(data) {}+    explicit Reader(Bytes data) : data_(data) {} -  [[nodiscard]] std::size_t offset() const { return pos_; }-  [[nodiscard]] std::size_t remaining() const { return data_.size() - pos_; }-  [[nodiscard]] bool at_end() const { return pos_ >= data_.size(); }+    [[nodiscard]] std::size_t offset() const {+        return pos_;+    }+    [[nodiscard]] std::size_t remaining() const {+        return data_.size() - pos_;+    }+    [[nodiscard]] bool at_end() const {+        return pos_ >= data_.size();+    } -  Result<std::uint8_t> u8();-  Result<std::uint16_t> u16le();-  Result<std::uint32_t> u32le();-  Result<std::uint64_t> u64le();-  Result<std::int16_t> i16le();-  Result<std::int64_t> i64le();-  Result<std::uint64_t> varint();-  Result<Bytes> raw(std::size_t n);-  Result<Bytes> bytes(std::size_t max_len);-  Result<std::string> string_bytes(std::size_t max_len);-  Result<std::size_t> list_len(std::size_t max);-  Result<Id> id();-  Result<std::optional<Id>> opt_id();-  Result<void> finish();+    Result<std::uint8_t> u8();+    Result<std::uint16_t> u16le();+    Result<std::uint32_t> u32le();+    Result<std::uint64_t> u64le();+    Result<std::int16_t> i16le();+    Result<std::int64_t> i64le();+    Result<std::uint64_t> varint();+    Result<Bytes> raw(std::size_t n);+    Result<Bytes> bytes(std::size_t max_len);+    Result<std::string> string_bytes(std::size_t max_len);+    Result<std::size_t> list_len(std::size_t max);+    Result<Id> id();+    Result<std::optional<Id>> opt_id();+    Result<void> finish(); -  struct Sig {-    std::string name;-    std::string email;-    std::int64_t seconds = 0;-    std::int16_t tz_min = 0;-  };-  struct TimeMs {-    std::int64_t ms = 0;-    std::int16_t tz_min = 0;-  };+    struct Sig {+        std::string name;+        std::string email;+        std::int64_t seconds = 0;+        std::int16_t tz_min = 0;+    };+    struct TimeMs {+        std::int64_t ms = 0;+        std::int16_t tz_min = 0;+    }; -  Result<Sig> sig(std::size_t max_name, std::size_t max_email);-  Result<TimeMs> time_ms();+    Result<Sig> sig(std::size_t max_name, std::size_t max_email);+    Result<TimeMs> time_ms(); -  static std::uint64_t read_u64le_at(Bytes data, std::size_t off);+    static std::uint64_t read_u64le_at(Bytes data, std::size_t off);  private:-  Bytes data_;-  std::size_t pos_ = 0;+    Bytes data_;+    std::size_t pos_ = 0; };  class ByteWriter { public:-  explicit ByteWriter(std::size_t reserve = 64) { buf_.reserve(reserve); }+    explicit ByteWriter(std::size_t reserve = 64) {+        buf_.reserve(reserve);+    } -  void u8(std::uint8_t v);-  void u16le(std::uint16_t v);-  void u32le(std::uint32_t v);-  void u64le(std::uint64_t v);-  void i16le(std::int16_t v);-  void i64le(std::int64_t v);-  void varint(std::uint64_t v);-  void raw(Bytes data);-  void raw(std::string_view s) { raw(bytes_of(s)); }-  void bytes(std::string_view s) { raw(s); }-  void length_prefixed(std::string_view s);-  void length_prefixed(Bytes b);-  void id(const Id &id);-  void opt_id(const std::optional<Id> &id);-  void sig(const Reader::Sig &s);-  void time_ms(const Reader::TimeMs &t);+    void u8(std::uint8_t v);+    void u16le(std::uint16_t v);+    void u32le(std::uint32_t v);+    void u64le(std::uint64_t v);+    void i16le(std::int16_t v);+    void i64le(std::int64_t v);+    void varint(std::uint64_t v);+    void raw(Bytes data);+    void raw(std::string_view s) {+        raw(bytes_of(s));+    }+    void bytes(std::string_view s) {+        raw(s);+    }+    void length_prefixed(std::string_view s);+    void length_prefixed(Bytes b);+    void id(const Id& id);+    void opt_id(const std::optional<Id>& id);+    void sig(const Reader::Sig& s);+    void time_ms(const Reader::TimeMs& t); -  [[nodiscard]] Bytes view() const { return Bytes(buf_.data(), buf_.size()); }-  [[nodiscard]] const std::vector<std::uint8_t> &data() const { return buf_; }-  [[nodiscard]] std::vector<std::uint8_t> take() { return std::move(buf_); }-  [[nodiscard]] std::size_t size() const { return buf_.size(); }-  void clear() { buf_.clear(); }-  void append(Bytes b) { raw(b); }-  void reserve(std::size_t n) { buf_.reserve(n); }+    [[nodiscard]] Bytes view() const {+        return Bytes(buf_.data(), buf_.size());+    }+    [[nodiscard]] const std::vector<std::uint8_t>& data() const {+        return buf_;+    }+    [[nodiscard]] std::vector<std::uint8_t> take() {+        return std::move(buf_);+    }+    [[nodiscard]] std::size_t size() const {+        return buf_.size();+    }+    void clear() {+        buf_.clear();+    }+    void append(Bytes b) {+        raw(b);+    }+    void reserve(std::size_t n) {+        buf_.reserve(n);+    }  private:-  std::vector<std::uint8_t> buf_;+    std::vector<std::uint8_t> buf_; };  // ---------------------------------------------------------------------------@@ -294,29 +349,27 @@ std::size_t available_cpu_count();  enum class Color {-  Default,-  Black,-  Red,-  Green,-  Yellow,-  Blue,-  Magenta,-  Cyan,-  BrightBlack,-  BrightRed,-  BrightGreen,-  BrightYellow,-  BrightBlue,-  BrightMagenta,-  BrightCyan,-  BrightWhite,+    Default,+    Black,+    Red,+    Green,+    Yellow,+    Blue,+    Magenta,+    Cyan,+    BrightBlack,+    BrightRed,+    BrightGreen,+    BrightYellow,+    BrightBlue,+    BrightMagenta,+    BrightCyan,+    BrightWhite, };  bool colors_enabled();-void print_colored(std::string_view text, Color color, bool dim = false,-                   bool to_stderr = false);-void print_styled(std::string_view text, Color fg, bool dim,-                  bool to_stderr = false);+void print_colored(std::string_view text, Color color, bool dim = false, bool to_stderr = false);+void print_styled(std::string_view text, Color fg, bool dim, bool to_stderr = false); void print_bold(std::string_view text, Color fg, bool to_stderr = false); void error_prefix(); void warning_prefix();@@ -327,69 +380,65 @@ // ---------------------------------------------------------------------------  fs::path path_from_bytes(std::string_view bytes);-std::string path_to_bytes(const fs::path &p);-std::string path_display(const fs::path &p);+std::string path_to_bytes(const fs::path& p);+std::string path_display(const fs::path& p); -Result<std::vector<std::uint8_t>> read_file(const fs::path &p);-std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path &p);-bool write_file(const fs::path &p, Bytes data);-bool append_file(const fs::path &p, Bytes data);-bool write_atomic(const fs::path &final_path, Bytes data);-bool write_atomic(const fs::path &tmp_path, const fs::path &final_path,-                  Bytes data);-bool ensure_directory(const fs::path &p);-bool remove_file(const fs::path &p);-bool remove_tree(const fs::path &p);-bool path_exists(const fs::path &p);-bool path_is_dir(const fs::path &p);-bool path_is_file(const fs::path &p);-bool path_is_symlink(const fs::path &p);-std::optional<std::uint64_t> path_file_size(const fs::path &p);-std::optional<std::uint64_t> file_mtime_ns(const fs::path &p);-std::optional<std::uint64_t> file_inode(const fs::path &p);-bool is_executable(const fs::path &p);-std::optional<std::string> path_read_symlink(const fs::path &p);-std::vector<std::string> list_directory(const fs::path &p);-bool same_or_under(const fs::path &child, const fs::path &parent);-std::string basename_string(const fs::path &p);+Result<std::vector<std::uint8_t>> read_file(const fs::path& p);+std::optional<std::vector<std::uint8_t>> read_file_opt(const fs::path& p);+bool write_file(const fs::path& p, Bytes data);+bool append_file(const fs::path& p, Bytes data);+bool write_atomic(const fs::path& final_path, Bytes data);+bool write_atomic(const fs::path& tmp_path, const fs::path& final_path, Bytes data);+bool ensure_directory(const fs::path& p);+bool remove_file(const fs::path& p);+bool remove_tree(const fs::path& p);+bool path_exists(const fs::path& p);+bool path_is_dir(const fs::path& p);+bool path_is_file(const fs::path& p);+bool path_is_symlink(const fs::path& p);+std::optional<std::uint64_t> path_file_size(const fs::path& p);+std::optional<std::uint64_t> file_mtime_ns(const fs::path& p);+std::optional<std::uint64_t> file_inode(const fs::path& p);+bool is_executable(const fs::path& p);+std::optional<std::string> path_read_symlink(const fs::path& p);+std::vector<std::string> list_directory(const fs::path& p);+bool same_or_under(const fs::path& child, const fs::path& parent);+std::string basename_string(const fs::path& p);  struct StatInfo {-  std::uint8_t kind = 0; // 0 missing, 1 file, 2 directory, 3 symlink-  bool executable = false;-  std::uint64_t size = 0;-  std::uint64_t mtime_ns = 0;-  std::uint64_t inode = 0;+    std::uint8_t kind = 0; // 0 missing, 1 file, 2 directory, 3 symlink+    bool executable = false;+    std::uint64_t size = 0;+    std::uint64_t mtime_ns = 0;+    std::uint64_t inode = 0; };-std::optional<StatInfo> stat_path(const fs::path &p);+std::optional<StatInfo> stat_path(const fs::path& p);  // --------------------------------------------------------------------------- // Configuration and identity // --------------------------------------------------------------------------- -std::optional<std::string> repo_config_value(const fs::path &repo_root,-                                             std::string_view key);-bool repo_config_set(const fs::path &repo_root, std::string_view key,-                     std::string_view value);-bool repo_config_remove(const fs::path &repo_root, std::string_view key);-bool repo_config_bool(const fs::path &repo_root, std::string_view key,-                      bool fallback);+std::optional<std::string> repo_config_value(const fs::path& repo_root, std::string_view key);+bool repo_config_set(const fs::path& repo_root, std::string_view key, std::string_view value);+bool repo_config_remove(const fs::path& repo_root, std::string_view key);+bool repo_config_bool(const fs::path& repo_root, std::string_view key, bool fallback);  struct Sig {-  std::string name;-  std::string email;-  std::int64_t seconds = 0;-  std::int16_t tz_min = 0;+    std::string name;+    std::string email;+    std::int64_t seconds = 0;+    std::int16_t tz_min = 0; }; -Sig identity_signature(const fs::path &repo_root);+Sig identity_signature(const fs::path& repo_root); std::optional<std::string> user_config_author_name(); std::optional<std::string> user_config_author_email(); bool user_config_set(std::string_view key, std::string_view value); bool user_config_remove(std::string_view key); -std::optional<std::string> current_bookmark_name(const fs::path &repo_root);-bool set_current_bookmark(const fs::path &repo_root, std::string_view name);-bool clear_current_bookmark(const fs::path &repo_root);+std::optional<std::string> current_bookmark_name(const fs::path& repo_root);+bool set_current_bookmark(const fs::path& repo_root, std::string_view name);+bool clear_current_bookmark(const fs::path& repo_root);  // --------------------------------------------------------------------------- // Ignore rules@@ -396,25 +445,24 @@ // ---------------------------------------------------------------------------  struct IgnoreRule {-  std::string pattern;-  bool negated = false;-  bool dir_only = false;-  bool anchored = false;-  bool has_slash = false;-  std::string base;+    std::string pattern;+    bool negated = false;+    bool dir_only = false;+    bool anchored = false;+    bool has_slash = false;+    std::string base; };  struct IgnoreRules {-  std::vector<IgnoreRule> items;+    std::vector<IgnoreRule> items; };  IgnoreRules ignore_empty();-void ignore_load_file(IgnoreRules &rules, const fs::path &repo_root,-                      std::string_view base, std::string_view name);-void ignore_load_root(IgnoreRules &rules, const fs::path &repo_root);-bool ignore_ignored(const IgnoreRules &rules, std::string_view path,-                    bool is_dir);-bool ignore_path_ignored(const fs::path &repo_root, std::string_view path);+void ignore_load_file(IgnoreRules& rules, const fs::path& repo_root, std::string_view base,+                      std::string_view name);+void ignore_load_root(IgnoreRules& rules, const fs::path& repo_root);+bool ignore_ignored(const IgnoreRules& rules, std::string_view path, bool is_dir);+bool ignore_path_ignored(const fs::path& repo_root, std::string_view path); bool glob_match(std::string_view pattern, std::string_view text);  } // namespace vn--- a/xveins/src/crypto.cpp+++ b/xveins/src/crypto.cpp@@ -16,192 +16,186 @@ constexpr char FINGERPRINT_DOMAIN[] = "veins/key/1";  PublicKey key_from_span(Bytes seed) {-  PublicKey out{};-  std::memcpy(out.data(), seed.data(), out.size());-  return out;+    PublicKey out{};+    std::memcpy(out.data(), seed.data(), out.size());+    return out; }  } // namespace  std::optional<PublicKey> ed25519_public_from_seed(Bytes seed) {-  if (seed.size() != 32)-    return std::nullopt;-  EVP_PKEY *pkey =-      EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);-  if (!pkey)-    return std::nullopt;-  PublicKey out{};-  std::size_t len = out.size();-  const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);-  EVP_PKEY_free(pkey);-  if (ok != 1 || len != out.size())-    return std::nullopt;-  return out;+    if (seed.size() != 32)+        return std::nullopt;+    EVP_PKEY* pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);+    if (!pkey)+        return std::nullopt;+    PublicKey out{};+    std::size_t len = out.size();+    const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);+    EVP_PKEY_free(pkey);+    if (ok != 1 || len != out.size())+        return std::nullopt;+    return out; }  std::optional<Signature> ed25519_sign(Bytes seed, Bytes message) {-  if (seed.size() != 32)-    return std::nullopt;-  EVP_PKEY *pkey =-      EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);-  if (!pkey)-    return std::nullopt;-  EVP_MD_CTX *ctx = EVP_MD_CTX_new();-  if (!ctx) {+    if (seed.size() != 32)+        return std::nullopt;+    EVP_PKEY* pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);+    if (!pkey)+        return std::nullopt;+    EVP_MD_CTX* ctx = EVP_MD_CTX_new();+    if (!ctx) {+        EVP_PKEY_free(pkey);+        return std::nullopt;+    }+    Signature out{};+    std::size_t sig_len = out.size();+    bool ok = false;+    if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&+        EVP_DigestSign(ctx, out.data(), &sig_len, message.data(), message.size()) == 1 &&+        sig_len == out.size()) {+        ok = true;+    }+    EVP_MD_CTX_free(ctx);     EVP_PKEY_free(pkey);-    return std::nullopt;-  }-  Signature out{};-  std::size_t sig_len = out.size();-  bool ok = false;-  if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&-      EVP_DigestSign(ctx, out.data(), &sig_len, message.data(),-                     message.size()) == 1 &&-      sig_len == out.size()) {-    ok = true;-  }-  EVP_MD_CTX_free(ctx);-  EVP_PKEY_free(pkey);-  if (!ok)-    return std::nullopt;-  return out;+    if (!ok)+        return std::nullopt;+    return out; } -bool ed25519_verify(const PublicKey &public_key, Bytes message,-                    Bytes signature) {-  if (signature.size() != 64)-    return false;-  EVP_PKEY *pkey = EVP_PKEY_new_raw_public_key(-      EVP_PKEY_ED25519, nullptr, public_key.data(), public_key.size());-  if (!pkey)-    return false;-  EVP_MD_CTX *ctx = EVP_MD_CTX_new();-  if (!ctx) {+bool ed25519_verify(const PublicKey& public_key, Bytes message, Bytes signature) {+    if (signature.size() != 64)+        return false;+    EVP_PKEY* pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key.data(),+                                                 public_key.size());+    if (!pkey)+        return false;+    EVP_MD_CTX* ctx = EVP_MD_CTX_new();+    if (!ctx) {+        EVP_PKEY_free(pkey);+        return false;+    }+    bool ok = false;+    if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&+        EVP_DigestVerify(ctx, signature.data(), signature.size(), message.data(), message.size()) ==+            1) {+        ok = true;+    }+    EVP_MD_CTX_free(ctx);     EVP_PKEY_free(pkey);-    return false;-  }-  bool ok = false;-  if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&-      EVP_DigestVerify(ctx, signature.data(), signature.size(), message.data(),-                       message.size()) == 1) {-    ok = true;-  }-  EVP_MD_CTX_free(ctx);-  EVP_PKEY_free(pkey);-  return ok;+    return ok; } -FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key) {-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN, sizeof(FINGERPRINT_DOMAIN));-  blake3_hasher_update(&hasher, public_key.data(), public_key.size());-  std::array<std::uint8_t, 32> digest{};-  blake3_hasher_finalize(&hasher, digest.data(), digest.size());-  FingerprintBytes out{};-  std::memcpy(out.data(), digest.data(), out.size());-  return out;+FingerprintBytes key_fingerprint_bytes(const PublicKey& public_key) {+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN, sizeof(FINGERPRINT_DOMAIN));+    blake3_hasher_update(&hasher, public_key.data(), public_key.size());+    std::array<std::uint8_t, 32> digest{};+    blake3_hasher_finalize(&hasher, digest.data(), digest.size());+    FingerprintBytes out{};+    std::memcpy(out.data(), digest.data(), out.size());+    return out; } -std::string key_fingerprint(const PublicKey &public_key) {-  const auto raw = key_fingerprint_bytes(public_key);-  return base32_text(Bytes(raw.data(), raw.size()));+std::string key_fingerprint(const PublicKey& public_key) {+    const auto raw = key_fingerprint_bytes(public_key);+    return base32_text(Bytes(raw.data(), raw.size())); }  std::string base32_text(Bytes raw) {-  static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";-  std::string out;-  out.reserve((raw.size() * 8) / 5 + 2);-  std::uint64_t bits = 0;-  std::size_t nbits = 0;-  for (std::uint8_t byte : raw) {-    bits = (bits << 8) | byte;-    nbits += 8;-    while (nbits >= 5) {-      nbits -= 5;-      out.push_back(alphabet[(bits >> nbits) & 31u]);+    static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";+    std::string out;+    out.reserve((raw.size() * 8) / 5 + 2);+    std::uint64_t bits = 0;+    std::size_t nbits = 0;+    for (std::uint8_t byte : raw) {+        bits = (bits << 8) | byte;+        nbits += 8;+        while (nbits >= 5) {+            nbits -= 5;+            out.push_back(alphabet[(bits >> nbits) & 31u]);+        }     }-  }-  if (nbits > 0)-    out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);-  return out;+    if (nbits > 0)+        out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);+    return out; }  std::string base64url_encode(Bytes raw) {-  static constexpr char alphabet[] =-      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";-  std::string out;-  out.reserve((raw.size() * 4) / 3 + 4);-  std::uint32_t acc = 0;-  std::size_t bits = 0;-  for (std::uint8_t byte : raw) {-    acc = (acc << 8) | byte;-    bits += 8;-    while (bits >= 6) {-      bits -= 6;-      out.push_back(alphabet[(acc >> bits) & 63u]);+    static constexpr char alphabet[] =+        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";+    std::string out;+    out.reserve((raw.size() * 4) / 3 + 4);+    std::uint32_t acc = 0;+    std::size_t bits = 0;+    for (std::uint8_t byte : raw) {+        acc = (acc << 8) | byte;+        bits += 8;+        while (bits >= 6) {+            bits -= 6;+            out.push_back(alphabet[(acc >> bits) & 63u]);+        }     }-  }-  if (bits > 0)-    out.push_back(alphabet[(acc << (6 - bits)) & 63u]);-  return out;+    if (bits > 0)+        out.push_back(alphabet[(acc << (6 - bits)) & 63u]);+    return out; } -std::optional<std::vector<std::uint8_t>>-base64url_decode(std::string_view text) {-  if (text.empty())-    return std::nullopt;-  static const auto value_of = [](char c) -> int {-    if (c >= 'A' && c <= 'Z')-      return c - 'A';-    if (c >= 'a' && c <= 'z')-      return c - 'a' + 26;-    if (c >= '0' && c <= '9')-      return c - '0' + 52;-    if (c == '-')-      return 62;-    if (c == '_')-      return 63;-    return -1;-  };-  std::vector<std::uint8_t> out;-  out.reserve((text.size() * 6) / 8);-  std::uint32_t acc = 0;-  std::size_t bits = 0;-  for (char c : text) {-    const int value = value_of(c);-    if (value < 0)-      return std::nullopt;-    acc = (acc << 6) | static_cast<std::uint32_t>(value);-    bits += 6;-    if (bits >= 8) {-      bits -= 8;-      out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));+std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text) {+    if (text.empty())+        return std::nullopt;+    static const auto value_of = [](char c) -> int {+        if (c >= 'A' && c <= 'Z')+            return c - 'A';+        if (c >= 'a' && c <= 'z')+            return c - 'a' + 26;+        if (c >= '0' && c <= '9')+            return c - '0' + 52;+        if (c == '-')+            return 62;+        if (c == '_')+            return 63;+        return -1;+    };+    std::vector<std::uint8_t> out;+    out.reserve((text.size() * 6) / 8);+    std::uint32_t acc = 0;+    std::size_t bits = 0;+    for (char c : text) {+        const int value = value_of(c);+        if (value < 0)+            return std::nullopt;+        acc = (acc << 6) | static_cast<std::uint32_t>(value);+        bits += 6;+        if (bits >= 8) {+            bits -= 8;+            out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));+        }     }-  }-  return out;+    return out; } -std::string format_public_key(const PublicKey &public_key) {-  return "ed25519:" +-         base64url_encode(Bytes(public_key.data(), public_key.size()));+std::string format_public_key(const PublicKey& public_key) {+    return "ed25519:" + base64url_encode(Bytes(public_key.data(), public_key.size())); }  std::optional<PublicKey> parse_public_key(std::string_view text) {-  constexpr std::string_view prefix = "ed25519:";-  if (!text.starts_with(prefix))-    return std::nullopt;-  auto decoded = base64url_decode(text.substr(prefix.size()));-  if (!decoded || decoded->size() != 32)-    return std::nullopt;-  return key_from_span(Bytes(decoded->data(), decoded->size()));+    constexpr std::string_view prefix = "ed25519:";+    if (!text.starts_with(prefix))+        return std::nullopt;+    auto decoded = base64url_decode(text.substr(prefix.size()));+    if (!decoded || decoded->size() != 32)+        return std::nullopt;+    return key_from_span(Bytes(decoded->data(), decoded->size())); }  std::vector<std::uint8_t> secure_random(std::size_t count) {-  std::vector<std::uint8_t> out(count);-  if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)-    out.clear();-  return out;+    std::vector<std::uint8_t> out(count);+    if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)+        out.clear();+    return out; }  } // namespace vn--- a/xveins/src/crypto.h+++ b/xveins/src/crypto.h@@ -16,11 +16,10 @@  std::optional<PublicKey> ed25519_public_from_seed(Bytes seed); std::optional<Signature> ed25519_sign(Bytes seed, Bytes message);-bool ed25519_verify(const PublicKey &public_key, Bytes message,-                    Bytes signature);+bool ed25519_verify(const PublicKey& public_key, Bytes message, Bytes signature); -FingerprintBytes key_fingerprint_bytes(const PublicKey &public_key);-std::string key_fingerprint(const PublicKey &public_key);+FingerprintBytes key_fingerprint_bytes(const PublicKey& public_key);+std::string key_fingerprint(const PublicKey& public_key);  // RFC 4648 base32 with no padding. The reference implementation emits // fingerprints in uppercase, so this matches it.@@ -27,10 +26,9 @@ std::string base32_text(Bytes raw); // Unpadded base64url. std::string base64url_encode(Bytes raw);-std::optional<std::vector<std::uint8_t>>-base64url_decode(std::string_view text);+std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text); -std::string format_public_key(const PublicKey &public_key);+std::string format_public_key(const PublicKey& public_key); std::optional<PublicKey> parse_public_key(std::string_view text);  std::vector<std::uint8_t> secure_random(std::size_t count);--- a/xveins/src/exclude.cpp+++ b/xveins/src/exclude.cpp@@ -11,135 +11,134 @@ namespace {  bool ex_is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';+    return !arg.empty() && arg.front() == '-'; }  std::string_view trim(std::string_view b) {-  std::size_t start = 0;-  std::size_t end = b.size();-  while (start < end) {-    const char c = b[start];-    if (c != ' ' && c != '\t' && c != '\r' && c != '\n')-      break;-    ++start;-  }-  while (end > start) {-    const char c = b[end - 1];-    if (c != ' ' && c != '\t' && c != '\r' && c != '\n')-      break;-    --end;-  }-  return b.substr(start, end - start);+    std::size_t start = 0;+    std::size_t end = b.size();+    while (start < end) {+        const char c = b[start];+        if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+            break;+        ++start;+    }+    while (end > start) {+        const char c = b[end - 1];+        if (c != ' ' && c != '\t' && c != '\r' && c != '\n')+            break;+        --end;+    }+    return b.substr(start, end - start); }  bool line_exists(std::string_view data, std::string_view pattern) {-  if (data.empty())-    return false;-  std::size_t start = 0;-  for (std::size_t pos = 0; pos <= data.size(); ++pos) {-    const bool at_end = pos == data.size();-    if (at_end || data[pos] == '\n') {-      if (trim(data.substr(start, pos - start)) == pattern)-        return true;-      start = pos + 1;+    if (data.empty())+        return false;+    std::size_t start = 0;+    for (std::size_t pos = 0; pos <= data.size(); ++pos) {+        const bool at_end = pos == data.size();+        if (at_end || data[pos] == '\n') {+            if (trim(data.substr(start, pos - start)) == pattern)+                return true;+            start = pos + 1;+        }     }-  }-  return false;+    return false; }  } // namespace -int ex_run(const std::vector<std::string> &args) {-  std::vector<std::string> operands;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && ex_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      operands.push_back(arg);+int ex_run(const std::vector<std::string>& args) {+    std::vector<std::string> operands;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && ex_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            operands.push_back(arg);+        }     }-  }-  if (operands.empty()) {-    error_prefix();-    std::cout << "ex requires at least one pattern\n";-    return 1;-  }--  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const auto cwd_rel = cwd_relative(*root);-  if (!cwd_rel) {-    error_prefix();-    std::cout << "cannot determine current directory\n";-    return 1;-  }+    if (operands.empty()) {+        error_prefix();+        std::cout << "ex requires at least one pattern\n";+        return 1;+    } -  std::vector<std::string> patterns;-  for (const auto &arg : operands) {-    auto norm = pathspec_normalize(*root, *cwd_rel, arg);-    if (!norm) {-      error_prefix();-      std::cout << "pattern is outside the repository: " << arg << "\n";-      return 1;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;     }-    if (norm->empty() || !valid_path(*norm)) {-      error_prefix();-      std::cout << arg << "\n";-      std::cout << "not a valid exclude pattern\n";-      return 1;+    const auto cwd_rel = cwd_relative(*root);+    if (!cwd_rel) {+        error_prefix();+        std::cout << "cannot determine current directory\n";+        return 1;     }-    patterns.push_back(std::move(*norm));-  } -  const fs::path exclude_path = *root / ".vnexclude";-  std::string data;-  if (auto existing = read_file_opt(exclude_path))-    data.assign(reinterpret_cast<const char *>(existing->data()),-                existing->size());+    std::vector<std::string> patterns;+    for (const auto& arg : operands) {+        auto norm = pathspec_normalize(*root, *cwd_rel, arg);+        if (!norm) {+            error_prefix();+            std::cout << "pattern is outside the repository: " << arg << "\n";+            return 1;+        }+        if (norm->empty() || !valid_path(*norm)) {+            error_prefix();+            std::cout << arg << "\n";+            std::cout << "not a valid exclude pattern\n";+            return 1;+        }+        patterns.push_back(std::move(*norm));+    } -  std::string additions;-  std::vector<std::string> added;-  for (const auto &pattern : patterns) {-    if (line_exists(data, pattern))-      continue;-    bool duplicate = false;-    for (const auto &prior : added) {-      if (prior == pattern) {-        duplicate = true;-        break;-      }+    const fs::path exclude_path = *root / ".vnexclude";+    std::string data;+    if (auto existing = read_file_opt(exclude_path))+        data.assign(reinterpret_cast<const char*>(existing->data()), existing->size());++    std::string additions;+    std::vector<std::string> added;+    for (const auto& pattern : patterns) {+        if (line_exists(data, pattern))+            continue;+        bool duplicate = false;+        for (const auto& prior : added) {+            if (prior == pattern) {+                duplicate = true;+                break;+            }+        }+        if (duplicate)+            continue;+        if (additions.empty() && !data.empty() && data.back() != '\n')+            additions.push_back('\n');+        added.push_back(pattern);+        additions += pattern;+        additions.push_back('\n');     }-    if (duplicate)-      continue;-    if (additions.empty() && !data.empty() && data.back() != '\n')-      additions.push_back('\n');-    added.push_back(pattern);-    additions += pattern;-    additions.push_back('\n');-  } -  if (added.empty()) {+    if (added.empty()) {+        info_prefix();+        std::cout << "no new exclude rules\n";+        return 0;+    }+    if (!append_file(exclude_path, bytes_of(additions))) {+        error_prefix();+        std::cout << "cannot write .vnexclude\n";+        return 1;+    }     info_prefix();-    std::cout << "no new exclude rules\n";+    std::cout << "added " << added.size() << " exclude rule(s)\n";     return 0;-  }-  if (!append_file(exclude_path, bytes_of(additions))) {-    error_prefix();-    std::cout << "cannot write .vnexclude\n";-    return 1;-  }-  info_prefix();-  std::cout << "added " << added.size() << " exclude rule(s)\n";-  return 0; }  } // namespace vn--- a/xveins/src/git.cpp+++ b/xveins/src/git.cpp@@ -26,487 +26,475 @@ using git::ParsedCommit;  struct OidHash {-  std::size_t operator()(const Oid &oid) const {-    std::size_t h = 1469598103934665603ull;-    for (auto b : oid) {-      h ^= b;-      h *= 1099511628211ull;+    std::size_t operator()(const Oid& oid) const {+        std::size_t h = 1469598103934665603ull;+        for (auto b : oid) {+            h ^= b;+            h *= 1099511628211ull;+        }+        return h;     }-    return h;-  } };  struct NamedTarget {-  std::string name;-  Oid oid{};+    std::string name;+    Oid oid{}; };  struct CommitRecord {-  Oid oid{};-  std::vector<std::uint8_t> body;-  ParsedCommit parsed;+    Oid oid{};+    std::vector<std::uint8_t> body;+    ParsedCommit parsed; }; -bool working_tree_empty(const fs::path &root) {-  for (const auto &name : list_directory(root)) {-    if (name != ".veins")-      return false;-  }-  return true;+bool working_tree_empty(const fs::path& root) {+    for (const auto& name : list_directory(root)) {+        if (name != ".veins")+            return false;+    }+    return true; } -ChangeId derive_change_id(const Oid &oid) {-  std::string input = "veins/change";-  input.append(reinterpret_cast<const char *>(oid.data()), oid.size());-  const auto hash = blake3_hash(bytes_of(input));-  ChangeId out{};-  std::memcpy(out.data(), hash.data(), out.size());-  return out;+ChangeId derive_change_id(const Oid& oid) {+    std::string input = "veins/change";+    input.append(reinterpret_cast<const char*>(oid.data()), oid.size());+    const auto hash = blake3_hash(bytes_of(input));+    ChangeId out{};+    std::memcpy(out.data(), hash.data(), out.size());+    return out; } -std::optional<Oid> peel_to_commit(git::Repo &repo, const Oid &start) {-  Oid current = start;-  for (std::size_t i = 0; i < 4096; ++i) {-    auto object = git::read_object(repo, current);-    if (!object)-      return std::nullopt;-    if (object->kind == git::KIND_COMMIT)-      return current;-    if (object->kind != git::KIND_TAG)-      return std::nullopt;-    auto tag = git::parse_tag(Bytes(object->body.data(), object->body.size()));-    if (!tag)-      return std::nullopt;-    current = tag->target;-  }-  return std::nullopt;+std::optional<Oid> peel_to_commit(git::Repo& repo, const Oid& start) {+    Oid current = start;+    for (std::size_t i = 0; i < 4096; ++i) {+        auto object = git::read_object(repo, current);+        if (!object)+            return std::nullopt;+        if (object->kind == git::KIND_COMMIT)+            return current;+        if (object->kind != git::KIND_TAG)+            return std::nullopt;+        auto tag = git::parse_tag(Bytes(object->body.data(), object->body.size()));+        if (!tag)+            return std::nullopt;+        current = tag->target;+    }+    return std::nullopt; } -void set_bookmark(View &view, std::string_view name, const Id &id) {-  for (auto &bookmark : view.bookmarks) {-    if (bookmark.name == name) {-      bookmark.targets.adds = {id};-      bookmark.targets.removes.clear();-      return;+void set_bookmark(View& view, std::string_view name, const Id& id) {+    for (auto& bookmark : view.bookmarks) {+        if (bookmark.name == name) {+            bookmark.targets.adds = {id};+            bookmark.targets.removes.clear();+            return;+        }     }-  }-  Bookmark bookmark;-  bookmark.name = std::string(name);-  bookmark.targets.adds = {id};-  view.bookmarks.push_back(std::move(bookmark));+    Bookmark bookmark;+    bookmark.name = std::string(name);+    bookmark.targets.adds = {id};+    view.bookmarks.push_back(std::move(bookmark)); } -void set_tag(View &view, std::string_view name, const Id &id) {-  for (auto &tag : view.tags) {-    if (tag.name == name) {-      tag.target = id;-      return;+void set_tag(View& view, std::string_view name, const Id& id) {+    for (auto& tag : view.tags) {+        if (tag.name == name) {+            tag.target = id;+            return;+        }     }-  }-  view.tags.push_back(TagRef{std::string(name), id});+    view.tags.push_back(TagRef{std::string(name), id}); } -void set_remote_ref(View &view, std::string_view remote, std::string_view name,-                    const Id &id) {-  for (auto &ref : view.remote_refs) {-    if (ref.remote == remote && ref.name == name) {-      ref.target = id;-      return;+void set_remote_ref(View& view, std::string_view remote, std::string_view name, const Id& id) {+    for (auto& ref : view.remote_refs) {+        if (ref.remote == remote && ref.name == name) {+            ref.target = id;+            return;+        }     }-  }-  view.remote_refs.push_back(-      RemoteRef{std::string(remote), std::string(name), id});+    view.remote_refs.push_back(RemoteRef{std::string(remote), std::string(name), id}); }  std::pair<std::string, std::string> split_remote(std::string_view full) {-  const std::size_t slash = full.find('/');-  if (slash == std::string_view::npos)-    return {std::string(full), "main"};-  return {std::string(full.substr(0, slash)),-          std::string(full.substr(slash + 1))};+    const std::size_t slash = full.find('/');+    if (slash == std::string_view::npos)+        return {std::string(full), "main"};+    return {std::string(full.substr(0, slash)), std::string(full.substr(slash + 1))}; } -int create_working_copy(const fs::path &root, const Id &parent) {-  Store store = Store::open_all(root);-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  auto loaded = load_commit(tx->store(), parent);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read imported commit\n";-    return 1;-  }-  Commit commit;-  commit.version = 1;-  commit.parents = {parent};-  commit.root_tree = loaded->commit.root_tree;-  commit.change_id = random_change_id();-  commit.author = identity_signature(root);-  commit.committer = commit.author;-  commit.renames_state = RENAMES_RECORDED;-  const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));-  remove_head(tx->view(), parent);-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());-  auto status = tx->finish("import");-  if (!status)-    return 1;-  store.refresh(root);-  return 0;+int create_working_copy(const fs::path& root, const Id& parent) {+    Store store = Store::open_all(root);+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    auto loaded = load_commit(tx->store(), parent);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read imported commit\n";+        return 1;+    }+    Commit commit;+    commit.version = 1;+    commit.parents = {parent};+    commit.root_tree = loaded->commit.root_tree;+    commit.change_id = random_change_id();+    commit.author = identity_signature(root);+    commit.committer = commit.author;+    commit.renames_state = RENAMES_RECORDED;+    const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));+    remove_head(tx->view(), parent);+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view());+    auto status = tx->finish("import");+    if (!status)+        return 1;+    store.refresh(root);+    return 0; } -int materialize_working_copy(const fs::path &root, Store &store) {-  store.refresh(root);-  auto view = current_view(root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  const auto wc = working_copy_id(*view);-  if (!wc)-    return 0;-  auto body = store.read_body(*wc, TYPE_COMMIT);-  if (!body)-    return 1;-  auto commit = decode_commit(bytes_of(*body));-  if (!commit)-    return 1;-  return checkout_materialize_commit(root, store, std::nullopt,-                                     commit->root_tree);+int materialize_working_copy(const fs::path& root, Store& store) {+    store.refresh(root);+    auto view = current_view(root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    const auto wc = working_copy_id(*view);+    if (!wc)+        return 0;+    auto body = store.read_body(*wc, TYPE_COMMIT);+    if (!body)+        return 1;+    auto commit = decode_commit(bytes_of(*body));+    if (!commit)+        return 1;+    return checkout_materialize_commit(root, store, std::nullopt, commit->root_tree); } -std::vector<Id> ordered_commits(Store &store, const std::vector<Id> &roots) {-  struct Mark {-    Id id{};-    bool expanded = false;-  };-  std::vector<Mark> stack;-  for (const auto &id : roots)-    stack.push_back(Mark{id, false});-  std::set<Id> visited;-  std::vector<Id> ordered;-  while (!stack.empty()) {-    Mark mark = stack.back();-    stack.pop_back();-    if (visited.count(mark.id))-      continue;-    if (!mark.expanded) {-      mark.expanded = true;-      stack.push_back(mark);-      if (auto loaded = load_commit(store, mark.id)) {-        for (auto it = loaded->commit.parents.rbegin();-             it != loaded->commit.parents.rend(); ++it) {-          if (!visited.count(*it))-            stack.push_back(Mark{*it, false});+std::vector<Id> ordered_commits(Store& store, const std::vector<Id>& roots) {+    struct Mark {+        Id id{};+        bool expanded = false;+    };+    std::vector<Mark> stack;+    for (const auto& id : roots)+        stack.push_back(Mark{id, false});+    std::set<Id> visited;+    std::vector<Id> ordered;+    while (!stack.empty()) {+        Mark mark = stack.back();+        stack.pop_back();+        if (visited.count(mark.id))+            continue;+        if (!mark.expanded) {+            mark.expanded = true;+            stack.push_back(mark);+            if (auto loaded = load_commit(store, mark.id)) {+                for (auto it = loaded->commit.parents.rbegin(); it != loaded->commit.parents.rend();+                     ++it) {+                    if (!visited.count(*it))+                        stack.push_back(Mark{*it, false});+                }+            }+        } else {+            visited.insert(mark.id);+            ordered.push_back(mark.id);         }-      }-    } else {-      visited.insert(mark.id);-      ordered.push_back(mark.id);     }-  }-  return ordered;+    return ordered; } -std::optional<Id> exportable_target(Store &store, const Id &start) {-  Id current = start;-  for (std::size_t steps = 0; steps < 100000; ++steps) {-    auto loaded = load_commit(store, current);-    if (!loaded)-      return std::nullopt;-    if (!tree_conflicted(store, loaded->commit.root_tree))-      return current;-    if (loaded->commit.parents.empty())-      return std::nullopt;-    current = loaded->commit.parents.front();-  }-  return std::nullopt;+std::optional<Id> exportable_target(Store& store, const Id& start) {+    Id current = start;+    for (std::size_t steps = 0; steps < 100000; ++steps) {+        auto loaded = load_commit(store, current);+        if (!loaded)+            return std::nullopt;+        if (!tree_conflicted(store, loaded->commit.root_tree))+            return current;+        if (loaded->commit.parents.empty())+            return std::nullopt;+        current = loaded->commit.parents.front();+    }+    return std::nullopt; }  struct MaterializeCtx {-  const fs::path &root;-  Store &store;-  Writer &writer;-  std::map<Id, Id> trees;-  std::map<Id, Id> blobs;-  std::map<Id, Id> commits;-  std::map<Id, Id> conflicts;-  std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;-  std::size_t new_commits = 0;-  std::size_t new_trees = 0;-  std::size_t new_blobs = 0;-  bool changed = false;+    const fs::path& root;+    Store& store;+    Writer& writer;+    std::map<Id, Id> trees;+    std::map<Id, Id> blobs;+    std::map<Id, Id> commits;+    std::map<Id, Id> conflicts;+    std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;+    std::size_t new_commits = 0;+    std::size_t new_trees = 0;+    std::size_t new_blobs = 0;+    bool changed = false; }; -std::optional<Id> materialize_blob(MaterializeCtx &ctx, const Id &old_id) {-  auto existing = ctx.blobs.find(old_id);-  if (existing != ctx.blobs.end())-    return existing->second;-  const auto oid = git::lazy_blob_oid(old_id);-  if (!oid) {-    ctx.blobs[old_id] = old_id;-    return old_id;-  }-  auto data = git_read_lazy_blob(ctx.root, old_id);-  if (!data)-    return std::nullopt;-  BlobBuild build = build_blob(bytes_of(*data));-  if (build.root == Id{})-    return std::nullopt;-  for (auto &object : build.objects) {-    const Id id =-        object.id ? *object.id : object_id(object.type, bytes_of(object.body));-    (void)ctx.writer.add_known(object.type, id, std::move(object.body));-  }-  ctx.blobs[old_id] = build.root;-  ++ctx.new_blobs;-  ctx.changed = true;-  return build.root;+std::optional<Id> materialize_blob(MaterializeCtx& ctx, const Id& old_id) {+    auto existing = ctx.blobs.find(old_id);+    if (existing != ctx.blobs.end())+        return existing->second;+    const auto oid = git::lazy_blob_oid(old_id);+    if (!oid) {+        ctx.blobs[old_id] = old_id;+        return old_id;+    }+    auto data = git_read_lazy_blob(ctx.root, old_id);+    if (!data)+        return std::nullopt;+    BlobBuild build = build_blob(bytes_of(*data));+    if (build.root == Id{})+        return std::nullopt;+    for (auto& object : build.objects) {+        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));+        (void)ctx.writer.add_known(object.type, id, std::move(object.body));+    }+    ctx.blobs[old_id] = build.root;+    ++ctx.new_blobs;+    ctx.changed = true;+    return build.root; } -std::optional<Id> materialize_tree(MaterializeCtx &ctx, const Id &old_id,-                                   std::size_t depth);+std::optional<Id> materialize_tree(MaterializeCtx& ctx, const Id& old_id, std::size_t depth); -std::optional<Id> materialize_conflict(MaterializeCtx &ctx, const Id &old_id,-                                       std::size_t depth) {-  if (depth > 4096)-    return std::nullopt;-  auto existing = ctx.conflicts.find(old_id);-  if (existing != ctx.conflicts.end())-    return existing->second;-  auto body = ctx.store.read_body(old_id, TYPE_CONFLICT);-  if (!body)-    return std::nullopt;-  auto conflict = decode_conflict(bytes_of(*body));-  if (!conflict)-    return std::nullopt;-  bool changed = false;-  auto rewire = [&](ConflictValue &value) -> bool {-    if (!value.target)-      return true;-    if (value.kind == KIND_FILE || value.kind == KIND_EXECUTABLE ||-        value.kind == KIND_SYMLINK) {-      if (!is_lazy_blob(*value.target))+std::optional<Id> materialize_conflict(MaterializeCtx& ctx, const Id& old_id, std::size_t depth) {+    if (depth > 4096)+        return std::nullopt;+    auto existing = ctx.conflicts.find(old_id);+    if (existing != ctx.conflicts.end())+        return existing->second;+    auto body = ctx.store.read_body(old_id, TYPE_CONFLICT);+    if (!body)+        return std::nullopt;+    auto conflict = decode_conflict(bytes_of(*body));+    if (!conflict)+        return std::nullopt;+    bool changed = false;+    auto rewire = [&](ConflictValue& value) -> bool {+        if (!value.target)+            return true;+        if (value.kind == KIND_FILE || value.kind == KIND_EXECUTABLE ||+            value.kind == KIND_SYMLINK) {+            if (!is_lazy_blob(*value.target))+                return true;+            auto mapped = materialize_blob(ctx, *value.target);+            if (!mapped)+                return false;+            if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {+                value.target = *mapped;+                changed = true;+            }+            return true;+        }+        if (value.kind == KIND_SUBTREE) {+            auto mapped = materialize_tree(ctx, *value.target, depth + 1);+            if (!mapped)+                return false;+            if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {+                value.target = *mapped;+                changed = true;+            }+            return true;+        }+        if (value.kind == KIND_CONFLICT) {+            auto mapped = materialize_conflict(ctx, *value.target, depth + 1);+            if (!mapped)+                return false;+            if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {+                value.target = *mapped;+                changed = true;+            }+            return true;+        }         return true;-      auto mapped = materialize_blob(ctx, *value.target);-      if (!mapped)-        return false;-      if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {-        value.target = *mapped;-        changed = true;-      }-      return true;+    };+    for (auto& value : conflict->adds) {+        if (!rewire(value))+            return std::nullopt;     }-    if (value.kind == KIND_SUBTREE) {-      auto mapped = materialize_tree(ctx, *value.target, depth + 1);-      if (!mapped)-        return false;-      if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {-        value.target = *mapped;-        changed = true;-      }-      return true;+    for (auto& value : conflict->removes) {+        if (!rewire(value))+            return std::nullopt;     }-    if (value.kind == KIND_CONFLICT) {-      auto mapped = materialize_conflict(ctx, *value.target, depth + 1);-      if (!mapped)-        return false;-      if (std::memcmp(mapped->data(), value.target->data(), ID_LEN) != 0) {-        value.target = *mapped;-        changed = true;-      }-      return true;+    if (!changed) {+        ctx.conflicts[old_id] = old_id;+        return old_id;     }-    return true;-  };-  for (auto &value : conflict->adds) {-    if (!rewire(value))-      return std::nullopt;-  }-  for (auto &value : conflict->removes) {-    if (!rewire(value))-      return std::nullopt;-  }-  if (!changed) {-    ctx.conflicts[old_id] = old_id;-    return old_id;-  }-  const Id new_id = ctx.writer.add(TYPE_CONFLICT, encode_conflict(*conflict));-  ctx.conflicts[old_id] = new_id;-  ctx.changed = true;-  return new_id;+    const Id new_id = ctx.writer.add(TYPE_CONFLICT, encode_conflict(*conflict));+    ctx.conflicts[old_id] = new_id;+    ctx.changed = true;+    return new_id; } -std::optional<Id> materialize_tree(MaterializeCtx &ctx, const Id &old_id,-                                   std::size_t depth) {-  if (depth > 4096)-    return std::nullopt;-  auto existing = ctx.trees.find(old_id);-  if (existing != ctx.trees.end())-    return existing->second;-  auto body = ctx.store.read_body(old_id, TYPE_TREE);-  if (!body)-    return std::nullopt;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return std::nullopt;-  bool changed = false;-  std::vector<TreeEntry> entries = tree->entries;-  for (auto &entry : entries) {-    std::optional<Id> mapped;-    if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||-        entry.kind == KIND_SYMLINK) {-      if (!is_lazy_blob(entry.target))-        continue;-      mapped = materialize_blob(ctx, entry.target);-    } else if (entry.kind == KIND_SUBTREE) {-      mapped = materialize_tree(ctx, entry.target, depth + 1);-    } else if (entry.kind == KIND_CONFLICT) {-      mapped = materialize_conflict(ctx, entry.target, depth + 1);-    } else if (entry.kind == KIND_SUBMODULE) {-      continue;-    } else {-      return std::nullopt;+std::optional<Id> materialize_tree(MaterializeCtx& ctx, const Id& old_id, std::size_t depth) {+    if (depth > 4096)+        return std::nullopt;+    auto existing = ctx.trees.find(old_id);+    if (existing != ctx.trees.end())+        return existing->second;+    auto body = ctx.store.read_body(old_id, TYPE_TREE);+    if (!body)+        return std::nullopt;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return std::nullopt;+    bool changed = false;+    std::vector<TreeEntry> entries = tree->entries;+    for (auto& entry : entries) {+        std::optional<Id> mapped;+        if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||+            entry.kind == KIND_SYMLINK) {+            if (!is_lazy_blob(entry.target))+                continue;+            mapped = materialize_blob(ctx, entry.target);+        } else if (entry.kind == KIND_SUBTREE) {+            mapped = materialize_tree(ctx, entry.target, depth + 1);+        } else if (entry.kind == KIND_CONFLICT) {+            mapped = materialize_conflict(ctx, entry.target, depth + 1);+        } else if (entry.kind == KIND_SUBMODULE) {+            continue;+        } else {+            return std::nullopt;+        }+        if (!mapped)+            return std::nullopt;+        if (std::memcmp(mapped->data(), entry.target.data(), ID_LEN) != 0) {+            entry.target = *mapped;+            changed = true;+        }     }-    if (!mapped)-      return std::nullopt;-    if (std::memcmp(mapped->data(), entry.target.data(), ID_LEN) != 0) {-      entry.target = *mapped;-      changed = true;+    if (!changed) {+        ctx.trees[old_id] = old_id;+        return old_id;     }-  }-  if (!changed) {-    ctx.trees[old_id] = old_id;-    return old_id;-  }-  auto new_body = encode_tree(entries);-  if (!new_body)-    return std::nullopt;-  const Id new_id = ctx.writer.add(TYPE_TREE, *new_body);-  ctx.trees[old_id] = new_id;-  ++ctx.new_trees;-  ctx.changed = true;-  if (auto raw = git::load_raw(ctx.root, old_id))-    ctx.raw_saves.emplace_back(new_id, std::move(*raw));-  return new_id;+    auto new_body = encode_tree(entries);+    if (!new_body)+        return std::nullopt;+    const Id new_id = ctx.writer.add(TYPE_TREE, *new_body);+    ctx.trees[old_id] = new_id;+    ++ctx.new_trees;+    ctx.changed = true;+    if (auto raw = git::load_raw(ctx.root, old_id))+        ctx.raw_saves.emplace_back(new_id, std::move(*raw));+    return new_id; } -std::map<Id, git::Oid> reverse_git_map(const git::IdMap &map) {-  std::map<Id, git::Oid> out;-  for (const auto &item : map.items)-    out[item.second] = item.first;-  return out;+std::map<Id, git::Oid> reverse_git_map(const git::IdMap& map) {+    std::map<Id, git::Oid> out;+    for (const auto& item : map.items)+        out[item.second] = item.first;+    return out; }  std::string shell_quote(std::string_view value) {-  std::string out;-  out.push_back('\'');-  for (char c : value) {-    if (c == '\'')-      out += "'\\''";-    else-      out.push_back(c);-  }-  out.push_back('\'');-  return out;+    std::string out;+    out.push_back('\'');+    for (char c : value) {+        if (c == '\'')+            out += "'\\''";+        else+            out.push_back(c);+    }+    out.push_back('\'');+    return out; } -int run_git(const fs::path &dir, const std::vector<std::string> &args) {-  std::string command = "git -C ";-  command += shell_quote(path_to_bytes(dir));-  for (const auto &arg : args) {-    command.push_back(' ');-    command += shell_quote(arg);-  }-  const int rc = std::system(command.c_str());-  if (rc == -1)-    return -1;+int run_git(const fs::path& dir, const std::vector<std::string>& args) {+    std::string command = "git -C ";+    command += shell_quote(path_to_bytes(dir));+    for (const auto& arg : args) {+        command.push_back(' ');+        command += shell_quote(arg);+    }+    const int rc = std::system(command.c_str());+    if (rc == -1)+        return -1; #if !defined(_WIN32)-  if (WIFEXITED(rc))-    return WEXITSTATUS(rc);-  return 1;+    if (WIFEXITED(rc))+        return WEXITSTATUS(rc);+    return 1; #else-  return rc;+    return rc; #endif } -bool configure_mirror(const fs::path &root, std::string_view remote,-                      std::string_view url) {-  const fs::path dir = git_dir(root);-  if (!path_is_dir(dir))-    return false;-  (void)run_git(dir, {"remote", "remove", std::string(remote)});-  return run_git(dir,-                 {"remote", "add", std::string(remote), std::string(url)}) == 0;+bool configure_mirror(const fs::path& root, std::string_view remote, std::string_view url) {+    const fs::path dir = git_dir(root);+    if (!path_is_dir(dir))+        return false;+    (void)run_git(dir, {"remote", "remove", std::string(remote)});+    return run_git(dir, {"remote", "add", std::string(remote), std::string(url)}) == 0; } -void add_unique(std::vector<Id> &ids, const Id &id) {-  if (!contains_id(ids, id))-    ids.push_back(id);+void add_unique(std::vector<Id>& ids, const Id& id) {+    if (!contains_id(ids, id))+        ids.push_back(id); } -int import_tree_impl(-    Writer &writer, git::Repo &repo, IdMap &trees, IdMap &blobs, const Oid &oid,-    std::vector<std::pair<Id, std::vector<std::uint8_t>>> &raw_saves,-    std::size_t &new_trees, std::size_t &new_blobs, std::size_t depth) {-  if (depth > 4096)-    return 1;-  if (auto existing = trees.get(oid)) {-    (void)existing;-    return 0;-  }-  auto object = git::read_object(repo, oid);-  if (!object || object->kind != git::KIND_TREE)-    return 1;-  auto parsed =-      git::parse_tree(Bytes(object->body.data(), object->body.size()));-  if (!parsed)-    return 1;-  std::stable_sort(parsed->entries.begin(), parsed->entries.end(),-                   [](const git::RawTreeEntry &a, const git::RawTreeEntry &b) {-                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                   });-  std::vector<TreeEntry> entries;-  entries.reserve(parsed->entries.size());-  for (const auto &raw : parsed->entries) {-    const std::uint8_t kind = git::mode_kind(raw.mode);-    Id target{};-    if (kind == KIND_SUBTREE) {-      if (import_tree_impl(writer, repo, trees, blobs, raw.oid, raw_saves,-                           new_trees, new_blobs, depth + 1) != 0)+int import_tree_impl(Writer& writer, git::Repo& repo, IdMap& trees, IdMap& blobs, const Oid& oid,+                     std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,+                     std::size_t& new_trees, std::size_t& new_blobs, std::size_t depth) {+    if (depth > 4096)         return 1;-      auto child = trees.get(raw.oid);-      if (!child)+    if (auto existing = trees.get(oid)) {+        (void)existing;+        return 0;+    }+    auto object = git::read_object(repo, oid);+    if (!object || object->kind != git::KIND_TREE)         return 1;-      target = *child;-    } else if (kind == KIND_SUBMODULE) {-      std::memcpy(target.data(), raw.oid.data(), 20);-    } else {-      auto existing = blobs.get(raw.oid);-      if (existing) {-        target = *existing;-      } else {-        target = git::lazy_blob_id(raw.oid);-        blobs.put(raw.oid, target);-        ++new_blobs;-      }+    auto parsed = git::parse_tree(Bytes(object->body.data(), object->body.size()));+    if (!parsed)+        return 1;+    std::stable_sort(parsed->entries.begin(), parsed->entries.end(),+                     [](const git::RawTreeEntry& a, const git::RawTreeEntry& b) {+                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                     });+    std::vector<TreeEntry> entries;+    entries.reserve(parsed->entries.size());+    for (const auto& raw : parsed->entries) {+        const std::uint8_t kind = git::mode_kind(raw.mode);+        Id target{};+        if (kind == KIND_SUBTREE) {+            if (import_tree_impl(writer, repo, trees, blobs, raw.oid, raw_saves, new_trees,+                                 new_blobs, depth + 1) != 0)+                return 1;+            auto child = trees.get(raw.oid);+            if (!child)+                return 1;+            target = *child;+        } else if (kind == KIND_SUBMODULE) {+            std::memcpy(target.data(), raw.oid.data(), 20);+        } else {+            auto existing = blobs.get(raw.oid);+            if (existing) {+                target = *existing;+            } else {+                target = git::lazy_blob_id(raw.oid);+                blobs.put(raw.oid, target);+                ++new_blobs;+            }+        }+        entries.push_back(TreeEntry{raw.name, kind, target});     }-    entries.push_back(TreeEntry{raw.name, kind, target});-  }-  auto body = encode_tree(entries);-  if (!body)-    return 1;-  const Id id = writer.add(TYPE_TREE, *body);-  trees.put(oid, id);-  ++new_trees;-  if (!parsed->canonical)-    raw_saves.emplace_back(id, object->body);-  return 0;+    auto body = encode_tree(entries);+    if (!body)+        return 1;+    const Id id = writer.add(TYPE_TREE, *body);+    trees.put(oid, id);+    ++new_trees;+    if (!parsed->canonical)+        raw_saves.emplace_back(id, object->body);+    return 0; }  } // namespace@@ -513,1044 +501,1012 @@  namespace git { -std::optional<Id>-import_tree(Writer &writer, Repo &repo, IdMap &trees, IdMap &blobs,-            const Oid &oid,-            std::vector<std::pair<Id, std::vector<std::uint8_t>>> &raw_saves,-            std::size_t &new_trees, std::size_t &new_blobs, std::size_t depth) {-  if (import_tree_impl(writer, repo, trees, blobs, oid, raw_saves, new_trees,-                       new_blobs, depth) != 0)-    return std::nullopt;-  return trees.get(oid);+std::optional<Id> import_tree(Writer& writer, Repo& repo, IdMap& trees, IdMap& blobs,+                              const Oid& oid,+                              std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,+                              std::size_t& new_trees, std::size_t& new_blobs, std::size_t depth) {+    if (import_tree_impl(writer, repo, trees, blobs, oid, raw_saves, new_trees, new_blobs, depth) !=+        0)+        return std::nullopt;+    return trees.get(oid); } -bool export_tree(const fs::path &root, Store &store, IdMap &trees, IdMap &blobs,-                 const Id &id, Oid &out, std::size_t depth) {-  if (depth > 4096)-    return false;-  if (auto existing = trees.reverse(id)) {-    out = *existing;-    return true;-  }-  const fs::path mirror = git_dir(root);-  if (auto raw = load_raw(root, id)) {-    auto oid = object_hash(git::KIND_TREE, Bytes(raw->data(), raw->size()));-    if (!oid || !write_loose(mirror, git::KIND_TREE, *oid,-                             Bytes(raw->data(), raw->size())))-      return false;+bool export_tree(const fs::path& root, Store& store, IdMap& trees, IdMap& blobs, const Id& id,+                 Oid& out, std::size_t depth) {+    if (depth > 4096)+        return false;+    if (auto existing = trees.reverse(id)) {+        out = *existing;+        return true;+    }+    const fs::path mirror = git_dir(root);+    if (auto raw = load_raw(root, id)) {+        auto oid = object_hash(git::KIND_TREE, Bytes(raw->data(), raw->size()));+        if (!oid || !write_loose(mirror, git::KIND_TREE, *oid, Bytes(raw->data(), raw->size())))+            return false;+        trees.put(*oid, id);+        out = *oid;+        return true;+    }+    auto body = store.read_body(id, TYPE_TREE);+    if (!body)+        return false;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return false;++    struct GitEntry {+        std::string mode;+        std::string name;+        Oid oid{};+        bool dir = false;+    };+    std::vector<GitEntry> entries;+    entries.reserve(tree->entries.size());+    for (const auto& entry : tree->entries) {+        GitEntry out_entry;+        out_entry.name = entry.name;+        out_entry.mode = mode_for_kind(entry.kind);+        out_entry.dir = entry.kind == KIND_SUBTREE;+        if (entry.kind == KIND_SUBTREE) {+            if (!export_tree(root, store, trees, blobs, entry.target, out_entry.oid, depth + 1))+                return false;+        } else if (entry.kind == KIND_SUBMODULE) {+            std::memcpy(out_entry.oid.data(), entry.target.data(), 20);+        } else if (entry.kind == KIND_CONFLICT) {+            return false;+        } else {+            Oid oid{};+            if (auto lazy = lazy_blob_oid(entry.target)) {+                oid = *lazy;+                blobs.put(oid, entry.target);+            } else if (auto existing = blobs.reverse(entry.target)) {+                oid = *existing;+            } else {+                auto data = read_blob(store, entry.target);+                if (!data)+                    return false;+                auto hash = object_hash(git::KIND_BLOB, Bytes(data->data(), data->size()));+                if (!hash ||+                    !write_loose(mirror, git::KIND_BLOB, *hash, Bytes(data->data(), data->size())))+                    return false;+                oid = *hash;+                blobs.put(oid, entry.target);+            }+            out_entry.oid = oid;+        }+        entries.push_back(std::move(out_entry));+    }+    std::stable_sort(entries.begin(), entries.end(), [](const GitEntry& a, const GitEntry& b) {+        std::string ak = a.name;+        std::string bk = b.name;+        if (a.dir)+            ak.push_back('/');+        if (b.dir)+            bk.push_back('/');+        return compare(bytes_of(ak), bytes_of(bk)) < 0;+    });+    std::vector<std::uint8_t> git_body;+    for (const auto& entry : entries) {+        git_body.insert(git_body.end(), entry.mode.begin(), entry.mode.end());+        git_body.push_back(' ');+        git_body.insert(git_body.end(), entry.name.begin(), entry.name.end());+        git_body.push_back(0);+        git_body.insert(git_body.end(), entry.oid.begin(), entry.oid.end());+    }+    auto oid = object_hash(git::KIND_TREE, Bytes(git_body.data(), git_body.size()));+    if (!oid || !write_loose(mirror, git::KIND_TREE, *oid, Bytes(git_body.data(), git_body.size())))+        return false;     trees.put(*oid, id);     out = *oid;     return true;-  }-  auto body = store.read_body(id, TYPE_TREE);-  if (!body)-    return false;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return false;+} -  struct GitEntry {-    std::string mode;-    std::string name;-    Oid oid{};-    bool dir = false;-  };-  std::vector<GitEntry> entries;-  entries.reserve(tree->entries.size());-  for (const auto &entry : tree->entries) {-    GitEntry out_entry;-    out_entry.name = entry.name;-    out_entry.mode = mode_for_kind(entry.kind);-    out_entry.dir = entry.kind == KIND_SUBTREE;-    if (entry.kind == KIND_SUBTREE) {-      if (!export_tree(root, store, trees, blobs, entry.target, out_entry.oid,-                       depth + 1))+bool export_commit(const fs::path& root, Store& store, IdMap& commits, IdMap& trees, IdMap& blobs,+                   const std::vector<Id>& native, const Id& id, Oid& out, std::size_t depth) {+    if (depth > 4096)         return false;-    } else if (entry.kind == KIND_SUBMODULE) {-      std::memcpy(out_entry.oid.data(), entry.target.data(), 20);-    } else if (entry.kind == KIND_CONFLICT) {-      return false;-    } else {-      Oid oid{};-      if (auto lazy = lazy_blob_oid(entry.target)) {-        oid = *lazy;-        blobs.put(oid, entry.target);-      } else if (auto existing = blobs.reverse(entry.target)) {-        oid = *existing;-      } else {-        auto data = read_blob(store, entry.target);-        if (!data)-          return false;-        auto hash =-            object_hash(git::KIND_BLOB, Bytes(data->data(), data->size()));-        if (!hash || !write_loose(mirror, git::KIND_BLOB, *hash,-                                  Bytes(data->data(), data->size())))-          return false;-        oid = *hash;-        blobs.put(oid, entry.target);-      }-      out_entry.oid = oid;+    if (auto existing = commits.reverse(id)) {+        out = *existing;+        return true;     }-    entries.push_back(std::move(out_entry));-  }-  std::stable_sort(entries.begin(), entries.end(),-                   [](const GitEntry &a, const GitEntry &b) {-                     std::string ak = a.name;-                     std::string bk = b.name;-                     if (a.dir)-                       ak.push_back('/');-                     if (b.dir)-                       bk.push_back('/');-                     return compare(bytes_of(ak), bytes_of(bk)) < 0;-                   });-  std::vector<std::uint8_t> git_body;-  for (const auto &entry : entries) {-    git_body.insert(git_body.end(), entry.mode.begin(), entry.mode.end());-    git_body.push_back(' ');-    git_body.insert(git_body.end(), entry.name.begin(), entry.name.end());-    git_body.push_back(0);-    git_body.insert(git_body.end(), entry.oid.begin(), entry.oid.end());-  }-  auto oid =-      object_hash(git::KIND_TREE, Bytes(git_body.data(), git_body.size()));-  if (!oid || !write_loose(mirror, git::KIND_TREE, *oid,-                           Bytes(git_body.data(), git_body.size())))-    return false;-  trees.put(*oid, id);-  out = *oid;-  return true;-}--bool export_commit(const fs::path &root, Store &store, IdMap &commits,-                   IdMap &trees, IdMap &blobs, const std::vector<Id> &native,-                   const Id &id, Oid &out, std::size_t depth) {-  if (depth > 4096)-    return false;-  if (auto existing = commits.reverse(id)) {-    out = *existing;-    return true;-  }-  auto loaded = load_commit(store, id);-  if (!loaded)-    return false;-  Oid tree_oid{};-  if (!export_tree(root, store, trees, blobs, loaded->commit.root_tree,-                   tree_oid, 0))-    return false;-  std::vector<Oid> parents;-  for (const auto &parent : loaded->commit.parents) {-    auto oid = commits.reverse(parent);-    if (!oid)-      return false;-    parents.push_back(*oid);-  }-  const fs::path mirror = git_dir(root);+    auto loaded = load_commit(store, id);+    if (!loaded)+        return false;+    Oid tree_oid{};+    if (!export_tree(root, store, trees, blobs, loaded->commit.root_tree, tree_oid, 0))+        return false;+    std::vector<Oid> parents;+    for (const auto& parent : loaded->commit.parents) {+        auto oid = commits.reverse(parent);+        if (!oid)+            return false;+        parents.push_back(*oid);+    }+    const fs::path mirror = git_dir(root); -  std::vector<std::uint8_t> body;-  bool used_raw = false;-  if (auto raw = load_raw(root, id)) {-    if (auto parsed = parse_commit(Bytes(raw->data(), raw->size()))) {-      bool matches = std::memcmp(parsed->tree.data(), tree_oid.data(),-                                 tree_oid.size()) == 0 &&-                     parsed->parents.size() == parents.size();-      for (std::size_t i = 0; matches && i < parents.size(); ++i)-        matches = std::memcmp(parsed->parents[i].data(), parents[i].data(),-                              parents[i].size()) == 0;-      if (matches) {-        body = *raw;-        used_raw = true;-      }+    std::vector<std::uint8_t> body;+    bool used_raw = false;+    if (auto raw = load_raw(root, id)) {+        if (auto parsed = parse_commit(Bytes(raw->data(), raw->size()))) {+            bool matches =+                std::memcmp(parsed->tree.data(), tree_oid.data(), tree_oid.size()) == 0 &&+                parsed->parents.size() == parents.size();+            for (std::size_t i = 0; matches && i < parents.size(); ++i)+                matches = std::memcmp(parsed->parents[i].data(), parents[i].data(),+                                      parents[i].size()) == 0;+            if (matches) {+                body = *raw;+                used_raw = true;+            }+        }     }-  }-  if (!used_raw) {-    ParsedCommit parsed;-    parsed.tree = tree_oid;-    parsed.parents = parents;-    parsed.author = loaded->commit.author;-    parsed.committer = loaded->commit.committer;-    parsed.message = loaded->commit.message;-    parsed.extras = loaded->commit.extra;-    if (is_native(native, id)) {-      parsed.extras.push_back(-          KeyValue{"veins-change-id",-                   hex_encode(Bytes(loaded->commit.change_id.data(),-                                    loaded->commit.change_id.size()))});+    if (!used_raw) {+        ParsedCommit parsed;+        parsed.tree = tree_oid;+        parsed.parents = parents;+        parsed.author = loaded->commit.author;+        parsed.committer = loaded->commit.committer;+        parsed.message = loaded->commit.message;+        parsed.extras = loaded->commit.extra;+        if (is_native(native, id)) {+            parsed.extras.push_back(+                KeyValue{"veins-change-id", hex_encode(Bytes(loaded->commit.change_id.data(),+                                                             loaded->commit.change_id.size()))});+        }+        body = serialize_commit(parsed);     }-    body = serialize_commit(parsed);-  }-  auto oid = object_hash(git::KIND_COMMIT, Bytes(body.data(), body.size()));-  if (!oid || !write_loose(mirror, git::KIND_COMMIT, *oid,-                           Bytes(body.data(), body.size())))-    return false;-  commits.put(*oid, id);-  out = *oid;-  return true;+    auto oid = object_hash(git::KIND_COMMIT, Bytes(body.data(), body.size()));+    if (!oid || !write_loose(mirror, git::KIND_COMMIT, *oid, Bytes(body.data(), body.size())))+        return false;+    commits.put(*oid, id);+    out = *oid;+    return true; }  } // namespace git -int git_import(const fs::path &root) {-  const bool checkout_after = working_tree_empty(root);-  const bool view_from_store = !read_heads(root).empty();-  const fs::path mirror = git_dir(root);-  auto repo = git::open_repo(mirror);-  if (!repo) {-    error_prefix();-    std::cout << "cannot open git mirror: " << path_display(mirror) << "\n";-    return 1;-  }-  IdMap commits_map;-  IdMap trees_map;-  IdMap blobs_map;-  if (!git::load_map(root, "commits", commits_map) ||-      !git::load_map(root, "trees", trees_map) ||-      !git::load_map(root, "blobs", blobs_map)) {-    error_prefix();-    std::cout << "corrupt git mapping table\n";-    return 1;-  }+int git_import(const fs::path& root) {+    const bool checkout_after = working_tree_empty(root);+    const bool view_from_store = !read_heads(root).empty();+    const fs::path mirror = git_dir(root);+    auto repo = git::open_repo(mirror);+    if (!repo) {+        error_prefix();+        std::cout << "cannot open git mirror: " << path_display(mirror) << "\n";+        return 1;+    }+    IdMap commits_map;+    IdMap trees_map;+    IdMap blobs_map;+    if (!git::load_map(root, "commits", commits_map) || !git::load_map(root, "trees", trees_map) ||+        !git::load_map(root, "blobs", blobs_map)) {+        error_prefix();+        std::cout << "corrupt git mapping table\n";+        return 1;+    } -  const auto refset = git::read_refs(mirror);-  Store store = Store::open_all(root);-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  View before = tx->view();-  Writer &writer = tx->writer();-  std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;-  std::size_t new_commits = 0;-  std::size_t new_trees = 0;-  std::size_t new_blobs = 0;+    const auto refset = git::read_refs(mirror);+    Store store = Store::open_all(root);+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    View before = tx->view();+    Writer& writer = tx->writer();+    std::vector<std::pair<Id, std::vector<std::uint8_t>>> raw_saves;+    std::size_t new_commits = 0;+    std::size_t new_trees = 0;+    std::size_t new_blobs = 0; -  std::vector<NamedTarget> branches;-  std::vector<NamedTarget> tags;-  std::vector<NamedTarget> remotes;-  std::vector<Oid> tips;-  for (const auto &ref : refset.branches) {-    auto peeled = peel_to_commit(*repo, ref.oid);-    if (peeled) {-      branches.push_back(NamedTarget{ref.name, *peeled});-      tips.push_back(*peeled);+    std::vector<NamedTarget> branches;+    std::vector<NamedTarget> tags;+    std::vector<NamedTarget> remotes;+    std::vector<Oid> tips;+    for (const auto& ref : refset.branches) {+        auto peeled = peel_to_commit(*repo, ref.oid);+        if (peeled) {+            branches.push_back(NamedTarget{ref.name, *peeled});+            tips.push_back(*peeled);+        }     }-  }-  for (const auto &ref : refset.tags) {-    auto peeled = peel_to_commit(*repo, ref.oid);-    if (peeled) {-      tags.push_back(NamedTarget{ref.name, *peeled});-      tips.push_back(*peeled);+    for (const auto& ref : refset.tags) {+        auto peeled = peel_to_commit(*repo, ref.oid);+        if (peeled) {+            tags.push_back(NamedTarget{ref.name, *peeled});+            tips.push_back(*peeled);+        }     }-  }-  for (const auto &ref : refset.remotes) {-    auto peeled = peel_to_commit(*repo, ref.oid);-    if (peeled) {-      remotes.push_back(NamedTarget{ref.name, *peeled});-      tips.push_back(*peeled);+    for (const auto& ref : refset.remotes) {+        auto peeled = peel_to_commit(*repo, ref.oid);+        if (peeled) {+            remotes.push_back(NamedTarget{ref.name, *peeled});+            tips.push_back(*peeled);+        }     }-  }-  std::optional<Oid> head_commit;-  if (refset.head) {-    head_commit = peel_to_commit(*repo, *refset.head);-    if (head_commit)-      tips.push_back(*head_commit);-  }+    std::optional<Oid> head_commit;+    if (refset.head) {+        head_commit = peel_to_commit(*repo, *refset.head);+        if (head_commit)+            tips.push_back(*head_commit);+    } -  std::optional<std::string> current_branch;-  if (head_commit) {-    std::optional<std::string> match;-    for (const auto &branch : branches) {-      if (std::memcmp(branch.oid.data(), head_commit->data(),-                      head_commit->size()) != 0)-        continue;-      if (branch.name == "main" || branch.name == "master")-        match = branch.name;-      else if (!match)-        match = branch.name;+    std::optional<std::string> current_branch;+    if (head_commit) {+        std::optional<std::string> match;+        for (const auto& branch : branches) {+            if (std::memcmp(branch.oid.data(), head_commit->data(), head_commit->size()) != 0)+                continue;+            if (branch.name == "main" || branch.name == "master")+                match = branch.name;+            else if (!match)+                match = branch.name;+        }+        current_branch = match;     }-    current_branch = match;-  }-  if (!current_branch) {-    for (const auto &branch : branches) {-      if (branch.name == "main" || branch.name == "master") {-        current_branch = branch.name;-        break;-      }+    if (!current_branch) {+        for (const auto& branch : branches) {+            if (branch.name == "main" || branch.name == "master") {+                current_branch = branch.name;+                break;+            }+        }     }-  }-  if (!current_branch && !branches.empty())-    current_branch = branches.front().name;+    if (!current_branch && !branches.empty())+        current_branch = branches.front().name; -  std::vector<CommitRecord> records;-  std::set<Oid, OidLess> seen;-  std::vector<Oid> stack(tips.rbegin(), tips.rend());-  while (!stack.empty()) {-    const Oid oid = stack.back();-    stack.pop_back();-    if (commits_map.get(oid) || seen.count(oid))-      continue;-    seen.insert(oid);-    auto object = git::read_object(*repo, oid);-    if (!object)-      continue;-    if (object->kind != git::KIND_COMMIT)-      continue;-    auto parsed =-        git::parse_commit(Bytes(object->body.data(), object->body.size()));-    if (!parsed)-      continue;-    records.push_back(-        CommitRecord{oid, std::move(object->body), std::move(*parsed)});-    for (const auto &parent : records.back().parsed.parents)-      stack.push_back(parent);-  }+    std::vector<CommitRecord> records;+    std::set<Oid, OidLess> seen;+    std::vector<Oid> stack(tips.rbegin(), tips.rend());+    while (!stack.empty()) {+        const Oid oid = stack.back();+        stack.pop_back();+        if (commits_map.get(oid) || seen.count(oid))+            continue;+        seen.insert(oid);+        auto object = git::read_object(*repo, oid);+        if (!object)+            continue;+        if (object->kind != git::KIND_COMMIT)+            continue;+        auto parsed = git::parse_commit(Bytes(object->body.data(), object->body.size()));+        if (!parsed)+            continue;+        records.push_back(CommitRecord{oid, std::move(object->body), std::move(*parsed)});+        for (const auto& parent : records.back().parsed.parents)+            stack.push_back(parent);+    } -  const std::size_t n = records.size();-  std::map<Oid, std::size_t, OidLess> index;-  for (std::size_t i = 0; i < n; ++i)-    index[records[i].oid] = i;-  std::vector<std::size_t> indegree(n, 0);-  std::vector<std::vector<std::size_t>> children(n);-  bool topo_failed = false;-  for (std::size_t i = 0; i < n; ++i) {-    for (const auto &parent : records[i].parsed.parents) {-      if (commits_map.get(parent))-        continue;-      auto it = index.find(parent);-      if (it == index.end()) {-        topo_failed = true;-        continue;-      }-      ++indegree[i];-      children[it->second].push_back(i);+    const std::size_t n = records.size();+    std::map<Oid, std::size_t, OidLess> index;+    for (std::size_t i = 0; i < n; ++i)+        index[records[i].oid] = i;+    std::vector<std::size_t> indegree(n, 0);+    std::vector<std::vector<std::size_t>> children(n);+    bool topo_failed = false;+    for (std::size_t i = 0; i < n; ++i) {+        for (const auto& parent : records[i].parsed.parents) {+            if (commits_map.get(parent))+                continue;+            auto it = index.find(parent);+            if (it == index.end()) {+                topo_failed = true;+                continue;+            }+            ++indegree[i];+            children[it->second].push_back(i);+        }     }-  }-  std::vector<std::size_t> queue;-  for (std::size_t i = 0; i < n; ++i) {-    if (indegree[i] == 0)-      queue.push_back(i);-  }-  std::vector<std::size_t> order;-  for (std::size_t head = 0; head < queue.size(); ++head) {-    const std::size_t current = queue[head];-    order.push_back(current);-    for (std::size_t child : children[current]) {-      if (indegree[child] > 0 && --indegree[child] == 0)-        queue.push_back(child);+    std::vector<std::size_t> queue;+    for (std::size_t i = 0; i < n; ++i) {+        if (indegree[i] == 0)+            queue.push_back(i);     }-  }-  if (topo_failed || order.size() != n) {-    error_prefix();-    std::cout << "git commit graph is incomplete or cyclic\n";-    return 1;-  }--  bool build_failed = false;-  for (std::size_t idx : order) {-    auto imported = git::import_tree(writer, *repo, trees_map, blobs_map,-                                     records[idx].parsed.tree, raw_saves,-                                     new_trees, new_blobs);-    if (!imported) {-      build_failed = true;-      break;+    std::vector<std::size_t> order;+    for (std::size_t head = 0; head < queue.size(); ++head) {+        const std::size_t current = queue[head];+        order.push_back(current);+        for (std::size_t child : children[current]) {+            if (indegree[child] > 0 && --indegree[child] == 0)+                queue.push_back(child);+        }     }-  }-  if (!build_failed) {+    if (topo_failed || order.size() != n) {+        error_prefix();+        std::cout << "git commit graph is incomplete or cyclic\n";+        return 1;+    }++    bool build_failed = false;     for (std::size_t idx : order) {-      const auto &record = records[idx];-      auto tree = trees_map.get(record.parsed.tree);-      if (!tree) {-        build_failed = true;-        break;-      }-      Commit commit;-      commit.version = 1;-      for (const auto &parent : record.parsed.parents) {-        auto mapped = commits_map.get(parent);-        if (!mapped) {-          build_failed = true;-          break;+        auto imported = git::import_tree(writer, *repo, trees_map, blobs_map,+                                         records[idx].parsed.tree, raw_saves, new_trees, new_blobs);+        if (!imported) {+            build_failed = true;+            break;         }-        commit.parents.push_back(*mapped);-      }-      if (build_failed)-        break;-      commit.root_tree = *tree;-      commit.change_id = record.parsed.change_id ? *record.parsed.change_id-                                                 : derive_change_id(record.oid);-      commit.author = record.parsed.author;-      commit.committer = record.parsed.committer;-      commit.message = record.parsed.message;-      commit.renames_state = RENAMES_UNKNOWN;-      commit.extra = record.parsed.extras;-      const Id id = writer.add(TYPE_COMMIT, encode_commit(commit));-      commits_map.put(record.oid, id);-      ++new_commits;-      const auto canonical = git::serialize_commit(record.parsed);-      const bool is_canonical =-          record.parsed.canonical &&-          equals(Bytes(canonical.data(), canonical.size()),-                 Bytes(record.body.data(), record.body.size()));-      if (!is_canonical)-        raw_saves.emplace_back(id, record.body);     }-  }-  if (build_failed) {-    error_prefix();-    std::cout << "referenced git object is missing\n";-    return 1;-  }+    if (!build_failed) {+        for (std::size_t idx : order) {+            const auto& record = records[idx];+            auto tree = trees_map.get(record.parsed.tree);+            if (!tree) {+                build_failed = true;+                break;+            }+            Commit commit;+            commit.version = 1;+            for (const auto& parent : record.parsed.parents) {+                auto mapped = commits_map.get(parent);+                if (!mapped) {+                    build_failed = true;+                    break;+                }+                commit.parents.push_back(*mapped);+            }+            if (build_failed)+                break;+            commit.root_tree = *tree;+            commit.change_id =+                record.parsed.change_id ? *record.parsed.change_id : derive_change_id(record.oid);+            commit.author = record.parsed.author;+            commit.committer = record.parsed.committer;+            commit.message = record.parsed.message;+            commit.renames_state = RENAMES_UNKNOWN;+            commit.extra = record.parsed.extras;+            const Id id = writer.add(TYPE_COMMIT, encode_commit(commit));+            commits_map.put(record.oid, id);+            ++new_commits;+            const auto canonical = git::serialize_commit(record.parsed);+            const bool is_canonical =+                record.parsed.canonical && equals(Bytes(canonical.data(), canonical.size()),+                                                  Bytes(record.body.data(), record.body.size()));+            if (!is_canonical)+                raw_saves.emplace_back(id, record.body);+        }+    }+    if (build_failed) {+        error_prefix();+        std::cout << "referenced git object is missing\n";+        return 1;+    } -  View &view = tx->view();-  for (const auto &branch : branches) {-    if (auto id = commits_map.get(branch.oid))-      set_bookmark(view, branch.name, *id);-  }-  for (const auto &tag : tags) {-    if (auto id = commits_map.get(tag.oid))-      set_tag(view, tag.name, *id);-  }-  for (const auto &remote : remotes) {-    if (auto id = commits_map.get(remote.oid)) {-      const auto parts = split_remote(remote.name);-      set_remote_ref(view, parts.first, parts.second, *id);-      if (!find_bookmark(view, parts.second))-        set_bookmark(view, parts.second, *id);+    View& view = tx->view();+    for (const auto& branch : branches) {+        if (auto id = commits_map.get(branch.oid))+            set_bookmark(view, branch.name, *id);     }-  }+    for (const auto& tag : tags) {+        if (auto id = commits_map.get(tag.oid))+            set_tag(view, tag.name, *id);+    }+    for (const auto& remote : remotes) {+        if (auto id = commits_map.get(remote.oid)) {+            const auto parts = split_remote(remote.name);+            set_remote_ref(view, parts.first, parts.second, *id);+            if (!find_bookmark(view, parts.second))+                set_bookmark(view, parts.second, *id);+        }+    } -  view.heads.clear();-  for (const auto &branch : branches) {-    if (auto id = commits_map.get(branch.oid))-      add_unique(view.heads, *id);-  }-  for (const auto &remote : remotes) {-    if (auto id = commits_map.get(remote.oid))-      add_unique(view.heads, *id);-  }-  if (view.heads.empty()) {-    for (const auto &tag : tags) {-      if (auto id = commits_map.get(tag.oid))-        add_unique(view.heads, *id);+    view.heads.clear();+    for (const auto& branch : branches) {+        if (auto id = commits_map.get(branch.oid))+            add_unique(view.heads, *id);     }-  }-  std::optional<Id> head_id;-  if (head_commit) {-    if (auto id = commits_map.get(*head_commit))-      head_id = *id;-  }-  if (view.heads.empty() && head_id)-    add_unique(view.heads, *head_id);-  sort_ids(view.heads);-  if (checkout_after || !view_from_store) {-    if (head_id)-      set_workspace(view, *head_id);-    else if (!view.heads.empty())-      set_workspace(view, view.heads.front());-  }+    for (const auto& remote : remotes) {+        if (auto id = commits_map.get(remote.oid))+            add_unique(view.heads, *id);+    }+    if (view.heads.empty()) {+        for (const auto& tag : tags) {+            if (auto id = commits_map.get(tag.oid))+                add_unique(view.heads, *id);+        }+    }+    std::optional<Id> head_id;+    if (head_commit) {+        if (auto id = commits_map.get(*head_commit))+            head_id = *id;+    }+    if (view.heads.empty() && head_id)+        add_unique(view.heads, *head_id);+    sort_ids(view.heads);+    if (checkout_after || !view_from_store) {+        if (head_id)+            set_workspace(view, *head_id);+        else if (!view.heads.empty())+            set_workspace(view, view.heads.front());+    } -  const auto old_encoded = encode_view(before);-  const auto new_encoded = encode_view(view);-  const bool unchanged = equals(bytes_of(old_encoded), bytes_of(new_encoded));-  const bool has_new_objects =-      new_commits > 0 || new_trees > 0 || new_blobs > 0;-  if (unchanged && !has_new_objects) {+    const auto old_encoded = encode_view(before);+    const auto new_encoded = encode_view(view);+    const bool unchanged = equals(bytes_of(old_encoded), bytes_of(new_encoded));+    const bool has_new_objects = new_commits > 0 || new_trees > 0 || new_blobs > 0;+    if (unchanged && !has_new_objects) {+        if (current_branch)+            (void)set_current_bookmark(root, *current_branch);+        else+            (void)clear_current_bookmark(root);+        info_prefix();+        std::cout << "already up to date\n";+        return 0;+    }+    auto status = tx->finish("git import");+    if (!status) {+        error_prefix();+        std::cout << "failed to write object pack\n";+        return 1;+    }     if (current_branch)-      (void)set_current_bookmark(root, *current_branch);+        (void)set_current_bookmark(root, *current_branch);     else-      (void)clear_current_bookmark(root);+        (void)clear_current_bookmark(root);+    for (const auto& raw : raw_saves)+        (void)git::save_raw(root, raw.first, Bytes(raw.second.data(), raw.second.size()));+    if (!git::save_map(root, "commits", commits_map) || !git::save_map(root, "trees", trees_map) ||+        !git::save_map(root, "blobs", blobs_map)) {+        error_prefix();+        std::cout << "failed to write git mapping tables\n";+    }     info_prefix();-    std::cout << "already up to date\n";-    return 0;-  }-  auto status = tx->finish("git import");-  if (!status) {-    error_prefix();-    std::cout << "failed to write object pack\n";-    return 1;-  }-  if (current_branch)-    (void)set_current_bookmark(root, *current_branch);-  else-    (void)clear_current_bookmark(root);-  for (const auto &raw : raw_saves)-    (void)git::save_raw(root, raw.first,-                        Bytes(raw.second.data(), raw.second.size()));-  if (!git::save_map(root, "commits", commits_map) ||-      !git::save_map(root, "trees", trees_map) ||-      !git::save_map(root, "blobs", blobs_map)) {-    error_prefix();-    std::cout << "failed to write git mapping tables\n";-  }-  info_prefix();-  std::cout << "imported " << new_commits << " commits, " << new_trees-            << " trees, " << new_blobs << " blobs\n";+    std::cout << "imported " << new_commits << " commits, " << new_trees << " trees, " << new_blobs+              << " blobs\n"; -  if (checkout_after && head_id) {-    const int wc_status = create_working_copy(root, *head_id);-    if (wc_status != 0) {-      error_prefix();-      std::cout << "imported history; cannot create working copy (code "-                << wc_status << ")\n";-      return 1;-    }-    const int checkout_status = materialize_working_copy(root, store);-    if (checkout_status != 0) {-      error_prefix();-      std::cout << "imported history; checkout failed (code " << checkout_status-                << ")\n";-      return 1;+    if (checkout_after && head_id) {+        const int wc_status = create_working_copy(root, *head_id);+        if (wc_status != 0) {+            error_prefix();+            std::cout << "imported history; cannot create working copy (code " << wc_status+                      << ")\n";+            return 1;+        }+        const int checkout_status = materialize_working_copy(root, store);+        if (checkout_status != 0) {+            error_prefix();+            std::cout << "imported history; checkout failed (code " << checkout_status << ")\n";+            return 1;+        }     }-  }-  return 0;+    return 0; } -int git_materialize(const fs::path &root) {-  git::IdMap commits_map;-  git::IdMap trees_map;-  git::IdMap blobs_map;-  if (!git::load_map(root, "commits", commits_map) ||-      !git::load_map(root, "trees", trees_map) ||-      !git::load_map(root, "blobs", blobs_map)) {-    error_prefix();-    std::cout << "corrupt git mapping table\n";-    return 1;-  }-  const auto reverse_commits = reverse_git_map(commits_map);-  const auto reverse_trees = reverse_git_map(trees_map);+int git_materialize(const fs::path& root) {+    git::IdMap commits_map;+    git::IdMap trees_map;+    git::IdMap blobs_map;+    if (!git::load_map(root, "commits", commits_map) || !git::load_map(root, "trees", trees_map) ||+        !git::load_map(root, "blobs", blobs_map)) {+        error_prefix();+        std::cout << "corrupt git mapping table\n";+        return 1;+    }+    const auto reverse_commits = reverse_git_map(commits_map);+    const auto reverse_trees = reverse_git_map(trees_map); -  Store store = Store::open_all(root);-  auto view = current_view(root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  MaterializeCtx ctx{root, store, tx->writer(), {}, {}, {}, {}, {}, 0,-                     0,    0,     false};-  const auto roots = view_roots(*view);-  const auto ordered = ordered_commits(store, roots);-  for (const auto &old_id : ordered) {-    auto body = store.read_body(old_id, TYPE_COMMIT);-    if (!body)-      break;-    auto commit = decode_commit(bytes_of(*body));-    if (!commit)-      break;-    auto mapped_root = materialize_tree(ctx, commit->root_tree, 0);-    if (!mapped_root)-      break;-    bool changed =-        std::memcmp(mapped_root->data(), commit->root_tree.data(), ID_LEN) != 0;-    std::vector<Id> parents;-    parents.reserve(commit->parents.size());-    bool parents_ok = true;-    for (const auto &parent : commit->parents) {-      auto it = ctx.commits.find(parent);-      if (it == ctx.commits.end()) {-        parents_ok = false;-        break;-      }-      parents.push_back(it->second);-      if (std::memcmp(it->second.data(), parent.data(), ID_LEN) != 0)-        changed = true;+    Store store = Store::open_all(root);+    auto view = current_view(root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;     }-    if (!parents_ok)-      break;-    if (!changed) {-      ctx.commits[old_id] = old_id;-      continue;+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;     }-    commit->root_tree = *mapped_root;-    commit->parents = std::move(parents);-    const Id new_id = ctx.writer.add(TYPE_COMMIT, encode_commit(*commit));-    ctx.commits[old_id] = new_id;-    ++ctx.new_commits;-    ctx.changed = true;-    if (auto raw = git::load_raw(root, old_id))-      ctx.raw_saves.emplace_back(new_id, std::move(*raw));-  }-  if (ctx.commits.size() != ordered.size()) {-    error_prefix();-    std::cout << "git materialize failed (missing or corrupt object)\n";-    return 1;-  }--  View &updated = tx->view();-  auto remap = [&](const Id &id) -> Id {-    auto it = ctx.commits.find(id);-    return it == ctx.commits.end() ? id : it->second;-  };-  for (auto &head : updated.heads)-    head = remap(head);-  for (auto &bookmark : updated.bookmarks) {-    for (auto &target : bookmark.targets.adds) {-      if (target)-        target = remap(*target);+    MaterializeCtx ctx{root, store, tx->writer(), {}, {}, {}, {}, {}, 0, 0, 0, false};+    const auto roots = view_roots(*view);+    const auto ordered = ordered_commits(store, roots);+    for (const auto& old_id : ordered) {+        auto body = store.read_body(old_id, TYPE_COMMIT);+        if (!body)+            break;+        auto commit = decode_commit(bytes_of(*body));+        if (!commit)+            break;+        auto mapped_root = materialize_tree(ctx, commit->root_tree, 0);+        if (!mapped_root)+            break;+        bool changed = std::memcmp(mapped_root->data(), commit->root_tree.data(), ID_LEN) != 0;+        std::vector<Id> parents;+        parents.reserve(commit->parents.size());+        bool parents_ok = true;+        for (const auto& parent : commit->parents) {+            auto it = ctx.commits.find(parent);+            if (it == ctx.commits.end()) {+                parents_ok = false;+                break;+            }+            parents.push_back(it->second);+            if (std::memcmp(it->second.data(), parent.data(), ID_LEN) != 0)+                changed = true;+        }+        if (!parents_ok)+            break;+        if (!changed) {+            ctx.commits[old_id] = old_id;+            continue;+        }+        commit->root_tree = *mapped_root;+        commit->parents = std::move(parents);+        const Id new_id = ctx.writer.add(TYPE_COMMIT, encode_commit(*commit));+        ctx.commits[old_id] = new_id;+        ++ctx.new_commits;+        ctx.changed = true;+        if (auto raw = git::load_raw(root, old_id))+            ctx.raw_saves.emplace_back(new_id, std::move(*raw));     }-    for (auto &target : bookmark.targets.removes) {-      if (target)-        target = remap(*target);+    if (ctx.commits.size() != ordered.size()) {+        error_prefix();+        std::cout << "git materialize failed (missing or corrupt object)\n";+        return 1;     }-  }-  for (auto &tag : updated.tags)-    tag.target = remap(tag.target);-  for (auto &ref : updated.remote_refs)-    ref.target = remap(ref.target);-  for (auto &workspace : updated.working_copies)-    workspace.target = remap(workspace.target);-  sort_ids(updated.heads); -  if (!ctx.changed) {+    View& updated = tx->view();+    auto remap = [&](const Id& id) -> Id {+        auto it = ctx.commits.find(id);+        return it == ctx.commits.end() ? id : it->second;+    };+    for (auto& head : updated.heads)+        head = remap(head);+    for (auto& bookmark : updated.bookmarks) {+        for (auto& target : bookmark.targets.adds) {+            if (target)+                target = remap(*target);+        }+        for (auto& target : bookmark.targets.removes) {+            if (target)+                target = remap(*target);+        }+    }+    for (auto& tag : updated.tags)+        tag.target = remap(tag.target);+    for (auto& ref : updated.remote_refs)+        ref.target = remap(ref.target);+    for (auto& workspace : updated.working_copies)+        workspace.target = remap(workspace.target);+    sort_ids(updated.heads);++    if (!ctx.changed) {+        info_prefix();+        std::cout << "already materialized\n";+        return 0;+    }+    auto status = tx->finish("git materialize");+    if (!status) {+        error_prefix();+        std::cout << "failed to write object pack\n";+        return 1;+    }+    for (const auto& raw : ctx.raw_saves)+        (void)git::save_raw(root, raw.first, Bytes(raw.second.data(), raw.second.size()));+    for (const auto& item : ctx.commits) {+        if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)+            continue;+        auto it = reverse_commits.find(item.first);+        if (it != reverse_commits.end())+            commits_map.put(it->second, item.second);+    }+    for (const auto& item : ctx.trees) {+        if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)+            continue;+        auto it = reverse_trees.find(item.first);+        if (it != reverse_trees.end())+            trees_map.put(it->second, item.second);+    }+    for (const auto& item : ctx.blobs) {+        if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)+            continue;+        if (auto oid = git::lazy_blob_oid(item.first))+            blobs_map.put(*oid, item.second);+    }+    if (!git::save_map(root, "commits", commits_map) || !git::save_map(root, "trees", trees_map) ||+        !git::save_map(root, "blobs", blobs_map)) {+        error_prefix();+        std::cout << "failed to write git mapping tables\n";+    }+    clear_stat_cache(root);     info_prefix();-    std::cout << "already materialized\n";+    std::cout << "materialized " << ctx.new_commits << " commits, " << ctx.new_trees << " trees, "+              << ctx.new_blobs << " blobs\n";     return 0;-  }-  auto status = tx->finish("git materialize");-  if (!status) {-    error_prefix();-    std::cout << "failed to write object pack\n";-    return 1;-  }-  for (const auto &raw : ctx.raw_saves)-    (void)git::save_raw(root, raw.first,-                        Bytes(raw.second.data(), raw.second.size()));-  for (const auto &item : ctx.commits) {-    if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)-      continue;-    auto it = reverse_commits.find(item.first);-    if (it != reverse_commits.end())-      commits_map.put(it->second, item.second);-  }-  for (const auto &item : ctx.trees) {-    if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)-      continue;-    auto it = reverse_trees.find(item.first);-    if (it != reverse_trees.end())-      trees_map.put(it->second, item.second);-  }-  for (const auto &item : ctx.blobs) {-    if (std::memcmp(item.first.data(), item.second.data(), ID_LEN) == 0)-      continue;-    if (auto oid = git::lazy_blob_oid(item.first))-      blobs_map.put(*oid, item.second);-  }-  if (!git::save_map(root, "commits", commits_map) ||-      !git::save_map(root, "trees", trees_map) ||-      !git::save_map(root, "blobs", blobs_map)) {-    error_prefix();-    std::cout << "failed to write git mapping tables\n";-  }-  clear_stat_cache(root);-  info_prefix();-  std::cout << "materialized " << ctx.new_commits << " commits, "-            << ctx.new_trees << " trees, " << ctx.new_blobs << " blobs\n";-  return 0; }--int git_export(const fs::path &root) {-  if (!git::ensure_mirror(root)) {-    error_prefix();-    std::cout << "cannot create git mirror\n";-    return 1;-  }-  IdMap commits;-  IdMap trees;-  IdMap blobs;-  (void)git::load_map(root, "commits", commits);-  (void)git::load_map(root, "trees", trees);-  (void)git::load_map(root, "blobs", blobs);-  const auto native = load_native(root);-  Store store = Store::open_all(root);-  auto view = current_view(root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  } -  std::vector<Id> roots;-  struct ResolvedBookmark {-    Bookmark bookmark;-  };-  std::vector<ResolvedBookmark> resolved_bookmarks;-  struct ResolvedTag {-    TagRef tag;-  };-  std::vector<ResolvedTag> resolved_tags;-  std::size_t skipped = 0;-  for (const auto &bookmark : view->bookmarks) {-    if (bookmark.targets.adds.empty() || !bookmark.targets.adds.front())-      continue;-    auto target = exportable_target(store, *bookmark.targets.adds.front());-    if (!target) {-      ++skipped;-      continue;+int git_export(const fs::path& root) {+    if (!git::ensure_mirror(root)) {+        error_prefix();+        std::cout << "cannot create git mirror\n";+        return 1;     }-    add_unique(roots, *target);-    Bookmark resolved;-    resolved.name = bookmark.name;-    resolved.targets.adds = {*target};-    resolved_bookmarks.push_back(ResolvedBookmark{std::move(resolved)});-  }-  for (const auto &tag : view->tags) {-    auto target = exportable_target(store, tag.target);-    if (!target) {-      ++skipped;-      continue;+    IdMap commits;+    IdMap trees;+    IdMap blobs;+    (void)git::load_map(root, "commits", commits);+    (void)git::load_map(root, "trees", trees);+    (void)git::load_map(root, "blobs", blobs);+    const auto native = load_native(root);+    Store store = Store::open_all(root);+    auto view = current_view(root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;     }-    add_unique(roots, *target);-    resolved_tags.push_back(ResolvedTag{TagRef{tag.name, *target}});-  } -  const auto ordered = ordered_commits(store, roots);-  std::size_t exported = 0;-  bool failed = false;-  for (const auto &id : ordered) {-    if (commits.reverse(id))-      continue;-    Oid oid{};-    if (!git::export_commit(root, store, commits, trees, blobs, native, id,-                            oid)) {-      failed = true;-      break;+    std::vector<Id> roots;+    struct ResolvedBookmark {+        Bookmark bookmark;+    };+    std::vector<ResolvedBookmark> resolved_bookmarks;+    struct ResolvedTag {+        TagRef tag;+    };+    std::vector<ResolvedTag> resolved_tags;+    std::size_t skipped = 0;+    for (const auto& bookmark : view->bookmarks) {+        if (bookmark.targets.adds.empty() || !bookmark.targets.adds.front())+            continue;+        auto target = exportable_target(store, *bookmark.targets.adds.front());+        if (!target) {+            ++skipped;+            continue;+        }+        add_unique(roots, *target);+        Bookmark resolved;+        resolved.name = bookmark.name;+        resolved.targets.adds = {*target};+        resolved_bookmarks.push_back(ResolvedBookmark{std::move(resolved)});     }-    ++exported;-  }-  int status = 0;-  if (failed) {-    error_prefix();-    std::cout << "git export failed\n";-    status = 1;-  } else {-    for (const auto &item : resolved_bookmarks) {-      if (item.bookmark.targets.adds.empty())-        continue;-      auto oid = commits.reverse(*item.bookmark.targets.adds.front());-      if (oid && !git::write_ref(git_dir(root),-                                 "refs/heads/" + item.bookmark.name, *oid))-        status = 1;+    for (const auto& tag : view->tags) {+        auto target = exportable_target(store, tag.target);+        if (!target) {+            ++skipped;+            continue;+        }+        add_unique(roots, *target);+        resolved_tags.push_back(ResolvedTag{TagRef{tag.name, *target}});     }-    for (const auto &item : resolved_tags) {-      auto oid = commits.reverse(item.tag.target);-      if (oid &&-          !git::write_ref(git_dir(root), "refs/tags/" + item.tag.name, *oid))-        status = 1;++    const auto ordered = ordered_commits(store, roots);+    std::size_t exported = 0;+    bool failed = false;+    for (const auto& id : ordered) {+        if (commits.reverse(id))+            continue;+        Oid oid{};+        if (!git::export_commit(root, store, commits, trees, blobs, native, id, oid)) {+            failed = true;+            break;+        }+        ++exported;     }-    if (skipped > 0) {-      warning_prefix();-      std::cout << "skipped " << skipped << " conflicted ref(s)\n";+    int status = 0;+    if (failed) {+        error_prefix();+        std::cout << "git export failed\n";+        status = 1;+    } else {+        for (const auto& item : resolved_bookmarks) {+            if (item.bookmark.targets.adds.empty())+                continue;+            auto oid = commits.reverse(*item.bookmark.targets.adds.front());+            if (oid && !git::write_ref(git_dir(root), "refs/heads/" + item.bookmark.name, *oid))+                status = 1;+        }+        for (const auto& item : resolved_tags) {+            auto oid = commits.reverse(item.tag.target);+            if (oid && !git::write_ref(git_dir(root), "refs/tags/" + item.tag.name, *oid))+                status = 1;+        }+        if (skipped > 0) {+            warning_prefix();+            std::cout << "skipped " << skipped << " conflicted ref(s)\n";+        }     }-  }-  if (status == 0) {-    if (!git::save_map(root, "commits", commits) ||-        !git::save_map(root, "trees", trees) ||-        !git::save_map(root, "blobs", blobs)) {-      error_prefix();-      std::cout << "failed to write git mapping tables\n";-      status = 1;+    if (status == 0) {+        if (!git::save_map(root, "commits", commits) || !git::save_map(root, "trees", trees) ||+            !git::save_map(root, "blobs", blobs)) {+            error_prefix();+            std::cout << "failed to write git mapping tables\n";+            status = 1;+        }     }-  }-  info_prefix();-  std::cout << "exported " << exported << " commits\n";-  return status;+    info_prefix();+    std::cout << "exported " << exported << " commits\n";+    return status; } -int git_fetch(const fs::path &root, std::string_view remote) {-  const auto url = repo_config_value(root, git::remote_key(remote, "url"));-  if (!url) {-    error_prefix();-    std::cout << "unknown remote: " << remote << "\n";-    return 1;-  }-  if (!configure_mirror(root, remote, *url)) {-    error_prefix();-    std::cout << "cannot configure git mirror\n";-    return 1;-  }-  if (run_git(git_dir(root), {"fetch", "--prune", std::string(remote)}) != 0) {-    error_prefix();-    std::cout << "git fetch failed\n";-    return 1;-  }-  return git_import(root);+int git_fetch(const fs::path& root, std::string_view remote) {+    const auto url = repo_config_value(root, git::remote_key(remote, "url"));+    if (!url) {+        error_prefix();+        std::cout << "unknown remote: " << remote << "\n";+        return 1;+    }+    if (!configure_mirror(root, remote, *url)) {+        error_prefix();+        std::cout << "cannot configure git mirror\n";+        return 1;+    }+    if (run_git(git_dir(root), {"fetch", "--prune", std::string(remote)}) != 0) {+        error_prefix();+        std::cout << "git fetch failed\n";+        return 1;+    }+    return git_import(root); } -int git_push(const fs::path &root, std::string_view remote,-             std::string_view bookmark) {-  const auto url = repo_config_value(root, git::remote_key(remote, "url"));-  if (!url) {-    error_prefix();-    std::cout << "unknown remote: " << remote << "\n";-    return 1;-  }-  if (!configure_mirror(root, remote, *url)) {-    error_prefix();-    std::cout << "cannot configure git mirror\n";-    return 1;-  }-  const int exported = git_export(root);-  if (exported != 0)-    return exported;-  const std::string refspec = "refs/heads/" + std::string(bookmark) +-                              ":refs/heads/" + std::string(bookmark);-  if (run_git(git_dir(root), {"push", std::string(remote), refspec}) != 0) {-    error_prefix();-    std::cout << "git push failed\n";-    return 1;-  }-  std::cout << "pushed " << bookmark << " to " << remote << "\n";-  return 0;+int git_push(const fs::path& root, std::string_view remote, std::string_view bookmark) {+    const auto url = repo_config_value(root, git::remote_key(remote, "url"));+    if (!url) {+        error_prefix();+        std::cout << "unknown remote: " << remote << "\n";+        return 1;+    }+    if (!configure_mirror(root, remote, *url)) {+        error_prefix();+        std::cout << "cannot configure git mirror\n";+        return 1;+    }+    const int exported = git_export(root);+    if (exported != 0)+        return exported;+    const std::string refspec =+        "refs/heads/" + std::string(bookmark) + ":refs/heads/" + std::string(bookmark);+    if (run_git(git_dir(root), {"push", std::string(remote), refspec}) != 0) {+        error_prefix();+        std::cout << "git push failed\n";+        return 1;+    }+    std::cout << "pushed " << bookmark << " to " << remote << "\n";+    return 0; } -int git_prepare_mirror(const fs::path &root, std::string_view source) {-  return git::prepare_mirror(root, path_from_bytes(source));+int git_prepare_mirror(const fs::path& root, std::string_view source) {+    return git::prepare_mirror(root, path_from_bytes(source)); } -std::optional<std::vector<std::uint8_t>>-git_read_lazy_blob(const fs::path &root, const Id &id) {-  const auto oid = git::lazy_blob_oid(id);-  if (!oid)-    return std::nullopt;-  auto repo = git::cached_repo(git_dir(root));-  if (!repo)-    return std::nullopt;-  auto object = git::read_object(*repo, *oid);-  if (!object || object->kind != git::KIND_BLOB)-    return std::nullopt;-  return std::move(object->body);+std::optional<std::vector<std::uint8_t>> git_read_lazy_blob(const fs::path& root, const Id& id) {+    const auto oid = git::lazy_blob_oid(id);+    if (!oid)+        return std::nullopt;+    auto repo = git::cached_repo(git_dir(root));+    if (!repo)+        return std::nullopt;+    auto object = git::read_object(*repo, *oid);+    if (!object || object->kind != git::KIND_BLOB)+        return std::nullopt;+    return std::move(object->body); }  namespace { -int git_import_cli(const std::vector<std::string> &args) {-  std::string repo_path = ".";-  std::optional<std::string> source;-  for (std::size_t i = 3; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (arg.starts_with("-source:")) {-      if (arg.size() == 8) {+int git_import_cli(const std::vector<std::string>& args) {+    std::string repo_path = ".";+    std::optional<std::string> source;+    for (std::size_t i = 3; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (arg.starts_with("-source:")) {+            if (arg.size() == 8) {+                error_prefix();+                std::cout << "-source: requires a path\n";+                return 1;+            }+            source = arg.substr(8);+        } else if (!arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            repo_path = arg;+        }+    }+    const auto root = discover_repo(path_from_bytes(repo_path));+    if (!root) {         error_prefix();-        std::cout << "-source: requires a path\n";+        std::cout << "not a veins repository: " << repo_path << "\n";         return 1;-      }-      source = arg.substr(8);-    } else if (!arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      repo_path = arg;     }-  }-  const auto root = discover_repo(path_from_bytes(repo_path));-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository: " << repo_path << "\n";-    return 1;-  }-  if (source) {-    const int prepared = git_prepare_mirror(*root, *source);-    if (prepared != 0) {-      error_prefix();-      if (prepared == 2) {-        std::cout << "-source: " << *source-                  << " is not a git repository root (expected the directory "-                     "containing .git)\n";-      } else {-        std::cout << "cannot prepare git mirror from " << *source << " (code "-                  << prepared << ")\n";-      }-      return 1;+    if (source) {+        const int prepared = git_prepare_mirror(*root, *source);+        if (prepared != 0) {+            error_prefix();+            if (prepared == 2) {+                std::cout << "-source: " << *source+                          << " is not a git repository root (expected the directory "+                             "containing .git)\n";+            } else {+                std::cout << "cannot prepare git mirror from " << *source << " (code " << prepared+                          << ")\n";+            }+            return 1;+        }     }-  }-  return git_import(*root);+    return git_import(*root); } -int git_export_cli(const std::vector<std::string> &args) {-  std::string repo_path = ".";-  for (std::size_t i = 3; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;+int git_export_cli(const std::vector<std::string>& args) {+    std::string repo_path = ".";+    for (std::size_t i = 3; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        }+        repo_path = arg;     }-    repo_path = arg;-  }-  const auto root = discover_repo(path_from_bytes(repo_path));-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository: " << repo_path << "\n";-    return 1;-  }-  return git_export(*root);+    const auto root = discover_repo(path_from_bytes(repo_path));+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository: " << repo_path << "\n";+        return 1;+    }+    return git_export(*root); } -int git_materialize_cli(const std::vector<std::string> &args) {-  std::string repo_path = ".";-  for (std::size_t i = 3; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;+int git_materialize_cli(const std::vector<std::string>& args) {+    std::string repo_path = ".";+    for (std::size_t i = 3; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        }+        repo_path = arg;     }-    repo_path = arg;-  }-  const auto root = discover_repo(path_from_bytes(repo_path));-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository: " << repo_path << "\n";-    return 1;-  }-  return git_materialize(*root);+    const auto root = discover_repo(path_from_bytes(repo_path));+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository: " << repo_path << "\n";+        return 1;+    }+    return git_materialize(*root); } -int git_fetch_cli(const std::vector<std::string> &args) {-  std::string remote = "origin";-  std::string repo_path = ".";-  bool have_remote = false;-  for (std::size_t i = 3; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;+int git_fetch_cli(const std::vector<std::string>& args) {+    std::string remote = "origin";+    std::string repo_path = ".";+    bool have_remote = false;+    for (std::size_t i = 3; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        }+        if (!have_remote) {+            remote = arg;+            have_remote = true;+        } else {+            repo_path = arg;+        }     }-    if (!have_remote) {-      remote = arg;-      have_remote = true;-    } else {-      repo_path = arg;+    const auto root = discover_repo(path_from_bytes(repo_path));+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;     }-  }-  const auto root = discover_repo(path_from_bytes(repo_path));-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  return git_fetch(*root, remote);+    return git_fetch(*root, remote); } -int git_push_cli(const std::vector<std::string> &args) {-  std::string remote = "origin";-  std::optional<std::string> bookmark;-  std::string repo_path = ".";-  bool have_remote = false;-  for (std::size_t i = 3; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;+int git_push_cli(const std::vector<std::string>& args) {+    std::string remote = "origin";+    std::optional<std::string> bookmark;+    std::string repo_path = ".";+    bool have_remote = false;+    for (std::size_t i = 3; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        }+        if (!have_remote) {+            remote = arg;+            have_remote = true;+        } else if (!bookmark) {+            bookmark = arg;+        } else {+            repo_path = arg;+        }     }-    if (!have_remote) {-      remote = arg;-      have_remote = true;-    } else if (!bookmark) {-      bookmark = arg;-    } else {-      repo_path = arg;+    if (!bookmark) {+        error_prefix();+        std::cout << "git push requires a bookmark\n";+        return 1;     }-  }-  if (!bookmark) {-    error_prefix();-    std::cout << "git push requires a bookmark\n";-    return 1;-  }-  const auto root = discover_repo(path_from_bytes(repo_path));-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  return git_push(*root, remote, *bookmark);+    const auto root = discover_repo(path_from_bytes(repo_path));+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    return git_push(*root, remote, *bookmark); } -int git_remote_cli(const std::vector<std::string> &args) {-  if (args.size() < 4) {-    error_prefix();-    std::cout << "expected remote subcommand (add, list, remove)\n";-    return 1;-  }-  const std::string &sub = args[3];-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  if (sub == "add") {-    if (args.size() < 6) {-      error_prefix();-      std::cout << "remote add requires a name and URL\n";-      return 1;+int git_remote_cli(const std::vector<std::string>& args) {+    if (args.size() < 4) {+        error_prefix();+        std::cout << "expected remote subcommand (add, list, remove)\n";+        return 1;     }-    if (!repo_config_set(*root, git::remote_key(args[4], "url"), args[5])) {-      error_prefix();-      std::cout << "cannot write repository config\n";-      return 1;+    const std::string& sub = args[3];+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;     }-    return 0;-  }-  if (sub == "list" || sub == "ls") {-    for (const auto &name : git::list_remotes(*root)) {-      const auto url = repo_config_value(*root, git::remote_key(name, "url"));-      std::cout << name << '\t' << (url ? *url : std::string()) << '\n';+    if (sub == "add") {+        if (args.size() < 6) {+            error_prefix();+            std::cout << "remote add requires a name and URL\n";+            return 1;+        }+        if (!repo_config_set(*root, git::remote_key(args[4], "url"), args[5])) {+            error_prefix();+            std::cout << "cannot write repository config\n";+            return 1;+        }+        return 0;     }-    return 0;-  }-  if (sub == "remove" || sub == "rm") {-    if (args.size() < 5) {-      error_prefix();-      std::cout << "remote remove requires a name\n";-      return 1;+    if (sub == "list" || sub == "ls") {+        for (const auto& name : git::list_remotes(*root)) {+            const auto url = repo_config_value(*root, git::remote_key(name, "url"));+            std::cout << name << '\t' << (url ? *url : std::string()) << '\n';+        }+        return 0;     }-    const std::string &name = args[4];-    (void)repo_config_remove(*root, git::remote_key(name, "url"));-    (void)repo_config_remove(*root, git::remote_key(name, "key"));-    (void)repo_config_remove(*root, git::remote_key(name, "tls-pin"));-    return 0;-  }-  error_prefix();-  std::cout << "unknown remote subcommand: " << sub << "\n";-  return 1;+    if (sub == "remove" || sub == "rm") {+        if (args.size() < 5) {+            error_prefix();+            std::cout << "remote remove requires a name\n";+            return 1;+        }+        const std::string& name = args[4];+        (void)repo_config_remove(*root, git::remote_key(name, "url"));+        (void)repo_config_remove(*root, git::remote_key(name, "key"));+        (void)repo_config_remove(*root, git::remote_key(name, "tls-pin"));+        return 0;+    }+    error_prefix();+    std::cout << "unknown remote subcommand: " << sub << "\n";+    return 1; }  } // namespace -int git_cli_run(const std::vector<std::string> &args) {-  if (args.size() < 3) {+int git_cli_run(const std::vector<std::string>& args) {+    if (args.size() < 3) {+        error_prefix();+        std::cout << "expected a git subcommand (import, export, materialize, "+                     "fetch, push, remote)\n";+        return 1;+    }+    const std::string& sub = args[2];+    if (sub == "import")+        return git_import_cli(args);+    if (sub == "export")+        return git_export_cli(args);+    if (sub == "materialize")+        return git_materialize_cli(args);+    if (sub == "fetch")+        return git_fetch_cli(args);+    if (sub == "push")+        return git_push_cli(args);+    if (sub == "remote")+        return git_remote_cli(args);     error_prefix();-    std::cout << "expected a git subcommand (import, export, materialize, "-                 "fetch, push, remote)\n";+    std::cout << "unknown git subcommand: " << sub << "\n";     return 1;-  }-  const std::string &sub = args[2];-  if (sub == "import")-    return git_import_cli(args);-  if (sub == "export")-    return git_export_cli(args);-  if (sub == "materialize")-    return git_materialize_cli(args);-  if (sub == "fetch")-    return git_fetch_cli(args);-  if (sub == "push")-    return git_push_cli(args);-  if (sub == "remote")-    return git_remote_cli(args);-  error_prefix();-  std::cout << "unknown git subcommand: " << sub << "\n";-  return 1; }  } // namespace vn--- a/xveins/src/git.h+++ b/xveins/src/git.h@@ -9,15 +9,13 @@  namespace vn { -int git_import(const fs::path &root);-int git_export(const fs::path &root);-int git_materialize(const fs::path &root);-int git_fetch(const fs::path &root, std::string_view remote);-int git_push(const fs::path &root, std::string_view remote,-             std::string_view bookmark);-int git_prepare_mirror(const fs::path &root, std::string_view source);-std::optional<std::vector<std::uint8_t>>-git_read_lazy_blob(const fs::path &root, const Id &id);-int git_cli_run(const std::vector<std::string> &args);+int git_import(const fs::path& root);+int git_export(const fs::path& root);+int git_materialize(const fs::path& root);+int git_fetch(const fs::path& root, std::string_view remote);+int git_push(const fs::path& root, std::string_view remote, std::string_view bookmark);+int git_prepare_mirror(const fs::path& root, std::string_view source);+std::optional<std::vector<std::uint8_t>> git_read_lazy_blob(const fs::path& root, const Id& id);+int git_cli_run(const std::vector<std::string>& args);  } // namespace vn--- a/xveins/src/git_internal.h+++ b/xveins/src/git_internal.h@@ -16,76 +16,75 @@ using Oid = std::array<std::uint8_t, 20>;  struct OidLess {-  bool operator()(const Oid &a, const Oid &b) const {-    return std::memcmp(a.data(), b.data(), a.size()) < 0;-  }+    bool operator()(const Oid& a, const Oid& b) const {+        return std::memcmp(a.data(), b.data(), a.size()) < 0;+    } };  enum Kind : std::uint8_t {-  KIND_NONE = 0,-  KIND_COMMIT = 1,-  KIND_TREE = 2,-  KIND_BLOB = 3,-  KIND_TAG = 4,-  KIND_OFS_DELTA = 6,-  KIND_REF_DELTA = 7,+    KIND_NONE = 0,+    KIND_COMMIT = 1,+    KIND_TREE = 2,+    KIND_BLOB = 3,+    KIND_TAG = 4,+    KIND_OFS_DELTA = 6,+    KIND_REF_DELTA = 7, };  struct Object {-  std::uint8_t kind = 0;-  std::vector<std::uint8_t> body;+    std::uint8_t kind = 0;+    std::vector<std::uint8_t> body; };  struct Pack {-  fs::path path;-  std::vector<std::uint8_t> data;-  std::vector<Oid> oids;-  std::vector<std::uint64_t> offsets;+    fs::path path;+    std::vector<std::uint8_t> data;+    std::vector<Oid> oids;+    std::vector<std::uint64_t> offsets; };  struct Repo {-  fs::path git_dir;-  std::vector<Pack> packs;+    fs::path git_dir;+    std::vector<Pack> packs; }; -std::string oid_hex(const Oid &oid);+std::string oid_hex(const Oid& oid); std::optional<Oid> oid_from_hex(std::string_view hex); std::optional<Oid> object_hash(std::uint8_t kind, Bytes body);-std::optional<Repo> open_repo(const fs::path &git_dir);-std::optional<Object> read_object(Repo &repo, const Oid &oid,-                                  bool verify = false);-std::shared_ptr<Repo> cached_repo(const fs::path &git_dir);+std::optional<Repo> open_repo(const fs::path& git_dir);+std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify = false);+std::shared_ptr<Repo> cached_repo(const fs::path& git_dir);  struct RawTreeEntry {-  std::string mode;-  std::string name;-  Oid oid{};+    std::string mode;+    std::string name;+    Oid oid{}; };  struct ParsedTree {-  std::vector<RawTreeEntry> entries;-  bool canonical = true;+    std::vector<RawTreeEntry> entries;+    bool canonical = true; };  struct ParsedTag {-  Oid target{};-  std::uint8_t target_kind = 0;+    Oid target{};+    std::uint8_t target_kind = 0; };  struct ParsedCommit {-  Oid tree{};-  std::vector<Oid> parents;-  Sig author;-  Sig committer;-  std::string message;-  std::vector<KeyValue> extras;-  std::optional<ChangeId> change_id;-  bool canonical = true;+    Oid tree{};+    std::vector<Oid> parents;+    Sig author;+    Sig committer;+    std::string message;+    std::vector<KeyValue> extras;+    std::optional<ChangeId> change_id;+    bool canonical = true; };  std::optional<Sig> parse_sig(std::string_view value); std::optional<ParsedCommit> parse_commit(Bytes body);-std::vector<std::uint8_t> serialize_commit(const ParsedCommit &commit);+std::vector<std::uint8_t> serialize_commit(const ParsedCommit& commit); std::optional<ParsedTree> parse_tree(Bytes body); std::string mode_for_kind(std::uint8_t kind); std::uint8_t mode_kind(std::string_view mode);@@ -92,54 +91,52 @@ std::optional<ParsedTag> parse_tag(Bytes body);  struct IdMap {-  std::map<Oid, Id, OidLess> items;+    std::map<Oid, Id, OidLess> items; -  std::optional<Id> get(const Oid &oid) const;-  void put(const Oid &oid, const Id &id);-  std::optional<Oid> reverse(const Id &id) const;+    std::optional<Id> get(const Oid& oid) const;+    void put(const Oid& oid, const Id& id);+    std::optional<Oid> reverse(const Id& id) const; }; -bool load_map(const fs::path &root, std::string_view name, IdMap &out);-bool save_map(const fs::path &root, std::string_view name, const IdMap &map);-bool save_raw(const fs::path &root, const Id &id, Bytes body);-std::optional<std::vector<std::uint8_t>> load_raw(const fs::path &root,-                                                  const Id &id);+bool load_map(const fs::path& root, std::string_view name, IdMap& out);+bool save_map(const fs::path& root, std::string_view name, const IdMap& map);+bool save_raw(const fs::path& root, const Id& id, Bytes body);+std::optional<std::vector<std::uint8_t>> load_raw(const fs::path& root, const Id& id);  struct Ref {-  std::string name;-  Oid oid{};+    std::string name;+    Oid oid{}; };  struct RefSet {-  std::vector<Ref> branches;-  std::vector<Ref> tags;-  std::vector<Ref> remotes;-  std::optional<Oid> head;+    std::vector<Ref> branches;+    std::vector<Ref> tags;+    std::vector<Ref> remotes;+    std::optional<Oid> head; }; -RefSet read_refs(const fs::path &git_dir);+RefSet read_refs(const fs::path& git_dir); -Id lazy_blob_id(const Oid &oid);-std::optional<Oid> lazy_blob_oid(const Id &id);+Id lazy_blob_id(const Oid& oid);+std::optional<Oid> lazy_blob_oid(const Id& id); -bool ensure_mirror(const fs::path &root);-int prepare_mirror(const fs::path &root, const fs::path &source);-bool write_loose(const fs::path &git_dir, std::uint8_t kind, const Oid &oid,-                 Bytes body);-bool write_ref(const fs::path &git_dir, std::string_view name, const Oid &oid);+bool ensure_mirror(const fs::path& root);+int prepare_mirror(const fs::path& root, const fs::path& source);+bool write_loose(const fs::path& git_dir, std::uint8_t kind, const Oid& oid, Bytes body);+bool write_ref(const fs::path& git_dir, std::string_view name, const Oid& oid);  std::string remote_key(std::string_view remote, std::string_view field);-std::vector<std::string> list_remotes(const fs::path &root);+std::vector<std::string> list_remotes(const fs::path& root); -std::optional<Id> import_tree(-    Writer &writer, Repo &repo, IdMap &trees, IdMap &blobs, const Oid &oid,-    std::vector<std::pair<Id, std::vector<std::uint8_t>>> &raw_saves,-    std::size_t &new_trees, std::size_t &new_blobs, std::size_t depth = 0);+std::optional<Id> import_tree(Writer& writer, Repo& repo, IdMap& trees, IdMap& blobs,+                              const Oid& oid,+                              std::vector<std::pair<Id, std::vector<std::uint8_t>>>& raw_saves,+                              std::size_t& new_trees, std::size_t& new_blobs,+                              std::size_t depth = 0); -bool export_tree(const fs::path &root, Store &store, IdMap &trees, IdMap &blobs,-                 const Id &id, Oid &out, std::size_t depth = 0);-bool export_commit(const fs::path &root, Store &store, IdMap &commits,-                   IdMap &trees, IdMap &blobs, const std::vector<Id> &native,-                   const Id &id, Oid &out, std::size_t depth = 0);+bool export_tree(const fs::path& root, Store& store, IdMap& trees, IdMap& blobs, const Id& id,+                 Oid& out, std::size_t depth = 0);+bool export_commit(const fs::path& root, Store& store, IdMap& commits, IdMap& trees, IdMap& blobs,+                   const std::vector<Id>& native, const Id& id, Oid& out, std::size_t depth = 0);  } // namespace vn::git--- a/xveins/src/git_object.cpp+++ b/xveins/src/git_object.cpp@@ -14,1128 +14,1096 @@ namespace {  std::uint32_t be32(Bytes data, std::size_t off) {-  return (static_cast<std::uint32_t>(data[off]) << 24) |-         (static_cast<std::uint32_t>(data[off + 1]) << 16) |-         (static_cast<std::uint32_t>(data[off + 2]) << 8) |-         static_cast<std::uint32_t>(data[off + 3]);+    return (static_cast<std::uint32_t>(data[off]) << 24) |+           (static_cast<std::uint32_t>(data[off + 1]) << 16) |+           (static_cast<std::uint32_t>(data[off + 2]) << 8) |+           static_cast<std::uint32_t>(data[off + 3]); }  std::uint64_t be64(Bytes data, std::size_t off) {-  return (static_cast<std::uint64_t>(be32(data, off)) << 32) |-         static_cast<std::uint64_t>(be32(data, off + 4));+    return (static_cast<std::uint64_t>(be32(data, off)) << 32) |+           static_cast<std::uint64_t>(be32(data, off + 4)); }  Oid sha1(Bytes data) {-  Oid out{};-  unsigned int len = 0;-  static const std::uint8_t empty = 0;-  const std::uint8_t *ptr = data.empty() ? &empty : data.data();-  EVP_Digest(ptr, data.size(), out.data(), &len, EVP_sha1(), nullptr);-  return out;+    Oid out{};+    unsigned int len = 0;+    static const std::uint8_t empty = 0;+    const std::uint8_t* ptr = data.empty() ? &empty : data.data();+    EVP_Digest(ptr, data.size(), out.data(), &len, EVP_sha1(), nullptr);+    return out; } -bool bytes_equal(const Oid &a, Bytes b) {-  return b.size() == a.size() && std::memcmp(a.data(), b.data(), a.size()) == 0;+bool bytes_equal(const Oid& a, Bytes b) {+    return b.size() == a.size() && std::memcmp(a.data(), b.data(), a.size()) == 0; }  std::string kind_name(std::uint8_t kind) {-  switch (kind) {-  case KIND_COMMIT:-    return "commit";-  case KIND_TREE:-    return "tree";-  case KIND_BLOB:-    return "blob";-  case KIND_TAG:-    return "tag";-  default:-    return "unknown";-  }+    switch (kind) {+    case KIND_COMMIT:+        return "commit";+    case KIND_TREE:+        return "tree";+    case KIND_BLOB:+        return "blob";+    case KIND_TAG:+        return "tag";+    default:+        return "unknown";+    } }  std::uint8_t kind_from_name(std::string_view name) {-  if (name == "commit")-    return KIND_COMMIT;-  if (name == "tree")-    return KIND_TREE;-  if (name == "blob")-    return KIND_BLOB;-  if (name == "tag")-    return KIND_TAG;-  return 0;+    if (name == "commit")+        return KIND_COMMIT;+    if (name == "tree")+        return KIND_TREE;+    if (name == "blob")+        return KIND_BLOB;+    if (name == "tag")+        return KIND_TAG;+    return 0; }  std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input); -std::optional<std::vector<std::uint8_t>> inflate_exact(Bytes input,-                                                       std::size_t expected) {-  if (expected == 0) {-    auto result = inflate_unknown(input);-    if (!result || !result->empty())-      return std::nullopt;-    return result;-  }-  std::vector<std::uint8_t> out(expected);-  uLongf dest_len = static_cast<uLongf>(expected);-  const int rc = uncompress(out.data(), &dest_len, input.data(),-                            static_cast<uLong>(input.size()));-  if (rc != Z_OK || dest_len != expected)-    return std::nullopt;-  out.resize(expected);-  return out;+std::optional<std::vector<std::uint8_t>> inflate_exact(Bytes input, std::size_t expected) {+    if (expected == 0) {+        auto result = inflate_unknown(input);+        if (!result || !result->empty())+            return std::nullopt;+        return result;+    }+    std::vector<std::uint8_t> out(expected);+    uLongf dest_len = static_cast<uLongf>(expected);+    const int rc =+        uncompress(out.data(), &dest_len, input.data(), static_cast<uLong>(input.size()));+    if (rc != Z_OK || dest_len != expected)+        return std::nullopt;+    out.resize(expected);+    return out; }  std::optional<std::vector<std::uint8_t>> inflate_unknown(Bytes input) {-  z_stream zs{};-  if (inflateInit(&zs) != Z_OK)-    return std::nullopt;-  std::vector<std::uint8_t> out(4096);-  zs.next_in = const_cast<Bytef *>(input.data());-  zs.avail_in = static_cast<uInt>(input.size());-  int rc = Z_OK;-  for (;;) {-    if (zs.total_out == out.size())-      out.resize(out.size() * 2);-    zs.next_out = out.data() + zs.total_out;-    zs.avail_out = static_cast<uInt>(out.size() - zs.total_out);-    rc = inflate(&zs, Z_NO_FLUSH);-    if (rc == Z_STREAM_END)-      break;-    if (rc != Z_OK) {-      inflateEnd(&zs);-      return std::nullopt;+    z_stream zs{};+    if (inflateInit(&zs) != Z_OK)+        return std::nullopt;+    std::vector<std::uint8_t> out(4096);+    zs.next_in = const_cast<Bytef*>(input.data());+    zs.avail_in = static_cast<uInt>(input.size());+    int rc = Z_OK;+    for (;;) {+        if (zs.total_out == out.size())+            out.resize(out.size() * 2);+        zs.next_out = out.data() + zs.total_out;+        zs.avail_out = static_cast<uInt>(out.size() - zs.total_out);+        rc = inflate(&zs, Z_NO_FLUSH);+        if (rc == Z_STREAM_END)+            break;+        if (rc != Z_OK) {+            inflateEnd(&zs);+            return std::nullopt;+        }     }-  }-  const std::size_t written = zs.total_out;-  inflateEnd(&zs);-  out.resize(written);-  return out;+    const std::size_t written = zs.total_out;+    inflateEnd(&zs);+    out.resize(written);+    return out; }  struct Varint {-  std::uint64_t value = 0;-  std::size_t next = 0;+    std::uint64_t value = 0;+    std::size_t next = 0; };  std::optional<Varint> read_be_varint(Bytes data, std::size_t start) {-  if (start >= data.size())-    return std::nullopt;-  const std::uint8_t c0 = data[start];-  std::uint64_t value = c0 & 0x0f;-  std::uint64_t shift = 4;-  std::size_t pos = start + 1;-  bool more = (c0 & 0x80) != 0;-  while (more) {-    if (pos >= data.size())-      return std::nullopt;-    const std::uint8_t c = data[pos++];-    value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);-    shift += 7;-    more = (c & 0x80) != 0;-  }-  return Varint{value, pos};+    if (start >= data.size())+        return std::nullopt;+    const std::uint8_t c0 = data[start];+    std::uint64_t value = c0 & 0x0f;+    std::uint64_t shift = 4;+    std::size_t pos = start + 1;+    bool more = (c0 & 0x80) != 0;+    while (more) {+        if (pos >= data.size())+            return std::nullopt;+        const std::uint8_t c = data[pos++];+        value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);+        shift += 7;+        more = (c & 0x80) != 0;+    }+    return Varint{value, pos}; }  std::optional<Varint> read_delta_varint(Bytes data, std::size_t start) {-  std::uint64_t value = 0;-  std::uint64_t shift = 0;-  std::size_t pos = start;-  for (;;) {-    if (pos >= data.size() || shift > 63)-      return std::nullopt;-    const std::uint8_t c = data[pos++];-    value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);-    shift += 7;-    if ((c & 0x80) == 0)-      return Varint{value, pos};-  }+    std::uint64_t value = 0;+    std::uint64_t shift = 0;+    std::size_t pos = start;+    for (;;) {+        if (pos >= data.size() || shift > 63)+            return std::nullopt;+        const std::uint8_t c = data[pos++];+        value |= (static_cast<std::uint64_t>(c & 0x7f) << shift);+        shift += 7;+        if ((c & 0x80) == 0)+            return Varint{value, pos};+    } }  std::optional<std::vector<std::uint8_t>> apply_delta(Bytes base, Bytes delta) {-  const auto src_size = read_delta_varint(delta, 0);-  if (!src_size || src_size->value != base.size())-    return std::nullopt;-  const auto dst_size = read_delta_varint(delta, src_size->next);-  if (!dst_size || dst_size->value > 2147483648ull)-    return std::nullopt;-  const std::size_t cap = static_cast<std::size_t>(dst_size->value);-  std::vector<std::uint8_t> out(cap);-  std::size_t written = 0;-  std::size_t pos = dst_size->next;-  while (pos < delta.size()) {-    const std::uint8_t op = delta[pos++];-    if ((op & 0x80) != 0) {-      std::uint64_t off = 0;-      std::uint64_t size = 0;-      for (int bit = 0; bit < 4; ++bit) {-        if ((op & (1u << bit)) != 0) {-          if (pos >= delta.size())-            return std::nullopt;-          off |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);-        }-      }-      for (int bit = 0; bit < 3; ++bit) {-        if ((op & (1u << (4 + bit))) != 0) {-          if (pos >= delta.size())-            return std::nullopt;-          size |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);-        }-      }-      if (size == 0)-        size = 65536;-      if (off > base.size() || size > base.size() - off)-        return std::nullopt;-      if (size > cap - written)-        return std::nullopt;-      if (size > 0)-        std::memcpy(out.data() + written, base.data() + off,-                    static_cast<std::size_t>(size));-      written += static_cast<std::size_t>(size);-    } else {-      if (op == 0)+    const auto src_size = read_delta_varint(delta, 0);+    if (!src_size || src_size->value != base.size())         return std::nullopt;-      const std::size_t n = op;-      if (pos + n > delta.size() || n > cap - written)+    const auto dst_size = read_delta_varint(delta, src_size->next);+    if (!dst_size || dst_size->value > 2147483648ull)         return std::nullopt;-      std::memcpy(out.data() + written, delta.data() + pos, n);-      pos += n;-      written += n;+    const std::size_t cap = static_cast<std::size_t>(dst_size->value);+    std::vector<std::uint8_t> out(cap);+    std::size_t written = 0;+    std::size_t pos = dst_size->next;+    while (pos < delta.size()) {+        const std::uint8_t op = delta[pos++];+        if ((op & 0x80) != 0) {+            std::uint64_t off = 0;+            std::uint64_t size = 0;+            for (int bit = 0; bit < 4; ++bit) {+                if ((op & (1u << bit)) != 0) {+                    if (pos >= delta.size())+                        return std::nullopt;+                    off |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);+                }+            }+            for (int bit = 0; bit < 3; ++bit) {+                if ((op & (1u << (4 + bit))) != 0) {+                    if (pos >= delta.size())+                        return std::nullopt;+                    size |= static_cast<std::uint64_t>(delta[pos++]) << (8 * bit);+                }+            }+            if (size == 0)+                size = 65536;+            if (off > base.size() || size > base.size() - off)+                return std::nullopt;+            if (size > cap - written)+                return std::nullopt;+            if (size > 0)+                std::memcpy(out.data() + written, base.data() + off,+                            static_cast<std::size_t>(size));+            written += static_cast<std::size_t>(size);+        } else {+            if (op == 0)+                return std::nullopt;+            const std::size_t n = op;+            if (pos + n > delta.size() || n > cap - written)+                return std::nullopt;+            std::memcpy(out.data() + written, delta.data() + pos, n);+            pos += n;+            written += n;+        }     }-  }-  if (written != cap)-    return std::nullopt;-  return out;+    if (written != cap)+        return std::nullopt;+    return out; } -std::optional<std::size_t> find_oid(const Pack &pack, const Oid &oid) {-  auto it =-      std::lower_bound(pack.oids.begin(), pack.oids.end(), oid, OidLess{});-  if (it == pack.oids.end() ||-      std::memcmp(it->data(), oid.data(), oid.size()) != 0)-    return std::nullopt;-  return static_cast<std::size_t>(it - pack.oids.begin());+std::optional<std::size_t> find_oid(const Pack& pack, const Oid& oid) {+    auto it = std::lower_bound(pack.oids.begin(), pack.oids.end(), oid, OidLess{});+    if (it == pack.oids.end() || std::memcmp(it->data(), oid.data(), oid.size()) != 0)+        return std::nullopt;+    return static_cast<std::size_t>(it - pack.oids.begin()); }--std::optional<Object> read_at(Repo &repo, Pack &pack, std::uint64_t start,-                              bool verify, std::size_t depth) {-  if (depth > 4096 || start >= pack.data.size())-    return std::nullopt;-  Bytes data(pack.data.data(), pack.data.size());-  const std::size_t begin = static_cast<std::size_t>(start);-  const std::uint8_t c0 = data[begin];-  const std::uint8_t kind = static_cast<std::uint8_t>((c0 >> 4) & 7);-  const auto header = read_be_varint(data, begin);-  if (!header || header->value > 2147483648ull)-    return std::nullopt;-  const std::size_t size = static_cast<std::size_t>(header->value);-  std::size_t pos = header->next; -  Oid base_oid{};-  bool has_base_oid = false;-  std::uint64_t base_off = 0;-  bool has_base_off = false;-  if (kind == KIND_OFS_DELTA) {-    if (pos >= data.size())-      return std::nullopt;-    std::uint8_t c = data[pos++];-    std::uint64_t acc = c & 0x7f;-    bool more = (c & 0x80) != 0;-    while (more) {-      if (pos >= data.size())+std::optional<Object> read_at(Repo& repo, Pack& pack, std::uint64_t start, bool verify,+                              std::size_t depth) {+    if (depth > 4096 || start >= pack.data.size())         return std::nullopt;-      c = data[pos++];-      acc = ((acc + 1) << 7) | (c & 0x7f);-      more = (c & 0x80) != 0;+    Bytes data(pack.data.data(), pack.data.size());+    const std::size_t begin = static_cast<std::size_t>(start);+    const std::uint8_t c0 = data[begin];+    const std::uint8_t kind = static_cast<std::uint8_t>((c0 >> 4) & 7);+    const auto header = read_be_varint(data, begin);+    if (!header || header->value > 2147483648ull)+        return std::nullopt;+    const std::size_t size = static_cast<std::size_t>(header->value);+    std::size_t pos = header->next;++    Oid base_oid{};+    bool has_base_oid = false;+    std::uint64_t base_off = 0;+    bool has_base_off = false;+    if (kind == KIND_OFS_DELTA) {+        if (pos >= data.size())+            return std::nullopt;+        std::uint8_t c = data[pos++];+        std::uint64_t acc = c & 0x7f;+        bool more = (c & 0x80) != 0;+        while (more) {+            if (pos >= data.size())+                return std::nullopt;+            c = data[pos++];+            acc = ((acc + 1) << 7) | (c & 0x7f);+            more = (c & 0x80) != 0;+        }+        has_base_off = true;+        base_off = start - acc;+    } else if (kind == KIND_REF_DELTA) {+        if (pos + 20 > data.size())+            return std::nullopt;+        std::memcpy(base_oid.data(), data.data() + pos, 20);+        has_base_oid = true;+        pos += 20;     }-    has_base_off = true;-    base_off = start - acc;-  } else if (kind == KIND_REF_DELTA) {-    if (pos + 20 > data.size())-      return std::nullopt;-    std::memcpy(base_oid.data(), data.data() + pos, 20);-    has_base_oid = true;-    pos += 20;-  } -  if (pos > data.size())-    return std::nullopt;-  auto inflated = inflate_exact(data.subspan(pos), size);-  if (!inflated)-    return std::nullopt;-  if (kind >= KIND_COMMIT && kind <= KIND_TAG)-    return Object{kind, std::move(*inflated)};-  if (kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA)-    return std::nullopt;+    if (pos > data.size())+        return std::nullopt;+    auto inflated = inflate_exact(data.subspan(pos), size);+    if (!inflated)+        return std::nullopt;+    if (kind >= KIND_COMMIT && kind <= KIND_TAG)+        return Object{kind, std::move(*inflated)};+    if (kind != KIND_OFS_DELTA && kind != KIND_REF_DELTA)+        return std::nullopt; -  std::optional<Object> base;-  if (has_base_off) {-    if (base_off >= start)-      return std::nullopt;-    base = read_at(repo, pack, base_off, verify, depth + 1);-  } else if (has_base_oid) {-    base = read_object(repo, base_oid, verify);-  }-  if (!base)-    return std::nullopt;-  auto merged = apply_delta(Bytes(base->body.data(), base->body.size()),-                            Bytes(inflated->data(), inflated->size()));-  if (!merged)-    return std::nullopt;-  return Object{base->kind, std::move(*merged)};+    std::optional<Object> base;+    if (has_base_off) {+        if (base_off >= start)+            return std::nullopt;+        base = read_at(repo, pack, base_off, verify, depth + 1);+    } else if (has_base_oid) {+        base = read_object(repo, base_oid, verify);+    }+    if (!base)+        return std::nullopt;+    auto merged = apply_delta(Bytes(base->body.data(), base->body.size()),+                              Bytes(inflated->data(), inflated->size()));+    if (!merged)+        return std::nullopt;+    return Object{base->kind, std::move(*merged)}; } -std::optional<Pack> parse_idx(Bytes data, std::size_t pack_count,-                              Bytes pack_trailer) {-  if (data.size() < 40)-    return std::nullopt;-  const std::size_t trailer_off = data.size() - 20;-  const Oid check = sha1(data.first(trailer_off));-  if (!bytes_equal(check, data.subspan(trailer_off, 20)))-    return std::nullopt;-  if (pack_trailer.size() != 20 ||-      std::memcmp(data.data() + data.size() - 40, pack_trailer.data(), 20) != 0)-    return std::nullopt;+std::optional<Pack> parse_idx(Bytes data, std::size_t pack_count, Bytes pack_trailer) {+    if (data.size() < 40)+        return std::nullopt;+    const std::size_t trailer_off = data.size() - 20;+    const Oid check = sha1(data.first(trailer_off));+    if (!bytes_equal(check, data.subspan(trailer_off, 20)))+        return std::nullopt;+    if (pack_trailer.size() != 20 ||+        std::memcmp(data.data() + data.size() - 40, pack_trailer.data(), 20) != 0)+        return std::nullopt; -  const bool is_v2 = data.size() >= 4 && data[0] == 0xff && data[1] == 0x74 &&-                     data[2] == 0x4f && data[3] == 0x63;-  const std::size_t fanout_off = is_v2 ? 8 : 0;-  if (is_v2 && be32(data, 4) != 2)-    return std::nullopt;-  if (data.size() < fanout_off + 1024 + 40)-    return std::nullopt;-  const std::size_t n = be32(data, fanout_off + 255 * 4);-  if (n != pack_count)-    return std::nullopt;+    const bool is_v2 = data.size() >= 4 && data[0] == 0xff && data[1] == 0x74 && data[2] == 0x4f &&+                       data[3] == 0x63;+    const std::size_t fanout_off = is_v2 ? 8 : 0;+    if (is_v2 && be32(data, 4) != 2)+        return std::nullopt;+    if (data.size() < fanout_off + 1024 + 40)+        return std::nullopt;+    const std::size_t n = be32(data, fanout_off + 255 * 4);+    if (n != pack_count)+        return std::nullopt; -  Pack pack;-  pack.oids.resize(n);-  pack.offsets.resize(n);-  if (is_v2) {-    const std::size_t names_off = fanout_off + 1024;-    const std::size_t crcs_off = names_off + n * 20;-    const std::size_t offs_off = crcs_off + n * 4;-    const std::size_t large_off = offs_off + n * 4;-    if (large_off + 40 > data.size())-      return std::nullopt;-    const std::size_t large_bytes = data.size() - 40 - large_off;-    if (large_bytes % 8 != 0)-      return std::nullopt;-    for (std::size_t i = 0; i < n; ++i) {-      std::memcpy(pack.oids[i].data(), data.data() + names_off + i * 20, 20);-      const std::uint32_t raw_off = be32(data, offs_off + i * 4);-      std::uint64_t resolved = raw_off;-      if ((raw_off & 0x80000000u) != 0) {-        const std::size_t idx = raw_off & 0x7fffffffu;-        if (idx * 8 + 8 > large_bytes)-          return std::nullopt;-        resolved = be64(data, large_off + idx * 8);-      }-      pack.offsets[i] = resolved;-    }-  } else {-    const std::size_t records_off = 1024;-    if (records_off + n * 24 + 40 > data.size())-      return std::nullopt;-    for (std::size_t i = 0; i < n; ++i) {-      const std::size_t rec = records_off + i * 24;-      pack.offsets[i] = be32(data, rec);-      std::memcpy(pack.oids[i].data(), data.data() + rec + 4, 20);+    Pack pack;+    pack.oids.resize(n);+    pack.offsets.resize(n);+    if (is_v2) {+        const std::size_t names_off = fanout_off + 1024;+        const std::size_t crcs_off = names_off + n * 20;+        const std::size_t offs_off = crcs_off + n * 4;+        const std::size_t large_off = offs_off + n * 4;+        if (large_off + 40 > data.size())+            return std::nullopt;+        const std::size_t large_bytes = data.size() - 40 - large_off;+        if (large_bytes % 8 != 0)+            return std::nullopt;+        for (std::size_t i = 0; i < n; ++i) {+            std::memcpy(pack.oids[i].data(), data.data() + names_off + i * 20, 20);+            const std::uint32_t raw_off = be32(data, offs_off + i * 4);+            std::uint64_t resolved = raw_off;+            if ((raw_off & 0x80000000u) != 0) {+                const std::size_t idx = raw_off & 0x7fffffffu;+                if (idx * 8 + 8 > large_bytes)+                    return std::nullopt;+                resolved = be64(data, large_off + idx * 8);+            }+            pack.offsets[i] = resolved;+        }+    } else {+        const std::size_t records_off = 1024;+        if (records_off + n * 24 + 40 > data.size())+            return std::nullopt;+        for (std::size_t i = 0; i < n; ++i) {+            const std::size_t rec = records_off + i * 24;+            pack.offsets[i] = be32(data, rec);+            std::memcpy(pack.oids[i].data(), data.data() + rec + 4, 20);+        }     }-  }-  return pack;+    return pack; } -std::optional<Pack> open_pack(const fs::path &pack_path,-                              const fs::path &idx_path) {-  auto pdata = read_file_opt(pack_path);-  if (!pdata || pdata->size() < 32)-    return std::nullopt;-  if (std::memcmp(pdata->data(), "PACK", 4) != 0)-    return std::nullopt;-  const std::uint32_t version = be32(bytes_of(*pdata), 4);-  if (version != 2 && version != 3)-    return std::nullopt;-  const std::size_t count = be32(bytes_of(*pdata), 8);-  const std::size_t trailer_off = pdata->size() - 20;-  const Oid pack_trailer = sha1(Bytes(pdata->data(), trailer_off));-  if (std::memcmp(pack_trailer.data(), pdata->data() + trailer_off, 20) != 0)-    return std::nullopt;+std::optional<Pack> open_pack(const fs::path& pack_path, const fs::path& idx_path) {+    auto pdata = read_file_opt(pack_path);+    if (!pdata || pdata->size() < 32)+        return std::nullopt;+    if (std::memcmp(pdata->data(), "PACK", 4) != 0)+        return std::nullopt;+    const std::uint32_t version = be32(bytes_of(*pdata), 4);+    if (version != 2 && version != 3)+        return std::nullopt;+    const std::size_t count = be32(bytes_of(*pdata), 8);+    const std::size_t trailer_off = pdata->size() - 20;+    const Oid pack_trailer = sha1(Bytes(pdata->data(), trailer_off));+    if (std::memcmp(pack_trailer.data(), pdata->data() + trailer_off, 20) != 0)+        return std::nullopt; -  auto idata = read_file_opt(idx_path);-  if (!idata)-    return std::nullopt;-  auto parsed = parse_idx(bytes_of(*idata), count,-                          Bytes(pdata->data() + trailer_off, 20));-  if (!parsed)-    return std::nullopt;-  parsed->path = pack_path;-  parsed->data = std::move(*pdata);-  return parsed;+    auto idata = read_file_opt(idx_path);+    if (!idata)+        return std::nullopt;+    auto parsed = parse_idx(bytes_of(*idata), count, Bytes(pdata->data() + trailer_off, 20));+    if (!parsed)+        return std::nullopt;+    parsed->path = pack_path;+    parsed->data = std::move(*pdata);+    return parsed; } -std::optional<Object> read_loose(const Repo &repo, const Oid &oid,-                                 bool verify) {-  const std::string hex = oid_hex(oid);-  const fs::path path = repo.git_dir / "objects" /-                        path_from_bytes(hex.substr(0, 2)) /-                        path_from_bytes(hex.substr(2));-  auto compressed = read_file_opt(path);-  if (!compressed)-    return std::nullopt;-  auto inflated = inflate_unknown(bytes_of(*compressed));-  if (!inflated)-    return std::nullopt;-  Bytes data(inflated->data(), inflated->size());-  const std::size_t space = static_cast<std::size_t>(-      std::find(data.begin(), data.end(), ' ') - data.begin());-  std::size_t nul = space;-  while (nul < data.size() && data[nul] != 0)-    ++nul;-  if (space == 0 || nul >= data.size())-    return std::nullopt;-  const std::uint8_t kind = kind_from_name(str_of(data.first(space)));-  if (kind == 0)-    return std::nullopt;-  std::uint64_t declared = 0;-  for (std::size_t i = space + 1; i < nul; ++i) {-    const std::uint8_t c = data[i];-    if (c < '0' || c > '9')-      return std::nullopt;-    declared = declared * 10 + (c - '0');-  }-  Bytes body = data.subspan(nul + 1);-  if (body.size() != declared)-    return std::nullopt;-  Object object{kind, std::vector<std::uint8_t>(body.begin(), body.end())};-  if (verify) {-    auto hash = object_hash(kind, body);-    if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)-      return std::nullopt;-  }-  return object;+std::optional<Object> read_loose(const Repo& repo, const Oid& oid, bool verify) {+    const std::string hex = oid_hex(oid);+    const fs::path path = repo.git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) /+                          path_from_bytes(hex.substr(2));+    auto compressed = read_file_opt(path);+    if (!compressed)+        return std::nullopt;+    auto inflated = inflate_unknown(bytes_of(*compressed));+    if (!inflated)+        return std::nullopt;+    Bytes data(inflated->data(), inflated->size());+    const std::size_t space =+        static_cast<std::size_t>(std::find(data.begin(), data.end(), ' ') - data.begin());+    std::size_t nul = space;+    while (nul < data.size() && data[nul] != 0)+        ++nul;+    if (space == 0 || nul >= data.size())+        return std::nullopt;+    const std::uint8_t kind = kind_from_name(str_of(data.first(space)));+    if (kind == 0)+        return std::nullopt;+    std::uint64_t declared = 0;+    for (std::size_t i = space + 1; i < nul; ++i) {+        const std::uint8_t c = data[i];+        if (c < '0' || c > '9')+            return std::nullopt;+        declared = declared * 10 + (c - '0');+    }+    Bytes body = data.subspan(nul + 1);+    if (body.size() != declared)+        return std::nullopt;+    Object object{kind, std::vector<std::uint8_t>(body.begin(), body.end())};+    if (verify) {+        auto hash = object_hash(kind, body);+        if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)+            return std::nullopt;+    }+    return object; }  std::string trim_line(std::string_view text) {-  while (!text.empty() && (text.back() == '\n' || text.back() == '\r'))-    text.remove_suffix(1);-  return std::string(text);+    while (!text.empty() && (text.back() == '\n' || text.back() == '\r'))+        text.remove_suffix(1);+    return std::string(text); } -void replace_ref(std::vector<Ref> &refs, std::string name, const Oid &oid) {-  for (auto &ref : refs) {-    if (ref.name == name) {-      ref.oid = oid;-      return;+void replace_ref(std::vector<Ref>& refs, std::string name, const Oid& oid) {+    for (auto& ref : refs) {+        if (ref.name == name) {+            ref.oid = oid;+            return;+        }     }-  }-  refs.push_back(Ref{std::move(name), oid});+    refs.push_back(Ref{std::move(name), oid}); } -std::optional<Oid> find_ref(const std::vector<Ref> &refs,-                            std::string_view name) {-  for (const auto &ref : refs) {-    if (ref.name == name)-      return ref.oid;-  }-  return std::nullopt;+std::optional<Oid> find_ref(const std::vector<Ref>& refs, std::string_view name) {+    for (const auto& ref : refs) {+        if (ref.name == name)+            return ref.oid;+    }+    return std::nullopt; } -void read_packed_refs(const fs::path &git_dir, std::vector<Ref> &branches,-                      std::vector<Ref> &tags) {-  auto data = read_file_opt(git_dir / "packed-refs");-  if (!data)-    return;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    std::string_view line = text.substr(start, end - start);-    if (!line.empty() && line.front() != '#' && line.front() != '^') {-      const std::size_t space = line.find(' ');-      if (space != std::string_view::npos && space != 0) {-        auto oid = oid_from_hex(line.substr(0, space));-        std::string_view name = line.substr(space + 1);-        if (oid) {-          if (name.starts_with("refs/heads/"))-            replace_ref(branches, std::string(name.substr(11)), *oid);-          else if (name.starts_with("refs/tags/"))-            replace_ref(tags, std::string(name.substr(10)), *oid);+void read_packed_refs(const fs::path& git_dir, std::vector<Ref>& branches, std::vector<Ref>& tags) {+    auto data = read_file_opt(git_dir / "packed-refs");+    if (!data)+        return;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        std::string_view line = text.substr(start, end - start);+        if (!line.empty() && line.front() != '#' && line.front() != '^') {+            const std::size_t space = line.find(' ');+            if (space != std::string_view::npos && space != 0) {+                auto oid = oid_from_hex(line.substr(0, space));+                std::string_view name = line.substr(space + 1);+                if (oid) {+                    if (name.starts_with("refs/heads/"))+                        replace_ref(branches, std::string(name.substr(11)), *oid);+                    else if (name.starts_with("refs/tags/"))+                        replace_ref(tags, std::string(name.substr(10)), *oid);+                }+            }         }-      }+        if (end == text.size())+            break;+        start = end + 1;     }-    if (end == text.size())-      break;-    start = end + 1;-  } } -void read_ref_dir(const fs::path &base, std::string_view rel,-                  std::vector<Ref> &refs) {-  const fs::path dir = rel.empty() ? base : base / path_from_bytes(rel);-  for (const auto &name : list_directory(dir)) {-    std::string child_rel(rel);-    if (!child_rel.empty())-      child_rel.push_back('/');-    child_rel += name;-    const fs::path child = base / path_from_bytes(child_rel);-    std::error_code ec;-    if (fs::is_directory(child, ec)) {-      read_ref_dir(base, child_rel, refs);-    } else {-      auto content = read_file_opt(child);-      if (!content)-        continue;-      const std::string line = trim_line(std::string_view(-          reinterpret_cast<const char *>(content->data()), content->size()));-      if (auto oid = oid_from_hex(line))-        replace_ref(refs, child_rel, *oid);+void read_ref_dir(const fs::path& base, std::string_view rel, std::vector<Ref>& refs) {+    const fs::path dir = rel.empty() ? base : base / path_from_bytes(rel);+    for (const auto& name : list_directory(dir)) {+        std::string child_rel(rel);+        if (!child_rel.empty())+            child_rel.push_back('/');+        child_rel += name;+        const fs::path child = base / path_from_bytes(child_rel);+        std::error_code ec;+        if (fs::is_directory(child, ec)) {+            read_ref_dir(base, child_rel, refs);+        } else {+            auto content = read_file_opt(child);+            if (!content)+                continue;+            const std::string line = trim_line(+                std::string_view(reinterpret_cast<const char*>(content->data()), content->size()));+            if (auto oid = oid_from_hex(line))+                replace_ref(refs, child_rel, *oid);+        }     }-  } } -std::optional<Oid> resolve_head(const fs::path &git_dir,-                                const std::vector<Ref> &branches,-                                const std::vector<Ref> &tags) {-  auto data = read_file_opt(git_dir / "HEAD");-  if (!data)-    return std::nullopt;-  const std::string line = trim_line(std::string_view(-      reinterpret_cast<const char *>(data->data()), data->size()));-  if (line.starts_with("ref: ")) {-    std::string_view name(line.data() + 5, line.size() - 5);-    if (name.starts_with("refs/heads/"))-      return find_ref(branches, name.substr(11));-    if (name.starts_with("refs/tags/"))-      return find_ref(tags, name.substr(10));-    return std::nullopt;-  }-  return oid_from_hex(line);+std::optional<Oid> resolve_head(const fs::path& git_dir, const std::vector<Ref>& branches,+                                const std::vector<Ref>& tags) {+    auto data = read_file_opt(git_dir / "HEAD");+    if (!data)+        return std::nullopt;+    const std::string line =+        trim_line(std::string_view(reinterpret_cast<const char*>(data->data()), data->size()));+    if (line.starts_with("ref: ")) {+        std::string_view name(line.data() + 5, line.size() - 5);+        if (name.starts_with("refs/heads/"))+            return find_ref(branches, name.substr(11));+        if (name.starts_with("refs/tags/"))+            return find_ref(tags, name.substr(10));+        return std::nullopt;+    }+    return oid_from_hex(line); } -std::optional<fs::path> resolve_source(const fs::path &source) {-  std::error_code ec;-  const fs::path dotgit = source / ".git";-  if (fs::is_directory(dotgit, ec))-    return dotgit;-  if (fs::is_regular_file(source / "HEAD", ec) &&-      fs::is_directory(source / "objects", ec))-    return source;-  return std::nullopt;+std::optional<fs::path> resolve_source(const fs::path& source) {+    std::error_code ec;+    const fs::path dotgit = source / ".git";+    if (fs::is_directory(dotgit, ec))+        return dotgit;+    if (fs::is_regular_file(source / "HEAD", ec) && fs::is_directory(source / "objects", ec))+        return source;+    return std::nullopt; } -bool copy_tree(const fs::path &src, const fs::path &dst) {-  std::error_code ec;-  fs::create_directories(dst, ec);-  if (ec)-    return false;-  for (const auto &name : list_directory(src)) {-    const fs::path s = src / path_from_bytes(name);-    const fs::path d = dst / path_from_bytes(name);-    if (fs::is_directory(s, ec)) {-      if (!copy_tree(s, d))+bool copy_tree(const fs::path& src, const fs::path& dst) {+    std::error_code ec;+    fs::create_directories(dst, ec);+    if (ec)         return false;-    } else if (fs::is_regular_file(s, ec)) {-      fs::create_hard_link(s, d, ec);-      if (ec) {-        ec.clear();-        fs::copy_file(s, d, fs::copy_options::overwrite_existing, ec);-        if (ec)-          return false;-      }+    for (const auto& name : list_directory(src)) {+        const fs::path s = src / path_from_bytes(name);+        const fs::path d = dst / path_from_bytes(name);+        if (fs::is_directory(s, ec)) {+            if (!copy_tree(s, d))+                return false;+        } else if (fs::is_regular_file(s, ec)) {+            fs::create_hard_link(s, d, ec);+            if (ec) {+                ec.clear();+                fs::copy_file(s, d, fs::copy_options::overwrite_existing, ec);+                if (ec)+                    return false;+            }+        }     }-  }-  return true;+    return true; }  } // namespace -std::string oid_hex(const Oid &oid) {-  return hex_encode(Bytes(oid.data(), oid.size()));+std::string oid_hex(const Oid& oid) {+    return hex_encode(Bytes(oid.data(), oid.size())); }  std::optional<Oid> oid_from_hex(std::string_view hex) {-  Oid out{};-  if (!hex_decode(hex, MutBytes(out.data(), out.size())))-    return std::nullopt;-  return out;+    Oid out{};+    if (!hex_decode(hex, MutBytes(out.data(), out.size())))+        return std::nullopt;+    return out; }  std::optional<Oid> object_hash(std::uint8_t kind, Bytes body) {-  const std::string name = kind_name(kind);-  if (name == "unknown")-    return std::nullopt;-  std::string header = name;-  header.push_back(' ');-  header += std::to_string(body.size());-  header.push_back('\0');-  std::vector<std::uint8_t> data;-  data.reserve(header.size() + body.size());-  data.insert(data.end(), header.begin(), header.end());-  data.insert(data.end(), body.begin(), body.end());-  return sha1(Bytes(data.data(), data.size()));+    const std::string name = kind_name(kind);+    if (name == "unknown")+        return std::nullopt;+    std::string header = name;+    header.push_back(' ');+    header += std::to_string(body.size());+    header.push_back('\0');+    std::vector<std::uint8_t> data;+    data.reserve(header.size() + body.size());+    data.insert(data.end(), header.begin(), header.end());+    data.insert(data.end(), body.begin(), body.end());+    return sha1(Bytes(data.data(), data.size())); } -std::optional<Repo> open_repo(const fs::path &git_dir) {-  Repo repo;-  repo.git_dir = git_dir;-  const fs::path pack_dir = git_dir / "objects" / "pack";-  std::error_code ec;-  if (fs::is_directory(pack_dir, ec)) {-    std::vector<std::string> names = list_directory(pack_dir);-    std::sort(names.begin(), names.end());-    for (const auto &name : names) {-      if (name.size() <= 4 || name.compare(name.size() - 4, 4, ".idx") != 0)-        continue;-      const std::string base = name.substr(0, name.size() - 4);-      const fs::path pack_path = pack_dir / path_from_bytes(base + ".pack");-      const fs::path idx_path = pack_dir / path_from_bytes(name);-      if (!path_is_file(pack_path))-        continue;-      auto pack = open_pack(pack_path, idx_path);-      if (!pack)-        return std::nullopt;-      repo.packs.push_back(std::move(*pack));+std::optional<Repo> open_repo(const fs::path& git_dir) {+    Repo repo;+    repo.git_dir = git_dir;+    const fs::path pack_dir = git_dir / "objects" / "pack";+    std::error_code ec;+    if (fs::is_directory(pack_dir, ec)) {+        std::vector<std::string> names = list_directory(pack_dir);+        std::sort(names.begin(), names.end());+        for (const auto& name : names) {+            if (name.size() <= 4 || name.compare(name.size() - 4, 4, ".idx") != 0)+                continue;+            const std::string base = name.substr(0, name.size() - 4);+            const fs::path pack_path = pack_dir / path_from_bytes(base + ".pack");+            const fs::path idx_path = pack_dir / path_from_bytes(name);+            if (!path_is_file(pack_path))+                continue;+            auto pack = open_pack(pack_path, idx_path);+            if (!pack)+                return std::nullopt;+            repo.packs.push_back(std::move(*pack));+        }     }-  }-  return repo;+    return repo; } -std::optional<Object> read_object(Repo &repo, const Oid &oid, bool verify) {-  for (auto &pack : repo.packs) {-    auto idx = find_oid(pack, oid);-    if (!idx)-      continue;-    auto object = read_at(repo, pack, pack.offsets[*idx], verify, 0);-    if (!object)-      return std::nullopt;-    if (verify) {-      auto hash = object_hash(object->kind,-                              Bytes(object->body.data(), object->body.size()));-      if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)-        return std::nullopt;+std::optional<Object> read_object(Repo& repo, const Oid& oid, bool verify) {+    for (auto& pack : repo.packs) {+        auto idx = find_oid(pack, oid);+        if (!idx)+            continue;+        auto object = read_at(repo, pack, pack.offsets[*idx], verify, 0);+        if (!object)+            return std::nullopt;+        if (verify) {+            auto hash = object_hash(object->kind, Bytes(object->body.data(), object->body.size()));+            if (!hash || std::memcmp(hash->data(), oid.data(), oid.size()) != 0)+                return std::nullopt;+        }+        return object;     }-    return object;-  }-  return read_loose(repo, oid, verify);+    return read_loose(repo, oid, verify); } -std::shared_ptr<Repo> cached_repo(const fs::path &git_dir) {-  static std::mutex mutex;-  static std::map<std::string,-                  std::pair<fs::file_time_type, std::shared_ptr<Repo>>>-      cache;-  std::error_code ec;-  const fs::path pack_dir = git_dir / "objects" / "pack";-  const fs::file_time_type stamp = fs::last_write_time(pack_dir, ec);-  const std::string key = path_to_bytes(git_dir);-  std::lock_guard<std::mutex> lock(mutex);-  auto it = cache.find(key);-  if (it != cache.end() && !ec && it->second.first == stamp)-    return it->second.second;-  auto repo = open_repo(git_dir);-  if (!repo)-    return nullptr;-  auto shared = std::make_shared<Repo>(std::move(*repo));-  cache[key] = {stamp, shared};-  return shared;+std::shared_ptr<Repo> cached_repo(const fs::path& git_dir) {+    static std::mutex mutex;+    static std::map<std::string, std::pair<fs::file_time_type, std::shared_ptr<Repo>>> cache;+    std::error_code ec;+    const fs::path pack_dir = git_dir / "objects" / "pack";+    const fs::file_time_type stamp = fs::last_write_time(pack_dir, ec);+    const std::string key = path_to_bytes(git_dir);+    std::lock_guard<std::mutex> lock(mutex);+    auto it = cache.find(key);+    if (it != cache.end() && !ec && it->second.first == stamp)+        return it->second.second;+    auto repo = open_repo(git_dir);+    if (!repo)+        return nullptr;+    auto shared = std::make_shared<Repo>(std::move(*repo));+    cache[key] = {stamp, shared};+    return shared; }  std::optional<Sig> parse_sig(std::string_view value) {-  const std::size_t tz_space = value.rfind(' ');-  if (tz_space == std::string_view::npos || tz_space == 0)-    return std::nullopt;-  const std::size_t sec_space = value.rfind(' ', tz_space - 1);-  if (sec_space == std::string_view::npos)-    return std::nullopt;-  const std::string_view sec_text =-      value.substr(sec_space + 1, tz_space - sec_space - 1);-  const std::string_view tz_text = value.substr(tz_space + 1);-  if (sec_text.empty() || tz_text.size() != 5 ||-      (tz_text[0] != '+' && tz_text[0] != '-'))-    return std::nullopt;-  std::int64_t seconds = 0;-  bool negative = false;-  std::size_t i = 0;-  if (sec_text[0] == '-') {-    negative = true;-    i = 1;-  }-  if (i >= sec_text.size())-    return std::nullopt;-  for (; i < sec_text.size(); ++i) {-    if (sec_text[i] < '0' || sec_text[i] > '9')-      return std::nullopt;-    seconds = seconds * 10 + (sec_text[i] - '0');-  }-  if (negative)-    seconds = -seconds;-  std::int64_t hh = 0;-  std::int64_t mm = 0;-  for (std::size_t j = 1; j < 3; ++j) {-    if (tz_text[j] < '0' || tz_text[j] > '9')-      return std::nullopt;-    hh = hh * 10 + (tz_text[j] - '0');-  }-  for (std::size_t j = 3; j < 5; ++j) {-    if (tz_text[j] < '0' || tz_text[j] > '9')-      return std::nullopt;-    mm = mm * 10 + (tz_text[j] - '0');-  }-  std::int64_t tz = hh * 60 + mm;-  if (tz_text[0] == '-')-    tz = -tz;-  if (tz > 32767 || tz < -32768)-    return std::nullopt;+    const std::size_t tz_space = value.rfind(' ');+    if (tz_space == std::string_view::npos || tz_space == 0)+        return std::nullopt;+    const std::size_t sec_space = value.rfind(' ', tz_space - 1);+    if (sec_space == std::string_view::npos)+        return std::nullopt;+    const std::string_view sec_text = value.substr(sec_space + 1, tz_space - sec_space - 1);+    const std::string_view tz_text = value.substr(tz_space + 1);+    if (sec_text.empty() || tz_text.size() != 5 || (tz_text[0] != '+' && tz_text[0] != '-'))+        return std::nullopt;+    std::int64_t seconds = 0;+    bool negative = false;+    std::size_t i = 0;+    if (sec_text[0] == '-') {+        negative = true;+        i = 1;+    }+    if (i >= sec_text.size())+        return std::nullopt;+    for (; i < sec_text.size(); ++i) {+        if (sec_text[i] < '0' || sec_text[i] > '9')+            return std::nullopt;+        seconds = seconds * 10 + (sec_text[i] - '0');+    }+    if (negative)+        seconds = -seconds;+    std::int64_t hh = 0;+    std::int64_t mm = 0;+    for (std::size_t j = 1; j < 3; ++j) {+        if (tz_text[j] < '0' || tz_text[j] > '9')+            return std::nullopt;+        hh = hh * 10 + (tz_text[j] - '0');+    }+    for (std::size_t j = 3; j < 5; ++j) {+        if (tz_text[j] < '0' || tz_text[j] > '9')+            return std::nullopt;+        mm = mm * 10 + (tz_text[j] - '0');+    }+    std::int64_t tz = hh * 60 + mm;+    if (tz_text[0] == '-')+        tz = -tz;+    if (tz > 32767 || tz < -32768)+        return std::nullopt; -  const std::string_view ident = value.substr(0, sec_space);-  const std::size_t lt = ident.rfind('<');-  const std::size_t gt = ident.rfind('>');-  if (lt == std::string_view::npos || gt == std::string_view::npos || gt <= lt)-    return std::nullopt;-  std::string_view name = ident.substr(0, lt);-  if (!name.empty() && name.back() == ' ')-    name.remove_suffix(1);-  Sig sig;-  sig.name = std::string(name);-  sig.email = std::string(ident.substr(lt + 1, gt - lt - 1));-  sig.seconds = seconds;-  sig.tz_min = static_cast<std::int16_t>(tz);-  return sig;+    const std::string_view ident = value.substr(0, sec_space);+    const std::size_t lt = ident.rfind('<');+    const std::size_t gt = ident.rfind('>');+    if (lt == std::string_view::npos || gt == std::string_view::npos || gt <= lt)+        return std::nullopt;+    std::string_view name = ident.substr(0, lt);+    if (!name.empty() && name.back() == ' ')+        name.remove_suffix(1);+    Sig sig;+    sig.name = std::string(name);+    sig.email = std::string(ident.substr(lt + 1, gt - lt - 1));+    sig.seconds = seconds;+    sig.tz_min = static_cast<std::int16_t>(tz);+    return sig; }  namespace { -void append_sig(std::vector<std::uint8_t> &out, const Sig &sig) {-  auto append = [&](std::string_view text) {-    out.insert(out.end(), text.begin(), text.end());-  };-  append(sig.name);-  append(" <");-  append(sig.email);-  append("> ");-  append(std::to_string(sig.seconds));-  out.push_back(' ');-  const std::int64_t minutes = sig.tz_min;-  const std::int64_t abs_min = minutes < 0 ? -minutes : minutes;-  out.push_back(minutes < 0 ? '-' : '+');-  const std::int64_t hh = abs_min / 60;-  const std::int64_t mm = abs_min % 60;-  out.push_back(static_cast<std::uint8_t>('0' + hh / 10));-  out.push_back(static_cast<std::uint8_t>('0' + hh % 10));-  out.push_back(static_cast<std::uint8_t>('0' + mm / 10));-  out.push_back(static_cast<std::uint8_t>('0' + mm % 10));+void append_sig(std::vector<std::uint8_t>& out, const Sig& sig) {+    auto append = [&](std::string_view text) { out.insert(out.end(), text.begin(), text.end()); };+    append(sig.name);+    append(" <");+    append(sig.email);+    append("> ");+    append(std::to_string(sig.seconds));+    out.push_back(' ');+    const std::int64_t minutes = sig.tz_min;+    const std::int64_t abs_min = minutes < 0 ? -minutes : minutes;+    out.push_back(minutes < 0 ? '-' : '+');+    const std::int64_t hh = abs_min / 60;+    const std::int64_t mm = abs_min % 60;+    out.push_back(static_cast<std::uint8_t>('0' + hh / 10));+    out.push_back(static_cast<std::uint8_t>('0' + hh % 10));+    out.push_back(static_cast<std::uint8_t>('0' + mm / 10));+    out.push_back(static_cast<std::uint8_t>('0' + mm % 10)); }  std::optional<ChangeId> parse_change_id(std::string_view text) {-  if (text.size() != 32)-    return std::nullopt;-  ChangeId id{};-  if (!hex_decode(text, MutBytes(id.data(), id.size())))-    return std::nullopt;-  return id;+    if (text.size() != 32)+        return std::nullopt;+    ChangeId id{};+    if (!hex_decode(text, MutBytes(id.data(), id.size())))+        return std::nullopt;+    return id; }  bool canonical_mode(std::string_view mode) {-  return mode == "100644" || mode == "100755" || mode == "120000" ||-         mode == "40000" || mode == "160000";+    return mode == "100644" || mode == "100755" || mode == "120000" || mode == "40000" ||+           mode == "160000"; }  } // namespace  std::optional<ParsedCommit> parse_commit(Bytes body) {-  const std::string_view text(reinterpret_cast<const char *>(body.data()),-                              body.size());-  const std::size_t blank = text.find("\n\n");-  if (blank == std::string_view::npos)-    return std::nullopt;-  ParsedCommit out;-  out.message = std::string(text.substr(blank + 2));-  const std::size_t header_end = blank;-  std::size_t pos = 0;-  int last_extra = -1;-  std::size_t last_extra_start = 0;-  while (pos < header_end) {-    std::size_t line_end = text.find('\n', pos);-    if (line_end == std::string_view::npos || line_end > header_end)-      line_end = header_end;-    const std::string_view line = text.substr(pos, line_end - pos);-    if (!line.empty() && line.front() == ' ') {-      if (last_extra < 0) {-        out.canonical = false;-      } else {-        out.extras[static_cast<std::size_t>(last_extra)].value = std::string(-            text.substr(last_extra_start, line_end - last_extra_start));-      }-    } else {-      last_extra = -1;-      const std::size_t space = line.find(' ');-      if (space == std::string_view::npos || space == 0) {-        out.canonical = false;-      } else {-        const std::string_view key = line.substr(0, space);-        const std::string_view value = line.substr(space + 1);-        if (key == "tree") {-          if (auto oid = oid_from_hex(value))-            out.tree = *oid;-          else-            out.canonical = false;-        } else if (key == "parent") {-          if (auto oid = oid_from_hex(value))-            out.parents.push_back(*oid);-          else-            out.canonical = false;-        } else if (key == "author") {-          if (auto sig = parse_sig(value))-            out.author = *sig;-          else-            out.canonical = false;-        } else if (key == "committer") {-          if (auto sig = parse_sig(value))-            out.committer = *sig;-          else-            out.canonical = false;-        } else if (key == "veins-change-id") {-          if (auto change = parse_change_id(value))-            out.change_id = *change;-          else-            out.canonical = false;+    const std::string_view text(reinterpret_cast<const char*>(body.data()), body.size());+    const std::size_t blank = text.find("\n\n");+    if (blank == std::string_view::npos)+        return std::nullopt;+    ParsedCommit out;+    out.message = std::string(text.substr(blank + 2));+    const std::size_t header_end = blank;+    std::size_t pos = 0;+    int last_extra = -1;+    std::size_t last_extra_start = 0;+    while (pos < header_end) {+        std::size_t line_end = text.find('\n', pos);+        if (line_end == std::string_view::npos || line_end > header_end)+            line_end = header_end;+        const std::string_view line = text.substr(pos, line_end - pos);+        if (!line.empty() && line.front() == ' ') {+            if (last_extra < 0) {+                out.canonical = false;+            } else {+                out.extras[static_cast<std::size_t>(last_extra)].value =+                    std::string(text.substr(last_extra_start, line_end - last_extra_start));+            }         } else {-          out.extras.push_back(KeyValue{std::string(key), std::string(value)});-          last_extra = static_cast<int>(out.extras.size() - 1);-          last_extra_start = pos + key.size() + 1;+            last_extra = -1;+            const std::size_t space = line.find(' ');+            if (space == std::string_view::npos || space == 0) {+                out.canonical = false;+            } else {+                const std::string_view key = line.substr(0, space);+                const std::string_view value = line.substr(space + 1);+                if (key == "tree") {+                    if (auto oid = oid_from_hex(value))+                        out.tree = *oid;+                    else+                        out.canonical = false;+                } else if (key == "parent") {+                    if (auto oid = oid_from_hex(value))+                        out.parents.push_back(*oid);+                    else+                        out.canonical = false;+                } else if (key == "author") {+                    if (auto sig = parse_sig(value))+                        out.author = *sig;+                    else+                        out.canonical = false;+                } else if (key == "committer") {+                    if (auto sig = parse_sig(value))+                        out.committer = *sig;+                    else+                        out.canonical = false;+                } else if (key == "veins-change-id") {+                    if (auto change = parse_change_id(value))+                        out.change_id = *change;+                    else+                        out.canonical = false;+                } else {+                    out.extras.push_back(KeyValue{std::string(key), std::string(value)});+                    last_extra = static_cast<int>(out.extras.size() - 1);+                    last_extra_start = pos + key.size() + 1;+                }+            }         }-      }+        pos = line_end + 1;     }-    pos = line_end + 1;-  }-  return out;+    return out; } -std::vector<std::uint8_t> serialize_commit(const ParsedCommit &commit) {-  std::vector<std::uint8_t> out;-  auto append = [&](std::string_view text) {-    out.insert(out.end(), text.begin(), text.end());-  };-  append("tree ");-  append(oid_hex(commit.tree));-  out.push_back('\n');-  for (const auto &parent : commit.parents) {-    append("parent ");-    append(oid_hex(parent));+std::vector<std::uint8_t> serialize_commit(const ParsedCommit& commit) {+    std::vector<std::uint8_t> out;+    auto append = [&](std::string_view text) { out.insert(out.end(), text.begin(), text.end()); };+    append("tree ");+    append(oid_hex(commit.tree));     out.push_back('\n');-  }-  append("author ");-  append_sig(out, commit.author);-  out.push_back('\n');-  append("committer ");-  append_sig(out, commit.committer);-  out.push_back('\n');-  for (const auto &kv : commit.extras) {-    append(kv.key);-    out.push_back(' ');-    append(kv.value);+    for (const auto& parent : commit.parents) {+        append("parent ");+        append(oid_hex(parent));+        out.push_back('\n');+    }+    append("author ");+    append_sig(out, commit.author);     out.push_back('\n');-  }-  out.push_back('\n');-  append(commit.message);-  return out;+    append("committer ");+    append_sig(out, commit.committer);+    out.push_back('\n');+    for (const auto& kv : commit.extras) {+        append(kv.key);+        out.push_back(' ');+        append(kv.value);+        out.push_back('\n');+    }+    out.push_back('\n');+    append(commit.message);+    return out; }  std::optional<ParsedTree> parse_tree(Bytes body) {-  ParsedTree out;-  std::size_t pos = 0;-  while (pos < body.size()) {-    const std::size_t mode_start = pos;-    while (pos < body.size() && body[pos] != ' ')-      ++pos;-    if (pos >= body.size()) {-      out.canonical = false;-      break;-    }-    const std::string mode(-        reinterpret_cast<const char *>(body.data() + mode_start),-        pos - mode_start);-    ++pos;-    const std::size_t name_start = pos;-    while (pos < body.size() && body[pos] != 0)-      ++pos;-    if (pos >= body.size()) {-      out.canonical = false;-      break;-    }-    const std::string name(-        reinterpret_cast<const char *>(body.data() + name_start),-        pos - name_start);-    ++pos;-    if (pos + 20 > body.size()) {-      out.canonical = false;-      break;+    ParsedTree out;+    std::size_t pos = 0;+    while (pos < body.size()) {+        const std::size_t mode_start = pos;+        while (pos < body.size() && body[pos] != ' ')+            ++pos;+        if (pos >= body.size()) {+            out.canonical = false;+            break;+        }+        const std::string mode(reinterpret_cast<const char*>(body.data() + mode_start),+                               pos - mode_start);+        ++pos;+        const std::size_t name_start = pos;+        while (pos < body.size() && body[pos] != 0)+            ++pos;+        if (pos >= body.size()) {+            out.canonical = false;+            break;+        }+        const std::string name(reinterpret_cast<const char*>(body.data() + name_start),+                               pos - name_start);+        ++pos;+        if (pos + 20 > body.size()) {+            out.canonical = false;+            break;+        }+        RawTreeEntry entry;+        entry.mode = mode;+        entry.name = name;+        std::memcpy(entry.oid.data(), body.data() + pos, 20);+        pos += 20;+        if (!canonical_mode(mode))+            out.canonical = false;+        out.entries.push_back(std::move(entry));     }-    RawTreeEntry entry;-    entry.mode = mode;-    entry.name = name;-    std::memcpy(entry.oid.data(), body.data() + pos, 20);-    pos += 20;-    if (!canonical_mode(mode))-      out.canonical = false;-    out.entries.push_back(std::move(entry));-  }-  if (pos != body.size())-    out.canonical = false;-  return out;+    if (pos != body.size())+        out.canonical = false;+    return out; }  std::string mode_for_kind(std::uint8_t kind) {-  if (kind == KIND_EXECUTABLE)-    return "100755";-  if (kind == KIND_SYMLINK)-    return "120000";-  if (kind == KIND_SUBTREE)-    return "40000";-  if (kind == KIND_SUBMODULE)-    return "160000";-  return "100644";+    if (kind == KIND_EXECUTABLE)+        return "100755";+    if (kind == KIND_SYMLINK)+        return "120000";+    if (kind == KIND_SUBTREE)+        return "40000";+    if (kind == KIND_SUBMODULE)+        return "160000";+    return "100644"; }  std::uint8_t mode_kind(std::string_view mode) {-  if (mode == "40000" || mode == "040000")-    return KIND_SUBTREE;-  if (mode == "120000")-    return KIND_SYMLINK;-  if (mode == "160000")-    return KIND_SUBMODULE;-  if (mode == "100755")-    return KIND_EXECUTABLE;-  return KIND_FILE;+    if (mode == "40000" || mode == "040000")+        return KIND_SUBTREE;+    if (mode == "120000")+        return KIND_SYMLINK;+    if (mode == "160000")+        return KIND_SUBMODULE;+    if (mode == "100755")+        return KIND_EXECUTABLE;+    return KIND_FILE; }  std::optional<ParsedTag> parse_tag(Bytes body) {-  ParsedTag out;-  const std::string_view text(reinterpret_cast<const char *>(body.data()),-                              body.size());-  std::size_t pos = 0;-  while (pos < text.size()) {-    std::size_t end = text.find('\n', pos);-    if (end == std::string_view::npos)-      end = text.size();-    const std::string_view line = text.substr(pos, end - pos);-    if (line.empty())-      break;-    const std::size_t space = line.find(' ');-    if (space != std::string_view::npos && space != 0) {-      const std::string_view key = line.substr(0, space);-      const std::string_view value = line.substr(space + 1);-      if (key == "object") {-        if (auto oid = oid_from_hex(value))-          out.target = *oid;-      } else if (key == "type") {-        out.target_kind = kind_from_name(value);-      }+    ParsedTag out;+    const std::string_view text(reinterpret_cast<const char*>(body.data()), body.size());+    std::size_t pos = 0;+    while (pos < text.size()) {+        std::size_t end = text.find('\n', pos);+        if (end == std::string_view::npos)+            end = text.size();+        const std::string_view line = text.substr(pos, end - pos);+        if (line.empty())+            break;+        const std::size_t space = line.find(' ');+        if (space != std::string_view::npos && space != 0) {+            const std::string_view key = line.substr(0, space);+            const std::string_view value = line.substr(space + 1);+            if (key == "object") {+                if (auto oid = oid_from_hex(value))+                    out.target = *oid;+            } else if (key == "type") {+                out.target_kind = kind_from_name(value);+            }+        }+        pos = end + 1;     }-    pos = end + 1;-  }-  return out;+    return out; } -std::optional<Id> IdMap::get(const Oid &oid) const {-  auto it = items.find(oid);-  if (it == items.end())-    return std::nullopt;-  return it->second;+std::optional<Id> IdMap::get(const Oid& oid) const {+    auto it = items.find(oid);+    if (it == items.end())+        return std::nullopt;+    return it->second; } -void IdMap::put(const Oid &oid, const Id &id) { items[oid] = id; }+void IdMap::put(const Oid& oid, const Id& id) {+    items[oid] = id;+} -std::optional<Oid> IdMap::reverse(const Id &id) const {-  for (const auto &item : items) {-    if (item.second == id)-      return item.first;-  }-  return std::nullopt;+std::optional<Oid> IdMap::reverse(const Id& id) const {+    for (const auto& item : items) {+        if (item.second == id)+            return item.first;+    }+    return std::nullopt; }  namespace { -fs::path map_path(const fs::path &root, std::string_view name) {-  return git_map_dir(root) / path_from_bytes(std::string(name) + ".map");+fs::path map_path(const fs::path& root, std::string_view name) {+    return git_map_dir(root) / path_from_bytes(std::string(name) + ".map"); }  } // namespace -bool load_map(const fs::path &root, std::string_view name, IdMap &out) {-  out.items.clear();-  auto data = read_file_opt(map_path(root, name));-  if (!data)+bool load_map(const fs::path& root, std::string_view name, IdMap& out) {+    out.items.clear();+    auto data = read_file_opt(map_path(root, name));+    if (!data)+        return true;+    if (data->size() < 9 || std::memcmp(data->data(), "VMAP1", 5) != 0)+        return false;+    const std::uint32_t count = static_cast<std::uint32_t>((*data)[5]) |+                                (static_cast<std::uint32_t>((*data)[6]) << 8) |+                                (static_cast<std::uint32_t>((*data)[7]) << 16) |+                                (static_cast<std::uint32_t>((*data)[8]) << 24);+    if (data->size() != 9 + static_cast<std::size_t>(count) * 52)+        return false;+    for (std::size_t i = 0; i < count; ++i) {+        const std::size_t off = 9 + i * 52;+        Oid oid{};+        std::memcpy(oid.data(), data->data() + off, 20);+        Id id{};+        std::memcpy(id.data(), data->data() + off + 20, 32);+        out.put(oid, id);+    }     return true;-  if (data->size() < 9 || std::memcmp(data->data(), "VMAP1", 5) != 0)-    return false;-  const std::uint32_t count = static_cast<std::uint32_t>((*data)[5]) |-                              (static_cast<std::uint32_t>((*data)[6]) << 8) |-                              (static_cast<std::uint32_t>((*data)[7]) << 16) |-                              (static_cast<std::uint32_t>((*data)[8]) << 24);-  if (data->size() != 9 + static_cast<std::size_t>(count) * 52)-    return false;-  for (std::size_t i = 0; i < count; ++i) {-    const std::size_t off = 9 + i * 52;-    Oid oid{};-    std::memcpy(oid.data(), data->data() + off, 20);-    Id id{};-    std::memcpy(id.data(), data->data() + off + 20, 32);-    out.put(oid, id);-  }-  return true; } -bool save_map(const fs::path &root, std::string_view name, const IdMap &map) {-  std::vector<std::uint8_t> data;-  data.insert(data.end(), {'V', 'M', 'A', 'P', '1'});-  const std::uint32_t count = static_cast<std::uint32_t>(map.items.size());-  data.push_back(static_cast<std::uint8_t>(count & 0xff));-  data.push_back(static_cast<std::uint8_t>((count >> 8) & 0xff));-  data.push_back(static_cast<std::uint8_t>((count >> 16) & 0xff));-  data.push_back(static_cast<std::uint8_t>((count >> 24) & 0xff));-  for (const auto &item : map.items) {-    data.insert(data.end(), item.first.begin(), item.first.end());-    data.insert(data.end(), item.second.begin(), item.second.end());-  }-  return write_atomic(map_path(root, name), Bytes(data.data(), data.size()));+bool save_map(const fs::path& root, std::string_view name, const IdMap& map) {+    std::vector<std::uint8_t> data;+    data.insert(data.end(), {'V', 'M', 'A', 'P', '1'});+    const std::uint32_t count = static_cast<std::uint32_t>(map.items.size());+    data.push_back(static_cast<std::uint8_t>(count & 0xff));+    data.push_back(static_cast<std::uint8_t>((count >> 8) & 0xff));+    data.push_back(static_cast<std::uint8_t>((count >> 16) & 0xff));+    data.push_back(static_cast<std::uint8_t>((count >> 24) & 0xff));+    for (const auto& item : map.items) {+        data.insert(data.end(), item.first.begin(), item.first.end());+        data.insert(data.end(), item.second.begin(), item.second.end());+    }+    return write_atomic(map_path(root, name), Bytes(data.data(), data.size())); } -bool save_raw(const fs::path &root, const Id &id, Bytes body) {-  const fs::path path =-      git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id));-  return write_atomic(path, body);+bool save_raw(const fs::path& root, const Id& id, Bytes body) {+    const fs::path path = git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id));+    return write_atomic(path, body); } -std::optional<std::vector<std::uint8_t>> load_raw(const fs::path &root,-                                                  const Id &id) {-  return read_file_opt(git_map_dir(root) / "raw" /-                       path_from_bytes(hex_encode(id)));+std::optional<std::vector<std::uint8_t>> load_raw(const fs::path& root, const Id& id) {+    return read_file_opt(git_map_dir(root) / "raw" / path_from_bytes(hex_encode(id))); } -RefSet read_refs(const fs::path &git_dir) {-  RefSet out;-  read_packed_refs(git_dir, out.branches, out.tags);-  read_ref_dir(git_dir / "refs" / "heads", "", out.branches);-  read_ref_dir(git_dir / "refs" / "tags", "", out.tags);-  read_ref_dir(git_dir / "refs" / "remotes", "", out.remotes);-  out.head = resolve_head(git_dir, out.branches, out.tags);-  return out;+RefSet read_refs(const fs::path& git_dir) {+    RefSet out;+    read_packed_refs(git_dir, out.branches, out.tags);+    read_ref_dir(git_dir / "refs" / "heads", "", out.branches);+    read_ref_dir(git_dir / "refs" / "tags", "", out.tags);+    read_ref_dir(git_dir / "refs" / "remotes", "", out.remotes);+    out.head = resolve_head(git_dir, out.branches, out.tags);+    return out; } -Id lazy_blob_id(const Oid &oid) {-  Id id{};-  std::memcpy(id.data(), "veins-gitoid", 12);-  std::memcpy(id.data() + 12, oid.data(), 20);-  return id;+Id lazy_blob_id(const Oid& oid) {+    Id id{};+    std::memcpy(id.data(), "veins-gitoid", 12);+    std::memcpy(id.data() + 12, oid.data(), 20);+    return id; } -std::optional<Oid> lazy_blob_oid(const Id &id) {-  if (!is_lazy_blob(id))-    return std::nullopt;-  Oid out{};-  std::memcpy(out.data(), id.data() + 12, 20);-  return out;+std::optional<Oid> lazy_blob_oid(const Id& id) {+    if (!is_lazy_blob(id))+        return std::nullopt;+    Oid out{};+    std::memcpy(out.data(), id.data() + 12, 20);+    return out; } -bool ensure_mirror(const fs::path &root) {-  const fs::path dir = git_dir(root);-  if (!ensure_directory(dir) || !ensure_directory(dir / "objects") ||-      !ensure_directory(dir / "refs" / "heads") ||-      !ensure_directory(dir / "refs" / "tags"))-    return false;-  if (!path_is_file(dir / "HEAD")) {-    const std::string body = "ref: refs/heads/main\n";-    if (!write_file(dir / "HEAD", bytes_of(body)))-      return false;-  }-  if (!path_is_file(dir / "config")) {-    const std::string body = "[core]\n\trepositoryformatversion = "-                             "0\n\tfilemode = true\n\tbare = true\n";-    if (!write_file(dir / "config", bytes_of(body)))-      return false;-  }-  return true;+bool ensure_mirror(const fs::path& root) {+    const fs::path dir = git_dir(root);+    if (!ensure_directory(dir) || !ensure_directory(dir / "objects") ||+        !ensure_directory(dir / "refs" / "heads") || !ensure_directory(dir / "refs" / "tags"))+        return false;+    if (!path_is_file(dir / "HEAD")) {+        const std::string body = "ref: refs/heads/main\n";+        if (!write_file(dir / "HEAD", bytes_of(body)))+            return false;+    }+    if (!path_is_file(dir / "config")) {+        const std::string body = "[core]\n\trepositoryformatversion = "+                                 "0\n\tfilemode = true\n\tbare = true\n";+        if (!write_file(dir / "config", bytes_of(body)))+            return false;+    }+    return true; } -int prepare_mirror(const fs::path &root, const fs::path &source) {-  const fs::path target = git_dir(root);-  if (path_is_file(target / "HEAD"))+int prepare_mirror(const fs::path& root, const fs::path& source) {+    const fs::path target = git_dir(root);+    if (path_is_file(target / "HEAD"))+        return 0;+    const auto resolved = resolve_source(source);+    if (!resolved)+        return 2;+    if (!copy_tree(*resolved, target))+        return 3;     return 0;-  const auto resolved = resolve_source(source);-  if (!resolved)-    return 2;-  if (!copy_tree(*resolved, target))-    return 3;-  return 0; } -bool write_loose(const fs::path &git_dir, std::uint8_t kind, const Oid &oid,-                 Bytes body) {-  const std::string hex = oid_hex(oid);-  const fs::path final_path = git_dir / "objects" /-                              path_from_bytes(hex.substr(0, 2)) /-                              path_from_bytes(hex.substr(2));-  if (path_is_file(final_path))-    return true;-  std::string header = kind_name(kind);-  header.push_back(' ');-  header += std::to_string(body.size());-  header.push_back('\0');-  uLongf bound = compressBound(static_cast<uLong>(header.size() + body.size()));-  std::vector<std::uint8_t> compressed(bound);-  uLongf dest_len = bound;-  std::vector<std::uint8_t> raw;-  raw.reserve(header.size() + body.size());-  raw.insert(raw.end(), header.begin(), header.end());-  raw.insert(raw.end(), body.begin(), body.end());-  const int rc = compress2(compressed.data(), &dest_len, raw.data(),-                           static_cast<uLong>(raw.size()), 6);-  if (rc != Z_OK)-    return false;-  compressed.resize(dest_len);-  return write_atomic(final_path, Bytes(compressed.data(), compressed.size()));+bool write_loose(const fs::path& git_dir, std::uint8_t kind, const Oid& oid, Bytes body) {+    const std::string hex = oid_hex(oid);+    const fs::path final_path =+        git_dir / "objects" / path_from_bytes(hex.substr(0, 2)) / path_from_bytes(hex.substr(2));+    if (path_is_file(final_path))+        return true;+    std::string header = kind_name(kind);+    header.push_back(' ');+    header += std::to_string(body.size());+    header.push_back('\0');+    uLongf bound = compressBound(static_cast<uLong>(header.size() + body.size()));+    std::vector<std::uint8_t> compressed(bound);+    uLongf dest_len = bound;+    std::vector<std::uint8_t> raw;+    raw.reserve(header.size() + body.size());+    raw.insert(raw.end(), header.begin(), header.end());+    raw.insert(raw.end(), body.begin(), body.end());+    const int rc =+        compress2(compressed.data(), &dest_len, raw.data(), static_cast<uLong>(raw.size()), 6);+    if (rc != Z_OK)+        return false;+    compressed.resize(dest_len);+    return write_atomic(final_path, Bytes(compressed.data(), compressed.size())); } -bool write_ref(const fs::path &git_dir, std::string_view name, const Oid &oid) {-  const std::string line = oid_hex(oid) + "\n";-  return write_atomic(git_dir / path_from_bytes(name), bytes_of(line));+bool write_ref(const fs::path& git_dir, std::string_view name, const Oid& oid) {+    const std::string line = oid_hex(oid) + "\n";+    return write_atomic(git_dir / path_from_bytes(name), bytes_of(line)); }  std::string remote_key(std::string_view remote, std::string_view field) {-  std::string out = "remote.";-  out += remote;-  out.push_back('.');-  out += field;-  return out;+    std::string out = "remote.";+    out += remote;+    out.push_back('.');+    out += field;+    return out; } -std::vector<std::string> list_remotes(const fs::path &root) {-  std::vector<std::string> out;-  auto data = read_file_opt(root / ".veins" / "config");-  if (!data)-    return out;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    const std::string_view line = text.substr(start, end - start);-    if (line.starts_with("remote.")) {-      const std::size_t dot = line.find(".url", 7);-      if (dot != std::string_view::npos && dot > 7)-        out.emplace_back(line.substr(7, dot - 7));+std::vector<std::string> list_remotes(const fs::path& root) {+    std::vector<std::string> out;+    auto data = read_file_opt(root / ".veins" / "config");+    if (!data)+        return out;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        const std::string_view line = text.substr(start, end - start);+        if (line.starts_with("remote.")) {+            const std::size_t dot = line.find(".url", 7);+            if (dot != std::string_view::npos && dot > 7)+                out.emplace_back(line.substr(7, dot - 7));+        }+        if (end == text.size())+            break;+        start = end + 1;     }-    if (end == text.size())-      break;-    start = end + 1;-  }-  return out;+    return out; }  } // namespace vn::git--- a/xveins/src/local_commands.h+++ b/xveins/src/local_commands.h@@ -7,13 +7,13 @@  // Local-only commands. Each receives the full argv-style vector and indexes // its own arguments (args[0] is the program, args[1] the command).-int bmk_run(const std::vector<std::string> &args);-int tag_run(const std::vector<std::string> &args);-int cfg_run(const std::vector<std::string> &args);-int rm_run(const std::vector<std::string> &args);-int mv_run(const std::vector<std::string> &args);-int ex_run(const std::vector<std::string> &args);-int op_run(const std::vector<std::string> &args);-int undo_run(const std::vector<std::string> &args);+int bmk_run(const std::vector<std::string>& args);+int tag_run(const std::vector<std::string>& args);+int cfg_run(const std::vector<std::string>& args);+int rm_run(const std::vector<std::string>& args);+int mv_run(const std::vector<std::string>& args);+int ex_run(const std::vector<std::string>& args);+int op_run(const std::vector<std::string>& args);+int undo_run(const std::vector<std::string>& args);  } // namespace vn--- a/xveins/src/main.cpp+++ b/xveins/src/main.cpp@@ -5,18 +5,18 @@ #include <string> #include <vector> -int main(int argc, char **argv) {-  std::vector<std::string> args;-  args.reserve(static_cast<std::size_t>(argc));-  for (int i = 0; i < argc; ++i)-    args.emplace_back(argv[i]);-  try {-    return vn::cli_run(args);-  } catch (const std::exception &e) {-    std::cout << "error: " << e.what() << "\n";-    return 1;-  } catch (...) {-    std::cout << "error: unexpected failure\n";-    return 1;-  }+int main(int argc, char** argv) {+    std::vector<std::string> args;+    args.reserve(static_cast<std::size_t>(argc));+    for (int i = 0; i < argc; ++i)+        args.emplace_back(argv[i]);+    try {+        return vn::cli_run(args);+    } catch (const std::exception& e) {+        std::cout << "error: " << e.what() << "\n";+        return 1;+    } catch (...) {+        std::cout << "error: unexpected failure\n";+        return 1;+    } }--- a/xveins/src/merge.cpp+++ b/xveins/src/merge.cpp@@ -18,2215 +18,2148 @@ // Object access that also sees pending transaction objects // --------------------------------------------------------------------------- -bool same_id(const Id &a, const Id &b) {-  return std::memcmp(a.data(), b.data(), ID_LEN) == 0;-}--std::optional<std::vector<std::uint8_t>>-read_body_any(Store &store, Txn *tx, std::uint8_t type, const Id &id) {-  if (tx) {-    if (auto cached = tx->writer().find_cached(type, id))-      return cached;-  }-  return store.read_body(id, type);-}--bool append_blob_any(Store &store, Txn *tx, const Id &id,-                     std::vector<std::uint8_t> &out, std::size_t depth) {-  if (depth > 64)-    return false;-  auto body = read_body_any(store, tx, TYPE_BLOB, id);-  if (!body)-    return false;-  auto blob = decode_blob(bytes_of(*body));-  if (!blob)-    return false;-  if (blob->form == BlobForm::Inline) {-    out.insert(out.end(), blob->data.begin(), blob->data.end());-    return true;-  }-  for (const auto &entry : blob->entries) {-    if (blob->form == BlobForm::Leaf) {-      auto chunk = read_body_any(store, tx, TYPE_CHUNK, entry.id);-      if (!chunk)-        return false;-      out.insert(out.end(), chunk->begin(), chunk->end());-    } else if (!append_blob_any(store, tx, entry.id, out, depth + 1)) {-      return false;-    }-  }-  return true;-}--std::optional<std::vector<std::uint8_t>> read_blob_any(Store &store, Txn *tx,-                                                       const Id &id) {-  std::vector<std::uint8_t> out;-  if (!append_blob_any(store, tx, id, out, 0))-    return std::nullopt;-  return out;-}--bool collect_chunks_any(Store &store, Txn *tx, const Id &id,-                        std::vector<Id> &out, std::size_t depth) {-  if (depth > 64)-    return false;-  auto body = read_body_any(store, tx, TYPE_BLOB, id);-  if (!body)-    return false;-  auto blob = decode_blob(bytes_of(*body));-  if (!blob)-    return false;-  if (blob->form == BlobForm::Leaf) {-    for (const auto &entry : blob->entries)-      out.push_back(entry.id);-    return true;-  }-  if (blob->form == BlobForm::Interior) {-    for (const auto &entry : blob->entries) {-      if (!collect_chunks_any(store, tx, entry.id, out, depth + 1))-        return false;-    }-  }-  return true;-}--bool flatten_any(Store &store, Txn *tx, const Id &tree_id, std::string &prefix,-                 std::vector<FlatEntry> &out, std::size_t depth) {-  if (depth > 4096)-    return false;-  auto body = read_body_any(store, tx, TYPE_TREE, tree_id);-  if (!body)-    return false;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return false;-  for (const auto &entry : tree->entries) {-    const std::size_t old_size = prefix.size();-    if (!prefix.empty())-      prefix.push_back('/');-    prefix.append(entry.name);-    if (entry.kind == KIND_SUBTREE) {-      if (!flatten_any(store, tx, entry.target, prefix, out, depth + 1)) {-        prefix.resize(old_size);-        return false;-      }-      prefix.resize(old_size);-    } else {-      out.push_back(FlatEntry{prefix, entry.kind, entry.target});-      prefix.resize(old_size);-    }-  }-  return true;-}--std::vector<FlatEntry> flatten_any_sorted(Store &store, Txn *tx,-                                          std::optional<Id> tree) {-  std::vector<FlatEntry> out;-  if (!tree)-    return out;-  std::string prefix;-  (void)flatten_any(store, tx, *tree, prefix, out, 0);-  std::stable_sort(out.begin(), out.end(),-                   [](const FlatEntry &a, const FlatEntry &b) {-                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                   });-  return out;-}--const FlatEntry *find_flat_entry(const std::vector<FlatEntry> &entries,-                                 std::string_view path) {-  for (const auto &entry : entries) {-    if (entry.path == path)-      return &entry;-  }-  return nullptr;-}--bool tree_empty_any(Store &store, Txn *tx, const Id &id) {-  auto body = read_body_any(store, tx, TYPE_TREE, id);-  if (!body)-    return true;-  auto tree = decode_tree(bytes_of(*body));-  return !tree || tree->entries.empty();-}--Id add_tree(Txn &tx, const std::vector<TreeEntry> &entries) {-  auto encoded = encode_tree(entries);-  if (!encoded)-    return Id{};-  return tx.add_object(TYPE_TREE, *encoded);-}--Id add_empty_tree(Txn &tx) { return add_tree(tx, {}); }--Id add_blob(Txn &tx, Bytes data) {-  BlobBuild build = build_blob(data);-  for (auto &object : build.objects) {-    const Id id =-        object.id ? *object.id : object_id(object.type, bytes_of(object.body));-    (void)tx.add_known(object.type, id, std::move(object.body));-  }-  return build.root;-}--// ----------------------------------------------------------------------------// Three-way line merge-// -----------------------------------------------------------------------------struct DiffOp {-  char tag = ' ';-  std::size_t ai = 0;-  std::size_t bi = 0;-};--std::vector<std::string> split_lines(Bytes data) {-  std::vector<std::string> out;-  std::size_t start = 0;-  for (std::size_t i = 0; i < data.size(); ++i) {-    if (data[i] == '\n') {-      out.emplace_back(reinterpret_cast<const char *>(data.data() + start),-                       i + 1 - start);-      start = i + 1;-    }-  }-  if (start < data.size())-    out.emplace_back(reinterpret_cast<const char *>(data.data() + start),-                     data.size() - start);-  return out;-}--std::vector<DiffOp> fallback_ops(const std::vector<std::string> &a,-                                 const std::vector<std::string> &b) {-  const std::size_t n = a.size();-  const std::size_t m = b.size();-  std::size_t prefix = 0;-  while (prefix < n && prefix < m && a[prefix] == b[prefix])-    ++prefix;-  std::size_t suffix = 0;-  while (suffix < n - prefix && suffix < m - prefix &&-         a[n - 1 - suffix] == b[m - 1 - suffix])-    ++suffix;-  std::vector<DiffOp> ops;-  for (std::size_t i = 0; i < prefix; ++i)-    ops.push_back(DiffOp{' ', i, i});-  for (std::size_t i = prefix; i < n - suffix; ++i)-    ops.push_back(DiffOp{'-', i, 0});-  for (std::size_t j = prefix; j < m - suffix; ++j)-    ops.push_back(DiffOp{'+', 0, j});-  for (std::size_t k = 0; k < suffix; ++k)-    ops.push_back(DiffOp{' ', n - suffix + k, m - suffix + k});-  return ops;-}--std::vector<DiffOp> build_ops(const std::vector<std::string> &a,-                              const std::vector<std::string> &b) {-  const std::size_t n = a.size();-  const std::size_t m = b.size();-  const std::uint64_t cells =-      static_cast<std::uint64_t>(n + 1) * static_cast<std::uint64_t>(m + 1);-  if (cells > 8000000)-    return fallback_ops(a, b);-  const std::size_t cols = m + 1;-  std::vector<std::uint32_t> dp(static_cast<std::size_t>(cells), 0);-  for (std::size_t i = 1; i <= n; ++i) {-    for (std::size_t j = 1; j <= m; ++j) {-      if (a[i - 1] == b[j - 1]) {-        dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;-      } else {-        dp[i * cols + j] =-            std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);-      }-    }-  }-  std::vector<DiffOp> ops;-  std::size_t oi = n;-  std::size_t oj = m;-  while (oi > 0 || oj > 0) {-    if (oi > 0 && oj > 0 && a[oi - 1] == b[oj - 1]) {-      ops.push_back(DiffOp{' ', oi - 1, oj - 1});-      --oi;-      --oj;-    } else if (oj > 0 && (oi == 0 || dp[oi * cols + (oj - 1)] >=-                                         dp[(oi - 1) * cols + oj])) {-      ops.push_back(DiffOp{'+', 0, oj - 1});-      --oj;-    } else {-      ops.push_back(DiffOp{'-', oi - 1, 0});-      --oi;-    }-  }-  std::reverse(ops.begin(), ops.end());-  return ops;-}--struct Hunk {-  std::size_t start = 0;-  std::size_t end = 0;-  std::vector<std::string> lines;-};--std::vector<Hunk> hunks_from_ops(const std::vector<std::string> &side,-                                 const std::vector<DiffOp> &ops) {-  std::vector<Hunk> out;-  std::size_t base_pos = 0;-  std::size_t i = 0;-  while (i < ops.size()) {-    if (ops[i].tag == ' ') {-      ++base_pos;-      ++i;-      continue;-    }-    Hunk hunk;-    hunk.start = base_pos;-    while (i < ops.size() && ops[i].tag != ' ') {-      if (ops[i].tag == '-') {-        ++base_pos;-      } else {-        hunk.lines.push_back(side[ops[i].bi]);-      }-      ++i;-    }-    hunk.end = base_pos;-    out.push_back(std::move(hunk));-  }-  return out;-}--std::vector<Hunk> diff_hunks(const std::vector<std::string> &base,-                             const std::vector<std::string> &side) {-  return hunks_from_ops(side, build_ops(base, side));-}--struct MergeRange {-  std::size_t base_start = 0;-  std::size_t base_end = 0;-  std::size_t ours_start = 0;-  std::size_t ours_end = 0;-  std::size_t theirs_start = 0;-  std::size_t theirs_end = 0;-};--struct EditResult {-  bool conflicted = false;-  std::vector<std::uint8_t> data;-  std::vector<MergeRange> ranges;-};--void append_lines(std::vector<std::uint8_t> &out,-                  const std::vector<std::string> &lines, std::size_t start,-                  std::size_t end) {-  for (std::size_t i = start; i < end && i < lines.size(); ++i)-    out.insert(out.end(), lines[i].begin(), lines[i].end());-}--void apply_hunks(std::vector<std::uint8_t> &out,-                 const std::vector<std::string> &base, std::size_t from,-                 std::size_t to, const std::vector<Hunk> &hunks,-                 std::size_t first, std::size_t last) {-  std::size_t pos = from;-  for (std::size_t k = first; k < last; ++k) {-    const Hunk &h = hunks[k];-    if (h.start > pos && h.start <= to)-      append_lines(out, base, pos, h.start);-    for (const auto &line : h.lines)-      out.insert(out.end(), line.begin(), line.end());-    if (h.end > pos)-      pos = h.end;-  }-  if (pos < to)-    append_lines(out, base, pos, to);-}--std::size_t map_pos(const std::vector<Hunk> &hunks, std::size_t pos) {-  std::ptrdiff_t out = static_cast<std::ptrdiff_t>(pos);-  for (const auto &h : hunks) {-    if (h.end <= pos) {-      const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(h.end - h.start);-      const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());-      out += fresh - old;-    } else if (h.start < pos) {-      const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(pos - h.start);-      const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());-      out += fresh - old;-      break;-    } else {-      break;-    }-  }-  return static_cast<std::size_t>(out);-}--bool same_hunks(const std::vector<Hunk> &ours, std::size_t of, std::size_t ol,-                const std::vector<Hunk> &theirs, std::size_t tf,-                std::size_t tl) {-  std::string a;-  std::string b;-  for (std::size_t k = of; k < ol; ++k)-    for (const auto &line : ours[k].lines)-      a += line;-  for (std::size_t j = tf; j < tl; ++j)-    for (const auto &line : theirs[j].lines)-      b += line;-  return a == b;-}--EditResult merge_lines(const std::vector<std::string> &base,-                       const std::vector<std::string> &ours,-                       const std::vector<std::string> &theirs,-                       bool adjacent_merge) {-  const auto ours_h = diff_hunks(base, ours);-  const auto theirs_h = diff_hunks(base, theirs);-  EditResult result;-  std::size_t oi = 0;-  std::size_t ti = 0;-  std::size_t pos = 0;-  while (oi < ours_h.size() || ti < theirs_h.size()) {-    const bool have_o = oi < ours_h.size();-    const bool have_t = ti < theirs_h.size();-    const std::size_t o_start = have_o ? ours_h[oi].start : 0;-    const std::size_t t_start = have_t ? theirs_h[ti].start : 0;-    const bool take_ours_cluster = have_o && (!have_t || o_start <= t_start);-    const std::size_t cluster_start = take_ours_cluster ? o_start : t_start;-    const std::size_t of = oi;-    const std::size_t tf = ti;-    std::size_t o_last = of;-    std::size_t t_last = tf;-    std::size_t end = cluster_start;-    bool seen_o = false;-    bool seen_t = false;-    for (;;) {-      bool progress = false;-      if (o_last < ours_h.size()) {-        const Hunk &h = ours_h[o_last];-        bool include = h.start <= end;-        if (o_last != of)-          include = adjacent_merge ? h.start < end : h.start <= end;-        if (include) {-          seen_o = true;-          ++o_last;-          if (h.end > end)-            end = h.end;-          progress = true;-        }-      }-      if (t_last < theirs_h.size()) {-        const Hunk &h = theirs_h[t_last];-        bool include = h.start <= end;-        if (t_last != tf)-          include = adjacent_merge ? h.start < end : h.start <= end;-        if (include) {-          seen_t = true;-          ++t_last;-          if (h.end > end)-            end = h.end;-          progress = true;-        }-      }-      if (!progress)-        break;-    }-    if (end < cluster_start)-      end = cluster_start;-    if (seen_o && !seen_t) {-      apply_hunks(result.data, base, pos, end, ours_h, of, o_last);-      pos = end;-      oi = o_last;-      ti = t_last;-    } else if (seen_t && !seen_o) {-      apply_hunks(result.data, base, pos, end, theirs_h, tf, t_last);-      pos = end;-      oi = o_last;-      ti = t_last;-    } else {-      if (same_hunks(ours_h, of, o_last, theirs_h, tf, t_last)) {-        apply_hunks(result.data, base, pos, end, ours_h, of, o_last);-        pos = end;-      } else {-        result.conflicted = true;-        apply_hunks(result.data, base, pos, end, ours_h, of, o_last);-        MergeRange range;-        range.base_start = cluster_start;-        range.base_end = end;-        range.ours_start = map_pos(ours_h, cluster_start);-        range.ours_end = map_pos(ours_h, end);-        range.theirs_start = map_pos(theirs_h, cluster_start);-        range.theirs_end = map_pos(theirs_h, end);-        result.ranges.push_back(range);-        pos = end;-      }-      oi = o_last;-      ti = t_last;-    }-  }-  if (pos < base.size())-    append_lines(result.data, base, pos, base.size());-  return result;-}--std::optional<EditResult> merge_blobs(Store &store, Txn *tx, const Id &base_id,-                                      const Id &ours_id, const Id &theirs_id,-                                      bool adjacent) {-  auto base = read_blob_any(store, tx, base_id);-  auto ours = read_blob_any(store, tx, ours_id);-  auto theirs = read_blob_any(store, tx, theirs_id);-  if (!base || !ours || !theirs)-    return std::nullopt;-  return merge_lines(split_lines(bytes_of(*base)), split_lines(bytes_of(*ours)),-                     split_lines(bytes_of(*theirs)), adjacent);-}--// ----------------------------------------------------------------------------// Rename detection-// -----------------------------------------------------------------------------struct RenamePair {-  std::string old_path;-  std::string new_path;-  std::size_t score = 0;-  bool old_used = false;-  bool new_used = false;-};--std::uint64_t hash_line(std::string_view line) {-  std::uint64_t h = 1469598103934665603ull;-  for (char raw : line) {-    const auto c = static_cast<unsigned char>(raw);-    h = (h ^ static_cast<std::uint64_t>(c)) * 1099511628211ull;-  }-  return h;-}--int line_similarity(Bytes a, Bytes b) {-  std::vector<std::uint64_t> la;-  std::vector<std::uint64_t> lb;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= a.size(); ++i) {-    if (i == a.size() || a[i] == '\n') {-      la.push_back(hash_line(str_of(a.subspan(start, i - start))));-      start = i + 1;-    }-  }-  start = 0;-  for (std::size_t j = 0; j <= b.size(); ++j) {-    if (j == b.size() || b[j] == '\n') {-      lb.push_back(hash_line(str_of(b.subspan(start, j - start))));-      start = j + 1;-    }-  }-  std::sort(la.begin(), la.end());-  std::sort(lb.begin(), lb.end());-  std::size_t ia = 0;-  std::size_t ib = 0;-  std::size_t inter = 0;-  while (ia < la.size() && ib < lb.size()) {-    if (la[ia] == lb[ib]) {-      ++inter;-      ++ia;-      ++ib;-    } else if (la[ia] < lb[ib]) {-      ++ia;-    } else {-      ++ib;-    }-  }-  const std::size_t total = la.size() + lb.size() - inter;-  if (total == 0)-    return 100;-  return static_cast<int>((inter * 100) / total);-}--int chunk_similarity(Store &store, Txn *tx, const Id &a, const Id &b) {-  std::vector<Id> ca;-  std::vector<Id> cb;-  if (!collect_chunks_any(store, tx, a, ca, 0) ||-      !collect_chunks_any(store, tx, b, cb, 0))-    return 0;-  std::size_t inter = 0;-  for (const auto &x : ca) {-    for (const auto &y : cb) {-      if (same_id(x, y)) {-        ++inter;-        break;-      }-    }-  }-  const std::size_t total = ca.size() + cb.size() - inter;-  if (total == 0)-    return 0;-  return static_cast<int>((inter * 100) / total);-}--int similarity(Store &store, Txn *tx, const Id &a, const Id &b) {-  if (same_id(a, b))-    return 100;-  auto da = read_blob_any(store, tx, a);-  auto db = read_blob_any(store, tx, b);-  if (!da || !db)-    return 0;-  int result = 0;-  if (da->size() >= 131072 && db->size() >= 131072)-    result = chunk_similarity(store, tx, a, b);-  if (result == 0)-    result = line_similarity(bytes_of(*da), bytes_of(*db));-  return result;-}--} // namespace--std::vector<Rename> detect_renames(Store &store, Txn *tx,-                                   std::optional<Id> old_tree,-                                   std::optional<Id> new_tree, int similar_pct,-                                   std::uint64_t parent_index) {-  const auto old_entries = flatten_any_sorted(store, tx, old_tree);-  const auto new_entries = flatten_any_sorted(store, tx, new_tree);-  std::vector<FlatEntry> deleted;-  std::vector<FlatEntry> added;-  for (const auto &entry : old_entries) {-    if (!find_flat_entry(new_entries, entry.path))-      deleted.push_back(entry);-  }-  for (const auto &entry : new_entries) {-    if (!find_flat_entry(old_entries, entry.path))-      added.push_back(entry);-  }-  std::vector<char> used_old(deleted.size(), 0);-  std::vector<char> used_new(added.size(), 0);-  std::vector<Rename> out;-  for (std::size_t di = 0; di < deleted.size(); ++di) {-    if (used_old[di])-      continue;-    for (std::size_t ai = 0; ai < added.size(); ++ai) {-      if (used_new[ai])-        continue;-      if (same_id(deleted[di].target, added[ai].target)) {-        out.push_back(-            Rename{parent_index, 0, deleted[di].path, added[ai].path});-        used_old[di] = 1;-        used_new[ai] = 1;-        break;-      }-    }-  }-  if (similar_pct > 0) {-    std::vector<RenamePair> pairs;-    constexpr std::size_t candidate_limit = 5000;-    for (std::size_t di = 0; di < deleted.size(); ++di) {-      if (used_old[di] || (deleted[di].kind != KIND_FILE &&-                           deleted[di].kind != KIND_EXECUTABLE))-        continue;-      for (std::size_t ai = 0;-           ai < added.size() && pairs.size() < candidate_limit; ++ai) {-        if (used_new[ai] ||-            (added[ai].kind != KIND_FILE && added[ai].kind != KIND_EXECUTABLE))-          continue;-        RenamePair pair;-        pair.old_path = deleted[di].path;-        pair.new_path = added[ai].path;-        pair.score = static_cast<std::size_t>(-            similarity(store, tx, deleted[di].target, added[ai].target));-        pairs.push_back(std::move(pair));-      }-    }-    for (;;) {-      std::ptrdiff_t best_i = -1;-      std::size_t best = 0;-      for (std::size_t i = 0; i < pairs.size(); ++i) {-        if (!pairs[i].old_used && !pairs[i].new_used && pairs[i].score > best) {-          best = pairs[i].score;-          best_i = static_cast<std::ptrdiff_t>(i);-        }-      }-      if (best_i < 0 || best < static_cast<std::size_t>(similar_pct))-        break;-      auto &pair = pairs[static_cast<std::size_t>(best_i)];-      pair.old_used = true;-      pair.new_used = true;-      out.push_back(Rename{parent_index, 0, pair.old_path, pair.new_path});-    }-  }-  std::stable_sort(-      out.begin(), out.end(), [](const Rename &a, const Rename &b) {-        if (a.parent_index != b.parent_index)-          return a.parent_index < b.parent_index;-        return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;-      });-  return out;-}--int rename_similar_pct(const fs::path &root) {-  if (auto value = repo_config_value(root, "rename.autodetect")) {-    if (*value == "off")-      return 0;-    return 60;-  }-  return 60;-}--namespace {--// ----------------------------------------------------------------------------// Rename maps-// -----------------------------------------------------------------------------using RenameMap = std::vector<std::pair<std::string, std::string>>;--std::optional<std::string> rename_lookup(const RenameMap &map,-                                         std::string_view path) {-  for (const auto &entry : map) {-    if (entry.first == path)-      return entry.second;-  }-  return std::nullopt;-}--void rename_apply(RenameMap &map, const std::string &from,-                  const std::string &to) {-  for (auto &entry : map) {-    if (entry.second == from) {-      entry.second = to;-      return;-    }-  }-  for (auto &entry : map) {-    if (entry.first == from) {-      entry.second = to;-      return;-    }-  }-  map.emplace_back(from, to);-}--std::optional<Id> tree_of(Store &store, const Id &commit_id) {-  auto loaded = load_commit(store, commit_id);-  if (!loaded)-    return std::nullopt;-  return loaded->commit.root_tree;-}--std::optional<Id> first_parent(Store &store, const Id &commit_id) {-  auto loaded = load_commit(store, commit_id);-  if (!loaded || loaded->commit.parents.empty())-    return std::nullopt;-  return loaded->commit.parents.front();-}--RenameMap map_from(Store &store, const Id &base, const Id &side) {-  RenameMap map;-  if (same_id(base, side))-    return map;-  std::vector<Id> chain;-  Id current = side;-  bool reached = false;-  for (std::size_t depth = 0; depth < 100000; ++depth) {-    if (same_id(current, base)) {-      reached = true;-      break;-    }-    chain.push_back(current);-    auto parent = first_parent(store, current);-    if (!parent)-      break;-    current = *parent;-  }-  if (!reached)-    return map;-  for (std::size_t i = chain.size(); i > 0; --i) {-    auto loaded = load_commit(store, chain[i - 1]);-    if (!loaded)-      continue;-    if (loaded->commit.renames_state == RENAMES_RECORDED) {-      for (const auto &rename : loaded->commit.renames) {-        if (rename.parent_index == 0)-          rename_apply(map, rename.from_path, rename.to_path);-      }-    } else {-      auto parent = first_parent(store, chain[i - 1]);-      if (!parent)-        continue;-      auto old_tree = tree_of(store, *parent);-      auto new_tree = tree_of(store, chain[i - 1]);-      for (const auto &rename :-           detect_renames(store, nullptr, old_tree, new_tree, 50, 0))-        rename_apply(map, rename.from_path, rename.to_path);-    }-  }-  return map;-}--// ----------------------------------------------------------------------------// Tree merge-// -----------------------------------------------------------------------------struct TreeTerm {-  bool positive = true;-  bool present = false;-  Id id{};-};--struct EntryTerm {-  bool positive = true;-  bool present = false;-  std::uint8_t kind = 0;-  std::optional<Id> target;-};--struct OrigEntry {-  std::size_t term = 0;-  std::string path;-  std::uint8_t kind = 0;-  Id target{};-};--struct OutEntry {-  std::string path;-  std::uint8_t kind = 0;-  Id target{};-};--struct MergeOutcome {-  Id tree{};-  std::size_t rerere = 0;-};--bool value_equal(const ConflictValue &a, const ConflictValue &b) {-  if (a.kind != b.kind)-    return false;-  if (a.kind == 0)-    return true;-  return a.target && b.target && same_id(*a.target, *b.target);-}--void flatten_values(Store &store, const std::vector<ConflictValue> &values,-                    bool positive, std::vector<ConflictValue> &adds,-                    std::vector<ConflictValue> &removes, std::size_t depth) {-  for (const auto &value : values) {-    if (value.kind == KIND_CONFLICT && value.target && depth < 64) {-      auto body = store.read_body(*value.target, TYPE_CONFLICT);-      if (body) {-        auto child = decode_conflict(bytes_of(*body));-        if (child) {-          flatten_values(store, child->adds, positive, adds, removes,-                         depth + 1);-          flatten_values(store, child->removes, !positive, adds, removes,-                         depth + 1);-          continue;-        }-      }-    }-    if (positive)-      adds.push_back(value);-    else-      removes.push_back(value);-  }-}--Conflict simplify(Store &store, const std::vector<ConflictValue> &adds_in,-                  const std::vector<ConflictValue> &removes_in) {-  std::vector<ConflictValue> flat_adds;-  std::vector<ConflictValue> flat_removes;-  flatten_values(store, adds_in, true, flat_adds, flat_removes, 0);-  flatten_values(store, removes_in, false, flat_adds, flat_removes, 0);--  std::vector<char> used(flat_adds.size(), 0);-  std::vector<char> rem_used(flat_removes.size(), 0);-  for (std::size_t r = 0; r < flat_removes.size(); ++r) {-    for (std::size_t a = 0; a < flat_adds.size(); ++a) {-      if (!used[a] && value_equal(flat_adds[a], flat_removes[r])) {-        used[a] = 1;-        rem_used[r] = 1;-        break;-      }-    }-  }-  Conflict out;-  for (std::size_t a = 0; a < flat_adds.size(); ++a) {-    if (!used[a])-      out.adds.push_back(flat_adds[a]);-  }-  for (std::size_t r = 0; r < flat_removes.size(); ++r) {-    if (!rem_used[r])-      out.removes.push_back(flat_removes[r]);-  }-  return out;-}--std::optional<ConflictValue> resolved(const Conflict &conflict) {-  if (conflict.adds.empty())-    return std::nullopt;-  for (std::size_t i = 1; i < conflict.adds.size(); ++i) {-    if (!value_equal(conflict.adds[0], conflict.adds[i]))-      return std::nullopt;-  }-  return conflict.adds[0];-}--bool all_files(const Conflict &conflict) {-  for (const auto &value : conflict.adds) {-    if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&-        value.kind != 0)-      return false;-  }-  for (const auto &value : conflict.removes) {-    if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE &&-        value.kind != 0)-      return false;-  }-  return true;-}--int merge_mode(const Conflict &conflict) {-  if (conflict.adds.size() != 2 || conflict.removes.size() != 1)-    return -1;-  auto mode = [](const ConflictValue &value) -> int {-    if (value.kind == 0)-      return -1;-    return value.kind == KIND_EXECUTABLE ? 1 : 0;-  };-  const int m0 = mode(conflict.adds[0]);-  const int m1 = mode(conflict.adds[1]);-  const int mr = mode(conflict.removes[0]);-  if (m0 < 0 || m1 < 0)-    return -1;-  if (m0 == m1)-    return m0;-  if (mr >= 0 && m0 == mr)-    return m1;-  if (mr >= 0 && m1 == mr)-    return m0;-  return -1;-}--bool merge_binary(const fs::path &repo, std::string_view path) {-  auto data = read_file_opt(repo / ".veinsattributes");-  if (!data)-    return false;-  const std::string_view text(reinterpret_cast<const char *>(data->data()),-                              data->size());-  bool result = false;-  std::size_t start = 0;-  for (std::size_t pos = 0; pos <= text.size(); ++pos) {-    if (pos != text.size() && text[pos] != '\n')-      continue;-    std::string_view line = text.substr(start, pos - start);-    start = pos + 1;-    while (!line.empty() && (line.front() == ' ' || line.front() == '\t' ||-                             line.front() == '\r' || line.front() == '\n'))-      line.remove_prefix(1);-    while (!line.empty() && (line.back() == ' ' || line.back() == '\t' ||-                             line.back() == '\r' || line.back() == '\n'))-      line.remove_suffix(1);-    if (line.empty() || line.front() == '#')-      continue;-    std::size_t glob_end = 0;-    while (glob_end < line.size() && line[glob_end] != ' ' &&-           line[glob_end] != '\t')-      ++glob_end;-    const std::string_view glob = line.substr(0, glob_end);-    std::string_view base = glob;-    if (const auto slash = glob.rfind('/'); slash != std::string_view::npos)-      base = glob.substr(slash + 1);-    const bool matched =-        glob_match(glob, path) ||-        (glob.find('/') == std::string_view::npos && glob_match(base, path));-    if (!matched)-      continue;-    std::size_t t = glob_end;-    while (t < line.size()) {-      while (t < line.size() && (line[t] == ' ' || line[t] == '\t'))-        ++t;-      const std::size_t tok_start = t;-      while (t < line.size() && line[t] != ' ' && line[t] != '\t')-        ++t;-      const std::string_view token = line.substr(tok_start, t - tok_start);-      const auto eq = token.find('=');-      if (eq != std::string_view::npos) {-        const std::string_view key = token.substr(0, eq);-        const std::string_view value = token.substr(eq + 1);-        if (key == "merge") {-          if (value == "binary")-            result = true;-          else if (value == "text")-            result = false;-        }-      }-    }-  }-  return result;-}--std::optional<Id> resolution_lookup(const fs::path &repo, Bytes body) {-  const auto digest = blake3_hash(body);-  const std::string key = hex_encode(Bytes(digest.data(), digest.size()));-  auto data = read_file_opt(resolutions_dir(repo) / key);-  if (!data || data->size() < 64)-    return std::nullopt;-  const std::string_view text(reinterpret_cast<const char *>(data->data()), 64);-  Id id{};-  if (!hex_decode(text, MutBytes(id.data(), id.size())))-    return std::nullopt;-  return id;-}--void resolution_record(const fs::path &repo, Bytes body, const Id &blob) {-  const auto digest = blake3_hash(body);-  const std::string key = hex_encode(Bytes(digest.data(), digest.size()));-  (void)write_file(resolutions_dir(repo) / key, bytes_of(hex_encode(blob)));-}--Id build_level(Txn &tx, const std::vector<OutEntry> &entries, std::size_t start,-               std::size_t end, std::size_t prefix_len) {-  std::vector<TreeEntry> out;-  std::size_t i = start;-  while (i < end) {-    const OutEntry &entry = entries[i];-    const std::size_t name_end = entry.path.find('/', prefix_len);-    const std::size_t cut =-        name_end == std::string::npos ? entry.path.size() : name_end;-    const std::string name = entry.path.substr(prefix_len, cut - prefix_len);-    if (cut == entry.path.size()) {-      out.push_back(TreeEntry{name, entry.kind, entry.target});-      ++i;-    } else {-      std::size_t j = i + 1;-      while (j < end) {-        const std::size_t other_end = entries[j].path.find('/', prefix_len);-        const std::size_t other_cut =-            other_end == std::string::npos ? entries[j].path.size() : other_end;-        if (other_cut != cut ||-            entries[j].path.compare(prefix_len, cut - prefix_len, name) != 0)-          break;-        ++j;-      }-      const Id child = build_level(tx, entries, i, j, cut + 1);-      out.push_back(TreeEntry{name, KIND_SUBTREE, child});-      i = j;-    }-  }-  return add_tree(tx, out);-}--Id build_from_entries(Txn &tx, std::vector<OutEntry> &entries) {-  if (entries.empty())-    return add_empty_tree(tx);-  std::stable_sort(entries.begin(), entries.end(),-                   [](const OutEntry &a, const OutEntry &b) {-                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                   });-  return build_level(tx, entries, 0, entries.size(), 0);-}--Id build_subtree(Txn &tx, const std::vector<OrigEntry> &canon, std::size_t term,-                 std::string_view prefix) {-  std::vector<OutEntry> rels;-  for (const auto &entry : canon) {-    if (entry.term != term)-      continue;-    if (entry.path.size() > prefix.size() &&-        entry.path.compare(0, prefix.size(), prefix) == 0 &&-        entry.path[prefix.size()] == '/')-      rels.push_back(OutEntry{entry.path.substr(prefix.size() + 1), entry.kind,-                              entry.target});-  }-  return build_from_entries(tx, rels);-}--bool has_prefix(std::string_view path, std::string_view prefix) {-  return path.size() > prefix.size() &&-         path.compare(0, prefix.size(), prefix) == 0 &&-         path[prefix.size()] == '/';-}--std::optional<OutEntry> merge_entry(const fs::path &repo, Txn &tx, Store &store,-                                    const std::string &path,-                                    const std::vector<EntryTerm> &terms,-                                    bool adjacent, std::size_t &rerere) {-  std::vector<ConflictValue> adds;-  std::vector<ConflictValue> removes;-  for (const auto &term : terms) {-    ConflictValue value;-    if (term.present) {-      value.kind = term.kind;-      value.target = term.target;-    }-    if (term.positive)-      adds.push_back(value);-    else-      removes.push_back(value);-  }-  Conflict sum = simplify(store, adds, removes);-  if (auto value = resolved(sum)) {-    if (value->kind == 0)-      return std::nullopt;-    return OutEntry{path, value->kind, *value->target};-  }-  if (all_files(sum) && sum.adds.size() == 2 && sum.removes.size() == 1 &&-      sum.adds[0].kind != 0 && sum.adds[1].kind != 0 &&-      sum.removes[0].kind != 0 && !merge_binary(repo, path)) {-    auto merged =-        merge_blobs(store, &tx, *sum.removes[0].target, *sum.adds[0].target,-                    *sum.adds[1].target, adjacent);-    if (merged && !merged->conflicted) {-      const Id blob = add_blob(tx, bytes_of(merged->data));-      const int mode = merge_mode(sum);-      if (mode >= 0)-        return OutEntry{-            path,-            static_cast<std::uint8_t>(mode == 1 ? KIND_EXECUTABLE : KIND_FILE),-            blob};-    }-  }-  const auto body = encode_conflict(sum);-  if (all_files(sum)) {-    if (auto memo = resolution_lookup(repo, bytes_of(body))) {-      ++rerere;-      return OutEntry{path, KIND_FILE, *memo};-    }-  }-  const Id id = tx.add_object(TYPE_CONFLICT, body);-  return OutEntry{path, KIND_CONFLICT, id};-}--MergeOutcome treemerge(const fs::path &repo, Txn &tx, Store &store,-                       const std::vector<TreeTerm> &terms,-                       const std::vector<RenameMap> &maps, bool adjacent) {-  std::vector<OrigEntry> orig;-  for (std::size_t t = 0; t < terms.size(); ++t) {-    if (!terms[t].present)-      continue;-    for (const auto &entry : flatten_any_sorted(store, &tx, terms[t].id))-      orig.push_back(OrigEntry{t, entry.path, entry.kind, entry.target});-  }--  auto canonical_targets = [&](const std::string &path)-      -> std::vector<std::pair<std::size_t, std::string>> {-    std::vector<std::pair<std::size_t, std::string>> out;-    for (std::size_t i = 0; i < maps.size(); ++i) {-      auto dest = rename_lookup(maps[i], path);-      if (!dest)-        continue;-      bool exists = false;-      for (const auto &item : out) {-        if (item.second == *dest) {-          exists = true;-          break;-        }-      }-      if (!exists)-        out.emplace_back(i, *dest);-    }-    return out;-  };--  auto find_orig = [&](std::size_t term,-                       const std::string &path) -> const OrigEntry * {-    for (const auto &entry : orig) {-      if (entry.term == term && entry.path == path)-        return &entry;-    }-    return nullptr;-  };--  std::vector<OrigEntry> canon;-  std::vector<std::string> special;-  std::vector<std::string> consumed;-  auto mark_consumed = [&](const std::string &path) {-    for (const auto &item : consumed) {-      if (item == path)-        return;-    }-    consumed.push_back(path);-  };-  for (const auto &entry : orig) {-    auto targets = canonical_targets(entry.path);-    if (targets.size() > 1) {-      bool seen = false;-      for (const auto &item : special) {-        if (item == entry.path) {-          seen = true;-          break;-        }-      }-      if (!seen)-        special.push_back(entry.path);-    }-    const std::string &canonical =-        targets.size() == 1 ? targets[0].second : entry.path;-    canon.push_back(OrigEntry{entry.term, canonical, entry.kind, entry.target});-  }--  std::vector<OutEntry> out;-  std::size_t rerere = 0;--  for (const auto &sp : special) {-    auto targets = canonical_targets(sp);-    std::vector<EntryTerm> ets;-    for (const auto &target : targets) {-      EntryTerm term;-      term.positive = true;-      if (const OrigEntry *found = find_orig(target.first, target.second)) {-        term.present = true;-        term.kind = found->kind;-        term.target = found->target;-      }-      ets.push_back(term);-      mark_consumed(target.second);-    }-    std::ptrdiff_t base_term = -1;-    for (std::size_t ti = 0; ti < terms.size(); ++ti) {-      if (!terms[ti].positive) {-        base_term = static_cast<std::ptrdiff_t>(ti);-        break;-      }-    }-    if (base_term >= 0) {-      EntryTerm term;-      term.positive = false;-      if (const OrigEntry *found =-              find_orig(static_cast<std::size_t>(base_term), sp)) {-        term.present = true;-        term.kind = found->kind;-        term.target = found->target;-      }-      ets.push_back(term);-    }-    if (auto merged = merge_entry(repo, tx, store, sp, ets, adjacent, rerere))-      out.push_back(std::move(*merged));-    mark_consumed(sp);-  }--  auto find_canon = [&](std::size_t term,-                        const std::string &path) -> const OrigEntry * {-    for (const auto &entry : canon) {-      if (entry.term == term && entry.path == path)-        return &entry;-    }-    return nullptr;-  };--  std::vector<std::string> paths;-  for (const auto &entry : canon) {-    bool seen = false;-    for (const auto &path : paths) {-      if (path == entry.path) {-        seen = true;-        break;-      }-    }-    if (!seen)-      paths.push_back(entry.path);-  }-  std::sort(paths.begin(), paths.end(),-            [](const std::string &a, const std::string &b) {-              return compare(bytes_of(a), bytes_of(b)) < 0;-            });--  auto is_consumed = [&](const std::string &path) {-    for (const auto &item : consumed) {-      if (item == path)-        return true;-    }-    return false;-  };--  for (const auto &path : paths) {-    if (is_consumed(path))-      continue;-    bool any_exact = false;-    bool any_children = false;-    for (std::size_t t = 0; t < terms.size(); ++t) {-      if (find_canon(t, path))-        any_exact = true;-      for (const auto &entry : canon) {-        if (entry.term == t && has_prefix(entry.path, path)) {-          any_children = true;-          break;-        }-      }-    }-    if (!any_exact)-      continue;-    const bool mixed = any_children;-    std::vector<EntryTerm> ets;-    for (std::size_t t = 0; t < terms.size(); ++t) {-      EntryTerm term;-      term.positive = terms[t].positive;-      if (const OrigEntry *exact = find_canon(t, path)) {-        term.present = true;-        term.kind = exact->kind;-        term.target = exact->target;-      } else if (mixed) {-        bool children = false;-        for (const auto &entry : canon) {-          if (entry.term == t && has_prefix(entry.path, path)) {-            children = true;-            break;-          }-        }-        if (children) {-          term.present = true;-          term.kind = KIND_SUBTREE;-          term.target = build_subtree(tx, canon, t, path);-        }-      }-      ets.push_back(term);-    }-    if (auto merged = merge_entry(repo, tx, store, path, ets, adjacent, rerere))-      out.push_back(std::move(*merged));-    if (mixed) {-      for (const auto &entry : canon) {-        if (has_prefix(entry.path, path))-          mark_consumed(entry.path);-      }-    }-  }--  return MergeOutcome{build_from_entries(tx, out), rerere};-}--// ----------------------------------------------------------------------------// Commit-level merge helpers-// -----------------------------------------------------------------------------bool contains_id_vec(const std::vector<Id> &ids, const Id &id) {-  for (const auto &candidate : ids) {-    if (same_id(candidate, id))-      return true;-  }-  return false;-}--std::vector<Id> merge_bases(Store &store, const Id &a, const Id &b) {-  const std::vector<Id> aa = collect_commits(store, std::vector<Id>{a});-  const std::vector<Id> bb = collect_commits(store, std::vector<Id>{b});-  std::vector<Id> common;-  for (const auto &x : aa) {-    if (contains_id_vec(bb, x))-      common.push_back(x);-  }-  std::vector<Id> out;-  for (const auto &c : common) {-    bool dominated = false;-    for (const auto &d : common) {-      if (same_id(c, d))-        continue;-      const auto descendants = collect_commits(store, std::vector<Id>{c});-      if (contains_id_vec(descendants, d)) {-        dominated = true;-        break;-      }-    }-    if (!dominated)-      out.push_back(c);-  }-  return out;-}--bool is_ancestor(Store &store, const Id &ancestor, const Id &descendant) {-  if (same_id(ancestor, descendant))-    return true;-  return contains_id_vec(collect_commits(store, std::vector<Id>{descendant}),-                         ancestor);-}--std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,-                            const std::vector<Id> &bases, bool adjacent);--std::optional<Id> base_tree(const fs::path &repo, Txn &tx, Store &store,-                            const std::vector<Id> &bases, bool adjacent) {-  if (bases.empty())-    return std::nullopt;-  if (bases.size() == 1)-    return tree_of(store, bases.front());-  auto t0 = tree_of(store, bases[0]);-  auto t1 = tree_of(store, bases[1]);-  const auto lcas = merge_bases(store, bases[0], bases[1]);-  std::vector<TreeTerm> terms;-  terms.push_back(TreeTerm{true, t0.has_value(), t0.value_or(Id{})});-  terms.push_back(TreeTerm{true, t1.has_value(), t1.value_or(Id{})});-  if (!lcas.empty()) {-    auto lt = tree_of(store, lcas.front());-    terms.push_back(TreeTerm{false, lt.has_value(), lt.value_or(Id{})});-  } else {-    terms.push_back(TreeTerm{false, false, Id{}});-  }-  std::vector<RenameMap> maps(3);-  return treemerge(repo, tx, store, terms, maps, adjacent).tree;-}--MergeOutcome merge_many(const fs::path &repo, Txn &tx, Store &store,-                        const std::vector<Id> &heads, bool adjacent) {-  if (heads.size() == 1) {-    auto t = tree_of(store, heads.front());-    std::vector<TreeTerm> terms{-        TreeTerm{true, t.has_value(), t.value_or(Id{})}};-    return treemerge(repo, tx, store, terms, {RenameMap{}}, adjacent);-  }-  std::vector<TreeTerm> terms;-  std::vector<RenameMap> maps;-  std::optional<Id> map_base;-  if (heads.size() > 1) {-    const auto bases = merge_bases(store, heads[0], heads[1]);-    if (!bases.empty())-      map_base = bases.front();-  }-  for (const auto &head : heads) {-    auto t = tree_of(store, head);-    terms.push_back(TreeTerm{true, t.has_value(), t.value_or(Id{})});-    if (map_base)-      maps.push_back(map_from(store, *map_base, head));-    else-      maps.push_back(RenameMap{});-  }-  for (std::size_t i = 1; i < heads.size(); ++i) {-    const auto bases = merge_bases(store, heads[0], heads[i]);-    auto bt = base_tree(repo, tx, store, bases, adjacent);-    if (bt)-      terms.push_back(TreeTerm{false, true, *bt});-    else-      terms.push_back(TreeTerm{false, false, Id{}});-    maps.push_back(RenameMap{});-  }-  return treemerge(repo, tx, store, terms, maps, adjacent);-}--MergeOutcome rewrite_tree(const fs::path &repo, Txn &tx, Store &store,-                          const Id &old_commit, const Id &commit_tree,-                          const std::vector<Id> &old_parents,-                          const std::vector<Id> &new_parents,-                          const std::vector<Id> &new_parent_trees,-                          bool adjacent) {-  std::vector<TreeTerm> terms;-  std::vector<RenameMap> maps;-  terms.push_back(TreeTerm{true, true, commit_tree});-  if (!old_parents.empty())-    maps.push_back(map_from(store, old_parents.front(), old_commit));-  else-    maps.push_back(RenameMap{});--  if (old_parents.empty()) {-    for (const auto &tree : new_parent_trees) {-      terms.push_back(TreeTerm{true, true, tree});-      maps.push_back(RenameMap{});-    }-    terms.push_back(TreeTerm{false, false, Id{}});-    maps.push_back(RenameMap{});-  } else {-    for (std::size_t i = 0; i < old_parents.size(); ++i) {-      auto old_tree = tree_of(store, old_parents[i]);-      const Id new_tree =-          i < new_parent_trees.size() ? new_parent_trees[i] : Id{};-      terms.push_back(TreeTerm{true, true, new_tree});-      terms.push_back(-          TreeTerm{false, old_tree.has_value(), old_tree.value_or(Id{})});-      if (i < new_parents.size())-        maps.push_back(map_from(store, old_parents[i], new_parents[i]));-      else-        maps.push_back(RenameMap{});-      maps.push_back(RenameMap{});-    }-  }-  return treemerge(repo, tx, store, terms, maps, adjacent);-}--Id make_commit(Txn &tx, Store &store, const fs::path &repo,-               const std::vector<Id> &parents, const Id &root,-               const ChangeId &change, const Sig &author,-               const std::string &message, std::uint8_t renames_state,-               const std::vector<KeyValue> &extra) {-  Commit commit;-  commit.version = 1;-  commit.parents = parents;-  commit.root_tree = root;-  commit.change_id = change;-  commit.author = author;-  commit.committer = identity_signature(repo);-  commit.message = message;-  commit.renames_state = renames_state;-  commit.extra = extra;-  if (renames_state == RENAMES_RECORDED) {-    for (std::size_t i = 0; i < parents.size(); ++i) {-      auto parent_tree = tree_of(store, parents[i]);-      auto detected = detect_renames(store, &tx, parent_tree,-                                     std::optional<Id>{root}, 0, i);-      for (auto &rename : detected)-        commit.renames.push_back(std::move(rename));-    }-  }-  return tx.add_object(TYPE_COMMIT, encode_commit(commit));-}--std::string rerere_suffix(std::size_t count) {-  if (count == 0)-    return std::string();-  return " (rerere " + std::to_string(count) + ")";-}--std::string join_revs(const std::vector<std::string> &revs) {-  std::string out;-  for (std::size_t i = 0; i < revs.size(); ++i) {-    if (i != 0)-      out.push_back(' ');-    out += revs[i];-  }-  return out;-}--bool adjacent_config(const fs::path &root) {-  auto value = repo_config_value(root, "merge.adjacent");-  return value && *value == "merge";-}--// ----------------------------------------------------------------------------// Tree editing-// -----------------------------------------------------------------------------std::optional<Id> tree_edit_into(Txn &tx, Store &store, const Id &tree_id,-                                 std::string_view path, bool present,-                                 std::uint8_t kind, const Id &target,-                                 std::size_t depth) {-  if (depth > 4096)-    return std::nullopt;-  auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);-  if (!body)-    return std::nullopt;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return std::nullopt;-  const std::size_t cut = path.find('/');-  const std::size_t cut_pos = cut == std::string_view::npos ? path.size() : cut;-  const std::string_view name = path.substr(0, cut_pos);-  std::vector<TreeEntry> entries;-  bool found = false;-  for (const auto &entry : tree->entries) {-    if (entry.name != name) {-      entries.push_back(entry);-      continue;-    }-    found = true;-    if (cut_pos == path.size()) {-      if (present)-        entries.push_back(TreeEntry{entry.name, kind, target});-    } else if (entry.kind == KIND_SUBTREE) {-      auto child =-          tree_edit_into(tx, store, entry.target, path.substr(cut_pos + 1),-                         present, kind, target, depth + 1);-      if (child && !tree_empty_any(store, &tx, *child))-        entries.push_back(TreeEntry{entry.name, KIND_SUBTREE, *child});-    } else {-      entries.push_back(entry);-    }-  }-  if (!found && cut_pos == path.size() && present)-    entries.push_back(TreeEntry{std::string(name), kind, target});-  return add_tree(tx, entries);-}--std::optional<Id> tree_edit_replace(Txn &tx, Store &store, const Id &root,-                                    std::string_view path, bool present,-                                    std::uint8_t kind, const Id &target) {-  auto edited = tree_edit_into(tx, store, root, path, present, kind, target, 0);-  if (!edited)-    return std::nullopt;-  return edited;-}--// ----------------------------------------------------------------------------// Conflicts-// -----------------------------------------------------------------------------std::string conflict_kind_label(const Conflict &conflict) {-  for (const auto &value : conflict.adds) {-    if (value.kind == KIND_SUBTREE)-      return "tree";-  }-  for (const auto &value : conflict.removes) {-    if (value.kind == KIND_SUBTREE)-      return "tree";-  }-  for (const auto &value : conflict.adds) {-    if (value.kind == 0)-      return "delete/modify";-  }-  for (const auto &value : conflict.removes) {-    if (value.kind == 0)-      return "delete/modify";-  }-  return "text";-}--void print_range(std::size_t a, std::size_t b) {-  if (a == b)-    std::cout << a + 1;-  else-    std::cout << a + 1 << "-" << b;-}--std::optional<EditResult>-conflict_ranges(Store &store, const Conflict &conflict, bool adjacent) {-  if (conflict.adds.size() != 2 || conflict.removes.size() != 1)-    return std::nullopt;-  const auto &ours = conflict.adds[0];-  const auto &theirs = conflict.adds[1];-  const auto &base = conflict.removes[0];-  if (ours.kind == 0 || theirs.kind == 0 || base.kind == 0)-    return std::nullopt;-  if (ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE ||-      base.kind == KIND_SUBTREE)-    return std::nullopt;-  return merge_blobs(store, nullptr, *base.target, *ours.target, *theirs.target,-                     adjacent);-}--std::vector<FlatEntry> flatten_store(Store &store, const Id &tree) {-  return flatten_any_sorted(store, nullptr, std::optional<Id>{tree});-}--// ----------------------------------------------------------------------------// Commands-// -----------------------------------------------------------------------------int merge_command(const std::vector<std::string> &revs) {-  if (revs.empty()) {-    error_prefix();-    std::cout << "merge requires at least one revision\n";-    return 1;-  }-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;--  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  if (!wc) {-    error_prefix();-    std::cout << "no working-copy commit to merge into\n";-    return 1;-  }--  std::vector<Id> parents{*wc};-  bool failed = false;-  for (const auto &rev : revs) {-    auto resolved = resolve_revision(store, tx->view(), rev);-    if (!resolved) {-      failed = true;-      continue;-    }-    if (same_id(*resolved, *wc)) {-      error_prefix();-      std::cout << "cannot merge a commit with itself\n";-      failed = true;-      continue;-    }-    parents.push_back(*resolved);-  }-  if (failed) {-    error_prefix();-    std::cout << "unknown revision\n";-    return 1;-  }--  const auto old_root = tree_of(store, *wc);-  const bool adjacent = adjacent_config(*root);-  MergeOutcome outcome = merge_many(*root, *tx, store, parents, adjacent);-  const Sig author = identity_signature(*root);-  const Id new_id =-      make_commit(*tx, store, *root, parents, outcome.tree, random_change_id(),-                  author, "", RENAMES_RECORDED, {});--  remove_head(tx->view(), *wc);-  move_bookmarks(tx->view(), *wc, new_id);-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());-  const std::string description =-      "merge " + join_revs(revs) + rerere_suffix(outcome.rerere);-  const auto status = tx->finish(description);-  if (!status)-    return 1;-  store.refresh(*root);-  (void)mark_native(*root, new_id);-  if (old_root)-    return checkout_materialize_commit(*root, store, old_root, outcome.tree);-  return 0;-}--int rebase_command(const std::string &source, const std::string &dest) {-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;--  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  auto src = resolve_revision(store, tx->view(), source);-  auto dst = resolve_revision(store, tx->view(), dest);-  if (!src || !dst) {-    error_prefix();-    std::cout << "unknown revision\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  std::optional<Id> old_wc_root;-  if (wc)-    old_wc_root = tree_of(store, *wc);--  std::vector<Id> set;-  for (const auto &commit : all_commits(store, tx->view())) {-    if (is_ancestor(store, *src, commit))-      set.push_back(commit);-  }--  std::vector<Id> old_ids;-  std::vector<Id> new_ids;-  std::vector<Id> new_tree_ids;-  std::vector<Id> remaining = set;-  std::size_t rerere_total = 0;-  const bool adjacent = adjacent_config(*root);-  const Sig fallback_sig = identity_signature(*root);-  (void)fallback_sig;--  while (!remaining.empty()) {-    std::ptrdiff_t ready_idx = -1;-    for (std::size_t i = 0; i < remaining.size(); ++i) {-      bool ready = true;-      auto loaded = load_commit(store, remaining[i]);-      if (!loaded)-        continue;-      for (const auto &parent : loaded->commit.parents) {-        if (contains_id_vec(set, parent) && !contains_id_vec(old_ids, parent) &&-            !same_id(remaining[i], *src))-          ready = false;-      }-      if (ready) {-        ready_idx = static_cast<std::ptrdiff_t>(i);-        break;-      }-    }-    if (ready_idx < 0) {-      error_prefix();-      std::cout << "rebase could not order commits\n";-      break;-    }-    const Id chosen = remaining[static_cast<std::size_t>(ready_idx)];-    auto loaded = load_commit(store, chosen);-    if (!loaded)-      break;--    std::vector<Id> new_parents;-    std::vector<Id> new_parent_trees;-    for (std::size_t pi = 0; pi < loaded->commit.parents.size(); ++pi) {-      const Id parent = loaded->commit.parents[pi];-      if (pi == 0 && same_id(chosen, *src)) {-        new_parents.push_back(*dst);-        new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));-        continue;-      }-      bool mapped = false;-      for (std::size_t mi = 0; mi < old_ids.size(); ++mi) {-        if (same_id(old_ids[mi], parent)) {-          new_parents.push_back(new_ids[mi]);-          new_parent_trees.push_back(new_tree_ids[mi]);-          mapped = true;-          break;-        }-      }-      if (!mapped) {-        new_parents.push_back(parent);-        new_parent_trees.push_back(tree_of(store, parent).value_or(Id{}));-      }-    }-    if (loaded->commit.parents.empty()) {-      new_parents.push_back(*dst);-      new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));-    }--    MergeOutcome outcome = rewrite_tree(-        *root, *tx, store, chosen, loaded->commit.root_tree,-        loaded->commit.parents, new_parents, new_parent_trees, adjacent);-    rerere_total += outcome.rerere;-    const Id new_id = make_commit(-        *tx, store, *root, new_parents, outcome.tree, loaded->commit.change_id,-        loaded->commit.author, loaded->commit.message,-        loaded->commit.renames_state, loaded->commit.extra);-    old_ids.push_back(chosen);-    new_ids.push_back(new_id);-    new_tree_ids.push_back(outcome.tree);-    remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(ready_idx));-  }--  auto remap = [&](std::optional<Id> &id) {-    if (!id)-      return;-    for (std::size_t i = 0; i < old_ids.size(); ++i) {-      if (same_id(old_ids[i], *id)) {-        id = new_ids[i];-        return;-      }-    }-  };-  for (auto &bookmark : tx->view().bookmarks) {-    for (auto &id : bookmark.targets.adds)-      remap(id);-    for (auto &id : bookmark.targets.removes)-      remap(id);-  }-  for (auto &tag : tx->view().tags) {-    std::optional<Id> target = tag.target;-    remap(target);-    if (target)-      tag.target = *target;-  }-  for (auto &workspace : tx->view().working_copies) {-    std::optional<Id> target = workspace.target;-    remap(target);-    if (target)-      workspace.target = *target;-  }-  rebuild_heads(tx->view());-  const auto status = tx->finish("rebase " + source + " onto " + dest +-                                 rerere_suffix(rerere_total));-  if (!status)-    return 1;-  for (const auto &id : new_ids)-    (void)mark_native(*root, id);-  if (wc) {-    for (std::size_t i = 0; i < old_ids.size(); ++i) {-      if (same_id(old_ids[i], *wc)) {-        Store refreshed = Store::open_all(*root);-        return checkout_materialize_commit(*root, refreshed, old_wc_root,-                                           new_tree_ids[i]);-      }-    }-  }-  return 0;-}--int xs_command(bool porcelain) {-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  std::vector<std::pair<std::string, Conflict>> items;-  if (const auto wc = working_copy_id(*view)) {-    auto loaded = load_commit(store, *wc);-    if (loaded) {-      for (const auto &entry : flatten_store(store, loaded->commit.root_tree)) {-        if (entry.kind != KIND_CONFLICT)-          continue;-        auto body = store.read_body(entry.target, TYPE_CONFLICT);-        if (!body)-          continue;-        auto conflict = decode_conflict(bytes_of(*body));-        if (!conflict)-          continue;-        items.emplace_back(entry.path, std::move(*conflict));-      }-    }-  }-  const bool adjacent = adjacent_config(*root);-  bool first = true;-  for (const auto &[path, conflict] : items) {-    const std::string kind = conflict_kind_label(conflict);-    auto ranges = conflict_ranges(store, conflict, adjacent);-    if (porcelain) {-      std::cout << path << "\t" << kind << "\t";-      if (ranges) {-        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-          if (i > 0)-            std::cout << ",";-          print_range(ranges->ranges[i].base_start, ranges->ranges[i].base_end);-        }-        std::cout << "\t";-        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-          if (i > 0)-            std::cout << ",";-          print_range(ranges->ranges[i].ours_start, ranges->ranges[i].ours_end);-        }-        std::cout << "\t";-        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-          if (i > 0)-            std::cout << ",";-          print_range(ranges->ranges[i].theirs_start,-                      ranges->ranges[i].theirs_end);-        }-      } else {-        std::cout << "\t\t";-      }-      std::cout << "\n";-    } else {-      std::cout << path << ": " << kind << " conflict";-      if (ranges && !ranges->ranges.empty()) {-        std::cout << " (";-        for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {-          if (i > 0)-            std::cout << ", ";-          std::cout << "base ";-          print_range(ranges->ranges[i].base_start, ranges->ranges[i].base_end);-          std::cout << ", ours ";-          print_range(ranges->ranges[i].ours_start, ranges->ranges[i].ours_end);-          std::cout << ", theirs ";-          print_range(ranges->ranges[i].theirs_start,-                      ranges->ranges[i].theirs_end);-        }-        std::cout << ")";-      }-      std::cout << "\n";-    }-    first = false;-  }-  if (first) {-    info_prefix();-    std::cout << "no conflicts\n";-  }-  return 0;-}--std::string shell_replace(std::string_view command, std::string_view key,-                          const std::string &value) {-  std::string out;-  std::size_t i = 0;-  while (i < command.size()) {-    if (i + key.size() <= command.size() &&-        command.compare(i, key.size(), key) == 0) {-      out.push_back('\'');-      out += value;-      out.push_back('\'');-      i += key.size();-    } else {-      out.push_back(command[i]);-      ++i;-    }-  }-  return out;-}--bool run_tool(const fs::path &root, std::string_view command,-              std::string_view path) {-  const std::string base = path_to_bytes(root / path_from_bytes(path));-  std::string expanded(command);-  expanded = shell_replace(expanded, "$BASE", base + ".base");-  expanded = shell_replace(expanded, "$OURS", base + ".ours");-  expanded = shell_replace(expanded, "$THEIRS", base + ".theirs");-  expanded = shell_replace(expanded, "$OUTPUT", base);-  return std::system(expanded.c_str()) == 0;-}--void delete_sidecar(const fs::path &root, std::string_view path,-                    std::string_view suffix) {-  std::string full(path);-  full += suffix;-  (void)remove_file(root / path_from_bytes(full));-}--void delete_sidecars(const fs::path &root, std::string_view path) {-  delete_sidecar(root, path, ".base");-  delete_sidecar(root, path, ".ours");-  delete_sidecar(root, path, ".theirs");-  for (int n = 2; n <= 64; ++n) {-    delete_sidecar(root, path, ".base" + std::to_string(n));-    delete_sidecar(root, path, ".theirs" + std::to_string(n));-  }-}--std::optional<ConflictValue> choose_value(const Conflict &conflict,-                                          std::string_view take) {-  if (take == "ours" && !conflict.adds.empty())-    return conflict.adds[0];-  if (take == "theirs" && conflict.adds.size() > 1)-    return conflict.adds[1];-  if (take == "base" && !conflict.removes.empty())-    return conflict.removes[0];-  return std::nullopt;-}--int resolve_command(std::string_view take, std::string_view tool,-                    const std::vector<std::string> &paths) {-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  if (!wc) {-    error_prefix();-    std::cout << "no working-copy commit\n";-    return 1;-  }-  auto loaded = load_commit(store, *wc);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read working-copy commit\n";-    return 1;-  }-  const Id old_root = loaded->commit.root_tree;-  Id mut_root = old_root;-  bool resolved_any = false;-  std::vector<std::string> normalized_paths;--  const auto cwd = cwd_relative(*root);-  for (const auto &arg : paths) {-    auto norm = cwd ? pathspec_normalize(*root, *cwd, arg) : std::nullopt;-    if (!norm || norm->empty()) {-      error_prefix();-      std::cout << "invalid path\n";-      continue;-    }-    normalized_paths.push_back(*norm);-    auto flat = flatten_store(store, mut_root);-    const FlatEntry *entry = find_flat_entry(flat, *norm);-    if (!entry || entry->kind != KIND_CONFLICT) {-      error_prefix();-      std::cout << "not a conflicted path: " << *norm << "\n";-      continue;-    }-    auto body = store.read_body(entry->target, TYPE_CONFLICT);-    if (!body)-      continue;-    auto conflict = decode_conflict(bytes_of(*body));-    if (!conflict)-      continue;--    bool present = false;-    std::uint8_t new_kind = KIND_FILE;-    std::optional<Id> new_target;-    if (auto chosen = choose_value(*conflict, take)) {-      if (chosen->kind != 0) {-        present = true;-        new_kind = chosen->kind;-        new_target = chosen->target;-      }-    } else if (!tool.empty()) {-      if (run_tool(*root, tool, *norm)) {-        if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {-          new_target = add_blob(*tx, bytes_of(*data));-          present = true;-          new_kind = KIND_FILE;-        }-      }-    } else {-      if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {-        new_target = add_blob(*tx, bytes_of(*data));-        present = true;-        new_kind = KIND_FILE;-      }-    }-    if (present) {-      if (auto info = stat_path(*root / path_from_bytes(*norm))) {-        if (info->executable)-          new_kind = KIND_EXECUTABLE;-      }-      if (new_kind == KIND_FILE || new_kind == KIND_EXECUTABLE) {-        if (auto conflict_body =-                store.read_body(entry->target, TYPE_CONFLICT)) {-          resolution_record(*root, bytes_of(*conflict_body), *new_target);-        }-      }-    }-    auto replaced = tree_edit_replace(*tx, store, mut_root, *norm, present,-                                      new_kind, new_target.value_or(Id{}));-    if (replaced) {-      mut_root = *replaced;-      resolved_any = true;-    }-  }--  if (!resolved_any) {-    return 1;-  }--  Commit commit = loaded->commit;-  commit.root_tree = mut_root;-  commit.committer = identity_signature(*root);-  const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));-  remove_head(tx->view(), *wc);-  move_bookmarks(tx->view(), *wc, new_id);-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());-  const auto status = tx->finish("resolve");-  if (!status)-    return 1;-  Store refreshed = Store::open_all(*root);-  const int materialized =-      checkout_materialize_commit(*root, refreshed, old_root, mut_root);-  if (materialized != 0)-    return materialized;-  for (const auto &path : normalized_paths)-    delete_sidecars(*root, path);-  return 0;-}--} // namespace--// ----------------------------------------------------------------------------// Argument parsing-// -----------------------------------------------------------------------------int merge_run(const std::vector<std::string> &args) {-  std::vector<std::string> revs;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && !arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      revs.push_back(arg);-    }-  }-  return merge_command(revs);-}--int rebase_run(const std::vector<std::string> &args) {-  std::string source;-  std::string dest;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-s" || arg == "-source")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      source = args[++i];-    } else if (!end_flags && (arg == "-d" || arg == "-destination")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a revision\n";-        return 1;-      }-      dest = args[++i];-    } else if (!end_flags && !arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      error_prefix();-      std::cout << "unexpected argument: " << arg << "\n";-      return 1;-    }-  }-  if (source.empty() || dest.empty()) {-    error_prefix();-    std::cout << "rebase requires -s <rev> and -d <rev>\n";-    return 1;-  }-  return rebase_command(source, dest);-}--int xs_run(const std::vector<std::string> &args) {-  bool porcelain = false;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-porcelain" || arg == "-p")) {-      porcelain = true;-    } else if (!end_flags && !arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      error_prefix();-      std::cout << "unexpected argument: " << arg << "\n";-      return 1;-    }-  }-  return xs_command(porcelain);-}--int resolve_run(const std::vector<std::string> &args) {-  std::string take;-  std::string tool;-  bool list_only = false;-  std::vector<std::string> paths;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-list" || arg == "-l")) {-      list_only = true;-    } else if (!end_flags && (arg == "-take" || arg == "-t")) {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires ours, theirs, or base\n";-        return 1;-      }-      take = args[++i];-    } else if (!end_flags && arg == "-tool") {-      if (i + 1 >= args.size()) {-        error_prefix();-        std::cout << arg << " requires a command\n";-        return 1;-      }-      tool = args[++i];-    } else if (!end_flags && !arg.empty() && arg.front() == '-') {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      paths.push_back(arg);-    }-  }-  if (list_only)-    return xs_command(false);-  if (paths.empty()) {-    error_prefix();-    std::cout << "resolve requires at least one path\n";-    return 1;-  }-  return resolve_command(take, tool, paths);+bool same_id(const Id& a, const Id& b) {+    return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+}++std::optional<std::vector<std::uint8_t>> read_body_any(Store& store, Txn* tx, std::uint8_t type,+                                                       const Id& id) {+    if (tx) {+        if (auto cached = tx->writer().find_cached(type, id))+            return cached;+    }+    return store.read_body(id, type);+}++bool append_blob_any(Store& store, Txn* tx, const Id& id, std::vector<std::uint8_t>& out,+                     std::size_t depth) {+    if (depth > 64)+        return false;+    auto body = read_body_any(store, tx, TYPE_BLOB, id);+    if (!body)+        return false;+    auto blob = decode_blob(bytes_of(*body));+    if (!blob)+        return false;+    if (blob->form == BlobForm::Inline) {+        out.insert(out.end(), blob->data.begin(), blob->data.end());+        return true;+    }+    for (const auto& entry : blob->entries) {+        if (blob->form == BlobForm::Leaf) {+            auto chunk = read_body_any(store, tx, TYPE_CHUNK, entry.id);+            if (!chunk)+                return false;+            out.insert(out.end(), chunk->begin(), chunk->end());+        } else if (!append_blob_any(store, tx, entry.id, out, depth + 1)) {+            return false;+        }+    }+    return true;+}++std::optional<std::vector<std::uint8_t>> read_blob_any(Store& store, Txn* tx, const Id& id) {+    std::vector<std::uint8_t> out;+    if (!append_blob_any(store, tx, id, out, 0))+        return std::nullopt;+    return out;+}++bool collect_chunks_any(Store& store, Txn* tx, const Id& id, std::vector<Id>& out,+                        std::size_t depth) {+    if (depth > 64)+        return false;+    auto body = read_body_any(store, tx, TYPE_BLOB, id);+    if (!body)+        return false;+    auto blob = decode_blob(bytes_of(*body));+    if (!blob)+        return false;+    if (blob->form == BlobForm::Leaf) {+        for (const auto& entry : blob->entries)+            out.push_back(entry.id);+        return true;+    }+    if (blob->form == BlobForm::Interior) {+        for (const auto& entry : blob->entries) {+            if (!collect_chunks_any(store, tx, entry.id, out, depth + 1))+                return false;+        }+    }+    return true;+}++bool flatten_any(Store& store, Txn* tx, const Id& tree_id, std::string& prefix,+                 std::vector<FlatEntry>& out, std::size_t depth) {+    if (depth > 4096)+        return false;+    auto body = read_body_any(store, tx, TYPE_TREE, tree_id);+    if (!body)+        return false;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return false;+    for (const auto& entry : tree->entries) {+        const std::size_t old_size = prefix.size();+        if (!prefix.empty())+            prefix.push_back('/');+        prefix.append(entry.name);+        if (entry.kind == KIND_SUBTREE) {+            if (!flatten_any(store, tx, entry.target, prefix, out, depth + 1)) {+                prefix.resize(old_size);+                return false;+            }+            prefix.resize(old_size);+        } else {+            out.push_back(FlatEntry{prefix, entry.kind, entry.target});+            prefix.resize(old_size);+        }+    }+    return true;+}++std::vector<FlatEntry> flatten_any_sorted(Store& store, Txn* tx, std::optional<Id> tree) {+    std::vector<FlatEntry> out;+    if (!tree)+        return out;+    std::string prefix;+    (void)flatten_any(store, tx, *tree, prefix, out, 0);+    std::stable_sort(out.begin(), out.end(), [](const FlatEntry& a, const FlatEntry& b) {+        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+    });+    return out;+}++const FlatEntry* find_flat_entry(const std::vector<FlatEntry>& entries, std::string_view path) {+    for (const auto& entry : entries) {+        if (entry.path == path)+            return &entry;+    }+    return nullptr;+}++bool tree_empty_any(Store& store, Txn* tx, const Id& id) {+    auto body = read_body_any(store, tx, TYPE_TREE, id);+    if (!body)+        return true;+    auto tree = decode_tree(bytes_of(*body));+    return !tree || tree->entries.empty();+}++Id add_tree(Txn& tx, const std::vector<TreeEntry>& entries) {+    auto encoded = encode_tree(entries);+    if (!encoded)+        return Id{};+    return tx.add_object(TYPE_TREE, *encoded);+}++Id add_empty_tree(Txn& tx) {+    return add_tree(tx, {});+}++Id add_blob(Txn& tx, Bytes data) {+    BlobBuild build = build_blob(data);+    for (auto& object : build.objects) {+        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));+        (void)tx.add_known(object.type, id, std::move(object.body));+    }+    return build.root;+}++// ---------------------------------------------------------------------------+// Three-way line merge+// ---------------------------------------------------------------------------++struct DiffOp {+    char tag = ' ';+    std::size_t ai = 0;+    std::size_t bi = 0;+};++std::vector<std::string> split_lines(Bytes data) {+    std::vector<std::string> out;+    std::size_t start = 0;+    for (std::size_t i = 0; i < data.size(); ++i) {+        if (data[i] == '\n') {+            out.emplace_back(reinterpret_cast<const char*>(data.data() + start), i + 1 - start);+            start = i + 1;+        }+    }+    if (start < data.size())+        out.emplace_back(reinterpret_cast<const char*>(data.data() + start), data.size() - start);+    return out;+}++std::vector<DiffOp> fallback_ops(const std::vector<std::string>& a,+                                 const std::vector<std::string>& b) {+    const std::size_t n = a.size();+    const std::size_t m = b.size();+    std::size_t prefix = 0;+    while (prefix < n && prefix < m && a[prefix] == b[prefix])+        ++prefix;+    std::size_t suffix = 0;+    while (suffix < n - prefix && suffix < m - prefix && a[n - 1 - suffix] == b[m - 1 - suffix])+        ++suffix;+    std::vector<DiffOp> ops;+    for (std::size_t i = 0; i < prefix; ++i)+        ops.push_back(DiffOp{' ', i, i});+    for (std::size_t i = prefix; i < n - suffix; ++i)+        ops.push_back(DiffOp{'-', i, 0});+    for (std::size_t j = prefix; j < m - suffix; ++j)+        ops.push_back(DiffOp{'+', 0, j});+    for (std::size_t k = 0; k < suffix; ++k)+        ops.push_back(DiffOp{' ', n - suffix + k, m - suffix + k});+    return ops;+}++std::vector<DiffOp> build_ops(const std::vector<std::string>& a,+                              const std::vector<std::string>& b) {+    const std::size_t n = a.size();+    const std::size_t m = b.size();+    const std::uint64_t cells =+        static_cast<std::uint64_t>(n + 1) * static_cast<std::uint64_t>(m + 1);+    if (cells > 8000000)+        return fallback_ops(a, b);+    const std::size_t cols = m + 1;+    std::vector<std::uint32_t> dp(static_cast<std::size_t>(cells), 0);+    for (std::size_t i = 1; i <= n; ++i) {+        for (std::size_t j = 1; j <= m; ++j) {+            if (a[i - 1] == b[j - 1]) {+                dp[i * cols + j] = dp[(i - 1) * cols + (j - 1)] + 1;+            } else {+                dp[i * cols + j] = std::max(dp[(i - 1) * cols + j], dp[i * cols + (j - 1)]);+            }+        }+    }+    std::vector<DiffOp> ops;+    std::size_t oi = n;+    std::size_t oj = m;+    while (oi > 0 || oj > 0) {+        if (oi > 0 && oj > 0 && a[oi - 1] == b[oj - 1]) {+            ops.push_back(DiffOp{' ', oi - 1, oj - 1});+            --oi;+            --oj;+        } else if (oj > 0 && (oi == 0 || dp[oi * cols + (oj - 1)] >= dp[(oi - 1) * cols + oj])) {+            ops.push_back(DiffOp{'+', 0, oj - 1});+            --oj;+        } else {+            ops.push_back(DiffOp{'-', oi - 1, 0});+            --oi;+        }+    }+    std::reverse(ops.begin(), ops.end());+    return ops;+}++struct Hunk {+    std::size_t start = 0;+    std::size_t end = 0;+    std::vector<std::string> lines;+};++std::vector<Hunk> hunks_from_ops(const std::vector<std::string>& side,+                                 const std::vector<DiffOp>& ops) {+    std::vector<Hunk> out;+    std::size_t base_pos = 0;+    std::size_t i = 0;+    while (i < ops.size()) {+        if (ops[i].tag == ' ') {+            ++base_pos;+            ++i;+            continue;+        }+        Hunk hunk;+        hunk.start = base_pos;+        while (i < ops.size() && ops[i].tag != ' ') {+            if (ops[i].tag == '-') {+                ++base_pos;+            } else {+                hunk.lines.push_back(side[ops[i].bi]);+            }+            ++i;+        }+        hunk.end = base_pos;+        out.push_back(std::move(hunk));+    }+    return out;+}++std::vector<Hunk> diff_hunks(const std::vector<std::string>& base,+                             const std::vector<std::string>& side) {+    return hunks_from_ops(side, build_ops(base, side));+}++struct MergeRange {+    std::size_t base_start = 0;+    std::size_t base_end = 0;+    std::size_t ours_start = 0;+    std::size_t ours_end = 0;+    std::size_t theirs_start = 0;+    std::size_t theirs_end = 0;+};++struct EditResult {+    bool conflicted = false;+    std::vector<std::uint8_t> data;+    std::vector<MergeRange> ranges;+};++void append_lines(std::vector<std::uint8_t>& out, const std::vector<std::string>& lines,+                  std::size_t start, std::size_t end) {+    for (std::size_t i = start; i < end && i < lines.size(); ++i)+        out.insert(out.end(), lines[i].begin(), lines[i].end());+}++void apply_hunks(std::vector<std::uint8_t>& out, const std::vector<std::string>& base,+                 std::size_t from, std::size_t to, const std::vector<Hunk>& hunks,+                 std::size_t first, std::size_t last) {+    std::size_t pos = from;+    for (std::size_t k = first; k < last; ++k) {+        const Hunk& h = hunks[k];+        if (h.start > pos && h.start <= to)+            append_lines(out, base, pos, h.start);+        for (const auto& line : h.lines)+            out.insert(out.end(), line.begin(), line.end());+        if (h.end > pos)+            pos = h.end;+    }+    if (pos < to)+        append_lines(out, base, pos, to);+}++std::size_t map_pos(const std::vector<Hunk>& hunks, std::size_t pos) {+    std::ptrdiff_t out = static_cast<std::ptrdiff_t>(pos);+    for (const auto& h : hunks) {+        if (h.end <= pos) {+            const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(h.end - h.start);+            const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());+            out += fresh - old;+        } else if (h.start < pos) {+            const std::ptrdiff_t old = static_cast<std::ptrdiff_t>(pos - h.start);+            const std::ptrdiff_t fresh = static_cast<std::ptrdiff_t>(h.lines.size());+            out += fresh - old;+            break;+        } else {+            break;+        }+    }+    return static_cast<std::size_t>(out);+}++bool same_hunks(const std::vector<Hunk>& ours, std::size_t of, std::size_t ol,+                const std::vector<Hunk>& theirs, std::size_t tf, std::size_t tl) {+    std::string a;+    std::string b;+    for (std::size_t k = of; k < ol; ++k)+        for (const auto& line : ours[k].lines)+            a += line;+    for (std::size_t j = tf; j < tl; ++j)+        for (const auto& line : theirs[j].lines)+            b += line;+    return a == b;+}++EditResult merge_lines(const std::vector<std::string>& base, const std::vector<std::string>& ours,+                       const std::vector<std::string>& theirs, bool adjacent_merge) {+    const auto ours_h = diff_hunks(base, ours);+    const auto theirs_h = diff_hunks(base, theirs);+    EditResult result;+    std::size_t oi = 0;+    std::size_t ti = 0;+    std::size_t pos = 0;+    while (oi < ours_h.size() || ti < theirs_h.size()) {+        const bool have_o = oi < ours_h.size();+        const bool have_t = ti < theirs_h.size();+        const std::size_t o_start = have_o ? ours_h[oi].start : 0;+        const std::size_t t_start = have_t ? theirs_h[ti].start : 0;+        const bool take_ours_cluster = have_o && (!have_t || o_start <= t_start);+        const std::size_t cluster_start = take_ours_cluster ? o_start : t_start;+        const std::size_t of = oi;+        const std::size_t tf = ti;+        std::size_t o_last = of;+        std::size_t t_last = tf;+        std::size_t end = cluster_start;+        bool seen_o = false;+        bool seen_t = false;+        for (;;) {+            bool progress = false;+            if (o_last < ours_h.size()) {+                const Hunk& h = ours_h[o_last];+                bool include = h.start <= end;+                if (o_last != of)+                    include = adjacent_merge ? h.start < end : h.start <= end;+                if (include) {+                    seen_o = true;+                    ++o_last;+                    if (h.end > end)+                        end = h.end;+                    progress = true;+                }+            }+            if (t_last < theirs_h.size()) {+                const Hunk& h = theirs_h[t_last];+                bool include = h.start <= end;+                if (t_last != tf)+                    include = adjacent_merge ? h.start < end : h.start <= end;+                if (include) {+                    seen_t = true;+                    ++t_last;+                    if (h.end > end)+                        end = h.end;+                    progress = true;+                }+            }+            if (!progress)+                break;+        }+        if (end < cluster_start)+            end = cluster_start;+        if (seen_o && !seen_t) {+            apply_hunks(result.data, base, pos, end, ours_h, of, o_last);+            pos = end;+            oi = o_last;+            ti = t_last;+        } else if (seen_t && !seen_o) {+            apply_hunks(result.data, base, pos, end, theirs_h, tf, t_last);+            pos = end;+            oi = o_last;+            ti = t_last;+        } else {+            if (same_hunks(ours_h, of, o_last, theirs_h, tf, t_last)) {+                apply_hunks(result.data, base, pos, end, ours_h, of, o_last);+                pos = end;+            } else {+                result.conflicted = true;+                apply_hunks(result.data, base, pos, end, ours_h, of, o_last);+                MergeRange range;+                range.base_start = cluster_start;+                range.base_end = end;+                range.ours_start = map_pos(ours_h, cluster_start);+                range.ours_end = map_pos(ours_h, end);+                range.theirs_start = map_pos(theirs_h, cluster_start);+                range.theirs_end = map_pos(theirs_h, end);+                result.ranges.push_back(range);+                pos = end;+            }+            oi = o_last;+            ti = t_last;+        }+    }+    if (pos < base.size())+        append_lines(result.data, base, pos, base.size());+    return result;+}++std::optional<EditResult> merge_blobs(Store& store, Txn* tx, const Id& base_id, const Id& ours_id,+                                      const Id& theirs_id, bool adjacent) {+    auto base = read_blob_any(store, tx, base_id);+    auto ours = read_blob_any(store, tx, ours_id);+    auto theirs = read_blob_any(store, tx, theirs_id);+    if (!base || !ours || !theirs)+        return std::nullopt;+    return merge_lines(split_lines(bytes_of(*base)), split_lines(bytes_of(*ours)),+                       split_lines(bytes_of(*theirs)), adjacent);+}++// ---------------------------------------------------------------------------+// Rename detection+// ---------------------------------------------------------------------------++struct RenamePair {+    std::string old_path;+    std::string new_path;+    std::size_t score = 0;+    bool old_used = false;+    bool new_used = false;+};++std::uint64_t hash_line(std::string_view line) {+    std::uint64_t h = 1469598103934665603ull;+    for (char raw : line) {+        const auto c = static_cast<unsigned char>(raw);+        h = (h ^ static_cast<std::uint64_t>(c)) * 1099511628211ull;+    }+    return h;+}++int line_similarity(Bytes a, Bytes b) {+    std::vector<std::uint64_t> la;+    std::vector<std::uint64_t> lb;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= a.size(); ++i) {+        if (i == a.size() || a[i] == '\n') {+            la.push_back(hash_line(str_of(a.subspan(start, i - start))));+            start = i + 1;+        }+    }+    start = 0;+    for (std::size_t j = 0; j <= b.size(); ++j) {+        if (j == b.size() || b[j] == '\n') {+            lb.push_back(hash_line(str_of(b.subspan(start, j - start))));+            start = j + 1;+        }+    }+    std::sort(la.begin(), la.end());+    std::sort(lb.begin(), lb.end());+    std::size_t ia = 0;+    std::size_t ib = 0;+    std::size_t inter = 0;+    while (ia < la.size() && ib < lb.size()) {+        if (la[ia] == lb[ib]) {+            ++inter;+            ++ia;+            ++ib;+        } else if (la[ia] < lb[ib]) {+            ++ia;+        } else {+            ++ib;+        }+    }+    const std::size_t total = la.size() + lb.size() - inter;+    if (total == 0)+        return 100;+    return static_cast<int>((inter * 100) / total);+}++int chunk_similarity(Store& store, Txn* tx, const Id& a, const Id& b) {+    std::vector<Id> ca;+    std::vector<Id> cb;+    if (!collect_chunks_any(store, tx, a, ca, 0) || !collect_chunks_any(store, tx, b, cb, 0))+        return 0;+    std::size_t inter = 0;+    for (const auto& x : ca) {+        for (const auto& y : cb) {+            if (same_id(x, y)) {+                ++inter;+                break;+            }+        }+    }+    const std::size_t total = ca.size() + cb.size() - inter;+    if (total == 0)+        return 0;+    return static_cast<int>((inter * 100) / total);+}++int similarity(Store& store, Txn* tx, const Id& a, const Id& b) {+    if (same_id(a, b))+        return 100;+    auto da = read_blob_any(store, tx, a);+    auto db = read_blob_any(store, tx, b);+    if (!da || !db)+        return 0;+    int result = 0;+    if (da->size() >= 131072 && db->size() >= 131072)+        result = chunk_similarity(store, tx, a, b);+    if (result == 0)+        result = line_similarity(bytes_of(*da), bytes_of(*db));+    return result;+}++} // namespace++std::vector<Rename> detect_renames(Store& store, Txn* tx, std::optional<Id> old_tree,+                                   std::optional<Id> new_tree, int similar_pct,+                                   std::uint64_t parent_index) {+    const auto old_entries = flatten_any_sorted(store, tx, old_tree);+    const auto new_entries = flatten_any_sorted(store, tx, new_tree);+    std::vector<FlatEntry> deleted;+    std::vector<FlatEntry> added;+    for (const auto& entry : old_entries) {+        if (!find_flat_entry(new_entries, entry.path))+            deleted.push_back(entry);+    }+    for (const auto& entry : new_entries) {+        if (!find_flat_entry(old_entries, entry.path))+            added.push_back(entry);+    }+    std::vector<char> used_old(deleted.size(), 0);+    std::vector<char> used_new(added.size(), 0);+    std::vector<Rename> out;+    for (std::size_t di = 0; di < deleted.size(); ++di) {+        if (used_old[di])+            continue;+        for (std::size_t ai = 0; ai < added.size(); ++ai) {+            if (used_new[ai])+                continue;+            if (same_id(deleted[di].target, added[ai].target)) {+                out.push_back(Rename{parent_index, 0, deleted[di].path, added[ai].path});+                used_old[di] = 1;+                used_new[ai] = 1;+                break;+            }+        }+    }+    if (similar_pct > 0) {+        std::vector<RenamePair> pairs;+        constexpr std::size_t candidate_limit = 5000;+        for (std::size_t di = 0; di < deleted.size(); ++di) {+            if (used_old[di] ||+                (deleted[di].kind != KIND_FILE && deleted[di].kind != KIND_EXECUTABLE))+                continue;+            for (std::size_t ai = 0; ai < added.size() && pairs.size() < candidate_limit; ++ai) {+                if (used_new[ai] ||+                    (added[ai].kind != KIND_FILE && added[ai].kind != KIND_EXECUTABLE))+                    continue;+                RenamePair pair;+                pair.old_path = deleted[di].path;+                pair.new_path = added[ai].path;+                pair.score = static_cast<std::size_t>(+                    similarity(store, tx, deleted[di].target, added[ai].target));+                pairs.push_back(std::move(pair));+            }+        }+        for (;;) {+            std::ptrdiff_t best_i = -1;+            std::size_t best = 0;+            for (std::size_t i = 0; i < pairs.size(); ++i) {+                if (!pairs[i].old_used && !pairs[i].new_used && pairs[i].score > best) {+                    best = pairs[i].score;+                    best_i = static_cast<std::ptrdiff_t>(i);+                }+            }+            if (best_i < 0 || best < static_cast<std::size_t>(similar_pct))+                break;+            auto& pair = pairs[static_cast<std::size_t>(best_i)];+            pair.old_used = true;+            pair.new_used = true;+            out.push_back(Rename{parent_index, 0, pair.old_path, pair.new_path});+        }+    }+    std::stable_sort(out.begin(), out.end(), [](const Rename& a, const Rename& b) {+        if (a.parent_index != b.parent_index)+            return a.parent_index < b.parent_index;+        return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;+    });+    return out;+}++int rename_similar_pct(const fs::path& root) {+    if (auto value = repo_config_value(root, "rename.autodetect")) {+        if (*value == "off")+            return 0;+        return 60;+    }+    return 60;+}++namespace {++// ---------------------------------------------------------------------------+// Rename maps+// ---------------------------------------------------------------------------++using RenameMap = std::vector<std::pair<std::string, std::string>>;++std::optional<std::string> rename_lookup(const RenameMap& map, std::string_view path) {+    for (const auto& entry : map) {+        if (entry.first == path)+            return entry.second;+    }+    return std::nullopt;+}++void rename_apply(RenameMap& map, const std::string& from, const std::string& to) {+    for (auto& entry : map) {+        if (entry.second == from) {+            entry.second = to;+            return;+        }+    }+    for (auto& entry : map) {+        if (entry.first == from) {+            entry.second = to;+            return;+        }+    }+    map.emplace_back(from, to);+}++std::optional<Id> tree_of(Store& store, const Id& commit_id) {+    auto loaded = load_commit(store, commit_id);+    if (!loaded)+        return std::nullopt;+    return loaded->commit.root_tree;+}++std::optional<Id> first_parent(Store& store, const Id& commit_id) {+    auto loaded = load_commit(store, commit_id);+    if (!loaded || loaded->commit.parents.empty())+        return std::nullopt;+    return loaded->commit.parents.front();+}++RenameMap map_from(Store& store, const Id& base, const Id& side) {+    RenameMap map;+    if (same_id(base, side))+        return map;+    std::vector<Id> chain;+    Id current = side;+    bool reached = false;+    for (std::size_t depth = 0; depth < 100000; ++depth) {+        if (same_id(current, base)) {+            reached = true;+            break;+        }+        chain.push_back(current);+        auto parent = first_parent(store, current);+        if (!parent)+            break;+        current = *parent;+    }+    if (!reached)+        return map;+    for (std::size_t i = chain.size(); i > 0; --i) {+        auto loaded = load_commit(store, chain[i - 1]);+        if (!loaded)+            continue;+        if (loaded->commit.renames_state == RENAMES_RECORDED) {+            for (const auto& rename : loaded->commit.renames) {+                if (rename.parent_index == 0)+                    rename_apply(map, rename.from_path, rename.to_path);+            }+        } else {+            auto parent = first_parent(store, chain[i - 1]);+            if (!parent)+                continue;+            auto old_tree = tree_of(store, *parent);+            auto new_tree = tree_of(store, chain[i - 1]);+            for (const auto& rename : detect_renames(store, nullptr, old_tree, new_tree, 50, 0))+                rename_apply(map, rename.from_path, rename.to_path);+        }+    }+    return map;+}++// ---------------------------------------------------------------------------+// Tree merge+// ---------------------------------------------------------------------------++struct TreeTerm {+    bool positive = true;+    bool present = false;+    Id id{};+};++struct EntryTerm {+    bool positive = true;+    bool present = false;+    std::uint8_t kind = 0;+    std::optional<Id> target;+};++struct OrigEntry {+    std::size_t term = 0;+    std::string path;+    std::uint8_t kind = 0;+    Id target{};+};++struct OutEntry {+    std::string path;+    std::uint8_t kind = 0;+    Id target{};+};++struct MergeOutcome {+    Id tree{};+    std::size_t rerere = 0;+};++bool value_equal(const ConflictValue& a, const ConflictValue& b) {+    if (a.kind != b.kind)+        return false;+    if (a.kind == 0)+        return true;+    return a.target && b.target && same_id(*a.target, *b.target);+}++void flatten_values(Store& store, const std::vector<ConflictValue>& values, bool positive,+                    std::vector<ConflictValue>& adds, std::vector<ConflictValue>& removes,+                    std::size_t depth) {+    for (const auto& value : values) {+        if (value.kind == KIND_CONFLICT && value.target && depth < 64) {+            auto body = store.read_body(*value.target, TYPE_CONFLICT);+            if (body) {+                auto child = decode_conflict(bytes_of(*body));+                if (child) {+                    flatten_values(store, child->adds, positive, adds, removes, depth + 1);+                    flatten_values(store, child->removes, !positive, adds, removes, depth + 1);+                    continue;+                }+            }+        }+        if (positive)+            adds.push_back(value);+        else+            removes.push_back(value);+    }+}++Conflict simplify(Store& store, const std::vector<ConflictValue>& adds_in,+                  const std::vector<ConflictValue>& removes_in) {+    std::vector<ConflictValue> flat_adds;+    std::vector<ConflictValue> flat_removes;+    flatten_values(store, adds_in, true, flat_adds, flat_removes, 0);+    flatten_values(store, removes_in, false, flat_adds, flat_removes, 0);++    std::vector<char> used(flat_adds.size(), 0);+    std::vector<char> rem_used(flat_removes.size(), 0);+    for (std::size_t r = 0; r < flat_removes.size(); ++r) {+        for (std::size_t a = 0; a < flat_adds.size(); ++a) {+            if (!used[a] && value_equal(flat_adds[a], flat_removes[r])) {+                used[a] = 1;+                rem_used[r] = 1;+                break;+            }+        }+    }+    Conflict out;+    for (std::size_t a = 0; a < flat_adds.size(); ++a) {+        if (!used[a])+            out.adds.push_back(flat_adds[a]);+    }+    for (std::size_t r = 0; r < flat_removes.size(); ++r) {+        if (!rem_used[r])+            out.removes.push_back(flat_removes[r]);+    }+    return out;+}++std::optional<ConflictValue> resolved(const Conflict& conflict) {+    if (conflict.adds.empty())+        return std::nullopt;+    for (std::size_t i = 1; i < conflict.adds.size(); ++i) {+        if (!value_equal(conflict.adds[0], conflict.adds[i]))+            return std::nullopt;+    }+    return conflict.adds[0];+}++bool all_files(const Conflict& conflict) {+    for (const auto& value : conflict.adds) {+        if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE && value.kind != 0)+            return false;+    }+    for (const auto& value : conflict.removes) {+        if (value.kind != KIND_FILE && value.kind != KIND_EXECUTABLE && value.kind != 0)+            return false;+    }+    return true;+}++int merge_mode(const Conflict& conflict) {+    if (conflict.adds.size() != 2 || conflict.removes.size() != 1)+        return -1;+    auto mode = [](const ConflictValue& value) -> int {+        if (value.kind == 0)+            return -1;+        return value.kind == KIND_EXECUTABLE ? 1 : 0;+    };+    const int m0 = mode(conflict.adds[0]);+    const int m1 = mode(conflict.adds[1]);+    const int mr = mode(conflict.removes[0]);+    if (m0 < 0 || m1 < 0)+        return -1;+    if (m0 == m1)+        return m0;+    if (mr >= 0 && m0 == mr)+        return m1;+    if (mr >= 0 && m1 == mr)+        return m0;+    return -1;+}++bool merge_binary(const fs::path& repo, std::string_view path) {+    auto data = read_file_opt(repo / ".veinsattributes");+    if (!data)+        return false;+    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    bool result = false;+    std::size_t start = 0;+    for (std::size_t pos = 0; pos <= text.size(); ++pos) {+        if (pos != text.size() && text[pos] != '\n')+            continue;+        std::string_view line = text.substr(start, pos - start);+        start = pos + 1;+        while (!line.empty() && (line.front() == ' ' || line.front() == '\t' ||+                                 line.front() == '\r' || line.front() == '\n'))+            line.remove_prefix(1);+        while (!line.empty() && (line.back() == ' ' || line.back() == '\t' || line.back() == '\r' ||+                                 line.back() == '\n'))+            line.remove_suffix(1);+        if (line.empty() || line.front() == '#')+            continue;+        std::size_t glob_end = 0;+        while (glob_end < line.size() && line[glob_end] != ' ' && line[glob_end] != '\t')+            ++glob_end;+        const std::string_view glob = line.substr(0, glob_end);+        std::string_view base = glob;+        if (const auto slash = glob.rfind('/'); slash != std::string_view::npos)+            base = glob.substr(slash + 1);+        const bool matched = glob_match(glob, path) ||+                             (glob.find('/') == std::string_view::npos && glob_match(base, path));+        if (!matched)+            continue;+        std::size_t t = glob_end;+        while (t < line.size()) {+            while (t < line.size() && (line[t] == ' ' || line[t] == '\t'))+                ++t;+            const std::size_t tok_start = t;+            while (t < line.size() && line[t] != ' ' && line[t] != '\t')+                ++t;+            const std::string_view token = line.substr(tok_start, t - tok_start);+            const auto eq = token.find('=');+            if (eq != std::string_view::npos) {+                const std::string_view key = token.substr(0, eq);+                const std::string_view value = token.substr(eq + 1);+                if (key == "merge") {+                    if (value == "binary")+                        result = true;+                    else if (value == "text")+                        result = false;+                }+            }+        }+    }+    return result;+}++std::optional<Id> resolution_lookup(const fs::path& repo, Bytes body) {+    const auto digest = blake3_hash(body);+    const std::string key = hex_encode(Bytes(digest.data(), digest.size()));+    auto data = read_file_opt(resolutions_dir(repo) / key);+    if (!data || data->size() < 64)+        return std::nullopt;+    const std::string_view text(reinterpret_cast<const char*>(data->data()), 64);+    Id id{};+    if (!hex_decode(text, MutBytes(id.data(), id.size())))+        return std::nullopt;+    return id;+}++void resolution_record(const fs::path& repo, Bytes body, const Id& blob) {+    const auto digest = blake3_hash(body);+    const std::string key = hex_encode(Bytes(digest.data(), digest.size()));+    (void)write_file(resolutions_dir(repo) / key, bytes_of(hex_encode(blob)));+}++Id build_level(Txn& tx, const std::vector<OutEntry>& entries, std::size_t start, std::size_t end,+               std::size_t prefix_len) {+    std::vector<TreeEntry> out;+    std::size_t i = start;+    while (i < end) {+        const OutEntry& entry = entries[i];+        const std::size_t name_end = entry.path.find('/', prefix_len);+        const std::size_t cut = name_end == std::string::npos ? entry.path.size() : name_end;+        const std::string name = entry.path.substr(prefix_len, cut - prefix_len);+        if (cut == entry.path.size()) {+            out.push_back(TreeEntry{name, entry.kind, entry.target});+            ++i;+        } else {+            std::size_t j = i + 1;+            while (j < end) {+                const std::size_t other_end = entries[j].path.find('/', prefix_len);+                const std::size_t other_cut =+                    other_end == std::string::npos ? entries[j].path.size() : other_end;+                if (other_cut != cut ||+                    entries[j].path.compare(prefix_len, cut - prefix_len, name) != 0)+                    break;+                ++j;+            }+            const Id child = build_level(tx, entries, i, j, cut + 1);+            out.push_back(TreeEntry{name, KIND_SUBTREE, child});+            i = j;+        }+    }+    return add_tree(tx, out);+}++Id build_from_entries(Txn& tx, std::vector<OutEntry>& entries) {+    if (entries.empty())+        return add_empty_tree(tx);+    std::stable_sort(entries.begin(), entries.end(), [](const OutEntry& a, const OutEntry& b) {+        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+    });+    return build_level(tx, entries, 0, entries.size(), 0);+}++Id build_subtree(Txn& tx, const std::vector<OrigEntry>& canon, std::size_t term,+                 std::string_view prefix) {+    std::vector<OutEntry> rels;+    for (const auto& entry : canon) {+        if (entry.term != term)+            continue;+        if (entry.path.size() > prefix.size() &&+            entry.path.compare(0, prefix.size(), prefix) == 0 && entry.path[prefix.size()] == '/')+            rels.push_back(+                OutEntry{entry.path.substr(prefix.size() + 1), entry.kind, entry.target});+    }+    return build_from_entries(tx, rels);+}++bool has_prefix(std::string_view path, std::string_view prefix) {+    return path.size() > prefix.size() && path.compare(0, prefix.size(), prefix) == 0 &&+           path[prefix.size()] == '/';+}++std::optional<OutEntry> merge_entry(const fs::path& repo, Txn& tx, Store& store,+                                    const std::string& path, const std::vector<EntryTerm>& terms,+                                    bool adjacent, std::size_t& rerere) {+    std::vector<ConflictValue> adds;+    std::vector<ConflictValue> removes;+    for (const auto& term : terms) {+        ConflictValue value;+        if (term.present) {+            value.kind = term.kind;+            value.target = term.target;+        }+        if (term.positive)+            adds.push_back(value);+        else+            removes.push_back(value);+    }+    Conflict sum = simplify(store, adds, removes);+    if (auto value = resolved(sum)) {+        if (value->kind == 0)+            return std::nullopt;+        return OutEntry{path, value->kind, *value->target};+    }+    if (all_files(sum) && sum.adds.size() == 2 && sum.removes.size() == 1 &&+        sum.adds[0].kind != 0 && sum.adds[1].kind != 0 && sum.removes[0].kind != 0 &&+        !merge_binary(repo, path)) {+        auto merged = merge_blobs(store, &tx, *sum.removes[0].target, *sum.adds[0].target,+                                  *sum.adds[1].target, adjacent);+        if (merged && !merged->conflicted) {+            const Id blob = add_blob(tx, bytes_of(merged->data));+            const int mode = merge_mode(sum);+            if (mode >= 0)+                return OutEntry{+                    path, static_cast<std::uint8_t>(mode == 1 ? KIND_EXECUTABLE : KIND_FILE), blob};+        }+    }+    const auto body = encode_conflict(sum);+    if (all_files(sum)) {+        if (auto memo = resolution_lookup(repo, bytes_of(body))) {+            ++rerere;+            return OutEntry{path, KIND_FILE, *memo};+        }+    }+    const Id id = tx.add_object(TYPE_CONFLICT, body);+    return OutEntry{path, KIND_CONFLICT, id};+}++MergeOutcome treemerge(const fs::path& repo, Txn& tx, Store& store,+                       const std::vector<TreeTerm>& terms, const std::vector<RenameMap>& maps,+                       bool adjacent) {+    std::vector<OrigEntry> orig;+    for (std::size_t t = 0; t < terms.size(); ++t) {+        if (!terms[t].present)+            continue;+        for (const auto& entry : flatten_any_sorted(store, &tx, terms[t].id))+            orig.push_back(OrigEntry{t, entry.path, entry.kind, entry.target});+    }++    auto canonical_targets =+        [&](const std::string& path) -> std::vector<std::pair<std::size_t, std::string>> {+        std::vector<std::pair<std::size_t, std::string>> out;+        for (std::size_t i = 0; i < maps.size(); ++i) {+            auto dest = rename_lookup(maps[i], path);+            if (!dest)+                continue;+            bool exists = false;+            for (const auto& item : out) {+                if (item.second == *dest) {+                    exists = true;+                    break;+                }+            }+            if (!exists)+                out.emplace_back(i, *dest);+        }+        return out;+    };++    auto find_orig = [&](std::size_t term, const std::string& path) -> const OrigEntry* {+        for (const auto& entry : orig) {+            if (entry.term == term && entry.path == path)+                return &entry;+        }+        return nullptr;+    };++    std::vector<OrigEntry> canon;+    std::vector<std::string> special;+    std::vector<std::string> consumed;+    auto mark_consumed = [&](const std::string& path) {+        for (const auto& item : consumed) {+            if (item == path)+                return;+        }+        consumed.push_back(path);+    };+    for (const auto& entry : orig) {+        auto targets = canonical_targets(entry.path);+        if (targets.size() > 1) {+            bool seen = false;+            for (const auto& item : special) {+                if (item == entry.path) {+                    seen = true;+                    break;+                }+            }+            if (!seen)+                special.push_back(entry.path);+        }+        const std::string& canonical = targets.size() == 1 ? targets[0].second : entry.path;+        canon.push_back(OrigEntry{entry.term, canonical, entry.kind, entry.target});+    }++    std::vector<OutEntry> out;+    std::size_t rerere = 0;++    for (const auto& sp : special) {+        auto targets = canonical_targets(sp);+        std::vector<EntryTerm> ets;+        for (const auto& target : targets) {+            EntryTerm term;+            term.positive = true;+            if (const OrigEntry* found = find_orig(target.first, target.second)) {+                term.present = true;+                term.kind = found->kind;+                term.target = found->target;+            }+            ets.push_back(term);+            mark_consumed(target.second);+        }+        std::ptrdiff_t base_term = -1;+        for (std::size_t ti = 0; ti < terms.size(); ++ti) {+            if (!terms[ti].positive) {+                base_term = static_cast<std::ptrdiff_t>(ti);+                break;+            }+        }+        if (base_term >= 0) {+            EntryTerm term;+            term.positive = false;+            if (const OrigEntry* found = find_orig(static_cast<std::size_t>(base_term), sp)) {+                term.present = true;+                term.kind = found->kind;+                term.target = found->target;+            }+            ets.push_back(term);+        }+        if (auto merged = merge_entry(repo, tx, store, sp, ets, adjacent, rerere))+            out.push_back(std::move(*merged));+        mark_consumed(sp);+    }++    auto find_canon = [&](std::size_t term, const std::string& path) -> const OrigEntry* {+        for (const auto& entry : canon) {+            if (entry.term == term && entry.path == path)+                return &entry;+        }+        return nullptr;+    };++    std::vector<std::string> paths;+    for (const auto& entry : canon) {+        bool seen = false;+        for (const auto& path : paths) {+            if (path == entry.path) {+                seen = true;+                break;+            }+        }+        if (!seen)+            paths.push_back(entry.path);+    }+    std::sort(paths.begin(), paths.end(), [](const std::string& a, const std::string& b) {+        return compare(bytes_of(a), bytes_of(b)) < 0;+    });++    auto is_consumed = [&](const std::string& path) {+        for (const auto& item : consumed) {+            if (item == path)+                return true;+        }+        return false;+    };++    for (const auto& path : paths) {+        if (is_consumed(path))+            continue;+        bool any_exact = false;+        bool any_children = false;+        for (std::size_t t = 0; t < terms.size(); ++t) {+            if (find_canon(t, path))+                any_exact = true;+            for (const auto& entry : canon) {+                if (entry.term == t && has_prefix(entry.path, path)) {+                    any_children = true;+                    break;+                }+            }+        }+        if (!any_exact)+            continue;+        const bool mixed = any_children;+        std::vector<EntryTerm> ets;+        for (std::size_t t = 0; t < terms.size(); ++t) {+            EntryTerm term;+            term.positive = terms[t].positive;+            if (const OrigEntry* exact = find_canon(t, path)) {+                term.present = true;+                term.kind = exact->kind;+                term.target = exact->target;+            } else if (mixed) {+                bool children = false;+                for (const auto& entry : canon) {+                    if (entry.term == t && has_prefix(entry.path, path)) {+                        children = true;+                        break;+                    }+                }+                if (children) {+                    term.present = true;+                    term.kind = KIND_SUBTREE;+                    term.target = build_subtree(tx, canon, t, path);+                }+            }+            ets.push_back(term);+        }+        if (auto merged = merge_entry(repo, tx, store, path, ets, adjacent, rerere))+            out.push_back(std::move(*merged));+        if (mixed) {+            for (const auto& entry : canon) {+                if (has_prefix(entry.path, path))+                    mark_consumed(entry.path);+            }+        }+    }++    return MergeOutcome{build_from_entries(tx, out), rerere};+}++// ---------------------------------------------------------------------------+// Commit-level merge helpers+// ---------------------------------------------------------------------------++bool contains_id_vec(const std::vector<Id>& ids, const Id& id) {+    for (const auto& candidate : ids) {+        if (same_id(candidate, id))+            return true;+    }+    return false;+}++std::vector<Id> merge_bases(Store& store, const Id& a, const Id& b) {+    const std::vector<Id> aa = collect_commits(store, std::vector<Id>{a});+    const std::vector<Id> bb = collect_commits(store, std::vector<Id>{b});+    std::vector<Id> common;+    for (const auto& x : aa) {+        if (contains_id_vec(bb, x))+            common.push_back(x);+    }+    std::vector<Id> out;+    for (const auto& c : common) {+        bool dominated = false;+        for (const auto& d : common) {+            if (same_id(c, d))+                continue;+            const auto descendants = collect_commits(store, std::vector<Id>{c});+            if (contains_id_vec(descendants, d)) {+                dominated = true;+                break;+            }+        }+        if (!dominated)+            out.push_back(c);+    }+    return out;+}++bool is_ancestor(Store& store, const Id& ancestor, const Id& descendant) {+    if (same_id(ancestor, descendant))+        return true;+    return contains_id_vec(collect_commits(store, std::vector<Id>{descendant}), ancestor);+}++std::optional<Id> base_tree(const fs::path& repo, Txn& tx, Store& store,+                            const std::vector<Id>& bases, bool adjacent);++std::optional<Id> base_tree(const fs::path& repo, Txn& tx, Store& store,+                            const std::vector<Id>& bases, bool adjacent) {+    if (bases.empty())+        return std::nullopt;+    if (bases.size() == 1)+        return tree_of(store, bases.front());+    auto t0 = tree_of(store, bases[0]);+    auto t1 = tree_of(store, bases[1]);+    const auto lcas = merge_bases(store, bases[0], bases[1]);+    std::vector<TreeTerm> terms;+    terms.push_back(TreeTerm{true, t0.has_value(), t0.value_or(Id{})});+    terms.push_back(TreeTerm{true, t1.has_value(), t1.value_or(Id{})});+    if (!lcas.empty()) {+        auto lt = tree_of(store, lcas.front());+        terms.push_back(TreeTerm{false, lt.has_value(), lt.value_or(Id{})});+    } else {+        terms.push_back(TreeTerm{false, false, Id{}});+    }+    std::vector<RenameMap> maps(3);+    return treemerge(repo, tx, store, terms, maps, adjacent).tree;+}++MergeOutcome merge_many(const fs::path& repo, Txn& tx, Store& store, const std::vector<Id>& heads,+                        bool adjacent) {+    if (heads.size() == 1) {+        auto t = tree_of(store, heads.front());+        std::vector<TreeTerm> terms{TreeTerm{true, t.has_value(), t.value_or(Id{})}};+        return treemerge(repo, tx, store, terms, {RenameMap{}}, adjacent);+    }+    std::vector<TreeTerm> terms;+    std::vector<RenameMap> maps;+    std::optional<Id> map_base;+    if (heads.size() > 1) {+        const auto bases = merge_bases(store, heads[0], heads[1]);+        if (!bases.empty())+            map_base = bases.front();+    }+    for (const auto& head : heads) {+        auto t = tree_of(store, head);+        terms.push_back(TreeTerm{true, t.has_value(), t.value_or(Id{})});+        if (map_base)+            maps.push_back(map_from(store, *map_base, head));+        else+            maps.push_back(RenameMap{});+    }+    for (std::size_t i = 1; i < heads.size(); ++i) {+        const auto bases = merge_bases(store, heads[0], heads[i]);+        auto bt = base_tree(repo, tx, store, bases, adjacent);+        if (bt)+            terms.push_back(TreeTerm{false, true, *bt});+        else+            terms.push_back(TreeTerm{false, false, Id{}});+        maps.push_back(RenameMap{});+    }+    return treemerge(repo, tx, store, terms, maps, adjacent);+}++MergeOutcome rewrite_tree(const fs::path& repo, Txn& tx, Store& store, const Id& old_commit,+                          const Id& commit_tree, const std::vector<Id>& old_parents,+                          const std::vector<Id>& new_parents,+                          const std::vector<Id>& new_parent_trees, bool adjacent) {+    std::vector<TreeTerm> terms;+    std::vector<RenameMap> maps;+    terms.push_back(TreeTerm{true, true, commit_tree});+    if (!old_parents.empty())+        maps.push_back(map_from(store, old_parents.front(), old_commit));+    else+        maps.push_back(RenameMap{});++    if (old_parents.empty()) {+        for (const auto& tree : new_parent_trees) {+            terms.push_back(TreeTerm{true, true, tree});+            maps.push_back(RenameMap{});+        }+        terms.push_back(TreeTerm{false, false, Id{}});+        maps.push_back(RenameMap{});+    } else {+        for (std::size_t i = 0; i < old_parents.size(); ++i) {+            auto old_tree = tree_of(store, old_parents[i]);+            const Id new_tree = i < new_parent_trees.size() ? new_parent_trees[i] : Id{};+            terms.push_back(TreeTerm{true, true, new_tree});+            terms.push_back(TreeTerm{false, old_tree.has_value(), old_tree.value_or(Id{})});+            if (i < new_parents.size())+                maps.push_back(map_from(store, old_parents[i], new_parents[i]));+            else+                maps.push_back(RenameMap{});+            maps.push_back(RenameMap{});+        }+    }+    return treemerge(repo, tx, store, terms, maps, adjacent);+}++Id make_commit(Txn& tx, Store& store, const fs::path& repo, const std::vector<Id>& parents,+               const Id& root, const ChangeId& change, const Sig& author,+               const std::string& message, std::uint8_t renames_state,+               const std::vector<KeyValue>& extra) {+    Commit commit;+    commit.version = 1;+    commit.parents = parents;+    commit.root_tree = root;+    commit.change_id = change;+    commit.author = author;+    commit.committer = identity_signature(repo);+    commit.message = message;+    commit.renames_state = renames_state;+    commit.extra = extra;+    if (renames_state == RENAMES_RECORDED) {+        for (std::size_t i = 0; i < parents.size(); ++i) {+            auto parent_tree = tree_of(store, parents[i]);+            auto detected = detect_renames(store, &tx, parent_tree, std::optional<Id>{root}, 0, i);+            for (auto& rename : detected)+                commit.renames.push_back(std::move(rename));+        }+    }+    return tx.add_object(TYPE_COMMIT, encode_commit(commit));+}++std::string rerere_suffix(std::size_t count) {+    if (count == 0)+        return std::string();+    return " (rerere " + std::to_string(count) + ")";+}++std::string join_revs(const std::vector<std::string>& revs) {+    std::string out;+    for (std::size_t i = 0; i < revs.size(); ++i) {+        if (i != 0)+            out.push_back(' ');+        out += revs[i];+    }+    return out;+}++bool adjacent_config(const fs::path& root) {+    auto value = repo_config_value(root, "merge.adjacent");+    return value && *value == "merge";+}++// ---------------------------------------------------------------------------+// Tree editing+// ---------------------------------------------------------------------------++std::optional<Id> tree_edit_into(Txn& tx, Store& store, const Id& tree_id, std::string_view path,+                                 bool present, std::uint8_t kind, const Id& target,+                                 std::size_t depth) {+    if (depth > 4096)+        return std::nullopt;+    auto body = read_body_any(store, &tx, TYPE_TREE, tree_id);+    if (!body)+        return std::nullopt;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return std::nullopt;+    const std::size_t cut = path.find('/');+    const std::size_t cut_pos = cut == std::string_view::npos ? path.size() : cut;+    const std::string_view name = path.substr(0, cut_pos);+    std::vector<TreeEntry> entries;+    bool found = false;+    for (const auto& entry : tree->entries) {+        if (entry.name != name) {+            entries.push_back(entry);+            continue;+        }+        found = true;+        if (cut_pos == path.size()) {+            if (present)+                entries.push_back(TreeEntry{entry.name, kind, target});+        } else if (entry.kind == KIND_SUBTREE) {+            auto child = tree_edit_into(tx, store, entry.target, path.substr(cut_pos + 1), present,+                                        kind, target, depth + 1);+            if (child && !tree_empty_any(store, &tx, *child))+                entries.push_back(TreeEntry{entry.name, KIND_SUBTREE, *child});+        } else {+            entries.push_back(entry);+        }+    }+    if (!found && cut_pos == path.size() && present)+        entries.push_back(TreeEntry{std::string(name), kind, target});+    return add_tree(tx, entries);+}++std::optional<Id> tree_edit_replace(Txn& tx, Store& store, const Id& root, std::string_view path,+                                    bool present, std::uint8_t kind, const Id& target) {+    auto edited = tree_edit_into(tx, store, root, path, present, kind, target, 0);+    if (!edited)+        return std::nullopt;+    return edited;+}++// ---------------------------------------------------------------------------+// Conflicts+// ---------------------------------------------------------------------------++std::string conflict_kind_label(const Conflict& conflict) {+    for (const auto& value : conflict.adds) {+        if (value.kind == KIND_SUBTREE)+            return "tree";+    }+    for (const auto& value : conflict.removes) {+        if (value.kind == KIND_SUBTREE)+            return "tree";+    }+    for (const auto& value : conflict.adds) {+        if (value.kind == 0)+            return "delete/modify";+    }+    for (const auto& value : conflict.removes) {+        if (value.kind == 0)+            return "delete/modify";+    }+    return "text";+}++void print_range(std::size_t a, std::size_t b) {+    if (a == b)+        std::cout << a + 1;+    else+        std::cout << a + 1 << "-" << b;+}++std::optional<EditResult> conflict_ranges(Store& store, const Conflict& conflict, bool adjacent) {+    if (conflict.adds.size() != 2 || conflict.removes.size() != 1)+        return std::nullopt;+    const auto& ours = conflict.adds[0];+    const auto& theirs = conflict.adds[1];+    const auto& base = conflict.removes[0];+    if (ours.kind == 0 || theirs.kind == 0 || base.kind == 0)+        return std::nullopt;+    if (ours.kind == KIND_SUBTREE || theirs.kind == KIND_SUBTREE || base.kind == KIND_SUBTREE)+        return std::nullopt;+    return merge_blobs(store, nullptr, *base.target, *ours.target, *theirs.target, adjacent);+}++std::vector<FlatEntry> flatten_store(Store& store, const Id& tree) {+    return flatten_any_sorted(store, nullptr, std::optional<Id>{tree});+}++// ---------------------------------------------------------------------------+// Commands+// ---------------------------------------------------------------------------++int merge_command(const std::vector<std::string>& revs) {+    if (revs.empty()) {+        error_prefix();+        std::cout << "merge requires at least one revision\n";+        return 1;+    }+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;++    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    if (!wc) {+        error_prefix();+        std::cout << "no working-copy commit to merge into\n";+        return 1;+    }++    std::vector<Id> parents{*wc};+    bool failed = false;+    for (const auto& rev : revs) {+        auto resolved = resolve_revision(store, tx->view(), rev);+        if (!resolved) {+            failed = true;+            continue;+        }+        if (same_id(*resolved, *wc)) {+            error_prefix();+            std::cout << "cannot merge a commit with itself\n";+            failed = true;+            continue;+        }+        parents.push_back(*resolved);+    }+    if (failed) {+        error_prefix();+        std::cout << "unknown revision\n";+        return 1;+    }++    const auto old_root = tree_of(store, *wc);+    const bool adjacent = adjacent_config(*root);+    MergeOutcome outcome = merge_many(*root, *tx, store, parents, adjacent);+    const Sig author = identity_signature(*root);+    const Id new_id = make_commit(*tx, store, *root, parents, outcome.tree, random_change_id(),+                                  author, "", RENAMES_RECORDED, {});++    remove_head(tx->view(), *wc);+    move_bookmarks(tx->view(), *wc, new_id);+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view());+    const std::string description = "merge " + join_revs(revs) + rerere_suffix(outcome.rerere);+    const auto status = tx->finish(description);+    if (!status)+        return 1;+    store.refresh(*root);+    (void)mark_native(*root, new_id);+    if (old_root)+        return checkout_materialize_commit(*root, store, old_root, outcome.tree);+    return 0;+}++int rebase_command(const std::string& source, const std::string& dest) {+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;++    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    auto src = resolve_revision(store, tx->view(), source);+    auto dst = resolve_revision(store, tx->view(), dest);+    if (!src || !dst) {+        error_prefix();+        std::cout << "unknown revision\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    std::optional<Id> old_wc_root;+    if (wc)+        old_wc_root = tree_of(store, *wc);++    std::vector<Id> set;+    for (const auto& commit : all_commits(store, tx->view())) {+        if (is_ancestor(store, *src, commit))+            set.push_back(commit);+    }++    std::vector<Id> old_ids;+    std::vector<Id> new_ids;+    std::vector<Id> new_tree_ids;+    std::vector<Id> remaining = set;+    std::size_t rerere_total = 0;+    const bool adjacent = adjacent_config(*root);+    const Sig fallback_sig = identity_signature(*root);+    (void)fallback_sig;++    while (!remaining.empty()) {+        std::ptrdiff_t ready_idx = -1;+        for (std::size_t i = 0; i < remaining.size(); ++i) {+            bool ready = true;+            auto loaded = load_commit(store, remaining[i]);+            if (!loaded)+                continue;+            for (const auto& parent : loaded->commit.parents) {+                if (contains_id_vec(set, parent) && !contains_id_vec(old_ids, parent) &&+                    !same_id(remaining[i], *src))+                    ready = false;+            }+            if (ready) {+                ready_idx = static_cast<std::ptrdiff_t>(i);+                break;+            }+        }+        if (ready_idx < 0) {+            error_prefix();+            std::cout << "rebase could not order commits\n";+            break;+        }+        const Id chosen = remaining[static_cast<std::size_t>(ready_idx)];+        auto loaded = load_commit(store, chosen);+        if (!loaded)+            break;++        std::vector<Id> new_parents;+        std::vector<Id> new_parent_trees;+        for (std::size_t pi = 0; pi < loaded->commit.parents.size(); ++pi) {+            const Id parent = loaded->commit.parents[pi];+            if (pi == 0 && same_id(chosen, *src)) {+                new_parents.push_back(*dst);+                new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));+                continue;+            }+            bool mapped = false;+            for (std::size_t mi = 0; mi < old_ids.size(); ++mi) {+                if (same_id(old_ids[mi], parent)) {+                    new_parents.push_back(new_ids[mi]);+                    new_parent_trees.push_back(new_tree_ids[mi]);+                    mapped = true;+                    break;+                }+            }+            if (!mapped) {+                new_parents.push_back(parent);+                new_parent_trees.push_back(tree_of(store, parent).value_or(Id{}));+            }+        }+        if (loaded->commit.parents.empty()) {+            new_parents.push_back(*dst);+            new_parent_trees.push_back(tree_of(store, *dst).value_or(Id{}));+        }++        MergeOutcome outcome =+            rewrite_tree(*root, *tx, store, chosen, loaded->commit.root_tree,+                         loaded->commit.parents, new_parents, new_parent_trees, adjacent);+        rerere_total += outcome.rerere;+        const Id new_id =+            make_commit(*tx, store, *root, new_parents, outcome.tree, loaded->commit.change_id,+                        loaded->commit.author, loaded->commit.message, loaded->commit.renames_state,+                        loaded->commit.extra);+        old_ids.push_back(chosen);+        new_ids.push_back(new_id);+        new_tree_ids.push_back(outcome.tree);+        remaining.erase(remaining.begin() + static_cast<std::ptrdiff_t>(ready_idx));+    }++    auto remap = [&](std::optional<Id>& id) {+        if (!id)+            return;+        for (std::size_t i = 0; i < old_ids.size(); ++i) {+            if (same_id(old_ids[i], *id)) {+                id = new_ids[i];+                return;+            }+        }+    };+    for (auto& bookmark : tx->view().bookmarks) {+        for (auto& id : bookmark.targets.adds)+            remap(id);+        for (auto& id : bookmark.targets.removes)+            remap(id);+    }+    for (auto& tag : tx->view().tags) {+        std::optional<Id> target = tag.target;+        remap(target);+        if (target)+            tag.target = *target;+    }+    for (auto& workspace : tx->view().working_copies) {+        std::optional<Id> target = workspace.target;+        remap(target);+        if (target)+            workspace.target = *target;+    }+    rebuild_heads(tx->view());+    const auto status =+        tx->finish("rebase " + source + " onto " + dest + rerere_suffix(rerere_total));+    if (!status)+        return 1;+    for (const auto& id : new_ids)+        (void)mark_native(*root, id);+    if (wc) {+        for (std::size_t i = 0; i < old_ids.size(); ++i) {+            if (same_id(old_ids[i], *wc)) {+                Store refreshed = Store::open_all(*root);+                return checkout_materialize_commit(*root, refreshed, old_wc_root, new_tree_ids[i]);+            }+        }+    }+    return 0;+}++int xs_command(bool porcelain) {+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    std::vector<std::pair<std::string, Conflict>> items;+    if (const auto wc = working_copy_id(*view)) {+        auto loaded = load_commit(store, *wc);+        if (loaded) {+            for (const auto& entry : flatten_store(store, loaded->commit.root_tree)) {+                if (entry.kind != KIND_CONFLICT)+                    continue;+                auto body = store.read_body(entry.target, TYPE_CONFLICT);+                if (!body)+                    continue;+                auto conflict = decode_conflict(bytes_of(*body));+                if (!conflict)+                    continue;+                items.emplace_back(entry.path, std::move(*conflict));+            }+        }+    }+    const bool adjacent = adjacent_config(*root);+    bool first = true;+    for (const auto& [path, conflict] : items) {+        const std::string kind = conflict_kind_label(conflict);+        auto ranges = conflict_ranges(store, conflict, adjacent);+        if (porcelain) {+            std::cout << path << "\t" << kind << "\t";+            if (ranges) {+                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+                    if (i > 0)+                        std::cout << ",";+                    print_range(ranges->ranges[i].base_start, ranges->ranges[i].base_end);+                }+                std::cout << "\t";+                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+                    if (i > 0)+                        std::cout << ",";+                    print_range(ranges->ranges[i].ours_start, ranges->ranges[i].ours_end);+                }+                std::cout << "\t";+                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+                    if (i > 0)+                        std::cout << ",";+                    print_range(ranges->ranges[i].theirs_start, ranges->ranges[i].theirs_end);+                }+            } else {+                std::cout << "\t\t";+            }+            std::cout << "\n";+        } else {+            std::cout << path << ": " << kind << " conflict";+            if (ranges && !ranges->ranges.empty()) {+                std::cout << " (";+                for (std::size_t i = 0; i < ranges->ranges.size(); ++i) {+                    if (i > 0)+                        std::cout << ", ";+                    std::cout << "base ";+                    print_range(ranges->ranges[i].base_start, ranges->ranges[i].base_end);+                    std::cout << ", ours ";+                    print_range(ranges->ranges[i].ours_start, ranges->ranges[i].ours_end);+                    std::cout << ", theirs ";+                    print_range(ranges->ranges[i].theirs_start, ranges->ranges[i].theirs_end);+                }+                std::cout << ")";+            }+            std::cout << "\n";+        }+        first = false;+    }+    if (first) {+        info_prefix();+        std::cout << "no conflicts\n";+    }+    return 0;+}++std::string shell_replace(std::string_view command, std::string_view key,+                          const std::string& value) {+    std::string out;+    std::size_t i = 0;+    while (i < command.size()) {+        if (i + key.size() <= command.size() && command.compare(i, key.size(), key) == 0) {+            out.push_back('\'');+            out += value;+            out.push_back('\'');+            i += key.size();+        } else {+            out.push_back(command[i]);+            ++i;+        }+    }+    return out;+}++bool run_tool(const fs::path& root, std::string_view command, std::string_view path) {+    const std::string base = path_to_bytes(root / path_from_bytes(path));+    std::string expanded(command);+    expanded = shell_replace(expanded, "$BASE", base + ".base");+    expanded = shell_replace(expanded, "$OURS", base + ".ours");+    expanded = shell_replace(expanded, "$THEIRS", base + ".theirs");+    expanded = shell_replace(expanded, "$OUTPUT", base);+    return std::system(expanded.c_str()) == 0;+}++void delete_sidecar(const fs::path& root, std::string_view path, std::string_view suffix) {+    std::string full(path);+    full += suffix;+    (void)remove_file(root / path_from_bytes(full));+}++void delete_sidecars(const fs::path& root, std::string_view path) {+    delete_sidecar(root, path, ".base");+    delete_sidecar(root, path, ".ours");+    delete_sidecar(root, path, ".theirs");+    for (int n = 2; n <= 64; ++n) {+        delete_sidecar(root, path, ".base" + std::to_string(n));+        delete_sidecar(root, path, ".theirs" + std::to_string(n));+    }+}++std::optional<ConflictValue> choose_value(const Conflict& conflict, std::string_view take) {+    if (take == "ours" && !conflict.adds.empty())+        return conflict.adds[0];+    if (take == "theirs" && conflict.adds.size() > 1)+        return conflict.adds[1];+    if (take == "base" && !conflict.removes.empty())+        return conflict.removes[0];+    return std::nullopt;+}++int resolve_command(std::string_view take, std::string_view tool,+                    const std::vector<std::string>& paths) {+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    if (!wc) {+        error_prefix();+        std::cout << "no working-copy commit\n";+        return 1;+    }+    auto loaded = load_commit(store, *wc);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read working-copy commit\n";+        return 1;+    }+    const Id old_root = loaded->commit.root_tree;+    Id mut_root = old_root;+    bool resolved_any = false;+    std::vector<std::string> normalized_paths;++    const auto cwd = cwd_relative(*root);+    for (const auto& arg : paths) {+        auto norm = cwd ? pathspec_normalize(*root, *cwd, arg) : std::nullopt;+        if (!norm || norm->empty()) {+            error_prefix();+            std::cout << "invalid path\n";+            continue;+        }+        normalized_paths.push_back(*norm);+        auto flat = flatten_store(store, mut_root);+        const FlatEntry* entry = find_flat_entry(flat, *norm);+        if (!entry || entry->kind != KIND_CONFLICT) {+            error_prefix();+            std::cout << "not a conflicted path: " << *norm << "\n";+            continue;+        }+        auto body = store.read_body(entry->target, TYPE_CONFLICT);+        if (!body)+            continue;+        auto conflict = decode_conflict(bytes_of(*body));+        if (!conflict)+            continue;++        bool present = false;+        std::uint8_t new_kind = KIND_FILE;+        std::optional<Id> new_target;+        if (auto chosen = choose_value(*conflict, take)) {+            if (chosen->kind != 0) {+                present = true;+                new_kind = chosen->kind;+                new_target = chosen->target;+            }+        } else if (!tool.empty()) {+            if (run_tool(*root, tool, *norm)) {+                if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {+                    new_target = add_blob(*tx, bytes_of(*data));+                    present = true;+                    new_kind = KIND_FILE;+                }+            }+        } else {+            if (auto data = read_file_opt(*root / path_from_bytes(*norm))) {+                new_target = add_blob(*tx, bytes_of(*data));+                present = true;+                new_kind = KIND_FILE;+            }+        }+        if (present) {+            if (auto info = stat_path(*root / path_from_bytes(*norm))) {+                if (info->executable)+                    new_kind = KIND_EXECUTABLE;+            }+            if (new_kind == KIND_FILE || new_kind == KIND_EXECUTABLE) {+                if (auto conflict_body = store.read_body(entry->target, TYPE_CONFLICT)) {+                    resolution_record(*root, bytes_of(*conflict_body), *new_target);+                }+            }+        }+        auto replaced = tree_edit_replace(*tx, store, mut_root, *norm, present, new_kind,+                                          new_target.value_or(Id{}));+        if (replaced) {+            mut_root = *replaced;+            resolved_any = true;+        }+    }++    if (!resolved_any) {+        return 1;+    }++    Commit commit = loaded->commit;+    commit.root_tree = mut_root;+    commit.committer = identity_signature(*root);+    const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));+    remove_head(tx->view(), *wc);+    move_bookmarks(tx->view(), *wc, new_id);+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view());+    const auto status = tx->finish("resolve");+    if (!status)+        return 1;+    Store refreshed = Store::open_all(*root);+    const int materialized = checkout_materialize_commit(*root, refreshed, old_root, mut_root);+    if (materialized != 0)+        return materialized;+    for (const auto& path : normalized_paths)+        delete_sidecars(*root, path);+    return 0;+}++} // namespace++// ---------------------------------------------------------------------------+// Argument parsing+// ---------------------------------------------------------------------------++int merge_run(const std::vector<std::string>& args) {+    std::vector<std::string> revs;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && !arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            revs.push_back(arg);+        }+    }+    return merge_command(revs);+}++int rebase_run(const std::vector<std::string>& args) {+    std::string source;+    std::string dest;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-s" || arg == "-source")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            source = args[++i];+        } else if (!end_flags && (arg == "-d" || arg == "-destination")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            dest = args[++i];+        } else if (!end_flags && !arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            error_prefix();+            std::cout << "unexpected argument: " << arg << "\n";+            return 1;+        }+    }+    if (source.empty() || dest.empty()) {+        error_prefix();+        std::cout << "rebase requires -s <rev> and -d <rev>\n";+        return 1;+    }+    return rebase_command(source, dest);+}++int xs_run(const std::vector<std::string>& args) {+    bool porcelain = false;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-porcelain" || arg == "-p")) {+            porcelain = true;+        } else if (!end_flags && !arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            error_prefix();+            std::cout << "unexpected argument: " << arg << "\n";+            return 1;+        }+    }+    return xs_command(porcelain);+}++int resolve_run(const std::vector<std::string>& args) {+    std::string take;+    std::string tool;+    bool list_only = false;+    std::vector<std::string> paths;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-list" || arg == "-l")) {+            list_only = true;+        } else if (!end_flags && (arg == "-take" || arg == "-t")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires ours, theirs, or base\n";+                return 1;+            }+            take = args[++i];+        } else if (!end_flags && arg == "-tool") {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a command\n";+                return 1;+            }+            tool = args[++i];+        } else if (!end_flags && !arg.empty() && arg.front() == '-') {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            paths.push_back(arg);+        }+    }+    if (list_only)+        return xs_command(false);+    if (paths.empty()) {+        error_prefix();+        std::cout << "resolve requires at least one path\n";+        return 1;+    }+    return resolve_command(take, tool, paths); }  } // namespace vn--- a/xveins/src/merge.h+++ b/xveins/src/merge.h@@ -11,17 +11,16 @@ // Detect renames between two trees. `tx` may be provided so trees and blobs // that have only been added to the pending transaction are visible. Results are // sorted by (parent_index, to_path).-std::vector<Rename> detect_renames(Store &store, Txn *tx,-                                   std::optional<Id> old_tree,+std::vector<Rename> detect_renames(Store& store, Txn* tx, std::optional<Id> old_tree,                                    std::optional<Id> new_tree, int similar_pct,                                    std::uint64_t parent_index);  // Configured rename similarity threshold (0 disables detection).-int rename_similar_pct(const fs::path &root);+int rename_similar_pct(const fs::path& root); -int merge_run(const std::vector<std::string> &args);-int rebase_run(const std::vector<std::string> &args);-int xs_run(const std::vector<std::string> &args);-int resolve_run(const std::vector<std::string> &args);+int merge_run(const std::vector<std::string>& args);+int rebase_run(const std::vector<std::string>& args);+int xs_run(const std::vector<std::string>& args);+int resolve_run(const std::vector<std::string>& args);  } // namespace vn--- a/xveins/src/net.cpp+++ b/xveins/src/net.cpp@@ -45,70 +45,68 @@  #if defined(_WIN32) void ensure_winsock() {-  static const bool initialized = [] {-    WSADATA data{};-    return WSAStartup(MAKEWORD(2, 2), &data) == 0;-  }();-  (void)initialized;+    static const bool initialized = [] {+        WSADATA data{};+        return WSAStartup(MAKEWORD(2, 2), &data) == 0;+    }();+    (void)initialized; }  std::wstring widen_utf8(std::string_view text) {-  if (text.empty())-    return {};-  const int len = MultiByteToWideChar(-      CP_UTF8, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);-  std::wstring out(static_cast<std::size_t>(len), L'\0');-  MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()),-                      out.data(), len);-  return out;+    if (text.empty())+        return {};+    const int len =+        MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);+    std::wstring out(static_cast<std::size_t>(len), L'\0');+    MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), out.data(), len);+    return out; }  // Quote one argument for CreateProcessW's command line. std::wstring quote_windows_arg(std::wstring_view arg) {-  if (!arg.empty() &&-      arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)-    return std::wstring(arg);-  std::wstring out = L"\"";-  for (std::size_t i = 0; i < arg.size(); ++i) {-    std::size_t backslashes = 0;-    while (i < arg.size() && arg[i] == L'\\') {-      ++backslashes;-      ++i;-    }-    if (i == arg.size()) {-      out.append(backslashes * 2, L'\\');-      break;-    }-    if (arg[i] == L'"') {-      out.append(backslashes * 2 + 1, L'\\');-      out.push_back(L'"');-    } else {-      out.append(backslashes, L'\\');-      out.push_back(arg[i]);+    if (!arg.empty() && arg.find_first_of(L" \t\n\v\"") == std::wstring_view::npos)+        return std::wstring(arg);+    std::wstring out = L"\"";+    for (std::size_t i = 0; i < arg.size(); ++i) {+        std::size_t backslashes = 0;+        while (i < arg.size() && arg[i] == L'\\') {+            ++backslashes;+            ++i;+        }+        if (i == arg.size()) {+            out.append(backslashes * 2, L'\\');+            break;+        }+        if (arg[i] == L'"') {+            out.append(backslashes * 2 + 1, L'\\');+            out.push_back(L'"');+        } else {+            out.append(backslashes, L'\\');+            out.push_back(arg[i]);+        }     }-  }-  out.push_back(L'"');-  return out;+    out.push_back(L'"');+    return out; } -std::wstring build_windows_command_line(const std::vector<std::string> &argv) {-  std::wstring out;-  for (std::size_t i = 0; i < argv.size(); ++i) {-    if (i != 0)-      out.push_back(L' ');-    out += quote_windows_arg(widen_utf8(argv[i]));-  }-  return out;+std::wstring build_windows_command_line(const std::vector<std::string>& argv) {+    std::wstring out;+    for (std::size_t i = 0; i < argv.size(); ++i) {+        if (i != 0)+            out.push_back(L' ');+        out += quote_windows_arg(widen_utf8(argv[i]));+    }+    return out; } #endif  std::string ssl_error_string() {-  unsigned long code = ERR_get_error();-  if (code == 0)-    return {};-  char buffer[256];-  ERR_error_string_n(code, buffer, sizeof(buffer));-  return std::string(buffer);+    unsigned long code = ERR_get_error();+    if (code == 0)+        return {};+    char buffer[256];+    ERR_error_string_n(code, buffer, sizeof(buffer));+    return std::string(buffer); }  } // namespace@@ -117,210 +115,212 @@ // Stream // --------------------------------------------------------------------------- -Stream::Stream(Stream &&other) noexcept { *this = std::move(other); }+Stream::Stream(Stream&& other) noexcept {+    *this = std::move(other);+} -Stream &Stream::operator=(Stream &&other) noexcept {-  if (this == &other)-    return *this;-  close();-  kind_ = other.kind_;-  fd_in_ = other.fd_in_;-  fd_out_ = other.fd_out_;-  ssl_ = other.ssl_;+Stream& Stream::operator=(Stream&& other) noexcept {+    if (this == &other)+        return *this;+    close();+    kind_ = other.kind_;+    fd_in_ = other.fd_in_;+    fd_out_ = other.fd_out_;+    ssl_ = other.ssl_; #if defined(_WIN32)-  process_ = other.process_;-  process_id_ = other.process_id_;+    process_ = other.process_;+    process_id_ = other.process_id_; #else-  pid_ = other.pid_;+    pid_ = other.pid_; #endif-  open_ = other.open_;-  other.open_ = false;-  other.ssl_ = nullptr;-  other.fd_in_ = 0;-  other.fd_out_ = 0;+    open_ = other.open_;+    other.open_ = false;+    other.ssl_ = nullptr;+    other.fd_in_ = 0;+    other.fd_out_ = 0; #if defined(_WIN32)-  other.process_ = nullptr;-  other.process_id_ = 0;+    other.process_ = nullptr;+    other.process_id_ = 0; #else-  other.pid_ = 0;+    other.pid_ = 0; #endif-  return *this;+    return *this; } -Stream::~Stream() { close(); }+Stream::~Stream() {+    close();+}  Stream Stream::stdio_stream() {-  Stream stream;-  stream.kind_ = Kind::Stdio;+    Stream stream;+    stream.kind_ = Kind::Stdio; #if defined(_WIN32)-  stream.fd_in_ = reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));-  stream.fd_out_ = reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE));+    stream.fd_in_ = reinterpret_cast<Socket>(GetStdHandle(STD_INPUT_HANDLE));+    stream.fd_out_ = reinterpret_cast<Socket>(GetStdHandle(STD_OUTPUT_HANDLE)); #else-  stream.fd_in_ = 0;-  stream.fd_out_ = 1;+    stream.fd_in_ = 0;+    stream.fd_out_ = 1; #endif-  stream.open_ = true;-  return stream;+    stream.open_ = true;+    return stream; }  Stream Stream::fd_stream(Socket fd) {-  Stream stream;-  stream.kind_ = Kind::Fd;-  stream.fd_in_ = fd;-  stream.fd_out_ = fd;-  stream.open_ = true;-  return stream;+    Stream stream;+    stream.kind_ = Kind::Fd;+    stream.fd_in_ = fd;+    stream.fd_out_ = fd;+    stream.open_ = true;+    return stream; } -Stream Stream::tls_stream(Socket fd, void *ssl) {-  Stream stream;-  stream.kind_ = Kind::Tls;-  stream.fd_in_ = fd;-  stream.fd_out_ = fd;-  stream.ssl_ = ssl;-  stream.open_ = true;-  return stream;+Stream Stream::tls_stream(Socket fd, void* ssl) {+    Stream stream;+    stream.kind_ = Kind::Tls;+    stream.fd_in_ = fd;+    stream.fd_out_ = fd;+    stream.ssl_ = ssl;+    stream.open_ = true;+    return stream; } -std::optional<Stream> Stream::spawn_argv(const std::vector<std::string> &argv) {-  return vn::net::spawn_argv(argv);+std::optional<Stream> Stream::spawn_argv(const std::vector<std::string>& argv) {+    return vn::net::spawn_argv(argv); } -std::int64_t Stream::read(void *buffer, std::size_t count) {-  if (!open_ || count == 0)-    return count == 0 ? 0 : -1;-  if (kind_ == Kind::Tls) {-    const int n = SSL_read(static_cast<SSL *>(ssl_), buffer,-                           static_cast<int>(std::min<std::size_t>(-                               count, static_cast<std::size_t>(INT_MAX))));-    if (n > 0)-      return n;-    if (n == 0)-      return 0;-    return -1;-  }+std::int64_t Stream::read(void* buffer, std::size_t count) {+    if (!open_ || count == 0)+        return count == 0 ? 0 : -1;+    if (kind_ == Kind::Tls) {+        const int n = SSL_read(+            static_cast<SSL*>(ssl_), buffer,+            static_cast<int>(std::min<std::size_t>(count, static_cast<std::size_t>(INT_MAX))));+        if (n > 0)+            return n;+        if (n == 0)+            return 0;+        return -1;+    } #if defined(_WIN32)-  if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {-    DWORD got = 0;-    if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,-                  static_cast<DWORD>(std::min<std::size_t>(-                      count, static_cast<std::size_t>(MAXDWORD))),-                  &got, nullptr))-      return -1;-    return static_cast<std::int64_t>(got);-  }-  const int n = recv(static_cast<SOCKET>(fd_in_), static_cast<char *>(buffer),-                     static_cast<int>(std::min<std::size_t>(-                         count, static_cast<std::size_t>(INT_MAX))),-                     0);-  return n;+    if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {+        DWORD got = 0;+        if (!ReadFile(reinterpret_cast<HANDLE>(fd_in_), buffer,+                      static_cast<DWORD>(+                          std::min<std::size_t>(count, static_cast<std::size_t>(MAXDWORD))),+                      &got, nullptr))+            return -1;+        return static_cast<std::int64_t>(got);+    }+    const int n =+        recv(static_cast<SOCKET>(fd_in_), static_cast<char*>(buffer),+             static_cast<int>(std::min<std::size_t>(count, static_cast<std::size_t>(INT_MAX))), 0);+    return n; #else-  const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);-  ssize_t n = 0;-  do {-    n = ::read(fd, buffer, count);-  } while (n < 0 && errno == EINTR);-  return n;+    const int fd = kind_ == Kind::Stdio ? 0 : static_cast<int>(fd_in_);+    ssize_t n = 0;+    do {+        n = ::read(fd, buffer, count);+    } while (n < 0 && errno == EINTR);+    return n; #endif }  bool Stream::write_all(Bytes data) {-  if (!open_)-    return false;-  std::size_t offset = 0;-  while (offset < data.size()) {-    const std::size_t remaining = data.size() - offset;-    std::int64_t written = -1;-    if (kind_ == Kind::Tls) {-      const int n =-          SSL_write(static_cast<SSL *>(ssl_), data.data() + offset,-                    static_cast<int>(std::min<std::size_t>(-                        remaining, static_cast<std::size_t>(INT_MAX))));-      written = n;-    }-#if defined(_WIN32)-    else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {-      DWORD count = 0;-      if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,-                     static_cast<DWORD>(std::min<std::size_t>(-                         remaining, static_cast<std::size_t>(MAXDWORD))),-                     &count, nullptr))+    if (!open_)         return false;-      written = static_cast<std::int64_t>(count);-    } else {-      const int n = send(static_cast<SOCKET>(fd_out_),-                         reinterpret_cast<const char *>(data.data() + offset),-                         static_cast<int>(std::min<std::size_t>(-                             remaining, static_cast<std::size_t>(INT_MAX))),-                         0);-      written = n;-    }+    std::size_t offset = 0;+    while (offset < data.size()) {+        const std::size_t remaining = data.size() - offset;+        std::int64_t written = -1;+        if (kind_ == Kind::Tls) {+            const int n = SSL_write(static_cast<SSL*>(ssl_), data.data() + offset,+                                    static_cast<int>(std::min<std::size_t>(+                                        remaining, static_cast<std::size_t>(INT_MAX))));+            written = n;+        }+#if defined(_WIN32)+        else if (kind_ == Kind::Stdio || kind_ == Kind::Proc) {+            DWORD count = 0;+            if (!WriteFile(reinterpret_cast<HANDLE>(fd_out_), data.data() + offset,+                           static_cast<DWORD>(std::min<std::size_t>(+                               remaining, static_cast<std::size_t>(MAXDWORD))),+                           &count, nullptr))+                return false;+            written = static_cast<std::int64_t>(count);+        } else {+            const int n = send(static_cast<SOCKET>(fd_out_),+                               reinterpret_cast<const char*>(data.data() + offset),+                               static_cast<int>(std::min<std::size_t>(+                                   remaining, static_cast<std::size_t>(INT_MAX))),+                               0);+            written = n;+        } #else-    else {-      ssize_t n = 0;-      do {-        n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),-                    data.data() + offset, remaining);-      } while (n < 0 && errno == EINTR);-      written = n;-    }+        else {+            ssize_t n = 0;+            do {+                n = ::write(kind_ == Kind::Stdio ? 1 : static_cast<int>(fd_out_),+                            data.data() + offset, remaining);+            } while (n < 0 && errno == EINTR);+            written = n;+        } #endif-    if (written <= 0)-      return false;-    offset += static_cast<std::size_t>(written);-  }-  return true;+        if (written <= 0)+            return false;+        offset += static_cast<std::size_t>(written);+    }+    return true; }  void Stream::close() {-  if (!open_)-    return;-  open_ = false;-  if (kind_ == Kind::Tls) {-    if (ssl_)-      tls_free(ssl_);-    ssl_ = nullptr;+    if (!open_)+        return;+    open_ = false;+    if (kind_ == Kind::Tls) {+        if (ssl_)+            tls_free(ssl_);+        ssl_ = nullptr; #if defined(_WIN32)-    closesocket(static_cast<SOCKET>(fd_in_));+        closesocket(static_cast<SOCKET>(fd_in_)); #else-    if (static_cast<int>(fd_in_) > 2)-      ::close(static_cast<int>(fd_in_));+        if (static_cast<int>(fd_in_) > 2)+            ::close(static_cast<int>(fd_in_)); #endif-    return;-  }-  if (kind_ == Kind::Proc) {-#if defined(_WIN32)-    if (fd_in_ != 0)-      CloseHandle(reinterpret_cast<HANDLE>(fd_in_));-    if (fd_out_ != 0)-      CloseHandle(reinterpret_cast<HANDLE>(fd_out_));-    if (process_) {-      WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);-      CloseHandle(reinterpret_cast<HANDLE>(process_));-      process_ = nullptr;+        return;     }+    if (kind_ == Kind::Proc) {+#if defined(_WIN32)+        if (fd_in_ != 0)+            CloseHandle(reinterpret_cast<HANDLE>(fd_in_));+        if (fd_out_ != 0)+            CloseHandle(reinterpret_cast<HANDLE>(fd_out_));+        if (process_) {+            WaitForSingleObject(reinterpret_cast<HANDLE>(process_), INFINITE);+            CloseHandle(reinterpret_cast<HANDLE>(process_));+            process_ = nullptr;+        } #else-    if (static_cast<int>(fd_in_) > 2)-      ::close(static_cast<int>(fd_in_));-    if (static_cast<int>(fd_out_) > 2)-      ::close(static_cast<int>(fd_out_));-    if (pid_ > 0) {-      int status = 0;-      while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {-      }-      pid_ = 0;-    }+        if (static_cast<int>(fd_in_) > 2)+            ::close(static_cast<int>(fd_in_));+        if (static_cast<int>(fd_out_) > 2)+            ::close(static_cast<int>(fd_out_));+        if (pid_ > 0) {+            int status = 0;+            while (waitpid(pid_, &status, 0) < 0 && errno == EINTR) {+            }+            pid_ = 0;+        } #endif-    return;-  }-  if (kind_ == Kind::Fd) {+        return;+    }+    if (kind_ == Kind::Fd) { #if defined(_WIN32)-    closesocket(static_cast<SOCKET>(fd_in_));+        closesocket(static_cast<SOCKET>(fd_in_)); #else-    if (static_cast<int>(fd_in_) > 2)-      ::close(static_cast<int>(fd_in_));+        if (static_cast<int>(fd_in_) > 2)+            ::close(static_cast<int>(fd_in_)); #endif-  }+    } }  // ---------------------------------------------------------------------------@@ -328,98 +328,97 @@ // ---------------------------------------------------------------------------  #if defined(_WIN32)-std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {-  if (argv.empty())-    return std::nullopt;-  ensure_winsock();-  SECURITY_ATTRIBUTES attributes{};-  attributes.nLength = sizeof(attributes);-  attributes.bInheritHandle = TRUE;-  HANDLE child_stdin_read = nullptr;-  HANDLE child_stdin_write = nullptr;-  HANDLE child_stdout_read = nullptr;-  HANDLE child_stdout_write = nullptr;-  if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||-      !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {-    if (child_stdin_read)-      CloseHandle(child_stdin_read);-    if (child_stdin_write)-      CloseHandle(child_stdin_write);-    return std::nullopt;-  }-  SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);-  SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);-  STARTUPINFOW startup{};-  startup.cb = sizeof(startup);-  startup.dwFlags = STARTF_USESTDHANDLES;-  startup.hStdInput = child_stdin_read;-  startup.hStdOutput = child_stdout_write;-  startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);-  PROCESS_INFORMATION process{};-  std::wstring command_line = build_windows_command_line(argv);-  const BOOL started =-      CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,-                     nullptr, nullptr, &startup, &process);-  CloseHandle(child_stdin_read);-  CloseHandle(child_stdout_write);-  if (!started) {-    CloseHandle(child_stdin_write);-    CloseHandle(child_stdout_read);-    return std::nullopt;-  }-  CloseHandle(process.hThread);-  Stream stream;-  stream.kind_ = Stream::Kind::Proc;-  stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);-  stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);-  stream.process_ = process.hProcess;-  stream.process_id_ = process.dwProcessId;-  stream.open_ = true;-  return stream;+std::optional<Stream> spawn_argv(const std::vector<std::string>& argv) {+    if (argv.empty())+        return std::nullopt;+    ensure_winsock();+    SECURITY_ATTRIBUTES attributes{};+    attributes.nLength = sizeof(attributes);+    attributes.bInheritHandle = TRUE;+    HANDLE child_stdin_read = nullptr;+    HANDLE child_stdin_write = nullptr;+    HANDLE child_stdout_read = nullptr;+    HANDLE child_stdout_write = nullptr;+    if (!CreatePipe(&child_stdin_read, &child_stdin_write, &attributes, 0) ||+        !CreatePipe(&child_stdout_read, &child_stdout_write, &attributes, 0)) {+        if (child_stdin_read)+            CloseHandle(child_stdin_read);+        if (child_stdin_write)+            CloseHandle(child_stdin_write);+        return std::nullopt;+    }+    SetHandleInformation(child_stdin_write, HANDLE_FLAG_INHERIT, 0);+    SetHandleInformation(child_stdout_read, HANDLE_FLAG_INHERIT, 0);+    STARTUPINFOW startup{};+    startup.cb = sizeof(startup);+    startup.dwFlags = STARTF_USESTDHANDLES;+    startup.hStdInput = child_stdin_read;+    startup.hStdOutput = child_stdout_write;+    startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);+    PROCESS_INFORMATION process{};+    std::wstring command_line = build_windows_command_line(argv);+    const BOOL started = CreateProcessW(nullptr, command_line.data(), nullptr, nullptr, TRUE, 0,+                                        nullptr, nullptr, &startup, &process);+    CloseHandle(child_stdin_read);+    CloseHandle(child_stdout_write);+    if (!started) {+        CloseHandle(child_stdin_write);+        CloseHandle(child_stdout_read);+        return std::nullopt;+    }+    CloseHandle(process.hThread);+    Stream stream;+    stream.kind_ = Stream::Kind::Proc;+    stream.fd_in_ = reinterpret_cast<Socket>(child_stdout_read);+    stream.fd_out_ = reinterpret_cast<Socket>(child_stdin_write);+    stream.process_ = process.hProcess;+    stream.process_id_ = process.dwProcessId;+    stream.open_ = true;+    return stream; } #else-std::optional<Stream> spawn_argv(const std::vector<std::string> &argv) {-  if (argv.empty())-    return std::nullopt;-  int in_pipe[2];-  int out_pipe[2];-  if (::pipe(in_pipe) != 0)-    return std::nullopt;-  if (::pipe(out_pipe) != 0) {-    ::close(in_pipe[0]);-    ::close(in_pipe[1]);-    return std::nullopt;-  }-  std::vector<char *> raw;-  raw.reserve(argv.size() + 1);-  for (const auto &item : argv)-    raw.push_back(const_cast<char *>(item.c_str()));-  raw.push_back(nullptr);-  const pid_t pid = ::fork();-  if (pid == 0) {-    (void)::dup2(in_pipe[0], 0);-    (void)::dup2(out_pipe[1], 1);+std::optional<Stream> spawn_argv(const std::vector<std::string>& argv) {+    if (argv.empty())+        return std::nullopt;+    int in_pipe[2];+    int out_pipe[2];+    if (::pipe(in_pipe) != 0)+        return std::nullopt;+    if (::pipe(out_pipe) != 0) {+        ::close(in_pipe[0]);+        ::close(in_pipe[1]);+        return std::nullopt;+    }+    std::vector<char*> raw;+    raw.reserve(argv.size() + 1);+    for (const auto& item : argv)+        raw.push_back(const_cast<char*>(item.c_str()));+    raw.push_back(nullptr);+    const pid_t pid = ::fork();+    if (pid == 0) {+        (void)::dup2(in_pipe[0], 0);+        (void)::dup2(out_pipe[1], 1);+        ::close(in_pipe[0]);+        ::close(in_pipe[1]);+        ::close(out_pipe[0]);+        ::close(out_pipe[1]);+        ::execvp(raw[0], raw.data());+        ::_exit(127);+    }     ::close(in_pipe[0]);-    ::close(in_pipe[1]);-    ::close(out_pipe[0]);     ::close(out_pipe[1]);-    ::execvp(raw[0], raw.data());-    ::_exit(127);-  }-  ::close(in_pipe[0]);-  ::close(out_pipe[1]);-  if (pid < 0) {-    ::close(in_pipe[1]);-    ::close(out_pipe[0]);-    return std::nullopt;-  }-  Stream stream;-  stream.kind_ = Stream::Kind::Proc;-  stream.fd_in_ = out_pipe[0];-  stream.fd_out_ = in_pipe[1];-  stream.pid_ = pid;-  stream.open_ = true;-  return stream;+    if (pid < 0) {+        ::close(in_pipe[1]);+        ::close(out_pipe[0]);+        return std::nullopt;+    }+    Stream stream;+    stream.kind_ = Stream::Kind::Proc;+    stream.fd_in_ = out_pipe[0];+    stream.fd_out_ = in_pipe[1];+    stream.pid_ = pid;+    stream.open_ = true;+    return stream; } #endif @@ -428,110 +427,105 @@ // ---------------------------------------------------------------------------  std::optional<Socket> tcp_connect(std::string_view host, int port) {-  if (host.empty())-    return std::nullopt;+    if (host.empty())+        return std::nullopt; #if defined(_WIN32)-  ensure_winsock();+    ensure_winsock(); #endif-  addrinfo hints{};-  hints.ai_family = AF_UNSPEC;-  hints.ai_socktype = SOCK_STREAM;-  const std::string service = std::to_string(port);-  const std::string host_text(host);-  addrinfo *results = nullptr;-  if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)-    return std::nullopt;-  Socket connected = INVALID_SOCKET_VALUE;-  for (addrinfo *it = results; it != nullptr; it = it->ai_next) {+    addrinfo hints{};+    hints.ai_family = AF_UNSPEC;+    hints.ai_socktype = SOCK_STREAM;+    const std::string service = std::to_string(port);+    const std::string host_text(host);+    addrinfo* results = nullptr;+    if (getaddrinfo(host_text.c_str(), service.c_str(), &hints, &results) != 0)+        return std::nullopt;+    Socket connected = INVALID_SOCKET_VALUE;+    for (addrinfo* it = results; it != nullptr; it = it->ai_next) { #if defined(_WIN32)-    SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);-    if (socket == INVALID_SOCKET)-      continue;-    if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {-      connected = static_cast<Socket>(socket);-      break;-    }-    closesocket(socket);+        SOCKET socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);+        if (socket == INVALID_SOCKET)+            continue;+        if (::connect(socket, it->ai_addr, static_cast<int>(it->ai_addrlen)) == 0) {+            connected = static_cast<Socket>(socket);+            break;+        }+        closesocket(socket); #else-    const int socket =-        ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);-    if (socket < 0)-      continue;-    if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {-      connected = socket;-      break;-    }-    ::close(socket);+        const int socket = ::socket(it->ai_family, it->ai_socktype, it->ai_protocol);+        if (socket < 0)+            continue;+        if (::connect(socket, it->ai_addr, it->ai_addrlen) == 0) {+            connected = socket;+            break;+        }+        ::close(socket); #endif-  }-  freeaddrinfo(results);-  return connected == INVALID_SOCKET_VALUE ? std::nullopt-                                           : std::optional<Socket>(connected);+    }+    freeaddrinfo(results);+    return connected == INVALID_SOCKET_VALUE ? std::nullopt : std::optional<Socket>(connected); }  Socket tcp_listen(int port, int backlog) { #if defined(_WIN32)-  ensure_winsock();-  SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);-  if (listener == INVALID_SOCKET)-    return INVALID_SOCKET_VALUE;-  BOOL reuse = TRUE;-  setsockopt(listener, SOL_SOCKET, SO_REUSEADDR,-             reinterpret_cast<const char *>(&reuse), sizeof(reuse));-  sockaddr_in address{};-  address.sin_family = AF_INET;-  address.sin_addr.s_addr = htonl(INADDR_ANY);-  address.sin_port = htons(static_cast<u_short>(port));-  if (::bind(listener, reinterpret_cast<sockaddr *>(&address),-             sizeof(address)) == SOCKET_ERROR ||-      ::listen(listener, backlog) == SOCKET_ERROR) {-    closesocket(listener);-    return INVALID_SOCKET_VALUE;-  }-  return static_cast<Socket>(listener);+    ensure_winsock();+    SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+    if (listener == INVALID_SOCKET)+        return INVALID_SOCKET_VALUE;+    BOOL reuse = TRUE;+    setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuse),+               sizeof(reuse));+    sockaddr_in address{};+    address.sin_family = AF_INET;+    address.sin_addr.s_addr = htonl(INADDR_ANY);+    address.sin_port = htons(static_cast<u_short>(port));+    if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == SOCKET_ERROR ||+        ::listen(listener, backlog) == SOCKET_ERROR) {+        closesocket(listener);+        return INVALID_SOCKET_VALUE;+    }+    return static_cast<Socket>(listener); #else-  const int listener = ::socket(AF_INET, SOCK_STREAM, 0);-  if (listener < 0)-    return INVALID_SOCKET_VALUE;-  int reuse = 1;-  (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));-  sockaddr_in address{};-  address.sin_family = AF_INET;-  address.sin_addr.s_addr = htonl(INADDR_ANY);-  address.sin_port = htons(static_cast<std::uint16_t>(port));-  if (::bind(listener, reinterpret_cast<sockaddr *>(&address),-             sizeof(address)) != 0 ||-      ::listen(listener, backlog) != 0) {-    ::close(listener);-    return INVALID_SOCKET_VALUE;-  }-  return listener;+    const int listener = ::socket(AF_INET, SOCK_STREAM, 0);+    if (listener < 0)+        return INVALID_SOCKET_VALUE;+    int reuse = 1;+    (void)setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));+    sockaddr_in address{};+    address.sin_family = AF_INET;+    address.sin_addr.s_addr = htonl(INADDR_ANY);+    address.sin_port = htons(static_cast<std::uint16_t>(port));+    if (::bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 ||+        ::listen(listener, backlog) != 0) {+        ::close(listener);+        return INVALID_SOCKET_VALUE;+    }+    return listener; #endif }  std::optional<Socket> tcp_accept(Socket listener) { #if defined(_WIN32)-  const SOCKET accepted =-      ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);-  if (accepted == INVALID_SOCKET)-    return std::nullopt;-  return static_cast<Socket>(accepted);+    const SOCKET accepted = ::accept(static_cast<SOCKET>(listener), nullptr, nullptr);+    if (accepted == INVALID_SOCKET)+        return std::nullopt;+    return static_cast<Socket>(accepted); #else-  const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);-  if (accepted < 0)-    return std::nullopt;-  return accepted;+    const int accepted = ::accept(static_cast<int>(listener), nullptr, nullptr);+    if (accepted < 0)+        return std::nullopt;+    return accepted; #endif }  void close_socket(Socket socket) {-  if (socket == INVALID_SOCKET_VALUE)-    return;+    if (socket == INVALID_SOCKET_VALUE)+        return; #if defined(_WIN32)-  closesocket(static_cast<SOCKET>(socket));+    closesocket(static_cast<SOCKET>(socket)); #else-  if (static_cast<int>(socket) > 2)-    ::close(static_cast<int>(socket));+    if (static_cast<int>(socket) > 2)+        ::close(static_cast<int>(socket)); #endif } @@ -541,66 +535,64 @@  void ignore_sigpipe() { #if !defined(_WIN32)-  (void)::signal(SIGPIPE, SIG_IGN);+    (void)::signal(SIGPIPE, SIG_IGN); #endif }  fs::path self_exe() { #if defined(_WIN32)-  std::wstring buffer(32768, L'\0');-  const DWORD len = GetModuleFileNameW(nullptr, buffer.data(),-                                       static_cast<DWORD>(buffer.size()));-  if (len > 0) {-    buffer.resize(len);-    return fs::path(buffer);-  }-  return fs::path("vn.exe");+    std::wstring buffer(32768, L'\0');+    const DWORD len = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));+    if (len > 0) {+        buffer.resize(len);+        return fs::path(buffer);+    }+    return fs::path("vn.exe"); #elif defined(__APPLE__)-  std::uint32_t size = 0;-  _NSGetExecutablePath(nullptr, &size);-  std::string buffer(size, '\0');-  if (_NSGetExecutablePath(buffer.data(), &size) == 0) {-    char resolved[PATH_MAX];-    if (::realpath(buffer.c_str(), resolved))-      return fs::path(resolved);-    buffer.resize(std::strlen(buffer.c_str()));-    return fs::path(buffer);-  }-  return fs::path("vn");+    std::uint32_t size = 0;+    _NSGetExecutablePath(nullptr, &size);+    std::string buffer(size, '\0');+    if (_NSGetExecutablePath(buffer.data(), &size) == 0) {+        char resolved[PATH_MAX];+        if (::realpath(buffer.c_str(), resolved))+            return fs::path(resolved);+        buffer.resize(std::strlen(buffer.c_str()));+        return fs::path(buffer);+    }+    return fs::path("vn"); #else-  std::string buffer(4096, '\0');-  const ssize_t len =-      ::readlink("/proc/self/exe", buffer.data(), buffer.size() - 1);-  if (len > 0) {-    buffer.resize(static_cast<std::size_t>(len));-    return fs::path(buffer);-  }-  return fs::path("vn");+    std::string buffer(4096, '\0');+    const ssize_t len = ::readlink("/proc/self/exe", buffer.data(), buffer.size() - 1);+    if (len > 0) {+        buffer.resize(static_cast<std::size_t>(len));+        return fs::path(buffer);+    }+    return fs::path("vn"); #endif }  std::string quote_shell(std::string_view word) {-  std::string out;-  out.reserve(word.size() + 2);-  out.push_back('\'');-  for (char c : word) {-    if (c == '\'')-      out += "'\\''";-    else-      out.push_back(c);-  }-  out.push_back('\'');-  return out;+    std::string out;+    out.reserve(word.size() + 2);+    out.push_back('\'');+    for (char c : word) {+        if (c == '\'')+            out += "'\\''";+        else+            out.push_back(c);+    }+    out.push_back('\'');+    return out; } -std::string build_shell_command(const std::vector<std::string> &parts) {-  std::string out;-  for (const auto &part : parts) {-    if (!out.empty())-      out.push_back(' ');-    out += quote_shell(part);-  }-  return out;+std::string build_shell_command(const std::vector<std::string>& parts) {+    std::string out;+    for (const auto& part : parts) {+        if (!out.empty())+            out.push_back(' ');+        out += quote_shell(part);+    }+    return out; }  // ---------------------------------------------------------------------------@@ -607,139 +599,137 @@ // TLS // --------------------------------------------------------------------------- -void *tls_server_ctx(std::string_view cert_path, std::string_view key_path) {-  SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());-  if (!ctx)-    return nullptr;-  if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)-    goto fail;-  if (SSL_CTX_use_certificate_chain_file(ctx, std::string(cert_path).c_str()) !=-      1)-    goto fail;-  if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(),-                                  SSL_FILETYPE_PEM) != 1)-    goto fail;-  if (SSL_CTX_check_private_key(ctx) != 1)-    goto fail;-  return ctx;+void* tls_server_ctx(std::string_view cert_path, std::string_view key_path) {+    SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());+    if (!ctx)+        return nullptr;+    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1)+        goto fail;+    if (SSL_CTX_use_certificate_chain_file(ctx, std::string(cert_path).c_str()) != 1)+        goto fail;+    if (SSL_CTX_use_PrivateKey_file(ctx, std::string(key_path).c_str(), SSL_FILETYPE_PEM) != 1)+        goto fail;+    if (SSL_CTX_check_private_key(ctx) != 1)+        goto fail;+    return ctx; fail:-  SSL_CTX_free(ctx);-  return nullptr;-}--void *tls_client_ctx(bool pinned) {-  SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());-  if (!ctx)-    return nullptr;-  if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {     SSL_CTX_free(ctx);     return nullptr;-  }-  if (pinned) {-    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);+}++void* tls_client_ctx(bool pinned) {+    SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());+    if (!ctx)+        return nullptr;+    if (SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION) != 1) {+        SSL_CTX_free(ctx);+        return nullptr;+    }+    if (pinned) {+        SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);+        return ctx;+    }+    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);+    if (SSL_CTX_set_default_verify_paths(ctx) != 1) {+        SSL_CTX_free(ctx);+        return nullptr;+    }     return ctx;-  }-  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, nullptr);-  if (SSL_CTX_set_default_verify_paths(ctx) != 1) {-    SSL_CTX_free(ctx);-    return nullptr;-  }-  return ctx; } -void *tls_accept(void *ctx, Socket fd) {-  SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));-  if (!ssl)-    return nullptr;-  if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 || SSL_accept(ssl) != 1) {-    SSL_free(ssl);-    return nullptr;-  }-  return ssl;+void* tls_accept(void* ctx, Socket fd) {+    SSL* ssl = SSL_new(static_cast<SSL_CTX*>(ctx));+    if (!ssl)+        return nullptr;+    if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1 || SSL_accept(ssl) != 1) {+        SSL_free(ssl);+        return nullptr;+    }+    return ssl; } -void *tls_connect(void *ctx, Socket fd, std::string_view host) {-  SSL *ssl = SSL_new(static_cast<SSL_CTX *>(ctx));-  if (!ssl)-    return nullptr;-  if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {-    SSL_free(ssl);-    return nullptr;-  }-  if (!host.empty()) {-    const std::string text(host);-    SSL_set_tlsext_host_name(ssl, text.c_str());-    X509_VERIFY_PARAM *param = SSL_get0_param(ssl);-    X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);-  }-  if (SSL_connect(ssl) != 1) {-    SSL_free(ssl);-    return nullptr;-  }-  return ssl;+void* tls_connect(void* ctx, Socket fd, std::string_view host) {+    SSL* ssl = SSL_new(static_cast<SSL_CTX*>(ctx));+    if (!ssl)+        return nullptr;+    if (SSL_set_fd(ssl, static_cast<int>(fd)) != 1) {+        SSL_free(ssl);+        return nullptr;+    }+    if (!host.empty()) {+        const std::string text(host);+        SSL_set_tlsext_host_name(ssl, text.c_str());+        X509_VERIFY_PARAM* param = SSL_get0_param(ssl);+        X509_VERIFY_PARAM_set1_host(param, text.c_str(), 0);+    }+    if (SSL_connect(ssl) != 1) {+        SSL_free(ssl);+        return nullptr;+    }+    return ssl; } -bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len) {-  static constexpr char label[] = "EXPORTER-veins-auth/1";-  return SSL_export_keying_material(static_cast<SSL *>(ssl), out, len, label,-                                    sizeof(label) - 1, nullptr, 0, 0) == 1;+bool tls_exporter(void* ssl, std::uint8_t* out, std::size_t len) {+    static constexpr char label[] = "EXPORTER-veins-auth/1";+    return SSL_export_keying_material(static_cast<SSL*>(ssl), out, len, label, sizeof(label) - 1,+                                      nullptr, 0, 0) == 1; } -bool tls_peer_sha256(void *ssl, std::uint8_t *out) {-  X509 *cert = SSL_get1_peer_certificate(static_cast<SSL *>(ssl));-  if (!cert)-    return false;-  unsigned int len = 0;-  const bool ok = X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;-  X509_free(cert);-  return ok;+bool tls_peer_sha256(void* ssl, std::uint8_t* out) {+    X509* cert = SSL_get1_peer_certificate(static_cast<SSL*>(ssl));+    if (!cert)+        return false;+    unsigned int len = 0;+    const bool ok = X509_digest(cert, EVP_sha256(), out, &len) == 1 && len == 32;+    X509_free(cert);+    return ok; } -void tls_free(void *ssl) {-  if (!ssl)-    return;-  SSL_shutdown(static_cast<SSL *>(ssl));-  SSL_free(static_cast<SSL *>(ssl));+void tls_free(void* ssl) {+    if (!ssl)+        return;+    SSL_shutdown(static_cast<SSL*>(ssl));+    SSL_free(static_cast<SSL*>(ssl)); } -void tls_ctx_free(void *ctx) {-  if (ctx)-    SSL_CTX_free(static_cast<SSL_CTX *>(ctx));+void tls_ctx_free(void* ctx) {+    if (ctx)+        SSL_CTX_free(static_cast<SSL_CTX*>(ctx)); } -std::string tls_error() { return ssl_error_string(); }+std::string tls_error() {+    return ssl_error_string();+}  std::string to_hex(Bytes data) {-  static constexpr char digits[] = "0123456789abcdef";-  std::string out;-  out.reserve(data.size() * 2);-  for (std::uint8_t byte : data) {-    out.push_back(digits[byte >> 4]);-    out.push_back(digits[byte & 15]);-  }-  return out;+    static constexpr char digits[] = "0123456789abcdef";+    std::string out;+    out.reserve(data.size() * 2);+    for (std::uint8_t byte : data) {+        out.push_back(digits[byte >> 4]);+        out.push_back(digits[byte & 15]);+    }+    return out; }  bool hex_equal(std::string_view a, std::string_view b) {-  auto skip = [](std::string_view text, std::size_t &index) {-    while (index < text.size() && text[index] == ':')-      ++index;-  };-  std::size_t ai = 0;-  std::size_t bi = 0;-  for (;;) {-    skip(a, ai);-    skip(b, bi);-    if (ai >= a.size() || bi >= b.size())-      return ai >= a.size() && bi >= b.size();-    auto lower = [](char c) {-      return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c);+    auto skip = [](std::string_view text, std::size_t& index) {+        while (index < text.size() && text[index] == ':')+            ++index;     };-    if (lower(a[ai]) != lower(b[bi]))-      return false;-    ++ai;-    ++bi;-  }+    std::size_t ai = 0;+    std::size_t bi = 0;+    for (;;) {+        skip(a, ai);+        skip(b, bi);+        if (ai >= a.size() || bi >= b.size())+            return ai >= a.size() && bi >= b.size();+        auto lower = [](char c) { return static_cast<char>((c >= 'A' && c <= 'Z') ? c + 32 : c); };+        if (lower(a[ai]) != lower(b[bi]))+            return false;+        ++ai;+        ++bi;+    } }  } // namespace vn::net--- a/xveins/src/net.h+++ b/xveins/src/net.h@@ -22,54 +22,61 @@ // or a child process. class Stream { public:-  enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc };+    enum class Kind : std::uint8_t { Stdio, Fd, Tls, Proc }; -  Stream() = default;-  ~Stream();+    Stream() = default;+    ~Stream(); -  Stream(Stream &&other) noexcept;-  Stream &operator=(Stream &&other) noexcept;-  Stream(const Stream &) = delete;-  Stream &operator=(const Stream &) = delete;+    Stream(Stream&& other) noexcept;+    Stream& operator=(Stream&& other) noexcept;+    Stream(const Stream&) = delete;+    Stream& operator=(const Stream&) = delete; -  static Stream stdio_stream();-  static Stream fd_stream(Socket fd);-  static Stream tls_stream(Socket fd, void *ssl);-  static std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);+    static Stream stdio_stream();+    static Stream fd_stream(Socket fd);+    static Stream tls_stream(Socket fd, void* ssl);+    static std::optional<Stream> spawn_argv(const std::vector<std::string>& argv); -  friend std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);+    friend std::optional<Stream> spawn_argv(const std::vector<std::string>& argv); -  [[nodiscard]] Kind kind() const { return kind_; }-  [[nodiscard]] void *ssl() const { return ssl_; }-  [[nodiscard]] Socket fd() const { return fd_in_; }-  [[nodiscard]] bool valid() const { return open_; }+    [[nodiscard]] Kind kind() const {+        return kind_;+    }+    [[nodiscard]] void* ssl() const {+        return ssl_;+    }+    [[nodiscard]] Socket fd() const {+        return fd_in_;+    }+    [[nodiscard]] bool valid() const {+        return open_;+    } -  // Returns the number of bytes read, 0 at clean end of stream, -1 on error.-  std::int64_t read(void *buffer, std::size_t count);-  bool write_all(Bytes data);-  bool write_all(std::string_view text) {-    return write_all(Bytes(reinterpret_cast<const std::uint8_t *>(text.data()),-                           text.size()));-  }-  void close();+    // Returns the number of bytes read, 0 at clean end of stream, -1 on error.+    std::int64_t read(void* buffer, std::size_t count);+    bool write_all(Bytes data);+    bool write_all(std::string_view text) {+        return write_all(Bytes(reinterpret_cast<const std::uint8_t*>(text.data()), text.size()));+    }+    void close();  private:-  Kind kind_ = Kind::Stdio;-  Socket fd_in_ = 0;-  Socket fd_out_ = 0;-  void *ssl_ = nullptr;+    Kind kind_ = Kind::Stdio;+    Socket fd_in_ = 0;+    Socket fd_out_ = 0;+    void* ssl_ = nullptr; #if defined(_WIN32)-  void *process_ = nullptr;-  std::uint32_t process_id_ = 0;+    void* process_ = nullptr;+    std::uint32_t process_id_ = 0; #else-  int pid_ = 0;+    int pid_ = 0; #endif-  bool open_ = false;+    bool open_ = false; };  // Run argv[0] with the given arguments. stdin/stdout are connected to the // stream; stderr is inherited.-std::optional<Stream> spawn_argv(const std::vector<std::string> &argv);+std::optional<Stream> spawn_argv(const std::vector<std::string>& argv);  std::optional<Socket> tcp_connect(std::string_view host, int port); Socket tcp_listen(int port, int backlog = 64);@@ -79,20 +86,20 @@ void ignore_sigpipe(); fs::path self_exe(); std::string quote_shell(std::string_view word);-std::string build_shell_command(const std::vector<std::string> &parts);+std::string build_shell_command(const std::vector<std::string>& parts);  // --------------------------------------------------------------------------- // TLS 1.3 // --------------------------------------------------------------------------- -void *tls_server_ctx(std::string_view cert_path, std::string_view key_path);-void *tls_client_ctx(bool pinned);-void *tls_accept(void *ctx, Socket fd);-void *tls_connect(void *ctx, Socket fd, std::string_view host);-bool tls_exporter(void *ssl, std::uint8_t *out, std::size_t len);-bool tls_peer_sha256(void *ssl, std::uint8_t *out);-void tls_free(void *ssl);-void tls_ctx_free(void *ctx);+void* tls_server_ctx(std::string_view cert_path, std::string_view key_path);+void* tls_client_ctx(bool pinned);+void* tls_accept(void* ctx, Socket fd);+void* tls_connect(void* ctx, Socket fd, std::string_view host);+bool tls_exporter(void* ssl, std::uint8_t* out, std::size_t len);+bool tls_peer_sha256(void* ssl, std::uint8_t* out);+void tls_free(void* ssl);+void tls_ctx_free(void* ctx); std::string tls_error();  std::string to_hex(Bytes data);--- a/xveins/src/net_commands.cpp+++ b/xveins/src/net_commands.cpp@@ -23,376 +23,360 @@ namespace {  bool starts_with(std::string_view text, std::string_view prefix) {-  return text.size() >= prefix.size() &&-         text.substr(0, prefix.size()) == prefix;+    return text.size() >= prefix.size() && text.substr(0, prefix.size()) == prefix; }  bool is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';+    return !arg.empty() && arg.front() == '-'; } -std::string arg_at(const std::vector<std::string> &args, std::size_t index) {-  return index < args.size() ? args[index] : std::string();+std::string arg_at(const std::vector<std::string>& args, std::size_t index) {+    return index < args.size() ? args[index] : std::string(); }  void report_connect_failure(std::string_view fallback) {-  error_prefix();-  const std::string &detail = proto::Client::last_connect_error();-  std::cout << (detail.empty() ? std::string(fallback) : detail) << "\n";+    error_prefix();+    const std::string& detail = proto::Client::last_connect_error();+    std::cout << (detail.empty() ? std::string(fallback) : detail) << "\n"; }  std::string trim_text(std::string_view text) {-  std::size_t start = 0;-  std::size_t end = text.size();-  auto blank = [](char c) {-    return c == ' ' || c == '\t' || c == '\r' || c == '\n';-  };-  while (start < end && blank(text[start]))-    ++start;-  while (end > start && blank(text[end - 1]))-    --end;-  return std::string(text.substr(start, end - start));+    std::size_t start = 0;+    std::size_t end = text.size();+    auto blank = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };+    while (start < end && blank(text[start]))+        ++start;+    while (end > start && blank(text[end - 1]))+        --end;+    return std::string(text.substr(start, end - start)); }  std::string remote_key(std::string_view remote, std::string_view field) {-  std::string out = "remote.";-  out += remote;-  out.push_back('.');-  out += field;-  return out;+    std::string out = "remote.";+    out += remote;+    out.push_back('.');+    out += field;+    return out; }  std::string last_segment(std::string_view path) {-  while (path.size() > 1 && path.back() == '/')-    path.remove_suffix(1);-  const auto slash = path.rfind('/');-  if (slash != std::string_view::npos && slash + 1 < path.size())-    return std::string(path.substr(slash + 1));-  if (!path.empty() && path != "/")-    return std::string(path);-  return "repo";+    while (path.size() > 1 && path.back() == '/')+        path.remove_suffix(1);+    const auto slash = path.rfind('/');+    if (slash != std::string_view::npos && slash + 1 < path.size())+        return std::string(path.substr(slash + 1));+    if (!path.empty() && path != "/")+        return std::string(path);+    return "repo"; } -bool same_id(const Id &a, const Id &b) {-  return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+bool same_id(const Id& a, const Id& b) {+    return std::memcmp(a.data(), b.data(), ID_LEN) == 0; } -void report_client_error(const proto::Client &client,-                         std::string_view context) {-  error_prefix();-  if (!client.error().empty())-    std::cout << context << ": " << client.error() << "\n";-  else-    std::cout << context << "\n";+void report_client_error(const proto::Client& client, std::string_view context) {+    error_prefix();+    if (!client.error().empty())+        std::cout << context << ": " << client.error() << "\n";+    else+        std::cout << context << "\n"; } -std::optional<Id> default_target(const std::vector<proto::RefInfo> &refs) {-  for (const auto &ref : refs) {-    if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))-      return ref.target;-  }-  for (const auto &ref : refs) {-    if (ref.kind == 0)-      return ref.target;-  }-  return std::nullopt;+std::optional<Id> default_target(const std::vector<proto::RefInfo>& refs) {+    for (const auto& ref : refs) {+        if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))+            return ref.target;+    }+    for (const auto& ref : refs) {+        if (ref.kind == 0)+            return ref.target;+    }+    return std::nullopt; } -std::optional<std::string>-default_ref_name(const std::vector<proto::RefInfo> &refs) {-  for (const auto &ref : refs) {-    if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))-      return ref.name;-  }-  for (const auto &ref : refs) {-    if (ref.kind == 0)-      return ref.name;-  }-  return std::nullopt;+std::optional<std::string> default_ref_name(const std::vector<proto::RefInfo>& refs) {+    for (const auto& ref : refs) {+        if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))+            return ref.name;+    }+    for (const auto& ref : refs) {+        if (ref.kind == 0)+            return ref.name;+    }+    return std::nullopt; } -std::vector<Id> selected_commits(const std::vector<proto::RefInfo> &refs,-                                 std::string_view policy) {-  std::vector<Id> out;-  if (policy == "none")-    return out;-  if (policy == "head") {-    if (auto target = default_target(refs))-      out.push_back(*target);+std::vector<Id> selected_commits(const std::vector<proto::RefInfo>& refs, std::string_view policy) {+    std::vector<Id> out;+    if (policy == "none")+        return out;+    if (policy == "head") {+        if (auto target = default_target(refs))+            out.push_back(*target);+        return out;+    }+    for (const auto& ref : refs)+        out.push_back(ref.target);     return out;-  }-  for (const auto &ref : refs)-    out.push_back(ref.target);-  return out; } -bool set_bookmark(View &view, std::string_view name, const Id &target) {-  if (auto index = find_bookmark(view, name)) {-    view.bookmarks[*index].targets.adds = {target};-    view.bookmarks[*index].targets.removes.clear();+bool set_bookmark(View& view, std::string_view name, const Id& target) {+    if (auto index = find_bookmark(view, name)) {+        view.bookmarks[*index].targets.adds = {target};+        view.bookmarks[*index].targets.removes.clear();+        return true;+    }+    Bookmark bookmark;+    bookmark.name = std::string(name);+    bookmark.targets.adds = {target};+    view.bookmarks.push_back(std::move(bookmark));     return true;-  }-  Bookmark bookmark;-  bookmark.name = std::string(name);-  bookmark.targets.adds = {target};-  view.bookmarks.push_back(std::move(bookmark));-  return true; } -bool set_tag(View &view, std::string_view name, const Id &target) {-  if (auto index = find_tag(view, name)) {-    view.tags[*index].target = target;+bool set_tag(View& view, std::string_view name, const Id& target) {+    if (auto index = find_tag(view, name)) {+        view.tags[*index].target = target;+        return true;+    }+    view.tags.push_back(TagRef{std::string(name), target});     return true;-  }-  view.tags.push_back(TagRef{std::string(name), target});-  return true; } -bool set_remote_ref(View &view, std::string_view remote, std::string_view name,-                    const Id &target) {-  for (auto &ref : view.remote_refs) {-    if (ref.remote == remote && ref.name == name) {-      ref.target = target;-      return true;+bool set_remote_ref(View& view, std::string_view remote, std::string_view name, const Id& target) {+    for (auto& ref : view.remote_refs) {+        if (ref.remote == remote && ref.name == name) {+            ref.target = target;+            return true;+        }     }-  }-  view.remote_refs.push_back(-      RemoteRef{std::string(remote), std::string(name), target});-  return true;+    view.remote_refs.push_back(RemoteRef{std::string(remote), std::string(name), target});+    return true; } -bool apply_refs(const fs::path &root, const std::vector<proto::RefInfo> &refs,+bool apply_refs(const fs::path& root, const std::vector<proto::RefInfo>& refs,                 std::string_view remote, bool clone) {-  Store store = Store::open_all(root);-  auto tx = Txn::begin(root, store);-  if (!tx)-    return false;-  for (const auto &ref : refs) {-    if (ref.kind == 1) {-      set_tag(tx->view(), ref.name, ref.target);-    } else if (clone) {-      set_bookmark(tx->view(), ref.name, ref.target);-    } else {-      set_remote_ref(tx->view(), remote, ref.name, ref.target);-      if (!find_bookmark(tx->view(), ref.name))-        set_bookmark(tx->view(), ref.name, ref.target);-    }-  }-  rebuild_heads(tx->view());-  if (clone) {-    if (auto target = default_target(refs)) {-      auto child = create_working_copy_commit(*tx, *target);-      if (!child)+    Store store = Store::open_all(root);+    auto tx = Txn::begin(root, store);+    if (!tx)         return false;-      set_workspace(tx->view(), *child);-      rebuild_heads(tx->view());+    for (const auto& ref : refs) {+        if (ref.kind == 1) {+            set_tag(tx->view(), ref.name, ref.target);+        } else if (clone) {+            set_bookmark(tx->view(), ref.name, ref.target);+        } else {+            set_remote_ref(tx->view(), remote, ref.name, ref.target);+            if (!find_bookmark(tx->view(), ref.name))+                set_bookmark(tx->view(), ref.name, ref.target);+        }     }-  }-  const bool ok = tx->finish("clone").has_value();-  if (ok && clone) {-    if (auto name = default_ref_name(refs))-      (void)set_current_bookmark(root, *name);-    else-      (void)clear_current_bookmark(root);-  }-  return ok;+    rebuild_heads(tx->view());+    if (clone) {+        if (auto target = default_target(refs)) {+            auto child = create_working_copy_commit(*tx, *target);+            if (!child)+                return false;+            set_workspace(tx->view(), *child);+            rebuild_heads(tx->view());+        }+    }+    const bool ok = tx->finish("clone").has_value();+    if (ok && clone) {+        if (auto name = default_ref_name(refs))+            (void)set_current_bookmark(root, *name);+        else+            (void)clear_current_bookmark(root);+    }+    return ok; }  struct Walker {-  Walker(Store &store, bool want_objects)-      : store(store), want_objects(want_objects) {}--  Store &store;-  bool want_objects = false;-  std::set<Id> blobs;-  std::set<Id> conflicts;-  std::set<Id> chunks;-  std::set<Id> objects;-  std::vector<Id> chunk_out;-  std::vector<Id> object_out;+    Walker(Store& store, bool want_objects) : store(store), want_objects(want_objects) {} -  void add_object(const Id &id) {-    if (want_objects && objects.insert(id).second)-      object_out.push_back(id);-  }+    Store& store;+    bool want_objects = false;+    std::set<Id> blobs;+    std::set<Id> conflicts;+    std::set<Id> chunks;+    std::set<Id> objects;+    std::vector<Id> chunk_out;+    std::vector<Id> object_out; -  void walk_blob(const Id &id) {-    if (!blobs.insert(id).second)-      return;-    add_object(id);-    auto body = store.read_body(id, TYPE_BLOB);-    if (!body)-      return;-    auto blob = decode_blob(bytes_of(*body));-    if (!blob)-      return;-    if (blob->form == BlobForm::Leaf) {-      for (const auto &entry : blob->entries) {-        if (chunks.insert(entry.id).second)-          chunk_out.push_back(entry.id);-        add_object(entry.id);-      }-    } else if (blob->form == BlobForm::Interior) {-      for (const auto &entry : blob->entries)-        walk_blob(entry.id);+    void add_object(const Id& id) {+        if (want_objects && objects.insert(id).second)+            object_out.push_back(id);     }-  } -  void walk_conflict(const Id &id) {-    if (!conflicts.insert(id).second)-      return;-    add_object(id);-    auto body = store.read_body(id, TYPE_CONFLICT);-    if (!body)-      return;-    auto conflict = decode_conflict(bytes_of(*body));-    if (!conflict)-      return;-    for (const auto &value : conflict->adds) {-      if (value.target)-        walk_value(value.kind, *value.target);+    void walk_blob(const Id& id) {+        if (!blobs.insert(id).second)+            return;+        add_object(id);+        auto body = store.read_body(id, TYPE_BLOB);+        if (!body)+            return;+        auto blob = decode_blob(bytes_of(*body));+        if (!blob)+            return;+        if (blob->form == BlobForm::Leaf) {+            for (const auto& entry : blob->entries) {+                if (chunks.insert(entry.id).second)+                    chunk_out.push_back(entry.id);+                add_object(entry.id);+            }+        } else if (blob->form == BlobForm::Interior) {+            for (const auto& entry : blob->entries)+                walk_blob(entry.id);+        }     }-    for (const auto &value : conflict->removes) {-      if (value.target)-        walk_value(value.kind, *value.target);++    void walk_conflict(const Id& id) {+        if (!conflicts.insert(id).second)+            return;+        add_object(id);+        auto body = store.read_body(id, TYPE_CONFLICT);+        if (!body)+            return;+        auto conflict = decode_conflict(bytes_of(*body));+        if (!conflict)+            return;+        for (const auto& value : conflict->adds) {+            if (value.target)+                walk_value(value.kind, *value.target);+        }+        for (const auto& value : conflict->removes) {+            if (value.target)+                walk_value(value.kind, *value.target);+        }     }-  } -  void walk_value(std::uint8_t kind, const Id &id) {-    if (kind == KIND_SUBTREE)-      walk_tree(id);-    else if (kind == KIND_CONFLICT)-      walk_conflict(id);-    else-      walk_blob(id);-  }+    void walk_value(std::uint8_t kind, const Id& id) {+        if (kind == KIND_SUBTREE)+            walk_tree(id);+        else if (kind == KIND_CONFLICT)+            walk_conflict(id);+        else+            walk_blob(id);+    } -  void walk_tree(const Id &id) {-    add_object(id);-    auto body = store.read_body(id, TYPE_TREE);-    if (!body)-      return;-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-      return;-    for (const auto &entry : tree->entries) {-      if (entry.kind == KIND_SUBTREE)-        walk_tree(entry.target);-      else if (entry.kind == KIND_CONFLICT)-        walk_conflict(entry.target);-      else if (entry.kind != KIND_SUBMODULE)-        walk_blob(entry.target);+    void walk_tree(const Id& id) {+        add_object(id);+        auto body = store.read_body(id, TYPE_TREE);+        if (!body)+            return;+        auto tree = decode_tree(bytes_of(*body));+        if (!tree)+            return;+        for (const auto& entry : tree->entries) {+            if (entry.kind == KIND_SUBTREE)+                walk_tree(entry.target);+            else if (entry.kind == KIND_CONFLICT)+                walk_conflict(entry.target);+            else if (entry.kind != KIND_SUBMODULE)+                walk_blob(entry.target);+        }     }-  } }; -std::vector<Id> chunks_for_commits(Store &store,-                                   const std::vector<Id> &commits) {-  Walker walker{store, false};-  for (const auto &id : commits) {-    auto loaded = load_commit(store, id);-    if (loaded)-      walker.walk_tree(loaded->commit.root_tree);-  }-  return std::move(walker.chunk_out);+std::vector<Id> chunks_for_commits(Store& store, const std::vector<Id>& commits) {+    Walker walker{store, false};+    for (const auto& id : commits) {+        auto loaded = load_commit(store, id);+        if (loaded)+            walker.walk_tree(loaded->commit.root_tree);+    }+    return std::move(walker.chunk_out); } -std::vector<Id> objects_for_commits(Store &store,-                                    const std::vector<Id> &commits) {-  Walker walker{store, true};-  for (const auto &id : commits) {-    walker.add_object(id);-    auto loaded = load_commit(store, id);-    if (loaded)-      walker.walk_tree(loaded->commit.root_tree);-  }-  return std::move(walker.object_out);+std::vector<Id> objects_for_commits(Store& store, const std::vector<Id>& commits) {+    Walker walker{store, true};+    for (const auto& id : commits) {+        walker.add_object(id);+        auto loaded = load_commit(store, id);+        if (loaded)+            walker.walk_tree(loaded->commit.root_tree);+    }+    return std::move(walker.object_out); } -bool send_chunks(proto::Client &client, const fs::path &root,-                 const std::vector<Id> &chunks) {-  constexpr std::size_t BATCH = 4096;-  for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {-    const std::size_t end = std::min(offset + BATCH, chunks.size());-    std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),-                          chunks.begin() + static_cast<std::ptrdiff_t>(end));-    if (!client.get_chunks(root, batch))-      return false;-  }-  return true;+bool send_chunks(proto::Client& client, const fs::path& root, const std::vector<Id>& chunks) {+    constexpr std::size_t BATCH = 4096;+    for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {+        const std::size_t end = std::min(offset + BATCH, chunks.size());+        std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),+                              chunks.begin() + static_cast<std::ptrdiff_t>(end));+        if (!client.get_chunks(root, batch))+            return false;+    }+    return true; } -bool send_missing_chunks(proto::Client &client, const fs::path &root,-                         const std::vector<Id> &chunks) {-  Store store = Store::open_all(root);-  std::vector<Id> missing;-  for (const auto &id : chunks) {-    if (!store.find(id))-      missing.push_back(id);-  }-  return send_chunks(client, root, missing);+bool send_missing_chunks(proto::Client& client, const fs::path& root,+                         const std::vector<Id>& chunks) {+    Store store = Store::open_all(root);+    std::vector<Id> missing;+    for (const auto& id : chunks) {+        if (!store.find(id))+            missing.push_back(id);+    }+    return send_chunks(client, root, missing); } -std::optional<std::string> config_value(const fs::path &root,-                                        std::string_view key) {-  return repo_config_value(root, key);+std::optional<std::string> config_value(const fs::path& root, std::string_view key) {+    return repo_config_value(root, key); } -std::vector<std::string> list_remote_names(const fs::path &root) {-  std::vector<std::string> out;-  auto data = read_file_opt(config_path(root));-  if (!data)-    return out;-  const std::string_view text(reinterpret_cast<const char *>(data->data()),-                              data->size());-  std::size_t start = 0;-  for (std::size_t i = 0; i <= text.size(); ++i) {-    if (i != text.size() && text[i] != '\n')-      continue;-    const std::string_view line = text.substr(start, i - start);-    if (starts_with(line, "remote.")) {-      const auto dot = line.find(".url", 7);-      if (dot != std::string_view::npos && dot > 7)-        out.emplace_back(line.substr(7, dot - 7));+std::vector<std::string> list_remote_names(const fs::path& root) {+    std::vector<std::string> out;+    auto data = read_file_opt(config_path(root));+    if (!data)+        return out;+    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    for (std::size_t i = 0; i <= text.size(); ++i) {+        if (i != text.size() && text[i] != '\n')+            continue;+        const std::string_view line = text.substr(start, i - start);+        if (starts_with(line, "remote.")) {+            const auto dot = line.find(".url", 7);+            if (dot != std::string_view::npos && dot > 7)+                out.emplace_back(line.substr(7, dot - 7));+        }+        start = i + 1;     }-    start = i + 1;-  }-  return out;+    return out; }  std::string role_text(std::uint8_t role) {-  if (role == 2)-    return "write";-  if (role == 1)-    return "read";-  return "anonymous";+    if (role == 2)+        return "write";+    if (role == 1)+        return "read";+    return "anonymous"; } -void print_key(const auth::Key &key) {-  std::cout << "name: " << key.name << "\n";-  std::cout << "public key: " << format_public_key(key.public_key) << "\n";-  std::cout << "fingerprint: " << key.fingerprint << "\n";+void print_key(const auth::Key& key) {+    std::cout << "name: " << key.name << "\n";+    std::cout << "public key: " << format_public_key(key.public_key) << "\n";+    std::cout << "fingerprint: " << key.fingerprint << "\n"; }  void auth_usage() {-  std::cout << "usage: vn auth <use|list|remove> ...\n";-  std::cout-      << "  vn auth use <key> [<host|url>]   set the default or host key\n";-  std::cout << "  vn auth list                     show stored key mappings\n";-  std::cout-      << "  vn auth remove [<host|url>]      remove a mapping (default if "-         "omitted)\n";+    std::cout << "usage: vn auth <use|list|remove> ...\n";+    std::cout << "  vn auth use <key> [<host|url>]   set the default or host key\n";+    std::cout << "  vn auth list                     show stored key mappings\n";+    std::cout << "  vn auth remove [<host|url>]      remove a mapping (default if "+                 "omitted)\n"; }  std::optional<PublicKey> read_public_key(std::string_view arg) {-  if (starts_with(arg, "ed25519:"))-    return parse_public_key(arg);-  auto data = read_file_opt(path_from_bytes(arg));-  if (!data)-    return std::nullopt;-  const std::string text = trim_text(std::string_view(-      reinterpret_cast<const char *>(data->data()), data->size()));-  return parse_public_key(text);+    if (starts_with(arg, "ed25519:"))+        return parse_public_key(arg);+    auto data = read_file_opt(path_from_bytes(arg));+    if (!data)+        return std::nullopt;+    const std::string text =+        trim_text(std::string_view(reinterpret_cast<const char*>(data->data()), data->size()));+    return parse_public_key(text); }  } // namespace@@ -400,123 +384,123 @@ // --------------------------------------------------------------------------- // remote // -----------------------------------------------------------------------------int remote_run(const std::vector<std::string> &args) {-  const std::string sub = arg_at(args, 2);-  if (sub.empty()) {-    error_prefix();-    std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";-    return 1;-  }-  auto repo = discover_repo(".");-  if (!repo) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const fs::path root = *repo; -  if (sub == "add" || sub == "set-url") {-    const bool replace = sub == "set-url";-    std::string name;-    std::string url;-    std::optional<std::string> key;-    std::optional<std::string> pin;-    for (std::size_t i = 3; i < args.size(); ++i) {-      const std::string &arg = args[i];-      if (starts_with(arg, "-key:")) {-        key = arg.substr(5);-      } else if (starts_with(arg, "-pin:")) {-        pin = arg.substr(5);-      } else if (is_flag(arg)) {-        error_prefix();-        std::cout << "unknown flag: " << arg << "\n";-        return 1;-      } else if (name.empty()) {-        name = arg;-      } else if (url.empty()) {-        url = arg;-      } else {-        error_prefix();-        std::cout << "too many arguments\n";-        return 1;-      }-    }-    if (name.empty() || url.empty()) {-      error_prefix();-      std::cout << (replace ? "remote set-url requires a name and URL\n"-                            : "remote add requires a name and URL\n");-      return 1;-    }-    const std::string url_key = remote_key(name, "url");-    const auto existing = config_value(root, url_key);-    if (existing && !replace) {-      error_prefix();-      std::cout << "remote already exists: " << name << "\n";-      return 1;-    }-    if (!existing && replace) {-      error_prefix();-      std::cout << "unknown remote: " << name << "\n";-      return 1;-    }-    if (!repo_config_set(root, url_key, url)) {-      error_prefix();-      std::cout << "cannot write repository config\n";-      return 1;-    }-    if (key) {-      const std::string field = remote_key(name, "key");-      const bool ok = key->empty() ? repo_config_remove(root, field)-                                   : repo_config_set(root, field, *key);-      if (!ok) {+int remote_run(const std::vector<std::string>& args) {+    const std::string sub = arg_at(args, 2);+    if (sub.empty()) {         error_prefix();-        std::cout << "cannot write repository config\n";+        std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";         return 1;-      }     }-    if (pin) {-      const std::string field = remote_key(name, "tls-pin");-      const bool ok = pin->empty() ? repo_config_remove(root, field)-                                   : repo_config_set(root, field, *pin);-      if (!ok) {+    auto repo = discover_repo(".");+    if (!repo) {         error_prefix();-        std::cout << "cannot write repository config\n";+        std::cout << "not a veins repository\n";         return 1;-      }     }-    return 0;-  }+    const fs::path root = *repo; -  if (sub == "list" || sub == "ls") {-    for (const auto &name : list_remote_names(root)) {-      const auto url = config_value(root, remote_key(name, "url"));-      std::cout << name << "\t" << (url ? *url : std::string()) << "\n";+    if (sub == "add" || sub == "set-url") {+        const bool replace = sub == "set-url";+        std::string name;+        std::string url;+        std::optional<std::string> key;+        std::optional<std::string> pin;+        for (std::size_t i = 3; i < args.size(); ++i) {+            const std::string& arg = args[i];+            if (starts_with(arg, "-key:")) {+                key = arg.substr(5);+            } else if (starts_with(arg, "-pin:")) {+                pin = arg.substr(5);+            } else if (is_flag(arg)) {+                error_prefix();+                std::cout << "unknown flag: " << arg << "\n";+                return 1;+            } else if (name.empty()) {+                name = arg;+            } else if (url.empty()) {+                url = arg;+            } else {+                error_prefix();+                std::cout << "too many arguments\n";+                return 1;+            }+        }+        if (name.empty() || url.empty()) {+            error_prefix();+            std::cout << (replace ? "remote set-url requires a name and URL\n"+                                  : "remote add requires a name and URL\n");+            return 1;+        }+        const std::string url_key = remote_key(name, "url");+        const auto existing = config_value(root, url_key);+        if (existing && !replace) {+            error_prefix();+            std::cout << "remote already exists: " << name << "\n";+            return 1;+        }+        if (!existing && replace) {+            error_prefix();+            std::cout << "unknown remote: " << name << "\n";+            return 1;+        }+        if (!repo_config_set(root, url_key, url)) {+            error_prefix();+            std::cout << "cannot write repository config\n";+            return 1;+        }+        if (key) {+            const std::string field = remote_key(name, "key");+            const bool ok =+                key->empty() ? repo_config_remove(root, field) : repo_config_set(root, field, *key);+            if (!ok) {+                error_prefix();+                std::cout << "cannot write repository config\n";+                return 1;+            }+        }+        if (pin) {+            const std::string field = remote_key(name, "tls-pin");+            const bool ok =+                pin->empty() ? repo_config_remove(root, field) : repo_config_set(root, field, *pin);+            if (!ok) {+                error_prefix();+                std::cout << "cannot write repository config\n";+                return 1;+            }+        }+        return 0;     }-    return 0;-  } -  if (sub == "remove" || sub == "rm") {-    const std::string name = arg_at(args, 3);-    if (name.empty()) {-      error_prefix();-      std::cout << "remote remove requires a name\n";-      return 1;+    if (sub == "list" || sub == "ls") {+        for (const auto& name : list_remote_names(root)) {+            const auto url = config_value(root, remote_key(name, "url"));+            std::cout << name << "\t" << (url ? *url : std::string()) << "\n";+        }+        return 0;     }-    if (!config_value(root, remote_key(name, "url"))) {-      error_prefix();-      std::cout << "unknown remote: " << name << "\n";-      return 1;++    if (sub == "remove" || sub == "rm") {+        const std::string name = arg_at(args, 3);+        if (name.empty()) {+            error_prefix();+            std::cout << "remote remove requires a name\n";+            return 1;+        }+        if (!config_value(root, remote_key(name, "url"))) {+            error_prefix();+            std::cout << "unknown remote: " << name << "\n";+            return 1;+        }+        (void)repo_config_remove(root, remote_key(name, "url"));+        (void)repo_config_remove(root, remote_key(name, "key"));+        (void)repo_config_remove(root, remote_key(name, "tls-pin"));+        return 0;     }-    (void)repo_config_remove(root, remote_key(name, "url"));-    (void)repo_config_remove(root, remote_key(name, "key"));-    (void)repo_config_remove(root, remote_key(name, "tls-pin"));-    return 0;-  } -  error_prefix();-  std::cout << "unknown remote subcommand: " << sub << "\n";-  return 1;+    error_prefix();+    std::cout << "unknown remote subcommand: " << sub << "\n";+    return 1; }  // ---------------------------------------------------------------------------@@ -523,140 +507,140 @@ // clone // --------------------------------------------------------------------------- -int clone_run(const std::vector<std::string> &args) {-  std::string url;-  std::string path;-  std::string policy = "head";-  std::string key_name;-  bool key_explicit = false;-  std::string tls_pin;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (starts_with(arg, "-blobs:")) {-      policy = arg.substr(7);-    } else if (starts_with(arg, "-key:")) {-      key_name = arg.substr(5);-      if (starts_with(key_name, "ed25519:")) {+int clone_run(const std::vector<std::string>& args) {+    std::string url;+    std::string path;+    std::string policy = "head";+    std::string key_name;+    bool key_explicit = false;+    std::string tls_pin;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (starts_with(arg, "-blobs:")) {+            policy = arg.substr(7);+        } else if (starts_with(arg, "-key:")) {+            key_name = arg.substr(5);+            if (starts_with(key_name, "ed25519:")) {+                error_prefix();+                std::cout << "-key: expects a local key name, not a public key\n";+                return 1;+            }+            key_explicit = true;+        } else if (starts_with(arg, "-pin:")) {+            tls_pin = arg.substr(5);+        } else if (is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (url.empty()) {+            url = arg;+        } else {+            path = arg;+        }+    }+    if (url.empty()) {         error_prefix();-        std::cout << "-key: expects a local key name, not a public key\n";+        std::cout << "clone requires a URL\n";         return 1;-      }-      key_explicit = true;-    } else if (starts_with(arg, "-pin:")) {-      tls_pin = arg.substr(5);-    } else if (is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (url.empty()) {-      url = arg;-    } else {-      path = arg;     }-  }-  if (url.empty()) {-    error_prefix();-    std::cout << "clone requires a URL\n";-    return 1;-  }-  const auto parsed = proto::parse_url(url);-  if (!parsed) {-    error_prefix();-    std::cout << "unsupported URL\n";-    return 1;-  }-  if (path.empty())-    path = last_segment(parsed->path);-  auto repo = init_repo(path_from_bytes(path));-  if (!repo) {-    error_prefix();-    std::cout << "cannot create repository\n";-    return 1;-  }-  const fs::path root = *repo;+    const auto parsed = proto::parse_url(url);+    if (!parsed) {+        error_prefix();+        std::cout << "unsupported URL\n";+        return 1;+    }+    if (path.empty())+        path = last_segment(parsed->path);+    auto repo = init_repo(path_from_bytes(path));+    if (!repo) {+        error_prefix();+        std::cout << "cannot create repository\n";+        return 1;+    }+    const fs::path root = *repo; -  if (key_name.empty()) {-    if (auto fallback = auth::key_for_url(url))-      key_name = *fallback;-  }-  (void)repo_config_set(root, remote_key("origin", "url"), url);-  if (key_explicit && !key_name.empty())-    (void)repo_config_set(root, remote_key("origin", "key"), key_name);-  if (!tls_pin.empty())-    (void)repo_config_set(root, remote_key("origin", "tls-pin"), tls_pin);+    if (key_name.empty()) {+        if (auto fallback = auth::key_for_url(url))+            key_name = *fallback;+    }+    (void)repo_config_set(root, remote_key("origin", "url"), url);+    if (key_explicit && !key_name.empty())+        (void)repo_config_set(root, remote_key("origin", "key"), key_name);+    if (!tls_pin.empty())+        (void)repo_config_set(root, remote_key("origin", "tls-pin"), tls_pin); -  const std::string repo_name = proto::url_repo_name(url);-  auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);-  if (!client) {-    report_connect_failure("cannot connect or authenticate");-    return 1;-  }-  std::vector<proto::RefInfo> refs;-  if (!client->list_refs(refs)) {-    report_client_error(*client, "cannot list remote refs");-    return 1;-  }-  std::vector<Id> wants;-  for (const auto &ref : refs)-    wants.push_back(ref.target);-  if (wants.empty()) {-    info_prefix();-    std::cout << "cloned empty repository into " << path << "\n";-    return 0;-  }-  if (!client->negotiate(wants, {})) {-    report_client_error(*client, "negotiation failed");-    return 1;-  }-  if (!client->fetch_skeleton(root, wants)) {-    report_client_error(*client, "fetch failed");-    return 1;-  }-  {-    Store store = Store::open_all(root);-    const auto commits = selected_commits(refs, policy);-    const auto chunks = chunks_for_commits(store, commits);-    if (!send_chunks(*client, root, chunks)) {-      report_client_error(*client, "chunk fetch failed");-      return 1;+    const std::string repo_name = proto::url_repo_name(url);+    auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);+    if (!client) {+        report_connect_failure("cannot connect or authenticate");+        return 1;     }-  }-  if (!apply_refs(root, refs, "origin", true)) {-    error_prefix();-    std::cout << "cannot write repository state\n";-    return 1;-  }-  (void)repo_config_set(root, "promisor", "origin");-  install_promisor_fetcher();-  if (policy == "none") {-    info_prefix();-    std::cout << "cloned metadata only; blobs are promised\n";-  }+    std::vector<proto::RefInfo> refs;+    if (!client->list_refs(refs)) {+        report_client_error(*client, "cannot list remote refs");+        return 1;+    }+    std::vector<Id> wants;+    for (const auto& ref : refs)+        wants.push_back(ref.target);+    if (wants.empty()) {+        info_prefix();+        std::cout << "cloned empty repository into " << path << "\n";+        return 0;+    }+    if (!client->negotiate(wants, {})) {+        report_client_error(*client, "negotiation failed");+        return 1;+    }+    if (!client->fetch_skeleton(root, wants)) {+        report_client_error(*client, "fetch failed");+        return 1;+    }+    {+        Store store = Store::open_all(root);+        const auto commits = selected_commits(refs, policy);+        const auto chunks = chunks_for_commits(store, commits);+        if (!send_chunks(*client, root, chunks)) {+            report_client_error(*client, "chunk fetch failed");+            return 1;+        }+    }+    if (!apply_refs(root, refs, "origin", true)) {+        error_prefix();+        std::cout << "cannot write repository state\n";+        return 1;+    }+    (void)repo_config_set(root, "promisor", "origin");+    install_promisor_fetcher();+    if (policy == "none") {+        info_prefix();+        std::cout << "cloned metadata only; blobs are promised\n";+    } -  int checkout_status = 1;-  {-    Store store = Store::open_all(root);-    auto view = current_view(root, store);-    if (view) {-      if (auto wc = working_copy_id(*view)) {-        auto body = store.read_body(*wc, TYPE_COMMIT);-        if (body) {-          auto commit = decode_commit(bytes_of(*body));-          if (commit) {-            checkout_status = checkout_materialize_commit(-                root, store, std::nullopt, commit->root_tree);-          }+    int checkout_status = 1;+    {+        Store store = Store::open_all(root);+        auto view = current_view(root, store);+        if (view) {+            if (auto wc = working_copy_id(*view)) {+                auto body = store.read_body(*wc, TYPE_COMMIT);+                if (body) {+                    auto commit = decode_commit(bytes_of(*body));+                    if (commit) {+                        checkout_status = checkout_materialize_commit(root, store, std::nullopt,+                                                                      commit->root_tree);+                    }+                }+            }         }-      }     }-  }-  if (checkout_status != 0) {+    if (checkout_status != 0) {+        info_prefix();+        std::cout << "cloned; checkout reported " << checkout_status << "\n";+    }     info_prefix();-    std::cout << "cloned; checkout reported " << checkout_status << "\n";-  }-  info_prefix();-  std::cout << "cloned into " << path << "\n";-  return 0;+    std::cout << "cloned into " << path << "\n";+    return 0; }  // ---------------------------------------------------------------------------@@ -663,110 +647,109 @@ // fetch // --------------------------------------------------------------------------- -int fetch_run(const std::vector<std::string> &args) {-  std::string remote_name = "origin";-  std::string path = ".";-  std::string explicit_key;-  std::string explicit_pin;-  bool have_remote = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (starts_with(arg, "-key:")) {-      explicit_key = arg.substr(5);-      if (starts_with(explicit_key, "ed25519:")) {+int fetch_run(const std::vector<std::string>& args) {+    std::string remote_name = "origin";+    std::string path = ".";+    std::string explicit_key;+    std::string explicit_pin;+    bool have_remote = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (starts_with(arg, "-key:")) {+            explicit_key = arg.substr(5);+            if (starts_with(explicit_key, "ed25519:")) {+                error_prefix();+                std::cout << "-key: expects a local key name, not a public key\n";+                return 1;+            }+        } else if (starts_with(arg, "-pin:")) {+            explicit_pin = arg.substr(5);+        } else if (is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (!have_remote) {+            remote_name = arg;+            have_remote = true;+        } else {+            path = arg;+        }+    }+    auto repo = discover_repo(path_from_bytes(path));+    if (!repo) {         error_prefix();-        std::cout << "-key: expects a local key name, not a public key\n";+        std::cout << "not a veins repository\n";         return 1;-      }-    } else if (starts_with(arg, "-pin:")) {-      explicit_pin = arg.substr(5);-    } else if (is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (!have_remote) {-      remote_name = arg;-      have_remote = true;+    }+    const fs::path root = *repo;+    auto url = config_value(root, remote_key(remote_name, "url"));+    if (!url) {+        error_prefix();+        std::cout << "unknown remote\n";+        return 1;+    }+    std::string key;+    if (!explicit_key.empty()) {+        key = explicit_key;     } else {-      path = arg;+        auto configured = config_value(root, remote_key(remote_name, "key"));+        if (configured && auth::local_key_exists(*configured))+            key = *configured;+        if (key.empty()) {+            if (auto fallback = auth::key_for_url(*url))+                key = *fallback;+        }     }-  }-  auto repo = discover_repo(path_from_bytes(path));-  if (!repo) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const fs::path root = *repo;-  auto url = config_value(root, remote_key(remote_name, "url"));-  if (!url) {-    error_prefix();-    std::cout << "unknown remote\n";-    return 1;-  }-  std::string key;-  if (!explicit_key.empty()) {-    key = explicit_key;-  } else {-    auto configured = config_value(root, remote_key(remote_name, "key"));-    if (configured && auth::local_key_exists(*configured))-      key = *configured;-    if (key.empty()) {-      if (auto fallback = auth::key_for_url(*url))-        key = *fallback;+    std::string pin;+    if (!explicit_pin.empty()) {+        pin = explicit_pin;+    } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {+        pin = *configured;     }-  }-  std::string pin;-  if (!explicit_pin.empty()) {-    pin = explicit_pin;-  } else if (auto configured =-                 config_value(root, remote_key(remote_name, "tls-pin"))) {-    pin = *configured;-  }-  const std::string repo_name = proto::url_repo_name(*url);-  auto client = proto::Client::connect(*url, key, repo_name, pin);-  if (!client) {-    report_connect_failure("cannot connect or authenticate");-    return 1;-  }-  std::vector<proto::RefInfo> refs;-  if (!client->list_refs(refs)) {-    report_client_error(*client, "cannot list remote refs");-    return 1;-  }-  std::vector<Id> haves = read_heads(root);-  std::vector<Id> wants;-  for (const auto &ref : refs)-    wants.push_back(ref.target);-  if (wants.empty()) {+    const std::string repo_name = proto::url_repo_name(*url);+    auto client = proto::Client::connect(*url, key, repo_name, pin);+    if (!client) {+        report_connect_failure("cannot connect or authenticate");+        return 1;+    }+    std::vector<proto::RefInfo> refs;+    if (!client->list_refs(refs)) {+        report_client_error(*client, "cannot list remote refs");+        return 1;+    }+    std::vector<Id> haves = read_heads(root);+    std::vector<Id> wants;+    for (const auto& ref : refs)+        wants.push_back(ref.target);+    if (wants.empty()) {+        info_prefix();+        std::cout << "no refs to fetch\n";+        return 0;+    }+    if (!client->negotiate(wants, haves)) {+        report_client_error(*client, "negotiation failed");+        return 1;+    }+    if (!client->fetch_skeleton(root, wants)) {+        report_client_error(*client, "fetch failed");+        return 1;+    }+    {+        Store store = Store::open_all(root);+        const auto chunks = chunks_for_commits(store, wants);+        if (!send_missing_chunks(*client, root, chunks)) {+            report_client_error(*client, "chunk fetch failed");+            return 1;+        }+    }+    if (!apply_refs(root, refs, remote_name, false)) {+        error_prefix();+        std::cout << "cannot write repository state\n";+        return 1;+    }     info_prefix();-    std::cout << "no refs to fetch\n";+    std::cout << "fetched from " << remote_name << "\n";     return 0;-  }-  if (!client->negotiate(wants, haves)) {-    report_client_error(*client, "negotiation failed");-    return 1;-  }-  if (!client->fetch_skeleton(root, wants)) {-    report_client_error(*client, "fetch failed");-    return 1;-  }-  {-    Store store = Store::open_all(root);-    const auto chunks = chunks_for_commits(store, wants);-    if (!send_missing_chunks(*client, root, chunks)) {-      report_client_error(*client, "chunk fetch failed");-      return 1;-    }-  }-  if (!apply_refs(root, refs, remote_name, false)) {-    error_prefix();-    std::cout << "cannot write repository state\n";-    return 1;-  }-  info_prefix();-  std::cout << "fetched from " << remote_name << "\n";-  return 0; }  // ---------------------------------------------------------------------------@@ -773,131 +756,130 @@ // push // --------------------------------------------------------------------------- -int push_run(const std::vector<std::string> &args) {-  std::string remote_name = "origin";-  std::string bookmark;-  std::string explicit_key;-  std::string explicit_pin;-  std::string path = ".";-  bool have_remote = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (starts_with(arg, "-key:")) {-      explicit_key = arg.substr(5);-      if (starts_with(explicit_key, "ed25519:")) {+int push_run(const std::vector<std::string>& args) {+    std::string remote_name = "origin";+    std::string bookmark;+    std::string explicit_key;+    std::string explicit_pin;+    std::string path = ".";+    bool have_remote = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (starts_with(arg, "-key:")) {+            explicit_key = arg.substr(5);+            if (starts_with(explicit_key, "ed25519:")) {+                error_prefix();+                std::cout << "-key: expects a local key name, not a public key\n";+                return 1;+            }+        } else if (starts_with(arg, "-pin:")) {+            explicit_pin = arg.substr(5);+        } else if (is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (!have_remote) {+            remote_name = arg;+            have_remote = true;+        } else if (bookmark.empty()) {+            bookmark = arg;+        } else {+            path = arg;+        }+    }+    auto repo = discover_repo(path_from_bytes(path));+    if (!repo) {         error_prefix();-        std::cout << "-key: expects a local key name, not a public key\n";+        std::cout << "not a veins repository\n";         return 1;-      }-    } else if (starts_with(arg, "-pin:")) {-      explicit_pin = arg.substr(5);-    } else if (is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (!have_remote) {-      remote_name = arg;-      have_remote = true;-    } else if (bookmark.empty()) {-      bookmark = arg;+    }+    const fs::path root = *repo;+    if (bookmark.empty()) {+        if (auto current = current_bookmark_name(root))+            bookmark = *current;+    }+    if (bookmark.empty()) {+        error_prefix();+        std::cout << "push requires a bookmark name (or a current bookmark)\n";+        return 1;+    }+    auto url = config_value(root, remote_key(remote_name, "url"));+    if (!url) {+        error_prefix();+        std::cout << "unknown remote\n";+        return 1;+    }+    std::string key;+    if (!explicit_key.empty()) {+        key = explicit_key;     } else {-      path = arg;+        auto configured = config_value(root, remote_key(remote_name, "key"));+        if (configured && auth::local_key_exists(*configured))+            key = *configured;+        if (key.empty()) {+            if (auto fallback = auth::key_for_url(*url))+                key = *fallback;+        }     }-  }-  auto repo = discover_repo(path_from_bytes(path));-  if (!repo) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const fs::path root = *repo;-  if (bookmark.empty()) {-    if (auto current = current_bookmark_name(root))-      bookmark = *current;-  }-  if (bookmark.empty()) {-    error_prefix();-    std::cout << "push requires a bookmark name (or a current bookmark)\n";-    return 1;-  }-  auto url = config_value(root, remote_key(remote_name, "url"));-  if (!url) {-    error_prefix();-    std::cout << "unknown remote\n";-    return 1;-  }-  std::string key;-  if (!explicit_key.empty()) {-    key = explicit_key;-  } else {-    auto configured = config_value(root, remote_key(remote_name, "key"));-    if (configured && auth::local_key_exists(*configured))-      key = *configured;-    if (key.empty()) {-      if (auto fallback = auth::key_for_url(*url))-        key = *fallback;+    std::string pin;+    if (!explicit_pin.empty()) {+        pin = explicit_pin;+    } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {+        pin = *configured;     }-  }-  std::string pin;-  if (!explicit_pin.empty()) {-    pin = explicit_pin;-  } else if (auto configured =-                 config_value(root, remote_key(remote_name, "tls-pin"))) {-    pin = *configured;-  } -  std::optional<Id> target;-  std::vector<Id> commits;-  std::vector<Id> objects;-  {-    Store store = Store::open_all(root);-    auto view = current_view(root, store);-    View empty;-    const View &current = view ? *view : empty;-    target = resolve_revision(store, current, bookmark);-    if (!target) {-      error_prefix();-      std::cout << "unknown bookmark: " << bookmark << "\n";-      return 1;+    std::optional<Id> target;+    std::vector<Id> commits;+    std::vector<Id> objects;+    {+        Store store = Store::open_all(root);+        auto view = current_view(root, store);+        View empty;+        const View& current = view ? *view : empty;+        target = resolve_revision(store, current, bookmark);+        if (!target) {+            error_prefix();+            std::cout << "unknown bookmark: " << bookmark << "\n";+            return 1;+        }+        const std::array<Id, 1> roots{*target};+        commits = collect_commits(store, roots);+        objects = objects_for_commits(store, commits);     }-    const std::array<Id, 1> roots{*target};-    commits = collect_commits(store, roots);-    objects = objects_for_commits(store, commits);-  }-  const std::string repo_name = proto::url_repo_name(*url);-  auto client = proto::Client::connect(*url, key, repo_name, pin);-  if (!client) {-    report_connect_failure("cannot connect or authenticate");-    return 1;-  }-  std::vector<proto::RefInfo> refs;-  if (!client->list_refs(refs)) {-    report_client_error(*client, "cannot list remote refs");-    return 1;-  }-  std::optional<Id> old;-  for (const auto &ref : refs) {-    if (ref.name == bookmark)-      old = ref.target;-  }-  if (old && same_id(*old, *target)) {+    const std::string repo_name = proto::url_repo_name(*url);+    auto client = proto::Client::connect(*url, key, repo_name, pin);+    if (!client) {+        report_connect_failure("cannot connect or authenticate");+        return 1;+    }+    std::vector<proto::RefInfo> refs;+    if (!client->list_refs(refs)) {+        report_client_error(*client, "cannot list remote refs");+        return 1;+    }+    std::optional<Id> old;+    for (const auto& ref : refs) {+        if (ref.name == bookmark)+            old = ref.target;+    }+    if (old && same_id(*old, *target)) {+        info_prefix();+        std::cout << "nothing to push, everything is up to date\n";+        return 0;+    }+    if (!client->push_objects(root, objects)) {+        report_client_error(*client, "push failed");+        return 1;+    }+    std::vector<proto::UpdateRef> updates;+    updates.push_back(proto::UpdateRef{bookmark, old, target});+    if (!client->update_refs(updates)) {+        report_client_error(*client, "ref update rejected");+        return 1;+    }     info_prefix();-    std::cout << "nothing to push, everything is up to date\n";+    std::cout << "pushed " << bookmark << " to " << remote_name << "\n";     return 0;-  }-  if (!client->push_objects(root, objects)) {-    report_client_error(*client, "push failed");-    return 1;-  }-  std::vector<proto::UpdateRef> updates;-  updates.push_back(proto::UpdateRef{bookmark, old, target});-  if (!client->update_refs(updates)) {-    report_client_error(*client, "ref update rejected");-    return 1;-  }-  info_prefix();-  std::cout << "pushed " << bookmark << " to " << remote_name << "\n";-  return 0; }  // ---------------------------------------------------------------------------@@ -904,76 +886,73 @@ // serve // --------------------------------------------------------------------------- -int serve_run(const std::vector<std::string> &args) {-  bool stdio_mode = false;-  std::string listen;-  std::string root = ".";-  std::string cert;-  std::string key;-  std::string repo_path = ".";-  std::uint64_t quota_bytes = 0;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (arg == "-stdio") {-      stdio_mode = true;-      if (i + 1 < args.size())-        repo_path = args[++i];-    } else if (arg == "-listen") {-      if (i + 1 < args.size())-        listen = args[++i];-    } else if (arg == "-root") {-      if (i + 1 < args.size())-        root = args[++i];-    } else if (arg == "-tls-cert") {-      if (i + 1 < args.size())-        cert = args[++i];-    } else if (arg == "-tls-key") {-      if (i + 1 < args.size())-        key = args[++i];-    } else if (arg == "-quota") {-      if (i + 1 >= args.size()) {+int serve_run(const std::vector<std::string>& args) {+    bool stdio_mode = false;+    std::string listen;+    std::string root = ".";+    std::string cert;+    std::string key;+    std::string repo_path = ".";+    std::uint64_t quota_bytes = 0;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (arg == "-stdio") {+            stdio_mode = true;+            if (i + 1 < args.size())+                repo_path = args[++i];+        } else if (arg == "-listen") {+            if (i + 1 < args.size())+                listen = args[++i];+        } else if (arg == "-root") {+            if (i + 1 < args.size())+                root = args[++i];+        } else if (arg == "-tls-cert") {+            if (i + 1 < args.size())+                cert = args[++i];+        } else if (arg == "-tls-key") {+            if (i + 1 < args.size())+                key = args[++i];+        } else if (arg == "-quota") {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << "-quota requires a byte count\n";+                return 1;+            }+            const std::string& value = args[++i];+            std::uint64_t parsed = 0;+            const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);+            if (result.ec != std::errc() || result.ptr != value.data() + value.size()) {+                error_prefix();+                std::cout << "-quota requires a byte count\n";+                return 1;+            }+            quota_bytes = parsed;+        } else {+            error_prefix();+            std::cout << "unknown serve option: " << arg << "\n";+            return 1;+        }+    }+    if (stdio_mode) {+        auto repo = discover_repo(path_from_bytes(repo_path));+        if (!repo) {+            error_prefix();+            std::cout << "not a veins repository\n";+            return 1;+        }+        return server::serve_stdio(*repo, quota_bytes);+    }+    if (listen.empty()) {         error_prefix();-        std::cout << "-quota requires a byte count\n";+        std::cout << "serve requires -stdio or -listen\n";         return 1;-      }-      const std::string &value = args[++i];-      std::uint64_t parsed = 0;-      const auto result =-          std::from_chars(value.data(), value.data() + value.size(), parsed);-      if (result.ec != std::errc() ||-          result.ptr != value.data() + value.size()) {+    }+    if (cert.empty() || key.empty()) {         error_prefix();-        std::cout << "-quota requires a byte count\n";+        std::cout << "TLS requires -tls-cert and -tls-key\n";         return 1;-      }-      quota_bytes = parsed;-    } else {-      error_prefix();-      std::cout << "unknown serve option: " << arg << "\n";-      return 1;-    }-  }-  if (stdio_mode) {-    auto repo = discover_repo(path_from_bytes(repo_path));-    if (!repo) {-      error_prefix();-      std::cout << "not a veins repository\n";-      return 1;     }-    return server::serve_stdio(*repo, quota_bytes);-  }-  if (listen.empty()) {-    error_prefix();-    std::cout << "serve requires -stdio or -listen\n";-    return 1;-  }-  if (cert.empty() || key.empty()) {-    error_prefix();-    std::cout << "TLS requires -tls-cert and -tls-key\n";-    return 1;-  }-  return server::serve_listen(listen, path_from_bytes(root), cert, key,-                              quota_bytes);+    return server::serve_listen(listen, path_from_bytes(root), cert, key, quota_bytes); }  // ---------------------------------------------------------------------------@@ -980,60 +959,60 @@ // key // --------------------------------------------------------------------------- -int key_run(const std::vector<std::string> &args) {-  const std::string sub = arg_at(args, 2);-  if (sub.empty()) {-    error_prefix();-    std::cout << "expected key subcommand (generate, list, show, import)\n";-    return 1;-  }-  if (sub == "generate") {-    const std::string name = arg_at(args, 3);-    if (name.empty()) {-      error_prefix();-      std::cout << "key generate requires a name\n";-      return 1;-    }-    auto key = auth::generate_key(name);-    if (!key) {-      error_prefix();-      std::cout << "cannot create key\n";-      return 1;+int key_run(const std::vector<std::string>& args) {+    const std::string sub = arg_at(args, 2);+    if (sub.empty()) {+        error_prefix();+        std::cout << "expected key subcommand (generate, list, show, import)\n";+        return 1;     }-    print_key(*key);-    return 0;-  }-  if (sub == "list") {-    for (const auto &name : auth::list_key_names()) {-      if (auto key = auth::load_key(name))+    if (sub == "generate") {+        const std::string name = arg_at(args, 3);+        if (name.empty()) {+            error_prefix();+            std::cout << "key generate requires a name\n";+            return 1;+        }+        auto key = auth::generate_key(name);+        if (!key) {+            error_prefix();+            std::cout << "cannot create key\n";+            return 1;+        }         print_key(*key);+        return 0;     }-    return 0;-  }-  if (sub == "show") {-    const std::string name = arg_at(args, 3);-    if (name.empty()) {-      error_prefix();-      std::cout << "key show requires a name\n";-      return 1;+    if (sub == "list") {+        for (const auto& name : auth::list_key_names()) {+            if (auto key = auth::load_key(name))+                print_key(*key);+        }+        return 0;     }-    auto key = auth::load_key(name);-    if (!key) {-      error_prefix();-      std::cout << "key not found or has unsafe permissions\n";-      return 1;+    if (sub == "show") {+        const std::string name = arg_at(args, 3);+        if (name.empty()) {+            error_prefix();+            std::cout << "key show requires a name\n";+            return 1;+        }+        auto key = auth::load_key(name);+        if (!key) {+            error_prefix();+            std::cout << "key not found or has unsafe permissions\n";+            return 1;+        }+        print_key(*key);+        return 0;     }-    print_key(*key);-    return 0;-  }-  if (sub == "import") {+    if (sub == "import") {+        error_prefix();+        std::cout << "OpenSSH key import is not supported\n";+        return 1;+    }     error_prefix();-    std::cout << "OpenSSH key import is not supported\n";+    std::cout << "unknown key subcommand: " << sub << "\n";     return 1;-  }-  error_prefix();-  std::cout << "unknown key subcommand: " << sub << "\n";-  return 1; }  // ---------------------------------------------------------------------------@@ -1040,57 +1019,57 @@ // auth // --------------------------------------------------------------------------- -int auth_run(const std::vector<std::string> &args) {-  const std::string sub = arg_at(args, 2);-  if (sub.empty()) {-    auth_usage();-    return 1;-  }-  if (sub == "use") {-    const std::string name = arg_at(args, 3);-    if (name.empty()) {-      auth_usage();-      return 1;+int auth_run(const std::vector<std::string>& args) {+    const std::string sub = arg_at(args, 2);+    if (sub.empty()) {+        auth_usage();+        return 1;     }-    if (!auth::load_key(name)) {-      error_prefix();-      std::cout << "key not found or has unsafe permissions: " << name << "\n";-      return 1;+    if (sub == "use") {+        const std::string name = arg_at(args, 3);+        if (name.empty()) {+            auth_usage();+            return 1;+        }+        if (!auth::load_key(name)) {+            error_prefix();+            std::cout << "key not found or has unsafe permissions: " << name << "\n";+            return 1;+        }+        const std::string target = auth::normalize_target(arg_at(args, 4));+        if (!auth::set_key(target, name)) {+            error_prefix();+            std::cout << "cannot write auth configuration\n";+            return 1;+        }+        if (target == "default")+            std::cout << "default key set to " << name << "\n";+        else+            std::cout << "key for " << target << " set to " << name << "\n";+        return 0;     }-    const std::string target = auth::normalize_target(arg_at(args, 4));-    if (!auth::set_key(target, name)) {-      error_prefix();-      std::cout << "cannot write auth configuration\n";-      return 1;+    if (sub == "list") {+        const auto lines = auth::list_credential_lines();+        if (lines.empty())+            std::cout << "no stored credentials\n";+        for (const auto& line : lines)+            std::cout << line;+        return 0;     }-    if (target == "default")-      std::cout << "default key set to " << name << "\n";-    else-      std::cout << "key for " << target << " set to " << name << "\n";-    return 0;-  }-  if (sub == "list") {-    const auto lines = auth::list_credential_lines();-    if (lines.empty())-      std::cout << "no stored credentials\n";-    for (const auto &line : lines)-      std::cout << line;-    return 0;-  }-  if (sub == "remove") {-    const std::string target = auth::normalize_target(arg_at(args, 3));-    if (auth::remove_key(target)) {-      std::cout << "removed " << target << "\n";-      return 0;+    if (sub == "remove") {+        const std::string target = auth::normalize_target(arg_at(args, 3));+        if (auth::remove_key(target)) {+            std::cout << "removed " << target << "\n";+            return 0;+        }+        error_prefix();+        std::cout << "no credential for " << target << "\n";+        return 1;     }     error_prefix();-    std::cout << "no credential for " << target << "\n";+    std::cout << "unknown auth subcommand: " << sub << "\n";+    auth_usage();     return 1;-  }-  error_prefix();-  std::cout << "unknown auth subcommand: " << sub << "\n";-  auth_usage();-  return 1; }  // ---------------------------------------------------------------------------@@ -1097,113 +1076,111 @@ // access // --------------------------------------------------------------------------- -int access_run(const std::vector<std::string> &args) {-  const std::string sub = arg_at(args, 2);-  if (sub.empty()) {-    error_prefix();-    std::cout << "expected access subcommand\n";-    return 1;-  }-  auto repo = discover_repo(".");-  if (!repo) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const fs::path root = *repo;-  if (sub == "add") {-    std::string role;-    std::string key_arg;-    std::string name;-    for (std::size_t i = 3; i < args.size(); ++i) {-      const std::string &arg = args[i];-      if (arg == "-role" && i + 1 < args.size()) {-        role = args[++i];-      } else if (arg == "-key" && i + 1 < args.size()) {-        key_arg = args[++i];-      } else if (arg == "-name" && i + 1 < args.size()) {-        name = args[++i];-      } else {+int access_run(const std::vector<std::string>& args) {+    const std::string sub = arg_at(args, 2);+    if (sub.empty()) {         error_prefix();-        std::cout << "unknown access add option: " << arg << "\n";+        std::cout << "expected access subcommand\n";         return 1;-      }-    }-    if (role.empty() || key_arg.empty()) {-      error_prefix();-      std::cout << "access add requires -role and -key\n";-      return 1;-    }-    std::uint8_t role_code = auth::ROLE_READ;-    if (role == "write") {-      role_code = auth::ROLE_WRITE;-    } else if (role != "read") {-      error_prefix();-      std::cout << "role must be read or write\n";-      return 1;-    }-    auto public_key = read_public_key(key_arg);-    if (!public_key) {-      error_prefix();-      std::cout << "invalid public key\n";-      return 1;-    }-    if (!auth::add_access(root, role_code, *public_key, name)) {-      error_prefix();-      std::cout << "cannot add key\n";-      return 1;     }-    info_prefix();-    std::cout << "access granted\n";-    return 0;-  }-  if (sub == "list") {-    const auth::Access access = auth::load_access(root);-    if (!access.valid) {-      error_prefix();-      std::cout << "invalid access file at line " << access.error_line << "\n";-      return 1;+    auto repo = discover_repo(".");+    if (!repo) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;     }-    std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off")-              << "\n";-    for (const auto &entry : access.entries) {-      std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "-                << key_fingerprint(entry.public_key) << " " << entry.name-                << "\n";+    const fs::path root = *repo;+    if (sub == "add") {+        std::string role;+        std::string key_arg;+        std::string name;+        for (std::size_t i = 3; i < args.size(); ++i) {+            const std::string& arg = args[i];+            if (arg == "-role" && i + 1 < args.size()) {+                role = args[++i];+            } else if (arg == "-key" && i + 1 < args.size()) {+                key_arg = args[++i];+            } else if (arg == "-name" && i + 1 < args.size()) {+                name = args[++i];+            } else {+                error_prefix();+                std::cout << "unknown access add option: " << arg << "\n";+                return 1;+            }+        }+        if (role.empty() || key_arg.empty()) {+            error_prefix();+            std::cout << "access add requires -role and -key\n";+            return 1;+        }+        std::uint8_t role_code = auth::ROLE_READ;+        if (role == "write") {+            role_code = auth::ROLE_WRITE;+        } else if (role != "read") {+            error_prefix();+            std::cout << "role must be read or write\n";+            return 1;+        }+        auto public_key = read_public_key(key_arg);+        if (!public_key) {+            error_prefix();+            std::cout << "invalid public key\n";+            return 1;+        }+        if (!auth::add_access(root, role_code, *public_key, name)) {+            error_prefix();+            std::cout << "cannot add key\n";+            return 1;+        }+        info_prefix();+        std::cout << "access granted\n";+        return 0;     }-    return 0;-  }-  if (sub == "remove") {-    const std::string arg = arg_at(args, 3);-    if (arg.empty()) {-      error_prefix();-      std::cout << "access remove requires a fingerprint or name\n";-      return 1;+    if (sub == "list") {+        const auth::Access access = auth::load_access(root);+        if (!access.valid) {+            error_prefix();+            std::cout << "invalid access file at line " << access.error_line << "\n";+            return 1;+        }+        std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off") << "\n";+        for (const auto& entry : access.entries) {+            std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "+                      << key_fingerprint(entry.public_key) << " " << entry.name << "\n";+        }+        return 0;     }-    const bool is_fingerprint = arg.size() == 26;-    const std::string fingerprint = is_fingerprint ? arg : std::string();-    const std::string name = is_fingerprint ? std::string() : arg;-    if (!auth::remove_access(root, fingerprint, name)) {-      error_prefix();-      std::cout << "key not found or cannot write access file\n";-      return 1;+    if (sub == "remove") {+        const std::string arg = arg_at(args, 3);+        if (arg.empty()) {+            error_prefix();+            std::cout << "access remove requires a fingerprint or name\n";+            return 1;+        }+        const bool is_fingerprint = arg.size() == 26;+        const std::string fingerprint = is_fingerprint ? arg : std::string();+        const std::string name = is_fingerprint ? std::string() : arg;+        if (!auth::remove_access(root, fingerprint, name)) {+            error_prefix();+            std::cout << "key not found or cannot write access file\n";+            return 1;+        }+        info_prefix();+        std::cout << "access removed\n";+        return 0;     }-    info_prefix();-    std::cout << "access removed\n";-    return 0;-  }-  if (sub == "anonymous") {-    const bool on = arg_at(args, 3) == "on";-    if (!auth::set_anonymous(root, on)) {-      error_prefix();-      std::cout << "cannot update access file\n";-      return 1;+    if (sub == "anonymous") {+        const bool on = arg_at(args, 3) == "on";+        if (!auth::set_anonymous(root, on)) {+            error_prefix();+            std::cout << "cannot update access file\n";+            return 1;+        }+        return 0;     }-    return 0;-  }-  error_prefix();-  std::cout << "unknown access subcommand: " << sub << "\n";-  return 1;+    error_prefix();+    std::cout << "unknown access subcommand: " << sub << "\n";+    return 1; }  // ---------------------------------------------------------------------------@@ -1210,64 +1187,64 @@ // whoami // --------------------------------------------------------------------------- -int whoami_run(const std::vector<std::string> &args) {-  std::string remote = "origin";-  std::string url;-  std::string key;-  std::string repo_name;-  std::string pin;-  const std::string arg = arg_at(args, 2);-  if (!arg.empty()) {-    if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||-        starts_with(arg, "veins://")) {-      url = arg;-      repo_name = proto::url_repo_name(url);-    } else {-      remote = arg;+int whoami_run(const std::vector<std::string>& args) {+    std::string remote = "origin";+    std::string url;+    std::string key;+    std::string repo_name;+    std::string pin;+    const std::string arg = arg_at(args, 2);+    if (!arg.empty()) {+        if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||+            starts_with(arg, "veins://")) {+            url = arg;+            repo_name = proto::url_repo_name(url);+        } else {+            remote = arg;+        }     }-  }-  if (url.empty()) {-    auto repo = discover_repo(".");-    if (!repo) {-      error_prefix();-      std::cout << "not a veins repository\n";-      return 1;+    if (url.empty()) {+        auto repo = discover_repo(".");+        if (!repo) {+            error_prefix();+            std::cout << "not a veins repository\n";+            return 1;+        }+        const fs::path root = *repo;+        auto configured = config_value(root, remote_key(remote, "url"));+        if (!configured) {+            error_prefix();+            std::cout << "unknown remote\n";+            return 1;+        }+        url = *configured;+        if (auto k = config_value(root, remote_key(remote, "key"))) {+            if (auth::local_key_exists(*k))+                key = *k;+        }+        if (auto p = config_value(root, remote_key(remote, "tls-pin")))+            pin = *p;+        repo_name = proto::url_repo_name(url);     }-    const fs::path root = *repo;-    auto configured = config_value(root, remote_key(remote, "url"));-    if (!configured) {-      error_prefix();-      std::cout << "unknown remote\n";-      return 1;+    if (key.empty()) {+        if (auto fallback = auth::key_for_url(url))+            key = *fallback;     }-    url = *configured;-    if (auto k = config_value(root, remote_key(remote, "key"))) {-      if (auth::local_key_exists(*k))-        key = *k;+    auto client = proto::Client::connect(url, key, repo_name, pin);+    if (!client) {+        report_connect_failure("cannot authenticate");+        return 1;     }-    if (auto p = config_value(root, remote_key(remote, "tls-pin")))-      pin = *p;-    repo_name = proto::url_repo_name(url);-  }-  if (key.empty()) {-    if (auto fallback = auth::key_for_url(url))-      key = *fallback;-  }-  auto client = proto::Client::connect(url, key, repo_name, pin);-  if (!client) {-    report_connect_failure("cannot authenticate");-    return 1;-  }-  std::uint8_t role = 0;-  std::string fingerprint;-  if (!client->whoami(role, fingerprint)) {-    error_prefix();-    std::cout << "cannot authenticate\n";-    return 1;-  }-  std::cout << "role: " << role_text(role) << "\n";-  std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";-  return 0;+    std::uint8_t role = 0;+    std::string fingerprint;+    if (!client->whoami(role, fingerprint)) {+        error_prefix();+        std::cout << "cannot authenticate\n";+        return 1;+    }+    std::cout << "role: " << role_text(role) << "\n";+    std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";+    return 0; }  // ---------------------------------------------------------------------------@@ -1275,85 +1252,80 @@ // ---------------------------------------------------------------------------  bool net_help(std::string_view command) {-  if (command == "remote") {-    std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";-    std::cout << "manage native remotes stored in .veins/config\n\n";-    std::cout << "subcommands:\n";-    std::cout << "  add <name> <url> [-key:<name>] [-pin:<hash>]\n";-    std::cout << "                            add a remote\n";-    std::cout << "  set-url <name> <url> [-key:<name>] [-pin:<hash>]\n";-    std::cout << "                            change a remote URL (and "-                 "optionally key/pin)\n";-    std::cout << "  list                      list remotes\n";-    std::cout << "  remove <name>             remove a remote\n\n";-    std::cout << "an empty -key: or -pin: value clears that setting\n\n";-    std::cout << "examples:\n";-    std::cout-        << "  vn remote add origin veins://127.0.0.1:7419/navid-m/veins2\n";-    std::cout-        << "  vn remote set-url origin veins://example/repo -key:my-key\n";-    return true;-  }-  if (command == "clone") {-    std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "-                 "[-pin:<sha256>] [path]\n\n";-    std::cout << "clone a repository over file://, ssh://, or veins://\n\n";-    std::cout << "without -key, the key stored by 'vn auth use' is used when "-                 "available\n";-    return true;-  }-  if (command == "fetch") {-    std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";-    std::cout << "fetch new history and chunks from a configured native "-                 "remote\n\n";-    std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";-    return true;-  }-  if (command == "push") {-    std::cout-        << "usage: vn push [-key:<name>] [<remote>] [<bookmark>] [path]\n\n";-    std::cout << "push a bookmark to a configured native remote\n\n";-    std::cout << "without <bookmark>, the current bookmark is pushed\n";-    std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";-    return true;-  }-  if (command == "serve") {-    std::cout << "usage: vn serve -stdio <repo> [-quota <bytes>]\n";-    std::cout << "       vn serve -listen <addr:port> -root <dir> -tls-cert "-                 "<file> -tls-key <file> [-quota <bytes>]\n\n";-    std::cout-        << "run the native server over standard input/output or TLS 1.3\n";-    std::cout << "-quota limits stored pack and index bytes per top-level "-                 "namespace\n";-    return true;-  }-  if (command == "key") {-    std::cout << "usage: vn key <generate|list|show> [name]\n\n";-    std::cout << "manage local Ed25519 keys in the user key directory\n";-    return true;-  }-  if (command == "auth") {-    std::cout << "usage: vn auth <use|list|remove> ...\n\n";-    std::cout << "remember which key clone/fetch/push should use\n\n";-    std::cout << "  vn auth use <key> [<host|url>]   set the default or host "-                 "key\n";-    std::cout-        << "  vn auth list                     show stored key mappings\n";-    std::cout << "  vn auth remove [<host|url>]      remove a mapping\n";-    return true;-  }-  if (command == "access") {-    std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";-    std::cout << "manage a served repository's .veins/access policy\n";-    return true;-  }-  if (command == "whoami") {-    std::cout << "usage: vn whoami [<remote>|<url>]\n\n";-    std::cout << "connect to a server and report the granted role and key "-                 "fingerprint\n";-    return true;-  }-  return false;+    if (command == "remote") {+        std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";+        std::cout << "manage native remotes stored in .veins/config\n\n";+        std::cout << "subcommands:\n";+        std::cout << "  add <name> <url> [-key:<name>] [-pin:<hash>]\n";+        std::cout << "                            add a remote\n";+        std::cout << "  set-url <name> <url> [-key:<name>] [-pin:<hash>]\n";+        std::cout << "                            change a remote URL (and "+                     "optionally key/pin)\n";+        std::cout << "  list                      list remotes\n";+        std::cout << "  remove <name>             remove a remote\n\n";+        std::cout << "an empty -key: or -pin: value clears that setting\n\n";+        std::cout << "examples:\n";+        std::cout << "  vn remote add origin veins://127.0.0.1:7419/navid-m/veins2\n";+        std::cout << "  vn remote set-url origin veins://example/repo -key:my-key\n";+        return true;+    }+    if (command == "clone") {+        std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "+                     "[-pin:<sha256>] [path]\n\n";+        std::cout << "clone a repository over file://, ssh://, or veins://\n\n";+        std::cout << "without -key, the key stored by 'vn auth use' is used when "+                     "available\n";+        return true;+    }+    if (command == "fetch") {+        std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";+        std::cout << "fetch new history and chunks from a configured native "+                     "remote\n\n";+        std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+        return true;+    }+    if (command == "push") {+        std::cout << "usage: vn push [-key:<name>] [<remote>] [<bookmark>] [path]\n\n";+        std::cout << "push a bookmark to a configured native remote\n\n";+        std::cout << "without <bookmark>, the current bookmark is pushed\n";+        std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";+        return true;+    }+    if (command == "serve") {+        std::cout << "usage: vn serve -stdio <repo> [-quota <bytes>]\n";+        std::cout << "       vn serve -listen <addr:port> -root <dir> -tls-cert "+                     "<file> -tls-key <file> [-quota <bytes>]\n\n";+        std::cout << "run the native server over standard input/output or TLS 1.3\n";+        std::cout << "-quota limits stored pack and index bytes per top-level "+                     "namespace\n";+        return true;+    }+    if (command == "key") {+        std::cout << "usage: vn key <generate|list|show> [name]\n\n";+        std::cout << "manage local Ed25519 keys in the user key directory\n";+        return true;+    }+    if (command == "auth") {+        std::cout << "usage: vn auth <use|list|remove> ...\n\n";+        std::cout << "remember which key clone/fetch/push should use\n\n";+        std::cout << "  vn auth use <key> [<host|url>]   set the default or host "+                     "key\n";+        std::cout << "  vn auth list                     show stored key mappings\n";+        std::cout << "  vn auth remove [<host|url>]      remove a mapping\n";+        return true;+    }+    if (command == "access") {+        std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";+        std::cout << "manage a served repository's .veins/access policy\n";+        return true;+    }+    if (command == "whoami") {+        std::cout << "usage: vn whoami [<remote>|<url>]\n\n";+        std::cout << "connect to a server and report the granted role and key "+                     "fingerprint\n";+        return true;+    }+    return false; }  } // namespace vn--- a/xveins/src/net_commands.h+++ b/xveins/src/net_commands.h@@ -6,15 +6,15 @@  namespace vn { -int remote_run(const std::vector<std::string> &args);-int clone_run(const std::vector<std::string> &args);-int fetch_run(const std::vector<std::string> &args);-int push_run(const std::vector<std::string> &args);-int serve_run(const std::vector<std::string> &args);-int key_run(const std::vector<std::string> &args);-int auth_run(const std::vector<std::string> &args);-int access_run(const std::vector<std::string> &args);-int whoami_run(const std::vector<std::string> &args);+int remote_run(const std::vector<std::string>& args);+int clone_run(const std::vector<std::string>& args);+int fetch_run(const std::vector<std::string>& args);+int push_run(const std::vector<std::string>& args);+int serve_run(const std::vector<std::string>& args);+int key_run(const std::vector<std::string>& args);+int auth_run(const std::vector<std::string>& args);+int access_run(const std::vector<std::string>& args);+int whoami_run(const std::vector<std::string>& args);  // Print help for a network command. Returns false when `command` is not one of // them.--- a/xveins/src/object.cpp+++ b/xveins/src/object.cpp@@ -6,28 +6,28 @@ namespace vn {  std::string_view type_name(std::uint8_t type) {-  switch (type) {-  case TYPE_CHUNK:-    return "chunk";-  case TYPE_BLOB:-    return "blob";-  case TYPE_TREE:-    return "tree";-  case TYPE_COMMIT:-    return "commit";-  case TYPE_CONFLICT:-    return "conflict";-  case TYPE_OPERATION:-    return "operation";-  case TYPE_VIEW:-    return "view";-  default:-    return "unknown";-  }+    switch (type) {+    case TYPE_CHUNK:+        return "chunk";+    case TYPE_BLOB:+        return "blob";+    case TYPE_TREE:+        return "tree";+    case TYPE_COMMIT:+        return "commit";+    case TYPE_CONFLICT:+        return "conflict";+    case TYPE_OPERATION:+        return "operation";+    case TYPE_VIEW:+        return "view";+    default:+        return "unknown";+    } }  bool type_valid(std::uint8_t type) {-  return type >= TYPE_CHUNK && type <= TYPE_VIEW;+    return type >= TYPE_CHUNK && type <= TYPE_VIEW; }  // ---------------------------------------------------------------------------@@ -34,50 +34,52 @@ // Names // --------------------------------------------------------------------------- -static bool is_dot_name(std::string_view s) { return s == "." || s == ".."; }+static bool is_dot_name(std::string_view s) {+    return s == "." || s == "..";+}  bool valid_name(std::string_view name) {-  if (name.empty() || name.size() > MAX_NAME_LEN)-    return false;-  for (char c : name) {-    if (c == '\0' || c == '/')-      return false;-  }-  if (is_dot_name(name))-    return false;-  if (ascii_iequals(bytes_of(name), bytes_of(".veins")))-    return false;-  return true;+    if (name.empty() || name.size() > MAX_NAME_LEN)+        return false;+    for (char c : name) {+        if (c == '\0' || c == '/')+            return false;+    }+    if (is_dot_name(name))+        return false;+    if (ascii_iequals(bytes_of(name), bytes_of(".veins")))+        return false;+    return true; }  static bool valid_component(std::string_view component) {-  if (component.empty() || component.size() > MAX_NAME_LEN)-    return false;-  if (is_dot_name(component))-    return false;-  for (char c : component) {-    if (c == '\0' || c == '/')-      return false;-  }-  return true;+    if (component.empty() || component.size() > MAX_NAME_LEN)+        return false;+    if (is_dot_name(component))+        return false;+    for (char c : component) {+        if (c == '\0' || c == '/')+            return false;+    }+    return true; }  bool valid_path(std::string_view path) {-  if (path.empty() || path.size() > MAX_PATH_LEN)-    return false;-  if (path.front() == '/')-    return false;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= path.size(); ++i) {-    const bool at_end = i == path.size();-    const bool sep = !at_end && path[i] == '/';-    if (at_end || sep) {-      if (!valid_component(path.substr(start, i - start)))+    if (path.empty() || path.size() > MAX_PATH_LEN)         return false;-      start = i + 1;+    if (path.front() == '/')+        return false;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= path.size(); ++i) {+        const bool at_end = i == path.size();+        const bool sep = !at_end && path[i] == '/';+        if (at_end || sep) {+            if (!valid_component(path.substr(start, i - start)))+                return false;+            start = i + 1;+        }     }-  }-  return true;+    return true; }  // ---------------------------------------------------------------------------@@ -85,56 +87,54 @@ // ---------------------------------------------------------------------------  static std::array<std::uint64_t, 256> make_gear_table() {-  static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', 'f',-                                            'a', 's', 't', 'c', 'd', 'c', '/',-                                            'g', 'e', 'a', 'r', '/', 'v', '1'};-  std::array<std::uint64_t, 256> table{};-  for (std::size_t i = 0; i < table.size(); ++i) {-    blake3_hasher hasher;-    blake3_hasher_init(&hasher);-    blake3_hasher_update(&hasher, prefix, sizeof(prefix));-    const auto byte = static_cast<std::uint8_t>(i);-    blake3_hasher_update(&hasher, &byte, 1);-    std::array<std::uint8_t, 32> digest{};-    blake3_hasher_finalize(&hasher, digest.data(), digest.size());-    std::uint64_t value = 0;-    for (int j = 0; j < 8; ++j)-      value |= static_cast<std::uint64_t>(digest[static_cast<std::size_t>(j)])-               << (j * 8);-    table[i] = value;-  }-  return table;+    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '/', 'f', 'a', 's', 't', 'c',+                                              'd', 'c', '/', 'g', 'e', 'a', 'r', '/', 'v', '1'};+    std::array<std::uint64_t, 256> table{};+    for (std::size_t i = 0; i < table.size(); ++i) {+        blake3_hasher hasher;+        blake3_hasher_init(&hasher);+        blake3_hasher_update(&hasher, prefix, sizeof(prefix));+        const auto byte = static_cast<std::uint8_t>(i);+        blake3_hasher_update(&hasher, &byte, 1);+        std::array<std::uint8_t, 32> digest{};+        blake3_hasher_finalize(&hasher, digest.data(), digest.size());+        std::uint64_t value = 0;+        for (int j = 0; j < 8; ++j)+            value |= static_cast<std::uint64_t>(digest[static_cast<std::size_t>(j)]) << (j * 8);+        table[i] = value;+    }+    return table; } -const std::array<std::uint64_t, 256> &fastcdc_gear() {-  static const auto table = make_gear_table();-  return table;+const std::array<std::uint64_t, 256>& fastcdc_gear() {+    static const auto table = make_gear_table();+    return table; }  std::size_t fastcdc_next(Bytes data) {-  constexpr std::size_t min_size = 16384;-  constexpr std::size_t avg_size = 65536;-  constexpr std::size_t max_size = 262144;-  constexpr std::uint64_t mask_s = 0x3ffffull;-  constexpr std::uint64_t mask_l = 0x3fffull;-  const std::size_t len = data.size();-  if (len <= min_size)-    return len;-  const std::size_t limit = std::min(len, max_size);-  const std::size_t normal = std::min(avg_size, limit);-  const auto &gear = fastcdc_gear();-  std::uint64_t fp = 0;-  for (std::size_t i = min_size; i < normal; ++i) {-    fp = (fp >> 1) + gear[data[i]];-    if ((fp & mask_s) == 0)-      return i + 1;-  }-  for (std::size_t i = normal; i < limit; ++i) {-    fp = (fp >> 1) + gear[data[i]];-    if ((fp & mask_l) == 0)-      return i + 1;-  }-  return limit;+    constexpr std::size_t min_size = 16384;+    constexpr std::size_t avg_size = 65536;+    constexpr std::size_t max_size = 262144;+    constexpr std::uint64_t mask_s = 0x3ffffull;+    constexpr std::uint64_t mask_l = 0x3fffull;+    const std::size_t len = data.size();+    if (len <= min_size)+        return len;+    const std::size_t limit = std::min(len, max_size);+    const std::size_t normal = std::min(avg_size, limit);+    const auto& gear = fastcdc_gear();+    std::uint64_t fp = 0;+    for (std::size_t i = min_size; i < normal; ++i) {+        fp = (fp >> 1) + gear[data[i]];+        if ((fp & mask_s) == 0)+            return i + 1;+    }+    for (std::size_t i = normal; i < limit; ++i) {+        fp = (fp >> 1) + gear[data[i]];+        if ((fp & mask_l) == 0)+            return i + 1;+    }+    return limit; }  // ---------------------------------------------------------------------------@@ -142,150 +142,148 @@ // ---------------------------------------------------------------------------  Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data) {-  ByteWriter w(data.size() + 8);-  w.u8(static_cast<std::uint8_t>(BlobForm::Inline));-  w.varint(data.size());-  w.raw(data);-  return w.take();+    ByteWriter w(data.size() + 8);+    w.u8(static_cast<std::uint8_t>(BlobForm::Inline));+    w.varint(data.size());+    w.raw(data);+    return w.take(); }  Result<Blob> decode_blob(Bytes body) {-  Reader r(body);-  const auto form = r.u8();-  if (!form)-    return unexpected(form.error());-  if (*form > 2)-    return fail(ErrorKind::InvalidValue, 0);-  Blob blob;-  blob.form = static_cast<BlobForm>(*form);-  if (blob.form == BlobForm::Inline) {-    const auto data = r.bytes(INLINE_THRESHOLD);-    if (!data)-      return unexpected(data.error());-    blob.data.assign(data->begin(), data->end());+    Reader r(body);+    const auto form = r.u8();+    if (!form)+        return unexpected(form.error());+    if (*form > 2)+        return fail(ErrorKind::InvalidValue, 0);+    Blob blob;+    blob.form = static_cast<BlobForm>(*form);+    if (blob.form == BlobForm::Inline) {+        const auto data = r.bytes(INLINE_THRESHOLD);+        if (!data)+            return unexpected(data.error());+        blob.data.assign(data->begin(), data->end());+        const auto fin = r.finish();+        if (!fin)+            return unexpected(fin.error());+        return blob;+    }+    const auto count = r.list_len(MAX_MANIFEST_ENTRIES);+    if (!count)+        return unexpected(count.error());+    if (*count == 0)+        return fail(ErrorKind::InvalidValue, 1);+    std::uint64_t total = 0;+    blob.entries.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const std::size_t at = r.offset();+        const auto cid = r.id();+        if (!cid)+            return unexpected(cid.error());+        const auto length = r.varint();+        if (!length)+            return unexpected(length.error());+        if (*length == 0)+            return fail(ErrorKind::InvalidValue, at);+        if (blob.form == BlobForm::Leaf && *length > MAX_CHUNK_LEN)+            return fail(ErrorKind::LimitExceeded, at);+        const std::uint64_t next = total + *length;+        if (next < total)+            return fail(ErrorKind::InvalidValue, at);+        total = next;+        blob.entries.push_back(BlobEntry{*cid, *length});+    }     const auto fin = r.finish();     if (!fin)-      return unexpected(fin.error());+        return unexpected(fin.error());     return blob;-  }-  const auto count = r.list_len(MAX_MANIFEST_ENTRIES);-  if (!count)-    return unexpected(count.error());-  if (*count == 0)-    return fail(ErrorKind::InvalidValue, 1);-  std::uint64_t total = 0;-  blob.entries.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const std::size_t at = r.offset();-    const auto cid = r.id();-    if (!cid)-      return unexpected(cid.error());-    const auto length = r.varint();-    if (!length)-      return unexpected(length.error());-    if (*length == 0)-      return fail(ErrorKind::InvalidValue, at);-    if (blob.form == BlobForm::Leaf && *length > MAX_CHUNK_LEN)-      return fail(ErrorKind::LimitExceeded, at);-    const std::uint64_t next = total + *length;-    if (next < total)-      return fail(ErrorKind::InvalidValue, at);-    total = next;-    blob.entries.push_back(BlobEntry{*cid, *length});-  }-  const auto fin = r.finish();-  if (!fin)-    return unexpected(fin.error());-  return blob; }  struct NodeRef {-  Id id{};-  std::uint64_t length = 0;+    Id id{};+    std::uint64_t length = 0; };  struct Group {-  std::size_t start = 0;-  std::size_t count = 0;+    std::size_t start = 0;+    std::size_t count = 0; }; -static bool manifest_cut_after(const Id &id, std::size_t current_len) {-  if (current_len >= MAX_MANIFEST_ENTRIES)-    return true;-  if (current_len < 16)-    return false;-  return id[0] == 0;+static bool manifest_cut_after(const Id& id, std::size_t current_len) {+    if (current_len >= MAX_MANIFEST_ENTRIES)+        return true;+    if (current_len < 16)+        return false;+    return id[0] == 0; }  BlobBuild build_blob(Bytes data) {-  BlobBuild build;-  if (data.size() <= INLINE_THRESHOLD) {-    auto body = encode_inline_blob(data);-    if (!body)-      return build;-    build.root = object_id(TYPE_BLOB, bytes_of(*body));-    RawObject object{TYPE_BLOB, std::move(*body), std::nullopt};-    object.id = build.root;-    build.objects.push_back(std::move(object));-    return build;-  }--  std::vector<NodeRef> level;-  std::size_t off = 0;-  while (off < data.size()) {-    const std::size_t n = fastcdc_next(data.subspan(off));-    const Bytes chunk = data.subspan(off, n);-    const Id cid = object_id(TYPE_CHUNK, chunk);-    RawObject object{TYPE_CHUNK,-                     std::vector<std::uint8_t>(chunk.begin(), chunk.end()),-                     std::nullopt};-    object.id = cid;-    build.objects.push_back(std::move(object));-    level.push_back(NodeRef{cid, static_cast<std::uint64_t>(n)});-    off += n;-  }--  bool leaf_level = true;-  for (;;) {-    std::vector<Group> groups;-    std::size_t start = 0;-    for (std::size_t i = 0; i < level.size(); ++i) {-      const std::size_t current = i - start + 1;-      if (manifest_cut_after(level[i].id, current) || i + 1 == level.size()) {-        groups.push_back(Group{start, current});-        start = i + 1;-      }+    BlobBuild build;+    if (data.size() <= INLINE_THRESHOLD) {+        auto body = encode_inline_blob(data);+        if (!body)+            return build;+        build.root = object_id(TYPE_BLOB, bytes_of(*body));+        RawObject object{TYPE_BLOB, std::move(*body), std::nullopt};+        object.id = build.root;+        build.objects.push_back(std::move(object));+        return build;     } -    std::vector<NodeRef> next;-    for (const Group &group : groups) {-      ByteWriter w(group.count * 40 + 8);-      w.u8(static_cast<std::uint8_t>(leaf_level ? BlobForm::Leaf-                                                : BlobForm::Interior));-      w.varint(group.count);-      std::uint64_t total = 0;-      for (std::size_t i = 0; i < group.count; ++i) {-        const NodeRef &node = level[group.start + i];-        w.id(node.id);-        w.varint(node.length);-        total += node.length;-      }-      auto body = w.take();-      const Id node_id = object_id(TYPE_BLOB, bytes_of(body));-      RawObject object{TYPE_BLOB, std::move(body), std::nullopt};-      object.id = node_id;-      build.objects.push_back(std::move(object));-      next.push_back(NodeRef{node_id, total});+    std::vector<NodeRef> level;+    std::size_t off = 0;+    while (off < data.size()) {+        const std::size_t n = fastcdc_next(data.subspan(off));+        const Bytes chunk = data.subspan(off, n);+        const Id cid = object_id(TYPE_CHUNK, chunk);+        RawObject object{TYPE_CHUNK, std::vector<std::uint8_t>(chunk.begin(), chunk.end()),+                         std::nullopt};+        object.id = cid;+        build.objects.push_back(std::move(object));+        level.push_back(NodeRef{cid, static_cast<std::uint64_t>(n)});+        off += n;     } -    if (next.size() == 1) {-      build.root = next.front().id;-      break;+    bool leaf_level = true;+    for (;;) {+        std::vector<Group> groups;+        std::size_t start = 0;+        for (std::size_t i = 0; i < level.size(); ++i) {+            const std::size_t current = i - start + 1;+            if (manifest_cut_after(level[i].id, current) || i + 1 == level.size()) {+                groups.push_back(Group{start, current});+                start = i + 1;+            }+        }++        std::vector<NodeRef> next;+        for (const Group& group : groups) {+            ByteWriter w(group.count * 40 + 8);+            w.u8(static_cast<std::uint8_t>(leaf_level ? BlobForm::Leaf : BlobForm::Interior));+            w.varint(group.count);+            std::uint64_t total = 0;+            for (std::size_t i = 0; i < group.count; ++i) {+                const NodeRef& node = level[group.start + i];+                w.id(node.id);+                w.varint(node.length);+                total += node.length;+            }+            auto body = w.take();+            const Id node_id = object_id(TYPE_BLOB, bytes_of(body));+            RawObject object{TYPE_BLOB, std::move(body), std::nullopt};+            object.id = node_id;+            build.objects.push_back(std::move(object));+            next.push_back(NodeRef{node_id, total});+        }++        if (next.size() == 1) {+            build.root = next.front().id;+            break;+        }+        level = std::move(next);+        leaf_level = false;     }-    level = std::move(next);-    leaf_level = false;-  }-  return build;+    return build; }  // ---------------------------------------------------------------------------@@ -293,78 +291,77 @@ // ---------------------------------------------------------------------------  static bool valid_tree_kind(std::uint8_t kind) {-  return kind >= KIND_FILE && kind <= KIND_CONFLICT;+    return kind >= KIND_FILE && kind <= KIND_CONFLICT; } -static bool valid_submodule_target(const Id &id) {-  for (std::size_t i = 20; i < ID_LEN; ++i) {-    if (id[i] != 0)-      return false;-  }-  return true;+static bool valid_submodule_target(const Id& id) {+    for (std::size_t i = 20; i < ID_LEN; ++i) {+        if (id[i] != 0)+            return false;+    }+    return true; }  Result<Tree> decode_tree(Bytes body) {-  Reader r(body);-  const auto count = r.list_len(MAX_TREE_ENTRIES);-  if (!count)-    return unexpected(count.error());-  Tree tree;-  tree.entries.reserve(*count);-  std::optional<std::string> prev;-  for (std::size_t i = 0; i < *count; ++i) {-    const std::size_t at = r.offset();-    auto name = r.string_bytes(MAX_NAME_LEN);-    if (!name)-      return unexpected(name.error());-    if (!valid_name(*name))-      return fail(ErrorKind::InvalidName, at);-    if (prev) {-      const int c = compare(bytes_of(*prev), bytes_of(*name));-      if (c == 0)-        return fail(ErrorKind::Duplicate, at);-      if (c > 0)-        return fail(ErrorKind::Unsorted, at);+    Reader r(body);+    const auto count = r.list_len(MAX_TREE_ENTRIES);+    if (!count)+        return unexpected(count.error());+    Tree tree;+    tree.entries.reserve(*count);+    std::optional<std::string> prev;+    for (std::size_t i = 0; i < *count; ++i) {+        const std::size_t at = r.offset();+        auto name = r.string_bytes(MAX_NAME_LEN);+        if (!name)+            return unexpected(name.error());+        if (!valid_name(*name))+            return fail(ErrorKind::InvalidName, at);+        if (prev) {+            const int c = compare(bytes_of(*prev), bytes_of(*name));+            if (c == 0)+                return fail(ErrorKind::Duplicate, at);+            if (c > 0)+                return fail(ErrorKind::Unsorted, at);+        }+        const auto kind = r.u8();+        if (!kind)+            return unexpected(kind.error());+        if (!valid_tree_kind(*kind))+            return fail(ErrorKind::InvalidValue, at);+        const auto target = r.id();+        if (!target)+            return unexpected(target.error());+        if (*kind == KIND_SUBMODULE && !valid_submodule_target(*target))+            return fail(ErrorKind::InvalidValue, at);+        tree.entries.push_back(TreeEntry{std::move(*name), *kind, *target});+        prev = tree.entries.back().name;     }-    const auto kind = r.u8();-    if (!kind)-      return unexpected(kind.error());-    if (!valid_tree_kind(*kind))-      return fail(ErrorKind::InvalidValue, at);-    const auto target = r.id();-    if (!target)-      return unexpected(target.error());-    if (*kind == KIND_SUBMODULE && !valid_submodule_target(*target))-      return fail(ErrorKind::InvalidValue, at);-    tree.entries.push_back(TreeEntry{std::move(*name), *kind, *target});-    prev = tree.entries.back().name;-  }-  const auto fin = r.finish();-  if (!fin)-    return unexpected(fin.error());-  tree.body.assign(body.begin(), body.end());-  return tree;+    const auto fin = r.finish();+    if (!fin)+        return unexpected(fin.error());+    tree.body.assign(body.begin(), body.end());+    return tree; } -Result<std::vector<std::uint8_t>>-encode_tree(const std::vector<TreeEntry> &entries) {-  ByteWriter w(entries.size() * 48 + 8);-  w.varint(entries.size());-  std::optional<std::string> prev;-  for (std::size_t i = 0; i < entries.size(); ++i) {-    const auto &e = entries[i];-    if (!valid_name(e.name))-      return fail(ErrorKind::InvalidName, i);-    if (prev && compare(bytes_of(*prev), bytes_of(e.name)) >= 0)-      return fail(ErrorKind::Unsorted, i);-    if (!valid_tree_kind(e.kind))-      return fail(ErrorKind::InvalidValue, i);-    w.length_prefixed(e.name);-    w.u8(e.kind);-    w.id(e.target);-    prev = e.name;-  }-  return w.take();+Result<std::vector<std::uint8_t>> encode_tree(const std::vector<TreeEntry>& entries) {+    ByteWriter w(entries.size() * 48 + 8);+    w.varint(entries.size());+    std::optional<std::string> prev;+    for (std::size_t i = 0; i < entries.size(); ++i) {+        const auto& e = entries[i];+        if (!valid_name(e.name))+            return fail(ErrorKind::InvalidName, i);+        if (prev && compare(bytes_of(*prev), bytes_of(e.name)) >= 0)+            return fail(ErrorKind::Unsorted, i);+        if (!valid_tree_kind(e.kind))+            return fail(ErrorKind::InvalidValue, i);+        w.length_prefixed(e.name);+        w.u8(e.kind);+        w.id(e.target);+        prev = e.name;+    }+    return w.take(); }  // ---------------------------------------------------------------------------@@ -371,174 +368,172 @@ // Commits // --------------------------------------------------------------------------- -static Result<std::vector<Id>> read_parents(Reader &r) {-  const auto n = r.list_len(1024);-  if (!n)-    return unexpected(n.error());-  std::vector<Id> out;-  out.reserve(*n);-  for (std::size_t i = 0; i < *n; ++i) {-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    out.push_back(*id);-  }-  return out;+static Result<std::vector<Id>> read_parents(Reader& r) {+    const auto n = r.list_len(1024);+    if (!n)+        return unexpected(n.error());+    std::vector<Id> out;+    out.reserve(*n);+    for (std::size_t i = 0; i < *n; ++i) {+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        out.push_back(*id);+    }+    return out; } -static Result<std::vector<Rename>>-read_renames(Reader &r, std::size_t parent_count, std::uint8_t state) {-  const auto n = r.list_len(1'000'000);-  if (!n)-    return unexpected(n.error());-  std::vector<Rename> out;-  if (state == RENAMES_UNKNOWN) {-    if (*n != 0)-      return fail(ErrorKind::InvalidValue, r.offset());-    return out;-  }-  out.reserve(*n);-  std::uint64_t prev_parent = 0;-  std::string prev_path;-  bool have_prev = false;-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    const auto parent = r.varint();-    if (!parent)-      return unexpected(parent.error());-    const auto kind = r.u8();-    if (!kind)-      return unexpected(kind.error());-    auto from = r.string_bytes(MAX_PATH_LEN);-    if (!from)-      return unexpected(from.error());-    auto to = r.string_bytes(MAX_PATH_LEN);-    if (!to)-      return unexpected(to.error());-    if (*parent >= parent_count)-      return fail(ErrorKind::InvalidValue, at);-    if (*kind > 1)-      return fail(ErrorKind::InvalidValue, at);-    if (!valid_path(*from) || !valid_path(*to))-      return fail(ErrorKind::InvalidName, at);-    if (have_prev) {-      if (*parent < prev_parent)-        return fail(ErrorKind::Unsorted, at);-      if (*parent == prev_parent &&-          compare(bytes_of(prev_path), bytes_of(*to)) >= 0)-        return fail(ErrorKind::Unsorted, at);+static Result<std::vector<Rename>> read_renames(Reader& r, std::size_t parent_count,+                                                std::uint8_t state) {+    const auto n = r.list_len(1'000'000);+    if (!n)+        return unexpected(n.error());+    std::vector<Rename> out;+    if (state == RENAMES_UNKNOWN) {+        if (*n != 0)+            return fail(ErrorKind::InvalidValue, r.offset());+        return out;     }-    out.push_back(Rename{*parent, *kind, std::move(*from), std::move(*to)});-    prev_parent = *parent;-    prev_path = out.back().to_path;-    have_prev = true;-  }-  return out;+    out.reserve(*n);+    std::uint64_t prev_parent = 0;+    std::string prev_path;+    bool have_prev = false;+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        const auto parent = r.varint();+        if (!parent)+            return unexpected(parent.error());+        const auto kind = r.u8();+        if (!kind)+            return unexpected(kind.error());+        auto from = r.string_bytes(MAX_PATH_LEN);+        if (!from)+            return unexpected(from.error());+        auto to = r.string_bytes(MAX_PATH_LEN);+        if (!to)+            return unexpected(to.error());+        if (*parent >= parent_count)+            return fail(ErrorKind::InvalidValue, at);+        if (*kind > 1)+            return fail(ErrorKind::InvalidValue, at);+        if (!valid_path(*from) || !valid_path(*to))+            return fail(ErrorKind::InvalidName, at);+        if (have_prev) {+            if (*parent < prev_parent)+                return fail(ErrorKind::Unsorted, at);+            if (*parent == prev_parent && compare(bytes_of(prev_path), bytes_of(*to)) >= 0)+                return fail(ErrorKind::Unsorted, at);+        }+        out.push_back(Rename{*parent, *kind, std::move(*from), std::move(*to)});+        prev_parent = *parent;+        prev_path = out.back().to_path;+        have_prev = true;+    }+    return out; } -static Result<std::vector<KeyValue>> read_extra(Reader &r) {-  const auto n = r.list_len(1024);-  if (!n)-    return unexpected(n.error());-  std::vector<KeyValue> out;-  out.reserve(*n);-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    auto key = r.string_bytes(MAX_NAME_LEN);-    if (!key)-      return unexpected(key.error());-    auto value = r.string_bytes(MAX_MESSAGE_LEN);-    if (!value)-      return unexpected(value.error());-    if (key->empty())-      return fail(ErrorKind::InvalidValue, at);-    out.push_back(KeyValue{std::move(*key), std::move(*value)});-  }-  return out;+static Result<std::vector<KeyValue>> read_extra(Reader& r) {+    const auto n = r.list_len(1024);+    if (!n)+        return unexpected(n.error());+    std::vector<KeyValue> out;+    out.reserve(*n);+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        auto key = r.string_bytes(MAX_NAME_LEN);+        if (!key)+            return unexpected(key.error());+        auto value = r.string_bytes(MAX_MESSAGE_LEN);+        if (!value)+            return unexpected(value.error());+        if (key->empty())+            return fail(ErrorKind::InvalidValue, at);+        out.push_back(KeyValue{std::move(*key), std::move(*value)});+    }+    return out; }  Result<Commit> decode_commit(Bytes body) {-  Reader r(body);-  const auto version = r.u8();-  if (!version)-    return unexpected(version.error());-  if (*version != 1)-    return fail(ErrorKind::UnsupportedVersion, 0);-  Commit commit;-  commit.version = *version;-  auto parents = read_parents(r);-  if (!parents)-    return unexpected(parents.error());-  commit.parents = std::move(*parents);-  const auto root = r.id();-  if (!root)-    return unexpected(root.error());-  commit.root_tree = *root;-  const auto change = r.raw(CHANGE_ID_LEN);-  if (!change)-    return unexpected(change.error());-  std::memcpy(commit.change_id.data(), change->data(), CHANGE_ID_LEN);-  auto author = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);-  if (!author)-    return unexpected(author.error());-  commit.author =-      Sig{author->name, author->email, author->seconds, author->tz_min};-  auto committer = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);-  if (!committer)-    return unexpected(committer.error());-  commit.committer = Sig{committer->name, committer->email, committer->seconds,-                         committer->tz_min};-  auto message = r.string_bytes(MAX_MESSAGE_LEN);-  if (!message)-    return unexpected(message.error());-  commit.message = std::move(*message);-  const auto state = r.u8();-  if (!state)-    return unexpected(state.error());-  if (*state > 1)-    return fail(ErrorKind::InvalidValue, r.offset() - 1);-  commit.renames_state = *state;-  auto renames = read_renames(r, commit.parents.size(), commit.renames_state);-  if (!renames)-    return unexpected(renames.error());-  commit.renames = std::move(*renames);-  auto extra = read_extra(r);-  if (!extra)-    return unexpected(extra.error());-  commit.extra = std::move(*extra);-  const auto fin = r.finish();-  if (!fin)-    return unexpected(fin.error());-  return commit;+    Reader r(body);+    const auto version = r.u8();+    if (!version)+        return unexpected(version.error());+    if (*version != 1)+        return fail(ErrorKind::UnsupportedVersion, 0);+    Commit commit;+    commit.version = *version;+    auto parents = read_parents(r);+    if (!parents)+        return unexpected(parents.error());+    commit.parents = std::move(*parents);+    const auto root = r.id();+    if (!root)+        return unexpected(root.error());+    commit.root_tree = *root;+    const auto change = r.raw(CHANGE_ID_LEN);+    if (!change)+        return unexpected(change.error());+    std::memcpy(commit.change_id.data(), change->data(), CHANGE_ID_LEN);+    auto author = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);+    if (!author)+        return unexpected(author.error());+    commit.author = Sig{author->name, author->email, author->seconds, author->tz_min};+    auto committer = r.sig(MAX_NAME_LEN, MAX_NAME_LEN);+    if (!committer)+        return unexpected(committer.error());+    commit.committer =+        Sig{committer->name, committer->email, committer->seconds, committer->tz_min};+    auto message = r.string_bytes(MAX_MESSAGE_LEN);+    if (!message)+        return unexpected(message.error());+    commit.message = std::move(*message);+    const auto state = r.u8();+    if (!state)+        return unexpected(state.error());+    if (*state > 1)+        return fail(ErrorKind::InvalidValue, r.offset() - 1);+    commit.renames_state = *state;+    auto renames = read_renames(r, commit.parents.size(), commit.renames_state);+    if (!renames)+        return unexpected(renames.error());+    commit.renames = std::move(*renames);+    auto extra = read_extra(r);+    if (!extra)+        return unexpected(extra.error());+    commit.extra = std::move(*extra);+    const auto fin = r.finish();+    if (!fin)+        return unexpected(fin.error());+    return commit; } -std::vector<std::uint8_t> encode_commit(const Commit &commit) {-  ByteWriter w(256);-  w.u8(commit.version);-  w.varint(commit.parents.size());-  for (const auto &p : commit.parents)-    w.id(p);-  w.id(commit.root_tree);-  w.raw(Bytes(commit.change_id.data(), commit.change_id.size()));-  w.sig(Reader::Sig{commit.author.name, commit.author.email,-                    commit.author.seconds, commit.author.tz_min});-  w.sig(Reader::Sig{commit.committer.name, commit.committer.email,-                    commit.committer.seconds, commit.committer.tz_min});-  w.length_prefixed(commit.message);-  w.u8(commit.renames_state);-  w.varint(commit.renames.size());-  for (const auto &r : commit.renames) {-    w.varint(r.parent_index);-    w.u8(r.kind);-    w.length_prefixed(r.from_path);-    w.length_prefixed(r.to_path);-  }-  w.varint(commit.extra.size());-  for (const auto &kv : commit.extra) {-    w.length_prefixed(kv.key);-    w.length_prefixed(kv.value);-  }-  return w.take();+std::vector<std::uint8_t> encode_commit(const Commit& commit) {+    ByteWriter w(256);+    w.u8(commit.version);+    w.varint(commit.parents.size());+    for (const auto& p : commit.parents)+        w.id(p);+    w.id(commit.root_tree);+    w.raw(Bytes(commit.change_id.data(), commit.change_id.size()));+    w.sig(Reader::Sig{commit.author.name, commit.author.email, commit.author.seconds,+                      commit.author.tz_min});+    w.sig(Reader::Sig{commit.committer.name, commit.committer.email, commit.committer.seconds,+                      commit.committer.tz_min});+    w.length_prefixed(commit.message);+    w.u8(commit.renames_state);+    w.varint(commit.renames.size());+    for (const auto& r : commit.renames) {+        w.varint(r.parent_index);+        w.u8(r.kind);+        w.length_prefixed(r.from_path);+        w.length_prefixed(r.to_path);+    }+    w.varint(commit.extra.size());+    for (const auto& kv : commit.extra) {+        w.length_prefixed(kv.key);+        w.length_prefixed(kv.value);+    }+    return w.take(); }  // ---------------------------------------------------------------------------@@ -546,102 +541,101 @@ // ---------------------------------------------------------------------------  static bool conflict_kind_valid(std::uint8_t kind) {-  return kind == 0 || (kind >= KIND_FILE && kind <= KIND_CONFLICT);+    return kind == 0 || (kind >= KIND_FILE && kind <= KIND_CONFLICT); } -static Result<ConflictValue> read_conflict_value(Reader &r) {-  const std::size_t at = r.offset();-  const auto kind = r.u8();-  if (!kind)-    return unexpected(kind.error());-  if (!conflict_kind_valid(*kind))-    return fail(ErrorKind::InvalidValue, at);-  if (*kind == 0)-    return ConflictValue{0, std::nullopt};-  const auto target = r.id();-  if (!target)-    return unexpected(target.error());-  return ConflictValue{*kind, *target};+static Result<ConflictValue> read_conflict_value(Reader& r) {+    const std::size_t at = r.offset();+    const auto kind = r.u8();+    if (!kind)+        return unexpected(kind.error());+    if (!conflict_kind_valid(*kind))+        return fail(ErrorKind::InvalidValue, at);+    if (*kind == 0)+        return ConflictValue{0, std::nullopt};+    const auto target = r.id();+    if (!target)+        return unexpected(target.error());+    return ConflictValue{*kind, *target}; } -static Result<std::vector<ConflictValue>> read_conflict_values(Reader &r) {-  const auto n = r.list_len(MAX_CONFLICT_TERMS);-  if (!n)-    return unexpected(n.error());-  std::vector<ConflictValue> out;-  out.reserve(*n);-  for (std::size_t i = 0; i < *n; ++i) {-    auto value = read_conflict_value(r);-    if (!value)-      return unexpected(value.error());-    out.push_back(*value);-  }-  return out;+static Result<std::vector<ConflictValue>> read_conflict_values(Reader& r) {+    const auto n = r.list_len(MAX_CONFLICT_TERMS);+    if (!n)+        return unexpected(n.error());+    std::vector<ConflictValue> out;+    out.reserve(*n);+    for (std::size_t i = 0; i < *n; ++i) {+        auto value = read_conflict_value(r);+        if (!value)+            return unexpected(value.error());+        out.push_back(*value);+    }+    return out; } -static bool conflict_value_equal(const ConflictValue &a,-                                 const ConflictValue &b) {-  if (a.kind != b.kind)-    return false;-  if (a.kind == 0)-    return true;-  return a.target == b.target;+static bool conflict_value_equal(const ConflictValue& a, const ConflictValue& b) {+    if (a.kind != b.kind)+        return false;+    if (a.kind == 0)+        return true;+    return a.target == b.target; }  Result<Conflict> decode_conflict(Bytes body) {-  Reader r(body);-  Conflict conflict;-  auto adds = read_conflict_values(r);-  if (!adds)-    return unexpected(adds.error());-  conflict.adds = std::move(*adds);-  auto removes = read_conflict_values(r);-  if (!removes)-    return unexpected(removes.error());-  conflict.removes = std::move(*removes);-  const std::size_t at = r.offset();-  const auto fin = r.finish();-  if (!fin)-    return unexpected(fin.error());-  if (conflict.removes.empty())-    return fail(ErrorKind::InvalidValue, at);-  if (conflict.adds.size() != conflict.removes.size() + 1)-    return fail(ErrorKind::InvalidValue, at);-  if (conflict.adds.size() + conflict.removes.size() > MAX_CONFLICT_TERMS)-    return fail(ErrorKind::LimitExceeded, at);-  for (const auto &a : conflict.adds) {-    for (const auto &rem : conflict.removes) {-      if (conflict_value_equal(a, rem))+    Reader r(body);+    Conflict conflict;+    auto adds = read_conflict_values(r);+    if (!adds)+        return unexpected(adds.error());+    conflict.adds = std::move(*adds);+    auto removes = read_conflict_values(r);+    if (!removes)+        return unexpected(removes.error());+    conflict.removes = std::move(*removes);+    const std::size_t at = r.offset();+    const auto fin = r.finish();+    if (!fin)+        return unexpected(fin.error());+    if (conflict.removes.empty())+        return fail(ErrorKind::InvalidValue, at);+    if (conflict.adds.size() != conflict.removes.size() + 1)         return fail(ErrorKind::InvalidValue, at);+    if (conflict.adds.size() + conflict.removes.size() > MAX_CONFLICT_TERMS)+        return fail(ErrorKind::LimitExceeded, at);+    for (const auto& a : conflict.adds) {+        for (const auto& rem : conflict.removes) {+            if (conflict_value_equal(a, rem))+                return fail(ErrorKind::InvalidValue, at);+        }     }-  }-  bool all_same = true;-  for (std::size_t i = 1; i < conflict.adds.size(); ++i) {-    if (!conflict_value_equal(conflict.adds[0], conflict.adds[i])) {-      all_same = false;-      break;+    bool all_same = true;+    for (std::size_t i = 1; i < conflict.adds.size(); ++i) {+        if (!conflict_value_equal(conflict.adds[0], conflict.adds[i])) {+            all_same = false;+            break;+        }     }-  }-  if (all_same)-    return fail(ErrorKind::InvalidValue, at);-  return conflict;+    if (all_same)+        return fail(ErrorKind::InvalidValue, at);+    return conflict; } -std::vector<std::uint8_t> encode_conflict(const Conflict &conflict) {-  ByteWriter w((conflict.adds.size() + conflict.removes.size()) * 40 + 16);-  w.varint(conflict.adds.size());-  for (const auto &v : conflict.adds) {-    w.u8(v.kind);-    if (v.kind != 0 && v.target)-      w.id(*v.target);-  }-  w.varint(conflict.removes.size());-  for (const auto &v : conflict.removes) {-    w.u8(v.kind);-    if (v.kind != 0 && v.target)-      w.id(*v.target);-  }-  return w.take();+std::vector<std::uint8_t> encode_conflict(const Conflict& conflict) {+    ByteWriter w((conflict.adds.size() + conflict.removes.size()) * 40 + 16);+    w.varint(conflict.adds.size());+    for (const auto& v : conflict.adds) {+        w.u8(v.kind);+        if (v.kind != 0 && v.target)+            w.id(*v.target);+    }+    w.varint(conflict.removes.size());+    for (const auto& v : conflict.removes) {+        w.u8(v.kind);+        if (v.kind != 0 && v.target)+            w.id(*v.target);+    }+    return w.take(); }  // ---------------------------------------------------------------------------@@ -649,290 +643,287 @@ // ---------------------------------------------------------------------------  static bool view_name_valid(std::string_view name) {-  if (name.empty() || name.size() > MAX_NAME_LEN)-    return false;-  return name.find('\0') == std::string_view::npos;+    if (name.empty() || name.size() > MAX_NAME_LEN)+        return false;+    return name.find('\0') == std::string_view::npos; } -static Result<std::vector<Id>> read_view_heads(Reader &r) {-  const auto n = r.list_len(1'000'000);-  if (!n)-    return unexpected(n.error());-  std::vector<Id> out;-  out.reserve(*n);-  std::optional<Id> prev;-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    if (prev) {-      const int c = std::memcmp(prev->data(), id->data(), ID_LEN);-      if (c == 0)-        return fail(ErrorKind::Duplicate, at);-      if (c > 0)-        return fail(ErrorKind::Unsorted, at);+static Result<std::vector<Id>> read_view_heads(Reader& r) {+    const auto n = r.list_len(1'000'000);+    if (!n)+        return unexpected(n.error());+    std::vector<Id> out;+    out.reserve(*n);+    std::optional<Id> prev;+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        if (prev) {+            const int c = std::memcmp(prev->data(), id->data(), ID_LEN);+            if (c == 0)+                return fail(ErrorKind::Duplicate, at);+            if (c > 0)+                return fail(ErrorKind::Unsorted, at);+        }+        out.push_back(*id);+        prev = *id;     }-    out.push_back(*id);-    prev = *id;-  }-  return out;+    return out; } -static Result<std::vector<std::optional<Id>>>-read_opt_id_list(Reader &r, std::size_t max) {-  const auto n = r.list_len(max);-  if (!n)-    return unexpected(n.error());-  std::vector<std::optional<Id>> out;-  out.reserve(*n);-  for (std::size_t i = 0; i < *n; ++i) {-    const auto id = r.opt_id();-    if (!id)-      return unexpected(id.error());-    out.push_back(*id);-  }-  return out;+static Result<std::vector<std::optional<Id>>> read_opt_id_list(Reader& r, std::size_t max) {+    const auto n = r.list_len(max);+    if (!n)+        return unexpected(n.error());+    std::vector<std::optional<Id>> out;+    out.reserve(*n);+    for (std::size_t i = 0; i < *n; ++i) {+        const auto id = r.opt_id();+        if (!id)+            return unexpected(id.error());+        out.push_back(*id);+    }+    return out; } -static bool opt_id_contains(const std::vector<std::optional<Id>> &ids,-                            const std::optional<Id> &id) {-  for (const auto &x : ids) {-    if (x.has_value() == id.has_value()) {-      if (!x || std::memcmp(x->data(), id->data(), ID_LEN) == 0)-        return true;+static bool opt_id_contains(const std::vector<std::optional<Id>>& ids,+                            const std::optional<Id>& id) {+    for (const auto& x : ids) {+        if (x.has_value() == id.has_value()) {+            if (!x || std::memcmp(x->data(), id->data(), ID_LEN) == 0)+                return true;+        }     }-  }-  return false;+    return false; } -static Result<TargetSet> read_target_set(Reader &r) {-  const std::size_t at = r.offset();-  TargetSet set;-  auto adds = read_opt_id_list(r, 64);-  if (!adds)-    return unexpected(adds.error());-  set.adds = std::move(*adds);-  auto removes = read_opt_id_list(r, 64);-  if (!removes)-    return unexpected(removes.error());-  set.removes = std::move(*removes);-  if (set.adds.empty())-    return fail(ErrorKind::InvalidValue, at);-  if (set.adds.size() != set.removes.size() + 1)-    return fail(ErrorKind::InvalidValue, at);-  if (set.adds.size() + set.removes.size() > MAX_CONFLICT_TERMS)-    return fail(ErrorKind::LimitExceeded, at);-  for (const auto &a : set.adds) {-    if (opt_id_contains(set.removes, a))-      return fail(ErrorKind::InvalidValue, at);-  }-  bool all_same = true;-  for (std::size_t i = 1; i < set.adds.size(); ++i) {-    const bool same =-        set.adds[0].has_value() == set.adds[i].has_value() &&-        (!set.adds[0] ||-         std::memcmp(set.adds[0]->data(), set.adds[i]->data(), ID_LEN) == 0);-    if (!same) {-      all_same = false;-      break;+static Result<TargetSet> read_target_set(Reader& r) {+    const std::size_t at = r.offset();+    TargetSet set;+    auto adds = read_opt_id_list(r, 64);+    if (!adds)+        return unexpected(adds.error());+    set.adds = std::move(*adds);+    auto removes = read_opt_id_list(r, 64);+    if (!removes)+        return unexpected(removes.error());+    set.removes = std::move(*removes);+    if (set.adds.empty())+        return fail(ErrorKind::InvalidValue, at);+    if (set.adds.size() != set.removes.size() + 1)+        return fail(ErrorKind::InvalidValue, at);+    if (set.adds.size() + set.removes.size() > MAX_CONFLICT_TERMS)+        return fail(ErrorKind::LimitExceeded, at);+    for (const auto& a : set.adds) {+        if (opt_id_contains(set.removes, a))+            return fail(ErrorKind::InvalidValue, at);     }-  }-  if (all_same && set.adds.size() > 1)-    return fail(ErrorKind::InvalidValue, at);-  return set;+    bool all_same = true;+    for (std::size_t i = 1; i < set.adds.size(); ++i) {+        const bool same =+            set.adds[0].has_value() == set.adds[i].has_value() &&+            (!set.adds[0] || std::memcmp(set.adds[0]->data(), set.adds[i]->data(), ID_LEN) == 0);+        if (!same) {+            all_same = false;+            break;+        }+    }+    if (all_same && set.adds.size() > 1)+        return fail(ErrorKind::InvalidValue, at);+    return set; } -static Result<std::vector<Bookmark>> read_bookmarks(Reader &r) {-  const auto n = r.list_len(1'000'000);-  if (!n)-    return unexpected(n.error());-  std::vector<Bookmark> out;-  out.reserve(*n);-  std::optional<std::string> prev;-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    auto name = r.string_bytes(MAX_NAME_LEN);-    if (!name)-      return unexpected(name.error());-    if (!view_name_valid(*name))-      return fail(ErrorKind::InvalidName, at);-    if (prev) {-      const int c = compare(bytes_of(*prev), bytes_of(*name));-      if (c == 0)-        return fail(ErrorKind::Duplicate, at);-      if (c > 0)-        return fail(ErrorKind::Unsorted, at);+static Result<std::vector<Bookmark>> read_bookmarks(Reader& r) {+    const auto n = r.list_len(1'000'000);+    if (!n)+        return unexpected(n.error());+    std::vector<Bookmark> out;+    out.reserve(*n);+    std::optional<std::string> prev;+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        auto name = r.string_bytes(MAX_NAME_LEN);+        if (!name)+            return unexpected(name.error());+        if (!view_name_valid(*name))+            return fail(ErrorKind::InvalidName, at);+        if (prev) {+            const int c = compare(bytes_of(*prev), bytes_of(*name));+            if (c == 0)+                return fail(ErrorKind::Duplicate, at);+            if (c > 0)+                return fail(ErrorKind::Unsorted, at);+        }+        auto targets = read_target_set(r);+        if (!targets)+            return unexpected(targets.error());+        out.push_back(Bookmark{std::move(*name), std::move(*targets)});+        prev = out.back().name;     }-    auto targets = read_target_set(r);-    if (!targets)-      return unexpected(targets.error());-    out.push_back(Bookmark{std::move(*name), std::move(*targets)});-    prev = out.back().name;-  }-  return out;+    return out; } -static Result<std::vector<TagRef>> read_tags(Reader &r) {-  const auto n = r.list_len(1'000'000);-  if (!n)-    return unexpected(n.error());-  std::vector<TagRef> out;-  out.reserve(*n);-  std::optional<std::string> prev;-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    auto name = r.string_bytes(MAX_NAME_LEN);-    if (!name)-      return unexpected(name.error());-    if (!view_name_valid(*name))-      return fail(ErrorKind::InvalidName, at);-    if (prev) {-      const int c = compare(bytes_of(*prev), bytes_of(*name));-      if (c == 0)-        return fail(ErrorKind::Duplicate, at);-      if (c > 0)-        return fail(ErrorKind::Unsorted, at);+static Result<std::vector<TagRef>> read_tags(Reader& r) {+    const auto n = r.list_len(1'000'000);+    if (!n)+        return unexpected(n.error());+    std::vector<TagRef> out;+    out.reserve(*n);+    std::optional<std::string> prev;+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        auto name = r.string_bytes(MAX_NAME_LEN);+        if (!name)+            return unexpected(name.error());+        if (!view_name_valid(*name))+            return fail(ErrorKind::InvalidName, at);+        if (prev) {+            const int c = compare(bytes_of(*prev), bytes_of(*name));+            if (c == 0)+                return fail(ErrorKind::Duplicate, at);+            if (c > 0)+                return fail(ErrorKind::Unsorted, at);+        }+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        out.push_back(TagRef{std::move(*name), *id});+        prev = out.back().name;     }-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    out.push_back(TagRef{std::move(*name), *id});-    prev = out.back().name;-  }-  return out;+    return out; } -static Result<std::vector<RemoteRef>> read_remote_refs(Reader &r) {-  const auto n = r.list_len(1'000'000);-  if (!n)-    return unexpected(n.error());-  std::vector<RemoteRef> out;-  out.reserve(*n);-  std::optional<std::pair<std::string, std::string>> prev;-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    auto remote = r.string_bytes(MAX_NAME_LEN);-    if (!remote)-      return unexpected(remote.error());-    auto name = r.string_bytes(MAX_NAME_LEN);-    if (!name)-      return unexpected(name.error());-    if (!view_name_valid(*remote) || !view_name_valid(*name))-      return fail(ErrorKind::InvalidName, at);-    if (prev) {-      const int c1 = compare(bytes_of(prev->first), bytes_of(*remote));-      const int c2 =-          c1 != 0 ? 0 : compare(bytes_of(prev->second), bytes_of(*name));-      if (c1 == 0 && c2 == 0)-        return fail(ErrorKind::Duplicate, at);-      if (c1 > 0 || (c1 == 0 && c2 > 0))-        return fail(ErrorKind::Unsorted, at);+static Result<std::vector<RemoteRef>> read_remote_refs(Reader& r) {+    const auto n = r.list_len(1'000'000);+    if (!n)+        return unexpected(n.error());+    std::vector<RemoteRef> out;+    out.reserve(*n);+    std::optional<std::pair<std::string, std::string>> prev;+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        auto remote = r.string_bytes(MAX_NAME_LEN);+        if (!remote)+            return unexpected(remote.error());+        auto name = r.string_bytes(MAX_NAME_LEN);+        if (!name)+            return unexpected(name.error());+        if (!view_name_valid(*remote) || !view_name_valid(*name))+            return fail(ErrorKind::InvalidName, at);+        if (prev) {+            const int c1 = compare(bytes_of(prev->first), bytes_of(*remote));+            const int c2 = c1 != 0 ? 0 : compare(bytes_of(prev->second), bytes_of(*name));+            if (c1 == 0 && c2 == 0)+                return fail(ErrorKind::Duplicate, at);+            if (c1 > 0 || (c1 == 0 && c2 > 0))+                return fail(ErrorKind::Unsorted, at);+        }+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        out.push_back(RemoteRef{std::move(*remote), std::move(*name), *id});+        prev = std::make_pair(out.back().remote, out.back().name);     }-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    out.push_back(RemoteRef{std::move(*remote), std::move(*name), *id});-    prev = std::make_pair(out.back().remote, out.back().name);-  }-  return out;+    return out; } -static Result<std::vector<WorkspaceRef>> read_workspaces(Reader &r) {-  const auto n = r.list_len(1'000'000);-  if (!n)-    return unexpected(n.error());-  std::vector<WorkspaceRef> out;-  out.reserve(*n);-  std::optional<std::string> prev;-  for (std::size_t i = 0; i < *n; ++i) {-    const std::size_t at = r.offset();-    auto workspace = r.string_bytes(MAX_NAME_LEN);-    if (!workspace)-      return unexpected(workspace.error());-    if (!view_name_valid(*workspace))-      return fail(ErrorKind::InvalidName, at);-    if (prev) {-      const int c = compare(bytes_of(*prev), bytes_of(*workspace));-      if (c == 0)-        return fail(ErrorKind::Duplicate, at);-      if (c > 0)-        return fail(ErrorKind::Unsorted, at);+static Result<std::vector<WorkspaceRef>> read_workspaces(Reader& r) {+    const auto n = r.list_len(1'000'000);+    if (!n)+        return unexpected(n.error());+    std::vector<WorkspaceRef> out;+    out.reserve(*n);+    std::optional<std::string> prev;+    for (std::size_t i = 0; i < *n; ++i) {+        const std::size_t at = r.offset();+        auto workspace = r.string_bytes(MAX_NAME_LEN);+        if (!workspace)+            return unexpected(workspace.error());+        if (!view_name_valid(*workspace))+            return fail(ErrorKind::InvalidName, at);+        if (prev) {+            const int c = compare(bytes_of(*prev), bytes_of(*workspace));+            if (c == 0)+                return fail(ErrorKind::Duplicate, at);+            if (c > 0)+                return fail(ErrorKind::Unsorted, at);+        }+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        out.push_back(WorkspaceRef{std::move(*workspace), *id});+        prev = out.back().workspace;     }-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    out.push_back(WorkspaceRef{std::move(*workspace), *id});-    prev = out.back().workspace;-  }-  return out;+    return out; }  Result<View> decode_view(Bytes body) {-  Reader r(body);-  View view;-  auto heads = read_view_heads(r);-  if (!heads)-    return unexpected(heads.error());-  view.heads = std::move(*heads);-  auto bookmarks = read_bookmarks(r);-  if (!bookmarks)-    return unexpected(bookmarks.error());-  view.bookmarks = std::move(*bookmarks);-  auto tags = read_tags(r);-  if (!tags)-    return unexpected(tags.error());-  view.tags = std::move(*tags);-  auto remote_refs = read_remote_refs(r);-  if (!remote_refs)-    return unexpected(remote_refs.error());-  view.remote_refs = std::move(*remote_refs);-  auto workspaces = read_workspaces(r);-  if (!workspaces)-    return unexpected(workspaces.error());-  view.working_copies = std::move(*workspaces);-  const auto fin = r.finish();-  if (!fin)-    return unexpected(fin.error());-  return view;+    Reader r(body);+    View view;+    auto heads = read_view_heads(r);+    if (!heads)+        return unexpected(heads.error());+    view.heads = std::move(*heads);+    auto bookmarks = read_bookmarks(r);+    if (!bookmarks)+        return unexpected(bookmarks.error());+    view.bookmarks = std::move(*bookmarks);+    auto tags = read_tags(r);+    if (!tags)+        return unexpected(tags.error());+    view.tags = std::move(*tags);+    auto remote_refs = read_remote_refs(r);+    if (!remote_refs)+        return unexpected(remote_refs.error());+    view.remote_refs = std::move(*remote_refs);+    auto workspaces = read_workspaces(r);+    if (!workspaces)+        return unexpected(workspaces.error());+    view.working_copies = std::move(*workspaces);+    const auto fin = r.finish();+    if (!fin)+        return unexpected(fin.error());+    return view; } -static void put_target_set(ByteWriter &w, const TargetSet &set) {-  w.varint(set.adds.size());-  for (const auto &id : set.adds)-    w.opt_id(id);-  w.varint(set.removes.size());-  for (const auto &id : set.removes)-    w.opt_id(id);+static void put_target_set(ByteWriter& w, const TargetSet& set) {+    w.varint(set.adds.size());+    for (const auto& id : set.adds)+        w.opt_id(id);+    w.varint(set.removes.size());+    for (const auto& id : set.removes)+        w.opt_id(id); } -std::vector<std::uint8_t> encode_view(const View &view) {-  ByteWriter w(256);-  w.varint(view.heads.size());-  for (const auto &id : view.heads)-    w.id(id);-  w.varint(view.bookmarks.size());-  for (const auto &bookmark : view.bookmarks) {-    w.length_prefixed(bookmark.name);-    put_target_set(w, bookmark.targets);-  }-  w.varint(view.tags.size());-  for (const auto &tag : view.tags) {-    w.length_prefixed(tag.name);-    w.id(tag.target);-  }-  w.varint(view.remote_refs.size());-  for (const auto &ref : view.remote_refs) {-    w.length_prefixed(ref.remote);-    w.length_prefixed(ref.name);-    w.id(ref.target);-  }-  w.varint(view.working_copies.size());-  for (const auto &workspace : view.working_copies) {-    w.length_prefixed(workspace.workspace);-    w.id(workspace.target);-  }-  return w.take();+std::vector<std::uint8_t> encode_view(const View& view) {+    ByteWriter w(256);+    w.varint(view.heads.size());+    for (const auto& id : view.heads)+        w.id(id);+    w.varint(view.bookmarks.size());+    for (const auto& bookmark : view.bookmarks) {+        w.length_prefixed(bookmark.name);+        put_target_set(w, bookmark.targets);+    }+    w.varint(view.tags.size());+    for (const auto& tag : view.tags) {+        w.length_prefixed(tag.name);+        w.id(tag.target);+    }+    w.varint(view.remote_refs.size());+    for (const auto& ref : view.remote_refs) {+        w.length_prefixed(ref.remote);+        w.length_prefixed(ref.name);+        w.id(ref.target);+    }+    w.varint(view.working_copies.size());+    for (const auto& workspace : view.working_copies) {+        w.length_prefixed(workspace.workspace);+        w.id(workspace.target);+    }+    return w.take(); }  // ---------------------------------------------------------------------------@@ -940,87 +931,87 @@ // ---------------------------------------------------------------------------  Result<Operation> decode_operation(Bytes body) {-  Reader r(body);-  Operation op;-  const auto parent_count = r.list_len(1024);-  if (!parent_count)-    return unexpected(parent_count.error());-  op.parents.reserve(*parent_count);-  for (std::size_t i = 0; i < *parent_count; ++i) {-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    op.parents.push_back(*id);-  }-  const auto view = r.id();-  if (!view)-    return unexpected(view.error());-  op.view = *view;-  auto start = r.time_ms();-  if (!start)-    return unexpected(start.error());-  op.start = *start;-  auto end = r.time_ms();-  if (!end)-    return unexpected(end.error());-  op.end = *end;-  auto hostname = r.string_bytes(MAX_NAME_LEN);-  if (!hostname)-    return unexpected(hostname.error());-  op.hostname = std::move(*hostname);-  auto username = r.string_bytes(MAX_NAME_LEN);-  if (!username)-    return unexpected(username.error());-  op.username = std::move(*username);-  auto description = r.string_bytes(MAX_MESSAGE_LEN);-  if (!description)-    return unexpected(description.error());-  op.description = std::move(*description);-  const auto tag_count = r.list_len(1024);-  if (!tag_count)-    return unexpected(tag_count.error());-  op.tags.reserve(*tag_count);-  for (std::size_t i = 0; i < *tag_count; ++i) {-    const std::size_t at = r.offset();-    auto key = r.string_bytes(MAX_NAME_LEN);-    if (!key)-      return unexpected(key.error());-    auto value = r.string_bytes(MAX_MESSAGE_LEN);-    if (!value)-      return unexpected(value.error());-    if (key->empty())-      return fail(ErrorKind::InvalidValue, at);-    op.tags.push_back(KeyValue{std::move(*key), std::move(*value)});-  }-  const auto fin = r.finish();-  if (!fin)-    return unexpected(fin.error());-  return op;+    Reader r(body);+    Operation op;+    const auto parent_count = r.list_len(1024);+    if (!parent_count)+        return unexpected(parent_count.error());+    op.parents.reserve(*parent_count);+    for (std::size_t i = 0; i < *parent_count; ++i) {+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        op.parents.push_back(*id);+    }+    const auto view = r.id();+    if (!view)+        return unexpected(view.error());+    op.view = *view;+    auto start = r.time_ms();+    if (!start)+        return unexpected(start.error());+    op.start = *start;+    auto end = r.time_ms();+    if (!end)+        return unexpected(end.error());+    op.end = *end;+    auto hostname = r.string_bytes(MAX_NAME_LEN);+    if (!hostname)+        return unexpected(hostname.error());+    op.hostname = std::move(*hostname);+    auto username = r.string_bytes(MAX_NAME_LEN);+    if (!username)+        return unexpected(username.error());+    op.username = std::move(*username);+    auto description = r.string_bytes(MAX_MESSAGE_LEN);+    if (!description)+        return unexpected(description.error());+    op.description = std::move(*description);+    const auto tag_count = r.list_len(1024);+    if (!tag_count)+        return unexpected(tag_count.error());+    op.tags.reserve(*tag_count);+    for (std::size_t i = 0; i < *tag_count; ++i) {+        const std::size_t at = r.offset();+        auto key = r.string_bytes(MAX_NAME_LEN);+        if (!key)+            return unexpected(key.error());+        auto value = r.string_bytes(MAX_MESSAGE_LEN);+        if (!value)+            return unexpected(value.error());+        if (key->empty())+            return fail(ErrorKind::InvalidValue, at);+        op.tags.push_back(KeyValue{std::move(*key), std::move(*value)});+    }+    const auto fin = r.finish();+    if (!fin)+        return unexpected(fin.error());+    return op; } -std::vector<std::uint8_t> encode_operation(const Operation &op) {-  ByteWriter w(256);-  w.varint(op.parents.size());-  for (const auto &p : op.parents)-    w.id(p);-  w.id(op.view);-  w.time_ms(op.start);-  w.time_ms(op.end);-  w.length_prefixed(op.hostname);-  w.length_prefixed(op.username);-  w.length_prefixed(op.description);-  w.varint(op.tags.size());-  for (const auto &kv : op.tags) {-    w.length_prefixed(kv.key);-    w.length_prefixed(kv.value);-  }-  return w.take();+std::vector<std::uint8_t> encode_operation(const Operation& op) {+    ByteWriter w(256);+    w.varint(op.parents.size());+    for (const auto& p : op.parents)+        w.id(p);+    w.id(op.view);+    w.time_ms(op.start);+    w.time_ms(op.end);+    w.length_prefixed(op.hostname);+    w.length_prefixed(op.username);+    w.length_prefixed(op.description);+    w.varint(op.tags.size());+    for (const auto& kv : op.tags) {+        w.length_prefixed(kv.key);+        w.length_prefixed(kv.value);+    }+    return w.take(); } -bool is_lazy_blob(const Id &id) {-  static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '-',-                                            'g', 'i', 't', 'o', 'i', 'd'};-  return std::memcmp(id.data(), prefix, sizeof(prefix)) == 0;+bool is_lazy_blob(const Id& id) {+    static constexpr std::uint8_t prefix[] = {'v', 'e', 'i', 'n', 's', '-',+                                              'g', 'i', 't', 'o', 'i', 'd'};+    return std::memcmp(id.data(), prefix, sizeof(prefix)) == 0; }  } // namespace vn--- a/xveins/src/object.h+++ b/xveins/src/object.h@@ -22,14 +22,14 @@ bool type_valid(std::uint8_t type);  struct RawObject {-  std::uint8_t type = 0;-  std::vector<std::uint8_t> body;-  std::optional<Id> id;+    std::uint8_t type = 0;+    std::vector<std::uint8_t> body;+    std::optional<Id> id; };  struct KeyValue {-  std::string key;-  std::string value;+    std::string key;+    std::string value; };  // ---------------------------------------------------------------------------@@ -46,14 +46,14 @@ enum class BlobForm : std::uint8_t { Inline = 0, Leaf = 1, Interior = 2 };  struct BlobEntry {-  Id id{};-  std::uint64_t length = 0;+    Id id{};+    std::uint64_t length = 0; };  struct Blob {-  BlobForm form = BlobForm::Inline;-  std::vector<std::uint8_t> data;-  std::vector<BlobEntry> entries;+    BlobForm form = BlobForm::Inline;+    std::vector<std::uint8_t> data;+    std::vector<BlobEntry> entries; };  Result<Blob> decode_blob(Bytes body);@@ -60,11 +60,11 @@ Result<std::vector<std::uint8_t>> encode_inline_blob(Bytes data);  std::size_t fastcdc_next(Bytes data);-const std::array<std::uint64_t, 256> &fastcdc_gear();+const std::array<std::uint64_t, 256>& fastcdc_gear();  struct BlobBuild {-  Id root{};-  std::vector<RawObject> objects;+    Id root{};+    std::vector<RawObject> objects; };  BlobBuild build_blob(Bytes data);@@ -82,19 +82,18 @@ constexpr std::uint8_t KIND_MISSING = 0;  struct TreeEntry {-  std::string name;-  std::uint8_t kind = 0;-  Id target{};+    std::string name;+    std::uint8_t kind = 0;+    Id target{}; };  struct Tree {-  std::vector<TreeEntry> entries;-  std::vector<std::uint8_t> body;+    std::vector<TreeEntry> entries;+    std::vector<std::uint8_t> body; };  Result<Tree> decode_tree(Bytes body);-Result<std::vector<std::uint8_t>>-encode_tree(const std::vector<TreeEntry> &entries);+Result<std::vector<std::uint8_t>> encode_tree(const std::vector<TreeEntry>& entries);  // --------------------------------------------------------------------------- // Commits@@ -104,27 +103,27 @@ constexpr std::uint8_t RENAMES_RECORDED = 1;  struct Rename {-  std::uint64_t parent_index = 0;-  std::uint8_t kind = 0;-  std::string from_path;-  std::string to_path;+    std::uint64_t parent_index = 0;+    std::uint8_t kind = 0;+    std::string from_path;+    std::string to_path; };  struct Commit {-  std::uint8_t version = 1;-  std::vector<Id> parents;-  Id root_tree{};-  ChangeId change_id{};-  Sig author;-  Sig committer;-  std::string message;-  std::uint8_t renames_state = RENAMES_RECORDED;-  std::vector<Rename> renames;-  std::vector<KeyValue> extra;+    std::uint8_t version = 1;+    std::vector<Id> parents;+    Id root_tree{};+    ChangeId change_id{};+    Sig author;+    Sig committer;+    std::string message;+    std::uint8_t renames_state = RENAMES_RECORDED;+    std::vector<Rename> renames;+    std::vector<KeyValue> extra; };  Result<Commit> decode_commit(Bytes body);-std::vector<std::uint8_t> encode_commit(const Commit &commit);+std::vector<std::uint8_t> encode_commit(const Commit& commit);  // --------------------------------------------------------------------------- // Conflicts@@ -131,17 +130,17 @@ // ---------------------------------------------------------------------------  struct ConflictValue {-  std::uint8_t kind = 0;-  std::optional<Id> target;+    std::uint8_t kind = 0;+    std::optional<Id> target; };  struct Conflict {-  std::vector<ConflictValue> adds;-  std::vector<ConflictValue> removes;+    std::vector<ConflictValue> adds;+    std::vector<ConflictValue> removes; };  Result<Conflict> decode_conflict(Bytes body);-std::vector<std::uint8_t> encode_conflict(const Conflict &conflict);+std::vector<std::uint8_t> encode_conflict(const Conflict& conflict);  // --------------------------------------------------------------------------- // Operations and views@@ -148,54 +147,54 @@ // ---------------------------------------------------------------------------  struct TargetSet {-  std::vector<std::optional<Id>> adds;-  std::vector<std::optional<Id>> removes;+    std::vector<std::optional<Id>> adds;+    std::vector<std::optional<Id>> removes; };  struct Bookmark {-  std::string name;-  TargetSet targets;+    std::string name;+    TargetSet targets; };  struct TagRef {-  std::string name;-  Id target{};+    std::string name;+    Id target{}; };  struct RemoteRef {-  std::string remote;-  std::string name;-  Id target{};+    std::string remote;+    std::string name;+    Id target{}; };  struct WorkspaceRef {-  std::string workspace;-  Id target{};+    std::string workspace;+    Id target{}; };  struct View {-  std::vector<Id> heads;-  std::vector<Bookmark> bookmarks;-  std::vector<TagRef> tags;-  std::vector<RemoteRef> remote_refs;-  std::vector<WorkspaceRef> working_copies;+    std::vector<Id> heads;+    std::vector<Bookmark> bookmarks;+    std::vector<TagRef> tags;+    std::vector<RemoteRef> remote_refs;+    std::vector<WorkspaceRef> working_copies; };  struct Operation {-  std::vector<Id> parents;-  Id view{};-  Reader::TimeMs start;-  Reader::TimeMs end;-  std::string hostname;-  std::string username;-  std::string description;-  std::vector<KeyValue> tags;+    std::vector<Id> parents;+    Id view{};+    Reader::TimeMs start;+    Reader::TimeMs end;+    std::string hostname;+    std::string username;+    std::string description;+    std::vector<KeyValue> tags; };  Result<View> decode_view(Bytes body);-std::vector<std::uint8_t> encode_view(const View &view);+std::vector<std::uint8_t> encode_view(const View& view); Result<Operation> decode_operation(Bytes body);-std::vector<std::uint8_t> encode_operation(const Operation &op);+std::vector<std::uint8_t> encode_operation(const Operation& op);  // --------------------------------------------------------------------------- // Graph, tree walking, and content@@ -202,50 +201,46 @@ // ---------------------------------------------------------------------------  struct LoadedCommit {-  Commit commit;-  std::vector<std::uint8_t> body;+    Commit commit;+    std::vector<std::uint8_t> body; }; -std::optional<LoadedCommit> load_commit(Store &store, const Id &id);-bool has_changes(Store &store, const LoadedCommit &loaded);-std::vector<Id> collect_commits(Store &store, std::span<const Id> start);-std::vector<Id> all_commits(Store &store, const View &view);-std::vector<Id> view_roots(const View &view);-std::optional<Id> resolve_revision(Store &store, const View &view,-                                   std::string_view rev);-std::optional<Id> working_copy_id(const View &view);+std::optional<LoadedCommit> load_commit(Store& store, const Id& id);+bool has_changes(Store& store, const LoadedCommit& loaded);+std::vector<Id> collect_commits(Store& store, std::span<const Id> start);+std::vector<Id> all_commits(Store& store, const View& view);+std::vector<Id> view_roots(const View& view);+std::optional<Id> resolve_revision(Store& store, const View& view, std::string_view rev);+std::optional<Id> working_copy_id(const View& view); -bool contains_id(const std::vector<Id> &ids, const Id &id);-bool target_contains(const std::vector<std::optional<Id>> &ids, const Id &id);+bool contains_id(const std::vector<Id>& ids, const Id& id);+bool target_contains(const std::vector<std::optional<Id>>& ids, const Id& id);  struct FlatEntry {-  std::string path;-  std::uint8_t kind = 0;-  Id target{};+    std::string path;+    std::uint8_t kind = 0;+    Id target{}; }; -std::vector<FlatEntry> flatten_tree(Store &store, const Id &tree_id);-Result<std::vector<FlatEntry>> flatten_tree_checked(Store &store,-                                                    const Id &tree_id);-std::vector<FlatEntry> flatten_or_empty(Store &store,-                                        std::optional<Id> tree_id);-const FlatEntry *find_flat(const std::vector<FlatEntry> &entries,-                           std::string_view path);-int find_tree_name(const Tree &tree, std::string_view name);-bool tree_conflicted(Store &store, const Id &tree_id);+std::vector<FlatEntry> flatten_tree(Store& store, const Id& tree_id);+Result<std::vector<FlatEntry>> flatten_tree_checked(Store& store, const Id& tree_id);+std::vector<FlatEntry> flatten_or_empty(Store& store, std::optional<Id> tree_id);+const FlatEntry* find_flat(const std::vector<FlatEntry>& entries, std::string_view path);+int find_tree_name(const Tree& tree, std::string_view name);+bool tree_conflicted(Store& store, const Id& tree_id);  struct TreeChange {-  std::string path;-  std::uint8_t old_kind = KIND_MISSING;-  std::uint8_t new_kind = KIND_MISSING;-  std::optional<Id> old_id;-  std::optional<Id> new_id;+    std::string path;+    std::uint8_t old_kind = KIND_MISSING;+    std::uint8_t new_kind = KIND_MISSING;+    std::optional<Id> old_id;+    std::optional<Id> new_id; }; -std::vector<TreeChange> compare_trees(Store &store, std::optional<Id> old_tree,+std::vector<TreeChange> compare_trees(Store& store, std::optional<Id> old_tree,                                       std::optional<Id> new_tree); -std::optional<std::vector<std::uint8_t>> read_blob(Store &store, const Id &id);-bool is_lazy_blob(const Id &id);+std::optional<std::vector<std::uint8_t>> read_blob(Store& store, const Id& id);+bool is_lazy_blob(const Id& id);  } // namespace vn--- a/xveins/src/oplog.cpp+++ b/xveins/src/oplog.cpp@@ -11,235 +11,232 @@ namespace {  struct OpRec {-  Id id{};-  Operation op;+    Id id{};+    Operation op; }; -std::vector<OpRec> collect_operations(Store &store,-                                      const std::vector<Id> &heads) {-  std::vector<OpRec> out;-  std::vector<Id> seen;-  std::vector<Id> stack(heads.rbegin(), heads.rend());-  while (!stack.empty()) {-    const Id id = stack.back();-    stack.pop_back();-    if (contains_id(seen, id))-      continue;-    seen.push_back(id);-    auto op = store.read_operation(id);-    if (!op)-      continue;-    for (const auto &parent : op->parents) {-      if (!contains_id(seen, parent))-        stack.push_back(parent);+std::vector<OpRec> collect_operations(Store& store, const std::vector<Id>& heads) {+    std::vector<OpRec> out;+    std::vector<Id> seen;+    std::vector<Id> stack(heads.rbegin(), heads.rend());+    while (!stack.empty()) {+        const Id id = stack.back();+        stack.pop_back();+        if (contains_id(seen, id))+            continue;+        seen.push_back(id);+        auto op = store.read_operation(id);+        if (!op)+            continue;+        for (const auto& parent : op->parents) {+            if (!contains_id(seen, parent))+                stack.push_back(parent);+        }+        out.push_back(OpRec{id, std::move(*op)});     }-    out.push_back(OpRec{id, std::move(*op)});-  }-  return out;+    return out; } -void sort_operations(std::vector<OpRec> &recs) {-  std::stable_sort(-      recs.begin(), recs.end(),-      [](const OpRec &a, const OpRec &b) { return a.op.end.ms > b.op.end.ms; });+void sort_operations(std::vector<OpRec>& recs) {+    std::stable_sort(recs.begin(), recs.end(),+                     [](const OpRec& a, const OpRec& b) { return a.op.end.ms > b.op.end.ms; }); } -std::optional<std::size_t> resolve_operation(const std::vector<OpRec> &recs,+std::optional<std::size_t> resolve_operation(const std::vector<OpRec>& recs,                                              std::string_view text) {-  std::optional<std::size_t> found;-  std::size_t count = 0;-  for (std::size_t i = 0; i < recs.size(); ++i) {-    const std::string full = hex_encode(recs[i].id);-    if (full.size() >= text.size() && full.compare(0, text.size(), text) == 0) {-      found = i;-      ++count;+    std::optional<std::size_t> found;+    std::size_t count = 0;+    for (std::size_t i = 0; i < recs.size(); ++i) {+        const std::string full = hex_encode(recs[i].id);+        if (full.size() >= text.size() && full.compare(0, text.size(), text) == 0) {+            found = i;+            ++count;+        }     }-  }-  if (count == 1)-    return found;-  return std::nullopt;+    if (count == 1)+        return found;+    return std::nullopt; } -std::optional<Id> wc_tree(Store &store, const View &view) {-  const auto wc = working_copy_id(view);-  if (!wc)-    return std::nullopt;-  auto loaded = load_commit(store, *wc);-  if (!loaded)-    return std::nullopt;-  return loaded->commit.root_tree;+std::optional<Id> wc_tree(Store& store, const View& view) {+    const auto wc = working_copy_id(view);+    if (!wc)+        return std::nullopt;+    auto loaded = load_commit(store, *wc);+    if (!loaded)+        return std::nullopt;+    return loaded->commit.root_tree; } -int write_view(const fs::path &root, Store &store, const View &next,-               std::string_view description) {-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto old_tree = wc_tree(store, tx->view());-  const auto new_tree = wc_tree(store, next);-  tx->view() = next;-  if (!tx->finish(description))-    return 1;-  return checkout_materialize_optional(root, store, old_tree, new_tree);+int write_view(const fs::path& root, Store& store, const View& next, std::string_view description) {+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto old_tree = wc_tree(store, tx->view());+    const auto new_tree = wc_tree(store, next);+    tx->view() = next;+    if (!tx->finish(description))+        return 1;+    return checkout_materialize_optional(root, store, old_tree, new_tree); } -int op_log(const std::vector<std::string> &) {-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  Store store = Store::open_all(*root);-  const auto heads = read_heads(*root);-  auto recs = collect_operations(store, heads);-  sort_operations(recs);-  for (const auto &rec : recs) {-    const std::string marker = contains_id(heads, rec.id) ? "@" : " ";-    const std::string stamp = format_utc(rec.op.end.ms / 1000);-    std::cout << marker << " " << hex_encode(rec.id).substr(0, 12) << " "-              << stamp << " " << rec.op.description << "\n";-  }-  return 0;+int op_log(const std::vector<std::string>&) {+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    Store store = Store::open_all(*root);+    const auto heads = read_heads(*root);+    auto recs = collect_operations(store, heads);+    sort_operations(recs);+    for (const auto& rec : recs) {+        const std::string marker = contains_id(heads, rec.id) ? "@" : " ";+        const std::string stamp = format_utc(rec.op.end.ms / 1000);+        std::cout << marker << " " << hex_encode(rec.id).substr(0, 12) << " " << stamp << " "+                  << rec.op.description << "\n";+    }+    return 0; } -int op_restore(const std::vector<std::string> &args, std::size_t start) {-  if (start >= args.size()) {-    error_prefix();-    std::cout << "op restore requires an operation id\n";-    return 1;-  }-  const std::string &text = args[start];-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  const auto heads = read_heads(*root);-  auto recs = collect_operations(store, heads);-  const auto target = resolve_operation(recs, text);-  if (!target) {-    error_prefix();-    std::cout << "unknown operation\n";-    return 1;-  }-  auto target_view = store.read_view(recs[*target].op.view);-  if (!target_view) {-    error_prefix();-    std::cout << "cannot read operation view\n";-    return 1;-  }-  return write_view(*root, store, *target_view, "op restore");+int op_restore(const std::vector<std::string>& args, std::size_t start) {+    if (start >= args.size()) {+        error_prefix();+        std::cout << "op restore requires an operation id\n";+        return 1;+    }+    const std::string& text = args[start];+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    const auto heads = read_heads(*root);+    auto recs = collect_operations(store, heads);+    const auto target = resolve_operation(recs, text);+    if (!target) {+        error_prefix();+        std::cout << "unknown operation\n";+        return 1;+    }+    auto target_view = store.read_view(recs[*target].op.view);+    if (!target_view) {+        error_prefix();+        std::cout << "cannot read operation view\n";+        return 1;+    }+    return write_view(*root, store, *target_view, "op restore"); } -int op_revert(const std::vector<std::string> &args, std::size_t start) {-  if (start >= args.size()) {-    error_prefix();-    std::cout << "op revert requires an operation id\n";-    return 1;-  }-  const std::string &text = args[start];-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  const auto heads = read_heads(*root);-  auto recs = collect_operations(store, heads);-  const auto target = resolve_operation(recs, text);-  if (!target) {-    error_prefix();-    std::cout << "unknown operation\n";-    return 1;-  }-  const auto &op = recs[*target].op;-  View view;-  if (!op.parents.empty()) {-    auto parent = store.read_operation(op.parents.front());-    if (parent) {-      auto parent_view = store.read_view(parent->view);-      if (parent_view)-        view = std::move(*parent_view);+int op_revert(const std::vector<std::string>& args, std::size_t start) {+    if (start >= args.size()) {+        error_prefix();+        std::cout << "op revert requires an operation id\n";+        return 1;     }-  }-  return write_view(*root, store, view, "op revert");+    const std::string& text = args[start];+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    const auto heads = read_heads(*root);+    auto recs = collect_operations(store, heads);+    const auto target = resolve_operation(recs, text);+    if (!target) {+        error_prefix();+        std::cout << "unknown operation\n";+        return 1;+    }+    const auto& op = recs[*target].op;+    View view;+    if (!op.parents.empty()) {+        auto parent = store.read_operation(op.parents.front());+        if (parent) {+            auto parent_view = store.read_view(parent->view);+            if (parent_view)+                view = std::move(*parent_view);+        }+    }+    return write_view(*root, store, view, "op revert"); }  } // namespace -int op_run(const std::vector<std::string> &args) {-  if (args.size() <= 2) {+int op_run(const std::vector<std::string>& args) {+    if (args.size() <= 2) {+        error_prefix();+        std::cout << "expected an op subcommand (log, restore, revert)\n";+        return 1;+    }+    const std::string& sub = args[2];+    if (sub == "log")+        return op_log(args);+    if (sub == "restore")+        return op_restore(args, 3);+    if (sub == "revert")+        return op_revert(args, 3);     error_prefix();-    std::cout << "expected an op subcommand (log, restore, revert)\n";+    std::cout << "unknown op subcommand: " << sub << "\n";     return 1;-  }-  const std::string &sub = args[2];-  if (sub == "log")-    return op_log(args);-  if (sub == "restore")-    return op_restore(args, 3);-  if (sub == "revert")-    return op_revert(args, 3);-  error_prefix();-  std::cout << "unknown op subcommand: " << sub << "\n";-  return 1; } -int undo_run(const std::vector<std::string> &) {-  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;-  Store store = Store::open_all(*root);-  const auto heads = read_heads(*root);-  if (heads.empty()) {-    error_prefix();-    std::cout << "no operations to undo\n";-    return 1;-  }-  auto recs = collect_operations(store, heads);-  sort_operations(recs);-  if (recs.empty()) {-    error_prefix();-    std::cout << "cannot resolve undo target\n";-    return 1;-  }-  const auto &latest = recs.front().op;-  View view;-  if (!latest.parents.empty()) {-    auto parent = store.read_operation(latest.parents.front());-    if (!parent) {-      error_prefix();-      std::cout << "cannot resolve undo target\n";-      return 1;+int undo_run(const std::vector<std::string>&) {+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;     }-    auto parent_view = store.read_view(parent->view);-    if (!parent_view) {-      error_prefix();-      std::cout << "cannot resolve undo target\n";-      return 1;+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap;+    Store store = Store::open_all(*root);+    const auto heads = read_heads(*root);+    if (heads.empty()) {+        error_prefix();+        std::cout << "no operations to undo\n";+        return 1;     }-    view = std::move(*parent_view);-  }-  return write_view(*root, store, view, "undo");+    auto recs = collect_operations(store, heads);+    sort_operations(recs);+    if (recs.empty()) {+        error_prefix();+        std::cout << "cannot resolve undo target\n";+        return 1;+    }+    const auto& latest = recs.front().op;+    View view;+    if (!latest.parents.empty()) {+        auto parent = store.read_operation(latest.parents.front());+        if (!parent) {+            error_prefix();+            std::cout << "cannot resolve undo target\n";+            return 1;+        }+        auto parent_view = store.read_view(parent->view);+        if (!parent_view) {+            error_prefix();+            std::cout << "cannot resolve undo target\n";+            return 1;+        }+        view = std::move(*parent_view);+    }+    return write_view(*root, store, view, "undo"); }  } // namespace vn--- a/xveins/src/pathspec.cpp+++ b/xveins/src/pathspec.cpp@@ -8,89 +8,85 @@  // Collapse "." and ".." components and drop empty components. std::optional<std::string> normalize_components(std::string_view input) {-  std::vector<std::string_view> comps;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= input.size(); ++i) {-    const bool at_end = i == input.size();-    if (!at_end && input[i] != '/')-      continue;-    const std::string_view comp = input.substr(start, i - start);-    if (!comp.empty() && comp != ".") {-      if (comp == "..") {-        if (comps.empty())-          return std::nullopt;-        comps.pop_back();-      } else {-        comps.push_back(comp);-      }+    std::vector<std::string_view> comps;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= input.size(); ++i) {+        const bool at_end = i == input.size();+        if (!at_end && input[i] != '/')+            continue;+        const std::string_view comp = input.substr(start, i - start);+        if (!comp.empty() && comp != ".") {+            if (comp == "..") {+                if (comps.empty())+                    return std::nullopt;+                comps.pop_back();+            } else {+                comps.push_back(comp);+            }+        }+        start = i + 1;     }-    start = i + 1;-  }-  std::string out;-  for (std::size_t i = 0; i < comps.size(); ++i) {-    if (i != 0)-      out.push_back('/');-    out.append(comps[i]);-  }-  return out;+    std::string out;+    for (std::size_t i = 0; i < comps.size(); ++i) {+        if (i != 0)+            out.push_back('/');+        out.append(comps[i]);+    }+    return out; }  std::string join_relative(std::string_view base, std::string_view arg) {-  if (base.empty())-    return std::string(arg);-  if (arg.empty())-    return std::string(base);-  std::string out(base);-  out.push_back('/');-  out.append(arg);-  return out;+    if (base.empty())+        return std::string(arg);+    if (arg.empty())+        return std::string(base);+    std::string out(base);+    out.push_back('/');+    out.append(arg);+    return out; }  } // namespace -std::optional<std::string> cwd_relative(const fs::path &root) {-  std::error_code ec;-  fs::path cwd = fs::current_path(ec);-  if (ec)-    return std::nullopt;-  cwd = fs::weakly_canonical(cwd, ec);-  if (ec)+std::optional<std::string> cwd_relative(const fs::path& root) {+    std::error_code ec;+    fs::path cwd = fs::current_path(ec);+    if (ec)+        return std::nullopt;+    cwd = fs::weakly_canonical(cwd, ec);+    if (ec)+        return std::nullopt;+    const std::string canon = path_to_bytes(cwd);+    const std::string root_bytes = path_to_bytes(root);+    if (canon == root_bytes)+        return std::string();+    if (canon.size() > root_bytes.size() && canon.compare(0, root_bytes.size(), root_bytes) == 0 &&+        canon[root_bytes.size()] == '/')+        return canon.substr(root_bytes.size() + 1);     return std::nullopt;-  const std::string canon = path_to_bytes(cwd);-  const std::string root_bytes = path_to_bytes(root);-  if (canon == root_bytes)-    return std::string();-  if (canon.size() > root_bytes.size() &&-      canon.compare(0, root_bytes.size(), root_bytes) == 0 &&-      canon[root_bytes.size()] == '/')-    return canon.substr(root_bytes.size() + 1);-  return std::nullopt; } -std::optional<std::string> pathspec_normalize(const fs::path &root,-                                              std::string_view cwd_rel,+std::optional<std::string> pathspec_normalize(const fs::path& root, std::string_view cwd_rel,                                               std::string_view arg) {-  if (arg.empty())-    return std::nullopt;-  if (arg.front() == '/') {-    auto norm = normalize_components(arg);-    if (!norm)-      return std::nullopt;-    std::string root_view = path_to_bytes(root);-    if (!root_view.empty() && root_view.front() == '/')-      root_view.erase(0, 1);-    if (norm->size() > root_view.size() &&-        norm->compare(0, root_view.size(), root_view) == 0 &&-        (*norm)[root_view.size()] == '/')-      return norm->substr(root_view.size() + 1);-    return std::nullopt;-  }-  return normalize_components(join_relative(cwd_rel, arg));+    if (arg.empty())+        return std::nullopt;+    if (arg.front() == '/') {+        auto norm = normalize_components(arg);+        if (!norm)+            return std::nullopt;+        std::string root_view = path_to_bytes(root);+        if (!root_view.empty() && root_view.front() == '/')+            root_view.erase(0, 1);+        if (norm->size() > root_view.size() && norm->compare(0, root_view.size(), root_view) == 0 &&+            (*norm)[root_view.size()] == '/')+            return norm->substr(root_view.size() + 1);+        return std::nullopt;+    }+    return normalize_components(join_relative(cwd_rel, arg)); }  bool pathspec_has_glob(std::string_view value) {-  return value.find('*') != std::string_view::npos ||-         value.find('?') != std::string_view::npos;+    return value.find('*') != std::string_view::npos || value.find('?') != std::string_view::npos; }  } // namespace vn--- a/xveins/src/pathspec.h+++ b/xveins/src/pathspec.h@@ -9,13 +9,12 @@  // Current directory relative to the repository root, or nullopt when the // process is outside the repository.-std::optional<std::string> cwd_relative(const fs::path &root);+std::optional<std::string> cwd_relative(const fs::path& root);  // Normalize one command-line operand into a repository-relative path. Relative // operands are resolved against `cwd_rel`; absolute operands must live inside // `root`. Glob metacharacters are preserved.-std::optional<std::string> pathspec_normalize(const fs::path &root,-                                              std::string_view cwd_rel,+std::optional<std::string> pathspec_normalize(const fs::path& root, std::string_view cwd_rel,                                               std::string_view arg);  bool pathspec_has_glob(std::string_view value);--- a/xveins/src/promisor.cpp+++ b/xveins/src/promisor.cpp@@ -12,46 +12,47 @@ namespace {  std::string remote_field(std::string_view remote, std::string_view field) {-  std::string out = "remote.";-  out += remote;-  out.push_back('.');-  out += field;-  return out;+    std::string out = "remote.";+    out += remote;+    out.push_back('.');+    out += field;+    return out; } -bool fetch_missing_chunk(const fs::path &root, const Id &id) {-  static thread_local bool active = false;-  if (active)-    return false;-  active = true;-  struct Guard {-    bool &flag;-    ~Guard() { flag = false; }-  } guard{active};+bool fetch_missing_chunk(const fs::path& root, const Id& id) {+    static thread_local bool active = false;+    if (active)+        return false;+    active = true;+    struct Guard {+        bool& flag;+        ~Guard() {+            flag = false;+        }+    } guard{active}; -  auto promisor = repo_config_value(root, "promisor");-  if (!promisor || promisor->empty())-    return false;-  auto url = repo_config_value(root, remote_field(*promisor, "url"));-  if (!url || url->empty())-    return false;-  auto key = repo_config_value(root, remote_field(*promisor, "key"));-  auto pin = repo_config_value(root, remote_field(*promisor, "tls-pin"));-  const std::string repo_name = proto::url_repo_name(*url);-  auto client = proto::Client::connect(*url, key ? *key : std::string(),-                                       repo_name, pin ? *pin : std::string());-  if (!client)-    return false;-  const std::vector<Id> ids = {id};-  return client->get_chunks(root, ids);+    auto promisor = repo_config_value(root, "promisor");+    if (!promisor || promisor->empty())+        return false;+    auto url = repo_config_value(root, remote_field(*promisor, "url"));+    if (!url || url->empty())+        return false;+    auto key = repo_config_value(root, remote_field(*promisor, "key"));+    auto pin = repo_config_value(root, remote_field(*promisor, "tls-pin"));+    const std::string repo_name = proto::url_repo_name(*url);+    auto client = proto::Client::connect(*url, key ? *key : std::string(), repo_name,+                                         pin ? *pin : std::string());+    if (!client)+        return false;+    const std::vector<Id> ids = {id};+    return client->get_chunks(root, ids); }  } // namespace  void install_promisor_fetcher() {-  set_promisor_fetcher([](const fs::path &root, const Id &id) {-    return fetch_missing_chunk(root, id);-  });+    set_promisor_fetcher(+        [](const fs::path& root, const Id& id) { return fetch_missing_chunk(root, id); }); }  } // namespace vn--- a/xveins/src/protocol.cpp+++ b/xveins/src/protocol.cpp@@ -14,168 +14,167 @@ namespace {  std::string connect_error;-std::string &connect_error_slot() { return connect_error; }+std::string& connect_error_slot() {+    return connect_error;+} -void put_u16_be(ByteWriter &writer, std::uint16_t value) {-  writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));-  writer.u8(static_cast<std::uint8_t>(value & 255u));+void put_u16_be(ByteWriter& writer, std::uint16_t value) {+    writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));+    writer.u8(static_cast<std::uint8_t>(value & 255u)); } -std::optional<std::uint16_t> read_u16_be(Reader &reader) {-  const auto high = reader.u8();-  if (!high)-    return std::nullopt;-  const auto low = reader.u8();-  if (!low)-    return std::nullopt;-  return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) |-                                    *low);+std::optional<std::uint16_t> read_u16_be(Reader& reader) {+    const auto high = reader.u8();+    if (!high)+        return std::nullopt;+    const auto low = reader.u8();+    if (!low)+        return std::nullopt;+    return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) | *low); } -std::vector<std::uint8_t>-encode_string_list(const std::vector<std::string> &items) {-  ByteWriter writer(128);-  writer.varint(items.size());-  for (const auto &item : items)-    writer.length_prefixed(item);-  return writer.take();+std::vector<std::uint8_t> encode_string_list(const std::vector<std::string>& items) {+    ByteWriter writer(128);+    writer.varint(items.size());+    for (const auto& item : items)+        writer.length_prefixed(item);+    return writer.take(); } -std::optional<std::vector<std::string>> decode_string_list(Reader &reader,-                                                           std::size_t max) {-  const auto count = reader.list_len(max);-  if (!count)-    return std::nullopt;-  std::vector<std::string> out;-  out.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const auto value = reader.bytes(4096);-    if (!value)-      return std::nullopt;-    out.emplace_back(str_of(*value));-  }-  return out;+std::optional<std::vector<std::string>> decode_string_list(Reader& reader, std::size_t max) {+    const auto count = reader.list_len(max);+    if (!count)+        return std::nullopt;+    std::vector<std::string> out;+    out.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const auto value = reader.bytes(4096);+        if (!value)+            return std::nullopt;+        out.emplace_back(str_of(*value));+    }+    return out; } -std::string bytes_to_string(Bytes data) { return std::string(str_of(data)); }+std::string bytes_to_string(Bytes data) {+    return std::string(str_of(data));+} -void append_id(ByteWriter &writer, const Id &id) {-  writer.raw(Bytes(id.data(), id.size()));+void append_id(ByteWriter& writer, const Id& id) {+    writer.raw(Bytes(id.data(), id.size())); } -std::optional<Id> read_id(Reader &reader) {-  const auto id = reader.id();-  if (!id)-    return std::nullopt;-  return *id;+std::optional<Id> read_id(Reader& reader) {+    const auto id = reader.id();+    if (!id)+        return std::nullopt;+    return *id; }  std::size_t find_char(std::string_view text, char needle) {-  const auto at = text.find(needle);-  return at == std::string_view::npos ? std::string_view::npos : at;+    const auto at = text.find(needle);+    return at == std::string_view::npos ? std::string_view::npos : at; }  struct Authority {-  std::string host;-  int port = 0;+    std::string host;+    int port = 0; }; -Authority parse_authority(std::string_view authority, int default_port,-                          bool strip_user) {-  if (strip_user) {-    const auto at = find_char(authority, '@');-    if (at != std::string_view::npos)-      authority.remove_prefix(at + 1);-  }-  Authority out;-  out.host = std::string(authority);-  out.port = default_port;-  const auto colon = find_char(authority, ':');-  if (colon != std::string_view::npos) {-    out.host = std::string(authority.substr(0, colon));-    const std::string_view port_text = authority.substr(colon + 1);-    if (!port_text.empty()) {-      int port = 0;-      bool numeric = true;-      for (char c : port_text) {-        if (c < '0' || c > '9') {-          numeric = false;-          break;+Authority parse_authority(std::string_view authority, int default_port, bool strip_user) {+    if (strip_user) {+        const auto at = find_char(authority, '@');+        if (at != std::string_view::npos)+            authority.remove_prefix(at + 1);+    }+    Authority out;+    out.host = std::string(authority);+    out.port = default_port;+    const auto colon = find_char(authority, ':');+    if (colon != std::string_view::npos) {+        out.host = std::string(authority.substr(0, colon));+        const std::string_view port_text = authority.substr(colon + 1);+        if (!port_text.empty()) {+            int port = 0;+            bool numeric = true;+            for (char c : port_text) {+                if (c < '0' || c > '9') {+                    numeric = false;+                    break;+                }+                if (port > 1000000)+                    port = 1000000;+                port = port * 10 + (c - '0');+            }+            if (numeric)+                out.port = port;         }-        if (port > 1000000)-          port = 1000000;-        port = port * 10 + (c - '0');-      }-      if (numeric)-        out.port = port;     }-  }-  return out;+    return out; } -std::optional<net::Stream>-connect_stream(const Url &url, std::string_view tls_pin, std::string &binding) {-  if (url.ssh) {-    std::vector<std::string> remote = {"vn", "serve", "-stdio", url.path};-    const std::string remote_command = net::build_shell_command(remote);-    std::vector<std::string> argv = {"ssh"};-    if (url.port != 22) {-      argv.push_back("-p");-      argv.push_back(std::to_string(url.port));+std::optional<net::Stream> connect_stream(const Url& url, std::string_view tls_pin,+                                          std::string& binding) {+    if (url.ssh) {+        std::vector<std::string> remote = {"vn", "serve", "-stdio", url.path};+        const std::string remote_command = net::build_shell_command(remote);+        std::vector<std::string> argv = {"ssh"};+        if (url.port != 22) {+            argv.push_back("-p");+            argv.push_back(std::to_string(url.port));+        }+        argv.push_back(url.host);+        argv.push_back(remote_command);+        auto stream = net::Stream::spawn_argv(argv);+        if (!stream)+            connect_error = "cannot start the SSH transport";+        return stream;     }-    argv.push_back(url.host);-    argv.push_back(remote_command);+    if (url.tls) {+        auto fd = net::tcp_connect(url.host, url.port);+        if (!fd) {+            connect_error = "cannot connect: host refused the connection or is unreachable";+            return std::nullopt;+        }+        void* ctx = net::tls_client_ctx(!tls_pin.empty());+        if (!ctx) {+            net::close_socket(*fd);+            connect_error = "cannot initialize TLS";+            return std::nullopt;+        }+        void* ssl = net::tls_connect(ctx, *fd, url.host);+        net::tls_ctx_free(ctx);+        if (!ssl) {+            net::close_socket(*fd);+            connect_error = "TLS handshake failed";+            return std::nullopt;+        }+        std::array<std::uint8_t, 32> exported{};+        if (net::tls_exporter(ssl, exported.data(), exported.size()))+            binding.assign(reinterpret_cast<const char*>(exported.data()), exported.size());+        if (!tls_pin.empty()) {+            std::array<std::uint8_t, 32> digest{};+            const bool got = net::tls_peer_sha256(ssl, digest.data());+            const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));+            if (!got || !net::hex_equal(hex, tls_pin)) {+                net::close_socket(*fd);+                net::tls_free(ssl);+                connect_error = "TLS certificate pin mismatch";+                return std::nullopt;+            }+        }+        return net::Stream::tls_stream(*fd, ssl);+    }+    std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve", "-stdio", url.path};     auto stream = net::Stream::spawn_argv(argv);     if (!stream)-      connect_error = "cannot start the SSH transport";+        connect_error = "cannot start the local vn server";     return stream;-  }-  if (url.tls) {-    auto fd = net::tcp_connect(url.host, url.port);-    if (!fd) {-      connect_error =-          "cannot connect: host refused the connection or is unreachable";-      return std::nullopt;-    }-    void *ctx = net::tls_client_ctx(!tls_pin.empty());-    if (!ctx) {-      net::close_socket(*fd);-      connect_error = "cannot initialize TLS";-      return std::nullopt;-    }-    void *ssl = net::tls_connect(ctx, *fd, url.host);-    net::tls_ctx_free(ctx);-    if (!ssl) {-      net::close_socket(*fd);-      connect_error = "TLS handshake failed";-      return std::nullopt;-    }-    std::array<std::uint8_t, 32> exported{};-    if (net::tls_exporter(ssl, exported.data(), exported.size()))-      binding.assign(reinterpret_cast<const char *>(exported.data()),-                     exported.size());-    if (!tls_pin.empty()) {-      std::array<std::uint8_t, 32> digest{};-      const bool got = net::tls_peer_sha256(ssl, digest.data());-      const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));-      if (!got || !net::hex_equal(hex, tls_pin)) {-        net::close_socket(*fd);-        net::tls_free(ssl);-        connect_error = "TLS certificate pin mismatch";-        return std::nullopt;-      }-    }-    return net::Stream::tls_stream(*fd, ssl);-  }-  std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve",-                                   "-stdio", url.path};-  auto stream = net::Stream::spawn_argv(argv);-  if (!stream)-    connect_error = "cannot start the local vn server";-  return stream; } -std::string id_text(const Id &id) { return hex_encode(id); }+std::string id_text(const Id& id) {+    return hex_encode(id);+}  } // namespace @@ -183,346 +182,343 @@ // Message codecs // --------------------------------------------------------------------------- -std::vector<std::uint8_t> encode_hello(const Hello &hello) {-  ByteWriter writer(128);-  put_u16_be(writer, hello.min_version);-  put_u16_be(writer, hello.max_version);-  writer.raw(Bytes(encode_string_list(hello.capabilities)));-  writer.length_prefixed(hello.repo);-  writer.length_prefixed(hello.client_nonce);-  return writer.take();+std::vector<std::uint8_t> encode_hello(const Hello& hello) {+    ByteWriter writer(128);+    put_u16_be(writer, hello.min_version);+    put_u16_be(writer, hello.max_version);+    writer.raw(Bytes(encode_string_list(hello.capabilities)));+    writer.length_prefixed(hello.repo);+    writer.length_prefixed(hello.client_nonce);+    return writer.take(); }  std::optional<Hello> decode_hello(Bytes data) {-  Reader reader(data);-  const auto min_version = read_u16_be(reader);-  if (!min_version)-    return std::nullopt;-  const auto max_version = read_u16_be(reader);-  if (!max_version)-    return std::nullopt;-  auto capabilities = decode_string_list(reader, 64);-  if (!capabilities)-    return std::nullopt;-  const auto repo = reader.bytes(4096);-  if (!repo)-    return std::nullopt;-  const auto nonce = reader.bytes(64);-  if (!nonce)-    return std::nullopt;-  if (!reader.finish())-    return std::nullopt;-  Hello out;-  out.min_version = *min_version;-  out.max_version = *max_version;-  out.capabilities = std::move(*capabilities);-  out.repo = bytes_to_string(*repo);-  out.client_nonce = bytes_to_string(*nonce);-  return out;+    Reader reader(data);+    const auto min_version = read_u16_be(reader);+    if (!min_version)+        return std::nullopt;+    const auto max_version = read_u16_be(reader);+    if (!max_version)+        return std::nullopt;+    auto capabilities = decode_string_list(reader, 64);+    if (!capabilities)+        return std::nullopt;+    const auto repo = reader.bytes(4096);+    if (!repo)+        return std::nullopt;+    const auto nonce = reader.bytes(64);+    if (!nonce)+        return std::nullopt;+    if (!reader.finish())+        return std::nullopt;+    Hello out;+    out.min_version = *min_version;+    out.max_version = *max_version;+    out.capabilities = std::move(*capabilities);+    out.repo = bytes_to_string(*repo);+    out.client_nonce = bytes_to_string(*nonce);+    return out; } -std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello) {-  ByteWriter writer(128);-  put_u16_be(writer, hello.version);-  writer.raw(Bytes(encode_string_list(hello.capabilities)));-  writer.length_prefixed(hello.server_nonce);-  writer.u8(hello.auth_required);-  return writer.take();+std::vector<std::uint8_t> encode_hello_ok(const HelloOk& hello) {+    ByteWriter writer(128);+    put_u16_be(writer, hello.version);+    writer.raw(Bytes(encode_string_list(hello.capabilities)));+    writer.length_prefixed(hello.server_nonce);+    writer.u8(hello.auth_required);+    return writer.take(); }  std::optional<HelloOk> decode_hello_ok(Bytes data) {-  Reader reader(data);-  const auto version = read_u16_be(reader);-  if (!version)-    return std::nullopt;-  auto capabilities = decode_string_list(reader, 64);-  if (!capabilities)-    return std::nullopt;-  const auto nonce = reader.bytes(64);-  if (!nonce)-    return std::nullopt;-  const auto auth = reader.u8();-  if (!auth)-    return std::nullopt;-  if (!reader.finish())-    return std::nullopt;-  HelloOk out;-  out.version = *version;-  out.capabilities = std::move(*capabilities);-  out.server_nonce = bytes_to_string(*nonce);-  out.auth_required = *auth;-  return out;+    Reader reader(data);+    const auto version = read_u16_be(reader);+    if (!version)+        return std::nullopt;+    auto capabilities = decode_string_list(reader, 64);+    if (!capabilities)+        return std::nullopt;+    const auto nonce = reader.bytes(64);+    if (!nonce)+        return std::nullopt;+    const auto auth = reader.u8();+    if (!auth)+        return std::nullopt;+    if (!reader.finish())+        return std::nullopt;+    HelloOk out;+    out.version = *version;+    out.capabilities = std::move(*capabilities);+    out.server_nonce = bytes_to_string(*nonce);+    out.auth_required = *auth;+    return out; } -std::vector<std::uint8_t> encode_auth(const Auth &auth) {-  ByteWriter writer(128);-  writer.length_prefixed(auth.public_key);-  writer.length_prefixed(auth.signature);-  return writer.take();+std::vector<std::uint8_t> encode_auth(const Auth& auth) {+    ByteWriter writer(128);+    writer.length_prefixed(auth.public_key);+    writer.length_prefixed(auth.signature);+    return writer.take(); }  std::optional<Auth> decode_auth(Bytes data) {-  Reader reader(data);-  const auto public_key = reader.bytes(64);-  if (!public_key)-    return std::nullopt;-  const auto signature = reader.bytes(128);-  if (!signature)-    return std::nullopt;-  if (!reader.finish())-    return std::nullopt;-  return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)};+    Reader reader(data);+    const auto public_key = reader.bytes(64);+    if (!public_key)+        return std::nullopt;+    const auto signature = reader.bytes(128);+    if (!signature)+        return std::nullopt;+    if (!reader.finish())+        return std::nullopt;+    return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)}; } -std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth) {-  ByteWriter writer(64);-  writer.u8(auth.role);-  writer.length_prefixed(auth.fingerprint);-  return writer.take();+std::vector<std::uint8_t> encode_auth_ok(const AuthOk& auth) {+    ByteWriter writer(64);+    writer.u8(auth.role);+    writer.length_prefixed(auth.fingerprint);+    return writer.take(); }  std::optional<AuthOk> decode_auth_ok(Bytes data) {-  Reader reader(data);-  const auto role = reader.u8();-  if (!role)-    return std::nullopt;-  const auto fingerprint = reader.bytes(64);-  if (!fingerprint)-    return std::nullopt;-  if (!reader.finish())-    return std::nullopt;-  return AuthOk{*role, bytes_to_string(*fingerprint)};+    Reader reader(data);+    const auto role = reader.u8();+    if (!role)+        return std::nullopt;+    const auto fingerprint = reader.bytes(64);+    if (!fingerprint)+        return std::nullopt;+    if (!reader.finish())+        return std::nullopt;+    return AuthOk{*role, bytes_to_string(*fingerprint)}; } -std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs) {-  ByteWriter writer(256);-  writer.varint(refs.size());-  for (const auto &ref : refs) {-    writer.length_prefixed(ref.name);-    append_id(writer, ref.target);-    writer.length_prefixed(ref.change_id);-    writer.u8(ref.kind);-  }-  return writer.take();+std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo>& refs) {+    ByteWriter writer(256);+    writer.varint(refs.size());+    for (const auto& ref : refs) {+        writer.length_prefixed(ref.name);+        append_id(writer, ref.target);+        writer.length_prefixed(ref.change_id);+        writer.u8(ref.kind);+    }+    return writer.take(); }  std::optional<std::vector<RefInfo>> decode_refs(Bytes data) {-  Reader reader(data);-  const auto count = reader.list_len(1000000);-  if (!count)-    return std::nullopt;-  std::vector<RefInfo> out;-  out.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const auto name = reader.bytes(4096);-    if (!name)-      return std::nullopt;-    const auto target = read_id(reader);-    if (!target)-      return std::nullopt;-    const auto change_id = reader.bytes(64);-    if (!change_id)-      return std::nullopt;-    const auto kind = reader.u8();-    if (!kind)-      return std::nullopt;-    RefInfo ref;-    ref.name = bytes_to_string(*name);-    ref.target = *target;-    ref.change_id = bytes_to_string(*change_id);-    ref.kind = *kind;-    out.push_back(std::move(ref));-  }-  if (!reader.finish())-    return std::nullopt;-  return out;+    Reader reader(data);+    const auto count = reader.list_len(1000000);+    if (!count)+        return std::nullopt;+    std::vector<RefInfo> out;+    out.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const auto name = reader.bytes(4096);+        if (!name)+            return std::nullopt;+        const auto target = read_id(reader);+        if (!target)+            return std::nullopt;+        const auto change_id = reader.bytes(64);+        if (!change_id)+            return std::nullopt;+        const auto kind = reader.u8();+        if (!kind)+            return std::nullopt;+        RefInfo ref;+        ref.name = bytes_to_string(*name);+        ref.target = *target;+        ref.change_id = bytes_to_string(*change_id);+        ref.kind = *kind;+        out.push_back(std::move(ref));+    }+    if (!reader.finish())+        return std::nullopt;+    return out; } -std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids) {-  ByteWriter writer(ids.size() * 32 + 8);-  writer.varint(ids.size());-  for (const auto &id : ids)-    append_id(writer, id);-  return writer.take();+std::vector<std::uint8_t> encode_ids(const std::vector<Id>& ids) {+    ByteWriter writer(ids.size() * 32 + 8);+    writer.varint(ids.size());+    for (const auto& id : ids)+        append_id(writer, id);+    return writer.take(); }  std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max) {-  Reader reader(data);-  const auto count = reader.list_len(max);-  if (!count)-    return std::nullopt;-  std::vector<Id> out;-  out.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const auto id = read_id(reader);-    if (!id)-      return std::nullopt;-    out.push_back(*id);-  }-  if (!reader.finish())-    return std::nullopt;-  return out;+    Reader reader(data);+    const auto count = reader.list_len(max);+    if (!count)+        return std::nullopt;+    std::vector<Id> out;+    out.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const auto id = read_id(reader);+        if (!id)+            return std::nullopt;+        out.push_back(*id);+    }+    if (!reader.finish())+        return std::nullopt;+    return out; } -std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,-                                           const std::vector<Id> &haves) {-  ByteWriter writer(256);-  writer.varint(wants.size());-  for (const auto &id : wants)-    append_id(writer, id);-  writer.varint(haves.size());-  for (const auto &id : haves)-    append_id(writer, id);-  return writer.take();+std::vector<std::uint8_t> encode_negotiate(const std::vector<Id>& wants,+                                           const std::vector<Id>& haves) {+    ByteWriter writer(256);+    writer.varint(wants.size());+    for (const auto& id : wants)+        append_id(writer, id);+    writer.varint(haves.size());+    for (const auto& id : haves)+        append_id(writer, id);+    return writer.take(); }  std::optional<Negotiate> decode_negotiate(Bytes data) {-  Reader reader(data);-  const auto want_count = reader.list_len(1000000);-  if (!want_count)-    return std::nullopt;-  Negotiate out;-  out.wants.reserve(*want_count);-  for (std::size_t i = 0; i < *want_count; ++i) {-    const auto id = read_id(reader);-    if (!id)-      return std::nullopt;-    out.wants.push_back(*id);-  }-  const auto have_count = reader.list_len(1000000);-  if (!have_count)-    return std::nullopt;-  out.haves.reserve(*have_count);-  for (std::size_t i = 0; i < *have_count; ++i) {-    const auto id = read_id(reader);-    if (!id)-      return std::nullopt;-    out.haves.push_back(*id);-  }-  if (!reader.finish())-    return std::nullopt;-  return out;+    Reader reader(data);+    const auto want_count = reader.list_len(1000000);+    if (!want_count)+        return std::nullopt;+    Negotiate out;+    out.wants.reserve(*want_count);+    for (std::size_t i = 0; i < *want_count; ++i) {+        const auto id = read_id(reader);+        if (!id)+            return std::nullopt;+        out.wants.push_back(*id);+    }+    const auto have_count = reader.list_len(1000000);+    if (!have_count)+        return std::nullopt;+    out.haves.reserve(*have_count);+    for (std::size_t i = 0; i < *have_count; ++i) {+        const auto id = read_id(reader);+        if (!id)+            return std::nullopt;+        out.haves.push_back(*id);+    }+    if (!reader.finish())+        return std::nullopt;+    return out; } -std::vector<std::uint8_t>-encode_negotiate_ok(const std::vector<std::uint8_t> &known,-                    std::uint8_t enough) {-  ByteWriter writer(known.size() + 16);-  writer.u8(enough);-  writer.varint(known.size());-  for (std::uint8_t bit : known)-    writer.u8(bit);-  return writer.take();+std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t>& known,+                                              std::uint8_t enough) {+    ByteWriter writer(known.size() + 16);+    writer.u8(enough);+    writer.varint(known.size());+    for (std::uint8_t bit : known)+        writer.u8(bit);+    return writer.take(); }  std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data) {-  Reader reader(data);-  const auto enough = reader.u8();-  if (!enough)-    return std::nullopt;-  const auto count = reader.list_len(1000000);-  if (!count)-    return std::nullopt;-  std::vector<std::uint8_t> out;-  out.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const auto bit = reader.u8();-    if (!bit)-      return std::nullopt;-    out.push_back(*bit);-  }-  if (!reader.finish())-    return std::nullopt;-  return out;+    Reader reader(data);+    const auto enough = reader.u8();+    if (!enough)+        return std::nullopt;+    const auto count = reader.list_len(1000000);+    if (!count)+        return std::nullopt;+    std::vector<std::uint8_t> out;+    out.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const auto bit = reader.u8();+        if (!bit)+            return std::nullopt;+        out.push_back(*bit);+    }+    if (!reader.finish())+        return std::nullopt;+    return out; } -std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits) {-  ByteWriter writer(bits.size() + 8);-  writer.varint(bits.size());-  for (std::uint8_t bit : bits)-    writer.u8(bit);-  return writer.take();+std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t>& bits) {+    ByteWriter writer(bits.size() + 8);+    writer.varint(bits.size());+    for (std::uint8_t bit : bits)+        writer.u8(bit);+    return writer.take(); }  std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data) {-  Reader reader(data);-  const auto count = reader.list_len(1000000);-  if (!count)-    return std::nullopt;-  std::vector<std::uint8_t> out;-  out.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const auto bit = reader.u8();-    if (!bit)-      return std::nullopt;-    out.push_back(*bit);-  }-  if (!reader.finish())-    return std::nullopt;-  return out;+    Reader reader(data);+    const auto count = reader.list_len(1000000);+    if (!count)+        return std::nullopt;+    std::vector<std::uint8_t> out;+    out.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const auto bit = reader.u8();+        if (!bit)+            return std::nullopt;+        out.push_back(*bit);+    }+    if (!reader.finish())+        return std::nullopt;+    return out; } -std::vector<std::uint8_t>-encode_update_refs(const std::vector<UpdateRef> &updates) {-  ByteWriter writer(256);-  writer.varint(updates.size());-  for (const auto &update : updates) {-    writer.length_prefixed(update.name);-    writer.opt_id(update.expected);-    writer.opt_id(update.target);-  }-  return writer.take();+std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef>& updates) {+    ByteWriter writer(256);+    writer.varint(updates.size());+    for (const auto& update : updates) {+        writer.length_prefixed(update.name);+        writer.opt_id(update.expected);+        writer.opt_id(update.target);+    }+    return writer.take(); }  std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data) {-  Reader reader(data);-  const auto count = reader.list_len(1000000);-  if (!count)-    return std::nullopt;-  std::vector<UpdateRef> out;-  out.reserve(*count);-  for (std::size_t i = 0; i < *count; ++i) {-    const auto name = reader.bytes(4096);-    if (!name)-      return std::nullopt;-    const auto expected = reader.opt_id();-    if (!expected)-      return std::nullopt;-    const auto target = reader.opt_id();-    if (!target)-      return std::nullopt;-    UpdateRef update;-    update.name = bytes_to_string(*name);-    update.expected = *expected;-    update.target = *target;-    out.push_back(std::move(update));-  }-  if (!reader.finish())-    return std::nullopt;-  return out;+    Reader reader(data);+    const auto count = reader.list_len(1000000);+    if (!count)+        return std::nullopt;+    std::vector<UpdateRef> out;+    out.reserve(*count);+    for (std::size_t i = 0; i < *count; ++i) {+        const auto name = reader.bytes(4096);+        if (!name)+            return std::nullopt;+        const auto expected = reader.opt_id();+        if (!expected)+            return std::nullopt;+        const auto target = reader.opt_id();+        if (!target)+            return std::nullopt;+        UpdateRef update;+        update.name = bytes_to_string(*name);+        update.expected = *expected;+        update.target = *target;+        out.push_back(std::move(update));+    }+    if (!reader.finish())+        return std::nullopt;+    return out; } -std::string auth_message(std::uint16_t version, std::string_view repo,-                         Bytes server_nonce, Bytes client_nonce,-                         Bytes binding) {-  ByteWriter writer(128);-  writer.raw(std::string_view("veins-auth/1"));-  writer.u8(0);-  writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));-  writer.u8(static_cast<std::uint8_t>(version & 255u));-  writer.length_prefixed(repo);-  writer.raw(server_nonce);-  writer.raw(client_nonce);-  writer.raw(binding);-  return std::string(str_of(writer.view()));+std::string auth_message(std::uint16_t version, std::string_view repo, Bytes server_nonce,+                         Bytes client_nonce, Bytes binding) {+    ByteWriter writer(128);+    writer.raw(std::string_view("veins-auth/1"));+    writer.u8(0);+    writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));+    writer.u8(static_cast<std::uint8_t>(version & 255u));+    writer.length_prefixed(repo);+    writer.raw(server_nonce);+    writer.raw(client_nonce);+    writer.raw(binding);+    return std::string(str_of(writer.view())); }  std::string_view role_name(std::uint8_t role) {-  if (role == 2)-    return "write";-  if (role == 1)-    return "read";-  return "anonymous";+    if (role == 2)+        return "write";+    if (role == 1)+        return "read";+    return "anonymous"; }  // ---------------------------------------------------------------------------@@ -530,38 +526,37 @@ // ---------------------------------------------------------------------------  std::optional<Url> parse_url(std::string_view url) {-  constexpr std::string_view file_prefix = "file://";-  constexpr std::string_view ssh_prefix = "ssh://";-  constexpr std::string_view veins_prefix = "veins://";-  if (url.starts_with(file_prefix))-    return Url{-        false, false, {}, 0, std::string(url.substr(file_prefix.size()))};-  if (url.starts_with(ssh_prefix)) {-    std::string_view rest = url.substr(ssh_prefix.size());-    const auto slash = rest.find('/');-    if (slash == std::string_view::npos)-      return std::nullopt;-    const auto authority = parse_authority(rest.substr(0, slash), 22, true);-    return Url{false, true, authority.host, authority.port,-               std::string(rest.substr(slash + 1))};-  }-  if (url.starts_with(veins_prefix)) {-    std::string_view rest = url.substr(veins_prefix.size());-    const auto slash = rest.find('/');-    if (slash == std::string_view::npos)-      return std::nullopt;-    const auto authority = parse_authority(rest.substr(0, slash), 7419, false);-    return Url{true, false, authority.host, authority.port,-               std::string(rest.substr(slash + 1))};-  }-  return std::nullopt;+    constexpr std::string_view file_prefix = "file://";+    constexpr std::string_view ssh_prefix = "ssh://";+    constexpr std::string_view veins_prefix = "veins://";+    if (url.starts_with(file_prefix))+        return Url{false, false, {}, 0, std::string(url.substr(file_prefix.size()))};+    if (url.starts_with(ssh_prefix)) {+        std::string_view rest = url.substr(ssh_prefix.size());+        const auto slash = rest.find('/');+        if (slash == std::string_view::npos)+            return std::nullopt;+        const auto authority = parse_authority(rest.substr(0, slash), 22, true);+        return Url{false, true, authority.host, authority.port,+                   std::string(rest.substr(slash + 1))};+    }+    if (url.starts_with(veins_prefix)) {+        std::string_view rest = url.substr(veins_prefix.size());+        const auto slash = rest.find('/');+        if (slash == std::string_view::npos)+            return std::nullopt;+        const auto authority = parse_authority(rest.substr(0, slash), 7419, false);+        return Url{true, false, authority.host, authority.port,+                   std::string(rest.substr(slash + 1))};+    }+    return std::nullopt; }  std::string url_repo_name(std::string_view url) {-  auto parsed = parse_url(url);-  if (!parsed || !parsed->tls)-    return {};-  return parsed->path;+    auto parsed = parse_url(url);+    if (!parsed || !parsed->tls)+        return {};+    return parsed->path; }  // ---------------------------------------------------------------------------@@ -568,364 +563,352 @@ // Client // --------------------------------------------------------------------------- -void Client::set_error(std::string text) { last_error_ = std::move(text); }+void Client::set_error(std::string text) {+    last_error_ = std::move(text);+} -void Client::set_error_frame(const wire::Frame &frame) {-  const std::uint8_t code = wire::read_error(frame.payload);-  const std::string_view name = wire::error_code_name(code);-  const std::string message = wire::error_message(frame.payload);-  std::string text = "server error: ";-  text += name;-  if (!message.empty()) {-    text += ": ";-    text += message;-  }-  set_error(std::move(text));+void Client::set_error_frame(const wire::Frame& frame) {+    const std::uint8_t code = wire::read_error(frame.payload);+    const std::string_view name = wire::error_code_name(code);+    const std::string message = wire::error_message(frame.payload);+    std::string text = "server error: ";+    text += name;+    if (!message.empty()) {+        text += ": ";+        text += message;+    }+    set_error(std::move(text)); }  std::optional<wire::Frame> Client::request(std::uint8_t kind, Bytes payload) {-  const std::uint32_t rid =-      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);-  if (!wire::write_frame(stream_, kind, rid, payload)) {-    set_error("connection closed while sending request");-    return std::nullopt;-  }-  auto frame = wire::read_frame(stream_);-  if (!frame) {-    set_error("connection closed while waiting for server response");-    return std::nullopt;-  }-  if (frame->kind == wire::ERROR) {-    set_error_frame(*frame);-    return std::nullopt;-  }-  return frame;+    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+    if (!wire::write_frame(stream_, kind, rid, payload)) {+        set_error("connection closed while sending request");+        return std::nullopt;+    }+    auto frame = wire::read_frame(stream_);+    if (!frame) {+        set_error("connection closed while waiting for server response");+        return std::nullopt;+    }+    if (frame->kind == wire::ERROR) {+        set_error_frame(*frame);+        return std::nullopt;+    }+    return frame; } -const std::string &Client::last_connect_error() { return connect_error; }+const std::string& Client::last_connect_error() {+    return connect_error;+} -std::optional<Client> Client::connect(std::string_view url,-                                      std::string_view key_name,-                                      std::string_view repo_name,-                                      std::string_view tls_pin) {-  connect_error.clear();-  auto parsed = parse_url(url);-  if (!parsed) {-    connect_error = "invalid remote URL";-    return std::nullopt;-  }-  std::string binding;-  auto stream = connect_stream(*parsed, tls_pin, binding);-  if (!stream) {-    if (connect_error.empty())-      connect_error = "cannot establish a connection";-    return std::nullopt;-  }+std::optional<Client> Client::connect(std::string_view url, std::string_view key_name,+                                      std::string_view repo_name, std::string_view tls_pin) {+    connect_error.clear();+    auto parsed = parse_url(url);+    if (!parsed) {+        connect_error = "invalid remote URL";+        return std::nullopt;+    }+    std::string binding;+    auto stream = connect_stream(*parsed, tls_pin, binding);+    if (!stream) {+        if (connect_error.empty())+            connect_error = "cannot establish a connection";+        return std::nullopt;+    } -  const auto nonce_bytes = secure_random(32);-  if (nonce_bytes.size() != 32) {-    stream->close();-    connect_error = "cannot generate a secure nonce";-    return std::nullopt;-  }-  const std::string client_nonce(-      reinterpret_cast<const char *>(nonce_bytes.data()), nonce_bytes.size());+    const auto nonce_bytes = secure_random(32);+    if (nonce_bytes.size() != 32) {+        stream->close();+        connect_error = "cannot generate a secure nonce";+        return std::nullopt;+    }+    const std::string client_nonce(reinterpret_cast<const char*>(nonce_bytes.data()),+                                   nonce_bytes.size()); -  Hello hello;-  hello.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};-  hello.repo = std::string(repo_name);-  hello.client_nonce = client_nonce;-  const auto hello_body = encode_hello(hello);-  if (!wire::write_frame(*stream, wire::HELLO, 1, hello_body)) {-    stream->close();-    connect_error = "connection closed during the protocol handshake";-    return std::nullopt;-  }-  auto hello_frame = wire::read_frame(*stream);-  if (!hello_frame || hello_frame->kind != wire::HELLO_OK) {-    stream->close();-    connect_error = "server rejected the protocol handshake";-    return std::nullopt;-  }-  auto hello_ok = decode_hello_ok(hello_frame->payload);-  if (!hello_ok) {-    stream->close();-    connect_error = "server sent an invalid protocol handshake";-    return std::nullopt;-  }+    Hello hello;+    hello.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};+    hello.repo = std::string(repo_name);+    hello.client_nonce = client_nonce;+    const auto hello_body = encode_hello(hello);+    if (!wire::write_frame(*stream, wire::HELLO, 1, hello_body)) {+        stream->close();+        connect_error = "connection closed during the protocol handshake";+        return std::nullopt;+    }+    auto hello_frame = wire::read_frame(*stream);+    if (!hello_frame || hello_frame->kind != wire::HELLO_OK) {+        stream->close();+        connect_error = "server rejected the protocol handshake";+        return std::nullopt;+    }+    auto hello_ok = decode_hello_ok(hello_frame->payload);+    if (!hello_ok) {+        stream->close();+        connect_error = "server sent an invalid protocol handshake";+        return std::nullopt;+    } -  Client client;-  client.stream_ = std::move(*stream);-  client.binding_ = std::move(binding);-  client.version_ = hello_ok->version;+    Client client;+    client.stream_ = std::move(*stream);+    client.binding_ = std::move(binding);+    client.version_ = hello_ok->version; -  std::string selected_key(key_name);-  if (selected_key.empty() && hello_ok->auth_required != 0)-    selected_key = "default";+    std::string selected_key(key_name);+    if (selected_key.empty() && hello_ok->auth_required != 0)+        selected_key = "default"; -  if (!selected_key.empty()) {-    auto key = auth::load_key(selected_key);-    if (key) {-      const std::string message = auth_message(-          hello_ok->version, repo_name,-          Bytes(reinterpret_cast<const std::uint8_t *>(-                    hello_ok->server_nonce.data()),-                hello_ok->server_nonce.size()),-          Bytes(reinterpret_cast<const std::uint8_t *>(client_nonce.data()),-                client_nonce.size()),-          Bytes(reinterpret_cast<const std::uint8_t *>(client.binding_.data()),-                client.binding_.size()));-      auto signature = ed25519_sign(-          Bytes(key->seed.data(), key->seed.size()),-          Bytes(reinterpret_cast<const std::uint8_t *>(message.data()),-                message.size()));-      if (signature) {-        Auth auth;-        auth.public_key.assign(-            reinterpret_cast<const char *>(key->public_key.data()),-            key->public_key.size());-        auth.signature.assign(reinterpret_cast<const char *>(signature->data()),-                              signature->size());-        const auto body = encode_auth(auth);-        if (wire::write_frame(client.stream_, wire::AUTH, 2, body)) {-          auto reply = wire::read_frame(client.stream_);-          if (reply && reply->kind == wire::AUTH_OK) {-            auto ok = decode_auth_ok(reply->payload);-            if (ok) {-              client.role_ = ok->role;-              client.authed_ = true;-              client.fingerprint_ = std::move(ok->fingerprint);+    if (!selected_key.empty()) {+        auto key = auth::load_key(selected_key);+        if (key) {+            const std::string message = auth_message(+                hello_ok->version, repo_name,+                Bytes(reinterpret_cast<const std::uint8_t*>(hello_ok->server_nonce.data()),+                      hello_ok->server_nonce.size()),+                Bytes(reinterpret_cast<const std::uint8_t*>(client_nonce.data()),+                      client_nonce.size()),+                Bytes(reinterpret_cast<const std::uint8_t*>(client.binding_.data()),+                      client.binding_.size()));+            auto signature = ed25519_sign(+                Bytes(key->seed.data(), key->seed.size()),+                Bytes(reinterpret_cast<const std::uint8_t*>(message.data()), message.size()));+            if (signature) {+                Auth auth;+                auth.public_key.assign(reinterpret_cast<const char*>(key->public_key.data()),+                                       key->public_key.size());+                auth.signature.assign(reinterpret_cast<const char*>(signature->data()),+                                      signature->size());+                const auto body = encode_auth(auth);+                if (wire::write_frame(client.stream_, wire::AUTH, 2, body)) {+                    auto reply = wire::read_frame(client.stream_);+                    if (reply && reply->kind == wire::AUTH_OK) {+                        auto ok = decode_auth_ok(reply->payload);+                        if (ok) {+                            client.role_ = ok->role;+                            client.authed_ = true;+                            client.fingerprint_ = std::move(ok->fingerprint);+                        }+                    }+                }             }-          }         }-      }     }-  } -  if (hello_ok->auth_required != 0 && !client.authed_) {-    connect_error = selected_key.empty()-                        ? "authentication required but no key is configured"-                        : "authentication failed: the key is missing or not "-                          "authorized";-    client.stream_.close();-    return std::nullopt;-  }-  connect_error.clear();-  return client;+    if (hello_ok->auth_required != 0 && !client.authed_) {+        connect_error = selected_key.empty() ? "authentication required but no key is configured"+                                             : "authentication failed: the key is missing or not "+                                               "authorized";+        client.stream_.close();+        return std::nullopt;+    }+    connect_error.clear();+    return client; } -bool Client::list_refs(std::vector<RefInfo> &refs) {-  auto frame = request(wire::LIST_REFS, Bytes{});-  if (!frame)-    return false;-  if (frame->kind != wire::REFS) {-    set_error("unexpected response to ref listing (message kind " +-              std::to_string(frame->kind) + ")");-    return false;-  }-  auto decoded = decode_refs(frame->payload);-  if (!decoded)-    return false;-  refs = std::move(*decoded);-  return true;+bool Client::list_refs(std::vector<RefInfo>& refs) {+    auto frame = request(wire::LIST_REFS, Bytes{});+    if (!frame)+        return false;+    if (frame->kind != wire::REFS) {+        set_error("unexpected response to ref listing (message kind " ++                  std::to_string(frame->kind) + ")");+        return false;+    }+    auto decoded = decode_refs(frame->payload);+    if (!decoded)+        return false;+    refs = std::move(*decoded);+    return true; } -bool Client::negotiate(const std::vector<Id> &wants,-                       const std::vector<Id> &haves) {-  const auto body = encode_negotiate(wants, haves);-  auto frame = request(wire::NEGOTIATE, body);-  if (!frame)-    return false;-  if (frame->kind != wire::NEGOTIATE_OK) {-    set_error("unexpected response to negotiation (message kind " +-              std::to_string(frame->kind) + ")");-    return false;-  }-  return true;+bool Client::negotiate(const std::vector<Id>& wants, const std::vector<Id>& haves) {+    const auto body = encode_negotiate(wants, haves);+    auto frame = request(wire::NEGOTIATE, body);+    if (!frame)+        return false;+    if (frame->kind != wire::NEGOTIATE_OK) {+        set_error("unexpected response to negotiation (message kind " ++                  std::to_string(frame->kind) + ")");+        return false;+    }+    return true; } -bool Client::receive_stream(const fs::path &repo) {-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  Writer writer;-  bool good = true;+bool Client::receive_stream(const fs::path& repo) {+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    Writer writer;+    bool good = true; -  for (;;) {-    auto frame = wire::read_frame(stream_);-    if (!frame) {-      set_error("connection closed while receiving data");-      return false;+    for (;;) {+        auto frame = wire::read_frame(stream_);+        if (!frame) {+            set_error("connection closed while receiving data");+            return false;+        }+        if (frame->kind == wire::END) {+            std::array<std::uint8_t, 32> digest{};+            blake3_hasher_finalize(&hasher, digest.data(), digest.size());+            if (frame->payload.size() != digest.size() ||+                std::memcmp(frame->payload.data(), digest.data(), digest.size()) != 0) {+                set_error("server sent a corrupt transfer checksum");+                return false;+            }+            break;+        }+        if (frame->kind == wire::ERROR) {+            set_error_frame(*frame);+            return false;+        }+        if (frame->kind != wire::RECORDS) {+            set_error("unexpected message while receiving data (message kind " ++                      std::to_string(frame->kind) + ")");+            return false;+        }+        blake3_hasher_update(&hasher, frame->payload.data(), frame->payload.size());+        auto record = wire::parse_record(bytes_of(frame->payload));+        if (!record) {+            good = false;+        } else {+            const Id computed = object_id(record->kind, bytes_of(record->body));+            if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {+                good = false;+            } else {+                writer.add_known(record->kind, record->id, std::move(record->body));+            }+        }+        if (!good)+            return false;     }-    if (frame->kind == wire::END) {-      std::array<std::uint8_t, 32> digest{};-      blake3_hasher_finalize(&hasher, digest.data(), digest.size());-      if (frame->payload.size() != digest.size() ||-          std::memcmp(frame->payload.data(), digest.data(), digest.size()) !=-              0) {-        set_error("server sent a corrupt transfer checksum");++    if (writer.finish(repo) != 0) {+        set_error("cannot write incoming objects to the store");         return false;-      }-      break;-    }-    if (frame->kind == wire::ERROR) {-      set_error_frame(*frame);-      return false;-    }-    if (frame->kind != wire::RECORDS) {-      set_error("unexpected message while receiving data (message kind " +-                std::to_string(frame->kind) + ")");-      return false;-    }-    blake3_hasher_update(&hasher, frame->payload.data(), frame->payload.size());-    auto record = wire::parse_record(bytes_of(frame->payload));-    if (!record) {-      good = false;-    } else {-      const Id computed = object_id(record->kind, bytes_of(record->body));-      if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {-        good = false;-      } else {-        writer.add_known(record->kind, record->id, std::move(record->body));-      }     }-    if (!good)-      return false;-  }--  if (writer.finish(repo) != 0) {-    set_error("cannot write incoming objects to the store");-    return false;-  }-  return true;+    return true; } -bool Client::fetch_skeleton(const fs::path &repo,-                            const std::vector<Id> &wants) {-  const auto body = encode_ids(wants);-  const std::uint32_t rid =-      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);-  if (!wire::write_frame(stream_, wire::FETCH_SKELETON, rid, body)) {-    set_error("connection closed while requesting objects");-    return false;-  }-  return receive_stream(repo);+bool Client::fetch_skeleton(const fs::path& repo, const std::vector<Id>& wants) {+    const auto body = encode_ids(wants);+    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+    if (!wire::write_frame(stream_, wire::FETCH_SKELETON, rid, body)) {+        set_error("connection closed while requesting objects");+        return false;+    }+    return receive_stream(repo); } -bool Client::get_chunks(const fs::path &repo, const std::vector<Id> &ids) {-  if (ids.empty())-    return true;-  const auto body = encode_ids(ids);-  const std::uint32_t rid =-      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);-  if (!wire::write_frame(stream_, wire::GET_CHUNKS, rid, body)) {-    set_error("connection closed while requesting chunks");-    return false;-  }-  return receive_stream(repo);+bool Client::get_chunks(const fs::path& repo, const std::vector<Id>& ids) {+    if (ids.empty())+        return true;+    const auto body = encode_ids(ids);+    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+    if (!wire::write_frame(stream_, wire::GET_CHUNKS, rid, body)) {+        set_error("connection closed while requesting chunks");+        return false;+    }+    return receive_stream(repo); } -bool Client::have_query(const std::vector<Id> &ids,-                        std::vector<std::uint8_t> &bits) {-  const auto body = encode_ids(ids);-  auto frame = request(wire::HAVE_QUERY, body);-  if (!frame)-    return false;-  if (frame->kind != wire::HAVE_BITMAP)-    return false;-  auto decoded = decode_bitmap(frame->payload);-  if (!decoded)-    return false;-  bits = std::move(*decoded);-  return true;+bool Client::have_query(const std::vector<Id>& ids, std::vector<std::uint8_t>& bits) {+    const auto body = encode_ids(ids);+    auto frame = request(wire::HAVE_QUERY, body);+    if (!frame)+        return false;+    if (frame->kind != wire::HAVE_BITMAP)+        return false;+    auto decoded = decode_bitmap(frame->payload);+    if (!decoded)+        return false;+    bits = std::move(*decoded);+    return true; } -bool Client::push_objects(const fs::path &repo, const std::vector<Id> &ids) {-  const std::uint32_t rid =-      static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);-  if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {-    set_error("connection closed while starting push");-    return false;-  }-  Store store = Store::open_all(repo);-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  bool good = true;-  for (const auto &id : ids) {-    const auto loc = store.find(id);-    if (!loc) {-      set_error("local object is missing from the store: " + id_text(id));-      good = false;-      break;+bool Client::push_objects(const fs::path& repo, const std::vector<Id>& ids) {+    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);+    if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {+        set_error("connection closed while starting push");+        return false;     }-    auto body = store.read_body(id, loc->kind);-    if (!body) {-      set_error("cannot read local object from the store: " + id_text(id));-      good = false;-      break;+    Store store = Store::open_all(repo);+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    bool good = true;+    for (const auto& id : ids) {+        const auto loc = store.find(id);+        if (!loc) {+            set_error("local object is missing from the store: " + id_text(id));+            good = false;+            break;+        }+        auto body = store.read_body(id, loc->kind);+        if (!body) {+            set_error("cannot read local object from the store: " + id_text(id));+            good = false;+            break;+        }+        const auto record = wire::make_record(id, loc->kind, bytes_of(*body));+        blake3_hasher_update(&hasher, record.data(), record.size());+        if (!wire::write_frame(stream_, wire::RECORDS, rid, Bytes(record.data(), record.size()))) {+            set_error("connection closed while sending object: " + id_text(id));+            good = false;+            break;+        }     }-    const auto record = wire::make_record(id, loc->kind, bytes_of(*body));-    blake3_hasher_update(&hasher, record.data(), record.size());-    if (!wire::write_frame(stream_, wire::RECORDS, rid,-                           Bytes(record.data(), record.size()))) {-      set_error("connection closed while sending object: " + id_text(id));-      good = false;-      break;+    std::array<std::uint8_t, 32> digest{};+    blake3_hasher_finalize(&hasher, digest.data(), digest.size());+    if (!good)+        return false;+    if (!wire::write_frame(stream_, wire::END, rid, Bytes(digest.data(), digest.size()))) {+        set_error("connection closed while finishing push");+        return false;     }-  }-  std::array<std::uint8_t, 32> digest{};-  blake3_hasher_finalize(&hasher, digest.data(), digest.size());-  if (!good)-    return false;-  if (!wire::write_frame(stream_, wire::END, rid,-                         Bytes(digest.data(), digest.size()))) {-    set_error("connection closed while finishing push");-    return false;-  }-  auto ack = wire::read_frame(stream_);-  if (!ack) {-    set_error("server closed the connection before acknowledging the push");-    return false;-  }-  if (ack->kind == wire::END)-    return true;-  if (ack->kind == wire::ERROR) {-    set_error_frame(*ack);+    auto ack = wire::read_frame(stream_);+    if (!ack) {+        set_error("server closed the connection before acknowledging the push");+        return false;+    }+    if (ack->kind == wire::END)+        return true;+    if (ack->kind == wire::ERROR) {+        set_error_frame(*ack);+        return false;+    }+    set_error("unexpected response to object push (message kind " + std::to_string(ack->kind) ++              ")");     return false;-  }-  set_error("unexpected response to object push (message kind " +-            std::to_string(ack->kind) + ")");-  return false; } -bool Client::update_refs(const std::vector<UpdateRef> &updates) {-  const auto body = encode_update_refs(updates);-  auto frame = request(wire::UPDATE_REFS, body);-  if (!frame)-    return false;-  if (frame->kind != wire::UPDATE_REFS_OK) {-    set_error("unexpected response to ref update (message kind " +-              std::to_string(frame->kind) + ")");-    return false;-  }-  return true;+bool Client::update_refs(const std::vector<UpdateRef>& updates) {+    const auto body = encode_update_refs(updates);+    auto frame = request(wire::UPDATE_REFS, body);+    if (!frame)+        return false;+    if (frame->kind != wire::UPDATE_REFS_OK) {+        set_error("unexpected response to ref update (message kind " + std::to_string(frame->kind) ++                  ")");+        return false;+    }+    return true; } -bool Client::whoami(std::uint8_t &role, std::string &fingerprint) {-  auto frame = request(wire::WHOAMI, Bytes{});-  if (!frame)-    return false;-  if (frame->kind != wire::WHOAMI_OK)-    return false;-  Reader reader(frame->payload);-  const auto role_value = reader.u8();-  if (!role_value)-    return false;-  const auto fp = reader.bytes(64);-  if (!fp)-    return false;-  role = *role_value;-  fingerprint = bytes_to_string(*fp);-  return true;+bool Client::whoami(std::uint8_t& role, std::string& fingerprint) {+    auto frame = request(wire::WHOAMI, Bytes{});+    if (!frame)+        return false;+    if (frame->kind != wire::WHOAMI_OK)+        return false;+    Reader reader(frame->payload);+    const auto role_value = reader.u8();+    if (!role_value)+        return false;+    const auto fp = reader.bytes(64);+    if (!fp)+        return false;+    role = *role_value;+    fingerprint = bytes_to_string(*fp);+    return true; }  } // namespace vn::proto--- a/xveins/src/protocol.h+++ b/xveins/src/protocol.h@@ -15,85 +15,83 @@ constexpr std::uint16_t PROTOCOL_VERSION = 1;  struct Hello {-  std::uint16_t min_version = PROTOCOL_VERSION;-  std::uint16_t max_version = PROTOCOL_VERSION;-  std::vector<std::string> capabilities;-  std::string repo;-  std::string client_nonce;+    std::uint16_t min_version = PROTOCOL_VERSION;+    std::uint16_t max_version = PROTOCOL_VERSION;+    std::vector<std::string> capabilities;+    std::string repo;+    std::string client_nonce; };  struct HelloOk {-  std::uint16_t version = 0;-  std::vector<std::string> capabilities;-  std::string server_nonce;-  std::uint8_t auth_required = 0;+    std::uint16_t version = 0;+    std::vector<std::string> capabilities;+    std::string server_nonce;+    std::uint8_t auth_required = 0; };  struct Auth {-  std::string public_key;-  std::string signature;+    std::string public_key;+    std::string signature; };  struct AuthOk {-  std::uint8_t role = 0;-  std::string fingerprint;+    std::uint8_t role = 0;+    std::string fingerprint; };  struct RefInfo {-  std::string name;-  Id target{};-  std::string change_id;-  std::uint8_t kind = 0; // 0 bookmark, 1 tag+    std::string name;+    Id target{};+    std::string change_id;+    std::uint8_t kind = 0; // 0 bookmark, 1 tag };  struct Negotiate {-  std::vector<Id> wants;-  std::vector<Id> haves;+    std::vector<Id> wants;+    std::vector<Id> haves; };  struct UpdateRef {-  std::string name;-  std::optional<Id> expected;-  std::optional<Id> target;+    std::string name;+    std::optional<Id> expected;+    std::optional<Id> target; }; -std::vector<std::uint8_t> encode_hello(const Hello &hello);+std::vector<std::uint8_t> encode_hello(const Hello& hello); std::optional<Hello> decode_hello(Bytes data); -std::vector<std::uint8_t> encode_hello_ok(const HelloOk &hello);+std::vector<std::uint8_t> encode_hello_ok(const HelloOk& hello); std::optional<HelloOk> decode_hello_ok(Bytes data); -std::vector<std::uint8_t> encode_auth(const Auth &auth);+std::vector<std::uint8_t> encode_auth(const Auth& auth); std::optional<Auth> decode_auth(Bytes data); -std::vector<std::uint8_t> encode_auth_ok(const AuthOk &auth);+std::vector<std::uint8_t> encode_auth_ok(const AuthOk& auth); std::optional<AuthOk> decode_auth_ok(Bytes data); -std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo> &refs);+std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo>& refs); std::optional<std::vector<RefInfo>> decode_refs(Bytes data); -std::vector<std::uint8_t> encode_ids(const std::vector<Id> &ids);+std::vector<std::uint8_t> encode_ids(const std::vector<Id>& ids); std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max); -std::vector<std::uint8_t> encode_negotiate(const std::vector<Id> &wants,-                                           const std::vector<Id> &haves);+std::vector<std::uint8_t> encode_negotiate(const std::vector<Id>& wants,+                                           const std::vector<Id>& haves); std::optional<Negotiate> decode_negotiate(Bytes data); -std::vector<std::uint8_t>-encode_negotiate_ok(const std::vector<std::uint8_t> &known,-                    std::uint8_t enough);+std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t>& known,+                                              std::uint8_t enough); std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data); -std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t> &bits);+std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t>& bits); std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data); -std::vector<std::uint8_t>-encode_update_refs(const std::vector<UpdateRef> &updates);+std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef>& updates); std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data);  // The bytes signed in AUTH.-std::string auth_message(std::uint16_t version, std::string_view repo,-                         Bytes server_nonce, Bytes client_nonce, Bytes binding);+std::string auth_message(std::uint16_t version, std::string_view repo, Bytes server_nonce,+                         Bytes client_nonce, Bytes binding); std::string_view role_name(std::uint8_t role);  // ---------------------------------------------------------------------------@@ -101,11 +99,11 @@ // ---------------------------------------------------------------------------  struct Url {-  bool tls = false;-  bool ssh = false;-  std::string host;-  int port = 0;-  std::string path;+    bool tls = false;+    bool ssh = false;+    std::string host;+    int port = 0;+    std::string path; };  std::optional<Url> parse_url(std::string_view url);@@ -117,49 +115,57 @@  class Client { public:-  Client() = default;-  ~Client() = default;-  Client(Client &&) noexcept = default;-  Client &operator=(Client &&) noexcept = default;-  Client(const Client &) = delete;-  Client &operator=(const Client &) = delete;+    Client() = default;+    ~Client() = default;+    Client(Client&&) noexcept = default;+    Client& operator=(Client&&) noexcept = default;+    Client(const Client&) = delete;+    Client& operator=(const Client&) = delete; -  // Connect and authenticate. An empty key name means anonymous unless the-  // server requires authentication, in which case "default" is used.-  static std::optional<Client> connect(std::string_view url,-                                       std::string_view key_name,-                                       std::string_view repo_name,-                                       std::string_view tls_pin = {});-  static const std::string &last_connect_error();+    // Connect and authenticate. An empty key name means anonymous unless the+    // server requires authentication, in which case "default" is used.+    static std::optional<Client> connect(std::string_view url, std::string_view key_name,+                                         std::string_view repo_name, std::string_view tls_pin = {});+    static const std::string& last_connect_error(); -  bool list_refs(std::vector<RefInfo> &refs);-  bool negotiate(const std::vector<Id> &wants, const std::vector<Id> &haves);-  bool fetch_skeleton(const fs::path &repo, const std::vector<Id> &wants);-  bool get_chunks(const fs::path &repo, const std::vector<Id> &ids);-  bool have_query(const std::vector<Id> &ids, std::vector<std::uint8_t> &bits);-  bool push_objects(const fs::path &repo, const std::vector<Id> &ids);-  bool update_refs(const std::vector<UpdateRef> &updates);-  bool whoami(std::uint8_t &role, std::string &fingerprint);+    bool list_refs(std::vector<RefInfo>& refs);+    bool negotiate(const std::vector<Id>& wants, const std::vector<Id>& haves);+    bool fetch_skeleton(const fs::path& repo, const std::vector<Id>& wants);+    bool get_chunks(const fs::path& repo, const std::vector<Id>& ids);+    bool have_query(const std::vector<Id>& ids, std::vector<std::uint8_t>& bits);+    bool push_objects(const fs::path& repo, const std::vector<Id>& ids);+    bool update_refs(const std::vector<UpdateRef>& updates);+    bool whoami(std::uint8_t& role, std::string& fingerprint); -  [[nodiscard]] const std::string &error() const { return last_error_; }-  [[nodiscard]] std::uint8_t role() const { return role_; }-  [[nodiscard]] bool authenticated() const { return authed_; }-  [[nodiscard]] const std::string &fingerprint() const { return fingerprint_; }-  [[nodiscard]] bool has_connection() const { return stream_.valid(); }+    [[nodiscard]] const std::string& error() const {+        return last_error_;+    }+    [[nodiscard]] std::uint8_t role() const {+        return role_;+    }+    [[nodiscard]] bool authenticated() const {+        return authed_;+    }+    [[nodiscard]] const std::string& fingerprint() const {+        return fingerprint_;+    }+    [[nodiscard]] bool has_connection() const {+        return stream_.valid();+    }  private:-  std::optional<wire::Frame> request(std::uint8_t kind, Bytes payload);-  bool receive_stream(const fs::path &repo);-  void set_error(std::string text);-  void set_error_frame(const wire::Frame &frame);+    std::optional<wire::Frame> request(std::uint8_t kind, Bytes payload);+    bool receive_stream(const fs::path& repo);+    void set_error(std::string text);+    void set_error_frame(const wire::Frame& frame); -  net::Stream stream_;-  std::string binding_;-  std::uint16_t version_ = PROTOCOL_VERSION;-  std::uint8_t role_ = 0;-  bool authed_ = false;-  std::string fingerprint_;-  std::string last_error_;+    net::Stream stream_;+    std::string binding_;+    std::uint16_t version_ = PROTOCOL_VERSION;+    std::uint8_t role_ = 0;+    bool authed_ = false;+    std::string fingerprint_;+    std::string last_error_; };  } // namespace vn::proto--- a/xveins/src/remove.cpp+++ b/xveins/src/remove.cpp@@ -14,407 +14,396 @@ namespace {  bool rm_is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';+    return !arg.empty() && arg.front() == '-'; }  bool starts_with_child(std::string_view path, std::string_view parent) {-  return path.size() > parent.size() &&-         path.compare(0, parent.size(), parent) == 0 &&-         path[parent.size()] == '/';+    return path.size() > parent.size() && path.compare(0, parent.size(), parent) == 0 &&+           path[parent.size()] == '/'; }  bool literal_matches(std::string_view operand, std::string_view path) {-  return path == operand || starts_with_child(path, operand);+    return path == operand || starts_with_child(path, operand); }  bool glob_matches(std::string_view operand, std::string_view path) {-  if (glob_match(operand, path))-    return true;-  for (std::size_t i = 0; i < path.size(); ++i) {-    if (path[i] == '/' && glob_match(operand, path.substr(0, i)))-      return true;-  }-  return false;+    if (glob_match(operand, path))+        return true;+    for (std::size_t i = 0; i < path.size(); ++i) {+        if (path[i] == '/' && glob_match(operand, path.substr(0, i)))+            return true;+    }+    return false; }  bool operand_matches(std::string_view operand, std::string_view path) {-  if (pathspec_has_glob(operand))-    return glob_matches(operand, path);-  return literal_matches(operand, path);+    if (pathspec_has_glob(operand))+        return glob_matches(operand, path);+    return literal_matches(operand, path); } -bool subtree_affected(std::string_view prefix,-                      const std::vector<std::string> &removes) {-  if (prefix.empty())-    return !removes.empty();-  for (const auto &r : removes) {-    if (prefix == r || starts_with_child(r, prefix) ||-        starts_with_child(prefix, r))-      return true;-  }-  return false;+bool subtree_affected(std::string_view prefix, const std::vector<std::string>& removes) {+    if (prefix.empty())+        return !removes.empty();+    for (const auto& r : removes) {+        if (prefix == r || starts_with_child(r, prefix) || starts_with_child(prefix, r))+            return true;+    }+    return false; } -bool path_removed(std::string_view path,-                  const std::vector<std::string> &removes) {-  for (const auto &r : removes) {-    if (path == r || starts_with_child(path, r))-      return true;-  }-  return false;+bool path_removed(std::string_view path, const std::vector<std::string>& removes) {+    for (const auto& r : removes) {+        if (path == r || starts_with_child(path, r))+            return true;+    }+    return false; }  std::string join_path(std::string_view prefix, std::string_view name) {-  if (prefix.empty())-    return std::string(name);-  std::string out(prefix);-  out.push_back('/');-  out.append(name);-  return out;+    if (prefix.empty())+        return std::string(name);+    std::string out(prefix);+    out.push_back('/');+    out.append(name);+    return out; } -Id empty_tree_id(Txn &tx) {-  auto body = encode_tree({});-  if (!body)-    return Id{};-  return tx.add_object(TYPE_TREE, *body);+Id empty_tree_id(Txn& tx) {+    auto body = encode_tree({});+    if (!body)+        return Id{};+    return tx.add_object(TYPE_TREE, *body); } -std::optional<Id> filter_tree(Txn &tx, Store &store, const Id &tree_id,-                              std::string_view prefix,-                              const std::vector<std::string> &removes,-                              std::size_t depth) {-  if (depth > 4096)-    return tree_id;-  if (!subtree_affected(prefix, removes))-    return tree_id;-  auto body = store.read_body(tree_id, TYPE_TREE);-  if (!body)-    return tree_id;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return tree_id;+std::optional<Id> filter_tree(Txn& tx, Store& store, const Id& tree_id, std::string_view prefix,+                              const std::vector<std::string>& removes, std::size_t depth) {+    if (depth > 4096)+        return tree_id;+    if (!subtree_affected(prefix, removes))+        return tree_id;+    auto body = store.read_body(tree_id, TYPE_TREE);+    if (!body)+        return tree_id;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return tree_id; -  std::vector<TreeEntry> entries;-  entries.reserve(tree->entries.size());-  for (const auto &entry : tree->entries) {-    const std::string full = join_path(prefix, entry.name);-    if (path_removed(full, removes))-      continue;-    if (entry.kind == KIND_SUBTREE && subtree_affected(full, removes)) {-      auto child =-          filter_tree(tx, store, entry.target, full, removes, depth + 1);-      if (child)-        entries.push_back(TreeEntry{entry.name, entry.kind, *child});-    } else {-      entries.push_back(entry);+    std::vector<TreeEntry> entries;+    entries.reserve(tree->entries.size());+    for (const auto& entry : tree->entries) {+        const std::string full = join_path(prefix, entry.name);+        if (path_removed(full, removes))+            continue;+        if (entry.kind == KIND_SUBTREE && subtree_affected(full, removes)) {+            auto child = filter_tree(tx, store, entry.target, full, removes, depth + 1);+            if (child)+                entries.push_back(TreeEntry{entry.name, entry.kind, *child});+        } else {+            entries.push_back(entry);+        }     }-  }-  if (entries.empty())-    return std::nullopt;-  auto encoded = encode_tree(entries);-  if (!encoded)-    return std::nullopt;-  return tx.add_object(TYPE_TREE, *encoded);+    if (entries.empty())+        return std::nullopt;+    auto encoded = encode_tree(entries);+    if (!encoded)+        return std::nullopt;+    return tx.add_object(TYPE_TREE, *encoded); }  std::optional<std::string> parent_of(std::string_view path) {-  const auto slash = path.rfind('/');-  if (slash == std::string_view::npos)-    return std::nullopt;-  return std::string(path.substr(0, slash));+    const auto slash = path.rfind('/');+    if (slash == std::string_view::npos)+        return std::nullopt;+    return std::string(path.substr(0, slash)); } -bool delete_one(const fs::path &root, std::string_view rel) {-  std::error_code ec;-  const fs::path full = root / path_from_bytes(rel);-  const bool removed = fs::remove(full, ec);-  return removed && !ec;+bool delete_one(const fs::path& root, std::string_view rel) {+    std::error_code ec;+    const fs::path full = root / path_from_bytes(rel);+    const bool removed = fs::remove(full, ec);+    return removed && !ec; } -void prune_empty_parents(const fs::path &root, std::string_view rel) {-  std::string current(rel);-  for (;;) {-    const auto slash = current.rfind('/');-    if (slash == std::string::npos)-      break;-    current.resize(slash);-    std::error_code ec;-    const fs::path dir = root / path_from_bytes(current);-    if (!fs::is_directory(dir, ec))-      break;-    if (!fs::remove(dir, ec) || ec)-      break;-  }+void prune_empty_parents(const fs::path& root, std::string_view rel) {+    std::string current(rel);+    for (;;) {+        const auto slash = current.rfind('/');+        if (slash == std::string::npos)+            break;+        current.resize(slash);+        std::error_code ec;+        const fs::path dir = root / path_from_bytes(current);+        if (!fs::is_directory(dir, ec))+            break;+        if (!fs::remove(dir, ec) || ec)+            break;+    } } -int delete_paths(const fs::path &root,-                 const std::vector<std::string> &removes) {-  std::size_t failed = 0;-  for (const auto &rel : removes) {-    if (!delete_one(root, rel))-      ++failed;-    else-      prune_empty_parents(root, rel);-  }-  if (failed > 0) {-    warning_prefix();-    std::cout << "could not delete " << failed << " path(s) from disk\n";-    return 1;-  }-  return 0;+int delete_paths(const fs::path& root, const std::vector<std::string>& removes) {+    std::size_t failed = 0;+    for (const auto& rel : removes) {+        if (!delete_one(root, rel))+            ++failed;+        else+            prune_empty_parents(root, rel);+    }+    if (failed > 0) {+        warning_prefix();+        std::cout << "could not delete " << failed << " path(s) from disk\n";+        return 1;+    }+    return 0; } -int run_removal(const fs::path &root, const std::vector<std::string> &operands,-                bool delete_mode) {-  Store store = Store::open_all(root);-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto wc = working_copy_id(tx->view());-  if (!wc) {-    error_prefix();-    std::cout << "no working-copy commit\n";-    return 1;-  }-  auto loaded = load_commit(store, *wc);-  if (!loaded) {-    error_prefix();-    std::cout << "cannot read working-copy commit\n";-    return 1;-  }+int run_removal(const fs::path& root, const std::vector<std::string>& operands, bool delete_mode) {+    Store store = Store::open_all(root);+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto wc = working_copy_id(tx->view());+    if (!wc) {+        error_prefix();+        std::cout << "no working-copy commit\n";+        return 1;+    }+    auto loaded = load_commit(store, *wc);+    if (!loaded) {+        error_prefix();+        std::cout << "cannot read working-copy commit\n";+        return 1;+    } -  std::vector<bool> matched(operands.size(), false);-  std::vector<std::string> removes;-  std::set<std::string> seen;-  for (const auto &entry : flatten_tree(store, loaded->commit.root_tree)) {-    for (std::size_t i = 0; i < operands.size(); ++i) {-      if (operand_matches(operands[i], entry.path)) {-        matched[i] = true;-        if (seen.insert(entry.path).second)-          removes.push_back(entry.path);-      }+    std::vector<bool> matched(operands.size(), false);+    std::vector<std::string> removes;+    std::set<std::string> seen;+    for (const auto& entry : flatten_tree(store, loaded->commit.root_tree)) {+        for (std::size_t i = 0; i < operands.size(); ++i) {+            if (operand_matches(operands[i], entry.path)) {+                matched[i] = true;+                if (seen.insert(entry.path).second)+                    removes.push_back(entry.path);+            }+        }     }-  } -  bool unmatched = false;-  for (std::size_t i = 0; i < operands.size(); ++i) {-    if (!matched[i]) {-      error_prefix();-      std::cout << "path is not tracked: " << operands[i] << "\n";-      unmatched = true;+    bool unmatched = false;+    for (std::size_t i = 0; i < operands.size(); ++i) {+        if (!matched[i]) {+            error_prefix();+            std::cout << "path is not tracked: " << operands[i] << "\n";+            unmatched = true;+        }     }-  }-  if (unmatched)-    return 1;+    if (unmatched)+        return 1; -  if (!delete_mode) {-    for (const auto &rel : removes) {-      if (!ignore_path_ignored(root, rel)) {-        warning_prefix();-        std::cout-            << rel-            << " is not ignored and will be re-added on the next snapshot\n";-      }+    if (!delete_mode) {+        for (const auto& rel : removes) {+            if (!ignore_path_ignored(root, rel)) {+                warning_prefix();+                std::cout << rel << " is not ignored and will be re-added on the next snapshot\n";+            }+        }     }-  } -  auto new_root =-      filter_tree(*tx, store, loaded->commit.root_tree, "", removes, 0);-  Id root_id{};-  if (new_root)-    root_id = *new_root;-  else-    root_id = empty_tree_id(*tx);-  if (std::memcmp(root_id.data(), loaded->commit.root_tree.data(), ID_LEN) ==-      0) {-    error_prefix();-    std::cout << "no tracked paths to remove\n";-    return 1;-  }+    auto new_root = filter_tree(*tx, store, loaded->commit.root_tree, "", removes, 0);+    Id root_id{};+    if (new_root)+        root_id = *new_root;+    else+        root_id = empty_tree_id(*tx);+    if (std::memcmp(root_id.data(), loaded->commit.root_tree.data(), ID_LEN) == 0) {+        error_prefix();+        std::cout << "no tracked paths to remove\n";+        return 1;+    } -  const Sig sig = identity_signature(root);-  Commit commit = loaded->commit;-  commit.root_tree = root_id;-  commit.committer = sig;-  commit.renames_state = RENAMES_RECORDED;-  commit.renames.clear();-  const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit));+    const Sig sig = identity_signature(root);+    Commit commit = loaded->commit;+    commit.root_tree = root_id;+    commit.committer = sig;+    commit.renames_state = RENAMES_RECORDED;+    commit.renames.clear();+    const Id new_id = tx->add_object(TYPE_COMMIT, encode_commit(commit)); -  remove_head(tx->view(), *wc);-  move_bookmarks(tx->view(), *wc, new_id);-  set_workspace(tx->view(), new_id);-  rebuild_heads(tx->view());+    remove_head(tx->view(), *wc);+    move_bookmarks(tx->view(), *wc, new_id);+    set_workspace(tx->view(), new_id);+    rebuild_heads(tx->view()); -  int status = 0;-  const auto finished = tx->finish("rm");-  if (!finished)-    status = 1;-  if (status == 0)-    (void)mark_native(root, new_id);+    int status = 0;+    const auto finished = tx->finish("rm");+    if (!finished)+        status = 1;+    if (status == 0)+        (void)mark_native(root, new_id); -  if (status == 0) {-    if (delete_mode) {-      const int del = delete_paths(root, removes);-      if (del != 0)-        status = del;+    if (status == 0) {+        if (delete_mode) {+            const int del = delete_paths(root, removes);+            if (del != 0)+                status = del;+        }+        info_prefix();+        std::cout << "untracked " << removes.size() << " path(s)\n";     }-    info_prefix();-    std::cout << "untracked " << removes.size() << " path(s)\n";-  }-  return status;+    return status; } -int rm_command(const std::vector<std::string> &args, std::size_t start) {-  bool delete_mode = false;-  std::vector<std::string> operands;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && arg == "-delete") {-      delete_mode = true;-    } else if (!end_flags && rm_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      operands.push_back(arg);+int rm_command(const std::vector<std::string>& args, std::size_t start) {+    bool delete_mode = false;+    std::vector<std::string> operands;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && arg == "-delete") {+            delete_mode = true;+        } else if (!end_flags && rm_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            operands.push_back(arg);+        }     }-  }-  if (operands.empty()) {-    error_prefix();-    std::cout << "rm requires at least one path\n";-    return 1;-  }+    if (operands.empty()) {+        error_prefix();+        std::cout << "rm requires at least one path\n";+        return 1;+    } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap; -  const auto cwd_rel = cwd_relative(*root);-  if (!cwd_rel) {-    error_prefix();-    std::cout << "cannot determine current directory\n";-    return 1;-  }+    const auto cwd_rel = cwd_relative(*root);+    if (!cwd_rel) {+        error_prefix();+        std::cout << "cannot determine current directory\n";+        return 1;+    } -  std::vector<std::string> normalized;-  for (const auto &arg : operands) {-    auto norm = pathspec_normalize(*root, *cwd_rel, arg);-    if (!norm) {-      error_prefix();-      std::cout << "path is outside the repository: " << arg << "\n";-      return 1;+    std::vector<std::string> normalized;+    for (const auto& arg : operands) {+        auto norm = pathspec_normalize(*root, *cwd_rel, arg);+        if (!norm) {+            error_prefix();+            std::cout << "path is outside the repository: " << arg << "\n";+            return 1;+        }+        if (norm->empty() || !valid_path(*norm)) {+            error_prefix();+            std::cout << "invalid path: " << arg << "\n";+            return 1;+        }+        normalized.push_back(std::move(*norm));     }-    if (norm->empty() || !valid_path(*norm)) {-      error_prefix();-      std::cout << "invalid path: " << arg << "\n";-      return 1;+    if (normalized.empty()) {+        error_prefix();+        std::cout << "rm requires at least one path\n";+        return 1;     }-    normalized.push_back(std::move(*norm));-  }-  if (normalized.empty()) {-    error_prefix();-    std::cout << "rm requires at least one path\n";-    return 1;-  }-  return run_removal(*root, normalized, delete_mode);+    return run_removal(*root, normalized, delete_mode); }  } // namespace -int rm_run(const std::vector<std::string> &args) { return rm_command(args, 2); }+int rm_run(const std::vector<std::string>& args) {+    return rm_command(args, 2);+} -int mv_run(const std::vector<std::string> &args) {-  std::vector<std::string> operands;-  bool end_flags = false;-  for (std::size_t i = 2; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && rm_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      operands.push_back(arg);+int mv_run(const std::vector<std::string>& args) {+    std::vector<std::string> operands;+    bool end_flags = false;+    for (std::size_t i = 2; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && rm_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            operands.push_back(arg);+        }     }-  } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap; -  if (operands.size() != 2) {-    error_prefix();-    std::cout << "mv requires a source and a destination\n";-    return 1;-  }+    if (operands.size() != 2) {+        error_prefix();+        std::cout << "mv requires a source and a destination\n";+        return 1;+    } -  const auto cwd_rel = cwd_relative(*root);-  if (!cwd_rel) {-    error_prefix();-    std::cout << "cannot determine current directory\n";-    return 1;-  }-  auto src = pathspec_normalize(*root, *cwd_rel, operands[0]);-  if (!src) {-    error_prefix();-    std::cout << "invalid path\n";-    return 1;-  }-  auto dst = pathspec_normalize(*root, *cwd_rel, operands[1]);-  if (!dst) {-    error_prefix();-    std::cout << "invalid path\n";-    return 1;-  }+    const auto cwd_rel = cwd_relative(*root);+    if (!cwd_rel) {+        error_prefix();+        std::cout << "cannot determine current directory\n";+        return 1;+    }+    auto src = pathspec_normalize(*root, *cwd_rel, operands[0]);+    if (!src) {+        error_prefix();+        std::cout << "invalid path\n";+        return 1;+    }+    auto dst = pathspec_normalize(*root, *cwd_rel, operands[1]);+    if (!dst) {+        error_prefix();+        std::cout << "invalid path\n";+        return 1;+    } -  const fs::path src_abs = *root / path_from_bytes(*src);-  const fs::path dst_abs = *root / path_from_bytes(*dst);-  if (!stat_path(src_abs)) {-    error_prefix();-    std::cout << "not a tracked path: " << *src << "\n";-    return 1;-  }-  if (stat_path(dst_abs)) {-    error_prefix();-    std::cout << "destination already exists: " << *dst << "\n";-    return 1;-  }+    const fs::path src_abs = *root / path_from_bytes(*src);+    const fs::path dst_abs = *root / path_from_bytes(*dst);+    if (!stat_path(src_abs)) {+        error_prefix();+        std::cout << "not a tracked path: " << *src << "\n";+        return 1;+    }+    if (stat_path(dst_abs)) {+        error_prefix();+        std::cout << "destination already exists: " << *dst << "\n";+        return 1;+    } -  if (const auto parent = parent_of(*dst)) {-    if (!ensure_directory(*root / path_from_bytes(*parent))) {-      error_prefix();-      std::cout << "cannot create destination directory\n";-      return 1;+    if (const auto parent = parent_of(*dst)) {+        if (!ensure_directory(*root / path_from_bytes(*parent))) {+            error_prefix();+            std::cout << "cannot create destination directory\n";+            return 1;+        }     }-  }-  std::error_code ec;-  fs::rename(src_abs, dst_abs, ec);-  if (ec) {-    error_prefix();-    std::cout << "cannot move path\n";-    return 1;-  }-  return snapshot_run(*root);+    std::error_code ec;+    fs::rename(src_abs, dst_abs, ec);+    if (ec) {+        error_prefix();+        std::cout << "cannot move path\n";+        return 1;+    }+    return snapshot_run(*root); }  } // namespace vn--- a/xveins/src/server.cpp+++ b/xveins/src/server.cpp@@ -27,965 +27,916 @@ constexpr std::size_t DRAIN_BYTES = 64u << 20;  struct Session {-  net::Stream stream;-  fs::path repo_root;-  bool repo_present = false;-  Store store;-  bool store_open = false;-  auth::Access access;-  std::string hello_repo;-  std::string server_nonce;-  std::string client_nonce;-  std::string binding;-  std::uint16_t version = proto::PROTOCOL_VERSION;-  bool authed = false;-  std::uint8_t role = auth::ROLE_ANONYMOUS;-  PublicKey public_key{};-  bool has_public_key = false;-  std::string fingerprint;-  std::vector<Id> haves;-  std::uint64_t quota_bytes = 0;-  int failed_auth = 0;-  bool closing = false;-  fs::path root;+    net::Stream stream;+    fs::path repo_root;+    bool repo_present = false;+    Store store;+    bool store_open = false;+    auth::Access access;+    std::string hello_repo;+    std::string server_nonce;+    std::string client_nonce;+    std::string binding;+    std::uint16_t version = proto::PROTOCOL_VERSION;+    bool authed = false;+    std::uint8_t role = auth::ROLE_ANONYMOUS;+    PublicKey public_key{};+    bool has_public_key = false;+    std::string fingerprint;+    std::vector<Id> haves;+    std::uint64_t quota_bytes = 0;+    int failed_auth = 0;+    bool closing = false;+    fs::path root; }; -fs::path quota_dir(const Session &session) {-  if (session.root.empty())-    return session.repo_root;-  std::string_view repo = session.hello_repo;-  const auto slash = repo.find('/');-  if (slash != std::string_view::npos)-    repo = repo.substr(0, slash);-  if (repo.empty())-    return session.root;-  return session.root / path_from_bytes(repo);+fs::path quota_dir(const Session& session) {+    if (session.root.empty())+        return session.repo_root;+    std::string_view repo = session.hello_repo;+    const auto slash = repo.find('/');+    if (slash != std::string_view::npos)+        repo = repo.substr(0, slash);+    if (repo.empty())+        return session.root;+    return session.root / path_from_bytes(repo); } -std::uint8_t effective_role(const Session &session) {-  if (session.authed)-    return session.role;-  if (session.access.valid && session.access.anonymous_read &&-      session.repo_present)-    return auth::ROLE_READ;-  return auth::ROLE_ANONYMOUS;+std::uint8_t effective_role(const Session& session) {+    if (session.authed)+        return session.role;+    if (session.access.valid && session.access.anonymous_read && session.repo_present)+        return auth::ROLE_READ;+    return auth::ROLE_ANONYMOUS; } -bool deny(Session &session, std::uint32_t request_id, bool write) {-  const std::uint8_t role = effective_role(session);-  if (write) {-    if (role == auth::ROLE_WRITE)-      return false;+bool deny(Session& session, std::uint32_t request_id, bool write) {+    const std::uint8_t role = effective_role(session);+    if (write) {+        if (role == auth::ROLE_WRITE)+            return false;+        if (!session.authed) {+            wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,+                              "authentication required");+        } else {+            wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,+                              "write role required");+        }+        return true;+    }+    if (role == auth::ROLE_READ || role == auth::ROLE_WRITE)+        return false;     if (!session.authed) {-      wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,-                        "authentication required");+        wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,+                          "authentication required");     } else {-      wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,-                        "write role required");+        wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN, "read role required");     }     return true;-  }-  if (role == auth::ROLE_READ || role == auth::ROLE_WRITE)-    return false;-  if (!session.authed) {-    wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,-                      "authentication required");-  } else {-    wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,-                      "read role required");-  }-  return true; } -void log_line(Session &session, std::string_view text) {-  if (!session.repo_present)-    return;-  (void)append_file(veins_dir(session.repo_root) / "server.log",-                    bytes_of(text));+void log_line(Session& session, std::string_view text) {+    if (!session.repo_present)+        return;+    (void)append_file(veins_dir(session.repo_root) / "server.log", bytes_of(text)); } -void log_outcome(Session &session, std::string_view outcome) {-  if (!session.repo_present)-    return;-  const std::string line =-      std::to_string(unix_now_millis()) + " " +-      std::string(proto::role_name(effective_role(session))) + " " +-      std::string(outcome) + " " + session.hello_repo + "\n";-  log_line(session, line);+void log_outcome(Session& session, std::string_view outcome) {+    if (!session.repo_present)+        return;+    const std::string line = std::to_string(unix_now_millis()) + " " ++                             std::string(proto::role_name(effective_role(session))) + " " ++                             std::string(outcome) + " " + session.hello_repo + "\n";+    log_line(session, line); }  bool safe_repo_name(std::string_view name) {-  if (name.empty() || name.size() > 4096)-    return false;-  if (name.front() == '/')-    return false;-  if (name.find('\0') != std::string_view::npos ||-      name.find('\\') != std::string_view::npos)-    return false;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= name.size(); ++i) {-    if (i == name.size() || name[i] == '/') {-      if (i - start == 2 && name[start] == '.' && name[start + 1] == '.')+    if (name.empty() || name.size() > 4096)         return false;-      start = i + 1;+    if (name.front() == '/')+        return false;+    if (name.find('\0') != std::string_view::npos || name.find('\\') != std::string_view::npos)+        return false;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= name.size(); ++i) {+        if (i == name.size() || name[i] == '/') {+            if (i - start == 2 && name[start] == '.' && name[start + 1] == '.')+                return false;+            start = i + 1;+        }     }-  }-  return true;+    return true; } -void open_session_store(Session &session) {-  if (session.store_open)-    return;-  session.store = Store::open_all(session.repo_root);-  session.store_open = true;+void open_session_store(Session& session) {+    if (session.store_open)+        return;+    session.store = Store::open_all(session.repo_root);+    session.store_open = true; } -void select_repo(Session &session, bool has_root) {-  if (session.repo_present || !has_root)-    return;-  if (!safe_repo_name(session.hello_repo))-    return;-  const fs::path joined = session.root / path_from_bytes(session.hello_repo);-  if (auto found = discover_repo(joined)) {-    session.repo_root = *found;-    session.repo_present = true;-  }+void select_repo(Session& session, bool has_root) {+    if (session.repo_present || !has_root)+        return;+    if (!safe_repo_name(session.hello_repo))+        return;+    const fs::path joined = session.root / path_from_bytes(session.hello_repo);+    if (auto found = discover_repo(joined)) {+        session.repo_root = *found;+        session.repo_present = true;+    } } -std::string change_id_of(Session &session, const Id &id) {-  auto loaded = load_commit(session.store, id);-  if (!loaded)-    return {};-  return std::string(-      reinterpret_cast<const char *>(loaded->commit.change_id.data()),-      loaded->commit.change_id.size());+std::string change_id_of(Session& session, const Id& id) {+    auto loaded = load_commit(session.store, id);+    if (!loaded)+        return {};+    return std::string(reinterpret_cast<const char*>(loaded->commit.change_id.data()),+                       loaded->commit.change_id.size()); } -bool send_record(Session &session, std::uint32_t request_id,-                 blake3_hasher &hasher, const Id &id, std::uint8_t kind,-                 Bytes body) {-  const auto record = wire::make_record(id, kind, body);-  blake3_hasher_update(&hasher, record.data(), record.size());-  return wire::write_frame(session.stream, wire::RECORDS, request_id,-                           Bytes(record.data(), record.size()));+bool send_record(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,+                 std::uint8_t kind, Bytes body) {+    const auto record = wire::make_record(id, kind, body);+    blake3_hasher_update(&hasher, record.data(), record.size());+    return wire::write_frame(session.stream, wire::RECORDS, request_id,+                             Bytes(record.data(), record.size())); } -bool send_end(Session &session, std::uint32_t request_id,-              blake3_hasher &hasher) {-  std::array<std::uint8_t, 32> digest{};-  blake3_hasher_finalize(&hasher, digest.data(), digest.size());-  return wire::write_frame(session.stream, wire::END, request_id,-                           Bytes(digest.data(), digest.size()));+bool send_end(Session& session, std::uint32_t request_id, blake3_hasher& hasher) {+    std::array<std::uint8_t, 32> digest{};+    blake3_hasher_finalize(&hasher, digest.data(), digest.size());+    return wire::write_frame(session.stream, wire::END, request_id,+                             Bytes(digest.data(), digest.size())); }  std::uint8_t value_kind_to_type(std::uint8_t kind) {-  if (kind == KIND_SUBTREE)-    return TYPE_TREE;-  if (kind == KIND_CONFLICT)-    return TYPE_CONFLICT;-  if (kind == KIND_FILE || kind == KIND_EXECUTABLE || kind == KIND_SYMLINK)-    return TYPE_BLOB;-  return 0;+    if (kind == KIND_SUBTREE)+        return TYPE_TREE;+    if (kind == KIND_CONFLICT)+        return TYPE_CONFLICT;+    if (kind == KIND_FILE || kind == KIND_EXECUTABLE || kind == KIND_SYMLINK)+        return TYPE_BLOB;+    return 0; } -void collect_object(Session &session, std::uint32_t request_id,-                    blake3_hasher &hasher, const Id &id, std::uint8_t kind,-                    std::set<Id> &seen, bool send, bool &failed);+void collect_object(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,+                    std::uint8_t kind, std::set<Id>& seen, bool send, bool& failed); -void collect_tree(Session &session, std::uint32_t request_id,-                  blake3_hasher &hasher, const Id &id, std::set<Id> &seen,-                  bool send, bool &failed) {-  if (!seen.insert(id).second)-    return;-  auto body = session.store.read_body(id, TYPE_TREE);-  if (!body) {-    failed = true;-    return;-  }-  if (send && !send_record(session, request_id, hasher, id, TYPE_TREE,-                           bytes_of(*body))) {-    failed = true;-  }-  auto tree = decode_tree(bytes_of(*body));-  if (!tree) {-    failed = true;-    return;-  }-  for (const auto &entry : tree->entries) {-    if (entry.kind == KIND_SUBTREE) {-      collect_tree(session, request_id, hasher, entry.target, seen, send,-                   failed);-    } else if (entry.kind == KIND_CONFLICT) {-      collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT,-                     seen, send, failed);-    } else if (entry.kind != KIND_SUBMODULE) {-      collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen,-                     send, failed);+void collect_tree(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,+                  std::set<Id>& seen, bool send, bool& failed) {+    if (!seen.insert(id).second)+        return;+    auto body = session.store.read_body(id, TYPE_TREE);+    if (!body) {+        failed = true;+        return;     }-    if (failed)-      return;-  }-}--void collect_object(Session &session, std::uint32_t request_id,-                    blake3_hasher &hasher, const Id &id, std::uint8_t kind,-                    std::set<Id> &seen, bool send, bool &failed) {-  if (!seen.insert(id).second)-    return;-  auto body = session.store.read_body(id, kind);-  if (!body) {-    failed = true;-    return;-  }-  if (send &&-      !send_record(session, request_id, hasher, id, kind, bytes_of(*body))) {-    failed = true;-  }-  if (kind == TYPE_BLOB) {-    auto blob = decode_blob(bytes_of(*body));-    if (!blob) {-      failed = true;-      return;+    if (send && !send_record(session, request_id, hasher, id, TYPE_TREE, bytes_of(*body))) {+        failed = true;     }-    if (blob->form == BlobForm::Interior) {-      for (const auto &entry : blob->entries) {-        collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen,-                       send, failed);-        if (failed)-          return;-      }+    auto tree = decode_tree(bytes_of(*body));+    if (!tree) {+        failed = true;+        return;     }-  } else if (kind == TYPE_CONFLICT) {-    auto conflict = decode_conflict(bytes_of(*body));-    if (!conflict) {-      failed = true;-      return;+    for (const auto& entry : tree->entries) {+        if (entry.kind == KIND_SUBTREE) {+            collect_tree(session, request_id, hasher, entry.target, seen, send, failed);+        } else if (entry.kind == KIND_CONFLICT) {+            collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT, seen, send,+                           failed);+        } else if (entry.kind != KIND_SUBMODULE) {+            collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen, send,+                           failed);+        }+        if (failed)+            return;     }-    for (const auto &value : conflict->adds) {-      if (!value.target)-        continue;-      const std::uint8_t child = value_kind_to_type(value.kind);-      if (child != 0)-        collect_object(session, request_id, hasher, *value.target, child, seen,-                       send, failed);-      if (failed)+}++void collect_object(Session& session, std::uint32_t request_id, blake3_hasher& hasher, const Id& id,+                    std::uint8_t kind, std::set<Id>& seen, bool send, bool& failed) {+    if (!seen.insert(id).second)         return;-    }-    for (const auto &value : conflict->removes) {-      if (!value.target)-        continue;-      const std::uint8_t child = value_kind_to_type(value.kind);-      if (child != 0)-        collect_object(session, request_id, hasher, *value.target, child, seen,-                       send, failed);-      if (failed)+    auto body = session.store.read_body(id, kind);+    if (!body) {+        failed = true;         return;     }-  }+    if (send && !send_record(session, request_id, hasher, id, kind, bytes_of(*body))) {+        failed = true;+    }+    if (kind == TYPE_BLOB) {+        auto blob = decode_blob(bytes_of(*body));+        if (!blob) {+            failed = true;+            return;+        }+        if (blob->form == BlobForm::Interior) {+            for (const auto& entry : blob->entries) {+                collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen, send,+                               failed);+                if (failed)+                    return;+            }+        }+    } else if (kind == TYPE_CONFLICT) {+        auto conflict = decode_conflict(bytes_of(*body));+        if (!conflict) {+            failed = true;+            return;+        }+        for (const auto& value : conflict->adds) {+            if (!value.target)+                continue;+            const std::uint8_t child = value_kind_to_type(value.kind);+            if (child != 0)+                collect_object(session, request_id, hasher, *value.target, child, seen, send,+                               failed);+            if (failed)+                return;+        }+        for (const auto& value : conflict->removes) {+            if (!value.target)+                continue;+            const std::uint8_t child = value_kind_to_type(value.kind);+            if (child != 0)+                collect_object(session, request_id, hasher, *value.target, child, seen, send,+                               failed);+            if (failed)+                return;+        }+    } } -bool handle_hello(Session &session, const wire::Frame &frame, bool has_root) {-  auto hello = proto::decode_hello(bytes_of(frame.payload));-  if (!hello) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "bad HELLO");-    return false;-  }-  if (hello->min_version > proto::PROTOCOL_VERSION ||-      hello->max_version < proto::PROTOCOL_VERSION) {-    wire::write_error(session.stream, frame.request_id,-                      wire::ERR_UNSUPPORTED_VERSION, "no common version");-    return false;-  }-  session.version = proto::PROTOCOL_VERSION;-  session.hello_repo = std::move(hello->repo);-  session.client_nonce = std::move(hello->client_nonce);-  select_repo(session, has_root);-  if (!session.repo_present && !session.hello_repo.empty()) {-    error_prefix();-    std::cout << "repository not found: " << session.hello_repo << "\n";-    wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,-                      "repository not found");-    return false;-  }-  if (session.repo_present) {-    session.access = auth::load_access(session.repo_root);-    if (!session.access.valid) {-      error_prefix();-      std::cout << "access file error at line " << session.access.error_line-                << " in " << path_display(session.repo_root) << "\n";-      wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,-                        "invalid access file");-      return false;+bool handle_hello(Session& session, const wire::Frame& frame, bool has_root) {+    auto hello = proto::decode_hello(bytes_of(frame.payload));+    if (!hello) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "bad HELLO");+        return false;     }-    open_session_store(session);-  }-  log_outcome(session, "hello");+    if (hello->min_version > proto::PROTOCOL_VERSION ||+        hello->max_version < proto::PROTOCOL_VERSION) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_UNSUPPORTED_VERSION,+                          "no common version");+        return false;+    }+    session.version = proto::PROTOCOL_VERSION;+    session.hello_repo = std::move(hello->repo);+    session.client_nonce = std::move(hello->client_nonce);+    select_repo(session, has_root);+    if (!session.repo_present && !session.hello_repo.empty()) {+        error_prefix();+        std::cout << "repository not found: " << session.hello_repo << "\n";+        wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,+                          "repository not found");+        return false;+    }+    if (session.repo_present) {+        session.access = auth::load_access(session.repo_root);+        if (!session.access.valid) {+            error_prefix();+            std::cout << "access file error at line " << session.access.error_line << " in "+                      << path_display(session.repo_root) << "\n";+            wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                              "invalid access file");+            return false;+        }+        open_session_store(session);+    }+    log_outcome(session, "hello"); -  const auto nonce = secure_random(32);-  if (nonce.size() != 32) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,-                      "cannot generate nonce");-    return false;-  }-  session.server_nonce.assign(reinterpret_cast<const char *>(nonce.data()),-                              nonce.size());+    const auto nonce = secure_random(32);+    if (nonce.size() != 32) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                          "cannot generate nonce");+        return false;+    }+    session.server_nonce.assign(reinterpret_cast<const char*>(nonce.data()), nonce.size()); -  proto::HelloOk hello_ok;-  hello_ok.version = session.version;-  hello_ok.capabilities = {"zstd-records", "lazy-chunks", "push",-                           "auth-ed25519"};-  hello_ok.server_nonce = session.server_nonce;-  hello_ok.auth_required =-      (session.repo_present && session.access.anonymous_read) ? 0 : 1;-  const auto body = proto::encode_hello_ok(hello_ok);-  return wire::write_frame(session.stream, wire::HELLO_OK, frame.request_id,-                           body);+    proto::HelloOk hello_ok;+    hello_ok.version = session.version;+    hello_ok.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};+    hello_ok.server_nonce = session.server_nonce;+    hello_ok.auth_required = (session.repo_present && session.access.anonymous_read) ? 0 : 1;+    const auto body = proto::encode_hello_ok(hello_ok);+    return wire::write_frame(session.stream, wire::HELLO_OK, frame.request_id, body); } -bool handle_auth(Session &session, const wire::Frame &frame) {-  if (session.authed) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "repeated AUTH");-    session.closing = true;-    return false;-  }-  auto auth = proto::decode_auth(bytes_of(frame.payload));-  if (!auth) {-    ++session.failed_auth;-    wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,-                      "authentication failed");-    if (session.failed_auth >= 3)-      session.closing = true;-    return true;-  }-  PublicKey public_key{};-  const bool key_well_formed = auth->public_key.size() == public_key.size();-  if (key_well_formed) {-    std::memcpy(public_key.data(), auth->public_key.data(), public_key.size());-  }-  std::uint8_t role = auth::ROLE_UNKNOWN;-  if (key_well_formed && session.repo_present && session.access.valid)-    role = auth::role_for(session.access, &public_key);+bool handle_auth(Session& session, const wire::Frame& frame) {+    if (session.authed) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "repeated AUTH");+        session.closing = true;+        return false;+    }+    auto auth = proto::decode_auth(bytes_of(frame.payload));+    if (!auth) {+        ++session.failed_auth;+        wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,+                          "authentication failed");+        if (session.failed_auth >= 3)+            session.closing = true;+        return true;+    }+    PublicKey public_key{};+    const bool key_well_formed = auth->public_key.size() == public_key.size();+    if (key_well_formed) {+        std::memcpy(public_key.data(), auth->public_key.data(), public_key.size());+    }+    std::uint8_t role = auth::ROLE_UNKNOWN;+    if (key_well_formed && session.repo_present && session.access.valid)+        role = auth::role_for(session.access, &public_key); -  const std::string message = proto::auth_message(-      session.version, session.hello_repo, bytes_of(session.server_nonce),-      bytes_of(session.client_nonce), bytes_of(session.binding));-  const bool signature_ok =-      role != auth::ROLE_UNKNOWN &&-      ed25519_verify(public_key, bytes_of(message), bytes_of(auth->signature));-  if (!signature_ok) {-    ++session.failed_auth;-    wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,-                      "authentication failed");-    if (session.failed_auth >= 3)-      session.closing = true;-    return true;-  }+    const std::string message =+        proto::auth_message(session.version, session.hello_repo, bytes_of(session.server_nonce),+                            bytes_of(session.client_nonce), bytes_of(session.binding));+    const bool signature_ok =+        role != auth::ROLE_UNKNOWN &&+        ed25519_verify(public_key, bytes_of(message), bytes_of(auth->signature));+    if (!signature_ok) {+        ++session.failed_auth;+        wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,+                          "authentication failed");+        if (session.failed_auth >= 3)+            session.closing = true;+        return true;+    } -  session.authed = true;-  session.role = role;-  session.public_key = public_key;-  session.has_public_key = true;-  const auto raw_fingerprint = key_fingerprint_bytes(public_key);-  session.fingerprint.assign(-      reinterpret_cast<const char *>(raw_fingerprint.data()),-      raw_fingerprint.size());+    session.authed = true;+    session.role = role;+    session.public_key = public_key;+    session.has_public_key = true;+    const auto raw_fingerprint = key_fingerprint_bytes(public_key);+    session.fingerprint.assign(reinterpret_cast<const char*>(raw_fingerprint.data()),+                               raw_fingerprint.size()); -  proto::AuthOk auth_ok;-  auth_ok.role = role;-  auth_ok.fingerprint = session.fingerprint;-  const auto body = proto::encode_auth_ok(auth_ok);-  const bool wrote =-      wire::write_frame(session.stream, wire::AUTH_OK, frame.request_id, body);-  log_outcome(session, "auth-ok");-  return wrote;+    proto::AuthOk auth_ok;+    auth_ok.role = role;+    auth_ok.fingerprint = session.fingerprint;+    const auto body = proto::encode_auth_ok(auth_ok);+    const bool wrote = wire::write_frame(session.stream, wire::AUTH_OK, frame.request_id, body);+    log_outcome(session, "auth-ok");+    return wrote; } -bool handle_whoami(Session &session, const wire::Frame &frame) {-  ByteWriter writer(64);-  writer.u8(effective_role(session));-  writer.length_prefixed(session.fingerprint);-  return wire::write_frame(session.stream, wire::WHOAMI_OK, frame.request_id,-                           writer.view());+bool handle_whoami(Session& session, const wire::Frame& frame) {+    ByteWriter writer(64);+    writer.u8(effective_role(session));+    writer.length_prefixed(session.fingerprint);+    return wire::write_frame(session.stream, wire::WHOAMI_OK, frame.request_id, writer.view()); } -bool handle_list_refs(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, false))-    return true;-  log_outcome(session, "list-refs");-  std::optional<View> view = current_view(session.repo_root, session.store);-  if (!view) {-    const auto heads = read_heads(session.repo_root);-    if (!heads.empty()) {-      wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,-                        "cannot read operation state");-      log_outcome(session, "list-refs-error");-      return true;+bool handle_list_refs(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, false))+        return true;+    log_outcome(session, "list-refs");+    std::optional<View> view = current_view(session.repo_root, session.store);+    if (!view) {+        const auto heads = read_heads(session.repo_root);+        if (!heads.empty()) {+            wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                              "cannot read operation state");+            log_outcome(session, "list-refs-error");+            return true;+        }+        view = empty_view();     }-    view = empty_view();-  }-  std::vector<proto::RefInfo> refs;-  for (const auto &bookmark : view->bookmarks) {-    if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front())-      continue;-    proto::RefInfo ref;-    ref.name = bookmark.name;-    ref.target = *bookmark.targets.adds.front();-    ref.change_id = change_id_of(session, ref.target);-    ref.kind = 0;-    refs.push_back(std::move(ref));-  }-  for (const auto &tag : view->tags) {-    proto::RefInfo ref;-    ref.name = tag.name;-    ref.target = tag.target;-    ref.change_id = change_id_of(session, tag.target);-    ref.kind = 1;-    refs.push_back(std::move(ref));-  }-  const auto body = proto::encode_refs(refs);-  const bool wrote =-      wire::write_frame(session.stream, wire::REFS, frame.request_id, body);-  if (!wrote)-    log_outcome(session, "list-refs-write-error");-  return wrote;-}--bool handle_negotiate(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, false))-    return true;-  auto negotiate = proto::decode_negotiate(bytes_of(frame.payload));-  if (!negotiate) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "bad NEGOTIATE");-    return true;-  }-  session.haves = std::move(negotiate->haves);-  std::vector<std::uint8_t> known;-  known.reserve(session.haves.size());-  bool any_known = false;-  for (const auto &id : session.haves) {-    const bool found = session.store.find(id).has_value();-    known.push_back(found ? 1 : 0);-    any_known = any_known || found;-  }-  const std::uint8_t enough = (session.haves.empty() || any_known) ? 1 : 0;-  const auto body = proto::encode_negotiate_ok(known, enough);-  return wire::write_frame(session.stream, wire::NEGOTIATE_OK, frame.request_id,-                           body);+    std::vector<proto::RefInfo> refs;+    for (const auto& bookmark : view->bookmarks) {+        if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front())+            continue;+        proto::RefInfo ref;+        ref.name = bookmark.name;+        ref.target = *bookmark.targets.adds.front();+        ref.change_id = change_id_of(session, ref.target);+        ref.kind = 0;+        refs.push_back(std::move(ref));+    }+    for (const auto& tag : view->tags) {+        proto::RefInfo ref;+        ref.name = tag.name;+        ref.target = tag.target;+        ref.change_id = change_id_of(session, tag.target);+        ref.kind = 1;+        refs.push_back(std::move(ref));+    }+    const auto body = proto::encode_refs(refs);+    const bool wrote = wire::write_frame(session.stream, wire::REFS, frame.request_id, body);+    if (!wrote)+        log_outcome(session, "list-refs-write-error");+    return wrote; }--bool handle_fetch(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, false))-    return true;-  auto wants = proto::decode_ids(bytes_of(frame.payload), 1000000);-  if (!wants) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "bad wants");-    return true;-  }-  if (wants->empty()) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "empty wants");-    return true;-  }-  const auto all = collect_commits(session.store, *wants);-  std::set<Id> exclude;-  for (const auto &have : session.haves) {-    const std::array<Id, 1> roots{have};-    for (const auto &id : collect_commits(session.store, roots))-      exclude.insert(id);-  } -  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  bool failed = false;-  std::set<Id> seen;-  for (const auto &id : all) {-    if (exclude.contains(id))-      continue;-    auto loaded = load_commit(session.store, id);-    if (!loaded) {-      failed = true;-      break;+bool handle_negotiate(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, false))+        return true;+    auto negotiate = proto::decode_negotiate(bytes_of(frame.payload));+    if (!negotiate) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "bad NEGOTIATE");+        return true;     }-    if (!send_record(session, frame.request_id, hasher, id, TYPE_COMMIT,-                     bytes_of(loaded->body))) {-      failed = true;-      break;+    session.haves = std::move(negotiate->haves);+    std::vector<std::uint8_t> known;+    known.reserve(session.haves.size());+    bool any_known = false;+    for (const auto& id : session.haves) {+        const bool found = session.store.find(id).has_value();+        known.push_back(found ? 1 : 0);+        any_known = any_known || found;     }-    collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree,-                 seen, true, failed);-    if (failed)-      break;-  }-  if (!failed)-    (void)send_end(session, frame.request_id, hasher);-  log_outcome(session, "fetch");-  return !failed;+    const std::uint8_t enough = (session.haves.empty() || any_known) ? 1 : 0;+    const auto body = proto::encode_negotiate_ok(known, enough);+    return wire::write_frame(session.stream, wire::NEGOTIATE_OK, frame.request_id, body); } -bool handle_get_chunks(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, false))-    return true;-  auto ids = proto::decode_ids(bytes_of(frame.payload), MAX_CHUNKS_PER_REQUEST);-  if (!ids) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "bad chunk list");-    return true;-  }-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  bool failed = false;-  for (const auto &id : *ids) {-    const auto loc = session.store.find(id);-    if (!loc || loc->kind != TYPE_CHUNK) {-      failed = true;-      break;+bool handle_fetch(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, false))+        return true;+    auto wants = proto::decode_ids(bytes_of(frame.payload), 1000000);+    if (!wants) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "bad wants");+        return true;     }-    auto body = session.store.get(*loc);-    if (!body) {-      failed = true;-      break;+    if (wants->empty()) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "empty wants");+        return true;     }-    if (!send_record(session, frame.request_id, hasher, id, TYPE_CHUNK,-                     bytes_of(*body))) {-      failed = true;-      break;+    const auto all = collect_commits(session.store, *wants);+    std::set<Id> exclude;+    for (const auto& have : session.haves) {+        const std::array<Id, 1> roots{have};+        for (const auto& id : collect_commits(session.store, roots))+            exclude.insert(id);     }-  }-  if (failed) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,-                      "chunk not found");-  } else {-    (void)send_end(session, frame.request_id, hasher);-  }-  return !failed;-}--bool handle_have_query(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, true))-    return true;-  auto ids = proto::decode_ids(bytes_of(frame.payload), 1000000);-  if (!ids) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "bad HAVE_QUERY");-    return true;-  }-  std::vector<std::uint8_t> bits;-  bits.reserve(ids->size());-  for (const auto &id : *ids)-    bits.push_back(session.store.find(id).has_value() ? 1 : 0);-  const auto body = proto::encode_bitmap(bits);-  return wire::write_frame(session.stream, wire::HAVE_BITMAP, frame.request_id,-                           body);-} -bool object_exists(Session &session, const Id &id) {-  return session.store.find(id).has_value();+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    bool failed = false;+    std::set<Id> seen;+    for (const auto& id : all) {+        if (exclude.contains(id))+            continue;+        auto loaded = load_commit(session.store, id);+        if (!loaded) {+            failed = true;+            break;+        }+        if (!send_record(session, frame.request_id, hasher, id, TYPE_COMMIT,+                         bytes_of(loaded->body))) {+            failed = true;+            break;+        }+        collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree, seen, true,+                     failed);+        if (failed)+            break;+    }+    if (!failed)+        (void)send_end(session, frame.request_id, hasher);+    log_outcome(session, "fetch");+    return !failed; } -bool check_closure(Session &session, const Id &id, std::uint8_t kind) {-  auto body = session.store.read_body(id, kind);-  if (!body)-    return false;-  bool fine = true;-  if (kind == TYPE_COMMIT) {-    auto commit = decode_commit(bytes_of(*body));-    if (!commit)-      return false;-    if (!object_exists(session, commit->root_tree))-      fine = false;-    for (const auto &parent : commit->parents) {-      if (!object_exists(session, parent))-        fine = false;-    }-  } else if (kind == TYPE_TREE) {-    auto tree = decode_tree(bytes_of(*body));-    if (!tree)-      return false;-    for (const auto &entry : tree->entries) {-      if (entry.kind != KIND_SUBMODULE && !object_exists(session, entry.target))-        fine = false;+bool handle_get_chunks(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, false))+        return true;+    auto ids = proto::decode_ids(bytes_of(frame.payload), MAX_CHUNKS_PER_REQUEST);+    if (!ids) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "bad chunk list");+        return true;     }-  } else if (kind == TYPE_BLOB) {-    auto blob = decode_blob(bytes_of(*body));-    if (!blob)-      return false;-    for (const auto &entry : blob->entries) {-      if (!object_exists(session, entry.id))-        fine = false;+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    bool failed = false;+    for (const auto& id : *ids) {+        const auto loc = session.store.find(id);+        if (!loc || loc->kind != TYPE_CHUNK) {+            failed = true;+            break;+        }+        auto body = session.store.get(*loc);+        if (!body) {+            failed = true;+            break;+        }+        if (!send_record(session, frame.request_id, hasher, id, TYPE_CHUNK, bytes_of(*body))) {+            failed = true;+            break;+        }     }-  } else if (kind == TYPE_CONFLICT) {-    auto conflict = decode_conflict(bytes_of(*body));-    if (!conflict)-      return false;-    for (const auto &value : conflict->adds) {-      if (value.target && !object_exists(session, *value.target))-        fine = false;+    if (failed) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND, "chunk not found");+    } else {+        (void)send_end(session, frame.request_id, hasher);     }-    for (const auto &value : conflict->removes) {-      if (value.target && !object_exists(session, *value.target))-        fine = false;+    return !failed;+}++bool handle_have_query(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, true))+        return true;+    auto ids = proto::decode_ids(bytes_of(frame.payload), 1000000);+    if (!ids) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "bad HAVE_QUERY");+        return true;     }-  }-  return fine;+    std::vector<std::uint8_t> bits;+    bits.reserve(ids->size());+    for (const auto& id : *ids)+        bits.push_back(session.store.find(id).has_value() ? 1 : 0);+    const auto body = proto::encode_bitmap(bits);+    return wire::write_frame(session.stream, wire::HAVE_BITMAP, frame.request_id, body); } -bool drain_push(Session &session, std::size_t max_bytes) {-  std::size_t seen = 0;-  while (seen <= max_bytes) {-    auto frame = wire::read_frame(session.stream);-    if (!frame)-      return false;-    if (frame->kind == wire::END)-      return true;-    if (frame->kind != wire::RECORDS)-      return false;-    seen += frame->payload.size();-  }-  return false;+bool object_exists(Session& session, const Id& id) {+    return session.store.find(id).has_value(); } -bool handle_put_records(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, true))-    return true;-  std::uint64_t limit = 0;-  if (session.quota_bytes > 0) {-    const std::uint64_t used = storage_usage(quota_dir(session));-    if (used + QUOTA_RESERVE >= session.quota_bytes) {-      if (!drain_push(session, DRAIN_BYTES))-        session.closing = true;-      wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,-                        "storage quota exceeded");-      return true;+bool check_closure(Session& session, const Id& id, std::uint8_t kind) {+    auto body = session.store.read_body(id, kind);+    if (!body)+        return false;+    bool fine = true;+    if (kind == TYPE_COMMIT) {+        auto commit = decode_commit(bytes_of(*body));+        if (!commit)+            return false;+        if (!object_exists(session, commit->root_tree))+            fine = false;+        for (const auto& parent : commit->parents) {+            if (!object_exists(session, parent))+                fine = false;+        }+    } else if (kind == TYPE_TREE) {+        auto tree = decode_tree(bytes_of(*body));+        if (!tree)+            return false;+        for (const auto& entry : tree->entries) {+            if (entry.kind != KIND_SUBMODULE && !object_exists(session, entry.target))+                fine = false;+        }+    } else if (kind == TYPE_BLOB) {+        auto blob = decode_blob(bytes_of(*body));+        if (!blob)+            return false;+        for (const auto& entry : blob->entries) {+            if (!object_exists(session, entry.id))+                fine = false;+        }+    } else if (kind == TYPE_CONFLICT) {+        auto conflict = decode_conflict(bytes_of(*body));+        if (!conflict)+            return false;+        for (const auto& value : conflict->adds) {+            if (value.target && !object_exists(session, *value.target))+                fine = false;+        }+        for (const auto& value : conflict->removes) {+            if (value.target && !object_exists(session, *value.target))+                fine = false;+        }     }-    limit = session.quota_bytes - used - QUOTA_RESERVE;-  }-  Writer writer;-  writer.set_limit(limit);-  blake3_hasher hasher;-  blake3_hasher_init(&hasher);-  bool failed = false;-  bool too_large = false;-  bool quota_hit = false;-  std::size_t records = 0;-  std::vector<Id> accepted;+    return fine;+} -  for (;;) {-    auto frame_opt = wire::read_frame(session.stream);-    if (!frame_opt) {-      failed = true;-      break;-    }-    const auto &incoming = *frame_opt;-    if (incoming.kind == wire::END) {-      std::array<std::uint8_t, 32> digest{};-      blake3_hasher_finalize(&hasher, digest.data(), digest.size());-      if (incoming.payload.size() != digest.size() ||-          std::memcmp(incoming.payload.data(), digest.data(), digest.size()) !=-              0) {-        failed = true;-      }-      break;-    }-    if (incoming.kind != wire::RECORDS) {-      failed = true;-      break;+bool drain_push(Session& session, std::size_t max_bytes) {+    std::size_t seen = 0;+    while (seen <= max_bytes) {+        auto frame = wire::read_frame(session.stream);+        if (!frame)+            return false;+        if (frame->kind == wire::END)+            return true;+        if (frame->kind != wire::RECORDS)+            return false;+        seen += frame->payload.size();     }-    if (++records > MAX_PUSH_RECORDS) {-      too_large = true;-      failed = true;-      break;+    return false;+}++bool handle_put_records(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, true))+        return true;+    std::uint64_t limit = 0;+    if (session.quota_bytes > 0) {+        const std::uint64_t used = storage_usage(quota_dir(session));+        if (used + QUOTA_RESERVE >= session.quota_bytes) {+            if (!drain_push(session, DRAIN_BYTES))+                session.closing = true;+            wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,+                              "storage quota exceeded");+            return true;+        }+        limit = session.quota_bytes - used - QUOTA_RESERVE;     }-    blake3_hasher_update(&hasher, incoming.payload.data(),-                         incoming.payload.size());-    auto record = wire::parse_record(bytes_of(incoming.payload));-    if (!record) {-      failed = true;-      break;+    Writer writer;+    writer.set_limit(limit);+    blake3_hasher hasher;+    blake3_hasher_init(&hasher);+    bool failed = false;+    bool too_large = false;+    bool quota_hit = false;+    std::size_t records = 0;+    std::vector<Id> accepted;++    for (;;) {+        auto frame_opt = wire::read_frame(session.stream);+        if (!frame_opt) {+            failed = true;+            break;+        }+        const auto& incoming = *frame_opt;+        if (incoming.kind == wire::END) {+            std::array<std::uint8_t, 32> digest{};+            blake3_hasher_finalize(&hasher, digest.data(), digest.size());+            if (incoming.payload.size() != digest.size() ||+                std::memcmp(incoming.payload.data(), digest.data(), digest.size()) != 0) {+                failed = true;+            }+            break;+        }+        if (incoming.kind != wire::RECORDS) {+            failed = true;+            break;+        }+        if (++records > MAX_PUSH_RECORDS) {+            too_large = true;+            failed = true;+            break;+        }+        blake3_hasher_update(&hasher, incoming.payload.data(), incoming.payload.size());+        auto record = wire::parse_record(bytes_of(incoming.payload));+        if (!record) {+            failed = true;+            break;+        }+        const Id computed = object_id(record->kind, bytes_of(record->body));+        if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {+            failed = true;+            break;+        }+        writer.add_known(record->kind, record->id, std::move(record->body));+        accepted.push_back(record->id);+        if (writer.quota_hit()) {+            quota_hit = true;+            failed = true;+            break;+        }     }-    const Id computed = object_id(record->kind, bytes_of(record->body));-    if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {-      failed = true;-      break;++    if (failed) {+        if (!drain_push(session, DRAIN_BYTES))+            session.closing = true;+        if (too_large) {+            wire::write_error(session.stream, frame.request_id, wire::ERR_TOO_LARGE,+                              "too many objects in one push");+        } else if (quota_hit) {+            wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,+                              "storage quota exceeded");+        } else {+            wire::write_error(session.stream, frame.request_id, wire::ERR_HASH_MISMATCH,+                              "record rejected");+        }+        return true;     }-    writer.add_known(record->kind, record->id, std::move(record->body));-    accepted.push_back(record->id);-    if (writer.quota_hit()) {-      quota_hit = true;-      failed = true;-      break;+    const int status = writer.finish(session.repo_root);+    if (status != 0) {+        wire::write_error(session.stream, frame.request_id,+                          status == 2 ? wire::ERR_QUOTA : wire::ERR_INTERNAL,+                          status == 2 ? "storage quota exceeded" : "pack write failed");+        return true;     }-  }+    open_session_store(session);+    session.store.refresh(session.repo_root); -  if (failed) {-    if (!drain_push(session, DRAIN_BYTES))-      session.closing = true;-    if (too_large) {-      wire::write_error(session.stream, frame.request_id, wire::ERR_TOO_LARGE,-                        "too many objects in one push");-    } else if (quota_hit) {-      wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,-                        "storage quota exceeded");-    } else {-      wire::write_error(session.stream, frame.request_id,-                        wire::ERR_HASH_MISMATCH, "record rejected");+    bool closure_ok = true;+    for (const auto& id : accepted) {+        const auto loc = session.store.find(id);+        if (!loc)+            continue;+        if (!check_closure(session, id, loc->kind)) {+            closure_ok = false;+            break;+        }     }-    return true;-  }-  const int status = writer.finish(session.repo_root);-  if (status != 0) {-    wire::write_error(session.stream, frame.request_id,-                      status == 2 ? wire::ERR_QUOTA : wire::ERR_INTERNAL,-                      status == 2 ? "storage quota exceeded"-                                  : "pack write failed");-    return true;-  }-  open_session_store(session);-  session.store.refresh(session.repo_root);--  bool closure_ok = true;-  for (const auto &id : accepted) {-    const auto loc = session.store.find(id);-    if (!loc)-      continue;-    if (!check_closure(session, id, loc->kind)) {-      closure_ok = false;-      break;+    if (!closure_ok) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_MISSING_CLOSURE,+                          "missing object closure");+        return true;     }-  }-  if (!closure_ok) {-    wire::write_error(session.stream, frame.request_id,-                      wire::ERR_MISSING_CLOSURE, "missing object closure");-    return true;-  }-  return wire::write_frame(session.stream, wire::END, frame.request_id,-                           Bytes{});+    return wire::write_frame(session.stream, wire::END, frame.request_id, Bytes{}); } -std::optional<Id> first_target(const TargetSet &targets) {-  if (targets.adds.empty())-    return std::nullopt;-  return targets.adds.front();+std::optional<Id> first_target(const TargetSet& targets) {+    if (targets.adds.empty())+        return std::nullopt;+    return targets.adds.front(); } -bool ref_matches(const View &view, std::string_view name,-                 const std::optional<Id> &expected) {-  std::optional<Id> current;-  if (auto index = find_bookmark(view, name)) {-    current = first_target(view.bookmarks[*index].targets);-  } else if (auto index = find_tag(view, name)) {-    current = view.tags[*index].target;-  }-  if (!expected)-    return !current.has_value();-  if (!current)-    return false;-  return std::memcmp(current->data(), expected->data(), ID_LEN) == 0;+bool ref_matches(const View& view, std::string_view name, const std::optional<Id>& expected) {+    std::optional<Id> current;+    if (auto index = find_bookmark(view, name)) {+        current = first_target(view.bookmarks[*index].targets);+    } else if (auto index = find_tag(view, name)) {+        current = view.tags[*index].target;+    }+    if (!expected)+        return !current.has_value();+    if (!current)+        return false;+    return std::memcmp(current->data(), expected->data(), ID_LEN) == 0; } -void apply_ref(View &view, std::string_view name,-               const std::optional<Id> &target) {-  if (!target) {-    if (auto index = find_bookmark(view, name))-      view.bookmarks.erase(view.bookmarks.begin() +-                           static_cast<std::ptrdiff_t>(*index));-    if (auto index = find_tag(view, name))-      view.tags.erase(view.tags.begin() + static_cast<std::ptrdiff_t>(*index));-    return;-  }-  if (auto index = find_bookmark(view, name)) {-    auto &bookmark = view.bookmarks[*index];+void apply_ref(View& view, std::string_view name, const std::optional<Id>& target) {+    if (!target) {+        if (auto index = find_bookmark(view, name))+            view.bookmarks.erase(view.bookmarks.begin() + static_cast<std::ptrdiff_t>(*index));+        if (auto index = find_tag(view, name))+            view.tags.erase(view.tags.begin() + static_cast<std::ptrdiff_t>(*index));+        return;+    }+    if (auto index = find_bookmark(view, name)) {+        auto& bookmark = view.bookmarks[*index];+        bookmark.targets.adds = {*target};+        bookmark.targets.removes.clear();+        return;+    }+    if (auto index = find_tag(view, name)) {+        view.tags[*index].target = *target;+        return;+    }+    Bookmark bookmark;+    bookmark.name = std::string(name);     bookmark.targets.adds = {*target};-    bookmark.targets.removes.clear();-    return;-  }-  if (auto index = find_tag(view, name)) {-    view.tags[*index].target = *target;-    return;-  }-  Bookmark bookmark;-  bookmark.name = std::string(name);-  bookmark.targets.adds = {*target};-  view.bookmarks.push_back(std::move(bookmark));+    view.bookmarks.push_back(std::move(bookmark)); } -bool handle_update_refs(Session &session, const wire::Frame &frame) {-  if (deny(session, frame.request_id, true))-    return true;-  if (session.quota_bytes > 0 &&-      storage_usage(quota_dir(session)) + QUOTA_RESERVE >=-          session.quota_bytes) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,-                      "storage quota exceeded");-    return true;-  }-  auto updates = proto::decode_update_refs(bytes_of(frame.payload));-  if (!updates) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                      "bad UPDATE_REFS");-    return true;-  }-  auto tx = Txn::begin(session.repo_root, session.store);-  if (!tx) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,-                      "cannot update refs");-    return true;-  }-  for (const auto &update : *updates) {-    if (!ref_matches(tx->view(), update.name, update.expected)) {-      wire::write_error(session.stream, frame.request_id,-                        wire::ERR_REF_CONFLICT, "ref changed");-      return true;+bool handle_update_refs(Session& session, const wire::Frame& frame) {+    if (deny(session, frame.request_id, true))+        return true;+    if (session.quota_bytes > 0 &&+        storage_usage(quota_dir(session)) + QUOTA_RESERVE >= session.quota_bytes) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_QUOTA,+                          "storage quota exceeded");+        return true;     }-  }-  for (const auto &update : *updates)-    apply_ref(tx->view(), update.name, update.target);-  rebuild_heads(tx->view());-  const auto status = tx->finish("remote push");-  if (!status) {-    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,-                      "commit failed");-    return true;-  }-  session.store.refresh(session.repo_root);-  const std::string line = std::to_string(unix_now_millis()) + " " +-                           base32_text(bytes_of(session.fingerprint)) +-                           " update-refs\n";-  log_line(session, line);-  return wire::write_simple(session.stream, wire::UPDATE_REFS_OK,-                            frame.request_id);+    auto updates = proto::decode_update_refs(bytes_of(frame.payload));+    if (!updates) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "bad UPDATE_REFS");+        return true;+    }+    auto tx = Txn::begin(session.repo_root, session.store);+    if (!tx) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,+                          "cannot update refs");+        return true;+    }+    for (const auto& update : *updates) {+        if (!ref_matches(tx->view(), update.name, update.expected)) {+            wire::write_error(session.stream, frame.request_id, wire::ERR_REF_CONFLICT,+                              "ref changed");+            return true;+        }+    }+    for (const auto& update : *updates)+        apply_ref(tx->view(), update.name, update.target);+    rebuild_heads(tx->view());+    const auto status = tx->finish("remote push");+    if (!status) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL, "commit failed");+        return true;+    }+    session.store.refresh(session.repo_root);+    const std::string line = std::to_string(unix_now_millis()) + " " ++                             base32_text(bytes_of(session.fingerprint)) + " update-refs\n";+    log_line(session, line);+    return wire::write_simple(session.stream, wire::UPDATE_REFS_OK, frame.request_id); } -bool dispatch(Session &session, const wire::Frame &frame) {-  if (frame.kind == wire::HELLO)-    return handle_hello(session, frame, !session.root.empty());-  if (frame.kind == wire::AUTH)-    return handle_auth(session, frame);-  if (frame.kind == wire::WHOAMI)-    return handle_whoami(session, frame);-  if (!session.repo_present) {-    wire::write_error(session.stream, frame.request_id,-                      wire::ERR_UNAUTHENTICATED, "authentication required");+bool dispatch(Session& session, const wire::Frame& frame) {+    if (frame.kind == wire::HELLO)+        return handle_hello(session, frame, !session.root.empty());+    if (frame.kind == wire::AUTH)+        return handle_auth(session, frame);+    if (frame.kind == wire::WHOAMI)+        return handle_whoami(session, frame);+    if (!session.repo_present) {+        wire::write_error(session.stream, frame.request_id, wire::ERR_UNAUTHENTICATED,+                          "authentication required");+        return true;+    }+    if (frame.kind == wire::LIST_REFS)+        return handle_list_refs(session, frame);+    if (frame.kind == wire::NEGOTIATE)+        return handle_negotiate(session, frame);+    if (frame.kind == wire::FETCH_SKELETON)+        return handle_fetch(session, frame);+    if (frame.kind == wire::GET_CHUNKS)+        return handle_get_chunks(session, frame);+    if (frame.kind == wire::HAVE_QUERY)+        return handle_have_query(session, frame);+    if (frame.kind == wire::PUT_RECORDS)+        return handle_put_records(session, frame);+    if (frame.kind == wire::UPDATE_REFS)+        return handle_update_refs(session, frame);+    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME, "unknown request");     return true;-  }-  if (frame.kind == wire::LIST_REFS)-    return handle_list_refs(session, frame);-  if (frame.kind == wire::NEGOTIATE)-    return handle_negotiate(session, frame);-  if (frame.kind == wire::FETCH_SKELETON)-    return handle_fetch(session, frame);-  if (frame.kind == wire::GET_CHUNKS)-    return handle_get_chunks(session, frame);-  if (frame.kind == wire::HAVE_QUERY)-    return handle_have_query(session, frame);-  if (frame.kind == wire::PUT_RECORDS)-    return handle_put_records(session, frame);-  if (frame.kind == wire::UPDATE_REFS)-    return handle_update_refs(session, frame);-  wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,-                    "unknown request");-  return true; } -void run_session(net::Stream stream, std::optional<fs::path> fixed,-                 std::optional<fs::path> root, std::string binding,-                 std::uint64_t quota_bytes) {-  Session session;-  session.stream = std::move(stream);-  session.binding = std::move(binding);-  session.quota_bytes = quota_bytes;-  if (root)-    session.root = *root;-  if (fixed) {-    session.repo_root = *fixed;-    session.repo_present = true;-    session.access = auth::load_access(session.repo_root);-    if (session.access.valid)-      open_session_store(session);-  }-  while (!session.closing) {-    auto frame = wire::read_frame(session.stream);-    if (!frame)-      break;-    const bool keep = dispatch(session, *frame);-    if (!keep)-      break;-  }-  log_outcome(session, "close");-  session.stream.close();+void run_session(net::Stream stream, std::optional<fs::path> fixed, std::optional<fs::path> root,+                 std::string binding, std::uint64_t quota_bytes) {+    Session session;+    session.stream = std::move(stream);+    session.binding = std::move(binding);+    session.quota_bytes = quota_bytes;+    if (root)+        session.root = *root;+    if (fixed) {+        session.repo_root = *fixed;+        session.repo_present = true;+        session.access = auth::load_access(session.repo_root);+        if (session.access.valid)+            open_session_store(session);+    }+    while (!session.closing) {+        auto frame = wire::read_frame(session.stream);+        if (!frame)+            break;+        const bool keep = dispatch(session, *frame);+        if (!keep)+            break;+    }+    log_outcome(session, "close");+    session.stream.close(); }  std::optional<int> parse_port(std::string_view address) {-  const auto colon = address.rfind(':');-  if (colon == std::string_view::npos || colon + 1 >= address.size())-    return std::nullopt;-  int port = 0;-  for (char c : address.substr(colon + 1)) {-    if (c < '0' || c > '9')-      return std::nullopt;-    port = port * 10 + (c - '0');-    if (port > 65535)-      return std::nullopt;-  }-  return port;+    const auto colon = address.rfind(':');+    if (colon == std::string_view::npos || colon + 1 >= address.size())+        return std::nullopt;+    int port = 0;+    for (char c : address.substr(colon + 1)) {+        if (c < '0' || c > '9')+            return std::nullopt;+        port = port * 10 + (c - '0');+        if (port > 65535)+            return std::nullopt;+    }+    return port; }  } // namespace -int serve_stdio(const fs::path &repo, std::uint64_t quota_bytes) {-  run_session(net::Stream::stdio_stream(), repo, std::nullopt, {}, quota_bytes);-  return 0;+int serve_stdio(const fs::path& repo, std::uint64_t quota_bytes) {+    run_session(net::Stream::stdio_stream(), repo, std::nullopt, {}, quota_bytes);+    return 0; } -int serve_listen(std::string_view address, const fs::path &root,-                 std::string_view cert_path, std::string_view key_path,-                 std::uint64_t quota_bytes) {-  net::ignore_sigpipe();-  auto port = parse_port(address);-  if (!port) {-    error_prefix();-    std::cout << "invalid listen address\n";-    return 1;-  }-  void *ctx = net::tls_server_ctx(cert_path, key_path);-  if (!ctx) {-    error_prefix();-    std::cout << "cannot load TLS certificate or key\n";-    return 1;-  }-  const net::Socket listener = net::tcp_listen(*port);-  if (listener == net::INVALID_SOCKET_VALUE) {-    error_prefix();-    std::cout << "cannot listen on port " << *port << "\n";-    net::tls_ctx_free(ctx);-    return 1;-  }-  info_prefix();-  std::cout << "listening on " << address << "\n";-  for (;;) {-    auto accepted = net::tcp_accept(listener);-    if (!accepted)-      break;-    void *ssl = net::tls_accept(ctx, *accepted);-    if (!ssl) {-      net::close_socket(*accepted);-      continue;+int serve_listen(std::string_view address, const fs::path& root, std::string_view cert_path,+                 std::string_view key_path, std::uint64_t quota_bytes) {+    net::ignore_sigpipe();+    auto port = parse_port(address);+    if (!port) {+        error_prefix();+        std::cout << "invalid listen address\n";+        return 1;     }-    std::array<std::uint8_t, 32> exported{};-    std::string binding;-    if (net::tls_exporter(ssl, exported.data(), exported.size())) {-      binding.assign(reinterpret_cast<const char *>(exported.data()),-                     exported.size());+    void* ctx = net::tls_server_ctx(cert_path, key_path);+    if (!ctx) {+        error_prefix();+        std::cout << "cannot load TLS certificate or key\n";+        return 1;     }-    run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root,-                std::move(binding), quota_bytes);-  }-  net::close_socket(listener);-  net::tls_ctx_free(ctx);-  return 0;+    const net::Socket listener = net::tcp_listen(*port);+    if (listener == net::INVALID_SOCKET_VALUE) {+        error_prefix();+        std::cout << "cannot listen on port " << *port << "\n";+        net::tls_ctx_free(ctx);+        return 1;+    }+    info_prefix();+    std::cout << "listening on " << address << "\n";+    for (;;) {+        auto accepted = net::tcp_accept(listener);+        if (!accepted)+            break;+        void* ssl = net::tls_accept(ctx, *accepted);+        if (!ssl) {+            net::close_socket(*accepted);+            continue;+        }+        std::array<std::uint8_t, 32> exported{};+        std::string binding;+        if (net::tls_exporter(ssl, exported.data(), exported.size())) {+            binding.assign(reinterpret_cast<const char*>(exported.data()), exported.size());+        }+        run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root, std::move(binding),+                    quota_bytes);+    }+    net::close_socket(listener);+    net::tls_ctx_free(ctx);+    return 0; }  } // namespace vn::server--- a/xveins/src/server.h+++ b/xveins/src/server.h@@ -6,9 +6,8 @@  namespace vn::server { -int serve_stdio(const fs::path &repo, std::uint64_t quota_bytes);-int serve_listen(std::string_view address, const fs::path &root,-                 std::string_view cert_path, std::string_view key_path,-                 std::uint64_t quota_bytes);+int serve_stdio(const fs::path& repo, std::uint64_t quota_bytes);+int serve_listen(std::string_view address, const fs::path& root, std::string_view cert_path,+                 std::string_view key_path, std::uint64_t quota_bytes);  } // namespace vn::server--- a/xveins/src/store.cpp+++ b/xveins/src/store.cpp@@ -18,7 +18,7 @@ } // namespace  void set_promisor_fetcher(PromisorFetcher fetcher) {-  promisor_fetcher = std::move(fetcher);+    promisor_fetcher = std::move(fetcher); }  // ---------------------------------------------------------------------------@@ -25,133 +25,137 @@ // Layout // --------------------------------------------------------------------------- -fs::path veins_dir(const fs::path &root) { return root / ".veins"; }-fs::path packs_dir(const fs::path &root) {-  return veins_dir(root) / "store" / "packs";+fs::path veins_dir(const fs::path& root) {+    return root / ".veins"; }-fs::path tmp_dir(const fs::path &root) {-  return veins_dir(root) / "store" / "tmp";+fs::path packs_dir(const fs::path& root) {+    return veins_dir(root) / "store" / "packs"; }-fs::path op_heads_dir(const fs::path &root) {-  return veins_dir(root) / "op-heads";+fs::path tmp_dir(const fs::path& root) {+    return veins_dir(root) / "store" / "tmp"; }-fs::path git_dir(const fs::path &root) { return veins_dir(root) / "git"; }-fs::path git_map_dir(const fs::path &root) {-  return veins_dir(root) / "git-map";+fs::path op_heads_dir(const fs::path& root) {+    return veins_dir(root) / "op-heads"; }-fs::path working_copy_dir(const fs::path &root) {-  return veins_dir(root) / "working-copy";+fs::path git_dir(const fs::path& root) {+    return veins_dir(root) / "git"; }-fs::path resolutions_dir(const fs::path &root) {-  return veins_dir(root) / "resolutions";+fs::path git_map_dir(const fs::path& root) {+    return veins_dir(root) / "git-map"; }-fs::path config_path(const fs::path &root) {-  return veins_dir(root) / "config";+fs::path working_copy_dir(const fs::path& root) {+    return veins_dir(root) / "working-copy"; }-fs::path format_path(const fs::path &root) {-  return veins_dir(root) / "format";+fs::path resolutions_dir(const fs::path& root) {+    return veins_dir(root) / "resolutions"; }--static std::uint64_t repo_storage_usage(const fs::path &root) {-  std::uint64_t total = 0;-  for (const auto &name : list_directory(packs_dir(root))) {-    const auto info = stat_path(packs_dir(root) / path_from_bytes(name));-    if (info && info->kind == 1)-      total += info->size;-  }-  return total;+fs::path config_path(const fs::path& root) {+    return veins_dir(root) / "config";+}+fs::path format_path(const fs::path& root) {+    return veins_dir(root) / "format"; } -std::uint64_t storage_usage(const fs::path &dir) {-  if (!stat_path(dir)) {-    return 0;-  }-  if (stat_path(format_path(dir))) {-    return repo_storage_usage(dir);-  }-  std::uint64_t total = 0;-  for (const auto &name : list_directory(dir)) {-    const fs::path child = dir / path_from_bytes(name);-    const auto info = stat_path(child);-    if (info && info->kind == 2)-      total += repo_storage_usage(child);-  }-  return total;+static std::uint64_t repo_storage_usage(const fs::path& root) {+    std::uint64_t total = 0;+    for (const auto& name : list_directory(packs_dir(root))) {+        const auto info = stat_path(packs_dir(root) / path_from_bytes(name));+        if (info && info->kind == 1)+            total += info->size;+    }+    return total; } -std::optional<fs::path> discover_repo(const fs::path &start) {-  std::error_code ec;-  fs::path current = fs::absolute(start, ec);-  if (ec)-    return std::nullopt;-  current = fs::weakly_canonical(current, ec);-  if (ec)-    return std::nullopt;-  for (;;) {-    if (path_is_file(current / ".veins" / "format"))-      return current;-    const fs::path parent = current.parent_path();-    if (parent == current || parent.empty())-      return std::nullopt;-    current = parent;-  }+std::uint64_t storage_usage(const fs::path& dir) {+    if (!stat_path(dir)) {+        return 0;+    }+    if (stat_path(format_path(dir))) {+        return repo_storage_usage(dir);+    }+    std::uint64_t total = 0;+    for (const auto& name : list_directory(dir)) {+        const fs::path child = dir / path_from_bytes(name);+        const auto info = stat_path(child);+        if (info && info->kind == 2)+            total += repo_storage_usage(child);+    }+    return total; } -static bool migrate_dir(const fs::path &from, const fs::path &to) {-  if (path_is_dir(from) && !path_is_dir(to)) {+std::optional<fs::path> discover_repo(const fs::path& start) {     std::error_code ec;-    fs::rename(from, to, ec);-    return !ec;-  }-  return true;+    fs::path current = fs::absolute(start, ec);+    if (ec)+        return std::nullopt;+    current = fs::weakly_canonical(current, ec);+    if (ec)+        return std::nullopt;+    for (;;) {+        if (path_is_file(current / ".veins" / "format"))+            return current;+        const fs::path parent = current.parent_path();+        if (parent == current || parent.empty())+            return std::nullopt;+        current = parent;+    } } -static bool ensure_layout(const fs::path &root) {-  if (!migrate_dir(veins_dir(root) / "op_heads", op_heads_dir(root)))-    return false;-  if (!migrate_dir(veins_dir(root) / "working_copy", working_copy_dir(root)))-    return false;-  const fs::path dirs[] = {-      veins_dir(root),           veins_dir(root) / "store",-      packs_dir(root),           tmp_dir(root),-      op_heads_dir(root),        git_map_dir(root),-      git_map_dir(root) / "raw", working_copy_dir(root),-      resolutions_dir(root),-  };-  for (const auto &dir : dirs) {-    if (!ensure_directory(dir))-      return false;-  }-  return true;+static bool migrate_dir(const fs::path& from, const fs::path& to) {+    if (path_is_dir(from) && !path_is_dir(to)) {+        std::error_code ec;+        fs::rename(from, to, ec);+        return !ec;+    }+    return true; } -Result<fs::path> init_repo(const fs::path &path) {-  fs::path root = path.lexically_normal();-  if (root.empty())-    root = ".";-  if (!path_is_dir(root)) {-    if (!ensure_directory(root))-      return unexpected(Error{ErrorKind::Io, 4, "init failed"});-  }-  const fs::path format = format_path(root);-  const std::string_view expected = "veins-store 1";-  if (path_exists(format)) {-    auto data = read_file(format);-    if (!data)-      return unexpected(Error{ErrorKind::Io, 3, "init failed"});-    if (!equals(bytes_of(*data), bytes_of(expected)))-      return unexpected(Error{ErrorKind::InvalidValue, 2, "init failed"});-  }-  if (!ensure_layout(root))-    return unexpected(Error{ErrorKind::Io, 4, "init failed"});-  if (!path_exists(format)) {-    if (!write_file(format, bytes_of(expected)))-      return unexpected(Error{ErrorKind::Io, 11, "init failed"});-  }-  if (!path_exists(config_path(root))) {-    (void)write_file(config_path(root), Bytes{});-  }-  return root;+static bool ensure_layout(const fs::path& root) {+    if (!migrate_dir(veins_dir(root) / "op_heads", op_heads_dir(root)))+        return false;+    if (!migrate_dir(veins_dir(root) / "working_copy", working_copy_dir(root)))+        return false;+    const fs::path dirs[] = {+        veins_dir(root),           veins_dir(root) / "store",+        packs_dir(root),           tmp_dir(root),+        op_heads_dir(root),        git_map_dir(root),+        git_map_dir(root) / "raw", working_copy_dir(root),+        resolutions_dir(root),+    };+    for (const auto& dir : dirs) {+        if (!ensure_directory(dir))+            return false;+    }+    return true;+}++Result<fs::path> init_repo(const fs::path& path) {+    fs::path root = path.lexically_normal();+    if (root.empty())+        root = ".";+    if (!path_is_dir(root)) {+        if (!ensure_directory(root))+            return unexpected(Error{ErrorKind::Io, 4, "init failed"});+    }+    const fs::path format = format_path(root);+    const std::string_view expected = "veins-store 1";+    if (path_exists(format)) {+        auto data = read_file(format);+        if (!data)+            return unexpected(Error{ErrorKind::Io, 3, "init failed"});+        if (!equals(bytes_of(*data), bytes_of(expected)))+            return unexpected(Error{ErrorKind::InvalidValue, 2, "init failed"});+    }+    if (!ensure_layout(root))+        return unexpected(Error{ErrorKind::Io, 4, "init failed"});+    if (!path_exists(format)) {+        if (!write_file(format, bytes_of(expected)))+            return unexpected(Error{ErrorKind::Io, 11, "init failed"});+    }+    if (!path_exists(config_path(root))) {+        (void)write_file(config_path(root), Bytes{});+    }+    return root; }  // ---------------------------------------------------------------------------@@ -159,128 +163,126 @@ // ---------------------------------------------------------------------------  std::optional<std::size_t> Pack::find_by_offset(std::uint64_t offset) const {-  std::size_t lo = 0;-  std::size_t hi = records.size();-  while (lo < hi) {-    const std::size_t mid = lo + (hi - lo) / 2;-    const std::uint64_t cur = records[mid].record_off;-    if (cur == offset)-      return mid;-    if (cur < offset)-      lo = mid + 1;-    else-      hi = mid;-  }-  return std::nullopt;+    std::size_t lo = 0;+    std::size_t hi = records.size();+    while (lo < hi) {+        const std::size_t mid = lo + (hi - lo) / 2;+        const std::uint64_t cur = records[mid].record_off;+        if (cur == offset)+            return mid;+        if (cur < offset)+            lo = mid + 1;+        else+            hi = mid;+    }+    return std::nullopt; }  Result<std::vector<std::uint8_t>> Pack::get(std::size_t record_index) const {-  if (record_index >= records.size())-    return fail(ErrorKind::Corrupt, 0);-  const PackRecord &rec = records[record_index];-  const auto raw_len = static_cast<std::size_t>(rec.raw_len);-  if (raw_len == 0)-    return std::vector<std::uint8_t>{};-  const auto off = static_cast<std::size_t>(rec.data_off);-  const auto stored_len = static_cast<std::size_t>(rec.stored_len);-  if (off > data.size() || stored_len > data.size() - off)-    return fail(ErrorKind::Corrupt, off);-  if (rec.compression == 0) {-    return std::vector<std::uint8_t>(-        data.begin() + static_cast<std::ptrdiff_t>(off),-        data.begin() + static_cast<std::ptrdiff_t>(off + stored_len));-  }-  std::vector<std::uint8_t> out(raw_len);-  const std::size_t n =-      ZSTD_decompress(out.data(), raw_len, data.data() + off, stored_len);-  if (ZSTD_isError(n) || n != raw_len)-    return fail(ErrorKind::Corrupt, off);-  return out;+    if (record_index >= records.size())+        return fail(ErrorKind::Corrupt, 0);+    const PackRecord& rec = records[record_index];+    const auto raw_len = static_cast<std::size_t>(rec.raw_len);+    if (raw_len == 0)+        return std::vector<std::uint8_t>{};+    const auto off = static_cast<std::size_t>(rec.data_off);+    const auto stored_len = static_cast<std::size_t>(rec.stored_len);+    if (off > data.size() || stored_len > data.size() - off)+        return fail(ErrorKind::Corrupt, off);+    if (rec.compression == 0) {+        return std::vector<std::uint8_t>(data.begin() + static_cast<std::ptrdiff_t>(off),+                                         data.begin() ++                                             static_cast<std::ptrdiff_t>(off + stored_len));+    }+    std::vector<std::uint8_t> out(raw_len);+    const std::size_t n = ZSTD_decompress(out.data(), raw_len, data.data() + off, stored_len);+    if (ZSTD_isError(n) || n != raw_len)+        return fail(ErrorKind::Corrupt, off);+    return out; }  static std::size_t pack_type_limit(std::uint8_t type) {-  return type == TYPE_CHUNK ? MAX_CHUNK_LEN : MAX_OBJECT_BODY;+    return type == TYPE_CHUNK ? MAX_CHUNK_LEN : MAX_OBJECT_BODY; }  Result<Pack> decode_pack(std::vector<std::uint8_t> data) {-  constexpr std::size_t header_len = 16;-  constexpr std::size_t record_min = 36;-  if (data.size() < header_len + 32)-    return fail(ErrorKind::UnexpectedEnd, 0);-  if (std::memcmp(data.data(), "VPK1", 4) != 0)-    return fail(ErrorKind::InvalidMagic, 0);-  Reader header(Bytes(data.data(), header_len));-  (void)header.raw(4);-  const auto version = header.u32le();-  if (!version)-    return unexpected(version.error());-  if (*version != 1)-    return fail(ErrorKind::UnsupportedVersion, 4);-  const auto count_u64 = header.u64le();-  if (!count_u64)-    return unexpected(count_u64.error());+    constexpr std::size_t header_len = 16;+    constexpr std::size_t record_min = 36;+    if (data.size() < header_len + 32)+        return fail(ErrorKind::UnexpectedEnd, 0);+    if (std::memcmp(data.data(), "VPK1", 4) != 0)+        return fail(ErrorKind::InvalidMagic, 0);+    Reader header(Bytes(data.data(), header_len));+    (void)header.raw(4);+    const auto version = header.u32le();+    if (!version)+        return unexpected(version.error());+    if (*version != 1)+        return fail(ErrorKind::UnsupportedVersion, 4);+    const auto count_u64 = header.u64le();+    if (!count_u64)+        return unexpected(count_u64.error()); -  const std::size_t body_end = data.size() - 32;-  const auto digest = blake3_hash(Bytes(data.data(), body_end));-  if (!equals(Bytes(digest.data(), digest.size()),-              Bytes(data.data() + body_end, 32)))-    return fail(ErrorKind::HashMismatch, body_end);+    const std::size_t body_end = data.size() - 32;+    const auto digest = blake3_hash(Bytes(data.data(), body_end));+    if (!equals(Bytes(digest.data(), digest.size()), Bytes(data.data() + body_end, 32)))+        return fail(ErrorKind::HashMismatch, body_end); -  if (*count_u64 > body_end / record_min)-    return fail(ErrorKind::LimitExceeded, 8);-  const std::size_t count = static_cast<std::size_t>(*count_u64);+    if (*count_u64 > body_end / record_min)+        return fail(ErrorKind::LimitExceeded, 8);+    const std::size_t count = static_cast<std::size_t>(*count_u64); -  Reader r(Bytes(data.data(), body_end));-  (void)r.raw(header_len);-  Pack pack;-  pack.records.reserve(count);-  for (std::size_t i = 0; i < count; ++i) {-    PackRecord rec;-    rec.record_off = r.offset();-    const auto id = r.id();-    if (!id)-      return unexpected(id.error());-    rec.id = *id;-    const auto kind = r.u8();-    if (!kind)-      return unexpected(kind.error());-    if (!type_valid(*kind))-      return fail(ErrorKind::InvalidValue, r.offset() - 1);-    rec.type = *kind;-    const auto comp = r.u8();-    if (!comp)-      return unexpected(comp.error());-    if (*comp > 1)-      return fail(ErrorKind::InvalidValue, r.offset() - 1);-    rec.compression = *comp;-    const std::size_t at = r.offset();-    const auto raw_len = r.varint();-    if (!raw_len)-      return unexpected(raw_len.error());-    const auto stored_len = r.varint();-    if (!stored_len)-      return unexpected(stored_len.error());-    if (*raw_len == 0)-      return fail(ErrorKind::InvalidValue, at);-    if (*raw_len > pack_type_limit(rec.type))-      return fail(ErrorKind::LimitExceeded, at);-    if (rec.compression == 0 && *raw_len != *stored_len)-      return fail(ErrorKind::InvalidValue, at);-    if (*stored_len > r.remaining())-      return fail(ErrorKind::UnexpectedEnd, at);-    rec.raw_len = *raw_len;-    rec.stored_len = *stored_len;-    rec.data_off = r.offset();-    const auto body = r.raw(static_cast<std::size_t>(*stored_len));-    if (!body)-      return unexpected(body.error());-    pack.records.push_back(rec);-  }-  if (r.offset() != body_end)-    return fail(ErrorKind::TrailingBytes, r.offset());-  std::memcpy(pack.trailer.data(), data.data() + body_end, 32);-  pack.data = std::move(data);-  return pack;+    Reader r(Bytes(data.data(), body_end));+    (void)r.raw(header_len);+    Pack pack;+    pack.records.reserve(count);+    for (std::size_t i = 0; i < count; ++i) {+        PackRecord rec;+        rec.record_off = r.offset();+        const auto id = r.id();+        if (!id)+            return unexpected(id.error());+        rec.id = *id;+        const auto kind = r.u8();+        if (!kind)+            return unexpected(kind.error());+        if (!type_valid(*kind))+            return fail(ErrorKind::InvalidValue, r.offset() - 1);+        rec.type = *kind;+        const auto comp = r.u8();+        if (!comp)+            return unexpected(comp.error());+        if (*comp > 1)+            return fail(ErrorKind::InvalidValue, r.offset() - 1);+        rec.compression = *comp;+        const std::size_t at = r.offset();+        const auto raw_len = r.varint();+        if (!raw_len)+            return unexpected(raw_len.error());+        const auto stored_len = r.varint();+        if (!stored_len)+            return unexpected(stored_len.error());+        if (*raw_len == 0)+            return fail(ErrorKind::InvalidValue, at);+        if (*raw_len > pack_type_limit(rec.type))+            return fail(ErrorKind::LimitExceeded, at);+        if (rec.compression == 0 && *raw_len != *stored_len)+            return fail(ErrorKind::InvalidValue, at);+        if (*stored_len > r.remaining())+            return fail(ErrorKind::UnexpectedEnd, at);+        rec.raw_len = *raw_len;+        rec.stored_len = *stored_len;+        rec.data_off = r.offset();+        const auto body = r.raw(static_cast<std::size_t>(*stored_len));+        if (!body)+            return unexpected(body.error());+        pack.records.push_back(rec);+    }+    if (r.offset() != body_end)+        return fail(ErrorKind::TrailingBytes, r.offset());+    std::memcpy(pack.trailer.data(), data.data() + body_end, 32);+    pack.data = std::move(data);+    return pack; }  // ---------------------------------------------------------------------------@@ -287,123 +289,117 @@ // Index // --------------------------------------------------------------------------- -std::optional<std::size_t> Index::find(const Id &id) const {-  std::size_t lo = 0;-  std::size_t hi = ids.size();-  while (lo < hi) {-    const std::size_t mid = lo + (hi - lo) / 2;-    const int c = std::memcmp(ids[mid].data(), id.data(), ID_LEN);-    if (c == 0)-      return mid;-    if (c < 0)-      lo = mid + 1;-    else-      hi = mid;-  }-  return std::nullopt;+std::optional<std::size_t> Index::find(const Id& id) const {+    std::size_t lo = 0;+    std::size_t hi = ids.size();+    while (lo < hi) {+        const std::size_t mid = lo + (hi - lo) / 2;+        const int c = std::memcmp(ids[mid].data(), id.data(), ID_LEN);+        if (c == 0)+            return mid;+        if (c < 0)+            lo = mid + 1;+        else+            hi = mid;+    }+    return std::nullopt; } -Result<Index> decode_index(-    std::vector<std::uint8_t> data,-    const std::optional<std::array<std::uint8_t, 32>> &expected_pack_trailer) {-  constexpr std::size_t base = 1032 + 64;-  if (data.size() < base)-    return fail(ErrorKind::UnexpectedEnd, 0);-  if (std::memcmp(data.data(), "VIX1", 4) != 0)-    return fail(ErrorKind::InvalidMagic, 0);-  Reader r(Bytes(data.data(), data.size()));-  (void)r.raw(4);-  const auto version = r.u32le();-  if (!version)-    return unexpected(version.error());-  if (*version != 1)-    return fail(ErrorKind::UnsupportedVersion, 4);-  std::array<std::uint32_t, 256> fanout{};-  std::uint32_t prev = 0;-  for (std::size_t i = 0; i < 256; ++i) {-    const auto v = r.u32le();-    if (!v)-      return unexpected(v.error());-    if (*v < prev)-      return fail(ErrorKind::Unsorted, r.offset() - 4);-    prev = *v;-    fanout[i] = *v;-  }-  const std::size_t body = data.size() - base;-  if (body % 40 != 0)-    return fail(ErrorKind::TrailingBytes, base);-  const std::size_t count = body / 40;-  if (count != fanout[255])-    return fail(ErrorKind::Corrupt, 1032);+Result<Index>+decode_index(std::vector<std::uint8_t> data,+             const std::optional<std::array<std::uint8_t, 32>>& expected_pack_trailer) {+    constexpr std::size_t base = 1032 + 64;+    if (data.size() < base)+        return fail(ErrorKind::UnexpectedEnd, 0);+    if (std::memcmp(data.data(), "VIX1", 4) != 0)+        return fail(ErrorKind::InvalidMagic, 0);+    Reader r(Bytes(data.data(), data.size()));+    (void)r.raw(4);+    const auto version = r.u32le();+    if (!version)+        return unexpected(version.error());+    if (*version != 1)+        return fail(ErrorKind::UnsupportedVersion, 4);+    std::array<std::uint32_t, 256> fanout{};+    std::uint32_t prev = 0;+    for (std::size_t i = 0; i < 256; ++i) {+        const auto v = r.u32le();+        if (!v)+            return unexpected(v.error());+        if (*v < prev)+            return fail(ErrorKind::Unsorted, r.offset() - 4);+        prev = *v;+        fanout[i] = *v;+    }+    const std::size_t body = data.size() - base;+    if (body % 40 != 0)+        return fail(ErrorKind::TrailingBytes, base);+    const std::size_t count = body / 40;+    if (count != fanout[255])+        return fail(ErrorKind::Corrupt, 1032); -  Index index;-  index.ids.resize(count);-  index.offsets.resize(count);-  std::memcpy(index.ids.data(), data.data() + 1032, count * 32);-  std::memcpy(index.offsets.data(), data.data() + 1032 + count * 32, count * 8);-  std::memcpy(index.pack_trailer.data(),-              data.data() + 1032 + count * 32 + count * 8, 32);-  const std::size_t index_trailer_off = data.size() - 32;-  const auto digest = blake3_hash(Bytes(data.data(), index_trailer_off));-  if (!equals(Bytes(digest.data(), digest.size()),-              Bytes(data.data() + index_trailer_off, 32)))-    return fail(ErrorKind::HashMismatch, index_trailer_off);-  if (expected_pack_trailer &&-      !equals(Bytes(index.pack_trailer.data(), 32),-              Bytes(expected_pack_trailer->data(), 32)))-    return fail(ErrorKind::Corrupt, index_trailer_off);+    Index index;+    index.ids.resize(count);+    index.offsets.resize(count);+    std::memcpy(index.ids.data(), data.data() + 1032, count * 32);+    std::memcpy(index.offsets.data(), data.data() + 1032 + count * 32, count * 8);+    std::memcpy(index.pack_trailer.data(), data.data() + 1032 + count * 32 + count * 8, 32);+    const std::size_t index_trailer_off = data.size() - 32;+    const auto digest = blake3_hash(Bytes(data.data(), index_trailer_off));+    if (!equals(Bytes(digest.data(), digest.size()), Bytes(data.data() + index_trailer_off, 32)))+        return fail(ErrorKind::HashMismatch, index_trailer_off);+    if (expected_pack_trailer &&+        !equals(Bytes(index.pack_trailer.data(), 32), Bytes(expected_pack_trailer->data(), 32)))+        return fail(ErrorKind::Corrupt, index_trailer_off); -  std::array<std::uint32_t, 256> counts{};-  for (std::size_t i = 0; i < count; ++i) {-    if (i > 0) {-      const int c =-          std::memcmp(index.ids[i - 1].data(), index.ids[i].data(), ID_LEN);-      if (c == 0)-        return fail(ErrorKind::Duplicate, 1032 + i * 32);-      if (c > 0)-        return fail(ErrorKind::Unsorted, 1032 + i * 32);+    std::array<std::uint32_t, 256> counts{};+    for (std::size_t i = 0; i < count; ++i) {+        if (i > 0) {+            const int c = std::memcmp(index.ids[i - 1].data(), index.ids[i].data(), ID_LEN);+            if (c == 0)+                return fail(ErrorKind::Duplicate, 1032 + i * 32);+            if (c > 0)+                return fail(ErrorKind::Unsorted, 1032 + i * 32);+        }+        counts[index.ids[i][0]]++;     }-    counts[index.ids[i][0]]++;-  }-  std::uint32_t running = 0;-  for (std::size_t i = 0; i < 256; ++i) {-    running += counts[i];-    if (fanout[i] != running)-      return fail(ErrorKind::Corrupt, 8 + i * 4);-  }-  return Result<Index>(std::move(index));+    std::uint32_t running = 0;+    for (std::size_t i = 0; i < 256; ++i) {+        running += counts[i];+        if (fanout[i] != running)+            return fail(ErrorKind::Corrupt, 8 + i * 4);+    }+    return Result<Index>(std::move(index)); } -static void write_u64le(std::vector<std::uint8_t> &out, std::size_t off,-                        std::uint64_t value) {-  for (int i = 0; i < 8; ++i)-    out[off + static_cast<std::size_t>(i)] =-        static_cast<std::uint8_t>((value >> (i * 8)) & 255u);+static void write_u64le(std::vector<std::uint8_t>& out, std::size_t off, std::uint64_t value) {+    for (int i = 0; i < 8; ++i)+        out[off + static_cast<std::size_t>(i)] =+            static_cast<std::uint8_t>((value >> (i * 8)) & 255u); } -std::vector<std::uint8_t>-encode_index(const std::vector<RecordMeta> &records,-             const std::array<std::uint8_t, 32> &trailer) {-  std::array<std::uint32_t, 256> counts{};-  for (const auto &rec : records)-    counts[rec.id[0]]++;-  ByteWriter w(records.size() * 40 + 128);-  w.raw("VIX1");-  w.u32le(1);-  std::uint32_t running = 0;-  for (std::size_t i = 0; i < 256; ++i) {-    running += counts[i];-    w.u32le(running);-  }-  for (const auto &rec : records)-    w.id(rec.id);-  for (const auto &rec : records)-    w.u64le(rec.offset);-  w.raw(Bytes(trailer.data(), trailer.size()));-  auto bytes = w.take();-  const auto digest = blake3_hash(bytes_of(bytes));-  bytes.insert(bytes.end(), digest.begin(), digest.end());-  return bytes;+std::vector<std::uint8_t> encode_index(const std::vector<RecordMeta>& records,+                                       const std::array<std::uint8_t, 32>& trailer) {+    std::array<std::uint32_t, 256> counts{};+    for (const auto& rec : records)+        counts[rec.id[0]]++;+    ByteWriter w(records.size() * 40 + 128);+    w.raw("VIX1");+    w.u32le(1);+    std::uint32_t running = 0;+    for (std::size_t i = 0; i < 256; ++i) {+        running += counts[i];+        w.u32le(running);+    }+    for (const auto& rec : records)+        w.id(rec.id);+    for (const auto& rec : records)+        w.u64le(rec.offset);+    w.raw(Bytes(trailer.data(), trailer.size()));+    auto bytes = w.take();+    const auto digest = blake3_hash(bytes_of(bytes));+    bytes.insert(bytes.end(), digest.begin(), digest.end());+    return bytes; }  // ---------------------------------------------------------------------------@@ -411,141 +407,135 @@ // ---------------------------------------------------------------------------  static std::vector<std::uint8_t> zstd_compress(Bytes data) {-  if (data.empty())-    return {};-  const std::size_t bound = ZSTD_compressBound(data.size());-  std::vector<std::uint8_t> out(bound);-  const std::size_t n =-      ZSTD_compress(out.data(), bound, data.data(), data.size(), 1);-  if (ZSTD_isError(n) || n >= data.size())-    return {};-  out.resize(n);-  return out;+    if (data.empty())+        return {};+    const std::size_t bound = ZSTD_compressBound(data.size());+    std::vector<std::uint8_t> out(bound);+    const std::size_t n = ZSTD_compress(out.data(), bound, data.data(), data.size(), 1);+    if (ZSTD_isError(n) || n >= data.size())+        return {};+    out.resize(n);+    return out; } -PackOutput encode_pack(const std::vector<RawObject> &objects) {-  PackOutput output;-  std::set<Id> seen;-  struct Pending {-    const RawObject *object = nullptr;-    Id id{};-    std::uint8_t compression = 0;-    std::vector<std::uint8_t> compressed;-  };-  std::vector<Pending> pending;-  pending.reserve(objects.size());-  for (const auto &object : objects) {-    if (!type_valid(object.type))-      continue;-    const Id id =-        object.id ? *object.id : object_id(object.type, bytes_of(object.body));-    if (!seen.insert(id).second)-      continue;-    pending.push_back(Pending{&object, id, 0, {}});-  }+PackOutput encode_pack(const std::vector<RawObject>& objects) {+    PackOutput output;+    std::set<Id> seen;+    struct Pending {+        const RawObject* object = nullptr;+        Id id{};+        std::uint8_t compression = 0;+        std::vector<std::uint8_t> compressed;+    };+    std::vector<Pending> pending;+    pending.reserve(objects.size());+    for (const auto& object : objects) {+        if (!type_valid(object.type))+            continue;+        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));+        if (!seen.insert(id).second)+            continue;+        pending.push_back(Pending{&object, id, 0, {}});+    } -  auto compress_one = [](Pending &item) {-    if (item.object->body.size() < 64)-      return;-    item.compressed = zstd_compress(bytes_of(item.object->body));-    item.compression = item.compressed.empty() ? 0 : 1;-  };-  if (pending.size() > 1) {-    std::size_t workers = available_cpu_count();-    if (workers == 0)-      workers = 1;-    workers = std::min<std::size_t>(workers, pending.size());-    workers = std::min<std::size_t>(workers, 16);-    if (workers > 1) {-      std::atomic<std::size_t> next{0};-      std::vector<std::thread> threads;-      threads.reserve(workers);-      for (std::size_t w = 0; w < workers; ++w) {-        threads.emplace_back([&]() {-          for (;;) {-            const std::size_t index = next.fetch_add(1);-            if (index >= pending.size())-              return;-            compress_one(pending[index]);-          }-        });-      }-      for (auto &thread : threads)-        thread.join();+    auto compress_one = [](Pending& item) {+        if (item.object->body.size() < 64)+            return;+        item.compressed = zstd_compress(bytes_of(item.object->body));+        item.compression = item.compressed.empty() ? 0 : 1;+    };+    if (pending.size() > 1) {+        std::size_t workers = available_cpu_count();+        if (workers == 0)+            workers = 1;+        workers = std::min<std::size_t>(workers, pending.size());+        workers = std::min<std::size_t>(workers, 16);+        if (workers > 1) {+            std::atomic<std::size_t> next{0};+            std::vector<std::thread> threads;+            threads.reserve(workers);+            for (std::size_t w = 0; w < workers; ++w) {+                threads.emplace_back([&]() {+                    for (;;) {+                        const std::size_t index = next.fetch_add(1);+                        if (index >= pending.size())+                            return;+                        compress_one(pending[index]);+                    }+                });+            }+            for (auto& thread : threads)+                thread.join();+        } else {+            for (auto& item : pending)+                compress_one(item);+        }     } else {-      for (auto &item : pending)-        compress_one(item);+        for (auto& item : pending)+            compress_one(item);     }-  } else {-    for (auto &item : pending)-      compress_one(item);-  } -  std::vector<RecordMeta> metas;-  metas.reserve(pending.size());-  std::size_t estimate = 16;-  for (const auto &item : pending) {-    estimate += 32 + 2 + 20 +-                (item.compression == 1 ? item.compressed.size()-                                       : item.object->body.size());-  }-  ByteWriter w(estimate);-  w.raw("VPK1");-  w.u32le(1);-  w.u64le(0);-  for (const auto &item : pending) {-    const auto &object = *item.object;-    const std::uint64_t offset = w.size();-    const Bytes stored = item.compression == 1 ? bytes_of(item.compressed)-                                               : bytes_of(object.body);-    ByteWriter rec(64);-    rec.id(item.id);-    rec.u8(object.type);-    rec.u8(item.compression);-    rec.varint(object.body.size());-    rec.varint(stored.size());-    rec.raw(stored);-    w.raw(rec.view());-    metas.push_back(-        RecordMeta{item.id, offset, object.type, object.body.size()});-  }+    std::vector<RecordMeta> metas;+    metas.reserve(pending.size());+    std::size_t estimate = 16;+    for (const auto& item : pending) {+        estimate += 32 + 2 + 20 ++                    (item.compression == 1 ? item.compressed.size() : item.object->body.size());+    }+    ByteWriter w(estimate);+    w.raw("VPK1");+    w.u32le(1);+    w.u64le(0);+    for (const auto& item : pending) {+        const auto& object = *item.object;+        const std::uint64_t offset = w.size();+        const Bytes stored =+            item.compression == 1 ? bytes_of(item.compressed) : bytes_of(object.body);+        ByteWriter rec(64);+        rec.id(item.id);+        rec.u8(object.type);+        rec.u8(item.compression);+        rec.varint(object.body.size());+        rec.varint(stored.size());+        rec.raw(stored);+        w.raw(rec.view());+        metas.push_back(RecordMeta{item.id, offset, object.type, object.body.size()});+    } -  auto pack = w.take();-  write_u64le(pack, 8, static_cast<std::uint64_t>(metas.size()));-  const auto digest = blake3_hash(bytes_of(pack));-  pack.insert(pack.end(), digest.begin(), digest.end());-  std::array<std::uint8_t, 32> trailer{};-  std::memcpy(trailer.data(), digest.data(), 32);+    auto pack = w.take();+    write_u64le(pack, 8, static_cast<std::uint64_t>(metas.size()));+    const auto digest = blake3_hash(bytes_of(pack));+    pack.insert(pack.end(), digest.begin(), digest.end());+    std::array<std::uint8_t, 32> trailer{};+    std::memcpy(trailer.data(), digest.data(), 32); -  std::stable_sort(metas.begin(), metas.end(),-                   [](const RecordMeta &a, const RecordMeta &b) {-                     return std::memcmp(a.id.data(), b.id.data(), ID_LEN) < 0;-                   });-  output.index = encode_index(metas, trailer);-  output.name = hex_encode(Bytes(trailer.data(), trailer.size()));-  output.count = metas.size();-  output.pack = std::move(pack);-  return output;+    std::stable_sort(metas.begin(), metas.end(), [](const RecordMeta& a, const RecordMeta& b) {+        return std::memcmp(a.id.data(), b.id.data(), ID_LEN) < 0;+    });+    output.index = encode_index(metas, trailer);+    output.name = hex_encode(Bytes(trailer.data(), trailer.size()));+    output.count = metas.size();+    output.pack = std::move(pack);+    return output; } -int write_pack(const fs::path &root, const std::vector<RawObject> &objects,-               std::uint64_t limit) {-  PackOutput output = encode_pack(objects);-  if (output.count == 0)+int write_pack(const fs::path& root, const std::vector<RawObject>& objects, std::uint64_t limit) {+    PackOutput output = encode_pack(objects);+    if (output.count == 0)+        return 0;+    if (limit > 0 && output.pack.size() + output.index.size() > limit)+        return 2;+    const fs::path pfinal = packs_dir(root) / (output.name + ".vpack");+    const fs::path ifinal = packs_dir(root) / (output.name + ".vidx");+    const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack.tmp");+    const fs::path itmp = tmp_dir(root) / (output.name + ".vidx.tmp");+    if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))+        return 1;+    if (!write_atomic(itmp, ifinal, bytes_of(output.index))) {+        (void)remove_file(pfinal);+        return 1;+    }     return 0;-  if (limit > 0 && output.pack.size() + output.index.size() > limit)-    return 2;-  const fs::path pfinal = packs_dir(root) / (output.name + ".vpack");-  const fs::path ifinal = packs_dir(root) / (output.name + ".vidx");-  const fs::path ptmp = tmp_dir(root) / (output.name + ".vpack.tmp");-  const fs::path itmp = tmp_dir(root) / (output.name + ".vidx.tmp");-  if (!write_atomic(ptmp, pfinal, bytes_of(output.pack)))-    return 1;-  if (!write_atomic(itmp, ifinal, bytes_of(output.index))) {-    (void)remove_file(pfinal);-    return 1;-  }-  return 0; }  // ---------------------------------------------------------------------------@@ -552,180 +542,177 @@ // Store // --------------------------------------------------------------------------- -static bool handle_index(StoreHandle &handle) {-  if (handle.index)+static bool handle_index(StoreHandle& handle) {+    if (handle.index)+        return true;+    std::string name = basename_string(handle.path);+    if (name.size() <= 6)+        return false;+    name.resize(name.size() - 6);+    const fs::path idx_path = handle.path.parent_path() / (name + ".vidx");+    auto data = read_file_opt(idx_path);+    if (!data)+        return false;+    auto decoded = decode_index(std::move(*data));+    if (!decoded)+        return false;+    if (name != hex_encode(Bytes(decoded->pack_trailer.data(), 32)))+        return false;+    handle.index = std::move(*decoded);     return true;-  std::string name = basename_string(handle.path);-  if (name.size() <= 6)-    return false;-  name.resize(name.size() - 6);-  const fs::path idx_path = handle.path.parent_path() / (name + ".vidx");-  auto data = read_file_opt(idx_path);-  if (!data)-    return false;-  auto decoded = decode_index(std::move(*data));-  if (!decoded)-    return false;-  if (name != hex_encode(Bytes(decoded->pack_trailer.data(), 32)))-    return false;-  handle.index = std::move(*decoded);-  return true; } -bool Store::ensure_index(StoreHandle &handle) { return handle_index(handle); }+bool Store::ensure_index(StoreHandle& handle) {+    return handle_index(handle);+} -bool Store::ensure_pack(StoreHandle &handle) {-  if (handle.pack)+bool Store::ensure_pack(StoreHandle& handle) {+    if (handle.pack)+        return true;+    if (!ensure_index(handle))+        return false;+    auto data = read_file_opt(handle.path);+    if (!data)+        return false;+    auto decoded = decode_pack(std::move(*data));+    if (!decoded)+        return false;+    if (!equals(Bytes(decoded->trailer.data(), 32), Bytes(handle.index->pack_trailer.data(), 32)))+        return false;+    handle.pack = std::move(*decoded);     return true;-  if (!ensure_index(handle))-    return false;-  auto data = read_file_opt(handle.path);-  if (!data)-    return false;-  auto decoded = decode_pack(std::move(*data));-  if (!decoded)-    return false;-  if (!equals(Bytes(decoded->trailer.data(), 32),-              Bytes(handle.index->pack_trailer.data(), 32)))-    return false;-  handle.pack = std::move(*decoded);-  return true; } -static std::uint64_t handle_mtime(const fs::path &path) {-  const auto info = stat_path(path);-  return info ? info->mtime_ns : 0;+static std::uint64_t handle_mtime(const fs::path& path) {+    const auto info = stat_path(path);+    return info ? info->mtime_ns : 0; } -Store Store::open_all(const fs::path &root) {-  Store store;-  store.root_ = root;-  for (const auto &name : list_directory(packs_dir(root))) {-    if (name.size() <= 6)-      continue;-    if (name.compare(name.size() - 6, 6, ".vpack") != 0)-      continue;-    StoreHandle handle;-    handle.path = packs_dir(root) / path_from_bytes(name);-    handle.mtime_ns = handle_mtime(handle.path);-    store.handles_.push_back(std::move(handle));-  }-  std::stable_sort(store.handles_.begin(), store.handles_.end(),-                   [](const StoreHandle &a, const StoreHandle &b) {-                     return a.mtime_ns >= b.mtime_ns;-                   });-  return store;+Store Store::open_all(const fs::path& root) {+    Store store;+    store.root_ = root;+    for (const auto& name : list_directory(packs_dir(root))) {+        if (name.size() <= 6)+            continue;+        if (name.compare(name.size() - 6, 6, ".vpack") != 0)+            continue;+        StoreHandle handle;+        handle.path = packs_dir(root) / path_from_bytes(name);+        handle.mtime_ns = handle_mtime(handle.path);+        store.handles_.push_back(std::move(handle));+    }+    std::stable_sort(+        store.handles_.begin(), store.handles_.end(),+        [](const StoreHandle& a, const StoreHandle& b) { return a.mtime_ns >= b.mtime_ns; });+    return store; }  void Store::preload() {-  for (auto &handle : handles_) {-    (void)ensure_index(handle);-    (void)ensure_pack(handle);-  }+    for (auto& handle : handles_) {+        (void)ensure_index(handle);+        (void)ensure_pack(handle);+    } } -void Store::refresh(const fs::path &root) {-  for (const auto &name : list_directory(packs_dir(root))) {-    if (name.size() <= 6)-      continue;-    if (name.compare(name.size() - 6, 6, ".vpack") != 0)-      continue;-    const fs::path path = packs_dir(root) / path_from_bytes(name);-    bool found = false;-    for (const auto &handle : handles_) {-      if (handle.path == path) {-        found = true;-        break;-      }-    }-    if (!found) {-      StoreHandle handle;-      handle.path = path;-      handle.mtime_ns = handle_mtime(path);-      handles_.push_back(std::move(handle));+void Store::refresh(const fs::path& root) {+    for (const auto& name : list_directory(packs_dir(root))) {+        if (name.size() <= 6)+            continue;+        if (name.compare(name.size() - 6, 6, ".vpack") != 0)+            continue;+        const fs::path path = packs_dir(root) / path_from_bytes(name);+        bool found = false;+        for (const auto& handle : handles_) {+            if (handle.path == path) {+                found = true;+                break;+            }+        }+        if (!found) {+            StoreHandle handle;+            handle.path = path;+            handle.mtime_ns = handle_mtime(path);+            handles_.push_back(std::move(handle));+        }     }-  }-  std::stable_sort(handles_.begin(), handles_.end(),-                   [](const StoreHandle &a, const StoreHandle &b) {-                     return a.mtime_ns >= b.mtime_ns;-                   });+    std::stable_sort(+        handles_.begin(), handles_.end(),+        [](const StoreHandle& a, const StoreHandle& b) { return a.mtime_ns >= b.mtime_ns; }); } -std::optional<Loc> Store::find(const Id &id) {-  for (std::size_t i = 0; i < handles_.size(); ++i) {-    auto &handle = handles_[i];-    if (!ensure_index(handle))-      continue;-    const auto pos = handle.index->find(id);-    if (!pos)-      continue;-    const std::uint64_t offset = handle.index->offsets[*pos];-    if (!ensure_pack(handle))-      continue;-    const auto rec = handle.pack->find_by_offset(offset);-    if (!rec)-      continue;-    return Loc{i, *rec, handle.pack->records[*rec].type};-  }-  return std::nullopt;+std::optional<Loc> Store::find(const Id& id) {+    for (std::size_t i = 0; i < handles_.size(); ++i) {+        auto& handle = handles_[i];+        if (!ensure_index(handle))+            continue;+        const auto pos = handle.index->find(id);+        if (!pos)+            continue;+        const std::uint64_t offset = handle.index->offsets[*pos];+        if (!ensure_pack(handle))+            continue;+        const auto rec = handle.pack->find_by_offset(offset);+        if (!rec)+            continue;+        return Loc{i, *rec, handle.pack->records[*rec].type};+    }+    return std::nullopt; } -Result<std::vector<std::uint8_t>> Store::get(const Loc &loc) {-  if (loc.pack_index >= handles_.size())-    return fail(ErrorKind::Corrupt, 0);-  auto &handle = handles_[loc.pack_index];-  if (!ensure_pack(handle))-    return fail(ErrorKind::Corrupt, 0);-  return handle.pack->get(loc.record_index);+Result<std::vector<std::uint8_t>> Store::get(const Loc& loc) {+    if (loc.pack_index >= handles_.size())+        return fail(ErrorKind::Corrupt, 0);+    auto& handle = handles_[loc.pack_index];+    if (!ensure_pack(handle))+        return fail(ErrorKind::Corrupt, 0);+    return handle.pack->get(loc.record_index); } -std::optional<std::vector<std::uint8_t>>-Store::read_body(const Id &id, std::uint8_t expected) {-  auto loc = find(id);-  if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {-    if (promisor_fetcher(root_, id)) {-      refresh(root_);-      loc = find(id);+std::optional<std::vector<std::uint8_t>> Store::read_body(const Id& id, std::uint8_t expected) {+    auto loc = find(id);+    if (!loc && expected == TYPE_CHUNK && promisor_fetcher && !root_.empty()) {+        if (promisor_fetcher(root_, id)) {+            refresh(root_);+            loc = find(id);+        }     }-  }-  if (!loc || loc->kind != expected)-    return std::nullopt;-  auto body = get(*loc);-  if (!body)-    return std::nullopt;-  const Id computed = object_id(expected, bytes_of(*body));-  if (std::memcmp(computed.data(), id.data(), ID_LEN) != 0)-    return std::nullopt;-  return std::move(*body);+    if (!loc || loc->kind != expected)+        return std::nullopt;+    auto body = get(*loc);+    if (!body)+        return std::nullopt;+    const Id computed = object_id(expected, bytes_of(*body));+    if (std::memcmp(computed.data(), id.data(), ID_LEN) != 0)+        return std::nullopt;+    return std::move(*body); } -std::optional<View> Store::read_view(const Id &id) {-  auto body = read_body(id, TYPE_VIEW);-  if (!body)-    return std::nullopt;-  auto view = decode_view(bytes_of(*body));-  if (!view)-    return std::nullopt;-  return std::move(*view);+std::optional<View> Store::read_view(const Id& id) {+    auto body = read_body(id, TYPE_VIEW);+    if (!body)+        return std::nullopt;+    auto view = decode_view(bytes_of(*body));+    if (!view)+        return std::nullopt;+    return std::move(*view); } -std::optional<Operation> Store::read_operation(const Id &id) {-  auto body = read_body(id, TYPE_OPERATION);-  if (!body)-    return std::nullopt;-  auto op = decode_operation(bytes_of(*body));-  if (!op)-    return std::nullopt;-  return std::move(*op);+std::optional<Operation> Store::read_operation(const Id& id) {+    auto body = read_body(id, TYPE_OPERATION);+    if (!body)+        return std::nullopt;+    auto op = decode_operation(bytes_of(*body));+    if (!op)+        return std::nullopt;+    return std::move(*op); } -bool Store::has_promisor(const fs::path &root) const {-  auto data = read_file_opt(config_path(root));-  if (!data)-    return false;-  const std::string_view text(reinterpret_cast<const char *>(data->data()),-                              data->size());-  return text.find("promisor") != std::string_view::npos;+bool Store::has_promisor(const fs::path& root) const {+    auto data = read_file_opt(config_path(root));+    if (!data)+        return false;+    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    return text.find("promisor") != std::string_view::npos; }  // ---------------------------------------------------------------------------@@ -732,82 +719,78 @@ // Writer // --------------------------------------------------------------------------- -Id Writer::add(std::uint8_t type, const std::vector<std::uint8_t> &body) {-  const Id id = object_id(type, bytes_of(body));-  if (quota_hit_ || !seen_.insert(id).second)-    return id;-  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {-    quota_hit_ = true;+Id Writer::add(std::uint8_t type, const std::vector<std::uint8_t>& body) {+    const Id id = object_id(type, bytes_of(body));+    if (quota_hit_ || !seen_.insert(id).second)+        return id;+    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+        quota_hit_ = true;+        return id;+    }+    raw_bytes_ += body.size();+    objects_.push_back(RawObject{type, body, id});+    if (type != TYPE_CHUNK || cache_chunks_)+        cache_.push_back(RawObject{type, body, id});     return id;-  }-  raw_bytes_ += body.size();-  objects_.push_back(RawObject{type, body, id});-  if (type != TYPE_CHUNK || cache_chunks_)-    cache_.push_back(RawObject{type, body, id});-  return id; } -Id Writer::add(std::uint8_t type, std::vector<std::uint8_t> &&body) {-  const Id id = object_id(type, bytes_of(body));-  if (quota_hit_ || !seen_.insert(id).second)-    return id;-  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {-    quota_hit_ = true;+Id Writer::add(std::uint8_t type, std::vector<std::uint8_t>&& body) {+    const Id id = object_id(type, bytes_of(body));+    if (quota_hit_ || !seen_.insert(id).second)+        return id;+    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+        quota_hit_ = true;+        return id;+    }+    raw_bytes_ += body.size();+    if (type != TYPE_CHUNK || cache_chunks_)+        cache_.push_back(RawObject{type, body, id});+    objects_.push_back(RawObject{type, std::move(body), id});     return id;-  }-  raw_bytes_ += body.size();-  if (type != TYPE_CHUNK || cache_chunks_)-    cache_.push_back(RawObject{type, body, id});-  objects_.push_back(RawObject{type, std::move(body), id});-  return id; } -Id Writer::add_known(std::uint8_t type, const Id &id,-                     const std::vector<std::uint8_t> &body) {-  if (quota_hit_ || !seen_.insert(id).second)-    return id;-  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {-    quota_hit_ = true;+Id Writer::add_known(std::uint8_t type, const Id& id, const std::vector<std::uint8_t>& body) {+    if (quota_hit_ || !seen_.insert(id).second)+        return id;+    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+        quota_hit_ = true;+        return id;+    }+    raw_bytes_ += body.size();+    objects_.push_back(RawObject{type, body, id});+    if (type != TYPE_CHUNK || cache_chunks_)+        cache_.push_back(RawObject{type, body, id});     return id;-  }-  raw_bytes_ += body.size();-  objects_.push_back(RawObject{type, body, id});-  if (type != TYPE_CHUNK || cache_chunks_)-    cache_.push_back(RawObject{type, body, id});-  return id; } -Id Writer::add_known(std::uint8_t type, const Id &id,-                     std::vector<std::uint8_t> &&body) {-  if (quota_hit_ || !seen_.insert(id).second)-    return id;-  if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {-    quota_hit_ = true;+Id Writer::add_known(std::uint8_t type, const Id& id, std::vector<std::uint8_t>&& body) {+    if (quota_hit_ || !seen_.insert(id).second)+        return id;+    if (limit_ > 0 && raw_bytes_ + body.size() > limit_) {+        quota_hit_ = true;+        return id;+    }+    raw_bytes_ += body.size();+    if (type != TYPE_CHUNK || cache_chunks_)+        cache_.push_back(RawObject{type, body, id});+    objects_.push_back(RawObject{type, std::move(body), id});     return id;-  }-  raw_bytes_ += body.size();-  if (type != TYPE_CHUNK || cache_chunks_)-    cache_.push_back(RawObject{type, body, id});-  objects_.push_back(RawObject{type, std::move(body), id});-  return id; } -std::optional<std::vector<std::uint8_t>>-Writer::find_cached(std::uint8_t type, const Id &id) const {-  for (const auto &object : cache_) {-    const Id candidate =-        object.id ? *object.id : object_id(type, bytes_of(object.body));-    if (object.type == type &&-        std::memcmp(candidate.data(), id.data(), ID_LEN) == 0)-      return object.body;-  }-  return std::nullopt;+std::optional<std::vector<std::uint8_t>> Writer::find_cached(std::uint8_t type,+                                                             const Id& id) const {+    for (const auto& object : cache_) {+        const Id candidate = object.id ? *object.id : object_id(type, bytes_of(object.body));+        if (object.type == type && std::memcmp(candidate.data(), id.data(), ID_LEN) == 0)+            return object.body;+    }+    return std::nullopt; } -int Writer::finish(const fs::path &root) {-  if (quota_hit_)-    return 2;-  return write_pack(root, objects_, limit_);+int Writer::finish(const fs::path& root) {+    if (quota_hit_)+        return 2;+    return write_pack(root, objects_, limit_); }  // ---------------------------------------------------------------------------@@ -814,264 +797,257 @@ // View helpers // --------------------------------------------------------------------------- -static bool id_less(const Id &a, const Id &b) {-  return std::memcmp(a.data(), b.data(), ID_LEN) < 0;+static bool id_less(const Id& a, const Id& b) {+    return std::memcmp(a.data(), b.data(), ID_LEN) < 0; } -static bool id_equal(const Id &a, const Id &b) {-  return std::memcmp(a.data(), b.data(), ID_LEN) == 0;+static bool id_equal(const Id& a, const Id& b) {+    return std::memcmp(a.data(), b.data(), ID_LEN) == 0; }  namespace { struct IdHash {-  std::size_t operator()(const Id &id) const noexcept {-    std::size_t h = 1469598103934665603ull;-    for (auto b : id) {-      h ^= b;-      h *= 1099511628211ull;+    std::size_t operator()(const Id& id) const noexcept {+        std::size_t h = 1469598103934665603ull;+        for (auto b : id) {+            h ^= b;+            h *= 1099511628211ull;+        }+        return h;     }-    return h;-  } }; struct IdEq {-  bool operator()(const Id &a, const Id &b) const noexcept {-    return id_equal(a, b);-  }+    bool operator()(const Id& a, const Id& b) const noexcept {+        return id_equal(a, b);+    } }; } // namespace -bool contains_id(const std::vector<Id> &ids, const Id &id) {-  return std::find_if(ids.begin(), ids.end(), [&](const Id &x) {-           return id_equal(x, id);-         }) != ids.end();+bool contains_id(const std::vector<Id>& ids, const Id& id) {+    return std::find_if(ids.begin(), ids.end(), [&](const Id& x) { return id_equal(x, id); }) !=+           ids.end(); } -bool target_contains(const std::vector<std::optional<Id>> &ids, const Id &id) {-  for (const auto &x : ids) {-    if (x && id_equal(*x, id))-      return true;-  }-  return false;+bool target_contains(const std::vector<std::optional<Id>>& ids, const Id& id) {+    for (const auto& x : ids) {+        if (x && id_equal(*x, id))+            return true;+    }+    return false; } -std::optional<Id> working_copy_id(const View &view) {-  for (const auto &workspace : view.working_copies) {-    if (workspace.workspace == "default")-      return workspace.target;-  }-  return std::nullopt;+std::optional<Id> working_copy_id(const View& view) {+    for (const auto& workspace : view.working_copies) {+        if (workspace.workspace == "default")+            return workspace.target;+    }+    return std::nullopt; } -void sort_ids(std::vector<Id> &ids) {-  std::stable_sort(ids.begin(), ids.end(), id_less);+void sort_ids(std::vector<Id>& ids) {+    std::stable_sort(ids.begin(), ids.end(), id_less); } -void sort_view(View &view) {-  sort_ids(view.heads);-  std::stable_sort(view.bookmarks.begin(), view.bookmarks.end(),-                   [](const Bookmark &a, const Bookmark &b) {-                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                   });-  std::stable_sort(view.tags.begin(), view.tags.end(),-                   [](const TagRef &a, const TagRef &b) {-                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                   });-  std::stable_sort(view.remote_refs.begin(), view.remote_refs.end(),-                   [](const RemoteRef &a, const RemoteRef &b) {-                     const int c =-                         compare(bytes_of(a.remote), bytes_of(b.remote));-                     if (c != 0)-                       return c < 0;-                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                   });-  std::stable_sort(view.working_copies.begin(), view.working_copies.end(),-                   [](const WorkspaceRef &a, const WorkspaceRef &b) {-                     return compare(bytes_of(a.workspace),-                                    bytes_of(b.workspace)) < 0;-                   });+void sort_view(View& view) {+    sort_ids(view.heads);+    std::stable_sort(view.bookmarks.begin(), view.bookmarks.end(),+                     [](const Bookmark& a, const Bookmark& b) {+                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                     });+    std::stable_sort(view.tags.begin(), view.tags.end(), [](const TagRef& a, const TagRef& b) {+        return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+    });+    std::stable_sort(view.remote_refs.begin(), view.remote_refs.end(),+                     [](const RemoteRef& a, const RemoteRef& b) {+                         const int c = compare(bytes_of(a.remote), bytes_of(b.remote));+                         if (c != 0)+                             return c < 0;+                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                     });+    std::stable_sort(view.working_copies.begin(), view.working_copies.end(),+                     [](const WorkspaceRef& a, const WorkspaceRef& b) {+                         return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;+                     }); } -void add_unique_head(View &view, const Id &id) {-  if (!contains_id(view.heads, id))-    view.heads.push_back(id);+void add_unique_head(View& view, const Id& id) {+    if (!contains_id(view.heads, id))+        view.heads.push_back(id); } -void rebuild_heads(View &view) {-  view.heads.clear();-  for (const auto &bookmark : view.bookmarks) {-    for (const auto &id : bookmark.targets.adds) {-      if (id)-        add_unique_head(view, *id);+void rebuild_heads(View& view) {+    view.heads.clear();+    for (const auto& bookmark : view.bookmarks) {+        for (const auto& id : bookmark.targets.adds) {+            if (id)+                add_unique_head(view, *id);+        }     }-  }-  for (const auto &tag : view.tags)-    add_unique_head(view, tag.target);-  for (const auto &workspace : view.working_copies)-    add_unique_head(view, workspace.target);-  sort_ids(view.heads);+    for (const auto& tag : view.tags)+        add_unique_head(view, tag.target);+    for (const auto& workspace : view.working_copies)+        add_unique_head(view, workspace.target);+    sort_ids(view.heads); } -void set_workspace(View &view, const Id &id) {-  for (auto &workspace : view.working_copies) {-    if (workspace.workspace == "default") {-      workspace.target = id;-      return;+void set_workspace(View& view, const Id& id) {+    for (auto& workspace : view.working_copies) {+        if (workspace.workspace == "default") {+            workspace.target = id;+            return;+        }     }-  }-  view.working_copies.push_back(WorkspaceRef{"default", id});-  std::stable_sort(view.working_copies.begin(), view.working_copies.end(),-                   [](const WorkspaceRef &a, const WorkspaceRef &b) {-                     return compare(bytes_of(a.workspace),-                                    bytes_of(b.workspace)) < 0;-                   });+    view.working_copies.push_back(WorkspaceRef{"default", id});+    std::stable_sort(view.working_copies.begin(), view.working_copies.end(),+                     [](const WorkspaceRef& a, const WorkspaceRef& b) {+                         return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;+                     }); } -void remove_head(View &view, const Id &id) {-  view.heads.erase(std::remove_if(view.heads.begin(), view.heads.end(),-                                  [&](const Id &x) { return id_equal(x, id); }),-                   view.heads.end());+void remove_head(View& view, const Id& id) {+    view.heads.erase(std::remove_if(view.heads.begin(), view.heads.end(),+                                    [&](const Id& x) { return id_equal(x, id); }),+                     view.heads.end()); } -void move_bookmarks(View &view, const Id &old_id, const Id &new_id) {-  if (id_equal(old_id, new_id))-    return;-  for (auto &bookmark : view.bookmarks) {-    if (target_contains(bookmark.targets.adds, old_id)) {-      bookmark.targets.adds = {new_id};-      bookmark.targets.removes.clear();+void move_bookmarks(View& view, const Id& old_id, const Id& new_id) {+    if (id_equal(old_id, new_id))+        return;+    for (auto& bookmark : view.bookmarks) {+        if (target_contains(bookmark.targets.adds, old_id)) {+            bookmark.targets.adds = {new_id};+            bookmark.targets.removes.clear();+        }     }-  } } -void set_bookmark_target(View &view, std::string_view name, const Id &id) {-  if (auto index = find_bookmark(view, name)) {-    view.bookmarks[*index].targets.adds = {id};-    view.bookmarks[*index].targets.removes.clear();-    return;-  }-  Bookmark bookmark;-  bookmark.name = std::string(name);-  bookmark.targets.adds = {id};-  view.bookmarks.push_back(std::move(bookmark));+void set_bookmark_target(View& view, std::string_view name, const Id& id) {+    if (auto index = find_bookmark(view, name)) {+        view.bookmarks[*index].targets.adds = {id};+        view.bookmarks[*index].targets.removes.clear();+        return;+    }+    Bookmark bookmark;+    bookmark.name = std::string(name);+    bookmark.targets.adds = {id};+    view.bookmarks.push_back(std::move(bookmark)); } -std::optional<std::size_t> find_bookmark(const View &view,-                                         std::string_view name) {-  for (std::size_t i = 0; i < view.bookmarks.size(); ++i) {-    if (view.bookmarks[i].name == name)-      return i;-  }-  return std::nullopt;+std::optional<std::size_t> find_bookmark(const View& view, std::string_view name) {+    for (std::size_t i = 0; i < view.bookmarks.size(); ++i) {+        if (view.bookmarks[i].name == name)+            return i;+    }+    return std::nullopt; } -std::optional<std::size_t> find_tag(const View &view, std::string_view name) {-  for (std::size_t i = 0; i < view.tags.size(); ++i) {-    if (view.tags[i].name == name)-      return i;-  }-  return std::nullopt;+std::optional<std::size_t> find_tag(const View& view, std::string_view name) {+    for (std::size_t i = 0; i < view.tags.size(); ++i) {+        if (view.tags[i].name == name)+            return i;+    }+    return std::nullopt; } -std::vector<std::string> bookmark_names(const View &view, const Id &id) {-  std::vector<std::string> out;-  for (const auto &bookmark : view.bookmarks) {-    if (target_contains(bookmark.targets.adds, id))-      out.push_back(bookmark.name);-  }-  return out;+std::vector<std::string> bookmark_names(const View& view, const Id& id) {+    std::vector<std::string> out;+    for (const auto& bookmark : view.bookmarks) {+        if (target_contains(bookmark.targets.adds, id))+            out.push_back(bookmark.name);+    }+    return out; } -std::vector<std::string> tag_names(const View &view, const Id &id) {-  std::vector<std::string> out;-  for (const auto &tag : view.tags) {-    if (id_equal(tag.target, id))-      out.push_back(tag.name);-  }-  return out;+std::vector<std::string> tag_names(const View& view, const Id& id) {+    std::vector<std::string> out;+    for (const auto& tag : view.tags) {+        if (id_equal(tag.target, id))+            out.push_back(tag.name);+    }+    return out; } -View empty_view() { return {}; }+View empty_view() {+    return {};+} -std::vector<Id> read_heads(const fs::path &root) {-  std::vector<Id> out;-  for (const auto &name : list_directory(op_heads_dir(root))) {-    if (name.size() != 64)-      continue;-    Id id{};-    if (!hex_decode(name, MutBytes(id.data(), id.size())))-      continue;-    out.push_back(id);-  }-  sort_ids(out);-  return out;+std::vector<Id> read_heads(const fs::path& root) {+    std::vector<Id> out;+    for (const auto& name : list_directory(op_heads_dir(root))) {+        if (name.size() != 64)+            continue;+        Id id{};+        if (!hex_decode(name, MutBytes(id.data(), id.size())))+            continue;+        out.push_back(id);+    }+    sort_ids(out);+    return out; } -bool write_head(const fs::path &root, const Id &id) {-  const std::string name = hex_encode(id);-  const fs::path final_path = op_heads_dir(root) / name;-  const fs::path tmp_path = tmp_dir(root) / (name + ".tmp");-  return write_atomic(tmp_path, final_path, Bytes{});+bool write_head(const fs::path& root, const Id& id) {+    const std::string name = hex_encode(id);+    const fs::path final_path = op_heads_dir(root) / name;+    const fs::path tmp_path = tmp_dir(root) / (name + ".tmp");+    return write_atomic(tmp_path, final_path, Bytes{}); } -bool delete_head(const fs::path &root, const Id &id) {-  return remove_file(op_heads_dir(root) / hex_encode(id));+bool delete_head(const fs::path& root, const Id& id) {+    return remove_file(op_heads_dir(root) / hex_encode(id)); } -std::optional<View> current_view(const fs::path &root, Store &store) {-  const auto heads = read_heads(root);-  if (heads.empty())-    return std::nullopt;-  auto op = store.read_operation(heads.front());-  if (!op)-    return std::nullopt;-  return store.read_view(op->view);+std::optional<View> current_view(const fs::path& root, Store& store) {+    const auto heads = read_heads(root);+    if (heads.empty())+        return std::nullopt;+    auto op = store.read_operation(heads.front());+    if (!op)+        return std::nullopt;+    return store.read_view(op->view); } -static std::optional<View> load_view_for_head(Store &store, const Id &id) {-  auto op = store.read_operation(id);-  if (!op)-    return std::nullopt;-  return store.read_view(op->view);+static std::optional<View> load_view_for_head(Store& store, const Id& id) {+    auto op = store.read_operation(id);+    if (!op)+        return std::nullopt;+    return store.read_view(op->view); } -static void merge_view_into(View &dst, const View &src) {-  for (const auto &head : src.heads)-    add_unique_head(dst, head);-  for (const auto &bookmark : src.bookmarks) {-    const auto found = find_bookmark(dst, bookmark.name);-    if (!found) {-      dst.bookmarks.push_back(bookmark);-      continue;+static void merge_view_into(View& dst, const View& src) {+    for (const auto& head : src.heads)+        add_unique_head(dst, head);+    for (const auto& bookmark : src.bookmarks) {+        const auto found = find_bookmark(dst, bookmark.name);+        if (!found) {+            dst.bookmarks.push_back(bookmark);+            continue;+        }+        auto& existing = dst.bookmarks[*found];+        std::optional<Id> a =+            existing.targets.adds.empty() ? std::optional<Id>{} : existing.targets.adds.front();+        std::optional<Id> b =+            bookmark.targets.adds.empty() ? std::optional<Id>{} : bookmark.targets.adds.front();+        const bool same = a.has_value() == b.has_value() && (!a || id_equal(*a, *b));+        if (!same || existing.targets.adds.size() != bookmark.targets.adds.size()) {+            existing.targets.adds = {a, b};+            existing.targets.removes = {std::nullopt};+        }     }-    auto &existing = dst.bookmarks[*found];-    std::optional<Id> a = existing.targets.adds.empty()-                              ? std::optional<Id>{}-                              : existing.targets.adds.front();-    std::optional<Id> b = bookmark.targets.adds.empty()-                              ? std::optional<Id>{}-                              : bookmark.targets.adds.front();-    const bool same =-        a.has_value() == b.has_value() && (!a || id_equal(*a, *b));-    if (!same || existing.targets.adds.size() != bookmark.targets.adds.size()) {-      existing.targets.adds = {a, b};-      existing.targets.removes = {std::nullopt};+    for (const auto& tag : src.tags) {+        if (!find_tag(dst, tag.name))+            dst.tags.push_back(tag);     }-  }-  for (const auto &tag : src.tags) {-    if (!find_tag(dst, tag.name))-      dst.tags.push_back(tag);-  }-  for (const auto &workspace : src.working_copies) {-    bool found = false;-    for (const auto &existing : dst.working_copies) {-      if (existing.workspace == workspace.workspace) {-        found = true;-        break;-      }+    for (const auto& workspace : src.working_copies) {+        bool found = false;+        for (const auto& existing : dst.working_copies) {+            if (existing.workspace == workspace.workspace) {+                found = true;+                break;+            }+        }+        if (!found)+            dst.working_copies.push_back(workspace);     }-    if (!found)-      dst.working_copies.push_back(workspace);-  } }  // ---------------------------------------------------------------------------@@ -1078,92 +1054,91 @@ // Transactions // --------------------------------------------------------------------------- -Result<Txn> Txn::begin(const fs::path &root, Store &store) {-  Txn tx;-  tx.root_ = root;-  tx.store_ = &store;-  const auto heads = read_heads(root);-  if (heads.empty()) {-    tx.view_ = empty_view();-  } else if (heads.size() == 1) {-    auto view = load_view_for_head(store, heads.front());-    if (!view)-      return fail_io("cannot load repository state");-    tx.view_ = std::move(*view);-  } else {-    auto base = load_view_for_head(store, heads.front());-    if (!base)-      return fail_io("cannot load repository state");-    for (std::size_t i = 1; i < heads.size(); ++i) {-      auto extra = load_view_for_head(store, heads[i]);-      if (extra)-        merge_view_into(*base, *extra);+Result<Txn> Txn::begin(const fs::path& root, Store& store) {+    Txn tx;+    tx.root_ = root;+    tx.store_ = &store;+    const auto heads = read_heads(root);+    if (heads.empty()) {+        tx.view_ = empty_view();+    } else if (heads.size() == 1) {+        auto view = load_view_for_head(store, heads.front());+        if (!view)+            return fail_io("cannot load repository state");+        tx.view_ = std::move(*view);+    } else {+        auto base = load_view_for_head(store, heads.front());+        if (!base)+            return fail_io("cannot load repository state");+        for (std::size_t i = 1; i < heads.size(); ++i) {+            auto extra = load_view_for_head(store, heads[i]);+            if (extra)+                merge_view_into(*base, *extra);+        }+        add_unique_head(*base, heads.front());+        tx.view_ = std::move(*base);     }-    add_unique_head(*base, heads.front());-    tx.view_ = std::move(*base);-  }-  std::stable_sort(tx.view_.bookmarks.begin(), tx.view_.bookmarks.end(),-                   [](const Bookmark &a, const Bookmark &b) {-                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                   });-  std::stable_sort(tx.view_.tags.begin(), tx.view_.tags.end(),-                   [](const TagRef &a, const TagRef &b) {-                     return compare(bytes_of(a.name), bytes_of(b.name)) < 0;-                   });-  std::stable_sort(-      tx.view_.working_copies.begin(), tx.view_.working_copies.end(),-      [](const WorkspaceRef &a, const WorkspaceRef &b) {-        return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;-      });-  tx.parents_ = heads;-  tx.start_ms_ = unix_now_millis();-  return Result<Txn>(std::move(tx));+    std::stable_sort(tx.view_.bookmarks.begin(), tx.view_.bookmarks.end(),+                     [](const Bookmark& a, const Bookmark& b) {+                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                     });+    std::stable_sort(tx.view_.tags.begin(), tx.view_.tags.end(),+                     [](const TagRef& a, const TagRef& b) {+                         return compare(bytes_of(a.name), bytes_of(b.name)) < 0;+                     });+    std::stable_sort(tx.view_.working_copies.begin(), tx.view_.working_copies.end(),+                     [](const WorkspaceRef& a, const WorkspaceRef& b) {+                         return compare(bytes_of(a.workspace), bytes_of(b.workspace)) < 0;+                     });+    tx.parents_ = heads;+    tx.start_ms_ = unix_now_millis();+    return Result<Txn>(std::move(tx)); }  static std::string host_name() {-  if (const char *v = std::getenv("HOSTNAME"); v && *v)-    return v;-  return "localhost";+    if (const char* v = std::getenv("HOSTNAME"); v && *v)+        return v;+    return "localhost"; }  static std::string user_name() {-  if (const char *v = std::getenv("USER"); v && *v)-    return v;+    if (const char* v = std::getenv("USER"); v && *v)+        return v; #if defined(_WIN32)-  if (const char *w = std::getenv("USERNAME"); w && *w)-    return w;+    if (const char* w = std::getenv("USERNAME"); w && *w)+        return w; #endif-  return "unknown";+    return "unknown"; }  Status Txn::finish(std::string_view description) {-  sort_view(view_);-  const auto view_body = encode_view(view_);-  const Id view_id = writer_.add(TYPE_VIEW, view_body);-  const std::int64_t now = unix_now_millis();+    sort_view(view_);+    const auto view_body = encode_view(view_);+    const Id view_id = writer_.add(TYPE_VIEW, view_body);+    const std::int64_t now = unix_now_millis(); -  Operation op;-  op.parents = parents_;-  op.view = view_id;-  op.start = Reader::TimeMs{start_ms_, 0};-  op.end = Reader::TimeMs{now, 0};-  op.hostname = host_name();-  op.username = user_name();-  op.description = std::string(description);-  op.tags.push_back(KeyValue{"command", std::string(description)});-  const auto op_body = encode_operation(op);-  const Id op_id = writer_.add(TYPE_OPERATION, op_body);+    Operation op;+    op.parents = parents_;+    op.view = view_id;+    op.start = Reader::TimeMs{start_ms_, 0};+    op.end = Reader::TimeMs{now, 0};+    op.hostname = host_name();+    op.username = user_name();+    op.description = std::string(description);+    op.tags.push_back(KeyValue{"command", std::string(description)});+    const auto op_body = encode_operation(op);+    const Id op_id = writer_.add(TYPE_OPERATION, op_body); -  if (writer_.finish(root_) != 0) {-    error_prefix();-    std::cout << "failed to write object pack\n";-    return fail_io("failed to write object pack");-  }-  if (!write_head(root_, op_id))-    return fail_io("failed to write operation head");-  for (const auto &parent : parents_)-    (void)delete_head(root_, parent);-  return {};+    if (writer_.finish(root_) != 0) {+        error_prefix();+        std::cout << "failed to write object pack\n";+        return fail_io("failed to write object pack");+    }+    if (!write_head(root_, op_id))+        return fail_io("failed to write operation head");+    for (const auto& parent : parents_)+        (void)delete_head(root_, parent);+    return {}; }  // ---------------------------------------------------------------------------@@ -1170,41 +1145,40 @@ // Native commit map // --------------------------------------------------------------------------- -static fs::path native_path(const fs::path &root) {-  return git_map_dir(root) / "native";+static fs::path native_path(const fs::path& root) {+    return git_map_dir(root) / "native"; } -bool mark_native(const fs::path &root, const Id &id) {-  const std::string line = hex_encode(id) + "\n";-  return append_file(native_path(root), bytes_of(line));+bool mark_native(const fs::path& root, const Id& id) {+    const std::string line = hex_encode(id) + "\n";+    return append_file(native_path(root), bytes_of(line)); } -std::vector<Id> load_native(const fs::path &root) {-  std::vector<Id> out;-  auto data = read_file_opt(native_path(root));-  if (!data)-    return out;-  std::string_view text(reinterpret_cast<const char *>(data->data()),-                        data->size());-  std::size_t start = 0;-  while (start <= text.size()) {-    std::size_t end = text.find('\n', start);-    if (end == std::string_view::npos)-      end = text.size();-    if (end - start >= 64) {-      Id id{};-      if (hex_decode(text.substr(start, 64), MutBytes(id.data(), id.size())))-        out.push_back(id);+std::vector<Id> load_native(const fs::path& root) {+    std::vector<Id> out;+    auto data = read_file_opt(native_path(root));+    if (!data)+        return out;+    std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());+    std::size_t start = 0;+    while (start <= text.size()) {+        std::size_t end = text.find('\n', start);+        if (end == std::string_view::npos)+            end = text.size();+        if (end - start >= 64) {+            Id id{};+            if (hex_decode(text.substr(start, 64), MutBytes(id.data(), id.size())))+                out.push_back(id);+        }+        if (end == text.size())+            break;+        start = end + 1;     }-    if (end == text.size())-      break;-    start = end + 1;-  }-  return out;+    return out; } -bool is_native(const std::vector<Id> &native, const Id &id) {-  return contains_id(native, id);+bool is_native(const std::vector<Id>& native, const Id& id) {+    return contains_id(native, id); }  // ---------------------------------------------------------------------------@@ -1211,154 +1185,150 @@ // Graph // --------------------------------------------------------------------------- -std::optional<LoadedCommit> load_commit(Store &store, const Id &id) {-  auto body = store.read_body(id, TYPE_COMMIT);-  if (!body)-    return std::nullopt;-  auto commit = decode_commit(bytes_of(*body));-  if (!commit)-    return std::nullopt;-  return LoadedCommit{std::move(*commit), std::move(*body)};+std::optional<LoadedCommit> load_commit(Store& store, const Id& id) {+    auto body = store.read_body(id, TYPE_COMMIT);+    if (!body)+        return std::nullopt;+    auto commit = decode_commit(bytes_of(*body));+    if (!commit)+        return std::nullopt;+    return LoadedCommit{std::move(*commit), std::move(*body)}; } -bool has_changes(Store &store, const LoadedCommit &loaded) {-  if (!loaded.commit.parents.empty()) {-    auto parent = load_commit(store, loaded.commit.parents.front());-    if (!parent)-      return true;-    return !id_equal(parent->commit.root_tree, loaded.commit.root_tree);-  }-  const auto entries = flatten_tree(store, loaded.commit.root_tree);-  return !entries.empty();+bool has_changes(Store& store, const LoadedCommit& loaded) {+    if (!loaded.commit.parents.empty()) {+        auto parent = load_commit(store, loaded.commit.parents.front());+        if (!parent)+            return true;+        return !id_equal(parent->commit.root_tree, loaded.commit.root_tree);+    }+    const auto entries = flatten_tree(store, loaded.commit.root_tree);+    return !entries.empty(); } -std::vector<Id> collect_commits(Store &store, std::span<const Id> start) {-  std::vector<Id> out;-  std::vector<Id> stack;-  std::unordered_set<Id, IdHash, IdEq> seen;-  for (const auto &id : start) {-    if (seen.insert(id).second)-      stack.push_back(id);-  }-  while (!stack.empty()) {-    const Id id = stack.back();-    stack.pop_back();-    out.push_back(id);-    auto loaded = load_commit(store, id);-    if (!loaded)-      continue;-    for (const auto &parent : loaded->commit.parents) {-      if (seen.insert(parent).second)-        stack.push_back(parent);+std::vector<Id> collect_commits(Store& store, std::span<const Id> start) {+    std::vector<Id> out;+    std::vector<Id> stack;+    std::unordered_set<Id, IdHash, IdEq> seen;+    for (const auto& id : start) {+        if (seen.insert(id).second)+            stack.push_back(id);     }-  }-  return out;+    while (!stack.empty()) {+        const Id id = stack.back();+        stack.pop_back();+        out.push_back(id);+        auto loaded = load_commit(store, id);+        if (!loaded)+            continue;+        for (const auto& parent : loaded->commit.parents) {+            if (seen.insert(parent).second)+                stack.push_back(parent);+        }+    }+    return out; } -std::vector<Id> view_roots(const View &view) {-  std::vector<Id> out;-  auto add = [&](const Id &id) {-    if (!contains_id(out, id))-      out.push_back(id);-  };-  for (const auto &head : view.heads)-    add(head);-  for (const auto &bookmark : view.bookmarks) {-    for (const auto &id : bookmark.targets.adds) {-      if (id)-        add(*id);+std::vector<Id> view_roots(const View& view) {+    std::vector<Id> out;+    auto add = [&](const Id& id) {+        if (!contains_id(out, id))+            out.push_back(id);+    };+    for (const auto& head : view.heads)+        add(head);+    for (const auto& bookmark : view.bookmarks) {+        for (const auto& id : bookmark.targets.adds) {+            if (id)+                add(*id);+        }     }-  }-  for (const auto &tag : view.tags)-    add(tag.target);-  for (const auto &workspace : view.working_copies)-    add(workspace.target);-  return out;+    for (const auto& tag : view.tags)+        add(tag.target);+    for (const auto& workspace : view.working_copies)+        add(workspace.target);+    return out; } -std::vector<Id> all_commits(Store &store, const View &view) {-  const auto roots = view_roots(view);-  return collect_commits(store, roots);+std::vector<Id> all_commits(Store& store, const View& view) {+    const auto roots = view_roots(view);+    return collect_commits(store, roots); } -static std::optional<Id> bookmark_target(const View &view,-                                         std::string_view name) {-  for (const auto &bookmark : view.bookmarks) {-    if (bookmark.name == name) {-      if (bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front())-        return bookmark.targets.adds.front();-      return std::nullopt;+static std::optional<Id> bookmark_target(const View& view, std::string_view name) {+    for (const auto& bookmark : view.bookmarks) {+        if (bookmark.name == name) {+            if (bookmark.targets.adds.size() == 1 && bookmark.targets.adds.front())+                return bookmark.targets.adds.front();+            return std::nullopt;+        }     }-  }-  return std::nullopt;+    return std::nullopt; } -static std::optional<Id> tag_target(const View &view, std::string_view name) {-  for (const auto &tag : view.tags) {-    if (tag.name == name)-      return tag.target;-  }-  return std::nullopt;+static std::optional<Id> tag_target(const View& view, std::string_view name) {+    for (const auto& tag : view.tags) {+        if (tag.name == name)+            return tag.target;+    }+    return std::nullopt; } -static std::optional<Id> remote_target(const View &view,-                                       std::string_view text) {-  for (const auto &ref : view.remote_refs) {-    const std::string joined = ref.remote + "/" + ref.name;-    if (joined == text)-      return ref.target;-  }-  return std::nullopt;+static std::optional<Id> remote_target(const View& view, std::string_view text) {+    for (const auto& ref : view.remote_refs) {+        const std::string joined = ref.remote + "/" + ref.name;+        if (joined == text)+            return ref.target;+    }+    return std::nullopt; }  static bool is_hex_char(char c) {-  return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||-         (c >= 'A' && c <= 'F');+    return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); }  static bool is_hex_prefix(std::string_view text) {-  if (text.size() < 4 || text.size() > 64)-    return false;-  for (char c : text) {-    if (!is_hex_char(c))-      return false;-  }-  return true;+    if (text.size() < 4 || text.size() > 64)+        return false;+    for (char c : text) {+        if (!is_hex_char(c))+            return false;+    }+    return true; } -std::optional<Id> resolve_revision(Store &store, const View &view,-                                   std::string_view rev) {-  if (rev.empty() || rev == "@")-    return working_copy_id(view);-  if (auto id = bookmark_target(view, rev))-    return id;-  if (auto id = tag_target(view, rev))-    return id;-  if (auto id = remote_target(view, rev))-    return id;+std::optional<Id> resolve_revision(Store& store, const View& view, std::string_view rev) {+    if (rev.empty() || rev == "@")+        return working_copy_id(view);+    if (auto id = bookmark_target(view, rev))+        return id;+    if (auto id = tag_target(view, rev))+        return id;+    if (auto id = remote_target(view, rev))+        return id; -  const auto ids = all_commits(store, view);-  std::vector<Id> matches;-  if (is_hex_prefix(rev)) {-    for (const auto &id : ids) {-      const std::string full = hex_encode(id);-      if (base32_prefix_matches(full, rev))-        matches.push_back(id);+    const auto ids = all_commits(store, view);+    std::vector<Id> matches;+    if (is_hex_prefix(rev)) {+        for (const auto& id : ids) {+            const std::string full = hex_encode(id);+            if (base32_prefix_matches(full, rev))+                matches.push_back(id);+        }     }-  }-  if (matches.empty()) {-    for (const auto &id : ids) {-      auto loaded = load_commit(store, id);-      if (!loaded)-        continue;-      const std::string encoded = base32_encode(loaded->commit.change_id);-      if (base32_prefix_matches(encoded, rev))-        matches.push_back(id);+    if (matches.empty()) {+        for (const auto& id : ids) {+            auto loaded = load_commit(store, id);+            if (!loaded)+                continue;+            const std::string encoded = base32_encode(loaded->commit.change_id);+            if (base32_prefix_matches(encoded, rev))+                matches.push_back(id);+        }     }-  }-  if (matches.size() == 1)-    return matches.front();-  return std::nullopt;+    if (matches.size() == 1)+        return matches.front();+    return std::nullopt; }  // ---------------------------------------------------------------------------@@ -1365,164 +1335,154 @@ // Tree walking // --------------------------------------------------------------------------- -static void join_path(std::string &prefix, std::string_view name) {-  if (!prefix.empty())-    prefix.push_back('/');-  prefix.append(name);+static void join_path(std::string& prefix, std::string_view name) {+    if (!prefix.empty())+        prefix.push_back('/');+    prefix.append(name); } -static bool flatten_into(Store &store, const Id &tree_id, std::string &prefix,-                         std::vector<FlatEntry> &out, std::size_t depth) {-  if (depth > 4096)-    return false;-  auto body = store.read_body(tree_id, TYPE_TREE);-  if (!body)-    return false;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return false;-  for (const auto &entry : tree->entries) {-    const std::size_t old_size = prefix.size();-    join_path(prefix, entry.name);-    if (entry.kind == KIND_SUBTREE) {-      if (!flatten_into(store, entry.target, prefix, out, depth + 1)) {-        prefix.resize(old_size);+static bool flatten_into(Store& store, const Id& tree_id, std::string& prefix,+                         std::vector<FlatEntry>& out, std::size_t depth) {+    if (depth > 4096)         return false;-      }-      prefix.resize(old_size);-    } else {-      out.push_back(FlatEntry{prefix, entry.kind, entry.target});-      prefix.resize(old_size);+    auto body = store.read_body(tree_id, TYPE_TREE);+    if (!body)+        return false;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return false;+    for (const auto& entry : tree->entries) {+        const std::size_t old_size = prefix.size();+        join_path(prefix, entry.name);+        if (entry.kind == KIND_SUBTREE) {+            if (!flatten_into(store, entry.target, prefix, out, depth + 1)) {+                prefix.resize(old_size);+                return false;+            }+            prefix.resize(old_size);+        } else {+            out.push_back(FlatEntry{prefix, entry.kind, entry.target});+            prefix.resize(old_size);+        }     }-  }-  return true;+    return true; } -std::vector<FlatEntry> flatten_tree(Store &store, const Id &tree_id) {-  std::vector<FlatEntry> out;-  std::string prefix;-  (void)flatten_into(store, tree_id, prefix, out, 0);-  std::stable_sort(out.begin(), out.end(),-                   [](const FlatEntry &a, const FlatEntry &b) {-                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                   });-  return out;+std::vector<FlatEntry> flatten_tree(Store& store, const Id& tree_id) {+    std::vector<FlatEntry> out;+    std::string prefix;+    (void)flatten_into(store, tree_id, prefix, out, 0);+    std::stable_sort(out.begin(), out.end(), [](const FlatEntry& a, const FlatEntry& b) {+        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+    });+    return out; } -Result<std::vector<FlatEntry>> flatten_tree_checked(Store &store,-                                                    const Id &tree_id) {-  std::vector<FlatEntry> out;-  std::string prefix;-  if (!flatten_into(store, tree_id, prefix, out, 0))-    return fail(ErrorKind::Corrupt, 0);-  std::stable_sort(out.begin(), out.end(),-                   [](const FlatEntry &a, const FlatEntry &b) {-                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                   });-  return Result<std::vector<FlatEntry>>(std::move(out));+Result<std::vector<FlatEntry>> flatten_tree_checked(Store& store, const Id& tree_id) {+    std::vector<FlatEntry> out;+    std::string prefix;+    if (!flatten_into(store, tree_id, prefix, out, 0))+        return fail(ErrorKind::Corrupt, 0);+    std::stable_sort(out.begin(), out.end(), [](const FlatEntry& a, const FlatEntry& b) {+        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+    });+    return Result<std::vector<FlatEntry>>(std::move(out)); } -std::vector<FlatEntry> flatten_or_empty(Store &store,-                                        std::optional<Id> tree_id) {-  if (!tree_id)-    return {};-  return flatten_tree(store, *tree_id);+std::vector<FlatEntry> flatten_or_empty(Store& store, std::optional<Id> tree_id) {+    if (!tree_id)+        return {};+    return flatten_tree(store, *tree_id); } -const FlatEntry *find_flat(const std::vector<FlatEntry> &entries,-                           std::string_view path) {-  std::size_t lo = 0;-  std::size_t hi = entries.size();-  while (lo < hi) {-    const std::size_t mid = lo + (hi - lo) / 2;-    const int c = compare(bytes_of(entries[mid].path), bytes_of(path));-    if (c == 0)-      return &entries[mid];-    if (c < 0)-      lo = mid + 1;-    else-      hi = mid;-  }-  return nullptr;+const FlatEntry* find_flat(const std::vector<FlatEntry>& entries, std::string_view path) {+    std::size_t lo = 0;+    std::size_t hi = entries.size();+    while (lo < hi) {+        const std::size_t mid = lo + (hi - lo) / 2;+        const int c = compare(bytes_of(entries[mid].path), bytes_of(path));+        if (c == 0)+            return &entries[mid];+        if (c < 0)+            lo = mid + 1;+        else+            hi = mid;+    }+    return nullptr; } -int find_tree_name(const Tree &tree, std::string_view name) {-  std::size_t lo = 0;-  std::size_t hi = tree.entries.size();-  while (lo < hi) {-    const std::size_t mid = lo + (hi - lo) / 2;-    const int c = compare(bytes_of(tree.entries[mid].name), bytes_of(name));-    if (c == 0)-      return static_cast<int>(mid);-    if (c < 0)-      lo = mid + 1;-    else-      hi = mid;-  }-  return -1;+int find_tree_name(const Tree& tree, std::string_view name) {+    std::size_t lo = 0;+    std::size_t hi = tree.entries.size();+    while (lo < hi) {+        const std::size_t mid = lo + (hi - lo) / 2;+        const int c = compare(bytes_of(tree.entries[mid].name), bytes_of(name));+        if (c == 0)+            return static_cast<int>(mid);+        if (c < 0)+            lo = mid + 1;+        else+            hi = mid;+    }+    return -1; } -static bool conflicted_into(Store &store, const Id &tree_id,-                            std::size_t depth) {-  if (depth > 4096)-    return true;-  auto body = store.read_body(tree_id, TYPE_TREE);-  if (!body)-    return true;-  auto tree = decode_tree(bytes_of(*body));-  if (!tree)-    return true;-  for (const auto &entry : tree->entries) {-    if (entry.kind == KIND_CONFLICT)-      return true;-    if (entry.kind == KIND_SUBTREE &&-        conflicted_into(store, entry.target, depth + 1))-      return true;-  }-  return false;+static bool conflicted_into(Store& store, const Id& tree_id, std::size_t depth) {+    if (depth > 4096)+        return true;+    auto body = store.read_body(tree_id, TYPE_TREE);+    if (!body)+        return true;+    auto tree = decode_tree(bytes_of(*body));+    if (!tree)+        return true;+    for (const auto& entry : tree->entries) {+        if (entry.kind == KIND_CONFLICT)+            return true;+        if (entry.kind == KIND_SUBTREE && conflicted_into(store, entry.target, depth + 1))+            return true;+    }+    return false; } -bool tree_conflicted(Store &store, const Id &tree_id) {-  return conflicted_into(store, tree_id, 0);+bool tree_conflicted(Store& store, const Id& tree_id) {+    return conflicted_into(store, tree_id, 0); } -std::vector<TreeChange> compare_trees(Store &store, std::optional<Id> old_tree,+std::vector<TreeChange> compare_trees(Store& store, std::optional<Id> old_tree,                                       std::optional<Id> new_tree) {-  const auto old_entries = flatten_or_empty(store, old_tree);-  const auto new_entries = flatten_or_empty(store, new_tree);-  std::vector<TreeChange> out;-  std::size_t i = 0;-  std::size_t j = 0;-  while (i < old_entries.size() || j < new_entries.size()) {-    int take = 0;-    if (i >= old_entries.size())-      take = 1;-    else if (j >= new_entries.size())-      take = -1;-    else-      take =-          compare(bytes_of(old_entries[i].path), bytes_of(new_entries[j].path));-    if (take < 0) {-      out.push_back(TreeChange{old_entries[i].path, old_entries[i].kind,-                               KIND_MISSING, old_entries[i].target,-                               std::nullopt});-      ++i;-    } else if (take > 0) {-      out.push_back(TreeChange{new_entries[j].path, KIND_MISSING,-                               new_entries[j].kind, std::nullopt,-                               new_entries[j].target});-      ++j;-    } else {-      const auto &o = old_entries[i];-      const auto &n = new_entries[j];-      const bool same = o.kind == n.kind && id_equal(o.target, n.target);-      if (!same)-        out.push_back(TreeChange{o.path, o.kind, n.kind, o.target, n.target});-      ++i;-      ++j;+    const auto old_entries = flatten_or_empty(store, old_tree);+    const auto new_entries = flatten_or_empty(store, new_tree);+    std::vector<TreeChange> out;+    std::size_t i = 0;+    std::size_t j = 0;+    while (i < old_entries.size() || j < new_entries.size()) {+        int take = 0;+        if (i >= old_entries.size())+            take = 1;+        else if (j >= new_entries.size())+            take = -1;+        else+            take = compare(bytes_of(old_entries[i].path), bytes_of(new_entries[j].path));+        if (take < 0) {+            out.push_back(TreeChange{old_entries[i].path, old_entries[i].kind, KIND_MISSING,+                                     old_entries[i].target, std::nullopt});+            ++i;+        } else if (take > 0) {+            out.push_back(TreeChange{new_entries[j].path, KIND_MISSING, new_entries[j].kind,+                                     std::nullopt, new_entries[j].target});+            ++j;+        } else {+            const auto& o = old_entries[i];+            const auto& n = new_entries[j];+            const bool same = o.kind == n.kind && id_equal(o.target, n.target);+            if (!same)+                out.push_back(TreeChange{o.path, o.kind, n.kind, o.target, n.target});+            ++i;+            ++j;+        }     }-  }-  return out;+    return out; }  // ---------------------------------------------------------------------------@@ -1529,49 +1489,48 @@ // Blob content // --------------------------------------------------------------------------- -static bool append_blob_data(Store &store, const Id &id,-                             std::vector<std::uint8_t> &out,+static bool append_blob_data(Store& store, const Id& id, std::vector<std::uint8_t>& out,                              std::size_t depth) {-  if (depth > 64)-    return false;-  if (is_lazy_blob(id)) {-    auto data = git_read_lazy_blob(store.root(), id);-    if (!data)-      return false;-    out.insert(out.end(), data->begin(), data->end());-    return true;-  }-  auto body = store.read_body(id, TYPE_BLOB);-  if (!body)-    return false;-  auto blob = decode_blob(bytes_of(*body));-  if (!blob)-    return false;-  if (blob->form == BlobForm::Inline) {-    out.insert(out.end(), blob->data.begin(), blob->data.end());-    return true;-  }-  if (blob->form == BlobForm::Leaf) {-    for (const auto &entry : blob->entries) {-      auto chunk = store.read_body(entry.id, TYPE_CHUNK);-      if (!chunk)+    if (depth > 64)         return false;-      out.insert(out.end(), chunk->begin(), chunk->end());+    if (is_lazy_blob(id)) {+        auto data = git_read_lazy_blob(store.root(), id);+        if (!data)+            return false;+        out.insert(out.end(), data->begin(), data->end());+        return true;+    }+    auto body = store.read_body(id, TYPE_BLOB);+    if (!body)+        return false;+    auto blob = decode_blob(bytes_of(*body));+    if (!blob)+        return false;+    if (blob->form == BlobForm::Inline) {+        out.insert(out.end(), blob->data.begin(), blob->data.end());+        return true;+    }+    if (blob->form == BlobForm::Leaf) {+        for (const auto& entry : blob->entries) {+            auto chunk = store.read_body(entry.id, TYPE_CHUNK);+            if (!chunk)+                return false;+            out.insert(out.end(), chunk->begin(), chunk->end());+        }+        return true;+    }+    for (const auto& entry : blob->entries) {+        if (!append_blob_data(store, entry.id, out, depth + 1))+            return false;     }     return true;-  }-  for (const auto &entry : blob->entries) {-    if (!append_blob_data(store, entry.id, out, depth + 1))-      return false;-  }-  return true; } -std::optional<std::vector<std::uint8_t>> read_blob(Store &store, const Id &id) {-  std::vector<std::uint8_t> out;-  if (!append_blob_data(store, id, out, 0))-    return std::nullopt;-  return out;+std::optional<std::vector<std::uint8_t>> read_blob(Store& store, const Id& id) {+    std::vector<std::uint8_t> out;+    if (!append_blob_data(store, id, out, 0))+        return std::nullopt;+    return out; }  // ---------------------------------------------------------------------------@@ -1581,432 +1540,416 @@ namespace {  struct FsckCtx {-  fs::path root;-  bool promisor = false;-  bool verbose = false;-  std::size_t errors = 0;-  std::size_t warnings = 0;+    fs::path root;+    bool promisor = false;+    bool verbose = false;+    std::size_t errors = 0;+    std::size_t warnings = 0; }; -void fsck_report(FsckCtx &ctx, const fs::path &path, std::string_view text) {-  ++ctx.errors;-  error_prefix();-  std::cout << "fsck: " << path_display(path) << ": " << text << "\n";+void fsck_report(FsckCtx& ctx, const fs::path& path, std::string_view text) {+    ++ctx.errors;+    error_prefix();+    std::cout << "fsck: " << path_display(path) << ": " << text << "\n"; } -void fsck_report_id(FsckCtx &ctx, const fs::path &path, std::string_view text,-                    const Id &id) {-  ++ctx.errors;-  error_prefix();-  std::cout << "fsck: " << path_display(path) << ": " << text << " "-            << hex_encode(id) << "\n";+void fsck_report_id(FsckCtx& ctx, const fs::path& path, std::string_view text, const Id& id) {+    ++ctx.errors;+    error_prefix();+    std::cout << "fsck: " << path_display(path) << ": " << text << " " << hex_encode(id) << "\n"; } -void fsck_warn(FsckCtx &ctx, const fs::path &path, std::string_view text) {-  ++ctx.warnings;-  if (ctx.verbose) {-    warning_prefix();-    std::cout << "fsck: " << path_display(path) << ": " << text << "\n";-  }+void fsck_warn(FsckCtx& ctx, const fs::path& path, std::string_view text) {+    ++ctx.warnings;+    if (ctx.verbose) {+        warning_prefix();+        std::cout << "fsck: " << path_display(path) << ": " << text << "\n";+    } } -void fsck_report_decode(FsckCtx &ctx, const fs::path &path,-                        std::string_view what, const Error &error) {-  ++ctx.errors;-  error_prefix();-  std::cout << "fsck: " << path_display(path) << ": invalid " << what-            << " at byte " << error.offset << ": "-            << error_kind_name(error.kind) << "\n";+void fsck_report_decode(FsckCtx& ctx, const fs::path& path, std::string_view what,+                        const Error& error) {+    ++ctx.errors;+    error_prefix();+    std::cout << "fsck: " << path_display(path) << ": invalid " << what << " at byte "+              << error.offset << ": " << error_kind_name(error.kind) << "\n"; } -bool check_format(FsckCtx &ctx) {-  const fs::path path = format_path(ctx.root);-  auto data = read_file_opt(path);-  if (!data) {-    fsck_report(ctx, ctx.root, "missing .veins/format");-    return false;-  }-  const std::string_view expected = "veins-store 1";-  bool ok = equals(bytes_of(*data), bytes_of(expected));-  if (!ok && data->size() == expected.size() + 1) {-    ok = equals(bytes_of(*data).first(expected.size()), bytes_of(expected)) &&-         (*data)[expected.size()] == '\n';-  }-  if (!ok) {-    fsck_report(ctx, ctx.root, "unsupported .veins/format");-    return false;-  }-  return true;+bool check_format(FsckCtx& ctx) {+    const fs::path path = format_path(ctx.root);+    auto data = read_file_opt(path);+    if (!data) {+        fsck_report(ctx, ctx.root, "missing .veins/format");+        return false;+    }+    const std::string_view expected = "veins-store 1";+    bool ok = equals(bytes_of(*data), bytes_of(expected));+    if (!ok && data->size() == expected.size() + 1) {+        ok = equals(bytes_of(*data).first(expected.size()), bytes_of(expected)) &&+             (*data)[expected.size()] == '\n';+    }+    if (!ok) {+        fsck_report(ctx, ctx.root, "unsupported .veins/format");+        return false;+    }+    return true; }  std::uint8_t expected_type_for_value(std::uint8_t kind) {-  if (kind == 1 || kind == 2 || kind == 3)-    return TYPE_BLOB;-  if (kind == 4)-    return TYPE_TREE;-  if (kind == 6)-    return TYPE_CONFLICT;-  return 0;+    if (kind == 1 || kind == 2 || kind == 3)+        return TYPE_BLOB;+    if (kind == 4)+        return TYPE_TREE;+    if (kind == 6)+        return TYPE_CONFLICT;+    return 0; } -bool check_ref(FsckCtx &ctx, Store &store, const fs::path &path, const Id &id,+bool check_ref(FsckCtx& ctx, Store& store, const fs::path& path, const Id& id,                std::uint8_t expected, std::string_view what) {-  if (expected == TYPE_BLOB && is_lazy_blob(id))-    return true;-  const auto loc = store.find(id);-  if (!loc) {-    const bool promised =-        ctx.promisor && (expected == TYPE_CHUNK || expected == TYPE_BLOB);-    if (promised)-      fsck_warn(ctx, path, "missing promised object");-    if (!promised) {-      ++ctx.errors;-      error_prefix();-      std::cout << "fsck: " << path_display(path) << ": missing " << what-                << " object " << hex_encode(id) << "\n";+    if (expected == TYPE_BLOB && is_lazy_blob(id))+        return true;+    const auto loc = store.find(id);+    if (!loc) {+        const bool promised = ctx.promisor && (expected == TYPE_CHUNK || expected == TYPE_BLOB);+        if (promised)+            fsck_warn(ctx, path, "missing promised object");+        if (!promised) {+            ++ctx.errors;+            error_prefix();+            std::cout << "fsck: " << path_display(path) << ": missing " << what << " object "+                      << hex_encode(id) << "\n";+        }+        return promised;     }-    return promised;-  }-  if (loc->kind != expected) {-    ++ctx.errors;-    error_prefix();-    std::cout << "fsck: " << path_display(path) << ": object has type "-              << type_name(loc->kind) << ", expected " << type_name(expected)-              << " " << hex_encode(id) << "\n";-    return false;-  }-  return true;+    if (loc->kind != expected) {+        ++ctx.errors;+        error_prefix();+        std::cout << "fsck: " << path_display(path) << ": object has type " << type_name(loc->kind)+                  << ", expected " << type_name(expected) << " " << hex_encode(id) << "\n";+        return false;+    }+    return true; } -void check_blob_refs(FsckCtx &ctx, Store &store, const fs::path &path,-                     const Blob &blob) {-  if (blob.form == BlobForm::Inline)-    return;-  const std::uint8_t expected =-      blob.form == BlobForm::Leaf ? TYPE_CHUNK : TYPE_BLOB;-  for (const auto &entry : blob.entries) {-    (void)check_ref(ctx, store, path, entry.id, expected, "blob");-  }+void check_blob_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Blob& blob) {+    if (blob.form == BlobForm::Inline)+        return;+    const std::uint8_t expected = blob.form == BlobForm::Leaf ? TYPE_CHUNK : TYPE_BLOB;+    for (const auto& entry : blob.entries) {+        (void)check_ref(ctx, store, path, entry.id, expected, "blob");+    } } -void check_tree_refs(FsckCtx &ctx, Store &store, const fs::path &path,-                     const Tree &tree) {-  for (const auto &entry : tree.entries) {-    std::uint8_t expected = 0;-    if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||-        entry.kind == KIND_SYMLINK)-      expected = TYPE_BLOB;-    else if (entry.kind == KIND_SUBTREE)-      expected = TYPE_TREE;-    else if (entry.kind == KIND_CONFLICT)-      expected = TYPE_CONFLICT;-    if (expected != 0)-      (void)check_ref(ctx, store, path, entry.target, expected, "tree");-  }+void check_tree_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Tree& tree) {+    for (const auto& entry : tree.entries) {+        std::uint8_t expected = 0;+        if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE || entry.kind == KIND_SYMLINK)+            expected = TYPE_BLOB;+        else if (entry.kind == KIND_SUBTREE)+            expected = TYPE_TREE;+        else if (entry.kind == KIND_CONFLICT)+            expected = TYPE_CONFLICT;+        if (expected != 0)+            (void)check_ref(ctx, store, path, entry.target, expected, "tree");+    } } -void check_conflict_refs(FsckCtx &ctx, Store &store, const fs::path &path,-                         const Conflict &conflict) {-  for (const auto &value : conflict.adds) {-    const std::uint8_t expected = expected_type_for_value(value.kind);-    if (expected != 0 && value.target)-      (void)check_ref(ctx, store, path, *value.target, expected, "conflict");-  }-  for (const auto &value : conflict.removes) {-    const std::uint8_t expected = expected_type_for_value(value.kind);-    if (expected != 0 && value.target)-      (void)check_ref(ctx, store, path, *value.target, expected, "conflict");-  }+void check_conflict_refs(FsckCtx& ctx, Store& store, const fs::path& path,+                         const Conflict& conflict) {+    for (const auto& value : conflict.adds) {+        const std::uint8_t expected = expected_type_for_value(value.kind);+        if (expected != 0 && value.target)+            (void)check_ref(ctx, store, path, *value.target, expected, "conflict");+    }+    for (const auto& value : conflict.removes) {+        const std::uint8_t expected = expected_type_for_value(value.kind);+        if (expected != 0 && value.target)+            (void)check_ref(ctx, store, path, *value.target, expected, "conflict");+    } } -void check_commit_refs(FsckCtx &ctx, Store &store, const fs::path &path,-                       const Commit &commit) {-  for (const auto &parent : commit.parents)-    (void)check_ref(ctx, store, path, parent, TYPE_COMMIT, "parent commit");-  (void)check_ref(ctx, store, path, commit.root_tree, TYPE_TREE, "root tree");+void check_commit_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Commit& commit) {+    for (const auto& parent : commit.parents)+        (void)check_ref(ctx, store, path, parent, TYPE_COMMIT, "parent commit");+    (void)check_ref(ctx, store, path, commit.root_tree, TYPE_TREE, "root tree"); } -void check_operation_refs(FsckCtx &ctx, Store &store, const fs::path &path,-                          const Operation &op) {-  for (const auto &parent : op.parents)-    (void)check_ref(ctx, store, path, parent, TYPE_OPERATION,-                    "parent operation");-  (void)check_ref(ctx, store, path, op.view, TYPE_VIEW, "view");+void check_operation_refs(FsckCtx& ctx, Store& store, const fs::path& path, const Operation& op) {+    for (const auto& parent : op.parents)+        (void)check_ref(ctx, store, path, parent, TYPE_OPERATION, "parent operation");+    (void)check_ref(ctx, store, path, op.view, TYPE_VIEW, "view"); } -void check_view_refs(FsckCtx &ctx, Store &store, const fs::path &path,-                     const View &view) {-  for (const auto &head : view.heads)-    (void)check_ref(ctx, store, path, head, TYPE_COMMIT, "head commit");-  for (const auto &bookmark : view.bookmarks) {-    for (const auto &id : bookmark.targets.adds) {-      if (id)-        (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");-    }-    for (const auto &id : bookmark.targets.removes) {-      if (id)-        (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");+void check_view_refs(FsckCtx& ctx, Store& store, const fs::path& path, const View& view) {+    for (const auto& head : view.heads)+        (void)check_ref(ctx, store, path, head, TYPE_COMMIT, "head commit");+    for (const auto& bookmark : view.bookmarks) {+        for (const auto& id : bookmark.targets.adds) {+            if (id)+                (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");+        }+        for (const auto& id : bookmark.targets.removes) {+            if (id)+                (void)check_ref(ctx, store, path, *id, TYPE_COMMIT, "bookmark");+        }     }-  }-  for (const auto &tag : view.tags)-    (void)check_ref(ctx, store, path, tag.target, TYPE_COMMIT, "tag");-  for (const auto &ref : view.remote_refs)-    (void)check_ref(ctx, store, path, ref.target, TYPE_COMMIT, "remote ref");-  for (const auto &workspace : view.working_copies)-    (void)check_ref(ctx, store, path, workspace.target, TYPE_COMMIT,-                    "working copy");+    for (const auto& tag : view.tags)+        (void)check_ref(ctx, store, path, tag.target, TYPE_COMMIT, "tag");+    for (const auto& ref : view.remote_refs)+        (void)check_ref(ctx, store, path, ref.target, TYPE_COMMIT, "remote ref");+    for (const auto& workspace : view.working_copies)+        (void)check_ref(ctx, store, path, workspace.target, TYPE_COMMIT, "working copy"); } -void check_object(FsckCtx &ctx, Store &store, const fs::path &path,-                  const Id &id, std::uint8_t kind, Bytes body) {-  const Id computed = object_id(kind, body);-  if (!id_equal(computed, id)) {-    fsck_report_id(ctx, path, "hash mismatch for", id);-    return;-  }-  switch (kind) {-  case TYPE_CHUNK:-    if (body.empty() || body.size() > MAX_CHUNK_LEN)-      fsck_report_id(ctx, path, "invalid chunk length for", id);-    return;-  case TYPE_BLOB: {-    auto blob = decode_blob(body);-    if (!blob) {-      fsck_report_decode(ctx, path, "blob", blob.error());-      return;-    }-    check_blob_refs(ctx, store, path, *blob);-    return;-  }-  case TYPE_TREE: {-    auto tree = decode_tree(body);-    if (!tree) {-      fsck_report_decode(ctx, path, "tree", tree.error());-      return;-    }-    check_tree_refs(ctx, store, path, *tree);-    return;-  }-  case TYPE_CONFLICT: {-    auto conflict = decode_conflict(body);-    if (!conflict) {-      fsck_report_decode(ctx, path, "conflict", conflict.error());-      return;-    }-    check_conflict_refs(ctx, store, path, *conflict);-    return;-  }-  case TYPE_COMMIT: {-    auto commit = decode_commit(body);-    if (!commit) {-      fsck_report_decode(ctx, path, "commit", commit.error());-      return;-    }-    check_commit_refs(ctx, store, path, *commit);-    return;-  }-  case TYPE_OPERATION: {-    auto op = decode_operation(body);-    if (!op) {-      fsck_report_decode(ctx, path, "operation", op.error());-      return;+void check_object(FsckCtx& ctx, Store& store, const fs::path& path, const Id& id, std::uint8_t kind,+                  Bytes body) {+    const Id computed = object_id(kind, body);+    if (!id_equal(computed, id)) {+        fsck_report_id(ctx, path, "hash mismatch for", id);+        return;     }-    check_operation_refs(ctx, store, path, *op);-    return;-  }-  case TYPE_VIEW: {-    auto view = decode_view(body);-    if (!view) {-      fsck_report_decode(ctx, path, "view", view.error());-      return;+    switch (kind) {+    case TYPE_CHUNK:+        if (body.empty() || body.size() > MAX_CHUNK_LEN)+            fsck_report_id(ctx, path, "invalid chunk length for", id);+        return;+    case TYPE_BLOB: {+        auto blob = decode_blob(body);+        if (!blob) {+            fsck_report_decode(ctx, path, "blob", blob.error());+            return;+        }+        check_blob_refs(ctx, store, path, *blob);+        return;     }-    check_view_refs(ctx, store, path, *view);-    return;-  }-  default:-    return;-  }-}--} // namespace--static void check_op_log(FsckCtx &ctx, Store &store) {-  const fs::path dir = op_heads_dir(ctx.root);-  if (!path_is_dir(dir)) {-    fsck_report(ctx, dir, "missing op-heads directory");-    return;-  }-  std::vector<Id> frontier;-  for (const auto &name : list_directory(dir)) {-    if (name.size() != 64) {-      fsck_report(ctx, dir, "op-heads entry is not a 64-character id");-      continue;+    case TYPE_TREE: {+        auto tree = decode_tree(body);+        if (!tree) {+            fsck_report_decode(ctx, path, "tree", tree.error());+            return;+        }+        check_tree_refs(ctx, store, path, *tree);+        return;     }-    Id id{};-    if (!hex_decode(name, MutBytes(id.data(), id.size()))) {-      fsck_report(ctx, dir, "op-heads entry is not hexadecimal");-      continue;+    case TYPE_CONFLICT: {+        auto conflict = decode_conflict(body);+        if (!conflict) {+            fsck_report_decode(ctx, path, "conflict", conflict.error());+            return;+        }+        check_conflict_refs(ctx, store, path, *conflict);+        return;     }-    frontier.push_back(id);-  }-  std::unordered_set<Id, IdHash, IdEq> seen;-  while (!frontier.empty()) {-    const Id id = frontier.back();-    frontier.pop_back();-    if (!seen.insert(id).second)-      continue;-    const auto loc = store.find(id);-    if (!loc) {-      fsck_report_id(ctx, dir, "operation head or parent is missing:", id);-      continue;+    case TYPE_COMMIT: {+        auto commit = decode_commit(body);+        if (!commit) {+            fsck_report_decode(ctx, path, "commit", commit.error());+            return;+        }+        check_commit_refs(ctx, store, path, *commit);+        return;     }-    if (loc->kind != TYPE_OPERATION) {-      fsck_report_id(ctx, dir, "op-log entry is not an operation:", id);-      continue;+    case TYPE_OPERATION: {+        auto op = decode_operation(body);+        if (!op) {+            fsck_report_decode(ctx, path, "operation", op.error());+            return;+        }+        check_operation_refs(ctx, store, path, *op);+        return;     }-    auto body = store.get(*loc);-    if (!body) {-      fsck_report_decode(ctx, dir, "operation", body.error());-      continue;+    case TYPE_VIEW: {+        auto view = decode_view(body);+        if (!view) {+            fsck_report_decode(ctx, path, "view", view.error());+            return;+        }+        check_view_refs(ctx, store, path, *view);+        return;     }-    auto op = decode_operation(bytes_of(*body));-    if (!op) {-      fsck_report_decode(ctx, dir, "operation", op.error());-      continue;+    default:+        return;     }-    for (const auto &parent : op->parents)-      frontier.push_back(parent);-    (void)check_ref(ctx, store, dir, op->view, TYPE_VIEW, "operation view");-  } } -int fsck_repository(const fs::path &root, bool verbose) {-  FsckCtx ctx;-  ctx.root = root;-  ctx.verbose = verbose;-  std::vector<StoreHandle> handles;-  if (check_format(ctx)) {-    auto cfg = read_file_opt(config_path(root));-    if (cfg) {-      const std::string_view text(reinterpret_cast<const char *>(cfg->data()),-                                  cfg->size());-      ctx.promisor = text.find("promisor") != std::string_view::npos;-    }-    const fs::path dir = packs_dir(root);+} // namespace++static void check_op_log(FsckCtx& ctx, Store& store) {+    const fs::path dir = op_heads_dir(ctx.root);     if (!path_is_dir(dir)) {-      fsck_report(ctx, dir, "missing store/packs directory");-    } else {-      const auto names = list_directory(dir);-      for (const auto &name : names) {-        if (name.size() > 5 && name.compare(name.size() - 5, 5, ".vidx") == 0) {-          std::string pack_name = name.substr(0, name.size() - 5) + ".vpack";-          const fs::path ppath = dir / path_from_bytes(pack_name);-          if (!path_is_file(ppath))-            fsck_report(ctx, ppath, "index has no pack");+        fsck_report(ctx, dir, "missing op-heads directory");+        return;+    }+    std::vector<Id> frontier;+    for (const auto& name : list_directory(dir)) {+        if (name.size() != 64) {+            fsck_report(ctx, dir, "op-heads entry is not a 64-character id");+            continue;         }-      }-      for (const auto &name : names) {-        if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)-          continue;-        const fs::path ppath = dir / path_from_bytes(name);-        auto pdata = read_file_opt(ppath);-        if (!pdata) {-          fsck_report(ctx, ppath, "cannot read pack");-          continue;+        Id id{};+        if (!hex_decode(name, MutBytes(id.data(), id.size()))) {+            fsck_report(ctx, dir, "op-heads entry is not hexadecimal");+            continue;         }-        auto pack = decode_pack(std::move(*pdata));-        if (!pack) {-          fsck_report_decode(ctx, ppath, "pack", pack.error());-          continue;+        frontier.push_back(id);+    }+    std::unordered_set<Id, IdHash, IdEq> seen;+    while (!frontier.empty()) {+        const Id id = frontier.back();+        frontier.pop_back();+        if (!seen.insert(id).second)+            continue;+        const auto loc = store.find(id);+        if (!loc) {+            fsck_report_id(ctx, dir, "operation head or parent is missing:", id);+            continue;         }-        std::string base = name.substr(0, name.size() - 6);-        const fs::path ipath = dir / path_from_bytes(base + ".vidx");-        auto idata = read_file_opt(ipath);-        if (!idata) {-          fsck_report(ctx, ppath, "pack has no index");-          continue;+        if (loc->kind != TYPE_OPERATION) {+            fsck_report_id(ctx, dir, "op-log entry is not an operation:", id);+            continue;         }-        auto index = decode_index(std::move(*idata), pack->trailer);-        if (!index) {-          fsck_report_decode(ctx, ipath, "index", index.error());-          continue;+        auto body = store.get(*loc);+        if (!body) {+            fsck_report_decode(ctx, dir, "operation", body.error());+            continue;         }-        bool eligible = true;-        if (index->ids.size() != pack->records.size()) {-          fsck_report(ctx, ppath, "pack and index object counts differ");-          eligible = false;+        auto op = decode_operation(bytes_of(*body));+        if (!op) {+            fsck_report_decode(ctx, dir, "operation", op.error());+            continue;         }-        if (eligible) {-          std::vector<bool> visited(pack->records.size(), false);-          for (std::size_t j = 0; j < index->ids.size(); ++j) {-            const auto rec = pack->find_by_offset(index->offsets[j]);-            if (!rec) {-              fsck_report_id(ctx, ppath, "index offset names no record for",-                             index->ids[j]);-              eligible = false;-              continue;-            }-            if (!id_equal(pack->records[*rec].id, index->ids[j])) {-              fsck_report_id(ctx, ppath, "index id does not match record for",-                             index->ids[j]);-              eligible = false;-            }-            if (visited[*rec]) {-              fsck_report_id(ctx, ppath, "record indexed more than once",-                             index->ids[j]);-              eligible = false;+        for (const auto& parent : op->parents)+            frontier.push_back(parent);+        (void)check_ref(ctx, store, dir, op->view, TYPE_VIEW, "operation view");+    }+}++int fsck_repository(const fs::path& root, bool verbose) {+    FsckCtx ctx;+    ctx.root = root;+    ctx.verbose = verbose;+    std::vector<StoreHandle> handles;+    if (check_format(ctx)) {+        auto cfg = read_file_opt(config_path(root));+        if (cfg) {+            const std::string_view text(reinterpret_cast<const char*>(cfg->data()), cfg->size());+            ctx.promisor = text.find("promisor") != std::string_view::npos;+        }+        const fs::path dir = packs_dir(root);+        if (!path_is_dir(dir)) {+            fsck_report(ctx, dir, "missing store/packs directory");+        } else {+            const auto names = list_directory(dir);+            for (const auto& name : names) {+                if (name.size() > 5 && name.compare(name.size() - 5, 5, ".vidx") == 0) {+                    std::string pack_name = name.substr(0, name.size() - 5) + ".vpack";+                    const fs::path ppath = dir / path_from_bytes(pack_name);+                    if (!path_is_file(ppath))+                        fsck_report(ctx, ppath, "index has no pack");+                }             }-            visited[*rec] = true;-          }-          for (std::size_t k = 0; k < pack->records.size(); ++k) {-            if (!visited[k]) {-              fsck_report_id(ctx, ppath, "record is not indexed",-                             pack->records[k].id);-              eligible = false;+            for (const auto& name : names) {+                if (name.size() <= 6 || name.compare(name.size() - 6, 6, ".vpack") != 0)+                    continue;+                const fs::path ppath = dir / path_from_bytes(name);+                auto pdata = read_file_opt(ppath);+                if (!pdata) {+                    fsck_report(ctx, ppath, "cannot read pack");+                    continue;+                }+                auto pack = decode_pack(std::move(*pdata));+                if (!pack) {+                    fsck_report_decode(ctx, ppath, "pack", pack.error());+                    continue;+                }+                std::string base = name.substr(0, name.size() - 6);+                const fs::path ipath = dir / path_from_bytes(base + ".vidx");+                auto idata = read_file_opt(ipath);+                if (!idata) {+                    fsck_report(ctx, ppath, "pack has no index");+                    continue;+                }+                auto index = decode_index(std::move(*idata), pack->trailer);+                if (!index) {+                    fsck_report_decode(ctx, ipath, "index", index.error());+                    continue;+                }+                bool eligible = true;+                if (index->ids.size() != pack->records.size()) {+                    fsck_report(ctx, ppath, "pack and index object counts differ");+                    eligible = false;+                }+                if (eligible) {+                    std::vector<bool> visited(pack->records.size(), false);+                    for (std::size_t j = 0; j < index->ids.size(); ++j) {+                        const auto rec = pack->find_by_offset(index->offsets[j]);+                        if (!rec) {+                            fsck_report_id(ctx, ppath, "index offset names no record for",+                                           index->ids[j]);+                            eligible = false;+                            continue;+                        }+                        if (!id_equal(pack->records[*rec].id, index->ids[j])) {+                            fsck_report_id(ctx, ppath, "index id does not match record for",+                                           index->ids[j]);+                            eligible = false;+                        }+                        if (visited[*rec]) {+                            fsck_report_id(ctx, ppath, "record indexed more than once",+                                           index->ids[j]);+                            eligible = false;+                        }+                        visited[*rec] = true;+                    }+                    for (std::size_t k = 0; k < pack->records.size(); ++k) {+                        if (!visited[k]) {+                            fsck_report_id(ctx, ppath, "record is not indexed",+                                           pack->records[k].id);+                            eligible = false;+                        }+                    }+                }+                if (!eligible)+                    continue;+                StoreHandle handle;+                handle.path = ppath;+                handle.index = std::move(*index);+                handle.pack = std::move(*pack);+                handles.push_back(std::move(handle));             }-          }         }-        if (!eligible)-          continue;-        StoreHandle handle;-        handle.path = ppath;-        handle.index = std::move(*index);-        handle.pack = std::move(*pack);-        handles.push_back(std::move(handle));-      }-    } -    Store store;-    store.handles() = std::move(handles);-    for (auto &handle : store.handles()) {-      if (!handle.pack)-        continue;-      for (std::size_t j = 0; j < handle.pack->records.size(); ++j) {-        const auto &rec = handle.pack->records[j];-        auto body = handle.pack->get(j);-        if (!body) {-          fsck_report_decode(ctx, handle.path, "record", body.error());-          continue;+        Store store;+        store.handles() = std::move(handles);+        for (auto& handle : store.handles()) {+            if (!handle.pack)+                continue;+            for (std::size_t j = 0; j < handle.pack->records.size(); ++j) {+                const auto& rec = handle.pack->records[j];+                auto body = handle.pack->get(j);+                if (!body) {+                    fsck_report_decode(ctx, handle.path, "record", body.error());+                    continue;+                }+                check_object(ctx, store, handle.path, rec.id, rec.type, bytes_of(*body));+            }         }-        check_object(ctx, store, handle.path, rec.id, rec.type,-                     bytes_of(*body));-      }+        check_op_log(ctx, store);     }-    check_op_log(ctx, store);-  } -  if (ctx.warnings > 0 && ctx.verbose) {-    warning_prefix();-    std::cout << ctx.warnings << " warning(s)\n";-  }-  if (ctx.errors == 0) {-    info_prefix();-    std::cout << "fsck: clean\n";-    return 0;-  }-  error_prefix();-  std::cout << ctx.errors << " error(s)\n";-  return 1;+    if (ctx.warnings > 0 && ctx.verbose) {+        warning_prefix();+        std::cout << ctx.warnings << " warning(s)\n";+    }+    if (ctx.errors == 0) {+        info_prefix();+        std::cout << "fsck: clean\n";+        return 0;+    }+    error_prefix();+    std::cout << ctx.errors << " error(s)\n";+    return 1; }  } // namespace vn--- a/xveins/src/store.h+++ b/xveins/src/store.h@@ -13,7 +13,7 @@  // Called when a promised chunk is missing. Returns true when the object was // fetched and written to a pack.-using PromisorFetcher = std::function<bool(const fs::path &, const Id &)>;+using PromisorFetcher = std::function<bool(const fs::path&, const Id&)>; void set_promisor_fetcher(PromisorFetcher fetcher);  // ---------------------------------------------------------------------------@@ -20,20 +20,20 @@ // Repository layout // --------------------------------------------------------------------------- -fs::path veins_dir(const fs::path &root);-fs::path packs_dir(const fs::path &root);-fs::path tmp_dir(const fs::path &root);-fs::path op_heads_dir(const fs::path &root);-fs::path git_dir(const fs::path &root);-fs::path git_map_dir(const fs::path &root);-fs::path working_copy_dir(const fs::path &root);-fs::path resolutions_dir(const fs::path &root);-fs::path config_path(const fs::path &root);-fs::path format_path(const fs::path &root);-std::uint64_t storage_usage(const fs::path &dir);+fs::path veins_dir(const fs::path& root);+fs::path packs_dir(const fs::path& root);+fs::path tmp_dir(const fs::path& root);+fs::path op_heads_dir(const fs::path& root);+fs::path git_dir(const fs::path& root);+fs::path git_map_dir(const fs::path& root);+fs::path working_copy_dir(const fs::path& root);+fs::path resolutions_dir(const fs::path& root);+fs::path config_path(const fs::path& root);+fs::path format_path(const fs::path& root);+std::uint64_t storage_usage(const fs::path& dir); -std::optional<fs::path> discover_repo(const fs::path &start);-Result<fs::path> init_repo(const fs::path &path);+std::optional<fs::path> discover_repo(const fs::path& start);+Result<fs::path> init_repo(const fs::path& path);  // --------------------------------------------------------------------------- // Pack and index files@@ -40,59 +40,57 @@ // ---------------------------------------------------------------------------  struct PackRecord {-  Id id{};-  std::uint8_t type = 0;-  std::uint8_t compression = 0;-  std::uint64_t raw_len = 0;-  std::uint64_t stored_len = 0;-  std::uint64_t data_off = 0;-  std::uint64_t record_off = 0;+    Id id{};+    std::uint8_t type = 0;+    std::uint8_t compression = 0;+    std::uint64_t raw_len = 0;+    std::uint64_t stored_len = 0;+    std::uint64_t data_off = 0;+    std::uint64_t record_off = 0; };  struct Pack {-  std::vector<std::uint8_t> data;-  std::vector<PackRecord> records;-  std::array<std::uint8_t, 32> trailer{};+    std::vector<std::uint8_t> data;+    std::vector<PackRecord> records;+    std::array<std::uint8_t, 32> trailer{}; -  std::optional<std::size_t> find_by_offset(std::uint64_t offset) const;-  Result<std::vector<std::uint8_t>> get(std::size_t record_index) const;+    std::optional<std::size_t> find_by_offset(std::uint64_t offset) const;+    Result<std::vector<std::uint8_t>> get(std::size_t record_index) const; };  Result<Pack> decode_pack(std::vector<std::uint8_t> data);  struct Index {-  std::vector<Id> ids;-  std::vector<std::uint64_t> offsets;-  std::array<std::uint8_t, 32> pack_trailer{};+    std::vector<Id> ids;+    std::vector<std::uint64_t> offsets;+    std::array<std::uint8_t, 32> pack_trailer{}; -  std::optional<std::size_t> find(const Id &id) const;+    std::optional<std::size_t> find(const Id& id) const; }; -Result<Index> decode_index(std::vector<std::uint8_t> data,-                           const std::optional<std::array<std::uint8_t, 32>>-                               &expected_pack_trailer = std::nullopt);+Result<Index> decode_index(+    std::vector<std::uint8_t> data,+    const std::optional<std::array<std::uint8_t, 32>>& expected_pack_trailer = std::nullopt);  struct RecordMeta {-  Id id{};-  std::uint64_t offset = 0;-  std::uint8_t type = 0;-  std::uint64_t raw_len = 0;+    Id id{};+    std::uint64_t offset = 0;+    std::uint8_t type = 0;+    std::uint64_t raw_len = 0; };  struct PackOutput {-  std::vector<std::uint8_t> pack;-  std::vector<std::uint8_t> index;-  std::string name;-  std::size_t count = 0;+    std::vector<std::uint8_t> pack;+    std::vector<std::uint8_t> index;+    std::string name;+    std::size_t count = 0; }; -PackOutput encode_pack(const std::vector<RawObject> &objects);-std::vector<std::uint8_t>-encode_index(const std::vector<RecordMeta> &records,-             const std::array<std::uint8_t, 32> &trailer);+PackOutput encode_pack(const std::vector<RawObject>& objects);+std::vector<std::uint8_t> encode_index(const std::vector<RecordMeta>& records,+                                       const std::array<std::uint8_t, 32>& trailer); -int write_pack(const fs::path &root, const std::vector<RawObject> &objects,-               std::uint64_t limit);+int write_pack(const fs::path& root, const std::vector<RawObject>& objects, std::uint64_t limit);  // --------------------------------------------------------------------------- // Store@@ -99,47 +97,52 @@ // ---------------------------------------------------------------------------  struct Loc {-  std::size_t pack_index = 0;-  std::size_t record_index = 0;-  std::uint8_t kind = 0;+    std::size_t pack_index = 0;+    std::size_t record_index = 0;+    std::uint8_t kind = 0; };  struct StoreHandle {-  fs::path path;-  std::uint64_t mtime_ns = 0;-  std::optional<Index> index;-  std::optional<Pack> pack;+    fs::path path;+    std::uint64_t mtime_ns = 0;+    std::optional<Index> index;+    std::optional<Pack> pack; };  class Store { public:-  Store() = default;-  Store(Store &&) noexcept = default;-  Store &operator=(Store &&) noexcept = default;-  Store(const Store &) = delete;-  Store &operator=(const Store &) = delete;+    Store() = default;+    Store(Store&&) noexcept = default;+    Store& operator=(Store&&) noexcept = default;+    Store(const Store&) = delete;+    Store& operator=(const Store&) = delete; -  static Store open_all(const fs::path &root);-  void refresh(const fs::path &root);+    static Store open_all(const fs::path& root);+    void refresh(const fs::path& root); -  std::optional<Loc> find(const Id &id);-  Result<std::vector<std::uint8_t>> get(const Loc &loc);-  std::optional<std::vector<std::uint8_t>> read_body(const Id &id,-                                                     std::uint8_t expected);-  std::optional<View> read_view(const Id &id);-  std::optional<Operation> read_operation(const Id &id);-  bool has_promisor(const fs::path &root) const;+    std::optional<Loc> find(const Id& id);+    Result<std::vector<std::uint8_t>> get(const Loc& loc);+    std::optional<std::vector<std::uint8_t>> read_body(const Id& id, std::uint8_t expected);+    std::optional<View> read_view(const Id& id);+    std::optional<Operation> read_operation(const Id& id);+    bool has_promisor(const fs::path& root) const; -  std::vector<StoreHandle> &handles() { return handles_; }-  const std::vector<StoreHandle> &handles() const { return handles_; }-  const fs::path &root() const { return root_; }-  void preload();+    std::vector<StoreHandle>& handles() {+        return handles_;+    }+    const std::vector<StoreHandle>& handles() const {+        return handles_;+    }+    const fs::path& root() const {+        return root_;+    }+    void preload();  private:-  bool ensure_index(StoreHandle &handle);-  bool ensure_pack(StoreHandle &handle);-  fs::path root_;-  std::vector<StoreHandle> handles_;+    bool ensure_index(StoreHandle& handle);+    bool ensure_pack(StoreHandle& handle);+    fs::path root_;+    std::vector<StoreHandle> handles_; };  // ---------------------------------------------------------------------------@@ -148,67 +151,76 @@  class Writer { public:-  Writer() = default;+    Writer() = default; -  Id add(std::uint8_t type, const std::vector<std::uint8_t> &body);-  Id add(std::uint8_t type, std::vector<std::uint8_t> &&body);-  Id add_known(std::uint8_t type, const Id &id,-               const std::vector<std::uint8_t> &body);-  Id add_known(std::uint8_t type, const Id &id,-               std::vector<std::uint8_t> &&body);-  void enable_chunk_cache() { cache_chunks_ = true; }-  void set_limit(std::uint64_t limit) { limit_ = limit; }-  bool quota_hit() const { return quota_hit_; }-  std::optional<std::vector<std::uint8_t>> find_cached(std::uint8_t type,-                                                       const Id &id) const;+    Id add(std::uint8_t type, const std::vector<std::uint8_t>& body);+    Id add(std::uint8_t type, std::vector<std::uint8_t>&& body);+    Id add_known(std::uint8_t type, const Id& id, const std::vector<std::uint8_t>& body);+    Id add_known(std::uint8_t type, const Id& id, std::vector<std::uint8_t>&& body);+    void enable_chunk_cache() {+        cache_chunks_ = true;+    }+    void set_limit(std::uint64_t limit) {+        limit_ = limit;+    }+    bool quota_hit() const {+        return quota_hit_;+    }+    std::optional<std::vector<std::uint8_t>> find_cached(std::uint8_t type, const Id& id) const; -  int finish(const fs::path &root);-  std::vector<RawObject> &objects() { return objects_; }+    int finish(const fs::path& root);+    std::vector<RawObject>& objects() {+        return objects_;+    }  private:-  std::vector<RawObject> objects_;-  std::vector<RawObject> cache_;-  std::set<Id> seen_;-  bool cache_chunks_ = false;-  std::uint64_t limit_ = 0;-  std::uint64_t raw_bytes_ = 0;-  bool quota_hit_ = false;+    std::vector<RawObject> objects_;+    std::vector<RawObject> cache_;+    std::set<Id> seen_;+    bool cache_chunks_ = false;+    std::uint64_t limit_ = 0;+    std::uint64_t raw_bytes_ = 0;+    bool quota_hit_ = false; };  class Txn { public:-  static Result<Txn> begin(const fs::path &root, Store &store);-  ~Txn() = default;+    static Result<Txn> begin(const fs::path& root, Store& store);+    ~Txn() = default; -  View &view() { return view_; }-  Writer &writer() { return writer_; }-  Store &store() { return *store_; }+    View& view() {+        return view_;+    }+    Writer& writer() {+        return writer_;+    }+    Store& store() {+        return *store_;+    } -  Id add_object(std::uint8_t type, const std::vector<std::uint8_t> &body) {-    return writer_.add(type, body);-  }-  Id add_object(std::uint8_t type, std::vector<std::uint8_t> &&body) {-    return writer_.add(type, std::move(body));-  }-  Id add_known(std::uint8_t type, const Id &id,-               const std::vector<std::uint8_t> &body) {-    return writer_.add_known(type, id, body);-  }-  Id add_known(std::uint8_t type, const Id &id,-               std::vector<std::uint8_t> &&body) {-    return writer_.add_known(type, id, std::move(body));-  }+    Id add_object(std::uint8_t type, const std::vector<std::uint8_t>& body) {+        return writer_.add(type, body);+    }+    Id add_object(std::uint8_t type, std::vector<std::uint8_t>&& body) {+        return writer_.add(type, std::move(body));+    }+    Id add_known(std::uint8_t type, const Id& id, const std::vector<std::uint8_t>& body) {+        return writer_.add_known(type, id, body);+    }+    Id add_known(std::uint8_t type, const Id& id, std::vector<std::uint8_t>&& body) {+        return writer_.add_known(type, id, std::move(body));+    } -  Status finish(std::string_view description);+    Status finish(std::string_view description);  private:-  Txn() = default;-  fs::path root_;-  Store *store_ = nullptr;-  View view_;-  std::vector<Id> parents_;-  std::int64_t start_ms_ = 0;-  Writer writer_;+    Txn() = default;+    fs::path root_;+    Store* store_ = nullptr;+    View view_;+    std::vector<Id> parents_;+    std::int64_t start_ms_ = 0;+    Writer writer_; };  // ---------------------------------------------------------------------------@@ -215,35 +227,34 @@ // Operation state and view mutations // --------------------------------------------------------------------------- -std::vector<Id> read_heads(const fs::path &root);-bool write_head(const fs::path &root, const Id &id);-bool delete_head(const fs::path &root, const Id &id);+std::vector<Id> read_heads(const fs::path& root);+bool write_head(const fs::path& root, const Id& id);+bool delete_head(const fs::path& root, const Id& id); View empty_view();-std::optional<View> current_view(const fs::path &root, Store &store);+std::optional<View> current_view(const fs::path& root, Store& store); -void sort_view(View &view);-void sort_ids(std::vector<Id> &ids);-void rebuild_heads(View &view);-void set_workspace(View &view, const Id &id);-void remove_head(View &view, const Id &id);-void move_bookmarks(View &view, const Id &old_id, const Id &new_id);-void set_bookmark_target(View &view, std::string_view name, const Id &id);-void add_unique_head(View &view, const Id &id);+void sort_view(View& view);+void sort_ids(std::vector<Id>& ids);+void rebuild_heads(View& view);+void set_workspace(View& view, const Id& id);+void remove_head(View& view, const Id& id);+void move_bookmarks(View& view, const Id& old_id, const Id& new_id);+void set_bookmark_target(View& view, std::string_view name, const Id& id);+void add_unique_head(View& view, const Id& id); -std::optional<std::size_t> find_bookmark(const View &view,-                                         std::string_view name);-std::optional<std::size_t> find_tag(const View &view, std::string_view name);-std::vector<std::string> bookmark_names(const View &view, const Id &id);-std::vector<std::string> tag_names(const View &view, const Id &id);+std::optional<std::size_t> find_bookmark(const View& view, std::string_view name);+std::optional<std::size_t> find_tag(const View& view, std::string_view name);+std::vector<std::string> bookmark_names(const View& view, const Id& id);+std::vector<std::string> tag_names(const View& view, const Id& id); -bool mark_native(const fs::path &root, const Id &id);-std::vector<Id> load_native(const fs::path &root);-bool is_native(const std::vector<Id> &native, const Id &id);+bool mark_native(const fs::path& root, const Id& id);+std::vector<Id> load_native(const fs::path& root);+bool is_native(const std::vector<Id>& native, const Id& id);  // --------------------------------------------------------------------------- // fsck // --------------------------------------------------------------------------- -int fsck_repository(const fs::path &root, bool verbose);+int fsck_repository(const fs::path& root, bool verbose);  } // namespace vn--- a/xveins/src/tag.cpp+++ b/xveins/src/tag.cpp@@ -13,413 +13,410 @@ namespace {  bool tag_is_flag(std::string_view arg) {-  return !arg.empty() && arg.front() == '-';+    return !arg.empty() && arg.front() == '-'; }  bool tag_contains(std::string_view name, std::string_view needle) {-  return !needle.empty() && name.find(needle) != std::string_view::npos;+    return !needle.empty() && name.find(needle) != std::string_view::npos; }  bool valid_tag_name(std::string_view name) {-  if (name.empty() || name.size() > MAX_NAME_LEN)-    return false;-  const auto first = static_cast<unsigned char>(name.front());-  if (first == '-' || first == '/' || first == '.')-    return false;-  const auto last = static_cast<unsigned char>(name.back());-  if (last == '/' || last == '.')-    return false;-  for (char raw : name) {-    const auto c = static_cast<unsigned char>(raw);-    if (c == 0 || c == ' ' || c < 32 || c == 127)-      return false;-    if (c == '~' || c == '^' || c == ':' || c == '?' || c == '*' || c == '[' ||-        c == '\\')-      return false;-  }-  if (tag_contains(name, "..") || tag_contains(name, "@{") ||-      tag_contains(name, "//"))-    return false;-  if (name == "@")-    return false;-  if (name.size() >= 5 && name.substr(name.size() - 5) == ".lock")-    return false;-  return true;+    if (name.empty() || name.size() > MAX_NAME_LEN)+        return false;+    const auto first = static_cast<unsigned char>(name.front());+    if (first == '-' || first == '/' || first == '.')+        return false;+    const auto last = static_cast<unsigned char>(name.back());+    if (last == '/' || last == '.')+        return false;+    for (char raw : name) {+        const auto c = static_cast<unsigned char>(raw);+        if (c == 0 || c == ' ' || c < 32 || c == 127)+            return false;+        if (c == '~' || c == '^' || c == ':' || c == '?' || c == '*' || c == '[' || c == '\\')+            return false;+    }+    if (tag_contains(name, "..") || tag_contains(name, "@{") || tag_contains(name, "//"))+        return false;+    if (name == "@")+        return false;+    if (name.size() >= 5 && name.substr(name.size() - 5) == ".lock")+        return false;+    return true; } -std::string short_commit(const Id &id, std::size_t n = 12) {-  if (n == 0)-    n = 12;-  n = std::min<std::size_t>(n, 64);-  return hex_encode(id).substr(0, n);+std::string short_commit(const Id& id, std::size_t n = 12) {+    if (n == 0)+        n = 12;+    n = std::min<std::size_t>(n, 64);+    return hex_encode(id).substr(0, n); }  void print_cell(std::string_view text, std::size_t width) {-  std::cout << text;-  for (std::size_t i = text.size(); i < width; ++i)-    std::cout << ' ';+    std::cout << text;+    for (std::size_t i = text.size(); i < width; ++i)+        std::cout << ' '; } -bool is_digit(char c) { return c >= '0' && c <= '9'; }+bool is_digit(char c) {+    return c >= '0' && c <= '9';+} -std::size_t skip_leading_zeroes(std::string_view text, std::size_t begin,-                                std::size_t end) {-  while (begin < end && text[begin] == '0')-    ++begin;-  return begin;+std::size_t skip_leading_zeroes(std::string_view text, std::size_t begin, std::size_t end) {+    while (begin < end && text[begin] == '0')+        ++begin;+    return begin; }  // Compare tag names as natural versions so v0.0.10 sorts after v0.0.9. int natural_compare(std::string_view a, std::string_view b) {-  std::size_t i = 0;-  std::size_t j = 0;-  while (i < a.size() && j < b.size()) {-    if (is_digit(a[i]) && is_digit(b[j])) {-      std::size_t ai = i;-      std::size_t bj = j;-      while (ai < a.size() && is_digit(a[ai]))-        ++ai;-      while (bj < b.size() && is_digit(b[bj]))-        ++bj;-      const std::size_t an = skip_leading_zeroes(a, i, ai);-      const std::size_t bn = skip_leading_zeroes(b, j, bj);-      const std::size_t alen = ai - an;-      const std::size_t blen = bj - bn;-      if (alen != blen)-        return alen < blen ? -1 : 1;-      for (std::size_t k = 0; k < alen; ++k) {-        const auto ac = static_cast<unsigned char>(a[an + k]);-        const auto bc = static_cast<unsigned char>(b[bn + k]);-        if (ac != bc)-          return ac < bc ? -1 : 1;-      }-      i = ai;-      j = bj;-    } else {-      const auto ac = static_cast<unsigned char>(a[i]);-      const auto bc = static_cast<unsigned char>(b[j]);-      if (ac != bc)-        return ac < bc ? -1 : 1;-      ++i;-      ++j;+    std::size_t i = 0;+    std::size_t j = 0;+    while (i < a.size() && j < b.size()) {+        if (is_digit(a[i]) && is_digit(b[j])) {+            std::size_t ai = i;+            std::size_t bj = j;+            while (ai < a.size() && is_digit(a[ai]))+                ++ai;+            while (bj < b.size() && is_digit(b[bj]))+                ++bj;+            const std::size_t an = skip_leading_zeroes(a, i, ai);+            const std::size_t bn = skip_leading_zeroes(b, j, bj);+            const std::size_t alen = ai - an;+            const std::size_t blen = bj - bn;+            if (alen != blen)+                return alen < blen ? -1 : 1;+            for (std::size_t k = 0; k < alen; ++k) {+                const auto ac = static_cast<unsigned char>(a[an + k]);+                const auto bc = static_cast<unsigned char>(b[bn + k]);+                if (ac != bc)+                    return ac < bc ? -1 : 1;+            }+            i = ai;+            j = bj;+        } else {+            const auto ac = static_cast<unsigned char>(a[i]);+            const auto bc = static_cast<unsigned char>(b[j]);+            if (ac != bc)+                return ac < bc ? -1 : 1;+            ++i;+            ++j;+        }     }-  }-  if (i < a.size())-    return 1;-  if (j < b.size())-    return -1;-  return 0;+    if (i < a.size())+        return 1;+    if (j < b.size())+        return -1;+    return 0; } -int tag_set(const std::vector<std::string> &args, std::size_t start) {-  std::string name;-  std::string rev;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && (arg == "-r" || arg == "-rev")) {-      if (i + 1 >= args.size()) {+int tag_set(const std::vector<std::string>& args, std::size_t start) {+    std::string name;+    std::string rev;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && (arg == "-r" || arg == "-rev")) {+            if (i + 1 >= args.size()) {+                error_prefix();+                std::cout << arg << " requires a revision\n";+                return 1;+            }+            rev = args[++i];+        } else if (!end_flags && tag_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (name.empty()) {+            name = arg;+        } else if (rev.empty()) {+            rev = arg;+        } else {+            error_prefix();+            std::cout << "tag set accepts a name and one revision\n";+            return 1;+        }+    }+    if (name.empty()) {         error_prefix();-        std::cout << arg << " requires a revision\n";+        std::cout << "tag set requires a name\n";         return 1;-      }-      rev = args[++i];-    } else if (!end_flags && tag_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (name.empty()) {-      name = arg;-    } else if (rev.empty()) {-      rev = arg;-    } else {-      error_prefix();-      std::cout << "tag set accepts a name and one revision\n";-      return 1;     }-  }-  if (name.empty()) {-    error_prefix();-    std::cout << "tag set requires a name\n";-    return 1;-  }-  if (!valid_tag_name(name)) {-    error_prefix();-    std::cout << "invalid tag name: " << name << "\n";-    return 1;-  }+    if (!valid_tag_name(name)) {+        error_prefix();+        std::cout << "invalid tag name: " << name << "\n";+        return 1;+    } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  const int snap = snapshot_run(*root);-  if (snap != 0)-    return snap;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    const int snap = snapshot_run(*root);+    if (snap != 0)+        return snap; -  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  auto target = resolve_revision(store, tx->view(), rev);-  if (!target) {-    error_prefix();-    if (rev.empty())-      std::cout << "no working-copy commit\n";-    else-      std::cout << "unknown revision: " << rev << "\n";-    return 1;-  }+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    auto target = resolve_revision(store, tx->view(), rev);+    if (!target) {+        error_prefix();+        if (rev.empty())+            std::cout << "no working-copy commit\n";+        else+            std::cout << "unknown revision: " << rev << "\n";+        return 1;+    } -  bool changed = true;-  if (const auto existing = find_tag(tx->view(), name)) {-    auto &tag = tx->view().tags[*existing];-    if (std::memcmp(tag.target.data(), target->data(), ID_LEN) == 0) {-      changed = false;+    bool changed = true;+    if (const auto existing = find_tag(tx->view(), name)) {+        auto& tag = tx->view().tags[*existing];+        if (std::memcmp(tag.target.data(), target->data(), ID_LEN) == 0) {+            changed = false;+        } else {+            tag.target = *target;+        }     } else {-      tag.target = *target;+        tx->view().tags.push_back(TagRef{name, *target});     }-  } else {-    tx->view().tags.push_back(TagRef{name, *target});-  } -  if (!changed) {+    if (!changed) {+        info_prefix();+        std::cout << "tag " << name << " is already at " << short_commit(*target) << "\n";+        return 0;+    }++    rebuild_heads(tx->view());+    const auto status = tx->finish("tag set " + name);+    if (!status)+        return 1;     info_prefix();-    std::cout << "tag " << name << " is already at " << short_commit(*target)-              << "\n";+    std::cout << "tag " << name << " set to " << short_commit(*target) << "\n";     return 0;-  }--  rebuild_heads(tx->view());-  const auto status = tx->finish("tag set " + name);-  if (!status)-    return 1;-  info_prefix();-  std::cout << "tag " << name << " set to " << short_commit(*target) << "\n";-  return 0; } -int tag_delete(const std::vector<std::string> &args, std::size_t start) {-  std::string name;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && tag_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else if (!name.empty()) {-      error_prefix();-      std::cout << "tag rm accepts exactly one name\n";-      return 1;-    } else {-      name = arg;+int tag_delete(const std::vector<std::string>& args, std::size_t start) {+    std::string name;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && tag_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else if (!name.empty()) {+            error_prefix();+            std::cout << "tag rm accepts exactly one name\n";+            return 1;+        } else {+            name = arg;+        }     }-  }-  if (name.empty()) {-    error_prefix();-    std::cout << "tag rm requires a name\n";-    return 1;-  }+    if (name.empty()) {+        error_prefix();+        std::cout << "tag rm requires a name\n";+        return 1;+    } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  Store store = Store::open_all(*root);-  auto tx = Txn::begin(*root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  }-  const auto existing = find_tag(tx->view(), name);-  if (!existing) {-    error_prefix();-    std::cout << "no such tag: " << name << "\n";-    return 1;-  }-  auto &tags = tx->view().tags;-  tags.erase(tags.begin() + static_cast<std::ptrdiff_t>(*existing));-  rebuild_heads(tx->view());-  const auto status = tx->finish("tag delete " + name);-  if (!status)-    return 1;-  info_prefix();-  std::cout << "deleted tag " << name << "\n";-  return 0;+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    Store store = Store::open_all(*root);+    auto tx = Txn::begin(*root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;+    }+    const auto existing = find_tag(tx->view(), name);+    if (!existing) {+        error_prefix();+        std::cout << "no such tag: " << name << "\n";+        return 1;+    }+    auto& tags = tx->view().tags;+    tags.erase(tags.begin() + static_cast<std::ptrdiff_t>(*existing));+    rebuild_heads(tx->view());+    const auto status = tx->finish("tag delete " + name);+    if (!status)+        return 1;+    info_prefix();+    std::cout << "deleted tag " << name << "\n";+    return 0; } -int tag_list(const std::vector<std::string> &args, std::size_t start) {-  bool col_titles = true;-  bool end_flags = false;-  for (std::size_t i = start; i < args.size(); ++i) {-    const std::string &arg = args[i];-    if (!end_flags && arg == "--") {-      end_flags = true;-    } else if (!end_flags && arg == "-no-col-titles") {-      col_titles = false;-    } else if (!end_flags && tag_is_flag(arg)) {-      error_prefix();-      std::cout << "unknown flag: " << arg << "\n";-      return 1;-    } else {-      error_prefix();-      std::cout << "tag ls takes no operands\n";-      return 1;+int tag_list(const std::vector<std::string>& args, std::size_t start) {+    bool col_titles = true;+    bool end_flags = false;+    for (std::size_t i = start; i < args.size(); ++i) {+        const std::string& arg = args[i];+        if (!end_flags && arg == "--") {+            end_flags = true;+        } else if (!end_flags && arg == "-no-col-titles") {+            col_titles = false;+        } else if (!end_flags && tag_is_flag(arg)) {+            error_prefix();+            std::cout << "unknown flag: " << arg << "\n";+            return 1;+        } else {+            error_prefix();+            std::cout << "tag ls takes no operands\n";+            return 1;+        }     }-  } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  const auto wc = working_copy_id(*view);+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    const auto wc = working_copy_id(*view); -  constexpr std::size_t w_commit = 12;-  constexpr std::size_t w_change = 8;-  std::size_t w_name = 3;-  for (const auto &tag : view->tags)-    w_name = std::max(w_name, tag.name.size());+    constexpr std::size_t w_commit = 12;+    constexpr std::size_t w_change = 8;+    std::size_t w_name = 3;+    for (const auto& tag : view->tags)+        w_name = std::max(w_name, tag.name.size()); -  if (col_titles) {-    print_cell("Tag", w_name);-    std::cout << "  ";-    print_cell("Commit", w_commit);-    std::cout << "  ";-    print_cell("Change", w_change);-    std::cout << "  Target\n";-  }+    if (col_titles) {+        print_cell("Tag", w_name);+        std::cout << "  ";+        print_cell("Commit", w_commit);+        std::cout << "  ";+        print_cell("Change", w_change);+        std::cout << "  Target\n";+    } -  for (const auto &tag : view->tags) {-    print_cell(tag.name, w_name);-    std::cout << "  ";-    print_cell(short_commit(tag.target), w_commit);-    std::cout << "  ";-    std::string change_text;-    if (auto loaded = load_commit(store, tag.target))-      change_text = base32_encode(loaded->commit.change_id).substr(0, 8);-    print_cell(change_text, w_change);-    std::cout << "  ";-    if (wc && std::memcmp(wc->data(), tag.target.data(), ID_LEN) == 0)-      print_colored("@", Color::Red, false, false);-    std::cout << "\n";-  }+    for (const auto& tag : view->tags) {+        print_cell(tag.name, w_name);+        std::cout << "  ";+        print_cell(short_commit(tag.target), w_commit);+        std::cout << "  ";+        std::string change_text;+        if (auto loaded = load_commit(store, tag.target))+            change_text = base32_encode(loaded->commit.change_id).substr(0, 8);+        print_cell(change_text, w_change);+        std::cout << "  ";+        if (wc && std::memcmp(wc->data(), tag.target.data(), ID_LEN) == 0)+            print_colored("@", Color::Red, false, false);+        std::cout << "\n";+    } -  if (view->tags.empty()) {-    info_prefix();-    std::cout << "no tags\n";-  }-  return 0;+    if (view->tags.empty()) {+        info_prefix();+        std::cout << "no tags\n";+    }+    return 0; } -int tag_latest(const std::vector<std::string> &args, std::size_t start) {-  for (std::size_t i = start; i < args.size(); ++i) {-    error_prefix();-    std::cout << "tag latest takes no operands\n";-    return 1;-  }+int tag_latest(const std::vector<std::string>& args, std::size_t start) {+    for (std::size_t i = start; i < args.size(); ++i) {+        error_prefix();+        std::cout << "tag latest takes no operands\n";+        return 1;+    } -  const auto root = discover_repo(".");-  if (!root) {-    error_prefix();-    std::cout << "not a veins repository\n";-    return 1;-  }-  Store store = Store::open_all(*root);-  auto view = current_view(*root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state\n";-    return 1;-  }-  if (view->tags.empty()) {-    error_prefix();-    std::cout << "no tags\n";-    return 1;-  }+    const auto root = discover_repo(".");+    if (!root) {+        error_prefix();+        std::cout << "not a veins repository\n";+        return 1;+    }+    Store store = Store::open_all(*root);+    auto view = current_view(*root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state\n";+        return 1;+    }+    if (view->tags.empty()) {+        error_prefix();+        std::cout << "no tags\n";+        return 1;+    } -  const TagRef *best = nullptr;-  std::int64_t best_time = std::numeric_limits<std::int64_t>::min();-  for (const auto &tag : view->tags) {-    std::int64_t time = std::numeric_limits<std::int64_t>::min();-    if (auto loaded = load_commit(store, tag.target))-      time = loaded->commit.committer.seconds;-    if (best == nullptr || time > best_time ||-        (time == best_time && natural_compare(tag.name, best->name) > 0)) {-      best = &tag;-      best_time = time;+    const TagRef* best = nullptr;+    std::int64_t best_time = std::numeric_limits<std::int64_t>::min();+    for (const auto& tag : view->tags) {+        std::int64_t time = std::numeric_limits<std::int64_t>::min();+        if (auto loaded = load_commit(store, tag.target))+            time = loaded->commit.committer.seconds;+        if (best == nullptr || time > best_time ||+            (time == best_time && natural_compare(tag.name, best->name) > 0)) {+            best = &tag;+            best_time = time;+        }     }-  }-  if (!best) {-    error_prefix();-    std::cout << "no tags\n";-    return 1;-  }-  std::cout << best->name << "\n";-  return 0;+    if (!best) {+        error_prefix();+        std::cout << "no tags\n";+        return 1;+    }+    std::cout << best->name << "\n";+    return 0; }  void tag_usage() {-  std::cout << "usage: vn tag <set|ls|rm|latest> ...\n";-  std::cout << "\n";-  std::cout << "manage named pointers to commits (tags)\n";-  std::cout << "\n";-  std::cout << "subcommands:\n";-  std::cout-      << "  set <name> [-rev <rev>]   create or move a tag (default: @)\n";-  std::cout << "  ls [-no-col-titles]       list tags\n";-  std::cout << "  rm <name>                 delete a tag\n";-  std::cout << "  latest                    print the latest tag name\n";-  std::cout << "\n";-  std::cout << "the latest tag is the one whose target commit has the newest\n";-  std::cout << "committer timestamp; equal timestamps use natural name order\n";+    std::cout << "usage: vn tag <set|ls|rm|latest> ...\n";+    std::cout << "\n";+    std::cout << "manage named pointers to commits (tags)\n";+    std::cout << "\n";+    std::cout << "subcommands:\n";+    std::cout << "  set <name> [-rev <rev>]   create or move a tag (default: @)\n";+    std::cout << "  ls [-no-col-titles]       list tags\n";+    std::cout << "  rm <name>                 delete a tag\n";+    std::cout << "  latest                    print the latest tag name\n";+    std::cout << "\n";+    std::cout << "the latest tag is the one whose target commit has the newest\n";+    std::cout << "committer timestamp; equal timestamps use natural name order\n"; }  } // namespace -int tag_run(const std::vector<std::string> &args) {-  if (args.size() <= 2) {+int tag_run(const std::vector<std::string>& args) {+    if (args.size() <= 2) {+        tag_usage();+        return 1;+    }+    const std::string& sub = args[2];+    if (sub == "set")+        return tag_set(args, 3);+    if (sub == "ls" || sub == "list")+        return tag_list(args, 3);+    if (sub == "rm" || sub == "remove")+        return tag_delete(args, 3);+    if (sub == "latest")+        return tag_latest(args, 3);+    if (sub == "help" || sub == "-h") {+        tag_usage();+        return 0;+    }+    error_prefix();+    std::cout << "unknown tag subcommand: " << sub << "\n";     tag_usage();     return 1;-  }-  const std::string &sub = args[2];-  if (sub == "set")-    return tag_set(args, 3);-  if (sub == "ls" || sub == "list")-    return tag_list(args, 3);-  if (sub == "rm" || sub == "remove")-    return tag_delete(args, 3);-  if (sub == "latest")-    return tag_latest(args, 3);-  if (sub == "help" || sub == "-h") {-    tag_usage();-    return 0;-  }-  error_prefix();-  std::cout << "unknown tag subcommand: " << sub << "\n";-  tag_usage();-  return 1; }  } // namespace vn--- a/xveins/src/wire.cpp+++ b/xveins/src/wire.cpp@@ -9,180 +9,174 @@  namespace { -bool read_exact(net::Stream &stream, std::uint8_t *out, std::size_t count) {-  std::size_t got = 0;-  while (got < count) {-    const std::int64_t n = stream.read(out + got, count - got);-    if (n <= 0)-      return false;-    got += static_cast<std::size_t>(n);-  }-  return true;+bool read_exact(net::Stream& stream, std::uint8_t* out, std::size_t count) {+    std::size_t got = 0;+    while (got < count) {+        const std::int64_t n = stream.read(out + got, count - got);+        if (n <= 0)+            return false;+        got += static_cast<std::size_t>(n);+    }+    return true; }  } // namespace -std::optional<Frame> read_frame(net::Stream &stream) {-  std::array<std::uint8_t, 4> head{};-  if (!read_exact(stream, head.data(), head.size()))-    return std::nullopt;-  const std::uint32_t length = (static_cast<std::uint32_t>(head[0]) << 24) |-                               (static_cast<std::uint32_t>(head[1]) << 16) |-                               (static_cast<std::uint32_t>(head[2]) << 8) |-                               static_cast<std::uint32_t>(head[3]);-  if (length < 5 || length > MAX_FRAME)-    return std::nullopt;-  std::vector<std::uint8_t> body(length);-  if (!read_exact(stream, body.data(), body.size()))-    return std::nullopt;-  Frame frame;-  frame.kind = body[0];-  frame.request_id = (static_cast<std::uint32_t>(body[1]) << 24) |-                     (static_cast<std::uint32_t>(body[2]) << 16) |-                     (static_cast<std::uint32_t>(body[3]) << 8) |-                     static_cast<std::uint32_t>(body[4]);-  frame.payload.assign(body.begin() + 5, body.end());-  return frame;+std::optional<Frame> read_frame(net::Stream& stream) {+    std::array<std::uint8_t, 4> head{};+    if (!read_exact(stream, head.data(), head.size()))+        return std::nullopt;+    const std::uint32_t length =+        (static_cast<std::uint32_t>(head[0]) << 24) | (static_cast<std::uint32_t>(head[1]) << 16) |+        (static_cast<std::uint32_t>(head[2]) << 8) | static_cast<std::uint32_t>(head[3]);+    if (length < 5 || length > MAX_FRAME)+        return std::nullopt;+    std::vector<std::uint8_t> body(length);+    if (!read_exact(stream, body.data(), body.size()))+        return std::nullopt;+    Frame frame;+    frame.kind = body[0];+    frame.request_id =+        (static_cast<std::uint32_t>(body[1]) << 24) | (static_cast<std::uint32_t>(body[2]) << 16) |+        (static_cast<std::uint32_t>(body[3]) << 8) | static_cast<std::uint32_t>(body[4]);+    frame.payload.assign(body.begin() + 5, body.end());+    return frame; } -bool write_frame(net::Stream &stream, std::uint8_t kind,-                 std::uint32_t request_id, Bytes payload) {-  if (payload.size() > MAX_FRAME - 5)-    return false;-  const std::uint32_t length = static_cast<std::uint32_t>(5 + payload.size());-  std::array<std::uint8_t, 9> head{};-  head[0] = static_cast<std::uint8_t>((length >> 24) & 255u);-  head[1] = static_cast<std::uint8_t>((length >> 16) & 255u);-  head[2] = static_cast<std::uint8_t>((length >> 8) & 255u);-  head[3] = static_cast<std::uint8_t>(length & 255u);-  head[4] = kind;-  head[5] = static_cast<std::uint8_t>((request_id >> 24) & 255u);-  head[6] = static_cast<std::uint8_t>((request_id >> 16) & 255u);-  head[7] = static_cast<std::uint8_t>((request_id >> 8) & 255u);-  head[8] = static_cast<std::uint8_t>(request_id & 255u);-  if (!stream.write_all(Bytes(head.data(), head.size())))-    return false;-  return payload.empty() || stream.write_all(payload);+bool write_frame(net::Stream& stream, std::uint8_t kind, std::uint32_t request_id, Bytes payload) {+    if (payload.size() > MAX_FRAME - 5)+        return false;+    const std::uint32_t length = static_cast<std::uint32_t>(5 + payload.size());+    std::array<std::uint8_t, 9> head{};+    head[0] = static_cast<std::uint8_t>((length >> 24) & 255u);+    head[1] = static_cast<std::uint8_t>((length >> 16) & 255u);+    head[2] = static_cast<std::uint8_t>((length >> 8) & 255u);+    head[3] = static_cast<std::uint8_t>(length & 255u);+    head[4] = kind;+    head[5] = static_cast<std::uint8_t>((request_id >> 24) & 255u);+    head[6] = static_cast<std::uint8_t>((request_id >> 16) & 255u);+    head[7] = static_cast<std::uint8_t>((request_id >> 8) & 255u);+    head[8] = static_cast<std::uint8_t>(request_id & 255u);+    if (!stream.write_all(Bytes(head.data(), head.size())))+        return false;+    return payload.empty() || stream.write_all(payload); } -bool write_simple(net::Stream &stream, std::uint8_t kind,-                  std::uint32_t request_id) {-  return write_frame(stream, kind, request_id, Bytes{});+bool write_simple(net::Stream& stream, std::uint8_t kind, std::uint32_t request_id) {+    return write_frame(stream, kind, request_id, Bytes{}); } -bool write_error(net::Stream &stream, std::uint32_t request_id,-                 std::uint8_t code, std::string_view message) {-  ByteWriter writer(64);-  writer.u8(code);-  writer.length_prefixed(message);-  return write_frame(stream, ERROR, request_id, writer.view());+bool write_error(net::Stream& stream, std::uint32_t request_id, std::uint8_t code,+                 std::string_view message) {+    ByteWriter writer(64);+    writer.u8(code);+    writer.length_prefixed(message);+    return write_frame(stream, ERROR, request_id, writer.view()); }  std::uint8_t read_error(Bytes payload) {-  if (payload.empty())-    return ERR_INTERNAL;-  return payload[0];+    if (payload.empty())+        return ERR_INTERNAL;+    return payload[0]; }  std::string error_message(Bytes payload) {-  if (payload.size() < 2)-    return {};-  Reader reader(payload.subspan(1));-  auto value = reader.bytes(4096);-  if (!value)-    return {};-  return std::string(str_of(*value));+    if (payload.size() < 2)+        return {};+    Reader reader(payload.subspan(1));+    auto value = reader.bytes(4096);+    if (!value)+        return {};+    return std::string(str_of(*value)); }  std::string_view error_code_name(std::uint8_t code) {-  switch (code) {-  case ERR_UNSUPPORTED_VERSION:-    return "unsupported protocol version";-  case ERR_BAD_FRAME:-    return "bad frame";-  case ERR_NOT_FOUND:-    return "object not found";-  case ERR_HASH_MISMATCH:-    return "hash mismatch";-  case ERR_NON_CANONICAL:-    return "non-canonical object";-  case ERR_MISSING_CLOSURE:-    return "missing object closure";-  case ERR_REF_CONFLICT:-    return "ref conflict";-  case ERR_REJECTED:-    return "request rejected";-  case ERR_INTERNAL:-    return "server internal error";-  case ERR_UNAUTHENTICATED:-    return "authentication required";-  case ERR_FORBIDDEN:-    return "permission denied";-  case ERR_AUTH_FAILED:-    return "authentication failed";-  case ERR_QUOTA:-    return "storage quota exceeded";-  case ERR_TOO_LARGE:-    return "push too large";-  default:-    return "unknown server error";-  }+    switch (code) {+    case ERR_UNSUPPORTED_VERSION:+        return "unsupported protocol version";+    case ERR_BAD_FRAME:+        return "bad frame";+    case ERR_NOT_FOUND:+        return "object not found";+    case ERR_HASH_MISMATCH:+        return "hash mismatch";+    case ERR_NON_CANONICAL:+        return "non-canonical object";+    case ERR_MISSING_CLOSURE:+        return "missing object closure";+    case ERR_REF_CONFLICT:+        return "ref conflict";+    case ERR_REJECTED:+        return "request rejected";+    case ERR_INTERNAL:+        return "server internal error";+    case ERR_UNAUTHENTICATED:+        return "authentication required";+    case ERR_FORBIDDEN:+        return "permission denied";+    case ERR_AUTH_FAILED:+        return "authentication failed";+    case ERR_QUOTA:+        return "storage quota exceeded";+    case ERR_TOO_LARGE:+        return "push too large";+    default:+        return "unknown server error";+    } }  std::optional<IncomingRecord> parse_record(Bytes data) {-  if (data.size() < 35)-    return std::nullopt;-  Reader reader(data);-  const auto id = reader.id();-  if (!id)-    return std::nullopt;-  const auto kind = reader.u8();-  if (!kind)-    return std::nullopt;-  const auto compression = reader.u8();-  if (!compression)-    return std::nullopt;-  const auto raw_len = reader.varint();-  if (!raw_len)-    return std::nullopt;-  const auto stored_len = reader.varint();-  if (!stored_len)-    return std::nullopt;-  if (*raw_len == 0 || *raw_len > 64u * 1024u * 1024u ||-      *stored_len > MAX_FRAME)-    return std::nullopt;-  const auto stored = reader.raw(static_cast<std::size_t>(*stored_len));-  if (!stored)-    return std::nullopt;-  if (!reader.at_end())-    return std::nullopt;-  IncomingRecord record;-  record.id = *id;-  record.kind = *kind;-  if (*compression == 0) {-    if (stored->size() != static_cast<std::size_t>(*raw_len))-      return std::nullopt;-    record.body.assign(stored->begin(), stored->end());+    if (data.size() < 35)+        return std::nullopt;+    Reader reader(data);+    const auto id = reader.id();+    if (!id)+        return std::nullopt;+    const auto kind = reader.u8();+    if (!kind)+        return std::nullopt;+    const auto compression = reader.u8();+    if (!compression)+        return std::nullopt;+    const auto raw_len = reader.varint();+    if (!raw_len)+        return std::nullopt;+    const auto stored_len = reader.varint();+    if (!stored_len)+        return std::nullopt;+    if (*raw_len == 0 || *raw_len > 64u * 1024u * 1024u || *stored_len > MAX_FRAME)+        return std::nullopt;+    const auto stored = reader.raw(static_cast<std::size_t>(*stored_len));+    if (!stored)+        return std::nullopt;+    if (!reader.at_end())+        return std::nullopt;+    IncomingRecord record;+    record.id = *id;+    record.kind = *kind;+    if (*compression == 0) {+        if (stored->size() != static_cast<std::size_t>(*raw_len))+            return std::nullopt;+        record.body.assign(stored->begin(), stored->end());+        return record;+    }+    record.body.resize(static_cast<std::size_t>(*raw_len));+    const std::size_t result =+        ZSTD_decompress(record.body.data(), record.body.size(), stored->data(), stored->size());+    if (ZSTD_isError(result) || result != record.body.size())+        return std::nullopt;     return record;-  }-  record.body.resize(static_cast<std::size_t>(*raw_len));-  const std::size_t result = ZSTD_decompress(-      record.body.data(), record.body.size(), stored->data(), stored->size());-  if (ZSTD_isError(result) || result != record.body.size())-    return std::nullopt;-  return record; } -std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,-                                      Bytes body) {-  ByteWriter writer(body.size() + 64);-  writer.raw(Bytes(id.data(), id.size()));-  writer.u8(kind);-  writer.u8(0);-  writer.varint(body.size());-  writer.varint(body.size());-  writer.raw(body);-  return writer.take();+std::vector<std::uint8_t> make_record(const Id& id, std::uint8_t kind, Bytes body) {+    ByteWriter writer(body.size() + 64);+    writer.raw(Bytes(id.data(), id.size()));+    writer.u8(kind);+    writer.u8(0);+    writer.varint(body.size());+    writer.varint(body.size());+    writer.raw(body);+    return writer.take(); }  } // namespace vn::wire--- a/xveins/src/wire.h+++ b/xveins/src/wire.h@@ -12,58 +12,56 @@ constexpr std::size_t MAX_FRAME = 16u * 1024u * 1024u;  enum Kind : std::uint8_t {-  HELLO = 1,-  HELLO_OK = 2,-  AUTH = 3,-  AUTH_OK = 4,-  WHOAMI = 5,-  WHOAMI_OK = 6,-  LIST_REFS = 7,-  REFS = 8,-  NEGOTIATE = 9,-  NEGOTIATE_OK = 10,-  FETCH_SKELETON = 11,-  GET_CHUNKS = 12,-  HAVE_QUERY = 13,-  HAVE_BITMAP = 14,-  PUT_RECORDS = 15,-  UPDATE_REFS = 16,-  UPDATE_REFS_OK = 17,-  RECORDS = 18,-  END = 19,-  ERROR = 20,+    HELLO = 1,+    HELLO_OK = 2,+    AUTH = 3,+    AUTH_OK = 4,+    WHOAMI = 5,+    WHOAMI_OK = 6,+    LIST_REFS = 7,+    REFS = 8,+    NEGOTIATE = 9,+    NEGOTIATE_OK = 10,+    FETCH_SKELETON = 11,+    GET_CHUNKS = 12,+    HAVE_QUERY = 13,+    HAVE_BITMAP = 14,+    PUT_RECORDS = 15,+    UPDATE_REFS = 16,+    UPDATE_REFS_OK = 17,+    RECORDS = 18,+    END = 19,+    ERROR = 20, };  enum ErrorCode : std::uint8_t {-  ERR_UNSUPPORTED_VERSION = 1,-  ERR_BAD_FRAME = 2,-  ERR_NOT_FOUND = 3,-  ERR_HASH_MISMATCH = 4,-  ERR_NON_CANONICAL = 5,-  ERR_MISSING_CLOSURE = 6,-  ERR_REF_CONFLICT = 7,-  ERR_REJECTED = 8,-  ERR_INTERNAL = 9,-  ERR_UNAUTHENTICATED = 10,-  ERR_FORBIDDEN = 11,-  ERR_AUTH_FAILED = 12,-  ERR_QUOTA = 13,-  ERR_TOO_LARGE = 14,+    ERR_UNSUPPORTED_VERSION = 1,+    ERR_BAD_FRAME = 2,+    ERR_NOT_FOUND = 3,+    ERR_HASH_MISMATCH = 4,+    ERR_NON_CANONICAL = 5,+    ERR_MISSING_CLOSURE = 6,+    ERR_REF_CONFLICT = 7,+    ERR_REJECTED = 8,+    ERR_INTERNAL = 9,+    ERR_UNAUTHENTICATED = 10,+    ERR_FORBIDDEN = 11,+    ERR_AUTH_FAILED = 12,+    ERR_QUOTA = 13,+    ERR_TOO_LARGE = 14, };  struct Frame {-  std::uint8_t kind = 0;-  std::uint32_t request_id = 0;-  std::vector<std::uint8_t> payload;+    std::uint8_t kind = 0;+    std::uint32_t request_id = 0;+    std::vector<std::uint8_t> payload; }; -std::optional<Frame> read_frame(net::Stream &stream);-bool write_frame(net::Stream &stream, std::uint8_t kind,-                 std::uint32_t request_id, Bytes payload);-bool write_simple(net::Stream &stream, std::uint8_t kind,-                  std::uint32_t request_id);-bool write_error(net::Stream &stream, std::uint32_t request_id,-                 std::uint8_t code, std::string_view message);+std::optional<Frame> read_frame(net::Stream& stream);+bool write_frame(net::Stream& stream, std::uint8_t kind, std::uint32_t request_id, Bytes payload);+bool write_simple(net::Stream& stream, std::uint8_t kind, std::uint32_t request_id);+bool write_error(net::Stream& stream, std::uint32_t request_id, std::uint8_t code,+                 std::string_view message);  std::uint8_t read_error(Bytes payload); std::string error_message(Bytes payload);@@ -71,12 +69,11 @@  // Encode/decode the record layout shared by packs and RECORDS frames. struct IncomingRecord {-  Id id{};-  std::uint8_t kind = 0;-  std::vector<std::uint8_t> body;+    Id id{};+    std::uint8_t kind = 0;+    std::vector<std::uint8_t> body; }; std::optional<IncomingRecord> parse_record(Bytes data);-std::vector<std::uint8_t> make_record(const Id &id, std::uint8_t kind,-                                      Bytes body);+std::vector<std::uint8_t> make_record(const Id& id, std::uint8_t kind, Bytes body);  } // namespace vn::wire--- a/xveins/src/worktree.cpp+++ b/xveins/src/worktree.cpp@@ -19,308 +19,296 @@ namespace {  struct CacheEntry {-  std::string path;-  std::uint64_t size = 0;-  std::uint64_t mtime_ns = 0;-  std::uint64_t inode = 0;-  std::uint8_t kind = 0;-  bool executable = false;-  Id target{};+    std::string path;+    std::uint64_t size = 0;+    std::uint64_t mtime_ns = 0;+    std::uint64_t inode = 0;+    std::uint8_t kind = 0;+    bool executable = false;+    Id target{}; };  struct Cache {-  std::vector<CacheEntry> entries;-  std::int64_t written_ms = 0;+    std::vector<CacheEntry> entries;+    std::int64_t written_ms = 0; };  std::string join_rel(std::string_view base, std::string_view name) {-  if (base.empty())-    return std::string(name);-  std::string out(base);-  out.push_back('/');-  out.append(name);-  return out;+    if (base.empty())+        return std::string(name);+    std::string out(base);+    out.push_back('/');+    out.append(name);+    return out; }  bool name_ends_with(std::string_view name, std::string_view suffix) {-  return name.size() >= suffix.size() &&-         name.substr(name.size() - suffix.size()) == suffix;+    return name.size() >= suffix.size() && name.substr(name.size() - suffix.size()) == suffix; }  std::optional<std::string> sidecar_base(std::string_view name) {-  if (name_ends_with(name, ".base") && name.size() > 5)-    return std::string(name.substr(0, name.size() - 5));-  if (name_ends_with(name, ".ours") && name.size() > 5)-    return std::string(name.substr(0, name.size() - 5));-  if (name_ends_with(name, ".theirs") && name.size() > 7)-    return std::string(name.substr(0, name.size() - 7));-  std::size_t digits = 0;-  while (digits < name.size() && name[name.size() - 1 - digits] >= '0' &&-         name[name.size() - 1 - digits] <= '9')-    ++digits;-  if (digits > 0) {-    const std::size_t stem_end = name.size() - digits;-    const std::string_view stem = name.substr(0, stem_end);-    if (stem_end > 5 && name_ends_with(stem, ".base"))-      return std::string(stem.substr(0, stem.size() - 5));-    if (stem_end > 7 && name_ends_with(stem, ".theirs"))-      return std::string(stem.substr(0, stem.size() - 7));-  }-  return std::nullopt;+    if (name_ends_with(name, ".base") && name.size() > 5)+        return std::string(name.substr(0, name.size() - 5));+    if (name_ends_with(name, ".ours") && name.size() > 5)+        return std::string(name.substr(0, name.size() - 5));+    if (name_ends_with(name, ".theirs") && name.size() > 7)+        return std::string(name.substr(0, name.size() - 7));+    std::size_t digits = 0;+    while (digits < name.size() && name[name.size() - 1 - digits] >= '0' &&+           name[name.size() - 1 - digits] <= '9')+        ++digits;+    if (digits > 0) {+        const std::size_t stem_end = name.size() - digits;+        const std::string_view stem = name.substr(0, stem_end);+        if (stem_end > 5 && name_ends_with(stem, ".base"))+            return std::string(stem.substr(0, stem.size() - 5));+        if (stem_end > 7 && name_ends_with(stem, ".theirs"))+            return std::string(stem.substr(0, stem.size() - 7));+    }+    return std::nullopt; }  bool is_meta_name(std::string_view name) {-  return name == ".veins" || name == ".git";+    return name == ".veins" || name == ".git"; } -bool cache_matches(const CacheEntry &entry, const StatInfo &info,-                   bool executable, std::int64_t now_ms,-                   std::int64_t written_ms) {-  if (entry.size != info.size || entry.mtime_ns != info.mtime_ns ||-      entry.inode != info.inode)-    return false;-  if (entry.executable != executable || entry.kind != info.kind)-    return false;-  const std::int64_t now_ns = now_ms * 1'000'000;-  const std::int64_t written_ns = written_ms * 1'000'000;-  constexpr std::int64_t window = 2'000'000'000;-  if (static_cast<std::int64_t>(info.mtime_ns) >= written_ns - window)-    return false;-  if (now_ns - static_cast<std::int64_t>(info.mtime_ns) < window)-    return false;-  return true;+bool cache_matches(const CacheEntry& entry, const StatInfo& info, bool executable,+                   std::int64_t now_ms, std::int64_t written_ms) {+    if (entry.size != info.size || entry.mtime_ns != info.mtime_ns || entry.inode != info.inode)+        return false;+    if (entry.executable != executable || entry.kind != info.kind)+        return false;+    const std::int64_t now_ns = now_ms * 1'000'000;+    const std::int64_t written_ns = written_ms * 1'000'000;+    constexpr std::int64_t window = 2'000'000'000;+    if (static_cast<std::int64_t>(info.mtime_ns) >= written_ns - window)+        return false;+    if (now_ns - static_cast<std::int64_t>(info.mtime_ns) < window)+        return false;+    return true; } -Cache load_cache(const fs::path &root) {-  Cache cache;-  auto data = read_file_opt(working_copy_dir(root) / "stat-cache");-  if (!data || data->size() < 13)-    return cache;-  if (std::memcmp(data->data(), "VST1", 4) != 0)-    return cache;-  Reader r(Bytes(data->data() + 4, data->size() - 4));-  const auto version = r.u8();-  if (!version || *version != 49)-    return cache;-  const auto written = r.u64le();-  if (!written)-    return cache;-  cache.written_ms = static_cast<std::int64_t>(*written);-  const auto count = r.varint();-  if (!count)+Cache load_cache(const fs::path& root) {+    Cache cache;+    auto data = read_file_opt(working_copy_dir(root) / "stat-cache");+    if (!data || data->size() < 13)+        return cache;+    if (std::memcmp(data->data(), "VST1", 4) != 0)+        return cache;+    Reader r(Bytes(data->data() + 4, data->size() - 4));+    const auto version = r.u8();+    if (!version || *version != 49)+        return cache;+    const auto written = r.u64le();+    if (!written)+        return cache;+    cache.written_ms = static_cast<std::int64_t>(*written);+    const auto count = r.varint();+    if (!count)+        return cache;+    for (std::uint64_t i = 0; i < *count; ++i) {+        auto path = r.string_bytes(65536);+        if (!path)+            break;+        const auto size = r.u64le();+        const auto mtime = r.u64le();+        const auto inode = r.u64le();+        const auto kind = r.u8();+        const auto executable = r.u8();+        const auto target = r.id();+        if (!size || !mtime || !inode || !kind || !executable || !target)+            break;+        cache.entries.push_back(+            CacheEntry{std::move(*path), *size, *mtime, *inode, *kind, *executable != 0, *target});+    }+    std::stable_sort(cache.entries.begin(), cache.entries.end(),+                     [](const CacheEntry& a, const CacheEntry& b) {+                         return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+                     });     return cache;-  for (std::uint64_t i = 0; i < *count; ++i) {-    auto path = r.string_bytes(65536);-    if (!path)-      break;-    const auto size = r.u64le();-    const auto mtime = r.u64le();-    const auto inode = r.u64le();-    const auto kind = r.u8();-    const auto executable = r.u8();-    const auto target = r.id();-    if (!size || !mtime || !inode || !kind || !executable || !target)-      break;-    cache.entries.push_back(CacheEntry{std::move(*path), *size, *mtime, *inode,-                                       *kind, *executable != 0, *target});-  }-  std::stable_sort(cache.entries.begin(), cache.entries.end(),-                   [](const CacheEntry &a, const CacheEntry &b) {-                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                   });-  return cache; } -bool save_cache(const fs::path &root, const std::vector<CacheEntry> &entries,+bool save_cache(const fs::path& root, const std::vector<CacheEntry>& entries,                 std::int64_t written_ms) {-  ByteWriter w(4096);-  w.raw("VST1");-  w.u8(49);-  w.u64le(static_cast<std::uint64_t>(written_ms));-  w.varint(entries.size());-  for (const auto &entry : entries) {-    w.length_prefixed(entry.path);-    w.u64le(entry.size);-    w.u64le(entry.mtime_ns);-    w.u64le(entry.inode);-    w.u8(entry.kind);-    w.u8(entry.executable ? 1 : 0);-    w.id(entry.target);-  }-  const fs::path final_path = working_copy_dir(root) / "stat-cache";-  const fs::path tmp_path = tmp_dir(root) / "stat-cache.tmp";-  return write_atomic(tmp_path, final_path, w.view());+    ByteWriter w(4096);+    w.raw("VST1");+    w.u8(49);+    w.u64le(static_cast<std::uint64_t>(written_ms));+    w.varint(entries.size());+    for (const auto& entry : entries) {+        w.length_prefixed(entry.path);+        w.u64le(entry.size);+        w.u64le(entry.mtime_ns);+        w.u64le(entry.inode);+        w.u8(entry.kind);+        w.u8(entry.executable ? 1 : 0);+        w.id(entry.target);+    }+    const fs::path final_path = working_copy_dir(root) / "stat-cache";+    const fs::path tmp_path = tmp_dir(root) / "stat-cache.tmp";+    return write_atomic(tmp_path, final_path, w.view()); } -const CacheEntry *cache_lookup(const Cache &cache, std::string_view path) {-  std::size_t lo = 0;-  std::size_t hi = cache.entries.size();-  while (lo < hi) {-    const std::size_t mid = lo + (hi - lo) / 2;-    const int c = compare(bytes_of(cache.entries[mid].path), bytes_of(path));-    if (c == 0)-      return &cache.entries[mid];-    if (c < 0)-      lo = mid + 1;-    else-      hi = mid;-  }-  return nullptr;+const CacheEntry* cache_lookup(const Cache& cache, std::string_view path) {+    std::size_t lo = 0;+    std::size_t hi = cache.entries.size();+    while (lo < hi) {+        const std::size_t mid = lo + (hi - lo) / 2;+        const int c = compare(bytes_of(cache.entries[mid].path), bytes_of(path));+        if (c == 0)+            return &cache.entries[mid];+        if (c < 0)+            lo = mid + 1;+        else+            hi = mid;+    }+    return nullptr; } -Id add_blob_data(Txn &txn, Bytes data) {-  BlobBuild build = build_blob(data);-  for (auto &object : build.objects) {-    const Id id =-        object.id ? *object.id : object_id(object.type, bytes_of(object.body));-    (void)txn.add_known(object.type, id, std::move(object.body));-  }-  return build.root;+Id add_blob_data(Txn& txn, Bytes data) {+    BlobBuild build = build_blob(data);+    for (auto& object : build.objects) {+        const Id id = object.id ? *object.id : object_id(object.type, bytes_of(object.body));+        (void)txn.add_known(object.type, id, std::move(object.body));+    }+    return build.root; }  struct BuildState {-  bool failed = false;+    bool failed = false; }; -std::optional<Id> empty_tree_id(Txn &txn) {-  static const std::vector<TreeEntry> empty;-  auto body = encode_tree(empty);-  if (!body)-    return std::nullopt;-  return txn.add_object(TYPE_TREE, std::move(*body));+std::optional<Id> empty_tree_id(Txn& txn) {+    static const std::vector<TreeEntry> empty;+    auto body = encode_tree(empty);+    if (!body)+        return std::nullopt;+    return txn.add_object(TYPE_TREE, std::move(*body)); } -std::optional<Id>-build_dir(Txn &txn, const fs::path &root, std::string_view base,-          std::optional<Id> old_tree_id, const IgnoreRules &base_rules,-          const Cache &cache, std::vector<CacheEntry> &new_cache,-          std::int64_t now_ms, BuildState &state, std::size_t depth) {-  if (depth > 4096) {-    state.failed = true;-    return std::nullopt;-  }+std::optional<Id> build_dir(Txn& txn, const fs::path& root, std::string_view base,+                            std::optional<Id> old_tree_id, const IgnoreRules& base_rules,+                            const Cache& cache, std::vector<CacheEntry>& new_cache,+                            std::int64_t now_ms, BuildState& state, std::size_t depth) {+    if (depth > 4096) {+        state.failed = true;+        return std::nullopt;+    } -  IgnoreRules local = base_rules;-  ignore_load_file(local, root, base, ".vnexclude");-  ignore_load_file(local, root, base, ".gitignore");+    IgnoreRules local = base_rules;+    ignore_load_file(local, root, base, ".vnexclude");+    ignore_load_file(local, root, base, ".gitignore"); -  std::optional<Tree> old_tree;-  if (old_tree_id) {-    auto body = txn.store().read_body(*old_tree_id, TYPE_TREE);-    if (!body) {-      state.failed = true;-      return std::nullopt;+    std::optional<Tree> old_tree;+    if (old_tree_id) {+        auto body = txn.store().read_body(*old_tree_id, TYPE_TREE);+        if (!body) {+            state.failed = true;+            return std::nullopt;+        }+        auto decoded = decode_tree(bytes_of(*body));+        if (!decoded) {+            state.failed = true;+            return std::nullopt;+        }+        old_tree = std::move(*decoded);     }-    auto decoded = decode_tree(bytes_of(*body));-    if (!decoded) {-      state.failed = true;-      return std::nullopt;++    const fs::path dir = base.empty() ? root : root / path_from_bytes(base);+    if (!path_is_dir(dir)) {+        state.failed = true;+        return std::nullopt;     }-    old_tree = std::move(*decoded);-  } -  const fs::path dir = base.empty() ? root : root / path_from_bytes(base);-  if (!path_is_dir(dir)) {-    state.failed = true;-    return std::nullopt;-  }+    auto names = list_directory(dir);+    std::stable_sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) {+        return compare(bytes_of(a), bytes_of(b)) < 0;+    }); -  auto names = list_directory(dir);-  std::stable_sort(names.begin(), names.end(),-                   [](const std::string &a, const std::string &b) {-                     return compare(bytes_of(a), bytes_of(b)) < 0;-                   });+    std::vector<TreeEntry> entries;+    for (const auto& name : names) {+        if (is_meta_name(name))+            continue;+        if (old_tree) {+            if (auto base_name = sidecar_base(name)) {+                const int index = find_tree_name(*old_tree, *base_name);+                if (index >= 0 &&+                    old_tree->entries[static_cast<std::size_t>(index)].kind == KIND_CONFLICT)+                    continue;+            }+        } -  std::vector<TreeEntry> entries;-  for (const auto &name : names) {-    if (is_meta_name(name))-      continue;-    if (old_tree) {-      if (auto base_name = sidecar_base(name)) {-        const int index = find_tree_name(*old_tree, *base_name);-        if (index >= 0 &&-            old_tree->entries[static_cast<std::size_t>(index)].kind ==-                KIND_CONFLICT)-          continue;-      }-    }+        const std::string rel = join_rel(base, name);+        const fs::path fs_path = dir / path_from_bytes(name);+        const auto info = stat_path(fs_path);+        if (!info)+            continue;+        const bool is_dir = info->kind == 2;+        const bool ignored = ignore_ignored(local, rel, is_dir);+        const int old_index = old_tree ? find_tree_name(*old_tree, name) : -1;+        if (old_index >= 0 &&+            old_tree->entries[static_cast<std::size_t>(old_index)].kind == KIND_CONFLICT) {+            entries.push_back(+                TreeEntry{name, KIND_CONFLICT,+                          old_tree->entries[static_cast<std::size_t>(old_index)].target});+            continue;+        }+        if (ignored && old_index < 0)+            continue; -    const std::string rel = join_rel(base, name);-    const fs::path fs_path = dir / path_from_bytes(name);-    const auto info = stat_path(fs_path);-    if (!info)-      continue;-    const bool is_dir = info->kind == 2;-    const bool ignored = ignore_ignored(local, rel, is_dir);-    const int old_index = old_tree ? find_tree_name(*old_tree, name) : -1;-    if (old_index >= 0 &&-        old_tree->entries[static_cast<std::size_t>(old_index)].kind ==-            KIND_CONFLICT) {-      entries.push_back(TreeEntry{-          name, KIND_CONFLICT,-          old_tree->entries[static_cast<std::size_t>(old_index)].target});-      continue;+        if (is_dir) {+            std::optional<Id> child_old;+            if (old_tree && old_index >= 0) {+                const auto& old_entry = old_tree->entries[static_cast<std::size_t>(old_index)];+                if (old_entry.kind == KIND_SUBTREE)+                    child_old = old_entry.target;+            }+            auto child = build_dir(txn, root, rel, child_old, local, cache, new_cache, now_ms,+                                   state, depth + 1);+            if (state.failed)+                return std::nullopt;+            if (child)+                entries.push_back(TreeEntry{name, KIND_SUBTREE, *child});+        } else if (info->kind == 3) {+            auto target = path_read_symlink(fs_path);+            if (!target) {+                state.failed = true;+                return std::nullopt;+            }+            const Id blob = add_blob_data(txn, bytes_of(*target));+            entries.push_back(TreeEntry{name, KIND_SYMLINK, blob});+            new_cache.push_back(+                CacheEntry{rel, info->size, info->mtime_ns, info->inode, info->kind, false, blob});+        } else if (info->kind == 1) {+            const bool executable = info->executable;+            std::optional<Id> target;+            if (const auto* cached = cache_lookup(cache, rel)) {+                if (cache_matches(*cached, *info, executable, now_ms, cache.written_ms)) {+                    target = cached->target;+                }+            }+            if (!target) {+                auto data = read_file_opt(fs_path);+                if (!data) {+                    state.failed = true;+                    return std::nullopt;+                }+                target = add_blob_data(txn, bytes_of(*data));+            }+            new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns, info->inode, info->kind,+                                           executable, *target});+            entries.push_back(TreeEntry{name, executable ? KIND_EXECUTABLE : KIND_FILE, *target});+        }     }-    if (ignored && old_index < 0)-      continue; -    if (is_dir) {-      std::optional<Id> child_old;-      if (old_tree && old_index >= 0) {-        const auto &old_entry =-            old_tree->entries[static_cast<std::size_t>(old_index)];-        if (old_entry.kind == KIND_SUBTREE)-          child_old = old_entry.target;-      }-      auto child = build_dir(txn, root, rel, child_old, local, cache, new_cache,-                             now_ms, state, depth + 1);-      if (state.failed)+    if (entries.empty())         return std::nullopt;-      if (child)-        entries.push_back(TreeEntry{name, KIND_SUBTREE, *child});-    } else if (info->kind == 3) {-      auto target = path_read_symlink(fs_path);-      if (!target) {+    auto body = encode_tree(entries);+    if (!body) {         state.failed = true;         return std::nullopt;-      }-      const Id blob = add_blob_data(txn, bytes_of(*target));-      entries.push_back(TreeEntry{name, KIND_SYMLINK, blob});-      new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns,-                                     info->inode, info->kind, false, blob});-    } else if (info->kind == 1) {-      const bool executable = info->executable;-      std::optional<Id> target;-      if (const auto *cached = cache_lookup(cache, rel)) {-        if (cache_matches(*cached, *info, executable, now_ms,-                          cache.written_ms)) {-          target = cached->target;-        }-      }-      if (!target) {-        auto data = read_file_opt(fs_path);-        if (!data) {-          state.failed = true;-          return std::nullopt;-        }-        target = add_blob_data(txn, bytes_of(*data));-      }-      new_cache.push_back(CacheEntry{rel, info->size, info->mtime_ns,-                                     info->inode, info->kind, executable,-                                     *target});-      entries.push_back(-          TreeEntry{name, executable ? KIND_EXECUTABLE : KIND_FILE, *target});     }-  }--  if (entries.empty())-    return std::nullopt;-  auto body = encode_tree(entries);-  if (!body) {-    state.failed = true;-    return std::nullopt;-  }-  return txn.add_object(TYPE_TREE, std::move(*body));+    return txn.add_object(TYPE_TREE, std::move(*body)); }  // ---------------------------------------------------------------------------@@ -328,414 +316,404 @@ // ---------------------------------------------------------------------------  struct WalkEntry {-  std::string path;-  std::uint8_t kind = 0;-  Id target{};+    std::string path;+    std::uint8_t kind = 0;+    Id target{}; };  bool valid_checkout_component(std::string_view component) {-  if (!valid_name(component))-    return false;-  return !ascii_iequals(bytes_of(component), bytes_of(".git"));+    if (!valid_name(component))+        return false;+    return !ascii_iequals(bytes_of(component), bytes_of(".git")); }  bool valid_checkout_path(std::string_view path) {-  if (!valid_path(path))-    return false;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= path.size(); ++i) {-    if (i == path.size() || path[i] == '/') {-      if (!valid_checkout_component(path.substr(start, i - start)))+    if (!valid_path(path))         return false;-      start = i + 1;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= path.size(); ++i) {+        if (i == path.size() || path[i] == '/') {+            if (!valid_checkout_component(path.substr(start, i - start)))+                return false;+            start = i + 1;+        }     }-  }-  return true;+    return true; } -bool has_symlink_component(const fs::path &root, std::string_view rel) {-  fs::path current = root;-  std::size_t start = 0;-  for (std::size_t i = 0; i < rel.size(); ++i) {-    if (rel[i] == '/') {-      if (i == start)-        return true;-      current /= path_from_bytes(rel.substr(start, i - start));-      const auto info = stat_path(current);-      if (info && info->kind == 3)-        return true;-      start = i + 1;+bool has_symlink_component(const fs::path& root, std::string_view rel) {+    fs::path current = root;+    std::size_t start = 0;+    for (std::size_t i = 0; i < rel.size(); ++i) {+        if (rel[i] == '/') {+            if (i == start)+                return true;+            current /= path_from_bytes(rel.substr(start, i - start));+            const auto info = stat_path(current);+            if (info && info->kind == 3)+                return true;+            start = i + 1;+        }     }-  }-  return false;+    return false; } -bool ensure_safe_dirs(const fs::path &root, std::string_view rel) {-  if (rel.empty())-    return true;-  fs::path current = root;-  std::size_t start = 0;-  for (std::size_t i = 0; i <= rel.size(); ++i) {-    const bool at_end = i == rel.size();-    if (!at_end && rel[i] != '/')-      continue;-    const std::string_view component = rel.substr(start, i - start);-    if (component.empty())-      return false;-    if (at_end)-      break; // final component is the file-    current /= path_from_bytes(component);-    const auto info = stat_path(current);-    if (info) {-      if (info->kind == 3 || info->kind != 2)-        return false;-    } else if (!ensure_directory(current)) {-      return false;+bool ensure_safe_dirs(const fs::path& root, std::string_view rel) {+    if (rel.empty())+        return true;+    fs::path current = root;+    std::size_t start = 0;+    for (std::size_t i = 0; i <= rel.size(); ++i) {+        const bool at_end = i == rel.size();+        if (!at_end && rel[i] != '/')+            continue;+        const std::string_view component = rel.substr(start, i - start);+        if (component.empty())+            return false;+        if (at_end)+            break; // final component is the file+        current /= path_from_bytes(component);+        const auto info = stat_path(current);+        if (info) {+            if (info->kind == 3 || info->kind != 2)+                return false;+        } else if (!ensure_directory(current)) {+            return false;+        }+        start = i + 1;     }-    start = i + 1;-  }-  return true;+    return true; } -bool remove_any(const fs::path &path) {-  std::error_code ec;-  if (path_is_dir(path) && !path_is_symlink(path)) {-    fs::remove_all(path, ec);-    return !ec;-  }-  return remove_file(path);+bool remove_any(const fs::path& path) {+    std::error_code ec;+    if (path_is_dir(path) && !path_is_symlink(path)) {+        fs::remove_all(path, ec);+        return !ec;+    }+    return remove_file(path); } -bool write_bytes_to_path(const fs::path &root, std::string_view rel, Bytes data,-                         bool executable, std::string &error_path) {-  error_path = std::string(rel);-  if (!valid_checkout_path(rel) || has_symlink_component(root, rel))-    return false;-  if (!ensure_safe_dirs(root, rel))-    return false;-  const fs::path final_path = root / path_from_bytes(rel);-  if (path_is_dir(final_path) && !path_is_symlink(final_path))-    return false;-  if (path_is_symlink(final_path))-    (void)remove_file(final_path);-  if (!write_file(final_path, data))-    return false;+bool write_bytes_to_path(const fs::path& root, std::string_view rel, Bytes data, bool executable,+                         std::string& error_path) {+    error_path = std::string(rel);+    if (!valid_checkout_path(rel) || has_symlink_component(root, rel))+        return false;+    if (!ensure_safe_dirs(root, rel))+        return false;+    const fs::path final_path = root / path_from_bytes(rel);+    if (path_is_dir(final_path) && !path_is_symlink(final_path))+        return false;+    if (path_is_symlink(final_path))+        (void)remove_file(final_path);+    if (!write_file(final_path, data))+        return false; #if !defined(_WIN32)-  const mode_t mode = executable ? 0755 : 0644;-  (void)::chmod(final_path.c_str(), mode);+    const mode_t mode = executable ? 0755 : 0644;+    (void)::chmod(final_path.c_str(), mode); #else-  (void)executable;+    (void)executable; #endif-  return true;+    return true; } -bool write_symlink_to_path(const fs::path &root, std::string_view rel,-                           std::string_view target, std::string &error_path) {-  error_path = std::string(rel);-  if (!valid_checkout_path(rel) || has_symlink_component(root, rel))-    return false;-  if (!ensure_safe_dirs(root, rel))-    return false;-  const fs::path final_path = root / path_from_bytes(rel);-  if (path_is_dir(final_path) && !path_is_symlink(final_path))-    return false;-  if (path_exists(final_path))-    (void)remove_any(final_path);-  std::error_code ec;-  fs::create_symlink(path_from_bytes(target), final_path, ec);-  return !ec;+bool write_symlink_to_path(const fs::path& root, std::string_view rel, std::string_view target,+                           std::string& error_path) {+    error_path = std::string(rel);+    if (!valid_checkout_path(rel) || has_symlink_component(root, rel))+        return false;+    if (!ensure_safe_dirs(root, rel))+        return false;+    const fs::path final_path = root / path_from_bytes(rel);+    if (path_is_dir(final_path) && !path_is_symlink(final_path))+        return false;+    if (path_exists(final_path))+        (void)remove_any(final_path);+    std::error_code ec;+    fs::create_symlink(path_from_bytes(target), final_path, ec);+    return !ec; } -bool write_entry(Store &store, const fs::path &root, const WalkEntry &entry,-                 std::string &error_path) {-  if (entry.kind == KIND_SYMLINK) {+bool write_entry(Store& store, const fs::path& root, const WalkEntry& entry,+                 std::string& error_path) {+    if (entry.kind == KIND_SYMLINK) {+        auto data = read_blob(store, entry.target);+        if (!data)+            return false;+        return write_symlink_to_path(root, entry.path, str_of(bytes_of(*data)), error_path);+    }     auto data = read_blob(store, entry.target);     if (!data)-      return false;-    return write_symlink_to_path(root, entry.path, str_of(bytes_of(*data)),-                                 error_path);-  }-  auto data = read_blob(store, entry.target);-  if (!data)-    return false;-  return write_bytes_to_path(root, entry.path, bytes_of(*data),-                             entry.kind == KIND_EXECUTABLE, error_path);+        return false;+    return write_bytes_to_path(root, entry.path, bytes_of(*data), entry.kind == KIND_EXECUTABLE,+                               error_path); } -bool prune_empty_parents(const fs::path &root, std::string_view rel) {-  std::size_t end = rel.size();-  while (end > 0) {-    const std::size_t slash = rel.rfind('/', end - 1);-    if (slash == std::string_view::npos)-      break;-    const std::string parent(rel.substr(0, slash));-    const fs::path abs = root / path_from_bytes(parent);-    std::error_code ec;-    if (!fs::remove(abs, ec) || ec)-      break;-    end = slash;-  }-  return true;+bool prune_empty_parents(const fs::path& root, std::string_view rel) {+    std::size_t end = rel.size();+    while (end > 0) {+        const std::size_t slash = rel.rfind('/', end - 1);+        if (slash == std::string_view::npos)+            break;+        const std::string parent(rel.substr(0, slash));+        const fs::path abs = root / path_from_bytes(parent);+        std::error_code ec;+        if (!fs::remove(abs, ec) || ec)+            break;+        end = slash;+    }+    return true; } -void remove_tracked_path(const fs::path &root, std::string_view rel) {-  const fs::path abs = root / path_from_bytes(rel);-  if (path_exists(abs) || path_is_symlink(abs)) {-    (void)remove_any(abs);-    (void)prune_empty_parents(root, rel);-  }+void remove_tracked_path(const fs::path& root, std::string_view rel) {+    const fs::path abs = root / path_from_bytes(rel);+    if (path_exists(abs) || path_is_symlink(abs)) {+        (void)remove_any(abs);+        (void)prune_empty_parents(root, rel);+    } }  std::vector<std::string> sidecar_suffixes() {-  std::vector<std::string> out = {".base", ".ours", ".theirs"};-  for (int n = 2; n <= 64; ++n) {-    out.push_back(".base" + std::to_string(n));-    out.push_back(".theirs" + std::to_string(n));-  }-  return out;-}--void delete_sidecars(const fs::path &root, std::string_view path) {-  static const auto suffixes = sidecar_suffixes();-  for (const auto &suffix : suffixes) {-    std::string full(path);-    full += suffix;-    remove_tracked_path(root, full);-  }+    std::vector<std::string> out = {".base", ".ours", ".theirs"};+    for (int n = 2; n <= 64; ++n) {+        out.push_back(".base" + std::to_string(n));+        out.push_back(".theirs" + std::to_string(n));+    }+    return out; } -bool delete_stale(Store &store, const fs::path &root,-                  const std::vector<FlatEntry> &old_entries,-                  const std::vector<FlatEntry> &new_entries) {-  bool ok = true;-  for (const auto &old_entry : old_entries) {-    if (old_entry.kind == KIND_SUBMODULE)-      continue;-    if (find_flat(new_entries, old_entry.path))-      continue;-    const fs::path abs = root / path_from_bytes(old_entry.path);-    if (path_exists(abs) || path_is_symlink(abs)) {-      if (!remove_any(abs))-        ok = false;-      else-        (void)prune_empty_parents(root, old_entry.path);+void delete_sidecars(const fs::path& root, std::string_view path) {+    static const auto suffixes = sidecar_suffixes();+    for (const auto& suffix : suffixes) {+        std::string full(path);+        full += suffix;+        remove_tracked_path(root, full);     }-    if (old_entry.kind == KIND_CONFLICT)-      delete_sidecars(root, old_entry.path);-  }-  (void)store;-  return ok; } -std::optional<Conflict> load_conflict(Store &store, const Id &id) {-  auto body = store.read_body(id, TYPE_CONFLICT);-  if (!body)-    return std::nullopt;-  auto decoded = decode_conflict(bytes_of(*body));-  if (!decoded)-    return std::nullopt;-  return std::move(*decoded);+bool delete_stale(Store& store, const fs::path& root, const std::vector<FlatEntry>& old_entries,+                  const std::vector<FlatEntry>& new_entries) {+    bool ok = true;+    for (const auto& old_entry : old_entries) {+        if (old_entry.kind == KIND_SUBMODULE)+            continue;+        if (find_flat(new_entries, old_entry.path))+            continue;+        const fs::path abs = root / path_from_bytes(old_entry.path);+        if (path_exists(abs) || path_is_symlink(abs)) {+            if (!remove_any(abs))+                ok = false;+            else+                (void)prune_empty_parents(root, old_entry.path);+        }+        if (old_entry.kind == KIND_CONFLICT)+            delete_sidecars(root, old_entry.path);+    }+    (void)store;+    return ok; } -bool write_tree_side(Store &store, const fs::path &root, const Id &tree_id,-                     std::string_view prefix, std::string &error_path) {-  const auto entries = flatten_tree(store, tree_id);-  for (const auto &entry : entries) {-    if (entry.kind == KIND_CONFLICT)-      continue;-    if (entry.kind == KIND_SUBMODULE)-      continue;-    std::string path(prefix);-    if (!path.empty())-      path.push_back('/');-    path += entry.path;-    if (!write_entry(store, root, WalkEntry{path, entry.kind, entry.target},-                     error_path))-      return false;-  }-  return true;+std::optional<Conflict> load_conflict(Store& store, const Id& id) {+    auto body = store.read_body(id, TYPE_CONFLICT);+    if (!body)+        return std::nullopt;+    auto decoded = decode_conflict(bytes_of(*body));+    if (!decoded)+        return std::nullopt;+    return std::move(*decoded); } -bool materialize_value(Store &store, const fs::path &root,-                       std::string_view path, const ConflictValue &value,-                       std::string &error_path) {-  error_path = std::string(path);-  if (value.kind == 0) {-    remove_tracked_path(root, path);+bool write_tree_side(Store& store, const fs::path& root, const Id& tree_id, std::string_view prefix,+                     std::string& error_path) {+    const auto entries = flatten_tree(store, tree_id);+    for (const auto& entry : entries) {+        if (entry.kind == KIND_CONFLICT)+            continue;+        if (entry.kind == KIND_SUBMODULE)+            continue;+        std::string path(prefix);+        if (!path.empty())+            path.push_back('/');+        path += entry.path;+        if (!write_entry(store, root, WalkEntry{path, entry.kind, entry.target}, error_path))+            return false;+    }     return true;-  }-  if (!value.target)-    return false;-  if (value.kind == KIND_SUBTREE) {-    remove_tracked_path(root, path);-    return write_tree_side(store, root, *value.target, path, error_path);-  }-  return write_entry(store, root,-                     WalkEntry{std::string(path), value.kind, *value.target},-                     error_path); } -bool materialize_conflict(Store &store, const fs::path &root,-                          std::string_view path, const Id &target,-                          std::string &error_path) {-  auto conflict = load_conflict(store, target);-  if (!conflict) {+bool materialize_value(Store& store, const fs::path& root, std::string_view path,+                       const ConflictValue& value, std::string& error_path) {     error_path = std::string(path);-    return false;-  }-  bool ok = true;-  for (std::size_t i = 0; i < conflict->removes.size(); ++i) {-    std::string suffix = i == 0 ? ".base" : ".base" + std::to_string(i + 1);-    std::string full(path);-    full += suffix;-    if (!materialize_value(store, root, full, conflict->removes[i], error_path))-      ok = false;-  }-  for (std::size_t i = 0; i < conflict->adds.size(); ++i) {-    std::string suffix;-    if (i == 0)-      suffix = ".ours";-    else if (i == 1)-      suffix = ".theirs";-    else-      suffix = ".theirs" + std::to_string(i + 1);-    std::string full(path);-    full += suffix;-    if (!materialize_value(store, root, full, conflict->adds[i], error_path))-      ok = false;-  }-  if (!conflict->adds.empty()) {-    if (!materialize_value(store, root, path, conflict->adds.front(),-                           error_path))-      ok = false;-  } else {-    remove_tracked_path(root, path);-  }-  return ok;+    if (value.kind == 0) {+        remove_tracked_path(root, path);+        return true;+    }+    if (!value.target)+        return false;+    if (value.kind == KIND_SUBTREE) {+        remove_tracked_path(root, path);+        return write_tree_side(store, root, *value.target, path, error_path);+    }+    return write_entry(store, root, WalkEntry{std::string(path), value.kind, *value.target},+                       error_path); } -int materialize_tree(Store &store, const fs::path &root,-                     const std::vector<FlatEntry> &old_entries,-                     const Id &new_root) {-  auto checked_entries = flatten_tree_checked(store, new_root);-  if (!checked_entries) {-    error_prefix();-    std::cout << "checkout tree validation failed\n";-    return 1;-  }-  const auto &new_entries = *checked_entries;-  std::set<std::string> dirs;-  std::vector<WalkEntry> files;-  std::vector<FlatEntry> conflicts;-  for (const auto &entry : new_entries) {-    if (!valid_checkout_path(entry.path)) {-      error_prefix();-      std::cout << "checkout tree validation failed at: " << entry.path << "\n";-      return 1;+bool materialize_conflict(Store& store, const fs::path& root, std::string_view path,+                          const Id& target, std::string& error_path) {+    auto conflict = load_conflict(store, target);+    if (!conflict) {+        error_path = std::string(path);+        return false;     }-    std::string dir_path;-    std::size_t start = 0;-    for (std::size_t i = 0; i < entry.path.size(); ++i) {-      if (entry.path[i] == '/') {-        dir_path.append(entry.path.substr(start, i - start));-        dirs.insert(dir_path);-        dir_path.push_back('/');-        start = i + 1;-      }+    bool ok = true;+    for (std::size_t i = 0; i < conflict->removes.size(); ++i) {+        std::string suffix = i == 0 ? ".base" : ".base" + std::to_string(i + 1);+        std::string full(path);+        full += suffix;+        if (!materialize_value(store, root, full, conflict->removes[i], error_path))+            ok = false;     }-    if (entry.kind == KIND_CONFLICT) {-      conflicts.push_back(entry);-    } else if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||-               entry.kind == KIND_SYMLINK) {-      files.push_back(WalkEntry{entry.path, entry.kind, entry.target});+    for (std::size_t i = 0; i < conflict->adds.size(); ++i) {+        std::string suffix;+        if (i == 0)+            suffix = ".ours";+        else if (i == 1)+            suffix = ".theirs";+        else+            suffix = ".theirs" + std::to_string(i + 1);+        std::string full(path);+        full += suffix;+        if (!materialize_value(store, root, full, conflict->adds[i], error_path))+            ok = false;     }-  }+    if (!conflict->adds.empty()) {+        if (!materialize_value(store, root, path, conflict->adds.front(), error_path))+            ok = false;+    } else {+        remove_tracked_path(root, path);+    }+    return ok;+} -  // Sidecar collision check.-  const auto suffixes = sidecar_suffixes();-  for (const auto &conflict : conflicts) {-    for (const auto &suffix : suffixes) {-      std::string full = conflict.path;-      full += suffix;-      if (find_flat(old_entries, full)) {+int materialize_tree(Store& store, const fs::path& root, const std::vector<FlatEntry>& old_entries,+                     const Id& new_root) {+    auto checked_entries = flatten_tree_checked(store, new_root);+    if (!checked_entries) {         error_prefix();-        std::cout << "conflict sidecar would overwrite a tracked path: " << full-                  << "\n";+        std::cout << "checkout tree validation failed\n";         return 1;-      }     }-  }+    const auto& new_entries = *checked_entries;+    std::set<std::string> dirs;+    std::vector<WalkEntry> files;+    std::vector<FlatEntry> conflicts;+    for (const auto& entry : new_entries) {+        if (!valid_checkout_path(entry.path)) {+            error_prefix();+            std::cout << "checkout tree validation failed at: " << entry.path << "\n";+            return 1;+        }+        std::string dir_path;+        std::size_t start = 0;+        for (std::size_t i = 0; i < entry.path.size(); ++i) {+            if (entry.path[i] == '/') {+                dir_path.append(entry.path.substr(start, i - start));+                dirs.insert(dir_path);+                dir_path.push_back('/');+                start = i + 1;+            }+        }+        if (entry.kind == KIND_CONFLICT) {+            conflicts.push_back(entry);+        } else if (entry.kind == KIND_FILE || entry.kind == KIND_EXECUTABLE ||+                   entry.kind == KIND_SYMLINK) {+            files.push_back(WalkEntry{entry.path, entry.kind, entry.target});+        }+    } -  // Remove sidecars left by a previous materialization.-  for (const auto &entry : old_entries) {-    if (entry.kind == KIND_CONFLICT)-      delete_sidecars(root, entry.path);-  }+    // Sidecar collision check.+    const auto suffixes = sidecar_suffixes();+    for (const auto& conflict : conflicts) {+        for (const auto& suffix : suffixes) {+            std::string full = conflict.path;+            full += suffix;+            if (find_flat(old_entries, full)) {+                error_prefix();+                std::cout << "conflict sidecar would overwrite a tracked path: " << full << "\n";+                return 1;+            }+        }+    } -  if (!delete_stale(store, root, old_entries, new_entries)) {-    error_prefix();-    std::cout << "cannot remove files that are absent from the target tree\n";-    return 1;-  }+    // Remove sidecars left by a previous materialization.+    for (const auto& entry : old_entries) {+        if (entry.kind == KIND_CONFLICT)+            delete_sidecars(root, entry.path);+    } -  for (const auto &dir : dirs) {-    if (!ensure_safe_dirs(root, dir + "/x")) {-      error_prefix();-      std::cout << "cannot create directory: " << dir << "\n";-      return 1;+    if (!delete_stale(store, root, old_entries, new_entries)) {+        error_prefix();+        std::cout << "cannot remove files that are absent from the target tree\n";+        return 1;     }-  } -  std::string error_path;-  if (!files.empty()) {-    std::size_t workers = available_cpu_count();-    if (workers == 0)-      workers = 1;-    workers = std::min<std::size_t>(workers, files.size());-    workers = std::min<std::size_t>(workers, 16);-    if (workers > 1)-      store.preload();-    std::atomic<std::size_t> next{0};-    std::atomic<bool> failed{false};-    std::mutex error_mutex;-    std::vector<std::thread> threads;-    threads.reserve(workers);-    for (std::size_t w = 0; w < workers; ++w) {-      threads.emplace_back([&]() {-        for (;;) {-          const std::size_t index = next.fetch_add(1);-          if (index >= files.size() || failed.load(std::memory_order_relaxed))-            return;-          std::string local_error;-          if (!write_entry(store, root, files[index], local_error)) {-            std::lock_guard<std::mutex> lock(error_mutex);-            if (!failed.exchange(true))-              error_path = std::move(local_error);-            return;-          }+    for (const auto& dir : dirs) {+        if (!ensure_safe_dirs(root, dir + "/x")) {+            error_prefix();+            std::cout << "cannot create directory: " << dir << "\n";+            return 1;         }-      });     }-    for (auto &thread : threads)-      thread.join();-    if (failed.load()) {-      error_prefix();-      std::cout << "checkout failed at: " << error_path << "\n";-      return 1;++    std::string error_path;+    if (!files.empty()) {+        std::size_t workers = available_cpu_count();+        if (workers == 0)+            workers = 1;+        workers = std::min<std::size_t>(workers, files.size());+        workers = std::min<std::size_t>(workers, 16);+        if (workers > 1)+            store.preload();+        std::atomic<std::size_t> next{0};+        std::atomic<bool> failed{false};+        std::mutex error_mutex;+        std::vector<std::thread> threads;+        threads.reserve(workers);+        for (std::size_t w = 0; w < workers; ++w) {+            threads.emplace_back([&]() {+                for (;;) {+                    const std::size_t index = next.fetch_add(1);+                    if (index >= files.size() || failed.load(std::memory_order_relaxed))+                        return;+                    std::string local_error;+                    if (!write_entry(store, root, files[index], local_error)) {+                        std::lock_guard<std::mutex> lock(error_mutex);+                        if (!failed.exchange(true))+                            error_path = std::move(local_error);+                        return;+                    }+                }+            });+        }+        for (auto& thread : threads)+            thread.join();+        if (failed.load()) {+            error_prefix();+            std::cout << "checkout failed at: " << error_path << "\n";+            return 1;+        }     }-  }-  for (const auto &conflict : conflicts) {-    if (!materialize_conflict(store, root, conflict.path, conflict.target,-                              error_path)) {-      error_prefix();-      std::cout << "checkout failed at: " << error_path << "\n";-      return 1;+    for (const auto& conflict : conflicts) {+        if (!materialize_conflict(store, root, conflict.path, conflict.target, error_path)) {+            error_prefix();+            std::cout << "checkout failed at: " << error_path << "\n";+            return 1;+        }     }-  } -  info_prefix();-  std::cout << "checked out " << files.size() << " files\n";-  return 0;+    info_prefix();+    std::cout << "checked out " << files.size() << " files\n";+    return 0; }  } // namespace@@ -744,157 +722,150 @@ // Snapshot // --------------------------------------------------------------------------- -int snapshot_run(const fs::path &root) {-  Store store = Store::open_all(root);-  const int status = snapshot_run(root, store);-  return status;+int snapshot_run(const fs::path& root) {+    Store store = Store::open_all(root);+    const int status = snapshot_run(root, store);+    return status; }--int snapshot_run(const fs::path &root, Store &store) {-  auto tx = Txn::begin(root, store);-  if (!tx) {-    error_prefix();-    std::cout << "cannot load repository state\n";-    return 1;-  } -  const auto wc = working_copy_id(tx->view());-  std::optional<Commit> old_commit;-  std::optional<Id> old_tree;-  bool old_empty = false;-  bool have_wc = false;-  if (wc) {-    have_wc = true;-    auto body = tx->store().read_body(*wc, TYPE_COMMIT);-    if (!body) {-      error_prefix();-      std::cout << "missing working-copy commit\n";-      return 1;-    }-    auto decoded = decode_commit(bytes_of(*body));-    if (!decoded) {-      error_prefix();-      std::cout << "corrupt working-copy commit\n";-      return 1;+int snapshot_run(const fs::path& root, Store& store) {+    auto tx = Txn::begin(root, store);+    if (!tx) {+        error_prefix();+        std::cout << "cannot load repository state\n";+        return 1;     }-    old_commit = std::move(*decoded);-    old_tree = old_commit->root_tree;-    if (old_commit->parents.size() == 1) {-      auto parent_body =-          tx->store().read_body(old_commit->parents.front(), TYPE_COMMIT);-      if (parent_body) {-        auto parent_commit = decode_commit(bytes_of(*parent_body));-        if (parent_commit)-          old_empty = std::memcmp(parent_commit->root_tree.data(),-                                  old_commit->root_tree.data(), ID_LEN) == 0;-      }++    const auto wc = working_copy_id(tx->view());+    std::optional<Commit> old_commit;+    std::optional<Id> old_tree;+    bool old_empty = false;+    bool have_wc = false;+    if (wc) {+        have_wc = true;+        auto body = tx->store().read_body(*wc, TYPE_COMMIT);+        if (!body) {+            error_prefix();+            std::cout << "missing working-copy commit\n";+            return 1;+        }+        auto decoded = decode_commit(bytes_of(*body));+        if (!decoded) {+            error_prefix();+            std::cout << "corrupt working-copy commit\n";+            return 1;+        }+        old_commit = std::move(*decoded);+        old_tree = old_commit->root_tree;+        if (old_commit->parents.size() == 1) {+            auto parent_body = tx->store().read_body(old_commit->parents.front(), TYPE_COMMIT);+            if (parent_body) {+                auto parent_commit = decode_commit(bytes_of(*parent_body));+                if (parent_commit)+                    old_empty = std::memcmp(parent_commit->root_tree.data(),+                                            old_commit->root_tree.data(), ID_LEN) == 0;+            }+        }     }-  } -  IgnoreRules rules = ignore_empty();-  ignore_load_root(rules, root);-  const Cache cache = load_cache(root);-  std::vector<CacheEntry> new_cache;-  const std::int64_t now_ms = unix_now_millis();-  BuildState state;-  auto built = build_dir(*tx, root, "", old_tree, rules, cache, new_cache,-                         now_ms, state, 0);+    IgnoreRules rules = ignore_empty();+    ignore_load_root(rules, root);+    const Cache cache = load_cache(root);+    std::vector<CacheEntry> new_cache;+    const std::int64_t now_ms = unix_now_millis();+    BuildState state;+    auto built = build_dir(*tx, root, "", old_tree, rules, cache, new_cache, now_ms, state, 0); -  std::optional<Id> new_root;-  if (!state.failed && built) {-    new_root = built;-  } else if (!state.failed) {-    new_root = empty_tree_id(*tx);-  }-  if (!new_root || state.failed) {-    error_prefix();-    std::cout << "failed to build working-copy tree\n";-    return 1;-  }+    std::optional<Id> new_root;+    if (!state.failed && built) {+        new_root = built;+    } else if (!state.failed) {+        new_root = empty_tree_id(*tx);+    }+    if (!new_root || state.failed) {+        error_prefix();+        std::cout << "failed to build working-copy tree\n";+        return 1;+    } -  const bool unchanged =-      old_tree && std::memcmp(old_tree->data(), new_root->data(), ID_LEN) == 0;-  if (unchanged) {-    std::vector<CacheEntry> sorted = new_cache;-    std::stable_sort(sorted.begin(), sorted.end(),-                     [](const CacheEntry &a, const CacheEntry &b) {-                       return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                     });-    (void)save_cache(root, sorted, now_ms);-    return 0;-  }+    const bool unchanged = old_tree && std::memcmp(old_tree->data(), new_root->data(), ID_LEN) == 0;+    if (unchanged) {+        std::vector<CacheEntry> sorted = new_cache;+        std::stable_sort(sorted.begin(), sorted.end(),+                         [](const CacheEntry& a, const CacheEntry& b) {+                             return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+                         });+        (void)save_cache(root, sorted, now_ms);+        return 0;+    } -  const Sig committer = identity_signature(root);-  Sig author = committer;-  std::vector<Id> parents;-  ChangeId change_id{};-  std::string message;-  if (old_commit) {-    if (!old_empty)-      author = old_commit->author;-    parents = old_commit->parents;-    change_id = old_commit->change_id;-    message = old_commit->message;-  } else {-    change_id = random_change_id();-  }+    const Sig committer = identity_signature(root);+    Sig author = committer;+    std::vector<Id> parents;+    ChangeId change_id{};+    std::string message;+    if (old_commit) {+        if (!old_empty)+            author = old_commit->author;+        parents = old_commit->parents;+        change_id = old_commit->change_id;+        message = old_commit->message;+    } else {+        change_id = random_change_id();+    } -  std::vector<Rename> renames;-  if (old_commit)-    renames = old_commit->renames;-  if (old_tree &&-      std::memcmp(old_tree->data(), new_root->data(), ID_LEN) != 0) {-    auto detected = detect_renames(tx->store(), &*tx, old_tree,-                                   std::optional<Id>{*new_root},-                                   rename_similar_pct(root), 0);-    for (auto &rename : detected)-      renames.push_back(std::move(rename));-  }-  std::stable_sort(-      renames.begin(), renames.end(), [](const Rename &a, const Rename &b) {+    std::vector<Rename> renames;+    if (old_commit)+        renames = old_commit->renames;+    if (old_tree && std::memcmp(old_tree->data(), new_root->data(), ID_LEN) != 0) {+        auto detected = detect_renames(tx->store(), &*tx, old_tree, std::optional<Id>{*new_root},+                                       rename_similar_pct(root), 0);+        for (auto& rename : detected)+            renames.push_back(std::move(rename));+    }+    std::stable_sort(renames.begin(), renames.end(), [](const Rename& a, const Rename& b) {         if (a.parent_index != b.parent_index)-          return a.parent_index < b.parent_index;+            return a.parent_index < b.parent_index;         return compare(bytes_of(a.to_path), bytes_of(b.to_path)) < 0;-      });+    }); -  Commit commit;-  commit.version = 1;-  commit.parents = parents;-  commit.root_tree = *new_root;-  commit.change_id = change_id;-  commit.author = author;-  commit.committer = committer;-  commit.message = message;-  commit.renames_state = RENAMES_RECORDED;-  commit.renames = std::move(renames);-  commit.extra = old_commit ? old_commit->extra : std::vector<KeyValue>{};-  const auto encoded = encode_commit(commit);-  const Id new_commit = tx->add_object(TYPE_COMMIT, encoded);+    Commit commit;+    commit.version = 1;+    commit.parents = parents;+    commit.root_tree = *new_root;+    commit.change_id = change_id;+    commit.author = author;+    commit.committer = committer;+    commit.message = message;+    commit.renames_state = RENAMES_RECORDED;+    commit.renames = std::move(renames);+    commit.extra = old_commit ? old_commit->extra : std::vector<KeyValue>{};+    const auto encoded = encode_commit(commit);+    const Id new_commit = tx->add_object(TYPE_COMMIT, encoded); -  if (have_wc) {-    remove_head(tx->view(), *wc);-    move_bookmarks(tx->view(), *wc, new_commit);-  }-  if (auto current = current_bookmark_name(root)) {-    if (find_bookmark(tx->view(), *current))-      set_bookmark_target(tx->view(), *current, new_commit);-  }-  set_workspace(tx->view(), new_commit);-  rebuild_heads(tx->view());+    if (have_wc) {+        remove_head(tx->view(), *wc);+        move_bookmarks(tx->view(), *wc, new_commit);+    }+    if (auto current = current_bookmark_name(root)) {+        if (find_bookmark(tx->view(), *current))+            set_bookmark_target(tx->view(), *current, new_commit);+    }+    set_workspace(tx->view(), new_commit);+    rebuild_heads(tx->view()); -  const auto status = tx->finish("snapshot");-  if (!status)-    return 1;-  store.refresh(root);-  (void)mark_native(root, new_commit);+    const auto status = tx->finish("snapshot");+    if (!status)+        return 1;+    store.refresh(root);+    (void)mark_native(root, new_commit); -  std::vector<CacheEntry> sorted = new_cache;-  std::stable_sort(sorted.begin(), sorted.end(),-                   [](const CacheEntry &a, const CacheEntry &b) {-                     return compare(bytes_of(a.path), bytes_of(b.path)) < 0;-                   });-  (void)save_cache(root, sorted, now_ms);-  return 0;+    std::vector<CacheEntry> sorted = new_cache;+    std::stable_sort(sorted.begin(), sorted.end(), [](const CacheEntry& a, const CacheEntry& b) {+        return compare(bytes_of(a.path), bytes_of(b.path)) < 0;+    });+    (void)save_cache(root, sorted, now_ms);+    return 0; }  // ---------------------------------------------------------------------------@@ -901,147 +872,144 @@ // Checkout // --------------------------------------------------------------------------- -int checkout_materialize_commit(const fs::path &root, Store &store,-                                std::optional<Id> old_root,-                                const Id &new_root) {-  if (old_root && std::memcmp(old_root->data(), new_root.data(), ID_LEN) == 0)-    return 0;-  const auto old_entries = flatten_or_empty(store, old_root);-  const int status = materialize_tree(store, root, old_entries, new_root);-  if (status == 0)-    clear_stat_cache(root);-  return status;+int checkout_materialize_commit(const fs::path& root, Store& store, std::optional<Id> old_root,+                                const Id& new_root) {+    if (old_root && std::memcmp(old_root->data(), new_root.data(), ID_LEN) == 0)+        return 0;+    const auto old_entries = flatten_or_empty(store, old_root);+    const int status = materialize_tree(store, root, old_entries, new_root);+    if (status == 0)+        clear_stat_cache(root);+    return status; } -void clear_stat_cache(const fs::path &root) {-  (void)remove_file(working_copy_dir(root) / "stat-cache");+void clear_stat_cache(const fs::path& root) {+    (void)remove_file(working_copy_dir(root) / "stat-cache"); } -int checkout_materialize_optional(const fs::path &root, Store &store,-                                  std::optional<Id> old_root,+int checkout_materialize_optional(const fs::path& root, Store& store, std::optional<Id> old_root,                                   std::optional<Id> new_root) {-  if (new_root)-    return checkout_materialize_commit(root, store, old_root, *new_root);-  const auto old_entries = flatten_or_empty(store, old_root);-  if (old_entries.empty()) {+    if (new_root)+        return checkout_materialize_commit(root, store, old_root, *new_root);+    const auto old_entries = flatten_or_empty(store, old_root);+    if (old_entries.empty()) {+        clear_stat_cache(root);+        return 0;+    }+    if (!delete_stale(store, root, old_entries, {})) {+        error_prefix();+        std::cout << "cannot remove files absent from the restored view\n";+        return 1;+    }     clear_stat_cache(root);     return 0;-  }-  if (!delete_stale(store, root, old_entries, {})) {-    error_prefix();-    std::cout << "cannot remove files absent from the restored view\n";-    return 1;-  }-  clear_stat_cache(root);-  return 0; } -std::optional<Id> create_working_copy_commit(Txn &tx, const Id &parent) {-  auto loaded = load_commit(tx.store(), parent);-  if (!loaded)-    return std::nullopt;-  Commit commit;-  commit.version = 1;-  commit.parents = {parent};-  commit.root_tree = loaded->commit.root_tree;-  commit.change_id = random_change_id();-  commit.author = identity_signature(tx.store().root());-  commit.committer = commit.author;-  commit.renames_state = RENAMES_RECORDED;-  return tx.add_object(TYPE_COMMIT, encode_commit(commit));+std::optional<Id> create_working_copy_commit(Txn& tx, const Id& parent) {+    auto loaded = load_commit(tx.store(), parent);+    if (!loaded)+        return std::nullopt;+    Commit commit;+    commit.version = 1;+    commit.parents = {parent};+    commit.root_tree = loaded->commit.root_tree;+    commit.change_id = random_change_id();+    commit.author = identity_signature(tx.store().root());+    commit.committer = commit.author;+    commit.renames_state = RENAMES_RECORDED;+    return tx.add_object(TYPE_COMMIT, encode_commit(commit)); }--int checkout_run(const fs::path &root, std::string_view rev) {-  const int snap = snapshot_run(root);-  if (snap != 0)-    return snap;--  Store store = Store::open_all(root);-  auto view = current_view(root, store);-  if (!view) {-    error_prefix();-    std::cout << "no operation state; import a repository first\n";-    return 1;-  } -  const auto target = resolve_revision(store, *view, rev);-  if (!target) {-    error_prefix();-    std::cout << "unknown revision: " << rev << "\n";-    return 1;-  }-  bool bookmark_checkout = false;-  bool detach_bookmark = false;-  if (!rev.empty() && rev != "@") {-    bookmark_checkout = find_bookmark(*view, rev).has_value();-    detach_bookmark = !bookmark_checkout;-  }-  auto commit_body = store.read_body(*target, TYPE_COMMIT);-  if (!commit_body) {-    error_prefix();-    std::cout << "cannot read commit\n";-    return 1;-  }-  auto commit = decode_commit(bytes_of(*commit_body));-  if (!commit) {-    error_prefix();-    std::cout << "cannot read commit\n";-    return 1;-  }+int checkout_run(const fs::path& root, std::string_view rev) {+    const int snap = snapshot_run(root);+    if (snap != 0)+        return snap; -  const auto wc = working_copy_id(*view);-  std::optional<Id> old_root;-  if (wc) {-    auto old_body = store.read_body(*wc, TYPE_COMMIT);-    if (old_body) {-      auto old_commit = decode_commit(bytes_of(*old_body));-      if (old_commit)-        old_root = old_commit->root_tree;+    Store store = Store::open_all(root);+    auto view = current_view(root, store);+    if (!view) {+        error_prefix();+        std::cout << "no operation state; import a repository first\n";+        return 1;     }-  }--  const int materialized =-      checkout_materialize_commit(root, store, old_root, commit->root_tree);-  if (materialized != 0)-    return materialized; -  if (!wc || std::memcmp(wc->data(), target->data(), ID_LEN) != 0) {-    bool already_empty_child = false;-    if (wc) {-      auto wc_loaded = load_commit(store, *wc);-      if (wc_loaded && wc_loaded->commit.parents.size() == 1 &&-          std::memcmp(wc_loaded->commit.parents.front().data(), target->data(),-                      ID_LEN) == 0 &&-          std::memcmp(wc_loaded->commit.root_tree.data(),-                      commit->root_tree.data(), ID_LEN) == 0 &&-          wc_loaded->commit.message.empty()) {-        already_empty_child = true;-      }-    }-    if (!already_empty_child) {-      auto tx = Txn::begin(root, store);-      if (!tx) {+    const auto target = resolve_revision(store, *view, rev);+    if (!target) {         error_prefix();-        std::cout << "cannot load repository state\n";+        std::cout << "unknown revision: " << rev << "\n";         return 1;-      }-      if (wc)-        remove_head(tx->view(), *wc);-      auto child = create_working_copy_commit(*tx, *target);-      if (!child)+    }+    bool bookmark_checkout = false;+    bool detach_bookmark = false;+    if (!rev.empty() && rev != "@") {+        bookmark_checkout = find_bookmark(*view, rev).has_value();+        detach_bookmark = !bookmark_checkout;+    }+    auto commit_body = store.read_body(*target, TYPE_COMMIT);+    if (!commit_body) {+        error_prefix();+        std::cout << "cannot read commit\n";         return 1;-      set_workspace(tx->view(), *child);-      rebuild_heads(tx->view());-      const auto status = tx->finish("checkout");-      if (!status)+    }+    auto commit = decode_commit(bytes_of(*commit_body));+    if (!commit) {+        error_prefix();+        std::cout << "cannot read commit\n";         return 1;     }-  }-  if (bookmark_checkout)-    (void)set_current_bookmark(root, rev);-  else if (detach_bookmark)-    (void)clear_current_bookmark(root);-  return 0;++    const auto wc = working_copy_id(*view);+    std::optional<Id> old_root;+    if (wc) {+        auto old_body = store.read_body(*wc, TYPE_COMMIT);+        if (old_body) {+            auto old_commit = decode_commit(bytes_of(*old_body));+            if (old_commit)+                old_root = old_commit->root_tree;+        }+    }++    const int materialized = checkout_materialize_commit(root, store, old_root, commit->root_tree);+    if (materialized != 0)+        return materialized;++    if (!wc || std::memcmp(wc->data(), target->data(), ID_LEN) != 0) {+        bool already_empty_child = false;+        if (wc) {+            auto wc_loaded = load_commit(store, *wc);+            if (wc_loaded && wc_loaded->commit.parents.size() == 1 &&+                std::memcmp(wc_loaded->commit.parents.front().data(), target->data(), ID_LEN) ==+                    0 &&+                std::memcmp(wc_loaded->commit.root_tree.data(), commit->root_tree.data(), ID_LEN) ==+                    0 &&+                wc_loaded->commit.message.empty()) {+                already_empty_child = true;+            }+        }+        if (!already_empty_child) {+            auto tx = Txn::begin(root, store);+            if (!tx) {+                error_prefix();+                std::cout << "cannot load repository state\n";+                return 1;+            }+            if (wc)+                remove_head(tx->view(), *wc);+            auto child = create_working_copy_commit(*tx, *target);+            if (!child)+                return 1;+            set_workspace(tx->view(), *child);+            rebuild_heads(tx->view());+            const auto status = tx->finish("checkout");+            if (!status)+                return 1;+        }+    }+    if (bookmark_checkout)+        (void)set_current_bookmark(root, rev);+    else if (detach_bookmark)+        (void)clear_current_bookmark(root);+    return 0; }  } // namespace vn--- a/xveins/src/worktree.h+++ b/xveins/src/worktree.h@@ -7,16 +7,15 @@  namespace vn { -int snapshot_run(const fs::path &root);-int snapshot_run(const fs::path &root, Store &store);+int snapshot_run(const fs::path& root);+int snapshot_run(const fs::path& root, Store& store); -int checkout_run(const fs::path &root, std::string_view rev);-std::optional<Id> create_working_copy_commit(Txn &tx, const Id &parent);-int checkout_materialize_commit(const fs::path &root, Store &store,-                                std::optional<Id> old_root, const Id &new_root);-int checkout_materialize_optional(const fs::path &root, Store &store,-                                  std::optional<Id> old_root,+int checkout_run(const fs::path& root, std::string_view rev);+std::optional<Id> create_working_copy_commit(Txn& tx, const Id& parent);+int checkout_materialize_commit(const fs::path& root, Store& store, std::optional<Id> old_root,+                                const Id& new_root);+int checkout_materialize_optional(const fs::path& root, Store& store, std::optional<Id> old_root,                                   std::optional<Id> new_root);-void clear_stat_cache(const fs::path &root);+void clear_stat_cache(const fs::path& root);  } // namespace vn