navid/veins / commit

35663f0f2ddf

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

parents: d3323c6c3a9d

Browse files at this commit · Download source

all: fixes to C++ baseline
--- a/veins-cpprewrite/CMakeLists.txt+++ b/veins-cpprewrite/CMakeLists.txt@@ -18,6 +18,9 @@  include(FetchContent) include(CheckCXXCompilerFlag)++# Prefer static archives for fetched dependencies (BLAKE3, zstd fallback).+set(BUILD_SHARED_LIBS OFF)  find_package(Threads REQUIRED) @@ -28,12 +31,8 @@ find_package(zstd CONFIG QUIET) if(TARGET zstd::libzstd_static)     set(VN_ZSTD_TARGET zstd::libzstd_static)-elseif(TARGET zstd::libzstd_shared)-    set(VN_ZSTD_TARGET zstd::libzstd_shared) elseif(TARGET libzstd_static)     set(VN_ZSTD_TARGET libzstd_static)-elseif(TARGET libzstd)-    set(VN_ZSTD_TARGET libzstd) else()     # Ubuntu/Debian's libzstd-dev ships zstd.h and libzstd.{a,so} but no CMake     # config. Never pass "libzstd" to the linker: -llibzstd looks for@@ -52,6 +51,10 @@             )         endif()         set(VN_ZSTD_TARGET vn_zstd)+    elseif(TARGET zstd::libzstd_shared)+        set(VN_ZSTD_TARGET zstd::libzstd_shared)+    elseif(TARGET libzstd)+        set(VN_ZSTD_TARGET libzstd)     endif() endif() @@ -101,6 +104,12 @@     src/object.cpp     src/store.cpp     src/worktree.cpp+    src/pathspec.cpp+    src/bookmark.cpp+    src/remove.cpp+    src/exclude.cpp+    src/oplog.cpp+    src/merge.cpp     src/cli.cpp ) --- /dev/null+++ b/veins-cpprewrite/src/bookmark.cpp@@ -0,0 +1,356 @@+#include "local_commands.h"++#include "pathspec.h"+#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <iostream>++namespace vn {++namespace {++bool bmk_is_flag(std::string_view arg) {+  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;+}++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;+}++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 << ' ';+}++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()) {+        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 << "bmk set requires a 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;++  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;+    } else {+      bookmark.targets.adds = {*target};+      bookmark.targets.removes.clear();+    }+  } else {+    Bookmark bookmark;+    bookmark.name = name;+    bookmark.targets.adds = {*target};+    tx->view().bookmarks.push_back(std::move(bookmark));+  }++  if (!changed) {+    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;+  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;+    }+  }+  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;+  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;+    }+  }++  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());++  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";+  }++  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";+  }++  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";+}++} // namespace++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;+}++} // namespace vn--- a/veins-cpprewrite/src/cli.cpp+++ b/veins-cpprewrite/src/cli.cpp@@ -1,5 +1,7 @@ #include "cli.h" +#include "local_commands.h"+#include "merge.h" #include "store.h" #include "worktree.h" @@ -2052,6 +2054,96 @@   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_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_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";@@ -2092,6 +2184,26 @@     show_checkout();   else if (cmd == "fsck")     show_fsck();+  else if (cmd == "bmk")+    show_bmk();+  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")@@ -2101,9 +2213,7 @@   else if (cmd == "git" || cmd == "remote" || cmd == "clone" ||            cmd == "fetch" || cmd == "push" || cmd == "serve" || cmd == "key" ||            cmd == "auth" || cmd == "access" || cmd == "whoami" ||-           cmd == "merge" || cmd == "rebase" || cmd == "xs" ||-           cmd == "resolve" || cmd == "bmk" || cmd == "rm" || cmd == "mv" ||-           cmd == "ex" || cmd == "undo" || cmd == "op" || cmd == "bench-import")+           cmd == "bench-import")     show_unimplemented(cmd);   else {     usage();@@ -2148,6 +2258,26 @@     return run_amend(args);   if (cmd == "co" || cmd == "checkout")     return run_checkout(args);+  if (cmd == "bmk")+    return bmk_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")@@ -2161,10 +2291,7 @@    if (cmd == "git" || cmd == "remote" || cmd == "clone" || cmd == "fetch" ||       cmd == "push" || cmd == "serve" || cmd == "key" || cmd == "auth" ||-      cmd == "access" || cmd == "whoami" || cmd == "merge" || cmd == "rebase" ||-      cmd == "xs" || cmd == "resolve" || cmd == "bmk" || cmd == "rm" ||-      cmd == "mv" || cmd == "ex" || cmd == "undo" || cmd == "op" ||-      cmd == "bench-import") {+      cmd == "access" || cmd == "whoami" || cmd == "bench-import") {     error_prefix();     std::cout << "command '" << cmd << "' is not available in this stage\n";     return 1;--- /dev/null+++ b/veins-cpprewrite/src/exclude.cpp@@ -0,0 +1,145 @@+#include "local_commands.h"++#include "pathspec.h"+#include "store.h"++#include <iostream>+#include <string_view>++namespace vn {++namespace {++bool ex_is_flag(std::string_view arg) {+  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);+}++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;+    }+  }+  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);+    }+  }+  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;+  }++  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));+  }++  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 (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 << "added " << added.size() << " exclude rule(s)\n";+  return 0;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/local_commands.h@@ -0,0 +1,17 @@+#pragma once++#include <string>+#include <vector>++namespace vn {++// Local-only commands. Each receives the full argv-style vector and indexes+// its own arguments (args[0] is the program, args[1] the command).+int bmk_run(const std::vector<std::string> &args);+int 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--- /dev/null+++ b/veins-cpprewrite/src/merge.cpp@@ -0,0 +1,2246 @@+#include "merge.h"++#include "pathspec.h"+#include "worktree.h"++#include <algorithm>+#include <cstdlib>+#include <cstring>+#include <iostream>+#include <set>+#include <utility>++namespace vn {++namespace {++// ---------------------------------------------------------------------------+// 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);+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/merge.h@@ -0,0 +1,27 @@+#pragma once++#include "store.h"++#include <optional>+#include <string>+#include <vector>++namespace vn {++// Detect renames between two trees. `tx` may be provided so trees and blobs that+// have only been added to the pending transaction are visible. Results are+// sorted by (parent_index, to_path).+std::vector<Rename> detect_renames(Store &store, Txn *tx,+                                   std::optional<Id> old_tree,+                                   std::optional<Id> new_tree, int similar_pct,+                                   std::uint64_t parent_index);++// Configured rename similarity threshold (0 disables detection).+int rename_similar_pct(const fs::path &root);++int merge_run(const std::vector<std::string> &args);+int rebase_run(const std::vector<std::string> &args);+int xs_run(const std::vector<std::string> &args);+int resolve_run(const std::vector<std::string> &args);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/oplog.cpp@@ -0,0 +1,246 @@+#include "local_commands.h"++#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <iostream>++namespace vn {++namespace {++struct OpRec {+  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);+    }+    out.push_back(OpRec{id, std::move(*op)});+  }+  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;+  });+}++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;+    }+  }+  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;+}++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_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);+    }+  }+  return write_view(*root, store, view, "op revert");+}++} // namespace++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 << "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;+    }+    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--- /dev/null+++ b/veins-cpprewrite/src/pathspec.cpp@@ -0,0 +1,96 @@+#include "pathspec.h"++#include <vector>++namespace vn {++namespace {++// 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);+      }+    }+    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 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;+}++} // 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)+    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::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));+}++bool pathspec_has_glob(std::string_view value) {+  return value.find('*') != std::string_view::npos ||+         value.find('?') != std::string_view::npos;+}++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/pathspec.h@@ -0,0 +1,23 @@+#pragma once++#include "common.h"++#include <optional>+#include <string>++namespace vn {++// 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);++// 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::string_view arg);++bool pathspec_has_glob(std::string_view value);++} // namespace vn--- /dev/null+++ b/veins-cpprewrite/src/remove.cpp@@ -0,0 +1,415 @@+#include "local_commands.h"++#include "pathspec.h"+#include "store.h"+#include "worktree.h"++#include <algorithm>+#include <iostream>+#include <set>+#include <system_error>++namespace vn {++namespace {++bool rm_is_flag(std::string_view arg) {+  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()] == '/';+}++bool literal_matches(std::string_view operand, std::string_view path) {+  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;+}++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);+}++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;+}++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;+}++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::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);+}++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));+}++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;+  }+}++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;+  }++  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;+    }+  }+  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";+      }+    }+  }++  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));++  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);++  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";+  }+  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);+    }+  }+  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 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;+    }+    if (norm->empty() || !valid_path(*norm)) {+      error_prefix();+      std::cout << "invalid path: " << arg << "\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);+}++} // namespace++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);+    }+  }++  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;+  }++  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;+  }++  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);+}++} // namespace vn--- a/veins-cpprewrite/src/worktree.cpp+++ b/veins-cpprewrite/src/worktree.cpp@@ -1,4 +1,6 @@ #include "worktree.h"++#include "merge.h"  #include <algorithm> #include <atomic>@@ -828,6 +830,21 @@   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 compare(bytes_of(a.to_path), bytes_of(b.to_path)) <+                            0;+                   });    Commit commit;   commit.version = 1;@@ -883,6 +900,25 @@  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,+                                  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()) {+    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; }  int checkout_run(const fs::path &root, std::string_view rev) {--- a/veins-cpprewrite/src/worktree.h+++ b/veins-cpprewrite/src/worktree.h@@ -13,6 +13,9 @@ int checkout_run(const fs::path &root, std::string_view rev); 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);  } // namespace vn