codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
use crate::error::{Context, Result};
use crate::branch::BranchManager;
use crate::provenance::ProvenanceLog;
use crate::vcs::VcsManager;

/// Convergence result for a single operation.
#[derive(Debug, Clone, serde::Serialize)]
pub struct OperationConvergence {
    pub operation: String,
    /// Divergent head commits (empty when the operation is already linear).
    pub heads: Vec<String>,
    /// `converged` | `conflict` | `linear` | `divergent` (dry-run only)
    pub status: String,
    /// The converged commit (when status == `converged`).
    pub commit: Option<String>,
    /// Conflicting file paths (when status == `conflict`).
    pub conflicts: Vec<String>,
}

/// Report covering every operation considered.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ConvergeReport {
    pub operations: Vec<OperationConvergence>,
    pub dry_run: bool,
}

/// Find divergent operations and converge them (jj-style `jj converge`).
///
/// Divergence is detected from the provenance sidecar: every commit records
/// the operation that produced it, so commits of one operation that are not
/// ancestors of each other are divergent heads — typically two agents
/// committing to the same operation, where only one commit stays on the
/// branch ref.
///
/// Shared by the CLI command and the MCP tool.
pub async fn converge_operations(
    git_manager: &VcsManager,
    branch_manager: &mut BranchManager,
    operation: Option<String>,
    dry_run: bool,
) -> Result<ConvergeReport> {
    let provenance = ProvenanceLog::load(git_manager.repo_path())?;

    // Group commits by the operation that produced them.
    let mut by_operation: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();
    for entry in &provenance.entries {
        by_operation
            .entry(entry.operation.clone())
            .or_default()
            .push(entry.commit.clone());
    }

    // Registered operations contribute their branch tip / last commit too.
    // `list_branches` returns borrowed entries — clone before mutating.
    let registered: Vec<crate::branch::BranchInfo> =
        branch_manager.list_branches().into_iter().cloned().collect();
    for info in &registered {
        if let Some(op) = &operation {
            if &info.name != op {
                continue;
            }
        }
        if let Some(tip) = git_manager.repo().refs().get_branch(&info.name)? {
            if !tip.is_empty() {
                by_operation
                    .entry(info.name.clone())
                    .or_default()
                    .push(tip);
            }
        }
        if let Some(last) = &info.last_commit {
            by_operation
                .entry(info.name.clone())
                .or_default()
                .push(last.clone());
        }
    }

    let mut operations: Vec<OperationConvergence> = Vec::new();

    let mut names: Vec<String> = by_operation.keys().cloned().collect();
    names.sort();

    for name in names {
        if let Some(op) = &operation {
            if &name != op {
                continue;
            }
        }
        let commits = &by_operation[&name];
        let mut heads = git_manager.commit_heads(commits)?;
        // Collapse rewrite artifacts (same tree) before judging divergence.
        heads = git_manager.dedupe_heads_by_tree(&heads)?;

        if heads.len() < 2 {
            continue; // already linear — nothing to converge
        }

        if dry_run {
            operations.push(OperationConvergence {
                operation: name.clone(),
                heads,
                status: "divergent".to_string(),
                commit: None,
                conflicts: vec![],
            });
            continue;
        }

        let outcome = git_manager.converge_heads(&heads)?;

        if !outcome.conflicts.is_empty() {
            operations.push(OperationConvergence {
                operation: name.clone(),
                heads,
                status: "conflict".to_string(),
                commit: None,
                conflicts: outcome.conflicts.iter().map(|c| c.path.clone()).collect(),
            });
            continue;
        }

        let new_commit = match outcome.commit {
            Some(c) => c,
            None => continue,
        };

        // Re-point the operation at the converged commit.
        let is_branch = git_manager.repo().refs().get_branch(&name)?.is_some();
        if is_branch {
            git_manager.set_branch_tip(&name, &new_commit)?;
        }
        if let Some(info) = registered.iter().find(|i| &i.name == &name) {
            if info.branchless {
                branch_manager.set_branch_last_commit(&name, &new_commit).await?;
            }
        }

        // If the working tree sits on this operation, bring it along.
        let current = git_manager.get_current_branch().await?;
        if current == name {
            git_manager.restore_working_tree_pub(&new_commit)?;
            git_manager.sync_index_to_commit(&new_commit)?;
        }

        // Record the converged commit so future convergence sees it.
        let agent_id = registered
            .iter()
            .find(|i| &i.name == &name)
            .and_then(|i| i.agent_id.clone());
        let mut provenance = ProvenanceLog::load(git_manager.repo_path())?;
        provenance.record(&new_commit, &name, agent_id, None);
        provenance.save(git_manager.repo_path())?;

        operations.push(OperationConvergence {
            operation: name.clone(),
            heads,
            status: "converged".to_string(),
            commit: Some(new_commit),
            conflicts: vec![],
        });
    }

    Ok(ConvergeReport { operations, dry_run })
}

/// `codetree converge [op]` — combine divergent commits of an operation.
pub async fn converge_command(operation: Option<String>, 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 mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let report = converge_operations(&git_manager, &mut branch_manager, operation.clone(), dry_run).await?;

    if report.operations.is_empty() {
        match &operation {
            Some(op) => println!("No divergent commits for operation '{}' — already converged", op),
            None => println!("No divergent commits found — all operations are linear"),
        }
        return Ok(());
    }

    for result in &report.operations {
        let heads: Vec<String> = result.heads.iter().map(|h| h[..7.min(h.len())].to_string()).collect();
        match result.status.as_str() {
            "converged" => {
                let commit = result.commit.as_deref().unwrap_or("");
                println!("Converged operation '{}': {} head(s) [{}] → {}",
                    result.operation, result.heads.len(), heads.join(", "), &commit[..7.min(commit.len())]);
            }
            "conflict" => {
                println!("Operation '{}' has {} divergent head(s) [{}] that conflict on: {}",
                    result.operation, result.heads.len(), heads.join(", "), result.conflicts.join(", "));
                println!("  Resolve the conflicting files manually, then run `codetree converge` again.");
            }
            _ => {
                println!("Operation '{}' has {} divergent head(s): [{}]",
                    result.operation, result.heads.len(), heads.join(", "));
                if dry_run {
                    println!("  (dry run — no changes made)");
                }
            }
        }
    }

    Ok(())
}