codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
//! Working-tree absorption rewrites 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::{Tree, TreeEntry, Commit};
use super::manager::{commit_tree_entries, AbsorbResult, VcsManager};

impl VcsManager {
    /// Absorb uncommitted working-tree changes into the best-matching commit
    /// in the current branch's history (Sapling-style). Returns the new HEAD
    /// commit hash and a description of what was absorbed.
    ///
    /// Algorithm:
    /// 1. Walk the working tree and compute modified files (vs HEAD tree).
    /// 2. Walk back through commits on the current branch (HEAD, HEAD~1, …).
    /// 3. For each commit, compute its changed files (diff vs its parent).
    /// 4. Pick the commit with the most file overlap with the working tree.
    /// 5. Amend that commit's tree with the new content for overlapping files.
    /// 6. Rebuild descendants: for each file in the absorbed set, if the
    ///    descendant didn't change it, take the new version; otherwise keep
    ///    the descendant's version.
    /// 7. Update the branch ref, sync index + working tree to new HEAD.
    pub async fn absorb(&self) -> Result<AbsorbResult> {
        let repo = self.repo.clone();
        let repo_path = self.repo_path.clone();
        tokio::task::spawn_blocking(move || -> Result<AbsorbResult> {
            let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };

            // 1. Compute working-tree modified files (path -> new blob id).
            let head_tree = mgr.head_tree()?;
            let head_map: std::collections::HashMap<String, String> = head_tree
                .entries
                .iter()
                .map(|e| (e.name.clone(), e.id.clone()))
                .collect();

            let wt_files = mgr.walk_working_tree(&repo_path)?;
            let mut wt_changes: Vec<(String, String)> = Vec::new(); // (path, new_blob_id)
            for file in &wt_files {
                let relative = file.strip_prefix(&repo_path).unwrap_or(file);
                let relative_str = relative.to_string_lossy().to_string();
                let content = std::fs::read(file)
                    .with_context(|| format!("absorb: read wt file {:?}", file))?;
                let blob_id = repo.write_blob(&content)?;
                match head_map.get(&relative_str) {
                    Some(h) if *h == blob_id => {} // unchanged
                    _ => wt_changes.push((relative_str, blob_id)),
                }
            }
            // Deleted files (in HEAD but not in working tree)
            let wt_set: std::collections::HashSet<&str> =
                wt_files.iter().map(|f| f.strip_prefix(&repo_path).unwrap_or(f).to_str().unwrap()).collect();
            for name in head_map.keys() {
                if !wt_set.contains(name.as_str()) {
                    wt_changes.push((name.clone(), String::new())); // empty = deleted
                }
            }

            if wt_changes.is_empty() {
                bail!("No uncommitted changes to absorb");
            }

            let wt_files_set: std::collections::HashSet<&str> =
                wt_changes.iter().map(|(p, _)| p.as_str()).collect();

            // 2. Walk back through commits, collecting (commit_hash, changed_files).
            let head_id = repo.refs().resolve_head()?.context("HEAD does not point to a commit")?;
            let mut commits: Vec<(String, Vec<String>)> = Vec::new();
            let mut current = head_id.clone();
            for _ in 0..50 {
                let commit = repo.read_commit(&current)?;
                let parent_tree = if !commit.parents.is_empty() {
                    let parent = repo.read_commit(&commit.parents[0])?;
                    repo.read_tree(&parent.tree)?
                } else {
                    Tree::new(vec![])
                };
                let changed: Vec<String> = {
                    let parent_set: std::collections::HashMap<&String, &String> = parent_tree
                        .entries.iter().map(|e| (&e.name, &e.id)).collect();
                    let mut files = Vec::new();
                    for entry in &commit_tree_entries(&repo, &current)? {
                        match parent_set.get(&entry.name) {
                            Some(h) if **h != entry.id => files.push(entry.name.clone()),
                            None => files.push(entry.name.clone()),
                            _ => {}
                        }
                    }
                    for name in parent_tree.entries.iter().map(|e| &e.name) {
                        if !commit_tree_entries(&repo, &current)?.iter().any(|e| &e.name == name) {
                            files.push(name.clone());
                        }
                    }
                    files
                };
                commits.push((current.clone(), changed));
                if commit.parents.is_empty() {
                    break;
                }
                current = commit.parents[0].clone();
            }

            // 3. Find the commit with the most overlap.
            let mut best_idx = 0usize;
            let mut best_overlap = 0usize;
            for (i, (_, changed)) in commits.iter().enumerate() {
                let overlap = changed.iter().filter(|f| wt_files_set.contains(f.as_str())).count();
                if overlap > best_overlap {
                    best_overlap = overlap;
                    best_idx = i;
                }
            }

            if best_overlap == 0 {
                // No commit has overlap — amend HEAD as fallback.
                best_idx = 0;
            }

            let (target_hash, _) = &commits[best_idx];
            let target_hash = target_hash.clone();

            // 4. Build the new target tree: start from target's tree, apply
            //    working-tree changes for overlapping files.
            let target_commit = repo.read_commit(&target_hash)?;
            let target_tree = repo.read_tree(&target_commit.tree)?;
            let mut target_entries: Vec<TreeEntry> = target_tree.entries.clone();
            let target_map: std::collections::HashMap<String, usize> = target_tree
                .entries.iter().enumerate().map(|(i, e)| (e.name.clone(), i)).collect();

            let mut absorbed_files = Vec::new();
            for (path, new_blob) in &wt_changes {
                if let Some(&idx) = target_map.get(path) {
                    if new_blob.is_empty() {
                        // File was deleted in working tree — remove from target tree
                        target_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
                    } else {
                        target_entries[idx].id = new_blob.clone();
                    }
                    absorbed_files.push(path.clone());
                } else if !new_blob.is_empty() {
                    // File is new (not in target tree) — add it only if the target
                    // is HEAD (otherwise it belongs to a later commit).
                    if best_idx == 0 {
                        target_entries.push(TreeEntry { mode: 0o100644, name: path.clone(), id: new_blob.clone() });
                        absorbed_files.push(path.clone());
                    }
                }
            }
            // Remove deleted entries (mode 0 = marker for deletion)
            target_entries.retain(|e| e.mode != 0);

            let new_target_tree = Tree::new(target_entries);
            let new_target_tree_id = repo.write_tree(&new_target_tree)?;

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

            let new_target_commit = Commit::new(
                new_target_tree_id,
                target_commit.parents.clone(),
                target_commit.author.clone(),
                target_commit.message.clone(),
                timestamp,
            );
            let new_target_id = repo.write_commit(&new_target_commit)?;

            // 5. Rebuild descendants (commits newer than the target).
            // `commits` is ordered newest-to-oldest, so descendants are
            // `commits[0..best_idx]` — iterate in reverse (oldest descendant first).
            let mut new_parent = new_target_id.clone();
            let absorbed_set: std::collections::HashSet<&str> =
                absorbed_files.iter().map(|s| s.as_str()).collect();

            for i in (0..best_idx).rev() {
                let (old_hash, _) = &commits[i];
                let old_commit = repo.read_commit(old_hash)?;
                let old_tree = repo.read_tree(&old_commit.tree)?;

                // For each absorbed file: if the descendant didn't change it
                // (same blob as the original target), update it to the new
                // version from the amended target tree.
                let mut new_entries = old_tree.entries.clone();
                let old_tree_map: std::collections::HashMap<String, usize> = old_tree
                    .entries.iter().enumerate().map(|(i, e)| (e.name.clone(), i)).collect();

                for (path, new_blob) in &wt_changes {
                    if !absorbed_set.contains(path.as_str()) {
                        continue;
                    }
                    if let Some(&idx) = old_tree_map.get(path) {
                        // Check if the descendant changed this file vs the target
                        let target_blob = target_tree.entries.iter()
                            .find(|e| e.name == *path)
                            .map(|e| e.id.clone());
                        if old_tree.entries[idx].id == target_blob.unwrap_or_default() {
                            // Descendant didn't change it — update to new version
                            if new_blob.is_empty() {
                                new_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
                            } else {
                                new_entries[idx].id = new_blob.clone();
                            }
                        }
                    }
                }
                new_entries.retain(|e| e.mode != 0);

                let new_tree = Tree::new(new_entries);
                let new_tree_id = repo.write_tree(&new_tree)?;

                let new_commit = Commit::new(
                    new_tree_id,
                    vec![new_parent.clone()],
                    old_commit.author.clone(),
                    old_commit.message.clone(),
                    timestamp,
                );
                new_parent = repo.write_commit(&new_commit)?;
            }

            // 6. Update branch ref to the new HEAD.
            let branch = repo.refs().current_branch()?.context("No current branch")?;
            repo.refs().set_branch(&branch, &new_parent)?;

            // 7. Sync index + working tree to new HEAD.
            let mgr2 = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
            mgr2.sync_index_to_commit(&new_parent)
                .context("absorb: sync index")?;
            mgr2.restore_working_tree_pub(&new_parent)
                .context("absorb: restore working tree")?;

            Ok(AbsorbResult {
                new_head: new_parent,
                target_commit: target_hash,
                absorbed_files,
                was_head: best_idx == 0,
            })
        })
        .await?
    }

    /// Soft reset to parent of HEAD (undo last commit, keep changes staged).
    pub async fn reset_soft_parent(&self) -> Result<()> {
        let head_id = self
            .repo
            .refs()
            .resolve_head()?
            .context("HEAD does not point to a commit")?;
        let head_commit = self.repo.read_commit(&head_id)?;

        if head_commit.parents.is_empty() {
            bail!("No parent commit to reset to");
        }

        let parent_id = &head_commit.parents[0];

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

        // Restore index to match parent commit's tree
        let parent_commit = self.repo.read_commit(parent_id)?;
        let tree = self.repo.read_tree(&parent_commit.tree)?;
        let mut index = self.repo.load_index()?;
        index.clear();
        for entry in &tree.entries {
            index.add(&entry.name, &entry.id);
        }
        index.save()?;

        Ok(())
    }

    // ── Status ─────────────────────────────────────────────────────

}