codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# TODO

## Completed

### Phase 1: Simplify to Elementary Commands (AI-Agent Focus)
- [x] Remove quality assessment module (`quality.rs`) and all references
- [x] Remove human-centric features: colored output, progress bars, interactive prompts
- [x] Reduce CLI to 6 elementary commands: `init`, `start`, `save`, `merge`, `status`, `list`
- [x] Simplify `config.rs`: remove `QualityConfig`, keep only git essentials
- [x] Update `branch.rs`: remove `quality_report`, `readiness_score`, simplify `BranchStatus`
- [x] Rewrite `commands.rs` with new elementary command handlers
- [x] Update `main.rs` CLI parser to match simplified commands

### Phase 2: Auto-Branching for Mini Operations
- [x] `start <description>`: auto-generate unique branch name from timestamp + description slug
- [x] `start`: create branch from base, switch to it, register in branch manager
- [x] `save [message]`: stage all changes, commit to current op branch with optional message
- [x] `merge [branch]`: merge specified op branch (or current) back to base branch
- [x] Ensure branch names are deterministic and unique for AI agents

### Phase 3: Minimal Storage & Offline Operation
- [x] Ensure all codetree state lives in single `.codetree/` folder
- [x] Simplify `branches.json` schema (remove quality fields, tags, notes)
- [x] Verify offline operation: no remote dependencies, no network calls
- [x] Confirm `.codetree/` is the only folder needed for backup/restore

### Phase 4: MCP Alignment
- [x] Reduce MCP tools to match simplified CLI: `start`, `save`, `merge`, `status`, `list`
- [x] Remove quality-related MCP tools and resources
- [x] Ensure MCP output is machine-friendly (not emoji-heavy)

### Phase 5: Tests & Documentation
- [x] Update integration tests to match simplified commands
- [x] Remove quality-related test assertions
- [x] Update `README.md` with new elementary command reference
- [x] Update `Cargo.toml` description to reflect AI-agent VCS purpose

### Phase 6: Base Branch Rename
- [x] Default base branch changed from `master` to `main`

### Audit Fixes (AGENTS.md Step 5)
- [x] Fix syntax error in `mcp_main.rs`: tuple destructuring `tokio::io::stdin(), stdout()`
- [x] Add missing `rmcp::service::ServiceExt` import in `mcp_main.rs`
- [x] Update `examples/simple_usage.rs`: remove references to removed `QualityAssessor` and `quality` config
- [x] Update `README.md`: replace outdated commands, MCP tools, config examples, and architecture
- [x] Update `.codetree/config.toml`: remove obsolete `[monitoring]`, `[quality]`, `[ui]` sections
- [x] Remove emoji from README per machine-friendly output guidelines
- [x] Verify `cargo test` passes (46 unit + 5 integration + 1 doctest)

### Dependency Simplification (AGENTS.md Step 5)
- [x] Remove `regex` — unused in codebase
- [x] Remove `pathdiff` — replaced with `std::path::Path::strip_prefix`
- [x] Remove `dirs` — replaced with `std::env::var("HOME")` fallback
- [x] Remove `uuid` — removed unused `BranchInfo.id` field
- [x] Remove `thiserror` — replaced `CodeTreeError` with manual `std::fmt::Display`
- [x] Remove `chrono` — replaced `DateTime<Utc>` with `u64` Unix timestamps via `std::time::SystemTime`
- [x] Remove `log` + `env_logger` — replaced with internal `debug!`, `info!`, `warn!` macros
- [x] Remove `anyhow` — built custom `Result<T>` type alias, `Context` trait, and `bail!` macro
- [x] Trim `tokio` features from `"full"` to `rt-multi-thread`, `macros`, `sync`, `io-std`, `fs`, `process`
- [x] Clean up unused import warnings
- [x] Verify `cargo update` + `rmcp 1.8.0` compatibility — all tests pass
- [x] Audit: suppress `tool_router` dead_code warning in `mcp.rs`
- [x] Audit: fix lifetime syntax warning in `git.rs` (`Signature` → `Signature<'_>`)
- [x] Verify `cargo test` passes with zero warnings (59 unit + 5 integration + 1 doctest)

### Bug Fixes (Code Review)
- [x] Fix `merge_branch` creating merge commit with HEAD tree instead of actual merged tree — now uses `repo.merge_commits()` + conflict detection
- [x] Fix `checkout_branch` not syncing working tree — now forces checkout so files absent in target branch are removed
- [x] Fix `init_command` failing in non-git directories — now bootstraps git repo before creating `GitManager`
- [x] Fix `save_command` destroying `created_at` via remove/re-register — now uses `update_branch_files()`
- [x] Fix MCP `init_repository` no-op — now delegates to actual `init_command`
- [x] Unify `slugify` between CLI and MCP via shared `utils::slugify()`
- [x] Implement atomic merge with rollback — restores original branch on merge failure
- [x] Add regression tests: `test_merge_branch_independent_files` verifying merged files exist
- [x] Verify `cargo test` passes (64 unit + 5 integration + 1 doctest)

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence)

Research into similar tools (Jujutsu, GitButler, Aider, Sapling, git-branchless) revealed capabilities codetree lacks:

### High Priority
- [x] **Diff preview in `status`** — `status` now lists staged (`+`), modified (`~`), and untracked (`?`) files
- [x] **Operation undo / rollback** — `undo` command reverts `start` (deletes branch, checks out base) and `save` (soft resets last commit). Operation log stored in `.codetree/ops.json`
- [x] **Stacked operations** — `start` automatically creates from current branch if it's a tracked active operation
- [x] **Atomic merge with auto-cleanup** — Rollback to original branch on merge failure; auto-delete on success

### Medium Priority
- [x] **File conflict early warning** — `status` CLI and MCP `get_status` both detect and report when two active operations modify the same files
- [x] **Operation squash** — `merge --squash` combines all feature-branch commits into a single commit on base
- [x] **Auto-generated commit messages** — `save` with no message auto-generates "Save changes to <file1>, <file2>..." from changed files
- [x] **Parallel branches (virtual branches)** — `start --parallel` creates branch without checkout; `switch <branch>` moves between active operations

### Low Priority / Nice to Have
- [x] **Git worktree integration** — `start --worktree` creates branch + linked worktree in `.codetree/worktrees/`; `worktree add/remove/list` commands manage them
- [x] **Operation templates / presets** — `start --template <name>` uses predefined branch prefix and commit message format from config `[templates.<name>]`
- [x] **Branchless workflow mode** — `start --branchless` tracks operation as bookmark without creating a git branch; `merge` marks bookmark done; `undo` removes bookmark
- [x] **MCP resource for diff preview** — `diff://current` resource returns unified diff of working tree changes against HEAD

### Phase 7: Automatic Parallel Task Isolation (Agent-First Workflow)
- [x] **README repositioning** — "Built on Git, not instead of it"; problem statement centers on agent granularity
- [x] **Parallel by default** — `start` no longer checks out by default; `--checkout` flag for old behavior
- [x] **`finish` command** — `finish [branch]` = `merge` + `git branch -d` + mark merged, one-step completion
- [x] **`withdraw` command** — `withdraw <branch>` = targeted revert: deletes branch, switches to base, archives op
- [x] **`compare` command** — `compare` = diff stats across all active branches + file conflict detection in one view
- [x] **`rebase` command** — `rebase` = rebase all active branches onto base; skip up-to-date; abort on conflict
- [x] **MCP tools: finish_op, withdraw_op, compare_ops, rebase_ops** — Agent can finish, withdraw, compare, and rebase via JSON-RPC
- [x] **ASCII → Mermaid diagram** — Workflow illustration showing every CodeTree command mapped to underlying Git operations

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 2)

Research into Jujutsu, GitButler, Aider, Sapling, git-branchless, and stgit revealed capabilities CodeTree lacks:

### High Priority
- [x] **Auto-rebase on base advance** — `codetree rebase` rebases all active parallel branches onto base; skips up-to-date; aborts and reports conflicts.
- [x] **Undo any operation (not just last)** — `codetree undo [index]` with `--list` flag; undo any Start or Save operation by index, not just the last one.
- [x] **Per-file operation assignment** — `start --files a,b,c` pre-declares operation scope; `save` only commits assigned files. Conflict detection works at file granularity.

### Medium Priority
- [x] **Auto-save / filesystem watch** — `codetree watch --debounce 2` watches working tree; auto-saves after N seconds of inactivity. Filters `.git/`, `.codetree/`, `target/`. Long-running CLI command (not exposed as MCP tool).
- [x] **Operation dependency graph** — `start --depends-on branch_a,branch_b` stores dependencies. `finish` blocks until all deps are merged. `compare` shows dependency DAG with status indicators and cycle detection.
- [x] **Export to PR** — `codetree publish [branch]` pushes to remote, generates PR title (from description) and body (commit log + diff summary), auto-creates PR via `gh` CLI if available. Gracefully degrades to printing PR content if `gh` is not installed. *(Now works via export-to-Git then git push + gh pr create.)*
- [x] **Conflict resolution cache** — Store how a merge conflict was resolved so identical conflicts in future operations auto-resolve. `merge` checks `.codetree/resolutions.json` keyed by (path, our_blob, their_blob) -> resolved_blob. New `codetree resolve` command caches manual resolutions after `merge` + conflict fix.

### Low Priority / Nice to Have
- [x] **Branchless mode: auto-absorb** — In branchless mode, `save` tracks the last commit hash in the bookmark. On subsequent saves, if HEAD is still that commit, it amends instead of creating a new one. Prevents commit sprawl on the base branch.
- [x] **Operation tags / grouping** — Tag operations (e.g., "sprint-42", "bugfix-week") and batch-finish or batch-withdraw by tag. `start --tags a,b,c` stores tags; `finish --tag X` / `withdraw --tag X` batch-operates; `list --tag X` filters.
- [x] **Smartlog visualization** — Text-based tree view of active operations and their relationship to base (like `sl` or `git sl`). `codetree smartlog` (alias `sl`) shows stacking, dependencies, divergence stats, tags, merged branches, and branchless bookmarks.
- [x] **Integration test coverage for all commands** — Added 9 end-to-end integration tests covering all new commands. All pass.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 3)

Research into git-branchless, Jujutsu, and Sapling revealed capabilities CodeTree lacks:

### High Priority
- [x] **`codetree next` / `codetree prev`** — Navigate between active operations without typing full branch names. `next` checks out the next active operation (alphabetically); `prev` goes back. Wraps around. Essential for agents managing multiple parallel tasks.
- [x] **Auto-restack after rebase** — When `rebase` runs, stacked branches are rebased onto their updated parents (not just onto base). Uses `get_branch_parent` to detect stacking via merge-base, topologically sorts, and rebases parents before children.

### Medium Priority
- [x] **Commit-level smartlog** — `smartlog --verbose` (or `smartlog -v`) shows individual commits within each operation, including short hash, commit message, and changed files. Helps agents understand what changed in each operation.
- [x] **`codetree restack`** — Standalone command to fix broken stacking relationships after manual rebases or amends. Detects branches whose merge-base no longer matches their parent's tip and rebases them. Uses `parent_branch` metadata for reliable parent detection.
- [x] **Operation age / staleness warning** — `status` and `smartlog` warn when an active operation hasn't been updated in 7+ days. Shows `(stale: Nd)` label next to the operation name.

### Low Priority / Nice to Have
- [x] **Revset-style queries** — `codetree list --query "active && tag:sprint-42"` for powerful filtering. Supports `active`, `merged`, `archived`, `branchless`, `stale`, `tag:<name>` with `&&` (AND) and `||` (OR) combinators.
- [x] **Snapshot / restore** — `codetree snapshot` saves the current state of all operations; `codetree restore <snapshot>` brings them back. Useful for agents that want to experiment and roll back.

### Original Completed (Git-backed era)
- [x] Core Git integration via git2
- [x] MCP server architecture with rmcp
- [x] Branch manager with JSON persistence
- [x] CLI scaffold with clap

---

## VCS Independence — Remove Git Dependency

CodeTree has fully migrated from a Git wrapper to a standalone VCS. All commands use the native VCS engine — no `git2` dependency, no `git` subprocess.

### Phase 1: VCS Core (Done)
- [x] **Object store** — `src/vcs/objects.rs`: Blob, Tree, Commit types with SHA-1 content addressing. Store in `.codetree/objects/`.
- [x] **Refs** — `src/vcs/refs.rs`: Branch refs in `.codetree/refs/heads/`, HEAD symbolic ref.
- [x] **Index** — `src/vcs/index.rs`: Staging area mapping file paths to blob hashes.
- [x] **Repository init** — `src/vcs/repo.rs`: `Repository::init()` creates `.codetree/` with object store, refs, HEAD, config.
- [x] **Unit tests** — Test object serialization, hash computation, store/write/read roundtrip (objects: 8, refs: 6, index: 5, repo: 11 tests).

### Phase 2: Working Tree Operations
- [x] **Status** — Compare working tree against index and HEAD. Report modified, untracked, staged files.
- [x] **Add** — Stage files into index (compute blob hash, write blob to store, update index).
- [x] **Commit** — Write tree from index, create commit object, update branch ref.
- [x] **Checkout** — Update HEAD and restore working tree from a branch ref.

### Phase 3: Port Elementary Commands
- [x] **`init`** — Use `vcs::Repository::init()` instead of `git2::Repository::init()`.
- [x] **`start`** — Create branch ref pointing at base commit. Register in branch manager.
- [x] **`save`** — Stage + commit via native VCS.
- [x] **`switch`** — Checkout via native VCS.
- [x] **`status`** — Native VCS status.
- [x] **`list`** — Already VCS-agnostic (reads branches.json).
- [x] **Integration tests** — All ported commands tested end-to-end with native VCS.

### Phase 4: Merge & Diff
- [x] **3-way merge** — Base/ours/theirs tree merge with conflict detection.
- [x] **Diff** — Tree-to-tree diff (insertions, deletions, file-level).
- [x] **Rebase** — Cherry-pick commits onto new parent.

### Phase 5: Port Advanced Commands
- [x] **`finish`** — Native merge + branch ref deletion.
- [x] **`withdraw`** — Native branch ref deletion + checkout base.
- [x] **`compare`** — Native diff across all active branches.
- [x] **`rebase`** / **`restack`** — Native rebase.
- [x] **`undo`** — Native reset / branch deletion.
- [x] **`smartlog`** — Native commit traversal.
- [x] **`watch`** — Native auto-save.
- [ ] **`publish`** — Push via remote protocol (Phase 7).

### Phase 6: Remove Git Dependency
- [x] Remove `git2` from `Cargo.toml`.
- [x] Remove `src/git.rs` (GitManager).
- [x] Remove all `git` subprocess calls.
- [x] Verify zero Git references in codebase.
- [x] Full test suite passes with native VCS only.

### Phase 7: Remote Protocol
- [ ] **Push/pull/clone** — Network protocol for collaboration between agents and humans.
- [x] **Bundle** — Offline transfer format (pack objects into a single file).
- [x] **GitHub export** — Convert CodeTree repo to Git repo for PR creation.

### Future AI-Native Features
- [x] **Operation state machine** — Draft → Active → Ready → Merged. `codetree ready` checks if an op can merge (no conflicts, up-to-date with base).
- [x] **Auto-commit policy** — Configurable: on-save, on-debounce, on-switch. Default: on-debounce (2s).
- [x] **Auto-rebase daemon** — Background process that keeps active branches rebased onto base. Implemented as `codetree rebase --watch <seconds>`.
- [x] **Snapshot / restore** — `codetree snapshot` saves the current state of all operations; `codetree restore <snapshot>` brings them back.
- [x] **JSON output mode** — `--json` flag on every command for machine-readable output.
- [x] **Git interop** — `codetree import` from a Git repo, `codetree export` to a Git repo. One-way bridge for collaboration.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 4)

Research into Jujutsu, git-branchless, and Sapling revealed capabilities CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **Bug: `list` panics in debug builds** — `list` bound `-q` to both `query` and `quiet`; clap `debug_assert!` aborted at parse time. Fixed: `query` now uses `-Q`, `quiet` keeps `-q`. Regression test in `src/main.rs` `tests::list_parses_without_short_flag_collision`.
- [x] **First-class conflicts** (jj) — Commit conflicts as structured data instead of aborting. Agents can continue working past conflicts and resolve later. `save` would store conflict metadata in the commit, `resolve` would fix it.
- [x] **`codetree split`** (git-branchless, jj) — Split a commit into two interactively. Agents that batch too many changes in one save can split them into logical units. `codetree split --files a,b` creates two commits.
- [x] **Auto-snapshot working copy** (jj) — Every command snapshots the working copy before running. Never lose work even if agent crashes before `save`. Snapshots stored as anonymous commits, promoted on explicit `save`.
- [x] **`codetree dry-run`** (git-branchless) — `rebase --dry-run` and `finish --dry-run` to test operations in memory before committing. Agents can preview results without side effects.
- [x] **`codetree switch -`** (git-branchless) — Quick toggle between current and last-checked-out operation. Reduces friction for agents juggling two ops.

### Medium Priority
- [x] **`codetree absorb`** (Sapling) — Auto-absorb uncommitted changes into the appropriate existing commit based on file overlap. Like `amend` but smarter — figures out which commit to amend.
- [x] **`codetree new`** (jj) — Create an empty commit on top of current for staging specific changes. Useful for agents that want a clean checkpoint before experimenting.
- [x] **`codetree test <commit>`** (git-branchless) — Run a validation command at a specific commit without checking out. Agents can verify any point in history.

### Low Priority / Nice to Have
- [x] **Revset `!` operator** (git-branchless) — Shortcut for "only child" commits in revset queries.
- [x] **Template-based output** (jj, Sapling) — User-customizable output format for `smartlog`, `list`, etc. Using a simple template language.
- [x] **Segmented changelog** (Sapling) — Efficient smartlog rendering for repos with thousands of operations. Implemented as `--limit` and `--offset` pagination flags on `smartlog`.

---

## Product Features (from PRODUCT.md)

### Phase P1: File Locking & Scope Isolation (PRODUCT.md #3) — Done
- [x] **Lock manager** — `src/lock.rs`: `LockManager` persists file locks to `.codetree/locks.json`. Maps `path -> operation_name`.
- [x] **Lock on start** — `start --files a.rs,b.rs` acquires locks. If a file is already locked by another op, `start` is rejected with a lock conflict error.
- [x] **Lock release** — `finish` and `withdraw` release all locks held by the operation.
- [x] **Lock enforcement on save** — `save` checks that all modified files are either unlocked or locked by the current operation. Rejects saves that touch files locked by other ops.
- [x] **`codetree unlock <path>`** — Manually release a lock (e.g., if an agent crashed).
- [x] **`codetree locks`** — List all active file locks and which operation holds them.
- [x] **Integration tests** — Lock acquisition, conflict detection, release on finish/withdraw.

### Phase P2: Code Freezing (PRODUCT.md #6) — Done
- [x] **Frozen paths store** — `.codetree/frozen.json` or config `[frozen] paths = [...]`.
- [x] **`codetree freeze <path>`** — Add a path to the frozen list. Frozen paths cannot be modified by any operation.
- [x] **`codetree unfreeze <path>`** — Remove a path from the frozen list (requires `--force`).
- [x] **Freeze enforcement on save** — `save` rejects commits that modify frozen paths.
- [x] **`codetree frozen`** — List all frozen paths.
- [x] **Integration tests** — Freeze a path, attempt save, verify rejection, unfreeze, verify save succeeds.

### Phase P3: Solution Candidates (PRODUCT.md #5) — Done
- [x] **Candidate groups** — Groups are stored in `.codetree/candidates.json` (group name → operation names); `evaluate` and `promote` operate on them. **Gap:** `start --candidate-group <name>` registration is planned — groups are currently created by editing the file directly. Multiple agents start ops in the same group.
- [x] **`codetree evaluate <group>`** — Compare all candidates in a group: diff stats, file changes, commit count. Output a summary table.
- [x] **`codetree promote <group> <op>`** — Merge the winning candidate into base, withdraw all other candidates in the group.
- [x] **Candidate group storage** — `.codetree/candidates.json` maps group name to list of operation names.
- [x] **Integration tests** — Create candidate group, evaluate, promote, verify losers are withdrawn.

### Phase P4: Pre-Commit Validation (PRODUCT.md #4) — Done
- [x] **Validation config** — `[validation] command = "cargo test"` in config.toml.
- [x] **`save --validate`** — Runs the validation command before committing. If it fails, the commit is aborted.
- [x] **`save --no-validate`** — Skip validation even if config policy requires it.
- [x] **Validation policy** — Config `[validation] mode = "required" | "optional" | "off"`. Default: off.
- [x] **Integration tests** — Configure validation, save with passing test, save with failing test (verify rejection).

### Phase P5: Agent Identity & Multi-Agent Tracking (PRODUCT.md #1) — Done
- [x] **Agent ID** — `--agent <id>` flag on `start`. Stored in `BranchInfo.agent_id`. Defaults to hostname + PID.
- [x] **Agent registry** — `agents` command lists all known agents and their active operations.
- [x] **`codetree agents`** — List all known agents and their active operations.
- [x] **Operation log enrichment** — `ops.json` entries include `agent_id`.
- [x] **Integration tests** — Start ops with different agent IDs, verify tracking.

### Phase P6: Redo (PRODUCT.md #2) — Done
- [x] **`codetree redo [index]`** — Recover from a mistaken `undo`. Re-applies the undone operation.
- [x] **Redo stack** — Track undone operations in `ops.json` with a `redo_stack` field. `redo` pops from the redo stack.
- [x] **`codetree redo --list`** — Show redoable operations.
- [x] **Integration tests** — Undo an operation, redo it, verify state is restored. Undo→Redo→Undo cycle test.

### Phase P7: Orientation Map (PRODUCT.md #7) — Done
- [x] **`codetree whereami`** — Show current position in the version tree: current branch, parent branch, base branch, divergence point, sibling operations, stacked children.
- [x] **Enhance `smartlog`** — Add `--position` flag to highlight the current operation and show position summary.
- [x] **MCP tool `whereami`** — JSON output of current position for agent consumption.
- [x] **Integration tests** — whereami on base, whereami on operation branch, smartlog --position flag.

### Performance: Beat git on the Agent Loop — Done
- [x] **Index stat cache** — Index entries carry `(mtime, size, inode)` fingerprints (`src/vcs/index.rs`). `add_all`/`add_files` skip read+SHA-1 for files unchanged since last staging. Legacy 2-field index format still loads. Same trade-off as git's stat cache.
- [x] **`get_status` fast path** — Files proven clean via the stat cache are not hashed.
- [x] **`restore_working_tree` skip-if-match** — `checkout`/`start`/`switch` no longer rewrite files whose content already matches the target tree (stat cache first, content hash fallback).
- [x] **`write_blob` de-copied** — blob content written without two intermediate clones.
- [x] **Benchmark harness** — `examples/bench_vs_git.rs`: codetree library/MCP-style calls vs git CLI subprocesses; disables local hooks for fair timing.
- [x] **Result** (macOS, 50 files, release): save ~17x, status ~40x, branch ~7x, undo ~11x faster than git CLI.
- [x] **Tests** — Stat-cache re-stage correctness, checkout skip-if-match, legacy index format load.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 5)

Research into Jujutsu v0.25+, git-branchless v0.11, and Sapling revealed capabilities CodeTree still lacks:

### High Priority (Agent-Centric)
- [x] **`codetree reword <commit> -m <message>`** (jj) — Rewrite a commit message without changing content. Agents often need to clean up commit messages before publishing.
- [x] **`codetree squash <commit>`** (jj) — Squash a commit into its parent. Useful for collapsing WIP checkpoints before publish.
- [x] **`codetree sync`** (git-branchless) — Pull from remote + rebase all active branches in one step. Combines `git pull` + `rebase`.

### Medium Priority
- [x] **Revset functions: `merges()`, `branches(pattern)`** (git-branchless) — Extend query language for more powerful filtering.
- [x] **`smartlog --reverse`** (git-branchless) — Reverse display order (newest first).
- [x] **`codetree move --reparent`** (git-branchless) — Move a commit to a new parent explicitly. Implemented as `codetree move <commit> --onto <new_parent>`.

### Low Priority / Nice to Have
- [ ] **Working-copy-as-a-commit** (jj) — The working copy is automatically a commit. Major architectural change.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 6)

Research into Jujutsu v0.25, Sapling, and git-branchless v0.11 revealed capabilities CodeTree still lacks:

### High Priority (Agent-Centric)
- [x] **`codetree revert <commit>`** (jj) — Create a commit that undoes a previous commit's changes. Agents need to safely reverse a commit without rewriting history.
- [x] **`codetree log [commit]`** (Sapling) — Linear commit history view (vs smartlog's tree view). Shows hash, date, message for each commit on the current branch.
- [x] **`codetree goto <commit>`** (Sapling) — Checkout a specific commit (detached HEAD equivalent). Agents may need to inspect an arbitrary commit's state.

### Medium Priority
- [x] **`codetree amend --to <commit>`** (Sapling) — Amend working-tree changes to a specific commit (not just HEAD). More precise than `absorb`.
- [x] **`codetree squash --into <commit>`** (jj) — Squash current changes into a specific ancestor commit, not just the parent.
- [x] **Large file handling** (jj) — Skip files larger than a configurable threshold. Prevents accidental commits of large files. Config: `[git] max_file_size = <bytes>`.

### Low Priority / Nice to Have
- [x] **`codetree fold --from <commit>`** (Sapling) — Fold a range of commits into one. Generalization of `squash`. Implemented as `codetree fold --from <commit>`.
- [ ] **`codetree diffedit <commit>`** (jj) — Interactively edit a commit's diff. Requires TUI.
- [ ] **`codetree histedit`** (Sapling) — Interactive history editing. Requires TUI.
- [x] **`jj unsquash`** — Reverse of squash. Undo a squash operation.
- [x] **`git smartlog --exact`** — Skip rendering HEAD and main branch for cleaner output.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 7)

Research into Jujutsu, git-branchless, and Sapling revealed commit inspection and repository maintenance capabilities CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **`codetree show <commit>`** — Show a commit's diff (what changed in that commit). Agents need to inspect what a specific commit did without checking it out.
- [x] **`codetree blame <file>`** (jj `file annotate`) — Show which commit last modified each line. Essential for agents to understand why code looks the way it does.
- [x] **`codetree filelog <file>`** — Show commit history for a specific file. Agents need to trace a file's evolution.

### Medium Priority
- [x] **`codetree diff [commit]`** — Show diff between working tree and HEAD, or between two commits. Currently `status` only lists file names, not content diffs.
- [x] **`codetree clean`** — Remove untracked files (like `git clean`). Agents may need to clean up after failed experiments.
- [x] **`codetree gc`** — Garbage collect unreachable objects. Keep the object store lean after many rewrites.

### Low Priority / Nice to Have
- [x] **`codetree op log`** — Show the operation log (undo/redo history). Currently `undo --list` exists but a dedicated `op log` would be more discoverable.
- [x] **`codetree bisect`** — Binary search for the commit that introduced a bug. Agents can automate this.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 8)

Research into Jujutsu v0.26, git-branchless v0.11, and Sapling revealed tagging, abandon, and dry-run capabilities CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **`codetree tag <name> <commit>`** — Named pointers to commits (jj tags, git tags). Agents can mark important commits (releases, milestones) for easy reference. Includes `tag list`, `tag delete`.
- [x] **`codetree abandon <commit>`** (jj) — Abandon a commit: remove it from the branch, rebuild descendants onto its parent. Unlike `withdraw` (which removes an entire operation), `abandon` works on individual commits.
- [x] **`codetree move --dry-run`** (git-branchless) — Preview a move without executing. Also add `--dry-run` to `rebase`, `reword`, `squash`, `fold`.

### Medium Priority
- [x] **`codetree revive <commit>`** (jj) — Restore an abandoned/removed commit back onto the branch. Agents can recover from accidental `abandon`.
- [x] **`codetree duplicate <commit>`** (jj) — Create a copy of a commit on top of HEAD. Useful for agents experimenting with variations.
- [x] **`codetree describe <commit>`** (jj) — Alias for `reword` with jj-compatible naming.

### Low Priority / Nice to Have
- [x] **`codetree config <get|set|list>`** (jj) — Manage config from the CLI. Currently config is file-only.
- [x] **`codetree tag --annotate`** (git) — Annotated tags with message and metadata.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 9)

Research into Jujutsu v0.27/v0.37 and git-branchless v0.11 revealed several agent-centric features CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **`codetree file search <pattern>`** (jj `jj file search`) — Search file contents across the repository. Agent-useful for finding where code lives without checking out commits. Returns file paths, line numbers, and matching lines.
- [x] **`codetree next-commit` / `codetree prev-commit`** (git-branchless) — Navigate to the next/previous commit in a stack. Agents can walk through a commit series without knowing exact hashes.
- [x] **`codetree restack-graph`** (git-branchless) — Repair broken commit graphs after rewrites. Rebuilds any commits left dangling by abandon/move/squash operations.

### Medium Priority
- [x] **`codetree fix`** (jj) — Run a formatting/fixing command across commits and amend changes automatically. Agents can auto-format code across a stack.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 10)

Research into Jujutsu v0.37/v0.38 and Sapling revealed several agent-centric features CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **`codetree evolog <commit>`** (jj) — Show the evolution history of a commit: predecessors created by reword/squash/move/rebase. Agents can trace how a commit was rewritten over time.
- [x] **`codetree restore --from <commit> --to <commit>`** (jj) — Restore a commit's tree contents from another commit. Agent-useful for undoing accidental changes without reverting history.
- [x] **`codetree interdiff <commit1> <commit2>`** (jj) — Show the diff between two arbitrary commits (not just HEAD vs working tree). Agent-useful for comparing approaches.

### Medium Priority
- [x] **`codetree log --count`** (jj) — Print the number of commits instead of displaying them. Agent-useful for quick stats.
- [x] **`codetree hide <commit>` / `codetree unhide <commit>`** (Sapling) — Hide/unhide commits without abandoning them. Hidden commits don't appear in smartlog but remain in the object store.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 11)

Research into Jujutsu v0.44, git-branchless v0.11.1, and Sapling revealed several agent-centric features CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **`codetree file search --name-only`** (jj) — Search for file names only (not contents). Agent-useful for finding files by name pattern without reading contents.
- [x] **`codetree forks`** (jj `forks()` revset) — List commits that have multiple children (fork points). Agent-useful for understanding branch structure.
- [x] **`codetree merge-point <a> <b>`** (jj `merge_point()`) — Find the common ancestor where two branches diverged. Agent-useful for understanding branch relationships.

### Medium Priority
- [x] **`codetree verify <commit>`** (jj sign verification) — Verify a commit's integrity (hash, tree, parents). Agent-useful for validating repository consistency.
- [x] **`codetree run <command...>`** (jj `jj run`) — Run a command across each commit in a range. Agent-useful for running tests across a stack.
- [x] **`codetree speculative-merge <branch>`** (git-branchless) — Pre-compute whether a merge would conflict. Agent-useful for checking merge readiness.

## Brainstorming (AGENTS.md Step 6 — Competitive Intelligence Round 12)

Research into Jujutsu v0.39+ and Sapling 0.2.20260811 revealed several agent-centric features CodeTree lacks:

### High Priority (Agent-Centric)
- [x] **`codetree branch rename <old> <new>`** (jj `jj bookmark rename`) — Rename a branch. Agent-useful for reorganizing work without recreating branches.
- [x] **`codetree branch advance <name> [commit]`** (jj `jj bookmark advance`) — Move a branch forward to a target commit (defaults to HEAD). Agent-useful for updating branch pointers without switching.
- [x] **`codetree forget <commit>`** (jj `jj forget`) — Remove a commit from the repo entirely (unlike abandon which preserves it). Agent-useful for cleaning up experimental commits.

### Medium Priority
- [x] **`codetree show --mutation`** (Sapling `sl show -t`) — Show the mutation history of a commit (what it was before amends/rewords). Reuses evolog data.
- [x] **`codetree save -m <title> -m <body>`** (Sapling multi -m) — Multiple -m flags combine into "title\n\nbody" format. Agent-useful for structured commit messages.
- [x] **`codetree file list [commit]`** (jj) — List all files in a commit's tree. Agent-useful for understanding what changed.
- [x] **`codetree heads`** (jj) — List all branch heads (commit tips). Useful for orientation.

## Repository Integrity & Concurrency Hardening (2026-09-14)

Code review scoring identified data-integrity and concurrency gaps that undercut the multi-agent coordination premise. Fixed:

- [x] **Atomic state writes** — `src/atomic.rs`: `write_atomic` = pid-stamped `<path>.lock` lockfile (O_EXCL, stale-break after 30s) + hidden staging sibling (`.name.tmp.<pid>`) + rename. Applied to refs, tags, HEAD, index, locks.json, branches.json, ops.json, resolutions.json, pending_resolution.json, candidates.json, snapshots.json, frozen.json, evolog.json, bisect state, hidden.json, config.toml, tag annotations, `last_branch`, and object writes (temp+rename only). A crash mid-write can no longer truncate any state file.
- [x] **Compare-and-swap ref updates** — `RefManager::set_branch_if_current(name, new_id, expected)`: apply only if the ref still reads `expected` (`None` = create-only). The optimistic-concurrency primitive for agents.
- [x] **Race-free lock RMW** — `LockManager::update_atomically`: load → conflict-check → persist under one `locks.json.lock`. Wired into `start --files` acquire, `finish`/`withdraw` release, and `unlock`. Two agents starting concurrently can no longer lose each other's locks (previously last-writer-wins).
- [x] **Ref-listing hygiene** — `list_branches`/`list_tags` ignore staging/lock litter, so crashed-writer leftovers never appear as branches.
- [x] **Tests** — 10 new unit tests (torn-write under thread contention, lock serialization, stale-lock breaking, CAS semantics, concurrent acquirers, release-vs-acquire race) + 3 integration tests (concurrent disjoint starts both survive, conflict-then-release via atomic path, no litter in ref listings).
- [x] **`VcsManager` god-module split** (2026-09-14) — former 3,898-line `vcs/manager.rs` split by concern into `manager.rs` (core, ~1,160 lines), `merge.rs` (merge base, 3-way merge, cached merges, ready, rebase), `rewrite.rs` (jj-style history surgery), `query.rs` (read-only diff/log/blame/search/gc), `worktree.rs`. Public API unchanged (multiple `impl VcsManager` blocks, `pub(super)` fields/helpers) — zero caller changes, 316 tests green.

### Remaining (follow-up)
- [ ] **`BranchManager` RMW race** — `branches.json` writes are atomic, but the in-memory `load all → &mut self → save all` API still loses concurrent branch registrations at document granularity. Restructure mutation methods to closure-based `update_atomically` calls. Same shape applies to `OperationLog` (ops.json). Low urgency: the atomic file-lock acquisition in `start` is the real coordination point agents contend on.

## Brainstorming (AGENTS.md Step 7 — Competitive Intelligence Round 13: AI-Native VCS Wave, 2026-11-07)

Rounds 1–12 studied jj / git-branchless / Sapling. This round studies the **2025–2026 AI-native source-control wave**: **Oak** (Rust VCS for agents: BLAKE3, lazy mount, branch-per-session, `--json` everywhere), **Supafork** (Git-wire-compatible, versions agent sessions read from harness session stores), **Regent/re_gent** (`rgt blame` traces lines to prompts), **Merget** ("every prompt becomes a commit"), **Cursor Origin** (versioned PRs; acquired Graphite 2025-12), **GitHub stacked PRs + Agent Merge** (GA 2026-10), **Mergiraf** (syntax-aware merge driver), **jj 0.45–0.47** (`converge`, `run`, megamerge), and merge-gate systems (CodeHerder, Harness AI Checks, Codacy Verity, Corridor). Research notes with sources: MEMORY.md §6.

### High Priority (Agent-Centric)
- [x] **Prompt/intent provenance** (Merget, Regent, Supafork) — Record which agent, task, and prompt produced each commit. Sidecar `.codetree/provenance.json` keyed by commit hash (**never** add fields to the hashed commit object — SHA-1 is the Git-compat contract, `hash_object` in `src/vcs/objects.rs`). New `codetree why <file>[:line]` = blame → commit → operation → agent → prompt. `save` gains `--prompt`; MCP `save_changes` accepts it. Answers the #1 question agent output raises: "where did this line come from?" *Done (2026-11-07): `src/provenance.rs` + `src/commands/why.rs` + `save --prompt` + MCP `save_changes` (prompt, returns commit hash) + MCP `why` tool.*
- [x] **Turn-level checkpoints + rewind** (Claude Code `/rewind`, Conductor checkpoints) — Snapshot the working tree at every agent turn (anonymous commits via `snapshot.rs` already exist), tagged with checkpoint ids in `snapshots.json`. `codetree rewind <checkpoint>` restores files without touching history; MCP tools `checkpoint`/`rewind`. VCS-level checkpoints cover what harness checkpoints miss: shell-command edits and subagent edits. *Done (2026-11-07): `SnapshotEntry.label` + `add_labeled`/`clear_unlabeled` (checkpoints survive `save`), `codetree checkpoint [-m label]` (records even clean trees, targeting HEAD), `codetree rewind <id> [--dry-run]`, shared cores `create_checkpoint`/`rewind_working_tree` in `commands/snapshot.rs`, MCP `checkpoint`/`rewind` tools.*
- [x] **Pluggable merge drivers + syntax-aware merge** (Mergiraf, Diversion, GitHub Agent Merge) — Config `[merge] drivers.<glob> = "<cmd> %base %ours %theirs -o %result"`, invoked per conflicting file in `merge_branch_with_cache` (`src/vcs/merge.rs`) before falling back to first-class conflicts. Subprocess pattern per `commands/import.rs`; zero new deps. Also a built-in JSON/YAML duplicate-key guard (line-based merge silently corrupts these — Mergiraf flags them). Big lever: every auto-resolved conflict is a saved agent loop. *Done (2026-11-07): `[merge.drivers]` config + `VcsManager::set_merge_drivers`; resolution order cache → driver → first-class conflict (`resolve_conflicts_via_cache_and_drivers`); driver output cached for future merges; JSON duplicate-key guard on driver output (`json_duplicate_key` scanner); `ready` counts driver-covered conflicts as auto-resolvable; wired in CLI merge/ready + MCP merge_branch.*
- [x] **`codetree converge`** (jj 0.45) — Auto-resolve *divergent* tips: two heads for the same op/agent/task merged with heuristics; non-interactive mode aborts into first-class conflicts when uncertain. Feeds `candidates.rs`: same candidate group + different ops = divergence to reconcile. *Done (2026-11-07): `src/vcs/converge.rs` (heads detection + pairwise merge) + `src/commands/converge.rs`; divergence detected via the provenance sidecar (commit → operation) — recovers work orphaned when two agents commit to the same operation; rewrite artifacts (same tree) collapsed so `reword`/`squash` don't look divergent; conflicting divergence reported, never force-merged; CLI `codetree converge [op] [--dry-run]` + MCP `converge_op`.*
- [x] **Megamerge + hunk-routing absorb** (jj) — `codetree megamerge` creates a working state merging all active ops (multi-parent commit, on no branch); the agent edits across ops; `absorb --route` sends each hunk to the operation that last touched those lines (blame/filelog data already exists). Surfaces cross-operation conflicts *before* finish-time. *Done (2026-11-07): `src/megamerge.rs` (session sidecar + LCS diff utils) + `src/vcs/megamerge.rs` (multi-parent megamerge commit, `commit_files_on` for branch-less commits) + `src/commands/megamerge.rs`; `codetree megamerge [--abort]`, `codetree absorb --route`, MCP `megamerge_op`/`route_op`; hunk attribution = the operation whose file version contains the replaced lines (content match, alignment-free); unattributable hunks are reported, never guessed.*

### Medium Priority
- [ ] **`publish --stack`** (Graphite `gt submit`, `gh-stack`, Origin) — Publish a stack of operations as a chained-PR series (export + branch-per-op + `gh pr create --base <parent-op-branch>`). The restack machinery already exists.
- [ ] **Verification gate pipeline** (CodeHerder, Harness AI Checks, Codacy Verity) — Generalize `[validation]` to an ordered gate list; verdicts recorded in `.codetree/gates.json` with the commit hash they validated (freshness: a new `save` invalidates); risk tier by diff size / frozen-path proximity; `finish` blocked while any required gate is red. Keep deterministic gates separate from any LLM review (Sonar's lesson: an LLM verdict alone must not be a merge gate).
- [ ] **Auto-land fix loop** (GitHub Agent Merge, Gitar) — `finish --fix --retries N`: validation failure → run configured fix command → amend → re-validate; on exhaustion leave the op active with a structured failure report. Never force-merge.
- [ ] **`codetree file edit/delete <commit>`** (jj 0.46) — Modify files in any revision without checking out; rebuild descendants (same machinery as `amend-to`).
- [ ] **`codetree serve` — read-only Git Smart-HTTP** (Oak ships this) — Let humans `git clone` a codetree repo directly; complements `export`/`publish` without building the full push protocol (Phase 7).
- [ ] **`--json` on every command + typed exit codes** (Oak) — Complete the machine-first CLI contract (today only `status`/`list`/`ready`); document an exit-code enum in SPEC.md. Cheap, high-leverage for MCP-less integrations.

### Low Priority / Nice to Have
- [ ] **Hunk-overlap conflict prediction** (Clash; worktree-orchestrator lesson: file isolation ≠ semantic isolation) — Extend `compare`/`speculative-merge` from file-level to line-range overlap: warn when two active ops edit overlapping regions of the same file.
- [ ] **Ship an agent skill** (`gh skill install` pattern) — Publish a SKILL.md (Claude Code / Codex / OpenCode) teaching the start→save→finish lifecycle, scoping with `--files`, and stacked operations.
- [ ] **Agent-scoped undo guard** (jj cross-workspace guard) — `undo`/`redo` refuse to revert operations started by another agent unless `--allow-cross-agent`; the op log already records `agent_id`.
- [ ] **Worktree runtime isolation** (Conductor, intentic) — Per-worktree `workspace.toml`: setup/run scripts and port-range allocation. Worktrees isolate files; ports/databases/env are the real collisions.
- [ ] **Versioned publishes** (Cursor Origin) — Each `publish` bumps a version and includes an interdiff since the previous publish in the PR body (evolog already holds the data).
- [ ] **Large-file chunking exploration** (Oak: BLAKE3 + content-defined chunking) — Study chunked blobs for big files; constraint: keep whole-object SHA-1 as the external ID for Git compat. Exploration only.