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::candidates::CandidateManager;
use crate::vcs::VcsManager;

use super::merge::merge_command;
use super::withdraw_single;

pub async fn agents_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let mut agent_ops: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
    for branch in branch_manager.list_branches() {
        if matches!(branch.status, BranchStatus::Active)
            && let Some(agent_id) = &branch.agent_id
        {
            agent_ops.entry(agent_id.clone())
                .or_default()
                .push(branch.name.clone());
        }
    }

    if agent_ops.is_empty() {
        println!("No agents tracked");
        return Ok(());
    }

    let mut agents: Vec<_> = agent_ops.iter().collect();
    agents.sort_by(|a, b| b.1.len().cmp(&a.1.len()));

    println!("Agents:");
    for (agent_id, ops) in agents {
        println!("  {} ({} active op{})", agent_id, ops.len(), if ops.len() == 1 { "" } else { "s" });
        for op in ops {
            println!("    - {}", op);
        }
    }

    Ok(())
}

pub async fn evaluate_command(group: String) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let candidates_path = current_dir.join(".codetree").join("candidates.json");
    let cand_mgr = CandidateManager::load(candidates_path)?;

    let candidates = cand_mgr.get_group(&group)
        .ok_or_else(|| format!("Candidate group '{}' not found", group))?;

    if candidates.is_empty() {
        println!("Candidate group '{}' is empty", group);
        return Ok(());
    }

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

    println!("Candidate group '{}' ({} operations):", group, candidates.len());
    println!("{:-<60}", "");

    for op_name in candidates {
        let branch_info = branch_manager.get_branch(op_name);
        if let Some(info) = branch_info {
            let diff = git_manager.get_branch_diff(op_name).ok();
            let line_count = diff.map(|d| d.lines().filter(|l| l.starts_with('+') || l.starts_with('-')).count()).unwrap_or(0);

            println!("  {} | {} | {} diff lines | {}",
                op_name,
                info.status.as_str(),
                line_count,
                info.change_group.description
            );
        } else {
            println!("  {} | (not tracked)", op_name);
        }
    }

    Ok(())
}

pub async fn promote_command(group: String, operation: String) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let candidates_path = current_dir.join(".codetree").join("candidates.json");
    let mut cand_mgr = CandidateManager::load(candidates_path)?;

    let candidates = cand_mgr.get_group(&group)
        .ok_or_else(|| format!("Candidate group '{}' not found", group))?
        .clone();

    if !candidates.contains(&operation) {
        bail!("Operation '{}' is not in candidate group '{}'", operation, group);
    }

    println!("Promoting '{}' from group '{}'", operation, group);

    merge_command(Some(operation.clone()), false).await?;

    for op_name in &candidates {
        if op_name != &operation {
            println!("Withdrawing losing candidate: {}", op_name);
            let _ = withdraw_single(op_name).await;
        }
    }

    cand_mgr.delete_group(&group);
    cand_mgr.save()?;

    println!("Promoted '{}' and withdrew {} other candidate(s)", operation, candidates.len() - 1);
    Ok(())
}