codetree 0.1.1

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;

/// 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())];
        println!("  #{} | {} | {} files | {} | {}",
            snap.id, short, snap.file_count, snap.branch, format_ts(snap.timestamp));
    }
    println!("\nRestore with: 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(())
}