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::megamerge::{apply_hunks, diff_hunks, Hunk, MegamergeState};
use crate::provenance::ProvenanceLog;
use crate::vcs::VcsManager;

/// What was routed to one operation.
#[derive(Debug, Clone, serde::Serialize)]
pub struct RoutedChange {
    pub operation: String,
    pub file: String,
    /// Number of hunks routed to this operation for this file.
    pub hunks: usize,
    /// True when the whole file was routed (file shared by several ops).
    pub whole_file: bool,
}

/// Report of a routing pass.
#[derive(Debug, Clone, serde::Serialize)]
pub struct RouteReport {
    pub routed: Vec<RoutedChange>,
    /// Changes that could not be attributed to an operation (file: reason).
    pub unrouted: Vec<String>,
    /// Operations that received changes.
    pub operations: Vec<String>,
}

/// Outcome of creating (or aborting) a megamerge.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MegamergeOutcome {
    /// The megamerge commit (None when aborted).
    pub commit: Option<String>,
    /// Operations merged into the megamerge.
    pub operations: Vec<String>,
    /// Cross-operation conflicts (files two operations changed differently).
    pub conflicts: Vec<String>,
    /// True when the megamerge was aborted.
    pub aborted: bool,
}

/// Core megamerge logic, shared by the CLI command and the MCP tool.
pub async fn megamerge_state(
    git_manager: &VcsManager,
    branch_manager: &mut BranchManager,
    abort: bool,
) -> Result<MegamergeOutcome> {
    let current_dir = git_manager.repo_path().to_path_buf();
    let existing = MegamergeState::load(&current_dir)?;

    if abort {
        let state = existing.ok_or("No megamerge in progress")?;
        git_manager.checkout_branch(&state.base_branch).await
            .context("Failed to restore the base branch")?;
        MegamergeState::clear(&current_dir)?;
        return Ok(MegamergeOutcome {
            commit: None,
            operations: state.operations,
            conflicts: vec![],
            aborted: true,
        });
    }

    if existing.is_some() {
        return Err("A megamerge is already in progress. Finish it with `codetree absorb --route` or abort with `codetree megamerge --abort`.".into());
    }

    let base_branch = git_manager.get_current_branch().await?;
    let base_commit = git_manager.get_head_hash()?;

    // Active operations and their tips.
    let registered: Vec<crate::branch::BranchInfo> =
        branch_manager.list_branches().into_iter().cloned().collect();
    let mut op_tips: Vec<(String, String)> = Vec::new();
    for info in &registered {
        if info.status != BranchStatus::Active || info.name == base_branch {
            continue;
        }
        let tip = if info.branchless {
            info.last_commit.clone()
        } else {
            git_manager.repo().refs().get_branch(&info.name)?
        };
        if let Some(tip) = tip.filter(|t| !t.is_empty()) {
            op_tips.push((info.name.clone(), tip));
        }
    }

    if op_tips.is_empty() {
        return Err("No active operations to merge — start an operation first.".into());
    }

    let (commit, conflicts) = git_manager.create_megamerge(&base_commit, &op_tips)?;

    // Enter the megamerge state: detached HEAD at the merge commit.
    git_manager.detach_head_at(&commit)?;
    git_manager.restore_working_tree_pub(&commit)?;
    git_manager.sync_index_to_commit(&commit)?;

    let state = MegamergeState {
        commit: commit.clone(),
        operations: op_tips.iter().map(|(n, _)| n.clone()).collect(),
        base_branch: base_branch.clone(),
        timestamp: crate::branch::now_ts(),
    };
    state.save(&current_dir)?;

    Ok(MegamergeOutcome {
        commit: Some(commit),
        operations: state.operations,
        conflicts: conflicts.iter().map(|c| c.path.clone()).collect(),
        aborted: false,
    })
}

/// `codetree megamerge` — merge every active operation into one working
/// state so cross-operation conflicts surface before `finish`.
///
/// With `--abort`, the megamerge state is discarded and the base branch is
/// restored.
pub async fn megamerge_command(abort: 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 outcome = megamerge_state(&git_manager, &mut branch_manager, abort).await?;

    if outcome.aborted {
        println!("Megamerge aborted — back on '{}'", git_manager.get_current_branch().await?);
        return Ok(());
    }

    let commit = outcome.commit.as_deref().unwrap_or("");
    println!("Megamerge {}: {} operation(s) merged ({}), {} conflict(s)",
        &commit[..7.min(commit.len())],
        outcome.operations.len(),
        outcome.operations.join(", "),
        outcome.conflicts.len());
    if !outcome.conflicts.is_empty() {
        println!("Cross-operation conflicts: {}", outcome.conflicts.join(", "));
        println!("Resolve them in the working tree, then run `codetree absorb --route` to send the work back.");
    } else {
        println!("Edit across operations, then run `codetree absorb --route` to send the work back.");
    }

    Ok(())
}

/// Route working-tree changes back to the operations that own them.
///
/// Every hunk is attributed to the operation whose version of the file
/// contains the replaced lines — so an edit lands on the operation whose
/// code it modifies. Hunks that cannot be attributed (e.g. edits inside a
/// region that several operations rewrote) are reported and left alone.
pub async fn route_changes(
    git_manager: &VcsManager,
    branch_manager: &mut BranchManager,
) -> Result<RouteReport> {
    let current_dir = git_manager.repo_path().to_path_buf();
    let state = MegamergeState::load(&current_dir)?
        .ok_or("No megamerge in progress — run `codetree megamerge` first")?;

    let provenance = ProvenanceLog::load(&current_dir)?;
    let status = git_manager.get_status().await?;

    let mut changed: Vec<String> = Vec::new();
    changed.extend(status.modified.iter().cloned());
    changed.extend(status.untracked.iter().cloned());
    changed.extend(status.staged.iter().cloned());
    changed.sort();
    changed.dedup();

    // operation → file → (hunks routed, positions in the operation's version)
    let mut routed: Vec<RoutedChange> = Vec::new();
    let mut unrouted: Vec<String> = Vec::new();
    // per-operation routed file contents: operation → file → new bytes
    let mut op_files: std::collections::HashMap<String, std::collections::HashMap<String, Vec<u8>>> =
        std::collections::HashMap::new();

    for path in &changed {
        let mega_lines: Vec<String> = match git_manager.read_file_at(&state.commit, path)? {
            Some(content) => String::from_utf8_lossy(&content)
                .lines()
                .map(|l| l.to_string())
                .collect(),
            None => Vec::new(),
        };
        let disk_content = std::fs::read(current_dir.join(path))?;
        let new_lines: Vec<String> = String::from_utf8_lossy(&disk_content)
            .lines()
            .map(|l| l.to_string())
            .collect();

        let hunks = diff_hunks(&mega_lines, &new_lines);
        if hunks.is_empty() {
            continue;
        }

        // Which operation owns which lines: for every operation, the content
        // of its latest version of this file.
        let mut versions: Vec<(String, Vec<String>)> = Vec::new();
        for op in &state.operations {
            if let Some(version) = latest_version_for_op(git_manager, &provenance, op, path)? {
                versions.push((op.clone(), version));
            }
        }

        let mut file_hunks: Vec<(String, Hunk)> = Vec::new();
        for hunk in &hunks {
            let replaced: Vec<String> = mega_lines
                .get(hunk.start.saturating_sub(1)..hunk.end.saturating_sub(1))
                .map(|s| s.to_vec())
                .unwrap_or_default();

            // Owner: the operation whose file version contains the replaced
            // lines contiguously.
            let mut owner: Option<(String, usize)> = None;
            for (op, version) in &versions {
                if let Some(pos) = find_contiguous(version, &replaced) {
                    owner = Some((op.clone(), pos));
                    break;
                }
            }

            match owner {
                Some((op, pos)) => {
                    // Re-base the hunk onto the operation's own coordinates.
                    let mut rebased = hunk.clone();
                    rebased.start = pos + 1;
                    rebased.end = pos + replaced.len() + 1;
                    file_hunks.push((op.clone(), rebased));
                }
                None => {
                    let reason = if replaced.is_empty() {
                        "new file has no owning operation"
                    } else {
                        "no operation owns the edited lines"
                    };
                    unrouted.push(format!("{}: {}", path, reason));
                }
            }
        }

        // Group by operation and commit onto each operation's branch.
        let mut by_op: std::collections::HashMap<String, Vec<Hunk>> = std::collections::HashMap::new();
        for (op, hunk) in file_hunks {
            by_op.entry(op).or_default().push(hunk);
        }

        for (op, op_hunks) in by_op {
            // The operation's current file content (from its branch tip).
            let tip = operation_tip(git_manager, branch_manager, &op)?;
            let base_lines: Vec<String> = match git_manager.read_file_at(&tip, path)? {
                Some(content) => String::from_utf8_lossy(&content)
                    .lines()
                    .map(|l| l.to_string())
                    .collect(),
                None => Vec::new(),
            };

            // Apply the hunks (positions are in the operation's coordinates;
            // apply back-to-front so earlier positions stay valid).
            let mut sorted = op_hunks.clone();
            sorted.sort_by(|a, b| b.start.cmp(&a.start));
            let mut content_lines = base_lines.clone();
            for hunk in &sorted {
                content_lines = apply_hunks(&content_lines, std::slice::from_ref(hunk));
            }
            let mut text = content_lines.join("\n");
            if !text.is_empty() {
                text.push('\n');
            }

            op_files
                .entry(op.clone())
                .or_default()
                .insert(path.clone(), text.into_bytes());
            routed.push(RoutedChange {
                operation: op.clone(),
                file: path.clone(),
                hunks: op_hunks.len(),
                whole_file: versions.len() > 1,
            });
        }
    }

    // Land the routed files on each operation's branch.
    let mut touched_ops: Vec<String> = Vec::new();
    for (op, files) in &op_files {
        let tip = operation_tip(git_manager, branch_manager, op)?;
        let file_list: Vec<(String, Vec<u8>)> = files
            .iter()
            .map(|(path, content)| (path.clone(), content.clone()))
            .collect();
        let message = format!("Route megamerge changes ({} file(s))", file_list.len());
        let new_commit = git_manager.commit_files_on(&tip, &file_list, &message)?;
        git_manager.set_branch_tip(op, &new_commit)?;

        // Keep provenance in sync so the routed commit stays attributable.
        let mut provenance = ProvenanceLog::load(&current_dir)?;
        provenance.record(&new_commit, op, None, Some("routed from megamerge".to_string()));
        provenance.save(&current_dir)?;

        touched_ops.push(op.clone());
    }

    // Leave the megamerge state: back to the base branch, state cleared.
    git_manager.checkout_branch(&state.base_branch).await
        .context("Failed to restore the base branch")?;
    MegamergeState::clear(&current_dir)?;

    Ok(RouteReport {
        routed,
        unrouted,
        operations: touched_ops,
    })
}

/// Latest version of a file produced by an operation (None if untouched).
fn latest_version_for_op(
    git_manager: &VcsManager,
    provenance: &ProvenanceLog,
    operation: &str,
    path: &str,
) -> Result<Option<Vec<String>>> {
    let mut latest: Option<String> = None;
    for entry in &provenance.entries {
        if entry.operation != operation {
            continue;
        }
        let changed = git_manager.files_changed_in_commit(&entry.commit)?;
        if changed.iter().any(|f| f == path) {
            latest = Some(entry.commit.clone());
        }
    }
    let commit = match latest {
        Some(c) => c,
        None => return Ok(None),
    };
    Ok(match git_manager.read_file_at(&commit, path)? {
        Some(content) => Some(
            String::from_utf8_lossy(&content)
                .lines()
                .map(|l| l.to_string())
                .collect(),
        ),
        None => None,
    })
}

/// Find `needle` inside `haystack` as a contiguous line sequence.
fn find_contiguous(haystack: &[String], needle: &[String]) -> Option<usize> {
    if needle.is_empty() {
        return Some(0);
    }
    if needle.len() > haystack.len() {
        return None;
    }
    (0..=haystack.len() - needle.len()).find(|&i| &haystack[i..i + needle.len()] == needle)
}

/// Tip commit of an operation (branch ref, or the branchless bookmark's
/// last commit).
fn operation_tip(
    git_manager: &VcsManager,
    branch_manager: &BranchManager,
    operation: &str,
) -> Result<String> {
    if let Some(tip) = git_manager.repo().refs().get_branch(operation)? {
        if !tip.is_empty() {
            return Ok(tip);
        }
    }
    let info = branch_manager
        .get_branch(operation)
        .ok_or_else(|| format!("Operation '{}' not found", operation))?;
    info.last_commit
        .clone()
        .ok_or_else(|| format!("Operation '{}' has no commits yet", operation).into())
}