codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
use crate::error::{Context, Result};

use crate::snapshot::{SnapshotManager, MAX_SNAPSHOTS};
use crate::vcs::VcsManager;

use super::format_ts;

/// Core checkpoint creation, shared by the CLI command and the MCP tool
/// (TODO Round 13: turn-level checkpoints, Claude Code `/rewind` semantics).
/// Unlike automatic snapshots, checkpoints are recorded even when the tree is
/// clean — a clean checkpoint targets HEAD's tree directly, so every agent
/// turn gets a stable rewind target. Returns (id, commit_hash, branch, file_count).
pub async fn create_checkpoint(
    git_manager: &VcsManager,
    label: Option<String>,
) -> Result<(usize, String, String, usize)> {
    let snapshots_path = git_manager.snapshots_path();
    let mut mgr = SnapshotManager::load(&snapshots_path).await?;

    let (commit_hash, timestamp, branch, file_count) = match git_manager.snapshot_working_tree().await? {
        Some(snap) => (snap.commit_hash, snap.timestamp, snap.branch, snap.file_count),
        None => {
            // Clean tree: no new commit needed — content addressing already
            // dedupes the objects, so the checkpoint simply targets HEAD.
            let head = git_manager.get_head_hash()?;
            let branch = git_manager.get_current_branch().await?;
            let commit = git_manager.repo().read_commit(&head)?;
            let tree = git_manager.repo().read_tree(&commit.tree)?;
            (head, crate::branch::now_ts(), branch, tree.entries.len())
        }
    };

    let id = mgr.add_labeled(commit_hash.clone(), timestamp, branch.clone(), file_count, label);
    mgr.prune(MAX_SNAPSHOTS);
    mgr.save(&snapshots_path).await?;
    Ok((id, commit_hash, branch, file_count))
}

/// Create a labeled turn-level checkpoint. Checkpoints survive `save`
/// (unlike automatic snapshots) so agents can rewind across turns.
pub async fn checkpoint_command(label: Option<String>) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let (id, commit_hash, branch, file_count) = create_checkpoint(&git_manager, label.clone()).await?;

    let short = &commit_hash[..7.min(commit_hash.len())];
    match &label {
        Some(l) => println!("Checkpoint #{} \"{}\" ({} files on '{}', commit {})", id, l, file_count, branch, short),
        None => println!("Checkpoint #{} ({} files on '{}', commit {})", id, file_count, branch, short),
    }
    println!("Rewind with: codetree rewind {}", id);
    Ok(())
}

/// Core rewind, shared by the CLI command and the MCP tool: restore the
/// working tree to a checkpoint/snapshot without touching HEAD or any ref.
/// Returns (commit_hash, label, changed_files); with `dry_run` the working
/// tree is left untouched and `changed_files` is the preview.
pub async fn rewind_working_tree(
    git_manager: &VcsManager,
    id: usize,
    dry_run: bool,
) -> Result<(String, Option<String>, Vec<String>)> {
    let mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;
    let snap = mgr.get(id)
        .ok_or_else(|| format!("Checkpoint/snapshot #{} not found. Run `codetree snapshots` to list available ones.", id))?;
    let commit_hash = snap.commit_hash.clone();
    let label = snap.label.clone();

    // Which files differ between the working tree and the checkpoint's tree?
    let diff = git_manager.diff_working_tree(Some(&commit_hash))?;
    let changed: Vec<String> = diff.lines()
        .filter_map(|l| l.strip_prefix("diff --git a/"))
        .filter_map(|rest| rest.split_once(' ').map(|(p, _)| p.to_string()))
        .collect();

    if !dry_run {
        git_manager.restore_working_tree_pub(&commit_hash)?;
        git_manager.sync_index_to_commit(&commit_hash)?;
    }
    Ok((commit_hash, label, changed))
}

/// Rewind the working tree to a checkpoint. HEAD and history are untouched —
/// the restored state can be saved or discarded. `--dry-run` previews.
pub async fn rewind_command(id: usize, dry_run: bool) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let (commit_hash, label, changed) = rewind_working_tree(&git_manager, id, dry_run).await?;

    let short = &commit_hash[..7.min(commit_hash.len())];
    let label_txt = label.as_deref()
        .map(|l| format!(" \"{}\"", l))
        .unwrap_or_default();

    if dry_run {
        if changed.is_empty() {
            println!("Rewind #{}{} would change nothing (working tree already matches)", id, label_txt);
        } else {
            println!("Rewind #{}{} would change {} file(s):", id, label_txt, changed.len());
            for f in &changed {
                println!("  - {}", f);
            }
        }
        return Ok(());
    }

    if changed.is_empty() {
        println!("Rewound to checkpoint #{}{} (commit {}) — no file changes needed", id, label_txt, short);
    } else {
        println!("Rewound to checkpoint #{}{} (commit {}) — {} file(s) restored:", id, label_txt, short, changed.len());
        for f in &changed {
            println!("  - {}", f);
        }
    }
    println!("HEAD and history untouched. Run `codetree save -m <message>` to commit this state, or edit further.");
    Ok(())
}

/// Manually create a working-copy snapshot. With `--ops`, also backs up
/// operation state (branches.json, ops.json) for full rollback capability.
pub async fn snapshot_command(ops: bool) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;

    let result = git_manager.snapshot_working_tree().await?;
    match result {
        Some(snap) => {
            let mut mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;
            let id = mgr.add(snap.commit_hash.clone(), snap.timestamp, snap.branch.clone(), snap.file_count);
            mgr.prune(MAX_SNAPSHOTS);
            mgr.save(&git_manager.snapshots_path()).await?;
            let short = &snap.commit_hash[..7.min(snap.commit_hash.len())];
            println!("Snapshot #{}: {} files on '{}' (commit {})",
                id, snap.file_count, snap.branch, short);

            if ops {
                backup_ops_state(&current_dir, id)?;
                println!("  Operation state backed up (branches.json, ops.json)");
            }
        }
        None => {
            if ops {
                // Even with a clean tree, back up operation state.
                let timestamp = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0) as usize;
                backup_ops_state(&current_dir, timestamp)?;
                println!("Operation state backed up (id: {})", timestamp);
            } else {
                println!("Working tree clean — no snapshot needed");
            }
        }
    }
    Ok(())
}

/// List all stored snapshots.
pub async fn snapshots_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;

    if mgr.is_empty() {
        println!("No snapshots");
        return Ok(());
    }

    println!("Snapshots ({}):", mgr.len());
    for snap in mgr.list() {
        let short = &snap.commit_hash[..7.min(snap.commit_hash.len())];
        let label = snap.label.as_deref()
            .map(|l| format!(" | \"{}\"", l))
            .unwrap_or_default();
        println!("  #{} | {} | {} files | {} | {}{}",
            snap.id, short, snap.file_count, snap.branch, format_ts(snap.timestamp), label);
    }
    println!("\nRestore with: codetree rewind <id> (or codetree restore-snapshot <id>)");
    Ok(())
}

/// Restore a snapshot's tree to the working tree (does not change HEAD or any ref).
/// With `--ops`, also restores operation state (branches.json, ops.json).
pub async fn restore_snapshot_command(id: usize, ops: bool) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let mgr = SnapshotManager::load(&git_manager.snapshots_path()).await?;

    let snap = mgr.get(id)
        .ok_or_else(|| format!("Snapshot #{} not found. Run `codetree snapshots` to list available snapshots.", id))?;

    let commit_hash = snap.commit_hash.clone();
    let file_count = snap.file_count;
    let branch = snap.branch.clone();

    // Restore the working tree to the snapshot's tree. This does NOT update
    // HEAD or any branch ref — the agent can then `save` to commit the restored
    // state, or discard it.
    git_manager.restore_working_tree_pub(&commit_hash)?;

    // Sync the index to the snapshot's tree so `save` sees a clean state.
    git_manager.sync_index_to_commit(&commit_hash)?;

    println!("Restored snapshot #{} ({} files from '{}', commit {})",
        id, file_count, branch, &commit_hash[..7.min(commit_hash.len())]);

    if ops {
        restore_ops_state(&current_dir, id)?;
        println!("  Operation state restored (branches.json, ops.json)");
    }

    println!("Working tree updated. Run `codetree save -m <message>` to commit, or discard changes to abort.");

    Ok(())
}

/// Back up operation state (branches.json, ops.json) to a snapshot-specific directory.
fn backup_ops_state(repo_dir: &std::path::Path, id: usize) -> Result<()> {
    let backup_dir = repo_dir.join(".codetree").join("ops_backups").join(id.to_string());
    std::fs::create_dir_all(&backup_dir)
        .context("Failed to create ops backup directory")?;

    let codetree_dir = repo_dir.join(".codetree");
    for file in &["branches.json", "ops.json"] {
        let src = codetree_dir.join(file);
        if src.exists() {
            std::fs::copy(&src, backup_dir.join(file))
                .with_context(|| format!("Failed to backup {}", file))?;
        }
    }
    Ok(())
}

/// Restore operation state from a snapshot-specific backup directory.
fn restore_ops_state(repo_dir: &std::path::Path, id: usize) -> Result<()> {
    let backup_dir = repo_dir.join(".codetree").join("ops_backups").join(id.to_string());
    if !backup_dir.exists() {
        bail!("No operation state backup for snapshot #{}. Use `codetree snapshot --ops` to create one.", id);
    }

    let codetree_dir = repo_dir.join(".codetree");
    for file in &["branches.json", "ops.json"] {
        let src = backup_dir.join(file);
        if src.exists() {
            std::fs::copy(&src, codetree_dir.join(file))
                .with_context(|| format!("Failed to restore {}", file))?;
        }
    }
    Ok(())
}