codetree 0.2.0

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

CodeTree is an **AI-native version control system**. It owns its object store, refs, commits, trees, and index in `.codetree/`. It does **not** depend on Git — no `git` subprocess, no `libgit2`. History is exposed through an *operation-centric* model designed for autonomous agents.

> **Migration complete:** CodeTree is fully Git-independent. All commands use the native VCS
> engine in `src/vcs/`. The `git2` dependency and `git.rs` have been removed.

## Philosophy

- **Git is not the engine.** CodeTree is its own engine. There is no `.git/` dependency.
- **The operation is the primitive**, not the branch. Branches/refs are storage details.
- **Agent output is untrusted by default** — isolated until validated and promoted.
- **Content-addressable storage**: objects (blobs, trees, commits) keyed by SHA-1, Git-compatible hashing.
- **Immutable, append-only history**; rewrites (`undo`, `rebase`) are explicit operations.
- **Agent-first API**: core lifecycle and coordination commands have JSON-returning MCP equivalents. No shell parsing.

## Module Map

```
src/
├── main.rs         CLI entry point (clap parser, command dispatch)
├── mcp_main.rs     MCP server entry point (stdio transport)
├── lib.rs          Library exports, feature gates (cli, mcp)
│
├── atomic.rs       ★ Crash-safe state writes: write_atomic (lockfile + staging
│                     sibling + rename), with_file_lock (generic RMW), stale-lock
│                     breaking. Every .codetree state file goes through this.
│
├── vcs/            ★ Native VCS core (the engine)
│   ├── objects.rs     Blob, Tree, Commit, ObjectId; SHA-1 content addressing
│   ├── refs.rs        RefManager + HeadRef: branch refs, HEAD symbolic ref
│   ├── index.rs       Index: staging area, path → blob hash + stat cache (skip re-hashing unchanged files)
│   ├── repo.rs        Repository::init() — creates .codetree/ skeleton
│   ├── manager.rs     VcsManager core: construction, branches, add/commit,
│   │                  status, working-tree plumbing, snapshot; shared types
│   ├── merge.rs       VcsManager impl: merge base, 3-way merge, cached merges,
│   │                  readiness, rebase, speculative merge
│   ├── rewrite.rs     VcsManager impl: jj-style history surgery (amend, reword,
│   │                  squash, move, abandon, fold, revert, absorb, restore)
│   ├── query.rs       VcsManager impl: read-only exploration (diffs, log, blame,
│   │                  search, forks, verify, run-across, gc, clean)
│   └── worktree.rs    VcsManager impl: linked worktrees + remote-push stub
│
│                     One type, many files: VcsManager's impl blocks are split
│                     by concern across merge/rewrite/query/worktree; the public
│                     API is unchanged (fields are pub(super), shared helpers are
│                     pub(super) fns in manager.rs).
│
├── commands/         CLI command implementations, focused modules
│                     (shared utils + re-exports in mod.rs)
│   ├── init_command       → VcsManager::init_at() — creates .codetree/ with native VCS
│   ├── start_command      → create branch ref + register operation
│   ├── save_command       → stage + commit via native VCS
│   ├── finish_command     → native merge + ref delete + mark merged
│   ├── withdraw_command   → native ref delete + checkout base + archive
│   ├── compare_command    → native diff across active ops + conflict detection
│   ├── rebase_command     → native rebase onto base/parent (topological order)
│   ├── restack_command    → fix broken stacking via parent_branch metadata
│   ├── switch/next/prev   → update HEAD + working tree (switch - toggles to last)
│   ├── watch_command      → fs watcher + debounce → auto stage + commit
│   ├── publish_command    → remote protocol push + Git bridge export
│   ├── merge_command      → low-level native merge + resolution cache
│   ├── resolve_command    → cache manual conflict resolutions, commit merge
│   ├── smartlog_command   → text tree view of operations, stacking, deps, tags (+ --position)
│   ├── undo_command       → revert Start/Save by index via operation log (pushes to redo stack)
│   ├── redo_command       → re-apply undone operation from redo stack
│   ├── whereami_command   → current position in version tree (parent, base, siblings, children)
│   ├── split_command      → split HEAD commit into two by file selection
│   ├── status_command     → native status (working tree vs index vs HEAD)
│   ├── list_command       → reads branches.json (already VCS-agnostic)
│   └── worktree_*         → linked working trees
│
├── branch.rs       BranchManager: operation metadata persistence
│   ├── branches: HashMap<String, BranchInfo>
│   ├── register_branch / register_branch_full (with tags, agent_id), update_branch_files
│   ├── set_parent_branch / get_parent_branch (stacking metadata)
│   ├── mark_branch_merged, archive_branch, remove_branch
│   ├── list_branches_by_tag, list_branches_by_agent, add_tag, remove_tag
│   └── save / load from branches.json
│
├── lock.rs         LockManager: file-level locking (.codetree/locks.json);
│                   acquire/release serialized by update_atomically (atomic.rs)
├── freeze.rs       FrozenPaths: read-only path protection (.codetree/frozen.json)
├── candidates.rs   CandidateManager: solution candidate groups (.codetree/candidates.json)
│
│
├── config.rs       Config: TOML persistence (base_branch, branch_prefix, templates, validation)
├── ops.rs          OperationLog: undo/redo journal (.codetree/ops.json)
│   ├── ops: Vec<Operation> + redo_stack: Vec<Operation>
│   ├── push/pop/remove (undo) + push_redo/pop_redo (redo)
├── resolution.rs   ResolutionCache + PendingResolution (conflict resolution cache)
├── mcp.rs          CodeTreeServer: MCP JSON-RPC tool handler
└── error.rs        Result<T>, Context trait, bail! macro
```

## Object Model

All history is content-addressable, stored under `.codetree/objects/`, using Git-compatible SHA-1 hashing (`"<type> <len>\0<content>"`):

```
Blob:   { content: Vec<u8> }                    → SHA-1
Tree:   { entries: Vec<(mode, name, hash)> }    → SHA-1
Commit: { tree, parents, author, message, ts }  → SHA-1
Ref:    branch name → commit hash
HEAD:   symbolic ref → branch name
```

Objects are written to `objects/<first-2-hex>/<remaining-38-hex>` (same fan-out layout as Git, so a future Git bridge can map objects directly).

## Storage Model

Everything lives in `.codetree/`. No `.git/` directory is created or used.

```
.codetree/
├── objects/        content-addressable store (blobs, trees, commits)
├── refs/heads/     branch refs (each file holds a commit hash)
├── HEAD            symbolic ref to current branch
├── index           staging area (path, blob hash, stat fingerprint for change detection)
├── config.toml     user configuration
├── branches.json   operation registry (descriptions, file scope, status, tags)
├── ops.json        operation log for undo
├── resolutions.json conflict resolution cache
├── locks.json      file locks (path → operation name)
├── frozen.json     frozen paths (read-only protection)
├── candidates.json candidate groups (group name → operation names)
└── pending_resolution.json  active merge conflict metadata for `resolve`
```

**Invariant:** `.codetree/` is the complete source of truth for code, history, and operation bookkeeping. Deleting it destroys the repository (unlike the old Git-backed design, where Git history survived).

## Data Flow

### Operation lifecycle: start → save → finish (happy path)

```
Agent / CLI
    │
    ├──► start "fix login"
    │       ├──► vcs: create branch ref at base commit
    │       ├──► branch::register_branch (description, file scope, tags)
    │       └──► ops::append(Start)                          [undo log]
    │
    ├──► save
    │       ├──► branch::get_branch → check assigned file scope
    │       ├──► vcs: stage files into index (respecting scope)
    │       ├──► vcs: write tree, create commit, advance branch ref
    │       ├──► branch::update_branch_files / set_last_commit
    │       └──► ops::append(Save)                           [undo log]
    │
    │   ┌── (optional) validation gate: tests / checks must pass ──┐
    │
    └──► finish
            ├──► branch::check depends_on satisfied
            ├──► vcs: checkout base, 3-way merge operation branch
            ├──► vcs: delete branch ref
            └──► branch::mark_branch_merged
```

### withdraw (abandon path)

```
withdraw <op>
    ├──► vcs: if HEAD is the branch, move HEAD to base
    ├──► vcs: delete branch ref
    └──► branch::archive_branch
```

### compare (inspection path)

```
compare
    ├──► branch::list → filter Active, non-branchless
    ├──► for each: vcs::diff(base..tip) → stats
    ├──► cross-reference declared file scope → conflict warnings
    └──► print aggregate summary
```

### undo (correction path)

```
undo [index]
    ├──► ops::load operation by index (or last)
    ├──► Start → vcs: delete branch ref + branch::remove_branch
    ├──► Save  → vcs: soft-reset last commit on branch
    └──► ops::save
```

## MCP Integration

```
AI Agent (Claude, Cursor, orchestrator)
    │
    ├──► stdio JSON-RPC  →  mcp_main.rs  →  mcp::CodeTreeServer
    │                          │
    │                          ├──► tool call → commands.rs → vcs / branch
    │                          └──► resource read → vcs / branch
    │
    └──► holds Arc<RwLock<BranchManager>> + Config
```

Core lifecycle and coordination commands have MCP twins returning typed JSON (`redo`, `split`, `smartlog`, `switch`/`next`/`prev`, `watch`, `resolve`, `worktree`, and `agents` are CLI-only for now — see `TODO.md`). The agent never shells out or parses CLI text.

## Deployment Topology

- **Single binary**, two entry points: `codetree` (CLI) + `codetree-mcp` (server).
- **Offline-first**: no daemon, no service, no network dependency for local work.
- **File-based state** in `.codetree/`; works on any filesystem.
- Remote collaboration is delivered via the planned remote protocol + Git bridge, not a hosted service.

## Feature Gates

- `cli` (default): `main.rs` CLI binary
- `mcp` (default): `mcp_main.rs` MCP server binary (implies `cli`)

Both can be disabled for library-only use:
```toml
[dependencies]
codetree = { version = "0.2", default-features = false }
```

## Testing Strategy

- **Unit tests** in each module (`vcs/objects.rs`, `branch.rs`, `config.rs`) — isolated behavior with temp directories.
- **Integration tests** in `tests/` — full CLI workflows end-to-end.
- **No mocking** — the native VCS is exercised against real temp repositories.