codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
# CodeTree

> **The AI-native version control system for fleets of autonomous coding agents.**

CodeTree is a standalone VCS — its own object store, refs, commits, and trees in `.codetree/`, with **no Git dependency**. It is built for the world Git wasn't: many agents, in parallel, writing code at machine speed with no human in the loop. Agents think in **operations**; CodeTree manages isolation, history, and merging natively.

> For the full product definition (what / who / why) see [`PRODUCT.md`](PRODUCT.md).
> For system design see [`ARCHITECTURE.md`](ARCHITECTURE.md); for the command/protocol contract see [`SPEC.md`](SPEC.md).

---

## The Problem

Git was designed for humans collaborating through pull requests and code review. Autonomous agents break that model in seven ways:

| # | Pain point | CodeTree's answer |
|---|---|---|
| 1 | Git serves human collaboration; agents need agent collaboration | **Operation-centric model** |
| 2 | Agents commit often, at variable quality | **Isolation + safe rollback** (undo + redo) |
| 3 | Agents overlap on the same files, wasting merge effort | **Scope ownership** (file locking) |
| 4 | Code must be tested before it lands in the repo | **Validation gate** (planned) |
| 5 | Several candidate solutions exist for one problem | **Candidate operations** — store many, evaluate, keep the winner |
| 6 | AI can break proven good code | **Frozen paths** — read-only protection for code that must not change |
| 7 | Agents need to know where they are in the version tree | **Orientation map** — `smartlog` + `whereami` |

### The operation lifecycle

The agent's mental model is a lifecycle, not a branch:

```
 start ─▶ save ─▶ … ─▶ finish    (promote: merge + cleanup)
   │                 └─▶ withdraw  (discard: clean rollback)
   └─▶ status                     (observe: ops, changes, conflicts)
```

- `start "fix login"` — create an isolated operation. **Default: parallel** (no checkout, no disruption).
- `save` — record progress to the operation.
- `finish` — promote it back to base and clean up. One command instead of `merge` + `branch -d`.
- `withdraw` — discard an operation entirely, cleanly and reversibly.

## Why a Native VCS

A Git wrapper would bolt agent concepts (ownership, locking, lifecycle, gates) on top as metadata. CodeTree makes them **first-class in the data model**:

- Ownership and locking live in the store, enforced at commit time.
- Rollback is a structured object-graph operation, not a fragile `git reset`.
- The operation lifecycle is part of history.
- No subprocess, no output parsing — the MCP API maps 1:1 to native primitives.
- **Crash-safe by construction**: every state write is atomic (temp file + rename, writer-serialized by lockfiles with stale-lock recovery). A killed agent can never leave a truncated branch ref or a corrupt lock registry.

Git-compatible SHA-1 object hashing means a future Git bridge (`codetree export`) can map objects directly for human collaboration and PRs.

> **Status:** the native VCS engine (`src/vcs/`: objects, refs, index, repo, and the `VcsManager` concern modules manager/merge/rewrite/query/worktree) is fully implemented. All commands run on the native VCS — no `git2` dependency, no `git` subprocess. File locking, code freezing, solution candidates, undo/redo, and the orientation map (`whereami`, `smartlog --position`) are implemented as CLI commands. Git interop (`import`/`export`/`publish`) uses `git` CLI as an optional subprocess for collaboration. See `TODO.md`.

---

## Installation

**Prerequisites:** Rust 1.70+.

```bash
cargo install --path .
# or from source:
cargo build --release   # smaller binary (opt-level=s, thin LTO, stripped)
```

This installs two binaries: `codetree` (CLI) and `codetree-mcp` (MCP server).

## Quick Start

```bash
codetree init                       # adopt the project (creates .codetree/)
codetree start "Fix login bug"      # create a parallel operation (stays on base)
# ... agent edits files ...
codetree save                       # stage + commit to the operation
codetree status                     # see current op, changes, active ops, conflicts
codetree finish                     # merge to base + delete branch + mark merged
codetree withdraw <op>              # (instead) discard an operation cleanly
codetree --json status              # machine-readable JSON output
```

## Commands

Only the essential lifecycle commands are shown here. Aliases in parentheses.
The full reference (navigation, maintenance, advanced) is in [`SPEC.md`](SPEC.md).

| Command | Description |
|---|---|
| `init` (`i`) | Initialize CodeTree; creates `.codetree/`. `--force` to reinitialize. |
| `start <desc>` (`st`) | Create an isolated operation (parallel by default). `--agent <id>` for multi-agent tracking. |
| `save [msg]` (`sv`) | Stage and commit progress to the current operation. `--validate` runs tests first; `--no-validate` skips. `--prompt <text>` records the intent behind the change (queried via `why`). |
| `finish [op]` (`f`) | Promote: merge to base + delete branch + mark merged. `--dry-run` to preview. On conflict, commits the merge and leaves the op active for `resolve`. |
| `merge [op]` | Low-level merge to base (use `finish` instead). `--squash` combines commits. Auto-resolves from the resolution cache, then configured merge drivers; otherwise commits first-class conflicts. |
| `resolve` | Finalize a conflicted merge: stage resolutions, amend the merge commit, cache resolutions, clean up. |
| `withdraw [op]` (`w`) | Discard an operation cleanly and reversibly. |
| `undo [index]` (`u`) | Roll back a prior `start`/`save` step. `--list` to browse. |
| `redo [index]` (`r`) | Re-apply a previously undone operation. `--list` to browse. |
| `status` (`s`) | Current op, changes, active ops, and file-conflict warnings. |
| `rebase` (`rb`) | Rebase all active ops onto base. `--dry-run` to preview. |
| `split` (`sp`) | Split HEAD commit into two by file selection. `--files a,b` picks first commit's files. |
| `new` | Create an empty commit on top of HEAD (jj-style checkpoint). `--message` to label it. |
| `absorb` (`ab`) | Auto-absorb uncommitted changes into the best-matching commit in branch history (Sapling-style). Figures out which commit to amend based on file overlap, then rebuilds descendants. `--route` instead sends changes back to the operations that own them (megamerge mode). |
| `megamerge` | Merge all active operations into one working state (multi-parent commit, HEAD detached) so cross-operation conflicts surface before `finish`. `--abort` discards it. |
| `test` | Run a validation command at a specific commit without checking out (git-branchless). `codetree test <commit> -- make test`. Restores the original working tree afterward. |
| `ready [branch]` | Check if a branch is ready to merge (read-only). Reports ahead/behind, conflicts, and cache auto-resolvability. Supports `--json`. |
| `import` | Import commits from a Git repository into CodeTree. One-way bridge using `git` CLI. `--force` to reimport. |
| `export` | Export commits from CodeTree to a Git repository (initializes one if needed). Enables PR creation via `gh`. |
| `bundle` | Pack `.codetree/` into a tar.gz archive for offline transfer. `unbundle <path>` restores it. |
| `switch <branch>` (`sw`) | Move to an active operation. Use `switch -` to toggle to last. |
| `freeze <path>` | Freeze a file or directory — no operation can modify it. |
| `unfreeze <path>` | Remove freeze. `--force` to skip confirmation. |
| `frozen` | List all frozen paths. |
| `unlock <path>` | Manually release a file lock (e.g. if an agent crashed). |
| `locks` | List all active file locks and which operation holds them. |
| `evaluate <group>` | Compare candidate operations in a group. |
| `promote <group> <op>` | Merge the winning candidate, withdraw all others in the group. |
| `agents` | List all known agents and their active operations. |
| `whereami` (`wa`) | Show current position in the version tree (parent, base, divergence, siblings). |
| `snapshot` (`snap`) | Manually create a working-copy snapshot (anonymous commit). No-op if clean. |
| `snapshots` (`snaps`) | List stored working-copy snapshots. |
| `restore-snapshot <id>` (`rsnap`) | Restore a snapshot's tree to the working tree (doesn't change HEAD). |
| `checkpoint` (`ckp`) | Create a labeled turn-level checkpoint (rewind target). Recorded even on a clean tree; survives `save`. `-m` labels it with the turn's prompt/intent. |
| `converge [op]` | Combine divergent commits of an operation into one (jj-style). Recovers work orphaned when two agents commit to the same operation. `--dry-run` previews. |
| `rewind <id>` | Rewind the working tree to a checkpoint — HEAD and history untouched. `--dry-run` previews changed files. |
| `reword <commit> -m <msg> [--dry-run]` | Rewrite a commit's message. Rebuilds descendants. `--dry-run` previews. |
| `squash <commit> [--dry-run]` | Squash a commit into its parent. `--dry-run` previews. |
| `unsquash <commit>` | Reverse of squash: split a commit back into two. |
| `move <commit> --onto <parent>` | Reparent a commit onto a new parent. |
| `revert <commit>` | Create a new commit that undoes a previous commit's changes (no history rewrite). |
| `amend-to <commit>` | Amend working-tree changes into a specific commit (not just HEAD). |
| `squash-into <ancestor>` | Squash HEAD into a specific ancestor commit. |
| `fold --from <commit> [--dry-run]` | Fold a range of commits (from specified commit to HEAD) into one. `--dry-run` previews. |
| `sync` | Pull from remote and rebase all active branches. |
| `log [commit] --limit <N>` | Linear commit history view (hash, date, message). |
| `show <commit>` | Show a commit's diff (what changed in that commit). |
| `diff [commit]` | Show diff between working tree and HEAD (or a specified commit). |
| `blame <file>` | Show which commit last modified each line of a file. |
| `why <path[:line]>` | Show provenance: the commit, operation, agent, and prompt behind a file or line (`codetree why src/main.rs:42`). |
| `filelog <file>` | Show commit history for a specific file. |
| `goto <commit>` | Checkout a specific commit (detached HEAD). Use `switch <branch>` to return. |
| `clean` | Remove untracked files from the working tree. |
| `gc` | Garbage collect unreachable objects from the object store. |
| `op-log` | Show the operation log (undo/redo history) with timestamps. |
| `bisect <subcommand>` | Binary search for the commit that introduced a bug. Subcommands: `start`, `good`, `bad`, `log`, `reset`. |
| `tag <subcommand>` | Manage tags (named pointers to commits). Subcommands: `create <name> [commit] [-m <msg>]` (annotated with `-m`), `list`, `delete <name>`. |
| `abandon <commit>` | Remove a commit from history and rebuild descendants onto its parent. |
| `revive <commit>` | Restore an abandoned commit onto HEAD. |
| `duplicate <commit>` | Create a copy of a commit on top of HEAD. |
| `describe <commit> -m <msg> [--dry-run]` | Alias for `reword` (jj-compatible naming). |
| `config <subcommand>` | Manage config: `get <key>`, `set <key> <value>`, `list`. |
| `file-search <pattern> [--name-only]` | Search file contents (or names with `--name-only`) in HEAD's tree. |
| `forks` | List fork points (commits with multiple children). |
| `merge-point <a> <b>` | Find the common ancestor of two commits. |
| `verify <commit>` | Verify a commit's integrity (tree, parents, blobs exist). |
| `run --from <commit> -- <cmd...>` | Run a command across each commit in a range. |
| `speculative-merge <branch>` | Check if merging a branch would conflict. |
| `branch-rename <old> <new>` | Rename a branch. |
| `branch-advance <name> [commit]` | Advance a branch to a target commit (default: HEAD). |
| `forget <commit>` | Abandon a commit and remove it from the object store. |
| `show <commit> [--mutation/-t]` | Show a commit's diff. `--mutation` shows predecessor history. |
| `save [-m <msg>]...` | Save changes. Multiple `-m` flags combine as title + body. |
| `file-list [commit]` | List all files in a commit's tree (default: HEAD). |
| `heads` | List all branch heads with their tip commits. |
| `next-commit` | Navigate to the next commit in the stack (child of HEAD). |
| `prev-commit` | Navigate to the previous commit in the stack (parent of HEAD). |
| `restack-graph` | Check and repair broken commit graphs after rewrites. |
| `fix -- <command...>` | Run a formatting/fixing command and amend changes into HEAD. |
| `evolog <commit>` | Show evolution history of a commit (predecessors from rewrites). |
| `interdiff <a> <b>` | Show diff between two arbitrary commits. |
| `restore --from <c1> --to <c2>` | Restore a commit's tree from another commit. |
| `hide <commit>` | Hide a commit from smartlog (remains in object store). |
| `unhide <commit>` | Unhide a previously hidden commit. |
| `log [commit] [--limit N] [--count]` | Linear commit history. `--count` prints only the count. |
| `move <commit> --onto <parent> [--dry-run]` | Reparent a commit. `--dry-run` previews without executing. |

### Scoping an operation

Declare scope up front so operations don't overlap (pillar: scope ownership):

```bash
codetree start "Fix login" --files src/auth.rs,src/login.html
codetree start "Add OAuth" --depends-on <op>   # finish blocks until deps merge
```

### Protecting proven code

Freeze files or directories so no operation can modify them:

```bash
codetree freeze src/critical.rs       # freeze a file
codetree freeze src/core/             # freeze a directory
codetree frozen                       # list all frozen paths
codetree unfreeze src/critical.rs     # remove freeze
```

### Solution candidates

Store multiple solutions for the same problem, evaluate, and keep the winner:

```bash
codetree start "Auth approach A" --files src/auth.rs
codetree start "Auth approach B" --files src/auth.rs  # different op, same file after A finishes
codetree evaluate auth-fix            # compare candidates in the group
codetree promote auth-fix <winner>    # merge winner, withdraw rest
```

---

## Configuration

CodeTree reads `.codetree/config.toml`:

```toml
[git]
branch_prefix = "codetree"
base_branch   = "main"
auto_push     = false
remote_name   = "origin"

[validation]
mode    = "off"       # "off", "optional", or "required"
command = "cargo test" # command to run before committing

[merge.drivers]
# Pluggable, syntax-aware conflict resolution (zero built-in deps).
# Order per conflict: resolution cache -> driver -> first-class conflict.
"*.json" = "mergiraf merge %base %ours %theirs -o %result"

[templates.refactor]
branch_prefix = "refactor"
commit_message_format = "Refactor: {description}"

[templates.bugfix]
branch_prefix = "fix"
commit_message_format = "Fix: {description}"
```

## MCP Server

Core lifecycle and coordination commands have a JSON-returning MCP equivalent — agents drive CodeTree via typed JSON-RPC, never shell parsing. (Not yet covered: `redo`, `split`, `smartlog`, `switch`/`next`/`prev`, `watch`, `worktree`, `agents`.)

```bash
codetree-mcp                         # stdio JSON-RPC server
codetree-mcp --verbose
codetree-mcp --codetree-dir /path/to/.codetree
```

**Tools:** `init_repository`, `start_op`, `save_changes`, `finish_op`, `withdraw_op`,
`compare_ops`, `rebase_ops`, `merge_branch`, `resolve_op`, `undo_op`, `publish_op`, `get_status`,
`list_branches`, `freeze_path`, `unfreeze_path`, `list_frozen`, `unlock_file`, `list_locks`,
`evaluate_candidates`, `promote_candidate`, `whereami`, `why`, `checkpoint`, `rewind`.

**Resources:** `config://codetree`, `status://branches`, `diff://current`.

```json
{
  "jsonrpc": "2.0", "id": 1, "method": "tools/call",
  "params": { "name": "start_op", "arguments": { "description": "Fix login bug" } }
}
```

## Architecture

Single binary, offline-first, file-based state in `.codetree/` (objects, refs, HEAD, index, config, branches registry, undo log, resolution cache). Modular core:

- **`vcs/`** — native VCS engine, one `VcsManager` type split by concern: `manager.rs` (core: branches, add/commit, status, working-tree plumbing), `merge.rs` (3-way merge, merge base, rebase), `rewrite.rs` (jj-style history surgery), `query.rs` (diff/log/blame/search/gc), `worktree.rs`, plus `objects.rs`/`refs.rs`/`index.rs`/`repo.rs`
- **`atomic.rs`** — crash-safe state writes: every `.codetree/` state file is replaced atomically (lockfile + staging file + rename), refs support compare-and-swap, and lock acquisition is race-free across concurrent agents
- **`branch.rs`** — operation metadata & lifecycle
- **`commands/`** — CLI command implementations (focused modules under `commands/`)
- **`mcp.rs`** — MCP JSON-RPC handler
- **`ops.rs`** — undo/rollback journal
- **`resolution.rs`** — conflict-resolution cache
- **`lock.rs`** — file-level locking (scope ownership)
- **`freeze.rs`** — frozen paths (read-only protection)
- **`candidates.rs`** — solution candidate groups

See [`ARCHITECTURE.md`](ARCHITECTURE.md) for the full module map and data flow.

## How It Compares

| Tool | Optimized for | Where CodeTree differs |
|---|---|---|
| git-branchless | A single human's stacked workflow | Concurrent agents; locking, queueing, gates, MCP-first |
| Jujutsu (jj) | Humans wanting a better VCS | Operation semantics tuned for autonomy |
| GitButler | Human-friendly virtual branches | Headless, API-first; no human at the keyboard |
| GitHub CLI (`gh`) | The PR workflow | Owns the local operation lifecycle before any PR exists |
| Oak (2026) | Raw agent speed — BLAKE3, lazy mount, branch-per-session | Coordination, not just speed: locking, freeze, candidates, validation gates, undo/redo |
| Supafork / Regent / Merget (2026) | Provenance for agent sessions ("every prompt becomes a commit") | Operations already carry agent + task identity; prompt-level provenance is on the roadmap (TODO Round 13) |
| Cursor Origin / Graphite / gh stacked PRs | Stacked *PR* review for humans and agents | Stacked *operations* locally; `publish`/`export` bridges to stacked PRs |

The core differentiator: **the 2026 wave (Oak, Supafork, Merget) confirms agent-native VCS is the right bet — CodeTree goes further than single-session speed or provenance with multi-agent coordination: locks, freeze, candidates, gates, and undo/redo as first-class store semantics.**

## Performance

CodeTree's native engine beats shelling out to git on the agent operation loop: library/MCP calls with zero subprocess overhead, plus a git-style stat cache in the index — unchanged files are never re-read or re-hashed on save, status, or checkout.

Measured on macOS (50 files, 15 saves editing 2 files per save; git driven as CLI subprocesses with hooks disabled):

| Operation | CodeTree | git (CLI) | Speedup |
|---|---|---|---|
| save (stage + commit) | ~4.5 ms | ~79 ms | ~17x |
| status | ~0.4 ms | ~18 ms | ~40x |
| branch (start operation) | ~3.1 ms | ~23 ms | ~7x |
| undo last save | ~1.8 ms | ~20 ms | ~11x |

Reproduce on your machine: `cargo run --release --example bench_vs_git`

## Development

```bash
cargo build          # dev build (faster)
cargo test           # unit + integration suite
cargo build --release
```

## License

Apache License 2.0 — see [LICENSE](LICENSE).