codetree 0.2.0

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

Scope, requirements, and protocol semantics for CodeTree.

> For the **product** definition (what/who/why, pain points, pillars) see [`PRODUCT.md`](PRODUCT.md).
> For the **system design** see [`ARCHITECTURE.md`](ARCHITECTURE.md). This file defines the contract.

## Scope

CodeTree is a **standalone version control system** built for AI agents. It does not depend on Git — no `git` subprocess, no `git2` library. CodeTree has its own object store, refs, commits, trees, and blobs, stored in `.codetree/`. The agent interface is operation-centric: the agent thinks in tasks, not branches.

## Design Principles

- **Operation-centric**: The primary unit of work is an operation, not a branch. Branches are an implementation detail.
- **No Git dependency**: CodeTree is a complete VCS. It does not shell out to `git` or link against `libgit2`.
- **JSON output**: `--json` global flag produces machine-readable JSON for `status` and `list` (more commands to follow).
- **Content-addressable storage**: Objects (blobs, trees, commits) are stored by SHA-1 hash, same as Git's model.
- **Immutable history**: Commits are append-only. Rewriting history requires explicit commands (`undo`, `rebase`).
- **Provenance sidecar**: `save --prompt` records the intent behind each commit in `.codetree/provenance.json`, keyed by commit hash (never inside the hashed commit object — SHA-1 object IDs stay Git-compatible). `codetree why <path[:line]>` traces blame → commit → operation → agent → prompt.
- **Agent-first API**: Core lifecycle and coordination commands have JSON-returning MCP equivalents. No shell parsing required. (CLI-only for now: `redo`, `split`, `new`, `absorb`, `test`, `smartlog`, `switch`/`next`/`prev`, `watch`, `worktree`, `agents`.)

## Product Requirements (from PRODUCT.md)

CodeTree is designed for **multi-agent collaboration**, not human collaboration. Seven requirements shape the system:

1. **Multi-agent collaboration**: Git is for humans; CodeTree is for agents. Multiple agents work concurrently on the same repo. Each agent has an identity. Operations track which agent created them.
2. **Safe rollback with undo + redo**: Agents commit frequently with varying quality. CodeTree must support easy rollback of any operation without impacting the rest of the codebase. Every commit is reversible via `undo`. A mistaken undo can be recovered with `redo`.
3. **File locking & scope isolation**: Agents may work on the same files. CodeTree supports file-level locking — when an agent claims files via `start --files`, those files are locked. Other agents queue or work on different files. Prevents merge conflicts by design.
4. **Pre-commit validation**: Code must be tested before it lands in the repo. CodeTree supports a validation gate (`--validate` flag or config policy) that runs tests before allowing a commit.
5. **Solution candidates**: Multiple agents may produce different solutions to the same problem. CodeTree supports **candidate groups** — parallel operations that solve the same task. The agent (or orchestrator) can evaluate, compare, and promote the best candidate, discarding the rest.
6. **Code freezing**: Parts of the codebase can be frozen (readonly). Frozen paths cannot be modified by any operation. Protects proven, working code from agent-induced regressions.
7. **Orientation map**: Agents need to know where they are in the version tree — current position relative to base and all other operations. `codetree smartlog` and `codetree status` provide this orientation: showing the active branch, its parent, sibling operations, and divergence from base.

## CLI Commands

| Command | Args | VCS Operations | Behavior |
|---------|------|---------------|----------|
| `init` | `--force` | Create object store, refs, HEAD | Creates `.codetree/` with object store, config, branches DB |
| `start <desc>` | `--checkout`, `--worktree`, `--branchless`, `--files`, `--depends-on`, `--template`, `--tags`, `--agent`, `--wait` | Create branch ref, optionally checkout/worktree | Creates isolated operation. **Default: parallel**. Branchless mode auto-absorbs saves into one commit. Tags enable batch finish/withdraw/list. `--agent <id>` tracks which agent owns the operation. `--wait` polls (2s interval) until conflicting file locks are released instead of failing immediately |
| `save` | `--message`, `--validate`, `--no-validate`, `--prompt` | Stage files, write tree, create commit | Stages and commits to active operation branch. `--validate` runs validation command before committing; `--no-validate` skips even if config requires it; `--prompt` records the intent that produced the change in the provenance sidecar |
| `finish [branch]` | `--tag`, `--dry-run` | Checkout base, merge, delete branch ref | One-step merge + cleanup. `--tag X` batch-finishes all active ops with tag X. `--dry-run` previews without changes |
| `withdraw [branch]` | `--tag` | Checkout base (if needed), delete branch ref | Reverts and removes operation. `--tag X` batch-withdraws all active ops with tag X |
| `compare` | — | Diff base..branch (per active branch) | Diff stats + conflict detection across all active ops |
| `split` | `--files`, `--message1`, `--message2` | Reset to parent, stage subset, commit, stage rest, commit | Splits HEAD commit into two by file selection |
| `new` | `--message` (`-m`) | Create empty commit | Create an empty commit (same tree as HEAD) on top of HEAD. Useful as a clean checkpoint before experimenting — `undo` brings you back without losing the working tree |
| `absorb` | — | Absorb uncommitted changes into the best-matching commit | Walks back through branch history, finds the commit with the most file overlap with working-tree changes, amends its tree, and rebuilds descendants. Working tree is synced to the new HEAD. With `--route`, changes are routed back to the operations that own them (megamerge mode) instead |
| `test` | `<commit> <command...>` | Run a validation command at a commit | Temporarily restores the working tree to the specified commit, runs the command, then restores the original state. Use `--` to separate the command from codetree flags. Returns non-zero if the command fails |
| `reword` | `<commit> -m <message> [--dry-run]` | Rewrite commit message | Changes a commit's message and rebuilds all descendants on the current branch. `--dry-run` previews without executing. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `squash` | `<commit> [--dry-run]` | Squash into parent | Combines a commit with its parent: the target's tree replaces the parent's, messages are combined, and descendants are rebuilt. `--dry-run` previews without executing. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `unsquash` | `<commit>` | Reverse of squash | Splits a squashed commit back into two: a restored parent (with grandparent's tree) and a new commit with the target's tree. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `move` | `<commit> --onto <parent>` | Reparent a commit | Changes a commit's parent to the specified commit. The tree is preserved — only the parent pointer changes. Descendants are rebuilt. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `revert` | `<commit>` | Undo a commit's changes | Creates a new commit on top of HEAD that reverses the target commit's changes via 3-way merge. Does not rewrite history. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `amend-to` | `<commit>` | Amend changes into a specific commit | Applies working-tree changes to the specified commit (not just HEAD). New files are only added if the target is HEAD. Descendants are rebuilt. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `squash-into` | `<into>` | Squash HEAD into a specific ancestor | Squashes the HEAD commit into the specified ancestor commit. HEAD's tree replaces the ancestor's tree, messages are combined. Intermediate descendants are rebuilt. Accepts `HEAD~N` or a hash prefix |
| `fold` | `--from <commit> [--dry-run]` | Fold a range into one | Folds all commits from the specified commit to HEAD into a single commit. HEAD's tree is used, all messages in the range are combined. `--dry-run` previews without executing. Accepts `HEAD~N` or a hash prefix |
| `show` | `<commit>` | Show a commit's diff | Displays the commit message and the unified diff of what changed in that commit vs its parent. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `diff` | `[commit]` | Show working-tree diff | Shows unified diff between the working tree and HEAD (or a specified commit). Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `blame` | `<file>` | Annotate file lines | Shows which commit last modified each line of the file. Output: line number, short commit hash, line content |
| `why` | `<path[:line]>` | Provenance lookup | Traces a file (or 1-based line) to the commit that introduced it, then reports the operation, agent, and prompt behind it from `.codetree/provenance.json`. With a line: blame finds the commit; without: the newest commit that touched the file |
| `filelog` | `<file>` | File commit history | Shows all commits that touched a specific file, newest first. Output: hash, date, message |
| `goto` | `<commit>` | Checkout a commit (detached HEAD) | Sets HEAD to point directly at a commit (detached HEAD). Working tree is restored to that commit's state. Use `switch <branch>` to return to a branch |
| `clean` | — | Remove untracked files | Deletes all files in the working tree that are not tracked in HEAD. Does not remove `.codetree/` |
| `gc` | — | Garbage collect objects | Removes unreachable objects from the object store. Run after history rewrites (rebase, squash, reword) to reclaim space |
| `op-log` | — | Show operation log | Displays the undo/redo operation log with index, timestamp, and operation details. Use `codetree undo <index>` to undo a specific operation |
| `bisect` | `<subcommand>` | Binary search for bugs | Subcommands: `start` (mark HEAD as bad), `good [commit]` (mark a commit as good), `bad [commit]` (mark a commit as bad), `log` (show state), `reset` (end session). Automatically checks out the midpoint commit for testing. State persists in `.codetree/bisect.json` |
| `tag` | `<subcommand>` | Manage tags | Subcommands: `create <name> [commit] [-m <message>]` (create a tag pointing at a commit, default HEAD; `--message` creates an annotated tag with metadata), `list` (list all tags with messages), `delete <name>` (delete a tag and its annotation). Tags are stored in `refs/tags/`, annotations in `refs/tags/<name>.annot` |
| `abandon` | `<commit>` | Remove a commit from history | Removes the target commit and rebuilds descendants onto its parent. Descendant trees are preserved (they already include the abandoned commit's changes). Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `revive` | `<commit>` | Restore an abandoned commit | Creates a new commit on top of HEAD with the abandoned commit's tree and message. Accepts a hash prefix |
| `duplicate` | `<commit>` | Copy a commit onto HEAD | Creates a new commit on top of HEAD with the same tree and message (suffixed with " (duplicated)"). Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `describe` | `<commit> -m <message> [--dry-run]` | Alias for reword | jj-compatible name for `reword`. Same behavior: changes a commit's message and rebuilds descendants |
| `config` | `<subcommand>` | Manage configuration | Subcommands: `get <key>` (read a dotted key like `git.base_branch`), `set <key> <value>` (write a key), `list` (show all config). Operates on `.codetree/config.toml` |
| `file-search` | `<pattern> [--name-only]` | Search file contents | Case-insensitive substring search across all files in HEAD's tree. Returns file path, line number, and matching line content. `--name-only` searches file names only |
| `file-list` | `[commit]` | List files in a commit | Lists all files in the specified commit's tree (default: HEAD). Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `heads` | — | List branch heads | Shows all branch names and their tip commit hashes |
| `next-commit` | — | Navigate to next commit | Checks out the child of HEAD (the commit whose parent is HEAD). Detached HEAD |
| `prev-commit` | — | Navigate to previous commit | Checks out the parent of HEAD. Detached HEAD |
| `restack-graph` | — | Repair commit graph | Walks all branches and checks for missing commits. Reports if the graph is consistent or needs repair |
| `fix` | `-- <command...>` | Run a fix command and amend | Runs the specified command in the working directory, stages all changes, and amends them into HEAD. Use `--` to separate the command from codetree flags |
| `evolog` | `<commit>` | Show evolution history | Shows the predecessor chain of a commit (rewrites from reword/squash/move/rebase). State persists in `.codetree/evolog.json` |
| `interdiff` | `<commit_a> <commit_b>` | Diff between two commits | Shows the unified diff between two arbitrary commits. Accepts `HEAD`, `HEAD~N`, or hash prefixes |
| `restore` | `--from <commit> --to <commit>` | Restore tree contents | Replaces the target commit's tree with the source commit's tree, rebuilding descendants. Accepts `HEAD`, `HEAD~N`, or hash prefixes |
| `hide` | `<commit>` | Hide a commit | Marks a commit as hidden (not shown in smartlog). Commit remains in the object store. State persists in `.codetree/hidden.json` |
| `unhide` | `<commit>` | Unhide a commit | Removes a commit from the hidden list. Accepts `HEAD`, `HEAD~N`, or hash prefixes |
| `log` | `[commit] --limit <N> [--count]` | Linear commit history | Shows hash, date, and first line of message for each commit. `--count` prints only the commit count. `--limit` caps the number of entries |
| `forks` | — | List fork points | Lists commits with multiple children across all branches. Shows commit hash and message |
| `merge-point` | `<commit_a> <commit_b>` | Find common ancestor | Finds the merge point (common ancestor) of two commits. Accepts `HEAD`, `HEAD~N`, or hash prefixes |
| `verify` | `<commit>` | Verify commit integrity | Checks that a commit's tree, parents, and blobs all exist in the object store. Reports any issues found |
| `run` | `--from <commit> -- <command...>` | Run command across commits | Runs the specified command in each commit's working tree, from `--from` to HEAD. Restores original HEAD afterward. Use `--` to separate the command |
| `speculative-merge` | `<branch>` | Check merge readiness | Pre-computes whether merging a branch into HEAD would conflict. Lists conflicting files if any |
| `branch-rename` | `<old_name> <new_name>` | Rename a branch | Renames a branch ref. Fails if the old branch doesn't exist or the new name is taken |
| `branch-advance` | `<name> [commit]` | Advance a branch | Moves a branch ref forward to the target commit (defaults to HEAD). Does not switch the current branch |
| `forget` | `<commit>` | Forget a commit | Abandons a commit AND removes its object from the store. Unlike `abandon`, the commit cannot be revived |
| `show` | `<commit> [--mutation/-t]` | Show a commit's diff | Displays the commit message and diff. `--mutation` also shows the predecessor chain from evolog |
| `save` | `[-m <msg>]... [--validate] [--no-validate]` | Save changes | Multiple `-m` flags combine as `title\n\nbody` (Sapling-style). `--validate` runs validation, `--no-validate` skips it |
| `move` | `<commit> --onto <parent> [--dry-run]` | Reparent a commit | Changes a commit's parent. `--dry-run` previews without executing. Descendants are rebuilt. Accepts `HEAD`, `HEAD~N`, or a hash prefix |
| `ready [branch]` | — | Check merge readiness (read-only) | Reports ahead/behind counts, conflict count, and whether conflicts would auto-resolve from the resolution cache. Supports `--json` for machine-readable output |
| `import` | `--force` | Import from Git | One-way bridge: reads Git history (via `git` CLI subprocess) and recreates commits in CodeTree's object store with original author, message, and timestamp. Use `--force` to reimport |
| `export` | — | Export to Git | One-way bridge: reads CodeTree history and recreates commits in a Git repo (initializing one if needed) with original author, message, and timestamp. Enables PR creation via `gh` |
| `bundle` | `-o <path>` | Create tar.gz archive | Packs `.codetree/` (objects, refs, metadata) into a single file for offline transfer. Excludes transient state (ops_backups, pending_resolution) |
| `unbundle` | `<path>` | Extract tar.gz archive | Restores `.codetree/` from a bundle and syncs the working tree to HEAD. Backs up any existing `.codetree/` first |
| `rebase` | `--dry-run`, `--watch <secs>` | Rebase branch onto parent (topological order) | Rebase all active branches; stacked branches rebase onto their parent (auto-restack). `--dry-run` previews without changes. `--watch <secs>` runs as a daemon, rebasing every N seconds |
| `restack` | — | Rebase broken branches onto parent | Fix broken stacking relationships; rebases branches that fell behind their parent |
| `sync` | — | Pull + rebase | Pulls from the configured remote via `git pull`, then rebases all active branches onto the updated base. Requires a Git repo (run `codetree export` first) |
| `merge [branch]` | `--squash` | Checkout base, merge (or squash), delete branch | Low-level merge (use `finish` instead). Auto-resolves from the resolution cache, then configured merge drivers (`[merge.drivers]`). **First-class conflicts**: if neither can resolve, the merge is *committed* with conflicting files at "our" side and `pending_resolution.json` is written — the branch is not deleted and the operation stays active. Edit the files, then run `resolve` |
| `converge [op]` | `--dry-run` | Merge divergent heads of an operation | Combines divergent commits of one operation (e.g. two agents committing to the same operation) into a single merge commit with two parents, then re-points the operation's branch. Conflicting divergence is reported, never force-merged |
| `resolve` | — | Stage files, amend merge commit | Finalizes a conflicted merge: stages the agent's resolutions, amends the merge commit's tree (keeps parents), caches resolutions for future auto-resolve, deletes the branch, marks the operation merged |
| `smartlog` | `--verbose`, `--position`, `--limit`, `--offset`, `--reverse`, `--exact` | — | Text-based tree view of active operations, stacking, divergence, dependencies, tags, merged, branchless. `--verbose` shows individual commits. `--position` highlights current location. `--limit`/`--offset` paginate for repos with many operations. `--reverse` shows newest first. `--exact` skips rendering HEAD and main branch. Stale ops (7d+) marked |
| `whereami` | — | — | Shows current position in the version tree: current branch, parent, base, divergence, siblings, stacked children |
| `switch <branch>` | — | Update HEAD + working tree | Moves to an active operation branch. Use `switch -` to toggle to last branch |
| `next` | — | Update HEAD + working tree | Switch to the next active operation (wraps around) |
| `prev` | — | Update HEAD + working tree | Switch to the previous active operation (wraps around) |
| `publish [branch]` | — | Export to Git + push + create PR | Exports CodeTree history to Git, pushes the branch to the configured remote, generates a PR title (from operation description) and body (commit log + diff summary), and auto-creates a PR via `gh` CLI if available. Gracefully degrades to printing PR content if `gh` is not installed |
| `watch` | `--debounce` | Stage + commit (triggered by fs events) | Auto-save after debounce period of inactivity |
| `undo [index]` | `--list` | Delete branch ref, checkout base, or reset HEAD | Reverts `start` or `save` by index (last if omitted). Pushes to redo stack |
| `redo [index]` | `--list` | Re-apply undone operation | Pops from redo stack and re-applies. `--list` shows redoable ops |
| `status` | — | Read working tree + index | Shows current branch, changes, active ops, conflicts. Stale ops (7d+) marked |
| `list` | `--tag` (`-t`), `--query` (`-Q`), `--format` (`-F`) | — | Lists all tracked operations with metadata. `--tag X` filters by tag. `--query` supports revset-style filtering: `active`, `merged`, `archived`, `branchless`, `stale`, `tag:<name>`, `merges()`, `branches(pattern)` with `&&` and `||`. `!` alone matches only-child branches; `!<term>` negates any term. `branches(pattern)` supports `*` wildcards. `--format` accepts a template string with placeholders: `{name}`, `{status}`, `{description}`, `{created}`, `{tags}`, `{stale}` |
| `snapshot` | `--ops` | Write anonymous commit | Manually create a working-copy snapshot. No-op if the working tree is clean. `--ops` also backs up operation state (branches.json, ops.json) |
| `snapshots` | — | — | List stored working-copy snapshots (newest last) |
| `restore-snapshot <id>` | `--ops` | Restore working tree | Restore a snapshot's tree to the working tree (does not change HEAD). Run `save` to commit the restored state. `--ops` also restores operation state |
| `checkpoint` (`ckp`) | `-m, --label <text>` | Labeled snapshot | Create a labeled turn-level checkpoint as a rewind target (Claude Code `/rewind` semantics). Recorded even on a clean tree (targets HEAD); **survives `save`** (auto-snapshots do not) |
| `rewind <id>` | `--dry-run` | Restore working tree | Rewind the working tree to a checkpoint/snapshot. HEAD and history are untouched — `save` to commit the restored state or keep editing. `--dry-run` previews which files would change |
| `worktree add/remove/list` | `<branch>` | Create/remove/list linked worktrees | Manages linked worktrees |
| `freeze <path>` | — | Mark path as frozen in frozen.json | No operation can modify a frozen path. Protects proven code |
| `unfreeze <path>` | `--force` | Remove path from frozen.json | Allows modifications again. `--force` skips confirmation |
| `frozen` | — | — | Lists all frozen paths |
| `unlock <path>` | — | Remove lock from locks.json | Manually release a file lock (e.g. if an agent crashed) |
| `locks` | — | — | Lists all active file locks and which operation holds them |
| `evaluate <group>` | — | — | Compares candidate operations in a group (diff stats, status) |
| `promote <group> <op>` | — | Merge winner + withdraw losers | Merges the winning candidate into base, withdraws all others in the group |
| `agents` | — | — | Lists all known agents and their active operations |

## MCP Tools

| Tool | Args | Returns |
|------|------|---------|
| `init_repository` | `force: bool` | `{success, message}` |
| `start_op` | `description, checkout, worktree, branchless, files, depends_on, template, tags, agent_id` | `{success, branch, status, base}` |
| `save_changes` | `message: Option<String>, validate: Option<bool>, no_validate: Option<bool>` | `{success, branch, files, message}` |
| `finish_op` | `branch: Option<String>` | `{success, message}` |
| `withdraw_op` | `branch: String` | `{success, message}` |
| `compare_ops` | — | `{success, message}` |
| `rebase_ops` | — | `{success, message}` |
| `merge_branch` | `branch, squash` | `{success, merged_branch, base_branch, squashed, auto_resolved}` or `{success, conflicts_pending: true, conflict_files, next_step: "resolve_op"}` when conflicts can't be auto-resolved |
| `resolve_op` | — | `{success, message}` — finalizes a conflicted merge after the agent edits the files |
| `undo_op` | `index: Option<usize>, list: Option<bool>` | `{success, message}` |
| `publish_op` | `branch: Option<String>` | `{success, message}` — stub, returns error until the remote protocol lands |
| `get_status` | — | `{current_branch, modified, untracked, staged, active_operations, operations, conflicts}` |
| `list_branches` | — | `{branches, total}` |
| `freeze_path` | `path: String` | `{success, message}` |
| `unfreeze_path` | `path: String, force: Option<bool>` | `{success, message}` |
| `list_frozen` | — | `{success, message}` |
| `unlock_file` | `path: String` | `{success, message}` |
| `list_locks` | — | `{success, message}` |
| `evaluate_candidates` | `group: String` | `{success, message}` |
| `promote_candidate` | `group: String, operation: String` | `{success, message}` |
| `whereami` | — | `{success, current_branch, base_branch, parent_branch, ahead, behind, siblings, children, description, tags, agent_id}` |

## MCP Resources

| URI | Content |
|-----|---------|
| `config://codetree` | Current config (base_branch, branch_prefix, auto_push, remote_name) |
| `status://branches` | Branch counts: total, active, merged, archived |
| `diff://current` | Unified diff of working tree vs HEAD |

## Data Types

### BranchInfo
```
name: String
created_at: u64
updated_at: u64
change_group: { description: String, files: Vec<String> }
status: Active | Merged | Archived
template: Option<String>
worktree: Option<PathBuf>
branchless: bool
depends_on: Vec<String>
last_commit: Option<String>
tags: Vec<String>
parent_branch: Option<String>
```

### VCS Objects
```
Blob:   { content: Vec<u8> }                    -> SHA-1 hash
Tree:   { entries: Vec<(mode, name, hash)> }    -> SHA-1 hash
Commit: { tree: hash, parents: Vec<hash>, author, message, timestamp } -> SHA-1 hash
Ref:    { name -> commit_hash }
HEAD:   { symbolic_ref -> branch_name }
```

### Operation (in ops.json log)
```
Start    { branch: String, timestamp: u64, agent_id: Option<String> }
Save     { branch: String, message: String, timestamp: u64 }
Merge    { branch: String, into: String, timestamp: u64 }
Withdraw { branch: String, timestamp: u64 }

ops: Vec<Operation>          // undo history
redo_stack: Vec<Operation>   // redo history
```

## Error Handling

- All commands return `Result<()>`; errors propagate with context via the custom `Context` trait
- MCP tools catch errors and return `{"success": false, "error": "..."}` JSON
- Merge failures trigger automatic rollback: checkout restored to original branch
- `withdraw` on a non-existent branch returns "Branch 'X' is not tracked"
- `finish` on a non-active branch returns "Branch 'X' is not active"

## Storage

All state lives in `.codetree/`:
- `objects/` — content-addressable object store (blobs, trees, commits)
- `refs/heads/` — branch refs (each file contains a commit hash)
- `HEAD` — symbolic ref to current branch
- `index` — staging area (list of path -> blob_hash entries)
- `config.toml` — user configuration (`[git]`, `[validation]`, `[hooks]`, `[auto]`, `[merge]` sections)
- `branches.json` — operation metadata (descriptions, file lists, status, tags)
- `ops.json` — operation log for undo/redo (ops + redo_stack)
- `resolutions.json` — conflict resolution cache (manual + merge-driver resolutions)
- `provenance.json` — commit provenance sidecar (commit → operation/agent/prompt), queried by `why`
- `pending_resolution.json` — active merge conflict metadata for the `resolve` command
- `locks.json` — file locks (path → operation name)
- `frozen.json` — frozen paths (read-only protection)
- `candidates.json` — candidate groups (group name → operation names)
- `megamerge.json` — active megamerge session (merged commit, operations, base branch)

No `.git/` directory is created or used.

## Protocol Semantics

- **start**: Creates a branch ref pointing at the base branch's current commit. If `--checkout`, updates HEAD + working tree. If `--worktree`, creates a linked worktree. If `--branchless`, only registers a bookmark. If `--files` is specified, those files are **locked** — no other operation can modify them until this operation is finished or withdrawn.
- **save**: Stages files into the index, creates a tree object from the index, creates a commit object with the tree and current HEAD as parent, updates the branch ref. If `--validate` is set (or config `[validation] mode = "required"`), runs the validation command before committing. If validation fails, the commit is aborted. `--no-validate` skips validation even if config requires it. If any staged file is in a **frozen path**, the commit is rejected.
- **finish**: Updates HEAD to base, performs a 3-way merge of the operation branch into base, deletes the branch ref, marks operation as merged. Releases file locks. Atomic — rollback on failure. If the merge conflicts and the resolution cache can't auto-resolve, the merge is committed with first-class conflicts (see below) and `finish` returns without deleting the branch or marking merged; the agent runs `resolve` to finalize.
- **withdraw**: If on the branch, updates HEAD to base first. Then deletes the branch ref. Archives operation in branch manager. Releases file locks.
- **compare**: For each active non-branchless operation, computes diff between base commit and branch tip. Count files changed, insertions, deletions. Cross-reference `change_group.files` to detect conflicts. For candidate groups, shows a side-by-side comparison.

## First-Class Conflicts

CodeTree commits merge conflicts as state instead of aborting (jj-style). When `merge`/`finish` hits a conflict that the resolution cache cannot auto-resolve:

1. A merge commit is created (two parents for a real merge, one for `--squash`) with the conflicting files left at the "our" side of the conflict.
2. The base branch ref advances to this merge commit and the working tree is restored to it.
3. Conflict metadata is written to `.codetree/pending_resolution.json` (`path`, `our_blob`, `their_blob` per file).
4. The source branch is **not** deleted and the operation stays **Active**. No `Merge` operation is pushed to the op log yet.

`status` shows conflicting files with `!` markers and a `codetree resolve` hint. The agent edits the conflicting files in the working tree, then runs `resolve` (CLI) or `resolve_op` (MCP), which:

1. Stages the resolved files (`add_all`).
2. Amends the merge commit's tree with the resolved content — `amend_commit` preserves the commit's parents and message, only swapping the tree.
3. Caches each resolution in `.codetree/resolutions.json` keyed by `(path, our_blob, their_blob) → resolved_blob` so identical future conflicts auto-resolve.
4. Clears `pending_resolution.json`, deletes the source branch, marks the operation merged, and pushes a `Merge` operation to the op log.

The resolution cache is also consulted on every merge: if every conflicting file has a cached resolution, the merge completes automatically with `auto_resolved: true` and no pending state.

### Merge Drivers

Pluggable, syntax-aware conflict resolution (à la [mergiraf](https://mergiraf.org)) without adding a dependency. Configure per-glob commands in `config.toml`:

```toml
[merge.drivers]
"*.json" = "mergiraf merge %base %ours %theirs -o %result"
"*.rs"   = "mergiraf merge %base %ours %theirs -o %result"
```

Resolution order per conflicting file: **resolution cache → merge driver → first-class conflict**. Drivers run per file via `sh -c` with `%base`/`%ours`/`%theirs` (temp inputs) and `%result` (output) substituted as shell-quoted paths. Exit 0 + a written result = resolved; anything else falls back to first-class conflicts — a broken or missing driver never fails the merge.

- **Resolutions compound**: driver output is recorded in the resolution cache, so identical future conflicts auto-resolve without invoking the driver again.
- **JSON duplicate-key guard**: for `.json` files, driver output is scanned for duplicate keys (the way line-based JSON merges silently corrupt data). Duplicate keys → the file stays a first-class conflict.
- `ready` reports a branch as auto-resolvable when every conflict is covered by the cache **or** a configured driver.

### Convergence

Two agents working the *same* operation can diverge: both commit from the same tip, but only one commit stays on the branch ref — the other is orphaned (invisible in `smartlog`, invisible to `finish`, easy to lose). `codetree converge` recovers that work.

- **Detection**: candidate commits per operation = the provenance sidecar's entries for that operation + the operation's branch tip + its last recorded commit. Heads are the candidates that are not ancestors of another candidate; more than one head means divergence.
- **Rewrite artifacts are not divergence**: heads with identical trees (e.g. after `reword`/`squash`, which produce a new commit id with the same content) collapse to the newest.
- **Combination**: divergent heads are merged pairwise into a merge commit with two parents; the operation's branch (or its branchless `last_commit`) is re-pointed at it, and the converged commit is recorded in the provenance sidecar. Nothing is rewritten and no commit is discarded.
- **Conflicting divergence is never force-merged**: the operation is left untouched and the conflicting files are reported for the agent to resolve — the same "conflicts are state, not errors" rule as everywhere else.

### Megamerge

Operations usually finish one at a time, so a conflict *between* two operations is discovered late — at `finish` time, when the first operation is already merged. A megamerge surfaces it early: every active operation is merged into a single working state the agent can work in.

- `codetree megamerge` merges the tips of all active operations (3-way against the common base) into one **multi-parent commit** (one parent per operation), detaches HEAD at it, and restores the working tree to the merged state. Files two operations changed differently are reported as cross-operation conflicts — visible *before* any `finish`.
- `codetree absorb --route` sends the work back: each changed file is diffed against the merged state, and every hunk is attributed to the operation whose version of that file contains the replaced lines. Attributed hunks are committed onto that operation's branch (no checkout needed); unattributable hunks are reported and left alone.
- The megamerge session is recorded in `.codetree/megamerge.json` (commit, operations, base branch). After routing (or `codetree megamerge --abort`) the base branch is restored and the session cleared.

## Auto-Snapshot (Working-Copy Safety Net)

CodeTree automatically snapshots the working copy before commands that could overwrite it (`switch`, `start` with checkout, `rebase`, `merge`, `finish`, `withdraw`, `undo`, `redo`, `resolve`). If the agent crashes before `save`, the work is recoverable.

- **Snapshot creation**: The working tree is walked, all files are hashed and written as blobs, a tree is built, and an anonymous commit (parent = HEAD) is created. No branch ref or HEAD is updated — the commit lives only in the object store. The snapshot is recorded in `.codetree/snapshots.json` with `{id, commit_hash, timestamp, branch, file_count, label}`.
- **Skip if clean**: If the working tree matches HEAD (no modified, untracked, or deleted files), no snapshot is created. The stat cache makes this check fast.
- **No index mutation**: The snapshot is built directly from the working tree — the staging index is never touched.
- **Promotion on save**: When `save` succeeds, all *unlabeled* snapshots are cleared (the real commit supersedes them). Labeled checkpoints (`codetree checkpoint`) survive so `rewind` targets stay valid across turns.
- **Pruning**: At most 20 snapshots are retained; older entries are pruned.
- **Manual control**: `codetree snapshot` creates a snapshot manually; `codetree snapshots` lists them; `codetree restore-snapshot <id>` restores a snapshot's tree to the working tree (without changing HEAD — the agent can then `save` to commit or discard to abort).
- **Turn-level checkpoints**: `codetree checkpoint -m <label>` records a labeled checkpoint even on a clean tree (it targets HEAD's tree directly — content addressing dedupes the objects). `codetree rewind <id>` restores the working tree to a checkpoint without touching HEAD or history; `--dry-run` previews changed files. Unlike harness-level checkpoints (Claude Code `/rewind`), VCS-level checkpoints capture shell-command and subagent edits too.
- **Failure is non-blocking**: If the auto-snapshot fails (e.g., I/O error), the calling command still proceeds — the snapshot is a safety net, not a gate.

## File Locking

When an operation is started with `--files a.rs,b.rs`, those paths are locked in `.codetree/locks.json`. Any `save` that touches a locked file from a different operation is rejected with a lock conflict error. Locks are released on `finish`, `withdraw`, or explicit `unlock`.

Acquisition and release are serialized by an exclusive `locks.json.lock` lockfile: the load → conflict-check → write cycle is atomic, so two agents starting operations concurrently cannot lose each other's locks. A lockfile left by a crashed process is force-broken after 30 seconds of inactivity.

## State-File Integrity

All persistent state under `.codetree/` (refs, `HEAD`, `index`, `*.json`) is written **atomically**: data goes to a hidden staging file (`.name.tmp.<pid>`) and is renamed over the target, so readers only ever see the old or the new contents — a crash mid-write can never truncate a branch ref, the index, or the op log. Ref, tag, and `HEAD` writes are additionally serialized by a `<path>.lock` lockfile. Ref listings ignore staging/lock litter.

`RefManager::set_branch_if_current(name, new_id, expected)` provides compare-and-swap semantics for agents: `expected = Some(id)` applies only if the ref still points at `id`; `expected = None` is create-only. This is the concurrency primitive for optimistic branch updates.

## Code Freezing

Frozen paths are stored in `.codetree/frozen.json` (or config `[frozen] paths = [...]`). Any `save` that modifies a frozen path is rejected. Frozen paths can only be modified by an explicit `codetree unfreeze <path>` command (requires confirmation).

## Solution Candidates

A **candidate group** is a set of operations that solve the same problem. Groups are stored in `.codetree/candidates.json` as `group_name → [operation_names]`. Registering an operation into a group via CLI/MCP is **planned** — groups are currently created by editing `candidates.json` directly. Each agent works on its own operation within the group. `codetree evaluate <group>` runs a comparison across all candidates (diff stats, code changes). `codetree promote <group> <op>` merges the winning candidate into base and withdraws the rest.

## Migration Path

CodeTree has fully migrated from a Git wrapper to a standalone VCS. The migration is complete:

1. **Phase 1** (done): VCS core — object store, refs, commits, trees, blobs, index
2. **Phase 2** (done): Working tree operations — status, add, commit, checkout
3. **Phase 3** (done): Ported `init`, `start`, `save`, `switch`, `status`, `list` to native VCS
4. **Phase 4** (done): Merge (3-way), diff, rebase
5. **Phase 5** (done): Ported `finish`, `withdraw`, `compare`, `rebase`, `restack`, `undo`, `smartlog`, `watch`
6. **Phase 6** (done): Removed `git2` dependency, removed `git.rs`, removed all `git` subprocess calls
7. **Phase 7** (planned): Remote protocol (push/pull/clone) for collaboration

No `git2` dependency, no `git` subprocess, no `.git/` directory. All commands use the native VCS engine.