# MEMORY
Institutional knowledge for codetree development. Consult before starting a task (AGENTS.md Step 0); harvest after completing one (Step 4). Sections match AGENTS.md "Memory System".
*Started 2026-09-05 from the first full docs-vs-code audit.*
---
## 1. VCS Engine Patterns
- **`VcsManager` is the native engine API** (`src/vcs/manager.rs`). There is no Git anywhere: no `git2` in `Cargo.toml`, no `git` subprocess. `VcsManager::push_branch` (worktree.rs) is a **stub that bails** — remote protocol is Phase 7. Anything documenting push/publish as working is stale.
- **One type, many files: VcsManager impl is split by concern** (2026-09-14, former 3,898-line god module): `vcs/manager.rs` (core: struct, shared types, branches, add/commit, status, working-tree plumbing, ~1,160 lines), `vcs/merge.rs` (merge base, 3-way merge, cached merges, ready, rebase, speculative), `vcs/rewrite.rs` (jj-style history surgery: amend/reword/squash/move/abandon/fold/revert/absorb/restore), `vcs/query.rs` (read-only: diff/log/blame/search/forks/verify/gc/clean), `vcs/worktree.rs` (worktrees + push stub). **Mechanics**: Rust allows multiple `impl VcsManager` blocks in sibling modules of the same crate — the public API is untouched, so commands/mcp/tests need zero changes. **Field/helper visibility**: struct fields and cross-file private helpers became `pub(super)` (visible in `vcs` and all its children); callers outside `vcs/` see no difference. **Refactor recipe that worked**: (1) map fn clusters with `grep -n "^ pub.*fn \|^ fn \|^impl \|^}"`, (2) script-extract contiguous line ranges per file, walking each cut point up past `///` doc comments (true method start), (3) paste identical import header into each new file, (4) run `cargo build` and let E0624 "method X is private" drive the `pub(super)` list, (5) `cargo fix --lib` for unused imports. **Gotchas hit**: `{{` escaping leaks literal braces if you template headers without `.format()`; range math off-by-one duplicated 3 methods across manager/merge (E0592 duplicates — check overlapping segments); `cargo fix` also strips imports the `#[cfg(test)]` module needs (E0433 in tests — re-add inside `mod tests`).
- **Concern-split of `vcs/merge.rs`** (2026-11-07, AGENTS.md Step 9): `src/vcs/merge.rs` (merge base, 3-way merge, cached merges, readiness, rebase, speculative merge — 695 lines) + `src/vcs/merge_drivers.rs` (driver machinery: `resolve_conflicts_via_cache_and_drivers`, `merge_driver_for`, `run_merge_driver`, the glob matcher, the JSON duplicate-key scanner and their unit tests — 408 lines). **The gotcha that bit**: finding the impl block's end with `max(i for ... if line.strip() == "}")` matches the **last** column-0 `}` in the file (a trailing `mod tests`!), not the impl's — the split then swallowed the free helper items and the test module into the wrong file. **Use the FIRST column-0 `}` after the impl header**, and treat every top-level item after it (free fns, structs, `#[cfg(test)] mod`) as belonging to the file that owns them. Cross-module calls then need `pub(super)` (the compiler's E0624 drives the list). **Repair trick**: when a split mis-detects a boundary, the blocks are still contiguous slices of the original — rebuild both files from the damaged state rather than `git checkout` (which would revert this round's feature work).
- **Concern-split of `vcs/rewrite.rs`** (2026-11-07, AGENTS.md Step 9): the 1,290-line `impl VcsManager` history-surgery block → `vcs/rewrite.rs` (amend/reword/amend_to/restore/move/revert, ~485 lines), `vcs/rewrite_combine.rs` (squash/unsquash/squash_into/fold), `vcs/rewrite_lifecycle.rs` (revive/duplicate/abandon/forget), `vcs/rewrite_absorb.rs` (absorb/reset_soft_parent). **The gotcha that bit**: doc comments inside an `impl` block are **indented** — the walk-up must test `line.strip().startswith("///")`, not `line.startswith("///")`, or every doc comment leaks into the *previous* method's block (symptom: rustc "expected item after doc comment" at the end of a file, plus docs silently attached to the wrong method). **Also**: restoring a file with `git checkout` during a split silently reverts *unrelated* earlier edits to that file (the `merge_drivers` field addition was lost this way) — re-apply them after restoring, then `cargo fix --lib` for the now-unused imports in each new file.
- **`mcp.rs` field naming trap**: `self.git_manager` is actually an `Arc<VcsManager>` — legacy name from the Git-backed era. Don't let it fool you into thinking Git is back; consider renaming in a cleanup pass.
- **Storage layout** (`.codetree/`): `objects/` (SHA-1 fan-out, Git-compatible), `refs/heads/`, `HEAD`, `index`, `config.toml`, `branches.json`, `ops.json` (ops + redo_stack), `resolutions.json`, `pending_resolution.json`, `locks.json`, `frozen.json`, `candidates.json`, `snapshots.json`. `pending_resolution.json` and `snapshots.json` are easy to forget in doc storage lists. All of these are now written via `crate::atomic` (see below).
- **Atomic state writes are mandatory — never plain `fs::write`** (2026-09-14, `src/atomic.rs`): every persistent state file is written with `crate::atomic::write_atomic(path, data)` = exclusive `<path>.lock` lockfile (O_EXCL `create_new`) → write to hidden staging sibling `.<name>.tmp.<pid>` → `rename` over target. Readers see old-or-new, never torn. Three primitives: `write_atomic` (lock + write, the default for `save()` methods), `write_locked` (temp+rename only, for use *inside* `with_file_lock` — the lock is **not reentrant**, calling `write_atomic` inside `with_file_lock` on the same path deadlocks until the 5s timeout then stale-breaks at 30s), and `with_file_lock(path, timeout, f)` (generic RMW wrapper). Stale locks (mtime > 30s, `STALE_LOCK_AGE`) are force-broken so a crash can't wedge the repo. **Lockfiles are pid-stamped** and `release_lockfile` only removes a lock that still holds *our* pid — otherwise a wedged process that recovers deletes the live lock of whoever stale-broke it. Converted call sites: refs/tags/HEAD (`vcs/refs.rs`), index (`vcs/index.rs`), locks/branches/ops/resolutions/pending/candidates/snapshots/frozen/evolog/bisect/hidden/config/tag-annotations/`last_branch`, and `Repository::write_object` (temp+rename only — content-addressed objects need no lockfile since concurrent writers produce identical bytes). **Anti-pattern**: `tokio::fs::write` / `std::fs::write` directly on any `.codetree` state file — a crash mid-write truncates the ref/index and the repo is silently corrupted.
- **Ref CAS primitive** (2026-09-14, `RefManager::set_branch_if_current(name, new_id, expected)`): compare-and-swap under one `with_file_lock` cycle — `expected = Some(id)` applies only if the ref currently reads `id`, `expected = None` is create-only (ref must not exist). Returns `bool` (applied or not). This is the primitive for optimistic/optimistic-concurrent branch updates between agents. Listings (`list_branches`/`list_tags`) filter via `is_ref_name`: skip names starting with `.` (staging) or ending `.lock` — otherwise crashed-writer litter shows up as branches.
- **Index stat cache** (2026-09-06, `src/vcs/index.rs`): entries are `path\0blob\0mtime_secs\0mtime_nanos\0size\0inode`. `matches_stat()` returns false when `mtime_secs == 0` (legacy/no-stat entries) so they always re-hash. Legacy 2-field index files still load. This is what makes `add_all`/`add_files`/`get_status` fast — never break the stat invariant: anything that stages content must call `add_staged` with real stat, and anything that rebuilds the index from a tree (`sync_index_to_head`, `reset_soft_parent`, `checkout_branch`) uses `add()` (no stat) so the next pass re-hashes.
- **`restore_working_tree` skip-if-match** (`src/vcs/manager.rs`): two fast paths — index stat match (zero reads), then content-hash match (read, no write). Checkout/start/switch on an unchanged tree is nearly free. Removing files not in the target tree still happens unconditionally.
- **`Repository::write_blob`** stores raw content (blob serialization == raw bytes; the `blob <len>\0` header exists only inside `hash_object`). Don't reintroduce `Blob::new(content.to_vec())` — it adds two clones per file.
- **Performance floor** (macOS, 2026-09-06, release, 50 files): save ~4.5ms, status ~0.4ms, branch ~3.1ms, undo ~1.8ms — vs git CLI ~15–80ms/op (subprocess spawn dominates). Bench: `examples/bench_vs_git.rs`. Keep codetree ahead when touching `add_all`/`get_status`/`restore_working_tree`: never read+hash a file when the stat cache can prove it unchanged.
## 2. Branch & Merge Patterns
- **`BranchStatus` has exactly 3 variants**: `Active | Merged | Archived` (`src/branch.rs:49` — unchanged). Older docs mention `Draft`/`Ready` — those were never in the current schema (they appear in TODO as a *future* state machine).
- **`Operation` variants** (`src/ops.rs:9-14`): `Start{branch,timestamp,agent_id}`, `Save{branch,message,timestamp}`, `Merge{branch,into,timestamp}`, `Withdraw{branch,timestamp}`. No `files` field on Save (that's in BranchInfo).
- **Candidate groups are storage-only right now**: `CandidateManager::add_candidate` (`src/candidates.rs:44`) has **zero callers**. Groups in `candidates.json` can only be created by hand-editing; `evaluate`/`promote` consume them. Any doc claiming `start --candidate-group` is wrong — the flag doesn't exist.
- **First-class conflicts (jj-style)** (2026-09-06, `src/vcs/merge.rs`): `merge_branch_with_cache`/`squash_merge_branch_with_cache` **never abort on conflict**. When the resolution cache can't auto-resolve, they commit the merge (2 parents for real merge, 1 for squash) with conflicting files left at "our" side, write `pending_resolution.json`, and return `Ok(MergeResult { resolved_from_cache: false, conflicts })`. The old `MergeError::Conflict` error path was **removed** — `MergeError` is gone entirely (was dead, removed from `vcs/mod.rs`). The merge command sees `!resolved_from_cache && !conflicts.is_empty()` and returns `Ok` without deleting the branch or marking merged. `resolve_command` (`src/commands/merge.rs`) finalizes: `add_all` → `amend_commit` (keeps parents, swaps tree) → cache resolutions → clear pending → delete branch → mark merged → push `Operation::Merge`. **`amend_commit` is the key primitive** for resolution: it preserves parent count and message while replacing the tree from the index. `status` shows `! path` markers when `pending_resolution.json` exists. MCP has a `resolve_op` tool mirroring the CLI.
- **Anti-pattern: aborting merges on conflict** (2026-09-06): the pre-native-VCS flow aborted, restored the original branch, and told users to run `git merge` — both wrong (no git; restore lost the merge state). Never reintroduce an abort-on-conflict path. Conflicts are committed state, not errors.
- **`pending_resolution.json` is the active-conflict sidecar** (`VcsManager::pending_resolution_path()`): its existence (`is_in_merge_state()`) means a merge is committed but unresolved. Reuse `PendingResolution`/`ConflictInfo` from `resolution.rs`; don't add a parallel "active conflicts" type.
- **Pluggable merge drivers** (2026-11-07, TODO Round 13): resolution order per conflicting file is **cache → merge driver → first-class conflict** (`resolve_conflicts_via_cache_and_drivers`, `src/vcs/merge.rs`). Drivers are `[merge.drivers]` glob→template config (`MergeConfig` in `config.rs`), set on the manager via `set_merge_drivers` (follows the `set_max_file_size` pattern); run per file via `sh -c` with `%base/%ours/%theirs/%result` substituted as **shell-quoted** temp paths (`run_merge_driver`). Driver failure (non-zero exit / no result / spawn error) NEVER fails the merge — it falls back to first-class conflicts. **Driver output is recorded into the `ResolutionCache`** (hence `merge_branch_with_cache` now takes `&mut ResolutionCache`) so identical conflicts later auto-resolve without re-invoking the driver — callers must persist the cache after a `driver_resolved` merge. `MergeResult` gained `driver_resolved: Vec<String>`. **JSON duplicate-key guard**: `json_duplicate_key` is a hand-rolled conservative scanner (bails → None on any anomaly; escapes decoded only enough for consistent key comparison); applied to `.json` driver output — dup keys keep the conflict first-class (mergiraf's "don't sweep conflicts under the rug"). **Gotcha**: report dups as soon as found — do NOT require the parser to consume the whole document (a `finished()` guard silently disabled all detection; caught by unit test). `ready`/`check_ready` counts cache-OR-driver coverage as auto-resolvable. MCP `merge_branch` clones the `Arc<VcsManager>` to attach drivers when configured (cheap: `Arc<Repository>` + `PathBuf`).
- **`codetree converge` (divergent-operation recovery)** (2026-11-07, TODO Round 13): `src/vcs/converge.rs` + `src/commands/converge.rs`. **Divergence detection rides on the provenance sidecar** (feature #1): candidate commits per operation = provenance entries with `operation == op` + the op's branch tip + its `last_commit`; heads = candidates that are not ancestors of another candidate. This recovers the classic multi-agent failure mode — two agents commit to the same operation, only one commit stays on the branch ref, the other is orphaned (invisible to `smartlog`/`finish`). **False-positive guard**: heads with the *same tree* collapse to the newest (`dedupe_heads_by_tree`) — otherwise a `reword`/`squash` (new commit id, same content) looks like divergence and converge would re-merge an old version. Combination = pairwise 3-way merge (merge base via `find_merge_base`) → merge commit with 2 parents → re-point branch (or branchless `last_commit`) → record provenance → restore working tree when HEAD is that op. **Conflicts are never force-merged**: `converge_heads` returns the conflicting files and writes nothing (jj's non-interactive abort). Heads = "not an ancestor of any other candidate" — computed per candidate (O(n²) ancestor walks, fine for small sets).
- **`codetree megamerge` + `absorb --route`** (2026-11-07, TODO Round 13): `src/megamerge.rs` (session sidecar `.codetree/megamerge.json` + LCS diff utils) + `src/vcs/megamerge.rs` (engine) + `src/commands/megamerge.rs`. Megamerge = **multi-parent commit** (one parent per active operation) whose tree merges every op 3-way against the common base; HEAD is **detached** at it (jj-style) and the working tree restored to the merged state — cross-operation conflicts surface *before* any `finish`. **Hunk routing**: each changed file is diffed against the merged state (`diff_hunks`, hand-rolled LCS — no diff crate; >1M cell inputs degrade to whole-file replacement) and every hunk is attributed to the operation whose **file version contains the replaced lines** — a *content* match, so it works even though line numbers differ per operation (other ops changed the same file). Attributed hunks are rebased onto that operation's coordinates and committed with `commit_files_on` (writes a commit on a branch **without checking it out**); unattributable hunks are reported, never guessed. Session state records commit/operations/base branch; routing (or `--abort`) restores the base branch and clears it.
## 3. Agent Coordination Patterns
- **Locks**: `locks.json` (`src/lock.rs`), acquired via `start --files`, released on `finish`/`withdraw`/`unlock`. `start --wait` polls every 2s (`src/commands/operations.rs`); not exposed to MCP `start_op`. **All mutating lock cycles must go through `LockManager::update_atomically(path, |m| ...)`** (2026-09-14): the load → conflict-check → persist cycle runs under one `locks.json.lock` lockfile, so concurrent agents can't lose each other's updates (the bare `load`/`save` pair is last-writer-wins). Wired into `start` acquire (the `--wait` poll loop stays outside as a read-only pre-check; `acquire`'s conflict error inside the locked section is the real gate), `cleanup_after_finish` release, and `unlock_command`. Inside the closure persist with the private `save_unlocked`, never `save` (deadlock). Read-only sites (`save.rs` bookmark check, `locks` listing) may keep plain `load`.
- **Known remaining RMW race: `BranchManager`/`OperationLog`** (2026-09-14): `branches.json` and `ops.json` saves are now atomic (no torn files), but the manager APIs are long-lived in-memory objects (`load all → &mut self methods → save all`), so two concurrent agents doing start/register can still lose a branch registration (last-writer-wins at document granularity). Fixing requires restructuring `BranchManager` methods into closure-based `update_atomically` calls — tracked in TODO.md. In practice the file-lock acquisition in `start` (fully atomic) is the coordination point agents contend on.
- **Freezes**: `frozen.json` + config `[frozen]`; enforced in `save`.
- **Undo/redo**: `ops.json` redo stack; `undo [index]` / `redo [index]` with `--list`.
## 4. CLI & MCP Patterns
- **Clap derive naming**: multi-word variants get kebab-case names (`WhereAmI` → `where-am-i`). Pin documented names explicitly with `#[command(name = "whereami")]` (done, `src/main.rs:585`). **Always check new commands against the docs naming.**
- **`codetree why` / provenance sidecar** (2026-11-07, TODO Round 13): `.codetree/provenance.json` (`src/provenance.rs`, `ProvenanceLog`) maps commit hash → {operation, agent_id, prompt, timestamp}. Recorded by `save_command` (covers CLI, `watch` auto-save, `switch` auto-save) and MCP `save_changes` (which now also returns the commit hash). **Why a sidecar**: SHA-1 hashing of commit objects is the Git-compat contract — never add fields to the hashed object (would break `import`/`export` object mapping). `blame` returns 7-char hash prefixes, so `ProvenanceLog::get` matches full **or** prefix. `codetree why <path[:line]>` (`src/commands/why.rs`, `lookup_why`): line → blame commit; no line → newest `file_log` commit; then joins provenance. `parse_target` uses `rsplit_once(':')` + numeric-suffix parse — Windows drive letters (`C:\...`) don't parse as numbers so they stay in the path. **Signature-change gotcha**: changing `save_command`'s arity requires updating ALL callers — tests had ~24 call sites including multiline `vec!["a", "b"]` forms that a single `replaceAll` missed; after bulk edits, re-grep `save_command(` for sites missing the new argument. MCP tool `why` mirrors the CLI.
- **`codetree checkpoint` / `rewind` (turn-level checkpoints)** (2026-11-07, TODO Round 13): checkpoints are **labeled snapshots** — `SnapshotEntry` gained `#[serde(default)] label: Option<String>` (old `snapshots.json` loads unchanged), `add_labeled()` records them, `clear_unlabeled()` replaced the old nuke-the-file `clear_snapshots` in the `save` path: **labeled checkpoints survive `save`** so rewind targets stay valid across turns, auto-snapshots are still superseded. Clean-tree checkpoints target HEAD's tree directly (no new commit — content addressing dedupes). **Anti-drift pattern worth copying**: core logic lives in `commands::snapshot::{create_checkpoint, rewind_working_tree}`, taking `&VcsManager` — the CLI command and the MCP tool both wrap the same functions, so CLI/MCP can't diverge (unlike `save` where MCP reimplements and has drifted: no branchless mode). `rewind --dry-run` derives changed files from `diff_working_tree(Some(commit))` by parsing `diff --git a/<path>` headers; real rewind = `restore_working_tree_pub` + `sync_index_to_commit`, HEAD/refs untouched.
- **Duplicate aliases panic**: clap debug assertions abort the binary at parse time if two subcommands share an alias (bit us: `watch` and `whereami` both had `wa` (pre-rename fix, `src/main.rs:585` is whereami now)). Smoke-test the CLI binary after touching aliases — see Testing below.
- **MCP tools are declared via rmcp `#[tool]` macros** in `src/mcp.rs`; list them with `grep -A1 '#\[tool(' src/mcp.rs`. 21 tools as of 2026-09-06 (`resolve_op` added for first-class conflicts). MCP `merge_branch` now uses the cache-aware merge and returns `conflicts_pending: true` + `conflict_files` + `next_step: "resolve_op"` instead of deleting the branch on conflict. MCP calls `VcsManager`/`BranchManager` directly, **not** `commands::*` (exception: `resolve_op` delegates to `commands::merge::resolve_command`), so CLI/MCP can drift (e.g. `start_op` lacks `--wait`). Not every CLI command has a twin: no MCP for `redo`, `split`, `smartlog`, `switch`/`next`/`prev`, `watch`, `worktree`, `agents`.
- **`publish` CLI command is a stub** (calls the bailing `push_branch`); MCP `publish_op` likewise always errors.
- **Known bug: `list` panics in debug builds** (2026-09-06, **fixed**): `list` defined both `query` (`-q`) and the global `quiet` (`-q`) with the same short flag, so clap's `debug_assert!` aborted at parse time for *any* `list` invocation in debug builds (release builds skip `debug_assert!` so it limped along). Fix: `query` now uses `short = 'Q'`; `quiet` keeps `-q`. **General lesson**: clap derives the short flag from the field name's first letter by default, so any local field starting with `q`/`v`/`h` collides with the global `quiet`/`verbose`/`help`. When adding a field whose name starts with one of those letters, pin an explicit `short = '<other letter>`. Regression test lives in `src/main.rs` `tests::list_parses_without_short_flag_collision` (uses `Cli::try_parse_from` — the only way to exercise clap parse-time from tests since `cargo test` doesn't run the binary).
## 5. Testing Patterns
- **`cargo test` does NOT exercise the CLI binary**: the `tests/<area>.rs` binaries call library functions directly, so clap parse-time panics never surface in the test suite. After CLI changes run: `cargo build --bin codetree && ./target/debug/codetree --help`.
- **Concurrency tests without subprocesses** (2026-09-14): the atomicity suite uses `std::thread::spawn` inside single tests (`src/atomic.rs`, `src/lock.rs`, `src/vcs/refs.rs` CAS test) to race writers against each other and assert exactly-one-winner / no-torn-read / no-lock-litter invariants — no need to spawn the binary. To simulate a crashed writer's leftover, write the litter file by hand (`.name.tmp.4242`, `name.lock`) and assert listings ignore it; to simulate a stale lock, backdate its mtime with `File::set_modified(now - STALE_LOCK_AGE - 1s)`. Library-level integration tests for the wiring live in `tests/coordination.rs` (`test_concurrent_starts_disjoint_files_both_locks_survive`, `test_lock_conflict_then_release_via_atomic_rmw`, `test_ref_writes_atomic_and_listings_clean`) — they still honor `WORKDIR_LOCK` + `DirGuard` since `start_command` reads the process cwd; `tokio::spawn`ed tasks inherit it, so set the guard in the test body before spawning.
- Unit tests live inline per module (`vcs/objects.rs`, `branch.rs`, `config.rs`); integration tests use `tempfile` dirs via `create_test_repo()` (`tests/common/mod.rs`).
- **cwd-touching tests MUST use `WORKDIR_LOCK` + `DirGuard`** (both in `tests/common/mod.rs`): `std::env::set_current_dir` is process-wide and tests within one binary run in parallel — a bare `set_current_dir` breaks unrelated command tests non-deterministically (bit us 2026-09-06; 8 tests failed until converted to the guard pattern).
- **Benchmarking git honestly** (`examples/bench_vs_git.rs`): (1) run with `--release`; (2) pass `-c core.hooksPath=/dev/null` — this machine has a global IBM Vault Radar pre-commit hook adding ~2s per commit, which otherwise fabricates a 100x "speedup"; (3) frame the comparison as codetree library/MCP calls (no subprocess) vs git CLI subprocesses — that's what agents actually pay with each tool.
- **Auto-snapshot (jj-style working-copy safety net)** (2026-09-06, `src/snapshot.rs` + `src/commands/snapshot.rs` + `VcsManager::snapshot_working_tree`): before risky commands (`switch`, `start` w/ checkout, `rebase`, `merge`, `finish` via `withdraw_single`, `withdraw`, `undo`, `redo`, `resolve`), `commands::auto_snapshot()` walks the working tree, writes blobs, builds a tree, creates an **anonymous commit** (parent=HEAD, no ref update), and records it in `.codetree/snapshots.json`. Key invariants: (1) **skip if clean** — compares working-tree blob IDs to HEAD tree; returns `None` if no diff, so read-only commands and clean-tree commands pay zero cost; (2) **no index mutation** — the snapshot tree is built directly from working-tree files, never touches the staging index; (3) **`save` clears snapshots** — `clear_snapshots()` deletes `snapshots.json` after a successful commit (the real commit supersedes them); (4) **prune to 20** — `SnapshotManager::prune(MAX_SNAPSHOTS)` keeps newest; (5) **failure is non-blocking** — `auto_snapshot()` logs a warning and returns; the calling command still proceeds (safety net, not a gate). `restore-snapshot <id>` uses `restore_working_tree_pub` + `sync_index_to_commit` (NOT `sync_index_to_head` — the snapshot is an anonymous commit, not HEAD). **Anti-pattern**: don't snapshot inside `save` itself — `save` *is* the commit that supersedes snapshots.
- **`warn!` macro cannot be used in match-arm expression position** (`src/lib.rs:54`): the macro ends with `;` which triggers `semicolon_in_expressions_from_macros` when used as `Err(e) => warn!(...)`. Always wrap in a block: `Err(e) => { warn!(...); }`.
- **`codetree new` (jj-style empty commit)** (2026-09-06, `VcsManager::commit_empty` + `commands::new_command`): creates a commit with the **same tree as HEAD** and HEAD as the sole parent. No index mutation, no working-tree change. Use case: clean checkpoint before experimenting — `undo` brings the agent back without losing the working tree. **Anti-pattern**: don't use `#[command(alias = "new")]` on a command named `New` — clap panics with "alias `new` is duplicated" because the kebab-case name *is* `new`.
- **`codetree absorb` (Sapling-style)** (2026-09-06, `VcsManager::absorb` in `src/vcs/rewrite.rs` + `commands::absorb_command`): auto-absorbs uncommitted working-tree changes into the best-matching commit in branch history. Algorithm: (1) compute wt-modified files vs HEAD, (2) walk back up to 50 commits collecting each commit's changed files (diff vs parent), (3) pick the commit with the most file overlap, (4) amend that commit's tree with new content for overlapping files, (5) rebuild descendants — for each absorbed file, if the descendant didn't change it (same blob as the original target), update to the new version; otherwise keep the descendant's version, (6) update branch ref + sync index/working tree. **Critical ordering bug**: `commits` vector is ordered newest-to-oldest (HEAD first), so descendants are `commits[0..best_idx]` iterated in **reverse** (oldest descendant first), NOT `commits[best_idx+1..]` which are ancestors. **Tree entry deletion marker**: use `mode == 0` as a sentinel for deletion, then `retain(|e| e.mode != 0)` to remove. New files (not in target tree) are only added if the target is HEAD (best_idx == 0).
- **`codetree test <commit>` (git-branchless-style)** (2026-09-06, `commands::test_command`): runs a validation command at a specific commit without permanently checking out. Flow: `auto_snapshot()` → `sync_index_to_commit` + `restore_working_tree_pub` to target → `std::process::Command::new(program).args(args).status()` → restore original HEAD's tree. **Clap pattern**: use `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]` on the `command: Vec<String>` field so users can write `codetree test HEAD -- make test -j4` without clap eating the `-j4`. **Always restore on both success and failure paths** — the restore code runs unconditionally before reporting the result. The command returns `Err` on non-zero exit so agents can detect test failures programmatically.
- **Revset `!` operator** (2026-09-06, `src/commands/status.rs`): `!` alone matches only-child branches (parent has no other active children). `!<term>` negates any term (e.g. `!active` matches non-active). Implementation: `matches_query` and `matches_term` now take `&[BranchInfo]` (all branches) as a parameter so `is_only_child` can check siblings. **Gotcha**: `BranchManager::list_branches()` returns `Vec<&BranchInfo>`, so the query path must clone into `Vec<BranchInfo>` before passing to `matches_query` — the borrow checker won't let you filter the original slice while borrowing it for the predicate.
- **JSON output mode** (2026-09-06, `src/main.rs` + `src/commands/status.rs`): `--json` global flag on the CLI. Currently implemented for `status` (returns `{branch, staged, modified, untracked, conflicts_pending, conflict_files, active_operations}`), `list` (returns array of `BranchInfo`), and `ready` (returns `{branch, base, ready, ahead, behind, up_to_date, conflicts, auto_resolvable, conflict_files}`). **Pattern**: extract `let json = cli.json;` before the `match cli.command` block because match arms consume `cli.command` and can't borrow `cli.json` simultaneously. `VcsStatus`, `BranchInfo` (vcs/manager.rs), and `ReadyCheck` now derive `serde::Serialize`. `BranchInfo` (branch.rs) was already `Serialize`/`Deserialize`. When adding JSON output to more commands, follow the same pattern: build a `serde_json::json!({...})` value, `to_string_pretty`, print, return early.
- **`codetree ready [branch]`** (2026-09-06, `VcsManager::check_ready` in `src/vcs/merge.rs` + `commands::ready_command`): read-only merge readiness check. Performs a trial 3-way merge (`merge_trees` is read-only — computes entries + conflicts without writing) and checks the resolution cache for auto-resolvability. Returns `ReadyCheck { ahead, behind, up_to_date, conflict_count, auto_resolvable, conflict_files }`. A branch is "ready" when `up_to_date && auto_resolvable`. **Gotcha**: `start` creates parallel operations that stay on `main`, so `ready` without a branch argument checks `main` (not a tracked operation) — always specify the branch name or switch to it first. The `branch: Option<String>` parameter is consumed by `match`, so check `branch.is_some()` before the match if you need to know whether the user specified a branch.
- **`codetree import` (Git interop)** (2026-09-06, `src/commands/import.rs`): one-way bridge from Git to CodeTree. Uses `git` CLI as a **subprocess** (not a library dependency — `git2` is still not in `Cargo.toml`). Flow: `git log --reverse --format=%H|%an <%ae>|%at|%s` → for each commit, `git checkout <hash> -- .` (or `git archive` fallback) → `VcsManager::add_all` + `commit_with_meta(message, author, timestamp)`. Preserves original author, message, and timestamp. `Repository::commit_with_meta` is a new method that accepts custom author/timestamp (the existing `Repository::commit` always uses current time). **Important**: this does NOT reintroduce Git as a core dependency — `import` is an optional interop command that gracefully bails if `git` is not installed. The `.git` directory is preserved after import; users can remove it manually.
- **Auto-commit policy** (2026-09-06, `src/config.rs` `AutoConfig` + `src/commands/operations.rs`): `[auto] save_on_switch = true` in config.toml makes `switch` auto-save uncommitted changes before switching (creates a real commit) instead of snapshotting (anonymous commit). Default: false (snapshot). The check is: `get_status().await?` → if modified/untracked is non-empty → `save_command(None, false, false)`. **Pattern**: `switch_command` now loads config before deciding whether to snapshot or save — the config load is cheap (single file read).
- **Operation-state snapshots** (2026-09-06, `src/commands/snapshot.rs`): `codetree snapshot --ops` and `codetree restore-snapshot <id> --ops` extend the working-copy snapshot system to also back up/restore operation state (branches.json, ops.json). Backups are stored in `.codetree/ops_backups/<id>/`. When the working tree is clean but `--ops` is passed, a timestamp-based ID is used instead of the snapshot manager's sequential ID. **Pattern**: `backup_ops_state` and `restore_ops_state` are simple file-copy helpers — no serialization complexity, just `std::fs::copy` for each state file.
- **`codetree export` (Git interop)** (2026-09-06, `src/commands/import.rs`): reverse of `import` — reads CodeTree commits oldest-first and recreates them in a Git repo. Uses `git` CLI subprocess with `GIT_AUTHOR_NAME`, `GIT_AUTHOR_EMAIL`, `GIT_AUTHOR_DATE`, `GIT_COMMITTER_DATE` env vars to preserve original metadata. Handles empty commits via `--allow-empty`. **Important**: this enables the "GitHub export" workflow — `codetree export && git push && gh pr create`. The `.codetree` directory is preserved alongside the new `.git` directory.
- **`codetree publish [branch]` (Export to PR)** (2026-09-06, `src/commands/compare.rs`): now works end-to-end by composing `export_command` + `git push -u <remote> <branch>` + `gh pr create`. Previously a stub calling `VcsManager::push_branch` (which is still a stub for the future Phase 7 remote protocol). The new flow: export CodeTree → Git → push to remote → generate PR title from operation description + body from commit log and diff summary → `gh pr create` (gracefully degrades if `gh` not installed). **Pattern**: compose existing commands (`super::export_command().await?`) rather than duplicating logic.
- **`codetree bundle` / `codetree unbundle`** (2026-09-06, `src/commands/bundle.rs`): offline transfer format using `tar` CLI subprocess (no new dependency). `bundle -o <path>` creates a tar.gz of `.codetree/` excluding transient state (ops_backups, pending_resolution). `unbundle <path>` extracts the archive, backs up any existing `.codetree/`, and restores the working tree to HEAD via `sync_index_to_commit` + `restore_working_tree_pub`. **Gotcha**: unbundle must restore the working tree after extraction — the bundle only contains `.codetree/` state, not working-tree files. **Pattern**: use `std::process::Command` for tar instead of adding a tar crate dependency; this matches the `import`/`export` pattern of using CLI subprocesses for optional interop features.
- **Template-based output** (2026-09-06, `src/commands/status.rs`): `list --format "{name} {status} {description}"` accepts a template string with placeholders. Supported: `{name}`, `{status}`, `{description}`, `{created}`, `{tags}`, `{stale}`. Implementation is simple `str::replace` chaining in `render_template` — no template engine dependency. **Pattern**: when adding `--format` to other commands, follow the same approach: add an `Option<String>` parameter, check it after the JSON branch, and use `render_template`-style placeholder substitution.
- **Auto-rebase daemon** (2026-09-06, `src/main.rs`): `codetree rebase --watch <secs>` runs `rebase_command` in a loop with `tokio::time::sleep`. The daemon logic is in the CLI dispatch, not in `rebase_command` itself — this keeps the command function pure and testable. **Pattern**: daemon modes should be implemented as a loop in the dispatch layer, not in the command function. The command function should remain a single-shot operation that can be tested in isolation.
- **Segmented changelog** (2026-09-06, `src/commands/status.rs`): `smartlog --limit <N> --offset <N>` paginates the operation list. Implementation: `skip(off).take(lim)` on the branch list before building the tree. Shows a `[Segment: X-Y of Z operations]` header when the segment is smaller than total. **Pattern**: pagination should be applied early (before tree construction) to avoid unnecessary work. The `Option<usize>` parameters default to `None` (no pagination), preserving backward compatibility.
- **`codetree reword <commit> -m <message>`** (2026-09-06, `VcsManager::reword` + `commands::reword_command`): rewrites a commit's message and rebuilds all descendants on the current branch. Accepts `HEAD`, `HEAD~N`, or a hash prefix. **Implementation**: walks from HEAD to the target collecting descendants (newest first), rewrites the target commit with the new message (preserving tree, parents, author), then rebuilds descendants in reverse order (oldest first) with the new parent. **Pattern**: `resolve_commit` is a new helper that supports `HEAD`, `HEAD~N`, and hash prefix lookup via `walk_object_hashes` (scans the object store directory). This same pattern can be reused for future commit-spec commands. **Gotcha**: the descendant rebuild must preserve each descendant's original tree, author, message, and timestamp — only the parent changes.
- **`codetree squash <commit>`** (2026-09-06, `VcsManager::squash` + `commands::squash_command`): squashes a commit into its parent. The squashed commit uses the target's tree (which includes all changes from both commits) and combines both messages. **Implementation**: same descendant-rebuild pattern as `reword` — collect descendants, create the squashed commit with the parent's parents and combined message, rebuild descendants. **Key insight**: the squashed commit's tree is the target's tree (not a merge), because the target already contains all changes from the parent plus its own. The combined message is `"{parent_message}\n\n{target_message}"` unless they're identical.
- **`codetree sync`** (2026-09-06, `src/commands/rebase.rs`): pulls from remote + rebases all active branches. Composes `git pull <remote> <base>` + `rebase_command(false)`. Requires a Git repo (`.git` directory) — users must run `codetree export` first. **Pattern**: `sync` is a composition command like `publish` — it calls existing commands rather than duplicating logic. This keeps the implementation lean and testable.
- **Revset functions `merges()` and `branches(pattern)`** (2026-09-06, `src/commands/status.rs`): extends the query language. `merges()` is an alias for `merged` status. `branches(pattern)` supports glob-style `*` wildcards: `branches(codetree_op_feat_*)` matches by prefix, `branches(*fix*)` matches by substring, `branches(exact_name)` matches exactly. **Implementation**: simple pattern matching in `matches_term` — no regex dependency. The `*` wildcard is handled with `starts_with`/`ends_with`/`contains` depending on wildcard position.
- **`smartlog --reverse`** (2026-09-06, `src/commands/status.rs`): reverses the branch list after pagination. **Pattern**: `--reverse` is applied after `skip`/`take` so pagination + reverse compose correctly. The `reverse` parameter defaults to `false`, preserving backward compatibility.
- **`codetree move <commit> --onto <parent>`** (2026-09-06, `VcsManager::move_commit`): reparents a commit onto a new parent. The tree is preserved — only the parent pointer changes. **Implementation**: same descendant-rebuild pattern as `reword`/`squash`. **Safety checks**: prevents moving a commit onto itself or onto one of its own descendants. **Pattern**: `move` is a graph-rewriting operation that doesn't change tree content, only the parent linkage. This is simpler than a full rebase (which would need to compute diffs and apply them).
- **`codetree unsquash <commit>`** (2026-09-06, `VcsManager::unsquash`): reverses a squash by splitting a commit back into two. **Limitation**: the original parent's tree was destroyed during squash, so unsquash uses the grandparent's tree as the restored parent's tree. This means the restored parent is effectively "empty" (same as grandparent) and the new commit contains all the changes. **Pattern**: unsquash cannot perfectly reverse squash because the original tree information is lost — it's a best-effort restoration. The combined message is split by using the parent's message for the restored commit and the target's message for the new commit.
- **`smartlog --exact`** (2026-09-06, `src/commands/status.rs`): skips rendering HEAD and the base branch for cleaner output. **Pattern**: `exact` mode is useful when you only want to see operation branches, not the base. Implemented as a simple boolean guard around the base branch and position rendering.
- **`codetree revert <commit>`** (2026-09-06, `VcsManager::revert`): creates a new commit that undoes a previous commit's changes. Uses 3-way merge with base=target_tree, ours=head_tree, theirs=target_parent_tree. **Key insight**: revert does NOT rewrite history — it adds a new commit on top of HEAD. This is safer than `undo` for shared branches. **Bug fix**: the `merge_trees` function was missing deletion cases — `(Some(b), Some(o), None) where b == o` (theirs deleted, ours unchanged) was falling through to conflict. Added three new cases: deletion in theirs/ours/both when the other side is unchanged.
- **`codetree log [commit] --limit <N>`** (2026-09-06, `src/commands/status.rs`): linear commit history view. Walks from HEAD (or specified commit) to root, printing hash, date, and first message line. Uses a simple `format_timestamp` helper that converts Unix timestamps to `YYYY-MM-DD HH:MM` format without chrono. **Pattern**: `log` is a read-only command that doesn't modify state — no auto-snapshot needed.
- **`codetree goto <commit>`** (2026-09-06, `VcsManager::goto_commit`): checks out a specific commit in detached HEAD mode. Uses `set_detached_head` (new method on `RefStore`). **Gotcha**: `switch_command` only works with tracked operation branches, not `main` — to return from detached HEAD to main, use `checkout_branch("main")` directly. **Pattern**: `goto` is useful for inspecting an arbitrary commit's state without creating a branch. The working tree is restored to the target commit's tree.
- **`codetree amend-to <commit>`** (2026-09-06, `VcsManager::amend_to`): amends working-tree changes into a specific commit (not just HEAD). Similar to `absorb` but with an explicit target. **Implementation**: computes working-tree changes, amends the target commit's tree for overlapping files, rebuilds descendants with updated blobs for amended files. New files are only added if the target is HEAD. **Pattern**: `amend_to` is more precise than `absorb` (which auto-detects the target) — use `amend_to` when you know which commit to amend.
- **`codetree squash-into <ancestor>`** (2026-09-06, `VcsManager::squash_into`): squashes HEAD into a specific ancestor (not just the parent). The HEAD's tree replaces the ancestor's tree, messages are combined. Intermediate descendants (between HEAD and the target) are rebuilt with their original trees. **Key insight**: HEAD itself is not rebuilt — its changes are absorbed into the squashed commit. The descendant rebuild `skip(1)`s HEAD since it's the one being squashed.
- **Large file handling** (2026-09-06, `src/config.rs` + `src/vcs/manager.rs`): `[git] max_file_size = <bytes>` config option. Files larger than the limit are skipped during `add_all` with a warning. **Implementation**: `VcsManager` has a `max_file_size` field (default 0 = no limit). `save_command` sets it from config before calling `add_all`. **Pattern**: the limit is enforced at the staging level, not the commit level — this prevents large files from ever entering the object store.
- **`codetree fold --from <commit>`** (2026-09-06, `VcsManager::fold`): folds a range of commits (from the specified commit to HEAD) into a single commit. **Implementation**: collects all commits in the range, uses HEAD's tree, combines all messages in oldest-first order. The folded commit's parent is the from-commit's parent. **Pattern**: `fold` is a generalization of `squash_into` — while `squash_into` squashes HEAD into a specific ancestor (combining only two messages), `fold` collapses an entire range (combining all messages). Both use HEAD's tree as the result tree since it already contains all accumulated changes.
- **Commit inspection commands** (2026-09-06, `src/vcs/query.rs` + `src/commands/status.rs`): `show`, `diff`, `blame`, `filelog`, `clean`, `gc`. All reuse existing infrastructure (`diff_trees`, `unified_diff`, `walk_working_tree`, `resolve_commit`). **Key patterns**: (1) `show_commit_diff` diffs a commit's tree against its parent's tree. (2) `diff_working_tree` builds a tree from the working tree and diffs against HEAD. (3) `blame` walks backwards through commits comparing line-by-line to find when each line changed. (4) `file_log` walks backwards and records commits where the file's blob hash changed. (5) `clean` removes files not in HEAD's tree. (6) `gc` walks all branch refs, marks reachable objects (commits + trees + blobs), and removes the rest. **Gotcha**: `gc` must clone `commit.tree` before inserting into the reachable set, since `read_tree` borrows it afterward.
- **`codetree op-log`** (2026-09-06, `src/commands/undo.rs`): dedicated operation log viewer. Reuses `OperationLog::new` and `op_log.iter()`. **Pattern**: the first match for `desc` uses `..` to ignore `timestamp` (avoiding unused variable warnings), while a second match extracts `timestamp` for display. This avoids borrowing issues from a single match.
- **`codetree bisect`** (2026-09-06, `src/bisect.rs` + `src/commands/bisect.rs`): binary search for the first bad commit. State persists in `.codetree/bisect.json` via serde. **Implementation**: `BisectState` tracks bad commit, good commits, current test commit, and original HEAD/branch for restoration. `midpoint()` walks ancestors of bad until hitting a good commit, then picks the middle. **Key decisions**: (1) `is_active()` only checks `bad.is_some()` (not `good.is_empty()`) because a session starts with only `bad` set. (2) Uses `goto_commit` to checkout the midpoint for testing. (3) `reset` restores the original branch via `checkout_branch`. (4) `BisectState` derives `Default` via `#[derive(Default)]` (clippy suggested this over manual impl). **Pattern**: bisect is agent-automatable — an agent can run `bisect start`, test the code, run `bisect good` or `bisect bad`, and repeat until the first bad commit is found.
- **`codetree tag`** (2026-09-06, `src/vcs/refs.rs` + `src/commands/tag.rs`): named pointers to commits, stored in `refs/tags/`. **Implementation**: added `set_tag`, `get_tag`, `delete_tag`, `list_tags` to `RefManager` mirroring the branch methods. Tags are lightweight (just a ref file containing the commit hash). **Pattern**: tag subcommands use a `TagAction` enum like `BisectAction` — clean dispatch from CLI subcommand to command logic.
- **`codetree abandon <commit>`** (2026-09-06, `VcsManager::abandon`): removes a commit from history and rebuilds descendants onto its parent. **Key insight**: descendant trees are preserved as-is — they already include the abandoned commit's changes (since each commit's tree is the cumulative result). The abandoned commit is simply skipped during descendant rebuild. **Pattern**: similar to `squash` but instead of merging two commits, it removes one. The descendant rebuild loop is the same as `reword`/`move`/`unsquash`: collect descendants newest-to-oldest, rebuild oldest-to-newest.
- **`codetree move --dry-run`** (2026-09-06, `src/commands/save.rs`): previews a move without executing. **Implementation**: in dry-run mode, resolves both commits and prints what would happen, then returns early without calling `move_commit`. Skips `auto_snapshot`. **Pattern**: dry-run is a command-layer concern — the VcsManager doesn't know about it. The command function checks `dry_run` before calling the manager. This same pattern was applied to `reword`, `squash`, and `fold` — each checks `dry_run` before calling the VcsManager and skips `auto_snapshot` in dry-run mode. **Gotcha**: when adding `dry_run: bool` parameters to command functions, all existing integration test callers must be updated with `false` for the new parameter. Use targeted `sed` commands but verify no collateral modifications (e.g., `unsquash_command` was accidentally modified by a broad sed pattern).
- **`codetree revive` / `duplicate` / `describe`** (2026-09-06, `src/vcs/rewrite.rs` + `src/commands/save.rs`): three lightweight commands built on existing patterns. **revive**: creates a new commit on HEAD with the abandoned commit's tree and message — essentially a cherry-pick without merge. **duplicate**: same as revive but appends " (duplicated)" to the message. **describe**: pure alias for `reword` — delegates directly to `reword_command`. **Pattern**: `revive` and `duplicate` are nearly identical (both create a new commit on HEAD with a target commit's tree), differing only in the message. They don't need descendant rebuilds since they add rather than modify.
- **`codetree config`** (2026-09-06, `src/commands/config_cmd.rs`): CLI config management with `get`, `set`, `list` subcommands. **Implementation**: parses TOML text directly (simple `[section]` + `key = value` format) without a full TOML parser — sufficient for CodeTree's flat config structure. **Pattern**: `find_config_value` walks lines tracking the current section, then matches the field. `set_config_value` updates in-place if found, appends to the section if the key is new, or creates a new section if needed. **Gotcha**: clippy warns about collapsible `if` chains — use `if X && let Some(...) && Y` pattern with let-chains (Rust 2024 edition).
- **`codetree tag --annotate`** (2026-09-06, `src/commands/tag.rs`): annotated tags with message and metadata. **Implementation**: annotation metadata is stored as a JSON file (`<name>.annot`) alongside the plain tag ref in `refs/tags/`. The `TagAnnotation` struct (serde-serializable) holds commit, tagger, timestamp, and message. **Pattern**: lightweight tags use the plain ref file; annotated tags add the `.annot` sidecar. `tag list` shows messages from annotations when present. `tag delete` removes both files. **Key decision**: storing annotation as a sidecar file (not embedding in the ref) keeps the ref format simple and backwards-compatible.
- **`codetree file-search` / `file-list` / `heads`** (2026-09-06, `src/vcs/query.rs` + `src/commands/status.rs`): three read-only inspection commands. **file-search**: walks HEAD tree entries, reads each blob, does case-insensitive substring search line-by-line. **file-list**: returns all entry names from a commit's tree. **heads**: lists all branches with their tip commit hashes. **Pattern**: all three are pure read operations — no working tree changes, no ref updates, no auto_snapshot. **Gotcha**: `Blob` struct uses `content` field (not `data`).
- **`codetree next-commit` / `prev-commit` / `restack-graph`** (2026-09-06, `src/commands/operations.rs`): commit navigation and graph repair. **Naming conflict**: `next_command`/`prev_command` already existed for operation/branch switching, so the commit-navigation versions were named `next_commit_command`/`prev_commit_command`. Similarly, `restack_command` existed in `rebase.rs`, so the graph-check version was named `restack_graph_command`. **Pattern**: when adding new commands that share a concept with existing ones, check for naming conflicts before implementing. **prev-commit** simply reads HEAD's parent and checks it out. **next-commit** walks from branch tips to find a commit whose parent is HEAD. **restack-graph** walks branches checking for missing commits.
- **`codetree fix`** (2026-09-06, `src/commands/save.rs`): runs a formatting/fixing command and amends changes into HEAD. **Implementation**: runs the command via `std::process::Command`, then `add_all`, then `amend_commit`. **Pattern**: similar to `test_command` but instead of restoring the original state, it keeps the changes and amends them. **Key detail**: uses `trailing_var_arg = true` and `allow_hyphen_values = true` in clap to pass the command after `--`. **Gotcha**: the amend method is `amend_commit()` (not `amend_head()`).
- **`codetree evolog` / `interdiff` / `restore` / `hide` / `unhide` / `log --count`** (2026-09-06): six features from jj v0.37/v0.38 and Sapling. **evolog** (`src/evolog.rs`): tracks commit predecessors in `.codetree/evolog.json`. `EvologLog::record()` is called when commits are rewritten. `history()` walks the predecessor chain. **interdiff**: uses `diff_trees` to diff two arbitrary commits' trees. **restore**: replaces target commit's tree with source's, rebuilds descendants — similar to `reword` but changes the tree instead of the message. **hide/unhide** (`src/hidden.rs`): persists hidden commit hashes in `.codetree/hidden.json`. Pure metadata — doesn't remove commits from the object store. **log --count**: walks the commit chain counting but not printing. **Clippy patterns**: (1) use `&Path` not `&PathBuf` for function parameters. (2) `while let Some(...)` is preferred over `loop { if let Some(...) }`.
- **`codetree file-search --name-only` / `forks` / `merge-point` / `verify` / `run` / `speculative-merge`** (2026-09-06): six features from jj v0.44 and git-branchless. **file-search --name-only**: filters tree entries by name pattern instead of reading blob contents. **forks**: walks all branches, counts children per commit, returns those with >1 child. **merge-point**: collects all ancestors of A into a HashSet, then walks B's ancestors to find the first match. **verify**: checks commit, tree, parent, and blob existence in the object store. **run**: restores each commit's working tree, runs the command, then restores original HEAD. **speculative-merge**: three-way merge conflict detection — compares base/ours/theirs tree entries, flags files where both sides modified differently from base. **Clippy pattern**: `&(_, &count)` pattern needed when iterating over `HashMap<&String, &usize>` references. **Test pattern**: use `git_manager.create_branch("name", None).await?` to create branches in tests (not `BranchManager::new` which is for the branch database).
- **`codetree branch-rename` / `branch-advance` / `forget` / `show --mutation` / `save` multi `-m`** (2026-09-06): five features from jj v0.39 and Sapling. **branch-rename**: `RefManager::rename_branch()` does `fs::rename` on the ref file. **branch-advance**: `RefManager::set_branch()` to move a branch pointer. **forget**: calls `abandon()` then best-effort removes the commit object via `object_path()`. **show --mutation**: reads evolog history and displays predecessor chain. **save multi -m**: changed `save_command` signature from `Option<String>` to `Vec<String>`; multiple `-m` flags combine as `title\n\nbody`. **Breaking change pattern**: when changing a command signature from `Option<String>` to `Vec<String>`, must update ALL callers — including `examples/bench_vs_git.rs` and internal callers in `save.rs` and `operations.rs`. Use `vec![]` for `None` and `vec!["msg".to_string()]` for `Some("msg")`. **Object path**: objects are stored as `objects/<first 2 chars>/<remaining 38 chars>` via `object_path()` in `src/vcs/objects.rs`.
- **Test-suite split into per-concern binaries** (2026-11-07, first AGENTS.md Step 9 application): `tests/integration_tests.rs` (5,997 lines, 162 tests) → `tests/{lifecycle,history_surgery,query,coordination,merge_conflicts,use_cases,interop,branch_registry}.rs` + `tests/common/mod.rs`. **The glob-import trick keeps it behavior-neutral**: `common/mod.rs` re-exports the original import surface (`pub use codetree::...`) plus helpers (`create_test_repo`, `WORKDIR_LOCK`, `DirGuard`); every test file starts `mod common; use common::*;` — glob imports never trigger `unused_imports`, so test bodies needed zero edits. **Required allows in `common/mod.rs`**: `#![allow(dead_code)]` + `#![allow(unused_imports)]` — in binary crates `pub` does NOT suppress dead-code warnings, and each binary uses a different helper subset. **Gotcha — mid-file non-test items**: any item that isn't a `#[tokio::test]` fn (a plain helper like `count_commits_from`, or a helper region like the original `use tokio::sync::Mutex; static WORKDIR_LOCK; struct DirGuard` block sitting between tests) is invisible to a test-anchored block parser and gets glued to the adjacent test's block — surfacing as E0425 "cannot find function" in one binary and dead-code duplicates in another. After splitting, grep for both and move stragglers to `common/mod.rs` as `pub` items. **Concurrency invariant**: `WORKDIR_LOCK` is now per-binary — safe because cargo runs test binaries sequentially; if test binaries ever run in parallel, cwd-touching tests across binaries will race (documented in `common/mod.rs`). **Split recipe**: locate `#[tokio::test]` + `async fn test_*` pairs, walk each start up over doc comments, classify by ordered name-regex rules (first match wins, explicit lists before substrings, `^test_uc` before area rules), verify total count == 162 before deleting the original.
## Documentation Audit Patterns
- **Sources of truth for doc audits**: `src/main.rs` `enum Commands` (+ aliases) is the CLI contract; `src/mcp.rs` `#[tool]` list is the MCP contract; `src/config.rs` structs are the config contract; `src/branch.rs`/`src/ops.rs` are the data-model contract.
- **2026-09-05 audit results** (all fixed): README "planned" claims for shipped features; SPEC data-type drift; `commands.rs` → `commands/` module map; stale `git` references in UC-11/TODO; broken LICENSE link; publish/candidate-group overclaims; "every command has an MCP twin" overclaim.
## 6. Competitive Intelligence — External Landscape (2026-11-07)
Consult before running AGENTS.md Step 7 rounds; harvest new rounds here with dates. Drove TODO.md Round 13.
### AI-native VCS entrants (2025–2026)
- **Oak** (oak.space, Apache-2.0 Rust, public beta 2026-06): BLAKE3 + content-defined chunking; SQLite or Git storage backends; **lazy mount** (streams manifest first, file contents on first read — agents start editing in ~1s); **branch-per-session** with the branch description doubling as the commit message; `--json` on every command + typed exit codes; claims up to 95% faster snapshots than Git on large repos; Git interop via `oak export` + **read-only git Smart-HTTP** so plain `git clone` works.
- **Supafork** (supafork.com, beta 2026): Git **wire-compatible** VCS for agents (agents' existing git knowledge works day one); versions harness sessions by reading Claude Code / Codex / OpenCode / Cursor session stores *after the fact* — nothing sits in the agent hot path.
- **Regent / re_gent** (re-gent.dev, Apache-2.0 alpha 2026): VCS for agent *activity*: `rgt log` (the conversation behind a commit), `rgt blame` (line → exact prompt), `rgt sessions` (session-per-branch); content-addressed storage that survives harness `/compact`.
- **Merget** (merget.ai, commercial): "every prompt becomes a commit" — prompt data, intent, and transcripts stored in commit objects; line/prompt/goal-level attribution; intra-prompt rollback; token-intelligence dashboards.
- **Mesa** (mesa.dev): versioned *filesystem* for agent documents (POSIX + VCS semantics) — adjacent, not a code VCS.
### Established players' agent moves
- **jj 0.45–0.47** (2026): `jj converge` auto-resolves divergent commits (non-interactive mode aborts if heuristics are inconclusive); `jj run` executes a command per revision in private working copies with changes propagating/rebasing automatically; `jj file edit`/`file delete` modify any revision without touching the working copy; workspaces colocate with Git worktrees; `git push --allow-conflicts`; **megamerge pattern**: `jj new a b c` (multi-parent), edit freely, `jj absorb` routes each hunk back to the branch that last touched those lines.
- **GitHub** (2026): stacked PRs GA 2026-10-06 (`gh stack sync`, stack map UI, branch protection against the final target); `gh skill install github/gh-stack` teaches agents to build stacks from the start of a task; Copilot **Agent Merge** auto-addresses failing checks, review comments, *and merge conflicts*, then merges when verification passes.
- **Graphite / Cursor Origin**: Cursor acquired Graphite 2025-12; Origin is Cursor's Git forge with **versioned PRs** (each push snapshots a new version; review threads carry per-version state; `--change-version` interdiffs); `gt create --ai` generates branch name + commit message.
- **Claude Code checkpoints**: snapshots before Write/Edit per turn; `/rewind` restores code, conversation, or both; SDK `rewind_files()` (has dry-run); explicitly "not a replacement for version control"; **does not capture** shell-command edits or most subagent edits — a VCS-level checkpoint has strictly more coverage.
- **Mergiraf** (mergiraf.org, Rust + tree-sitter): syntax-aware merge driver for git/jj; resolves same-line changes to independent syntax elements, commutative-parent insertions (class fields, imports, HTML attrs); **flags duplicate JSON/YAML keys that line-based merge silently corrupts**; `solve`/`review` subcommands; falls back to line merge on parse errors/timeout. Diversion wires it (and AI) as per-pattern merge tools: `dv merge-tool add --pattern '\.json$'`.
- **Merge gates / agentic review** (2026): review is the bottleneck with agents (Faros: +441% median PR review time; LinearB: 4.6x longer first-review wait). Working patterns: risk-tiered stage gates (CodeHerder: todo→plan→code→review→merge→verify, server-enforced); deterministic gates kept separate from LLM review (Sonar: "an LLM verdict should not serve as a merge gate on its own"); approval freshness (Corridor: approval goes stale the moment code is pushed); Codacy Verity checks agent output against the original prompt.
- **Worktree orchestrators** (Conductor, Claude Squad, Superset, Sculptor, intentic, Docker sbx): worktree-per-agent + session UI, setup/run scripts, checks aggregation, turn-level checkpoints. Consensus lessons: worktrees isolate files, **not** runtime (ports/dbs/env) and **not** semantics (a clean merge can still break the build) — pair with conflict prediction.
### Design implications for codetree (drove TODO Round 13)
- **Provenance must be a sidecar** (`.codetree/provenance.json` keyed by commit hash) — never add fields to the hashed commit object; SHA-1 hashing is the Git-compat contract (`hash_object`, `src/vcs/objects.rs`).
- **Merge drivers follow the import/export pattern**: optional subprocess, config-declared (`[merge] drivers`), zero new deps, graceful fallback to line merge — mirrors `commands/import.rs`.
- **Checkpoints build on `snapshot.rs`**: anonymous-commit snapshots already exist; turn-level = tag snapshot entries with checkpoint ids + a `rewind` command; VCS-level checkpoints cover shell/subagent edits harness checkpoints miss.
- **Gates generalize `[validation]`**: ordered gate list + verdicts in a `gates.json` sidecar; freshness = each verdict records the commit hash it validated.
- **Sources**: oak.space · supafork.com · re-gent.dev/blog/git-for-ai-agents · merget.ai · docs.jj-vcs.dev/latest/changelog · graphite.com/guides/stacked-diffs · infoq.com/news/2026/04/github-stacked-prs · mergiraf.org · code.claude.com/docs/en/checkpointing · codeherder.com/verification · blog.codacy.com (2026-09-18) · nimbalyst.com/blog/best-git-worktree-tools-ai-coding-2026