codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
use std::collections::HashMap;
use std::path::PathBuf;
use crate::error::Result;

/// Manages candidate groups — sets of operations that solve the same problem.
/// Multiple agents create operations in the same group; the orchestrator
/// evaluates and promotes the best one.
/// Stored in `.codetree/candidates.json` as a map of `group_name -> Vec<operation_name>`.
pub struct CandidateManager {
    path: PathBuf,
    groups: HashMap<String, Vec<String>>,
}

impl CandidateManager {
    pub fn new(path: PathBuf) -> Self {
        Self {
            path,
            groups: HashMap::new(),
        }
    }

    /// Load candidate groups from disk. If no file exists, starts empty.
    pub fn load(path: PathBuf) -> Result<Self> {
        let groups = if path.exists() {
            let data = std::fs::read_to_string(&path)?;
            serde_json::from_str(&data).unwrap_or_default()
        } else {
            HashMap::new()
        };
        Ok(Self { path, groups })
    }

    /// Save candidate groups to disk.
    pub fn save(&self) -> Result<()> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let data = serde_json::to_string_pretty(&self.groups)?;
        crate::atomic::write_atomic(&self.path, data.as_bytes())?;
        Ok(())
    }

    /// Add an operation to a candidate group. Creates the group if it doesn't exist.
    pub fn add_candidate(&mut self, group: &str, operation: &str) -> Result<()> {
        let candidates = self.groups.entry(group.to_string()).or_default();
        if candidates.contains(&operation.to_string()) {
            bail!("Operation '{}' is already in candidate group '{}'", operation, group);
        }
        candidates.push(operation.to_string());
        Ok(())
    }

    /// Remove an operation from a candidate group.
    pub fn remove_candidate(&mut self, group: &str, operation: &str) -> bool {
        if let Some(candidates) = self.groups.get_mut(group) {
            let before = candidates.len();
            candidates.retain(|c| c != operation);
            return candidates.len() < before;
        }
        false
    }

    /// Get all operations in a candidate group.
    pub fn get_group(&self, group: &str) -> Option<&Vec<String>> {
        self.groups.get(group)
    }

    /// List all candidate group names.
    pub fn list_groups(&self) -> Vec<String> {
        let mut names: Vec<_> = self.groups.keys().cloned().collect();
        names.sort();
        names
    }

    /// Delete a candidate group entirely.
    pub fn delete_group(&mut self, group: &str) -> bool {
        self.groups.remove(group).is_some()
    }

    /// Get all operations across all groups (for checking if an op belongs to any group).
    pub fn all_candidates(&self) -> Vec<String> {
        self.groups.values().flatten().cloned().collect()
    }

    /// Check if an operation belongs to a specific group.
    pub fn is_candidate(&self, group: &str, operation: &str) -> bool {
        self.groups.get(group).is_some_and(|c| c.contains(&operation.to_string()))
    }

    /// Get the group name for an operation, if any.
    pub fn group_for_operation(&self, operation: &str) -> Option<&str> {
        for (group, candidates) in &self.groups {
            if candidates.contains(&operation.to_string()) {
                return Some(group.as_str());
            }
        }
        None
    }
}

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

    fn setup() -> (TempDir, CandidateManager) {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("candidates.json");
        let mgr = CandidateManager::new(path);
        (tmp, mgr)
    }

    #[test]
    fn test_add_candidate_creates_group() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        assert_eq!(mgr.get_group("auth-fix").unwrap(), &vec!["op1".to_string()]);
    }

    #[test]
    fn test_add_multiple_candidates() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        mgr.add_candidate("auth-fix", "op2").unwrap();
        mgr.add_candidate("auth-fix", "op3").unwrap();
        assert_eq!(mgr.get_group("auth-fix").unwrap().len(), 3);
    }

    #[test]
    fn test_add_duplicate_candidate_fails() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        let result = mgr.add_candidate("auth-fix", "op1");
        assert!(result.is_err());
    }

    #[test]
    fn test_remove_candidate() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        mgr.add_candidate("auth-fix", "op2").unwrap();
        assert!(mgr.remove_candidate("auth-fix", "op1"));
        assert_eq!(mgr.get_group("auth-fix").unwrap().len(), 1);
    }

    #[test]
    fn test_remove_nonexistent_candidate() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        assert!(!mgr.remove_candidate("auth-fix", "nonexistent"));
        assert!(!mgr.remove_candidate("nonexistent", "op1"));
    }

    #[test]
    fn test_list_groups() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("zebra", "op1").unwrap();
        mgr.add_candidate("alpha", "op2").unwrap();
        mgr.add_candidate("mango", "op3").unwrap();
        assert_eq!(mgr.list_groups(), vec!["alpha", "mango", "zebra"]);
    }

    #[test]
    fn test_delete_group() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        assert!(mgr.delete_group("auth-fix"));
        assert!(mgr.get_group("auth-fix").is_none());
    }

    #[test]
    fn test_is_candidate() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        assert!(mgr.is_candidate("auth-fix", "op1"));
        assert!(!mgr.is_candidate("auth-fix", "op2"));
        assert!(!mgr.is_candidate("other", "op1"));
    }

    #[test]
    fn test_group_for_operation() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("auth-fix", "op1").unwrap();
        mgr.add_candidate("ui-redesign", "op2").unwrap();
        assert_eq!(mgr.group_for_operation("op1"), Some("auth-fix"));
        assert_eq!(mgr.group_for_operation("op2"), Some("ui-redesign"));
        assert_eq!(mgr.group_for_operation("op3"), None);
    }

    #[test]
    fn test_save_and_load() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("candidates.json");

        let mut mgr = CandidateManager::new(path.clone());
        mgr.add_candidate("auth-fix", "op1").unwrap();
        mgr.add_candidate("auth-fix", "op2").unwrap();
        mgr.save().unwrap();

        let loaded = CandidateManager::load(path).unwrap();
        assert_eq!(loaded.get_group("auth-fix").unwrap().len(), 2);
        assert!(loaded.is_candidate("auth-fix", "op1"));
    }

    #[test]
    fn test_load_empty() {
        let tmp = TempDir::new().unwrap();
        let mgr = CandidateManager::load(tmp.path().join("candidates.json")).unwrap();
        assert!(mgr.list_groups().is_empty());
    }

    #[test]
    fn test_all_candidates() {
        let (_tmp, mut mgr) = setup();
        mgr.add_candidate("g1", "op1").unwrap();
        mgr.add_candidate("g1", "op2").unwrap();
        mgr.add_candidate("g2", "op3").unwrap();
        let all = mgr.all_candidates();
        assert_eq!(all.len(), 3);
    }
}