codetree 0.2.0

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

use crate::branch::{BranchManager, BranchStatus};
use crate::vcs::VcsManager;
use crate::ops::{Operation, OperationLog};

use super::{format_ts, load_config, withdraw_single, auto_snapshot};
use super::merge::merge_command;

/// Show the operation log (alias for `undo --list` with richer output).
pub async fn op_log_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let ops_path = current_dir.join(".codetree").join("ops.json");
    let op_log = OperationLog::new(&ops_path).await?;

    if op_log.is_empty() {
        println!("No operations in history");
        return Ok(());
    }

    println!("Operation log ({} entries, newest last):", op_log.len());
    println!("{:>4}  {:<20}  OPERATION", "IDX", "TIMESTAMP");
    println!("{}", "-".repeat(60));
    for (i, op) in op_log.iter() {
        let desc = match op {
            Operation::Start { branch, .. } => {
                format!("start  branch='{}'", branch)
            }
            Operation::Save { branch, message, .. } => {
                format!("save   branch='{}' msg=\"{}\"", branch, message)
            }
            Operation::Merge { branch, into, .. } => {
                format!("merge  branch='{}' into='{}'", branch, into)
            }
            Operation::Withdraw { branch, .. } => {
                format!("withdraw  branch='{}'", branch)
            }
        };
        let ts = match op {
            Operation::Start { timestamp, .. } => *timestamp,
            Operation::Save { timestamp, .. } => *timestamp,
            Operation::Merge { timestamp, .. } => *timestamp,
            Operation::Withdraw { timestamp, .. } => *timestamp,
        };
        println!("{:>4}  {:<20}  {}", i, format_ts(ts), desc);
    }
    println!("\nUse `codetree undo <index>` to undo a specific operation");
    Ok(())
}

pub async fn undo_command(index: Option<usize>, list: bool) -> Result<()> {
    if !list {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let ops_path = current_dir.join(".codetree").join("ops.json");
    let mut op_log = OperationLog::new(&ops_path).await?;

    if list {
        if op_log.is_empty() {
            println!("No operations in history");
            return Ok(());
        }
        println!("Undoable operations:");
        for (i, op) in op_log.iter() {
            let desc = match op {
                Operation::Start { branch, timestamp, .. } => {
                    format!("Start branch '{}' ({})", branch, format_ts(*timestamp))
                }
                Operation::Save { branch, message, timestamp } => {
                    format!("Save on '{}' — \"{}\" ({})", branch, message, format_ts(*timestamp))
                }
                Operation::Merge { branch, into, timestamp } => {
                    format!("Merge '{}' into '{}' ({})", branch, into, format_ts(*timestamp))
                }
                Operation::Withdraw { branch, timestamp } => {
                    format!("Withdraw '{}' ({})", branch, format_ts(*timestamp))
                }
            };
            println!("  [{}] {}", i, desc);
        }
        println!("\nUse `codetree undo <index>` to undo a specific operation");
        return Ok(());
    }

    let git_manager = VcsManager::new(current_dir.clone())?;
    let mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let op = match index {
        Some(i) => {
            let op = op_log.remove(i)
                .with_context(|| format!("No operation at index {}", i))?;
            info!("Undoing operation #{}: {:?}", i, op);
            op
        }
        None => {
            let Some(op) = op_log.pop() else {
                println!("No operations to undo");
                return Ok(());
            };
            info!("Undoing last operation: {:?}", op);
            op
        }
    };

    match &op {
        Operation::Start { branch, .. } => {
            let is_branchless = branch_manager.get_branch(branch)
                .map(|b| b.branchless)
                .unwrap_or(false);
            if is_branchless {
                info!("Undoing start of branchless bookmark '{}'", branch);
                branch_manager.remove_branch(branch).await?;
                println!("Undone: start of branchless bookmark '{}'", branch);
            } else {
                info!("Undoing start of branch '{}'", branch);
                if let Ok(base) = load_config(None).await {
                    let _ = git_manager.checkout_branch(&base.git.base_branch).await;
                }
                let _ = git_manager.delete_branch(branch, true).await;
                branch_manager.remove_branch(branch).await?;
                println!("Undone: start of branch '{}'", branch);
            }
        }
        Operation::Save { branch, .. } => {
            let is_branchless = branch_manager.get_branch(branch)
                .map(|b| b.branchless)
                .unwrap_or(false);
            if is_branchless {
                info!("Undoing save on branchless bookmark '{}'", branch);
                let current = git_manager.get_current_branch().await?;
                git_manager.reset_soft_parent().await
                    .context("Failed to undo commit")?;
                println!("Undone: save on '{}' (changes preserved in working tree)", current);
            } else {
                info!("Undoing save on branch '{}'", branch);
                if git_manager.checkout_branch(branch).await.is_ok() {
                    git_manager.reset_soft_parent().await
                        .context("Failed to undo commit")?;
                } else {
                    println!("Branch '{}' no longer exists; save operation removed from log only", branch);
                }
                println!("Undone: save on branch '{}' (changes preserved in working tree)", branch);
            }
        }
        Operation::Merge { branch, into, .. } => {
            let config = load_config(None).await?;
            let base_branch = config.git.base_branch.clone();
            if branch_manager.get_branch(branch).is_some() {
                branch_manager.update_branch_status(branch, BranchStatus::Active).await?;
            } else {
                let _ = git_manager.create_branch(branch, Some(&base_branch)).await;
                branch_manager.register_branch_full(
                    branch,
                    Vec::new(),
                    "Undone merge".to_string(),
                    Vec::new(),
                    None,
                    Vec::new(),
                    None,
                ).await?;
            }
            println!("Undone: merge of '{}' into '{}' (branch re-activated; base already contains merged content)", branch, into);
        }
        Operation::Withdraw { branch, .. } => {
            if branch_manager.get_branch(branch).is_some() {
                branch_manager.update_branch_status(branch, BranchStatus::Active).await?;
                let config = load_config(None).await?;
                let _ = git_manager.create_branch(branch, Some(&config.git.base_branch)).await;
                println!("Undone: withdraw of '{}' (branch re-activated)", branch);
            } else {
                bail!("Cannot undo withdraw: branch '{}' is no longer tracked", branch);
            }
        }
    }

    op_log.push_redo(op);
    op_log.save(&ops_path).await?;
    Ok(())
}

pub async fn redo_command(index: Option<usize>, list: bool) -> Result<()> {
    if !list {
        auto_snapshot().await;
    }
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let ops_path = current_dir.join(".codetree").join("ops.json");
    let mut op_log = OperationLog::new(&ops_path).await?;

    if list {
        if op_log.is_redo_empty() {
            println!("No redoable operations");
            return Ok(());
        }
        println!("Redoable operations:");
        for (i, op) in op_log.redo_iter() {
            let desc = match op {
                Operation::Start { branch, timestamp, .. } => {
                    format!("Start branch '{}' ({})", branch, format_ts(*timestamp))
                }
                Operation::Save { branch, message, timestamp } => {
                    format!("Save on '{}' — \"{}\" ({})", branch, message, format_ts(*timestamp))
                }
                Operation::Merge { branch, into, timestamp } => {
                    format!("Merge '{}' into '{}' ({})", branch, into, format_ts(*timestamp))
                }
                Operation::Withdraw { branch, timestamp } => {
                    format!("Withdraw '{}' ({})", branch, format_ts(*timestamp))
                }
            };
            println!("  [{}] {}", i, desc);
        }
        println!("\nUse `codetree redo <index>` to redo a specific operation");
        return Ok(());
    }

    let git_manager = VcsManager::new(current_dir.clone())?;
    let mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let op = match index {
        Some(i) => {
            let redo_len = op_log.redo_len();
            if i >= redo_len {
                bail!("No redoable operation at index {}", i);
            }
            op_log.remove_redo(i)
                .with_context(|| format!("No redoable operation at index {}", i))?
        }
        None => {
            let Some(op) = op_log.pop_redo() else {
                println!("No operations to redo");
                return Ok(());
            };
            op
        }
    };

    info!("Redoing operation: {:?}", op);

    match &op {
        Operation::Start { branch, agent_id, .. } => {
            let config = load_config(None).await?;
            let base_branch = config.git.base_branch.clone();
            if branch_manager.get_branch(branch).is_some() {
                bail!("Cannot redo: branch '{}' already exists", branch);
            }
            git_manager.create_branch(branch, Some(&base_branch)).await
                .context("Failed to recreate branch")?;
            branch_manager.register_branch_full(
                branch,
                Vec::new(),
                "Redone operation".to_string(),
                Vec::new(),
                None,
                Vec::new(),
                agent_id.clone(),
            ).await.context("Failed to register redone branch")?;
            println!("Redone: start of branch '{}'", branch);
        }
        Operation::Save { branch, message, .. } => {
            if git_manager.checkout_branch(branch).await.is_ok() {
                git_manager.add_all().await
                    .context("Failed to stage changes for redo")?;
                git_manager.commit(message).await
                    .context("Failed to re-commit for redo")?;
                println!("Redone: save on branch '{}' (re-committed)", branch);
            } else {
                bail!("Cannot redo: branch '{}' no longer exists", branch);
            }
        }
        Operation::Merge { branch, into, .. } => {
            if branch_manager.get_branch(branch).is_none() {
                bail!("Cannot redo: branch '{}' no longer exists", branch);
            }
            branch_manager.update_branch_status(branch, BranchStatus::Active).await?;
            merge_command(Some(branch.clone()), false).await
                .context("Failed to re-merge for redo")?;
            println!("Redone: merge of '{}' into '{}'", branch, into);
        }
        Operation::Withdraw { branch, .. } => {
            if branch_manager.get_branch(branch).is_none() {
                bail!("Cannot redo: branch '{}' no longer tracked", branch);
            }
            withdraw_single(branch).await
                .context("Failed to re-withdraw for redo")?;
            println!("Redone: withdraw of '{}'", branch);
        }
    }

    op_log.push_no_clear(op);
    op_log.save(&ops_path).await?;
    Ok(())
}