codetree 0.1.2

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

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

use super::{load_config, cleanup_after_finish, auto_snapshot};

pub async fn merge_command(branch: Option<String>, squash: bool) -> Result<()> {
    auto_snapshot().await;
    let config = load_config(None).await?;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let mut git_manager = VcsManager::new(current_dir.clone())?;
    git_manager.set_merge_drivers(config.merge.drivers.clone());
    let mut branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let target_branch = match branch {
        Some(b) => b,
        None => git_manager.get_current_branch().await?,
    };

    if target_branch == config.git.base_branch {
        return Err(format!("Cannot merge the base branch '{}' into itself", config.git.base_branch).into());
    }

    if let Some(info) = branch_manager.get_branch(&target_branch) {
        let unmerged: Vec<_> = info.depends_on.iter()
            .filter(|dep| {
                branch_manager.get_branch(dep)
                    .map(|b| !matches!(b.status, BranchStatus::Merged))
                    .unwrap_or(true)
            })
            .cloned()
            .collect();
        if !unmerged.is_empty() {
            return Err(format!(
                "Cannot finish '{}': {} unfinished dependency(ies): {}",
                target_branch, unmerged.len(), unmerged.join(", ")
            ).into());
        }
    }

    let is_branchless = branch_manager.get_branch(&target_branch)
        .map(|b| b.branchless)
        .unwrap_or(false);

    if is_branchless {
        branch_manager.mark_branch_merged(&target_branch).await
            .context("Failed to mark branchless bookmark as merged")?;
        println!("Finished branchless bookmark '{}'", target_branch);
    } else {
        info!("Merging branch '{}' into '{}'", target_branch, config.git.base_branch);

        let original_branch = git_manager.get_current_branch().await
            .context("Failed to get current branch")?;

        git_manager.checkout_branch(&config.git.base_branch).await
            .context("Failed to checkout base branch")?;

        let cache_path = current_dir.join(".codetree").join("resolutions.json");
        let mut cache = ResolutionCache::load(&cache_path).await?;

        let merge_result = if squash {
            git_manager.squash_merge_branch_with_cache(&target_branch, &mut cache).await
        } else {
            git_manager.merge_branch_with_cache(&target_branch, &mut cache).await
        };

        match merge_result {
            Ok(result) => {
                if result.resolved_from_cache {
                    if result.driver_resolved.is_empty() {
                        println!("Conflicts auto-resolved from cache for {} file(s)", result.conflicts.len());
                    } else {
                        println!("Conflicts auto-resolved by merge driver for {} file(s): {}",
                            result.driver_resolved.len(), result.driver_resolved.join(", "));
                        // Driver resolutions are cached — persist so identical
                        // future conflicts auto-resolve without the driver.
                        cache.save(&cache_path).await?;
                    }
                } else if !result.conflicts.is_empty() {
                    // First-class conflicts: the merge is committed with the
                    // conflicting files at "our" side. The agent edits them and
                    // runs `codetree resolve` to finalize. Do NOT delete the
                    // branch or mark it merged yet.
                    let conflict_files: Vec<_> = result.conflicts.iter()
                        .map(|c| c.path.as_str()).collect();
                    println!("Merge committed with {} conflict(s): {}",
                        result.conflicts.len(), conflict_files.join(", "));
                    println!("Edit the conflicting files, then run `codetree resolve` to finish the merge.");
                    return Ok(());
                }
            }
            Err(e) => {
                let _ = git_manager.checkout_branch(&original_branch).await;
                return Err(format!("Failed to merge branch '{}': {}; restored original branch '{}'",
                    target_branch, e, original_branch).into());
            }
        }

        if let Err(e) = git_manager.delete_branch(&target_branch, false).await {
            return Err(format!("Merge succeeded but failed to delete branch '{}': {}",
                target_branch, e).into());
        }

        branch_manager.mark_branch_merged(&target_branch).await
            .context("Failed to mark branch as merged")?;
    }

    cleanup_after_finish(&current_dir, &target_branch, Operation::Merge {
        branch: target_branch.clone(),
        into: config.git.base_branch.clone(),
        timestamp: crate::branch::now_ts(),
    }).await?;

    println!("Merged '{}' into '{}'", target_branch, config.git.base_branch);

    Ok(())
}

/// Check if a branch is ready to merge (read-only). Reports ahead/behind
/// counts, conflicts, and whether conflicts would auto-resolve from cache.
pub async fn ready_command(branch: Option<String>, json: bool) -> Result<()> {
    let config = load_config(None).await?;
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let mut git_manager = VcsManager::new(current_dir.clone())?;
    git_manager.set_merge_drivers(config.merge.drivers.clone());
    let branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let base_branch = config.git.base_branch.clone();

    let branch_was_specified = branch.is_some();
    let target_branch = match branch {
        Some(b) => b,
        None => {
            // Use the current branch if none specified.
            git_manager.get_current_branch().await
                .context("No branch specified and no current branch")?
        }
    };

    // Check if the branch exists and is active.
    let branch_info = match branch_manager.get_branch(&target_branch) {
        Some(info) => info,
        None => {
            if !branch_was_specified {
                bail!("Current branch '{}' is not a tracked operation. Specify a branch name: codetree ready <branch>", target_branch);
            } else {
                bail!("Branch '{}' not found in branch manager", target_branch);
            }
        }
    };

    if branch_info.status != BranchStatus::Active {
        if json {
            let result = serde_json::json!({
                "branch": target_branch,
                "base": base_branch,
                "ready": false,
                "reason": format!("branch is {:?}, not active", branch_info.status),
            });
            println!("{}", serde_json::to_string_pretty(&result)?);
        } else {
            println!("Branch '{}' is {:?}, not active — not ready to merge.",
                target_branch, branch_info.status);
        }
        return Ok(());
    }

    let check = git_manager.check_ready(&target_branch, &base_branch).await?;

    let ready = check.up_to_date && check.auto_resolvable;

    if json {
        let result = serde_json::json!({
            "branch": target_branch,
            "base": base_branch,
            "ready": ready,
            "ahead": check.ahead,
            "behind": check.behind,
            "up_to_date": check.up_to_date,
            "conflicts": check.conflict_count,
            "auto_resolvable": check.auto_resolvable,
            "conflict_files": check.conflict_files,
        });
        println!("{}", serde_json::to_string_pretty(&result)?);
    } else {
        println!("Branch: {} (base: {})", target_branch, base_branch);
        println!("  Ahead: {}, Behind: {}", check.ahead, check.behind);
        if check.up_to_date {
            println!("  Up to date with base: yes");
        } else {
            println!("  Up to date with base: no ({} commit(s) behind)", check.behind);
        }
        if check.conflict_count == 0 {
            println!("  Conflicts: none");
        } else {
            println!("  Conflicts: {} file(s)", check.conflict_count);
            for f in &check.conflict_files {
                println!("    ! {}", f);
            }
            if check.auto_resolvable {
                println!("  All conflicts auto-resolvable from cache: yes");
            } else {
                println!("  All conflicts auto-resolvable from cache: no");
            }
        }
        if ready {
            println!("  → READY to merge");
        } else {
            println!("  → NOT ready");
        }
    }

    Ok(())
}

pub async fn resolve_command() -> Result<()> {
    auto_snapshot().await;
    let config = load_config(None).await?;
    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 pending_path = git_manager.pending_resolution_path();
    let pending = PendingResolution::load(&pending_path).await?
        .ok_or("No pending merge conflict. Run `codetree merge <branch>` first.")?;
    let target_branch = pending.branch.clone();

    // Stage the agent's resolutions from the working tree.
    git_manager.add_all().await?;

    // Amend the merge commit's tree with the resolved content. This keeps the
    // merge commit's parents (two for a real merge, one for squash) and only
    // replaces the tree, finalizing the first-class-conflict resolution.
    git_manager.amend_commit().await?;
    println!("Merge commit updated with resolutions");

    // Cache resolutions so identical conflicts auto-resolve next time.
    let cache_path = current_dir.join(".codetree").join("resolutions.json");
    let mut cache = ResolutionCache::load(&cache_path).await?;
    for conflict in &pending.conflicts {
        match git_manager.get_staged_blob_hash(&conflict.path) {
            Ok(resolved_blob) => {
                cache.set(&conflict.path, &conflict.our_blob, &conflict.their_blob, &resolved_blob);
                info!("Cached resolution for {} ({} -> {})", conflict.path, conflict.our_blob, resolved_blob);
            }
            Err(e) => {
                warn!("Could not get resolved blob for {}: {}", conflict.path, e);
            }
        }
    }
    cache.save(&cache_path).await?;
    println!("Cached {} resolution(s)", pending.conflicts.len());

    if let Err(e) = git_manager.delete_branch(&target_branch, false).await {
        warn!("Failed to delete branch '{}': {}", target_branch, e);
    }

    branch_manager.mark_branch_merged(&target_branch).await
        .context("Failed to mark branch as merged")?;

    PendingResolution::clear(&pending_path).await?;

    let ops_path = current_dir.join(".codetree").join("ops.json");
    let mut op_log = OperationLog::new(&ops_path).await?;
    op_log.push(Operation::Merge {
        branch: target_branch.clone(),
        into: config.git.base_branch.clone(),
        timestamp: crate::branch::now_ts(),
    });
    op_log.save(&ops_path).await?;

    println!("Resolved and merged '{}' into '{}'", target_branch, config.git.base_branch);

    Ok(())
}