codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
//! Conflict resolution cache for automatic merge conflict resolution.
//!
//! Stores blob-hash-level resolutions so that identical conflicts in future
//! merges are auto-resolved without user intervention.

use crate::error::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// A single cached resolution: maps (file_path, our_blob, their_blob) -> resolved_blob.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolutionEntry {
    pub path: String,
    pub our_blob: String,
    pub their_blob: String,
    pub resolved_blob: String,
}

/// In-memory resolution cache backed by a JSON file.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResolutionCache {
    /// Keyed by `{path}:{our_blob}:{their_blob}`
    entries: HashMap<String, ResolutionEntry>,
}

impl ResolutionCache {
    /// Look up a cached resolution for a conflicting file.
    pub fn get(&self, path: &str, our_blob: &str, their_blob: &str) -> Option<&str> {
        let key = Self::key(path, our_blob, their_blob);
        self.entries.get(&key).map(|e| e.resolved_blob.as_str())
    }

    /// Store a resolution.
    pub fn set(&mut self, path: &str, our_blob: &str, their_blob: &str, resolved_blob: &str) {
        let key = Self::key(path, our_blob, their_blob);
        self.entries.insert(key, ResolutionEntry {
            path: path.to_string(),
            our_blob: our_blob.to_string(),
            their_blob: their_blob.to_string(),
            resolved_blob: resolved_blob.to_string(),
        });
    }

    /// Number of cached resolutions.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Load from a JSON file. Returns empty cache if file doesn't exist.
    pub async fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let data = tokio::fs::read_to_string(path)
            .await
            .with_context(|| format!("Failed to read resolution cache: {:?}", path))?;
        if data.trim().is_empty() {
            return Ok(Self::default());
        }
        serde_json::from_str(&data)
            .with_context(|| format!("Failed to parse resolution cache: {:?}", path))
    }

    /// Save to a JSON file (atomic: temp file + rename).
    pub async fn save(&self, path: &Path) -> Result<()> {
        let data = serde_json::to_string_pretty(self)
            .context("Failed to serialize resolution cache")?;
        crate::atomic::write_atomic(path, data.as_bytes())
            .with_context(|| format!("Failed to write resolution cache: {:?}", path))?;
        Ok(())
    }

    fn key(path: &str, our_blob: &str, their_blob: &str) -> String {
        format!("{}:{}:{}", path, our_blob, their_blob)
    }
}

/// Metadata about a pending merge conflict, written before the user resolves manually.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingResolution {
    pub branch: String,
    pub base_branch: String,
    pub conflicts: Vec<ConflictInfo>,
}

/// Information about a single conflicting file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConflictInfo {
    pub path: String,
    pub our_blob: String,
    pub their_blob: String,
}

impl PendingResolution {
    /// Load from a JSON file. Returns None if file doesn't exist.
    pub async fn load(path: &Path) -> Result<Option<Self>> {
        if !path.exists() {
            return Ok(None);
        }
        let data = tokio::fs::read_to_string(path)
            .await
            .with_context(|| format!("Failed to read pending resolution: {:?}", path))?;
        if data.trim().is_empty() {
            return Ok(None);
        }
        let pending: Self = serde_json::from_str(&data)
            .with_context(|| format!("Failed to parse pending resolution: {:?}", path))?;
        Ok(Some(pending))
    }

    /// Save to a JSON file (atomic: temp file + rename).
    pub async fn save(&self, path: &Path) -> Result<()> {
        let data = serde_json::to_string_pretty(self)
            .context("Failed to serialize pending resolution")?;
        crate::atomic::write_atomic(path, data.as_bytes())
            .with_context(|| format!("Failed to write pending resolution: {:?}", path))?;
        Ok(())
    }

    /// Delete the file if it exists.
    pub async fn clear(path: &Path) -> Result<()> {
        if path.exists() {
            tokio::fs::remove_file(path)
                .await
                .with_context(|| format!("Failed to remove pending resolution: {:?}", path))?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cache_set_get() {
        let mut cache = ResolutionCache::default();
        assert!(cache.get("src/main.rs", "abc", "def").is_none());

        cache.set("src/main.rs", "abc", "def", "resolved123");
        assert_eq!(cache.get("src/main.rs", "abc", "def"), Some("resolved123"));
        assert!(cache.get("src/main.rs", "abc", "xyz").is_none());
        assert!(cache.get("src/other.rs", "abc", "def").is_none());
    }

    #[test]
    fn test_cache_len() {
        let mut cache = ResolutionCache::default();
        assert!(cache.is_empty());
        cache.set("a.rs", "1", "2", "3");
        cache.set("b.rs", "4", "5", "6");
        assert_eq!(cache.len(), 2);
    }

    #[tokio::test]
    async fn test_cache_save_and_load() -> Result<()> {
        let temp = tempfile::TempDir::new()?;
        let path = temp.path().join("resolutions.json");

        let mut cache = ResolutionCache::default();
        cache.set("file.rs", "blob_a", "blob_b", "blob_r");
        cache.save(&path).await?;

        let loaded = ResolutionCache::load(&path).await?;
        assert_eq!(loaded.get("file.rs", "blob_a", "blob_b"), Some("blob_r"));
        assert_eq!(loaded.len(), 1);

        Ok(())
    }

    #[tokio::test]
    async fn test_cache_load_nonexistent() -> Result<()> {
        let temp = tempfile::TempDir::new()?;
        let path = temp.path().join("nonexistent.json");
        let cache = ResolutionCache::load(&path).await?;
        assert!(cache.is_empty());
        Ok(())
    }

    #[tokio::test]
    async fn test_pending_resolution_save_load_clear() -> Result<()> {
        let temp = tempfile::TempDir::new()?;
        let path = temp.path().join("pending.json");

        let pending = PendingResolution {
            branch: "feature".to_string(),
            base_branch: "main".to_string(),
            conflicts: vec![ConflictInfo {
                path: "src/main.rs".to_string(),
                our_blob: "abc".to_string(),
                their_blob: "def".to_string(),
            }],
        };
        pending.save(&path).await?;

        let loaded = PendingResolution::load(&path).await?;
        assert!(loaded.is_some());
        let loaded = loaded.unwrap();
        assert_eq!(loaded.branch, "feature");
        assert_eq!(loaded.conflicts.len(), 1);
        assert_eq!(loaded.conflicts[0].path, "src/main.rs");

        PendingResolution::clear(&path).await?;
        let after_clear = PendingResolution::load(&path).await?;
        assert!(after_clear.is_none());

        Ok(())
    }
}