# USE CASES
Concrete scenarios showing how CodeTree solves real problems for AI-agent fleets and their orchestrators.
> For the product definition see [`PRODUCT.md`](PRODUCT.md).
> For the design rationale see [`DESIGN.md`](DESIGN.md).
> For the command reference see [`SPEC.md`](SPEC.md).
---
## UC-1: Parallel Bug Fixes by Multiple Agents
**Actor:** Orchestrator + 3 coding agents
**Scenario:** Three bugs need fixing in the same repository. Each agent should work independently without interfering with the others.
**Steps:**
```bash
# Orchestrator creates three parallel operations
codetree start "Fix login timeout" --files src/auth.rs --agent agent-1
codetree start "Fix CSS overflow" --files src/styles.css --agent agent-2
codetree start "Fix API rate limit" --files src/api.rs --agent agent-3
# Each agent switches to its own operation and works
codetree switch codetree_1700000000_fix_login_timeout
codetree save --message "Increase timeout to 30s"
codetree finish
codetree switch codetree_1700000001_fix_css_overflow
codetree save --message "Add overflow-x: hidden"
codetree finish
codetree switch codetree_1700000002_fix_api_rate_limit
codetree save --message "Bump rate limit to 100 req/min"
codetree finish
```
**Why CodeTree:** Each operation is isolated by file scope. File locking prevents overlap. `finish` merges cleanly because the operations touch different files. No merge conflicts, no coordination overhead.
---
## UC-2: Safe Rollback of a Bad Agent Commit
**Actor:** Coding agent
**Scenario:** An agent commits a change that breaks tests. It needs to roll back the commit, try a different approach, and recover if the rollback was wrong.
**Steps:**
```bash
codetree start "Refactor parser" --files src/parser.rs
codetree save --message "Rewrite tokenizer" # commit 1
codetree save --message "Add error handling" # commit 2 (breaks tests)
# Roll back the last save
codetree undo # soft-resets commit 2
codetree status # verify working tree has changes back
# Agent tries a different approach
codetree save --message "Add error handling v2" # new commit 2
# If undo was a mistake, recover it
codetree redo --list # see redoable operations
codetree redo 0 # re-apply the undone commit
```
**Why CodeTree:** `undo` is a structured operation that soft-resets the last commit, preserving changes in the working tree. The redo stack ensures no work is lost. The operation log (`ops.json`) tracks every structural change.
---
## UC-3: Solution Candidates — Multiple Approaches to One Problem
**Actor:** Orchestrator + 3 coding agents
**Scenario:** The orchestrator wants three different approaches to implementing OAuth, then picks the best one.
**Steps:**
```bash
# Three agents start operations in the same candidate group
codetree start "OAuth: JWT approach" --files src/auth.rs --agent agent-a
codetree start "OAuth: Session approach" --files src/auth.rs --agent agent-b
codetree start "OAuth: OAuth2 provider" --files src/auth.rs --agent agent-c
# Register the three operations in the group 'oauth-impl'
# (CLI/MCP registration is planned — edit .codetree/candidates.json:
# {"oauth-impl": ["codetree_..._jwt", "codetree_..._session", "codetree_..._provider"]})
# Each agent saves and the orchestrator evaluates
codetree evaluate oauth-impl
# Output:
# Candidate group 'oauth-impl' (3 operations):
# ------------------------------------------------------------
# codetree_..._jwt | active | 142 diff lines | OAuth: JWT approach
# codetree_..._session | active | 98 diff lines | OAuth: Session approach
# codetree_..._provider | active | 203 diff lines | OAuth: OAuth2 provider
# Orchestrator picks the winner
codetree promote oauth-impl codetree_..._jwt
# Merges the winner into base, withdraws the other two
```
**Why CodeTree:** Candidate groups let multiple agents solve the same problem in parallel. `evaluate` provides a side-by-side comparison. `promote` merges the winner and cleanly withdraws the losers — no manual branch deletion or merge conflict resolution. (Note: registering operations into a group via CLI/MCP is planned; for now, create the group in `candidates.json`.)
---
## UC-4: Protecting Proven Code from Agent Regressions
**Actor:** Orchestrator
**Scenario:** The `src/core/` directory contains proven, tested code that must not be modified by any agent. An agent attempts to change a file in that directory.
**Steps:**
```bash
# Freeze the core directory
codetree freeze src/core/
codetree frozen
# Frozen paths:
# src/core/
# An agent starts an operation and tries to save a change to a frozen file
codetree start "Optimize startup" --files src/main.rs,src/core/config.rs
codetree save
# Error: Cannot save: file 'src/core/config.rs' is frozen.
# Use `codetree unfreeze 'src/core/config.rs'` to allow changes.
# The agent works around the frozen file
codetree save --message "Optimize startup (main.rs only)" # only touches src/main.rs
# When the freeze is no longer needed
codetree unfreeze src/core/ --force
```
**Why CodeTree:** Frozen paths are enforced at the storage layer — `save` rejects any commit that modifies a frozen path. This prevents AI agents from accidentally breaking proven code, even if they try to edit it.
---
## UC-5: Stacked Operations with Dependencies
**Actor:** Coding agent
**Scenario:** An agent needs to implement a feature in three stages, where each stage depends on the previous one being merged.
**Steps:**
```bash
# Stage 1: Add database schema
codetree start "Add users table" --files src/db/schema.rs
codetree save --message "Create users table schema"
codetree finish # merges to base
# Stage 2: Add API endpoint (depends on stage 1)
codetree start "Add GET /users" --files src/api/users.rs --depends-on codetree_..._add_users_table
codetree save --message "Implement GET /users endpoint"
# Attempt to finish before stage 1 is merged (if stage 1 were still active)
codetree finish
# Error: Cannot finish: 1 unfinished dependency: codetree_..._add_users_table
# After stage 1 is merged, stage 2 can finish
codetree finish # succeeds
# Stage 3: Add frontend (depends on stage 2)
codetree start "Add users page" --files src/pages/users.ts --depends-on codetree_..._add_get_users
codetree save --message "Create users page component"
codetree finish
```
**Why CodeTree:** `--depends-on` creates an explicit dependency graph. `finish` blocks until all dependencies are merged. `compare` shows the dependency DAG with cycle detection. This prevents agents from merging out-of-order.
---
## UC-6: Agent Orientation — Where Am I?
**Actor:** Coding agent
**Scenario:** An agent wakes up and needs to understand its position in the version tree before starting work.
**Steps:**
```bash
codetree whereami
# You are here: codetree_1700000000_fix_login_timeout
# Parent: main
# Base: main
# Divergence from base: +3 / -1
# Description: Fix login timeout
# Tags: [auth, sprint-42]
# Depends on: codetree_..._refactor_auth
# Agent: agent-1
# Sibling operations (same parent):
# - codetree_..._fix_css_overflow (+2 — Fix CSS overflow)
# Stacked operations (children):
# - codetree_..._add_oauth (+1 — Add OAuth)
codetree smartlog --position --verbose
# >>> You are on: codetree_..._fix_login_timeout (+3/-1 from base) <<<
#
# main
# ├── codetree_..._fix_login_timeout (active, +3/-1) *
# │ ├── abc1234 Increase timeout to 30s (src/auth.rs)
# │ └── def5678 Add retry logic (src/auth.rs, src/retry.rs)
# ├── codetree_..._fix_css_overflow (active, +2/-0)
# └── codetree_..._add_oauth (active, +1/-0)
```
**Why CodeTree:** `whereami` gives the agent a complete picture of its position: parent, base, divergence, siblings, children, tags, and dependencies. `smartlog --position --verbose` shows the full tree with individual commits. This is the "orientation map" that agents need to make informed decisions.
---
## UC-7: Batch Operations by Tag
**Actor:** Orchestrator
**Scenario:** An orchestrator tagged 5 operations with `sprint-42`. The sprint is over — merge the finished ones and withdraw the incomplete ones.
**Steps:**
```bash
# Start operations with tags
codetree start "Feature A" --tags sprint-42 --files src/a.rs
codetree start "Feature B" --tags sprint-42 --files src/b.rs
codetree start "Feature C" --tags sprint-42 --files src/c.rs
codetree start "Feature D" --tags sprint-42 --files src/d.rs
codetree start "Feature E" --tags sprint-42 --files src/e.rs
# ... agents work on each ...
# Batch finish all sprint-42 operations
codetree finish --tag sprint-42
# Finishing 5 operation(s) with tag 'sprint-42'
# Or batch withdraw the incomplete ones
codetree withdraw --tag sprint-42
# Withdrawing 5 operation(s) with tag 'sprint-42'
# List operations by tag
codetree list --tag sprint-42
```
**Why CodeTree:** Tags enable batch operations — `finish --tag`, `withdraw --tag`, `list --tag`. This is essential for orchestrators managing sprints or batches of agent work.
---
## UC-8: File Locking with Wait Queue
**Actor:** Two coding agents
**Scenario:** Agent A is working on `src/auth.rs`. Agent B needs to work on the same file and should wait until A finishes.
**Steps:**
```bash
# Agent A claims the file
codetree start "Refactor auth" --files src/auth.rs --agent agent-a
# Lock acquired for src/auth.rs
# Agent B tries to start with the same file
codetree start "Add OAuth to auth" --files src/auth.rs --agent agent-b
# Error: Cannot start: file 'src/auth.rs' is locked by operation 'codetree_..._refactor_auth'
# Agent B waits for the lock
codetree start "Add OAuth to auth" --files src/auth.rs --agent agent-b --wait
# Waiting for file locks: src/auth.rs (held by codetree_..._refactor_auth)
# ... (polls every 2s for up to 5 minutes)
# Agent A finishes, releasing the lock
codetree finish # agent A
# Agent B's start command proceeds automatically
```
**Why CodeTree:** File locking prevents two agents from producing conflicting changes to the same file. The `--wait` flag provides a queue mechanism — agent B blocks until the lock is released, then proceeds automatically.
---
## UC-9: Validation Gate Before Commit
**Actor:** Coding agent
**Scenario:** An agent's code must pass tests before it can be committed. The orchestrator configures validation as required.
**Steps:**
```bash
# Orchestrator configures validation
# .codetree/config.toml:
# [validation]
# mode = "required"
# command = "cargo test"
# Agent saves with validation
codetree save --validate
# Running validation: cargo test
# Validation passed
# Saved changes to branch 'codetree_..._fix_bug'
# Agent's code has a failing test
codetree save
# Running validation: cargo test
# Validation failed (exit code 1). Aborting save.
# --- stdout ---
# ... test failures ...
# Agent skips validation (e.g., WIP commit)
codetree save --no-validate --message "WIP: partial fix"
# Saved changes to branch 'codetree_..._fix_bug'
```
**Why CodeTree:** The validation gate runs tests before allowing a commit. `mode = "required"` enforces it by default. `--validate` opts in when mode is optional. `--no-validate` opts out for WIP commits. This ensures code quality at the storage layer.
---
## UC-10: Branchless Workflow for Lightweight Bookmarks
**Actor:** Coding agent
**Scenario:** An agent wants to track progress on the base branch without creating a separate branch. Saves should auto-absorb into a single commit.
**Steps:**
```bash
codetree start "Quick fix" --branchless --files src/utils.rs
# Created branchless bookmark: codetree_..._quick_fix (on main)
# First save creates a commit on main
codetree save --message "Fix utils helper"
# Saved changes to 'codetree_..._quick_fix' (new commit)
# Second save amends the same commit (auto-absorb)
codetree save --message "Fix utils helper + add test"
# Absorbed changes into 'codetree_..._quick_fix' (amended)
# Finish marks the bookmark as merged (no merge needed — changes are already on main)
codetree finish
# Finished branchless bookmark 'codetree_..._quick_fix'
```
**Why CodeTree:** Branchless mode is for lightweight, single-commit operations on the base branch. Auto-absorb prevents commit sprawl by amending the same commit. This is ideal for small fixes that don't warrant a full branch lifecycle.
---
## UC-11: Conflict Resolution Cache for Repeated Merges
**Actor:** Coding agent
**Scenario:** Two operations modify the same file. The first merge produces a conflict. After manual resolution, the second merge of a similar conflict auto-resolves from the cache.
**Steps:**
```bash
# Operation A modifies src/config.rs
codetree start "Update config format" --files src/config.rs
codetree save --message "Change config to TOML"
codetree finish
# Merge conflict in src/config.rs
# To resolve: fix the conflicted files in the working tree, then run `codetree resolve`
# Agent resolves manually
# (fixes the conflict in src/config.rs)
codetree resolve
# Cached 1 resolution(s)
# Merge committed
# Resolved and merged 'codetree_..._update_config' into 'main'
# Operation B makes a similar change to src/config.rs
codetree start "Add config validation" --files src/config.rs
codetree save --message "Add validation to config"
codetree finish
# Conflicts auto-resolved from cache for 1 file(s)
# Merged 'codetree_..._add_config_validation' into 'main'
```
**Why CodeTree:** The resolution cache (`resolutions.json`) stores how a conflict was resolved, keyed by `(path, our_blob, their_blob) → resolved_blob`. When an identical conflict arises in a future merge, it auto-resolves from the cache. This reduces manual intervention for repeated conflict patterns.
---
## UC-12: MCP-Driven Multi-Agent Orchestration
**Actor:** Orchestrator (MCP client)
**Scenario:** An orchestrator manages a fleet of agents via MCP JSON-RPC. It creates operations, monitors progress, and promotes results — all without shell commands.
**Steps:**
```json
// Create an operation
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"start_op","arguments":{"description":"Fix login bug","files":["src/auth.rs"],"agent_id":"agent-1"}}}
// → {"success":true,"branch":"codetree_..._fix_login_bug","status":"active","base":"main"}
// Save changes
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"save_changes","arguments":{"message":"Fix timeout","validate":true}}}
// → {"success":true,"branch":"codetree_..._fix_login_bug","files":["src/auth.rs"],"message":"Fix timeout"}
// Check status
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_status","arguments":{}}}
// → {"current_branch":"main","active_operations":3,"operations":[...],"conflicts":[]}
// Finish the operation
{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"finish_op","arguments":{"branch":"codetree_..._fix_login_bug"}}}
// → {"success":true,"message":"Operation finished"}
// Check orientation
{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"whereami","arguments":{}}}
// → {"success":true,"current_branch":"main","base_branch":"main","ahead":0,"behind":0,...}
```
**Why CodeTree:** Every CLI command has an MCP twin returning typed JSON. The orchestrator never shells out or parses CLI text. This is the "agent-first API" — CodeTree is designed to be driven by machines, not humans.
---
## UC-13: Splitting a Commit for Cleaner History
**Actor:** Coding agent
**Scenario:** An agent batched too many changes into one save. It needs to split the commit into two logical units.
**Steps:**
```bash
codetree save --message "Add validation and update docs"
# Saved changes to branch 'codetree_..._feature'
# Split the HEAD commit: validation files go in commit 1, docs in commit 2
codetree split --files src/validate.rs --message1 "Add validation" --message2 "Update docs"
# Splitting commit 'abc1234' on branch 'codetree_..._feature'
# First commit: 1 files (src/validate.rs)
# Second commit: 2 files (README.md, docs/guide.md)
# Created first commit: def5678 — "Add validation"
# Created second commit: ghi9012 — "Update docs"
# Split complete on branch 'codetree_..._feature': 1 commit → 2 commits
```
**Why CodeTree:** `split` resets to the parent commit, stages a subset of files, commits, then stages the rest and commits again. This lets agents clean up batched commits into logical units without manual `git reset` + `git add` choreography.
---
## UC-14: Auto-Save with Filesystem Watch
**Actor:** Long-running coding agent
**Scenario:** An agent works continuously over minutes. It wants CodeTree to auto-save after periods of inactivity, so no work is lost if the agent crashes.
**Steps:**
```bash
codetree watch --debounce 3
# Watching /project for changes (debounce: 3s)
# Press Ctrl+C to stop
# Agent edits files...
# [watch] Auto-save #1 completed
# Agent edits more files...
# [watch] Auto-save #2 completed
```
**Why CodeTree:** `watch` uses a filesystem watcher with debounce. After `N` seconds of no file changes, it auto-saves. Filters out `.codetree/`, `.git/`, and `target/` directories. This is a safety net for long-running agents — no work is lost to crashes.
---
## UC-15: Dry-Run Preview Before Destructive Operations
**Actor:** Coding agent or orchestrator
**Scenario:** Before finishing or rebasing, the agent wants to preview what will happen without making changes.
**Steps:**
```bash
# Preview a finish
codetree finish --dry-run
# [dry-run] Would finish: codetree_..._fix_login
# Merge 'codetree_..._fix_login' into 'main'
# Divergence: +3 / -1
# Would delete branch ref and mark as merged
# Preview a rebase
codetree rebase --dry-run
# [dry-run] Would rebase 'codetree_..._fix_login' onto 'main'
# [dry-run] Would rebase 'codetree_..._add_oauth' onto parent 'codetree_..._fix_login'
# Rebase summary: 2 rebased, 0 up-to-date, 0 failed
```
**Why CodeTree:** `--dry-run` previews the operation in memory without side effects. Agents can verify the outcome before committing to a destructive operation. This reduces the risk of irreversible mistakes.