codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
//! Commit-combining rewrites (squash, fold) on VcsManager.

//! History surgery (jj-style): amend, reword, squash, move, abandon, fold,
//! revert, absorb, and other commit-rewriting operations on VcsManager.

use crate::error::{Context, Result};
use super::objects::Commit;
use super::manager::VcsManager;

impl VcsManager {
    /// Squash a commit into its parent. The commit's tree is merged into
    /// the parent's tree (3-way merge with the commit as "theirs" and parent
    /// as "ours"), and the resulting commit replaces the parent. All
    /// descendants are rebuilt. Returns the new HEAD hash.
    pub async fn squash(&self, commit_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;

            let target_commit = repo.read_commit(&target_id)?;
            if target_commit.parents.is_empty() {
                bail!("Cannot squash the root commit");
            }
            let parent_id = &target_commit.parents[0];
            let parent_commit = repo.read_commit(parent_id)?;

            // The squashed commit uses the target's tree (which includes
            // all changes from both the parent and the target).
            // The message combines both messages.
            let combined_message = if parent_commit.message == target_commit.message {
                target_commit.message.clone()
            } else {
                format!("{}\n\n{}", parent_commit.message, target_commit.message)
            };

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let squashed = Commit::new(
                target_commit.tree,
                parent_commit.parents.clone(),
                parent_commit.author.clone(),
                combined_message,
                timestamp,
            );
            let squashed_id = repo.write_commit(&squashed)?;

            // Collect descendants of the target (commits from HEAD to target,
            // excluding the target itself).
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                if current == target_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &commit_spec);
                }
                current = commit.parents[0].clone();
            }

            // Rebuild descendants in reverse order (oldest first).
            let mut new_parent = squashed_id.clone();
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let new_commit = Commit::new(
                    old_commit.tree,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Unsquash a commit: split it back into two commits (the original parent
    /// tree + a new commit with the diff). This is the reverse of `squash`.
    /// Requires that the squashed commit has a grandparent (i.e., the original
    /// parent had parents). Returns the new HEAD hash.
    pub async fn unsquash(&self, commit_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let commit_spec = commit_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;
            let target_commit = repo.read_commit(&target_id)?;

            if target_commit.parents.is_empty() {
                bail!("Cannot unsquash the root commit (no parent to split from)");
            }

            let parent_id = &target_commit.parents[0];
            let parent_commit = repo.read_commit(parent_id)?;
            if parent_commit.parents.is_empty() {
                bail!("Cannot unsquash: parent commit is the root (no grandparent to restore)");
            }

            // The unsquash creates two commits:
            // 1. A restored parent commit with the grandparent's tree and the
            //    parent's original message (we don't have the original parent
            //    message, so we use a default).
            // 2. A new commit with the target's tree, parented to the restored
            //    parent, with the target's message.
            //
            // Since we can't recover the original parent's tree (it was
            // destroyed during squash), we use the grandparent's tree as the
            // restored parent's tree. This effectively splits the squashed
            // commit into: "empty parent" + "all changes".
            let grandparent_id = &parent_commit.parents[0];
            let grandparent_commit = repo.read_commit(grandparent_id)?;

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            // Restored parent: grandparent's tree, grandparent as parent.
            let restored_parent = Commit::new(
                grandparent_commit.tree,
                vec![grandparent_id.clone()],
                parent_commit.author.clone(),
                format!("{} (restored)", parent_commit.message),
                timestamp,
            );
            let restored_id = repo.write_commit(&restored_parent)?;

            // New commit: target's tree, restored parent as parent.
            let new_commit = Commit::new(
                target_commit.tree,
                vec![restored_id.clone()],
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_commit_id = repo.write_commit(&new_commit)?;

            // Collect descendants of the target.
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                if current == target_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &commit_spec);
                }
                current = commit.parents[0].clone();
            }

            // Rebuild descendants.
            let mut new_parent = new_commit_id.clone();
            for old_hash in descendants.iter().rev() {
                let old_commit = repo.read_commit(old_hash)?;
                let rebuilt = Commit::new(
                    old_commit.tree,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&rebuilt)?;
            }

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Squash the current HEAD commit into a specific ancestor commit
    /// (not just the parent). The HEAD's tree replaces the ancestor's tree,
    /// messages are combined, and descendants between them are rebuilt.
    /// Returns the new HEAD hash.
    pub async fn squash_into(&self, into_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let into_spec = into_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let target_id = mgr.resolve_commit(&into_spec, &head_id)?;

            if target_id == head_id {
                bail!("Cannot squash HEAD into itself");
            }

            let head_commit = repo.read_commit(&head_id)?;
            let target_commit = repo.read_commit(&target_id)?;

            // The squashed commit uses HEAD's tree (which includes all changes
            // from the target through HEAD).
            let combined_message = if target_commit.message == head_commit.message {
                head_commit.message.clone()
            } else {
                format!("{}\n\n{}", target_commit.message, head_commit.message)
            };

            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let squashed = Commit::new(
                head_commit.tree,
                target_commit.parents.clone(),
                target_commit.author.clone(),
                combined_message,
                timestamp,
            );
            let squashed_id = repo.write_commit(&squashed)?;

            // Collect descendants of the target (commits from HEAD to target,
            // excluding both).
            let mut descendants: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                if current == target_id {
                    break;
                }
                descendants.push(current.clone());
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &into_spec);
                }
                current = commit.parents[0].clone();
            }

            // Rebuild descendants (excluding HEAD, which was squashed into target).
            // The last descendant (HEAD) is skipped — its changes are now in the
            // squashed commit. Other descendants keep their trees.
            let mut new_parent = squashed_id.clone();
            for old_hash in descendants.iter().rev().skip(1) {
                let old_commit = repo.read_commit(old_hash)?;
                let new_commit = Commit::new(
                    old_commit.tree,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    old_commit.timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_parent)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&new_parent)?;
            mgr.restore_working_tree_pub(&new_parent)?;

            Ok(new_parent)
        })
        .await?
    }

    /// Fold a range of commits (from the specified commit to HEAD) into a
    /// single commit. The folded commit uses HEAD's tree and combines all
    /// messages in the range. Returns the new HEAD hash.
    pub async fn fold(&self, from_spec: &str) -> Result<String> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        let from_spec = from_spec.to_string();
        tokio::task::spawn_blocking(move || -> Result<String> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let from_id = mgr.resolve_commit(&from_spec, &head_id)?;

            if from_id == head_id {
                bail!("Cannot fold a single commit (from == HEAD)");
            }

            // Collect all commits in the range [from, HEAD].
            let mut commits_in_range: Vec<String> = Vec::new();
            let mut current = head_id.clone();
            loop {
                commits_in_range.push(current.clone());
                if current == from_id {
                    break;
                }
                let commit = repo.read_commit(&current)?;
                if commit.parents.is_empty() {
                    bail!("Commit {} is not an ancestor of HEAD", &from_spec);
                }
                current = commit.parents[0].clone();
            }

            // The from commit's parent is the new folded commit's parent.
            let from_commit = repo.read_commit(&from_id)?;
            if from_commit.parents.is_empty() {
                bail!("Cannot fold from the root commit");
            }
            let new_parent_id = &from_commit.parents[0];

            // Collect all messages (oldest first).
            let mut messages: Vec<String> = Vec::new();
            for hash in commits_in_range.iter().rev() {
                let commit = repo.read_commit(hash)?;
                messages.push(commit.message.clone());
            }
            let combined_message = messages.join("\n\n");

            // The folded commit uses HEAD's tree.
            let head_commit = repo.read_commit(&head_id)?;
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);

            let folded = Commit::new(
                head_commit.tree,
                vec![new_parent_id.clone()],
                head_commit.author.clone(),
                combined_message,
                timestamp,
            );
            let folded_id = repo.write_commit(&folded)?;

            // Update branch ref.
            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &folded_id)?;
            }

            // Sync index and working tree.
            mgr.sync_index_to_commit(&folded_id)?;
            mgr.restore_working_tree_pub(&folded_id)?;

            Ok(folded_id)
        })
        .await?
    }

}