codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
//! Megamerge engine: merge every active operation into one working state,
//! and commit routed file changes back onto an operation's branch.
//!
//! The megamerge commit has one parent per merged operation (plus the base
//! commit) — a multi-parent commit that lives on no branch. HEAD is detached
//! at it so the agent can edit across operation boundaries; `codetree
//! absorb --route` then routes the edits back to the operations that own
//! them (see `src/commands/megamerge.rs`).

use crate::error::{Context, Result};
use crate::resolution::ConflictInfo;

use super::objects::{Commit, Tree, TreeEntry};
use super::manager::VcsManager;

impl VcsManager {
    /// Create a megamerge commit merging every operation tip into the base
    /// commit's tree. Returns (commit_hash, conflicts).
    ///
    /// Each operation is merged against the common base with a 3-way merge,
    /// so the merged tree contains every operation's changes. Files two
    /// operations changed differently are reported as conflicts (the merged
    /// tree keeps the first side) — the agent resolves them in the working
    /// copy and routes the result back with `absorb --route`.
    pub fn create_megamerge(
        &self,
        base_commit: &str,
        op_tips: &[(String, String)],
    ) -> Result<(String, Vec<ConflictInfo>)> {
        if op_tips.is_empty() {
            return Err("No active operations to merge".into());
        }

        // Common base for the sibling operation branches.
        let mut base_tree = self.commit_tree(base_commit)?;
        for (_, tip) in op_tips {
            let mb = self.find_merge_base(base_commit, tip)?;
            if !mb.is_empty() {
                base_tree = self.commit_tree(&mb)?;
                break;
            }
        }

        let base_entries = base_tree.entries.clone();
        let mut accumulated = base_entries.clone();
        let mut conflicts: Vec<ConflictInfo> = Vec::new();

        for (_, tip) in op_tips {
            let their_tree = self.commit_tree(tip)?;
            let base = Tree::new(base_entries.clone());
            let ours = Tree::new(accumulated.clone());
            let (merged, file_conflicts) = self.merge_trees(&base, &ours, &their_tree)?;
            accumulated = merged;
            conflicts.extend(file_conflicts);
        }

        let tree = Tree::new(accumulated);
        let tree_id = self.repo.write_tree(&tree)?;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        let mut parents = vec![base_commit.to_string()];
        for (_, tip) in op_tips {
            if !parents.contains(tip) {
                parents.push(tip.clone());
            }
        }

        let commit = Commit::new(
            tree_id,
            parents,
            "CodeTree <agent@codetree>".to_string(),
            format!("Megamerge of {} operation(s)", op_tips.len()),
            timestamp,
        );
        let commit_id = self.repo.write_commit(&commit)?;
        Ok((commit_id, conflicts))
    }

    /// Commit the given file contents on top of `base_commit`, without
    /// touching the working tree or any ref. Returns the new commit hash.
    /// Used to land routed changes on an operation's branch.
    pub fn commit_files_on(
        &self,
        base_commit: &str,
        files: &[(String, Vec<u8>)],
        message: &str,
    ) -> Result<String> {
        let tree = self.commit_tree(base_commit)?;
        let mut entries = tree.entries.clone();

        for (path, content) in files {
            let blob_id = self.repo.write_blob(content)?;
            entries.retain(|e: &TreeEntry| e.name != *path);
            entries.push(TreeEntry { mode: 0o100644, name: path.clone(), id: blob_id });
        }

        let new_tree = Tree::new(entries);
        let tree_id = self.repo.write_tree(&new_tree)?;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let commit = Commit::new(
            tree_id,
            vec![base_commit.to_string()],
            "CodeTree <agent@codetree>".to_string(),
            message.to_string(),
            timestamp,
        );
        Ok(self.repo.write_commit(&commit)?)
    }

    /// Read a file's content at a commit (None when absent).
    pub fn read_file_at(&self, commit: &str, path: &str) -> Result<Option<Vec<u8>>> {
        let tree = self.commit_tree(commit)?;
        match tree.entries.iter().find(|e| e.name == path) {
            Some(entry) => Ok(Some(self.repo.read_blob(&entry.id)?.content)),
            None => Ok(None),
        }
    }

    /// Files changed by a commit (relative to its first parent).
    pub fn files_changed_in_commit(&self, commit: &str) -> Result<Vec<String>> {
        let c = self
            .repo
            .read_commit(&commit.to_string())
            .with_context(|| format!("Commit '{}' not found", commit))?;
        let tree = self.commit_tree(commit)?;
        let parent_tree = match c.parents.first() {
            Some(p) => Some(self.commit_tree(p)?),
            None => None,
        };

        let mut changed = Vec::new();
        for entry in &tree.entries {
            let before = parent_tree
                .as_ref()
                .and_then(|pt| pt.entries.iter().find(|e| e.name == entry.name))
                .map(|e| e.id.clone());
            if before.as_deref() != Some(entry.id.as_str()) {
                changed.push(entry.name.clone());
            }
        }
        if let Some(pt) = &parent_tree {
            for entry in &pt.entries {
                if !tree.entries.iter().any(|e| e.name == entry.name) {
                    changed.push(entry.name.clone());
                }
            }
        }
        changed.sort();
        Ok(changed)
    }

    /// Set HEAD to a detached commit (used to enter the megamerge state).
    pub fn detach_head_at(&self, commit: &str) -> Result<()> {
        self.repo.refs().set_detached_head(commit)
    }
}