codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
//! Commit lifecycle rewrites (revive, abandon, forget) 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::{object_path, Commit};
use super::manager::VcsManager;

impl VcsManager {
    /// Revive an abandoned commit: restore it onto HEAD as a new commit.
    /// The revived commit gets HEAD as its parent and the abandoned commit's tree.
    /// Returns the new HEAD hash.
    pub async fn revive(&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)?;

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

            let revived = Commit::new(
                target_commit.tree,
                vec![head_id.clone()],
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_id = repo.write_commit(&revived)?;

            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_id)?;
            }

            mgr.sync_index_to_commit(&new_id)?;
            mgr.restore_working_tree_pub(&new_id)?;

            Ok(new_id)
        })
        .await?
    }

    /// Duplicate a commit: create a copy on top of HEAD with the same tree
    /// and metadata. Useful for experimenting with variations.
    /// Returns the new HEAD hash.
    pub async fn duplicate(&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)?;

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

            let duplicated = Commit::new(
                target_commit.tree,
                vec![head_id.clone()],
                target_commit.author.clone(),
                format!("{} (duplicated)", target_commit.message),
                timestamp,
            );
            let new_id = repo.write_commit(&duplicated)?;

            if let Some(branch) = repo.refs().current_branch()? {
                repo.refs().set_branch(&branch, &new_id)?;
            }

            mgr.sync_index_to_commit(&new_id)?;
            mgr.restore_working_tree_pub(&new_id)?;

            Ok(new_id)
        })
        .await?
    }

    /// Abandon a commit: remove it from the branch and rebuild descendants
    /// onto its parent. Unlike `withdraw` (which removes an entire operation),
    /// `abandon` works on individual commits. Returns the new HEAD hash.
    pub async fn abandon(&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 abandon the root commit");
            }
            let new_parent_id = target_commit.parents[0].clone();

            // Collect descendants (commits from HEAD to target, excluding 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();
            }

            // If no descendants, just move branch to target's parent.
            if descendants.is_empty() {
                if let Some(branch) = repo.refs().current_branch()? {
                    repo.refs().set_branch(&branch, &new_parent_id)?;
                }
                mgr.sync_index_to_commit(&new_parent_id)?;
                mgr.restore_working_tree_pub(&new_parent_id)?;
                return Ok(new_parent_id);
            }

            // Rebuild descendants onto target's parent, skipping the target.
            let mut new_parent = new_parent_id;
            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?
    }

    /// Forget a commit: abandon it AND remove it from the object store.
    /// Unlike abandon, the commit cannot be revived afterward.
    pub async fn forget(&self, commit_spec: &str) -> Result<String> {
        let new_head = self.abandon(commit_spec).await?;

        // Remove the forgotten commit's objects from the store.
        let head_id = self.repo.refs().resolve_head()?
            .context("HEAD does not point to a commit")?;
        let target_id = self.resolve_commit_pub(commit_spec, &head_id)?;

        // Best-effort deletion of the commit object.
        // The gc command will clean up any orphaned trees/blobs.
        let commit_path = object_path(self.repo.root(), &target_id);
        if commit_path.exists() {
            let _ = std::fs::remove_file(&commit_path);
        }

        Ok(new_head)
    }

}