codetree 0.2.0

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

/// Bound on how long an agent waits for the locks.json writer lock.
const RMW_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);

/// Manages file locks to prevent concurrent agents from modifying the same files.
/// Locks are stored in `.codetree/locks.json` as a map of `path -> operation_name`.
pub struct LockManager {
    path: PathBuf,
    locks: HashMap<String, String>,
}

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

    /// Load locks from disk. If no file exists, starts empty.
    pub fn load(path: PathBuf) -> Result<Self> {
        let locks = 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, locks })
    }

    /// Save locks to disk (atomic: temp file + rename, writer-serialized).
    /// For read-modify-write cycles prefer [`Self::update_atomically`], which
    /// also makes the *read* side of the cycle race-free.
    pub fn save(&self) -> Result<()> {
        let data = serde_json::to_string_pretty(&self.locks)?;
        crate::atomic::write_atomic(&self.path, data.as_bytes())?;
        Ok(())
    }

    /// Run a read-modify-write cycle against `locks.json` atomically.
    ///
    /// The load → modify → save sequence executes under an exclusive
    /// `<locks.json>.lock` lockfile, so two agents acquiring/releasing locks
    /// concurrently cannot lose each other's updates (the plain
    /// `load`/`save` pair is last-writer-wins and must not be used for RMW).
    ///
    /// `f` may inspect or mutate the manager freely; persist the result with
    /// the lock-free `Self::save_unlocked` — never `Self::save` (it would
    /// deadlock on the lock we already hold).
    pub fn update_atomically<T, F>(path: PathBuf, f: F) -> Result<T>
    where
        F: FnOnce(&mut Self) -> Result<T>,
    {
        crate::atomic::with_file_lock(&path, RMW_LOCK_TIMEOUT, || {
            let mut manager = Self::load(path.clone())?;
            let out = f(&mut manager)?;
            manager.save_unlocked()?;
            Ok(out)
        })
    }

    /// Serialize and write state, assuming the caller already holds the
    /// `<locks.json>.lock` lockfile (via `update_atomically`).
    fn save_unlocked(&self) -> Result<()> {
        let data = serde_json::to_string_pretty(&self.locks)?;
        crate::atomic::write_locked(&self.path, data.as_bytes())
    }

    /// Try to acquire locks for the given files on behalf of an operation.
    /// Returns `Ok(())` if all files are available (or already locked by this op).
    /// Returns `Err` with a conflict message if any file is locked by a different operation.
    pub fn acquire(&mut self, files: &[String], operation: &str) -> Result<()> {
        let conflicts = self.conflicts(files, operation);
        if !conflicts.is_empty() {
            bail!(
                "File '{}' is locked by operation '{}'",
                conflicts[0].0,
                conflicts[0].1
            );
        }
        // All clear — acquire locks
        for file in files {
            self.locks.insert(file.clone(), operation.to_string());
        }
        Ok(())
    }

    /// Check for conflicts without acquiring. Returns a list of (file, holder) pairs
    /// for files locked by a different operation.
    pub fn conflicts(&self, files: &[String], operation: &str) -> Vec<(String, String)> {
        files.iter()
            .filter_map(|file| {
                self.locks.get(file).and_then(|holder| {
                    if holder != operation {
                        Some((file.clone(), holder.clone()))
                    } else {
                        None
                    }
                })
            })
            .collect()
    }

    /// Release all locks held by the given operation.
    pub fn release_for_operation(&mut self, operation: &str) {
        self.locks.retain(|_, holder| holder != operation);
    }

    /// Release a specific file lock, regardless of which operation holds it.
    pub fn release_file(&mut self, file: &str) -> bool {
        self.locks.remove(file).is_some()
    }

    /// Check if a file is locked by a specific operation.
    pub fn is_locked_by(&self, file: &str, operation: &str) -> bool {
        self.locks.get(file).is_some_and(|h| h == operation)
    }

    /// Check if a file is locked by any operation.
    pub fn is_locked(&self, file: &str) -> bool {
        self.locks.contains_key(file)
    }

    /// Check if a file is locked by a different operation than the given one.
    pub fn is_locked_by_other(&self, file: &str, operation: &str) -> bool {
        self.locks.get(file).is_some_and(|h| h != operation)
    }

    /// Get the operation that holds a lock for a file, if any.
    pub fn lock_holder(&self, file: &str) -> Option<&str> {
        self.locks.get(file).map(|s| s.as_str())
    }

    /// List all locks as (path, operation) pairs, sorted by path.
    pub fn list_locks(&self) -> Vec<(String, String)> {
        let mut entries: Vec<_> = self.locks.iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        entries
    }

    /// Get all files locked by a specific operation.
    pub fn files_for_operation(&self, operation: &str) -> Vec<String> {
        self.locks.iter()
            .filter(|(_, h)| h.as_str() == operation)
            .map(|(f, _)| f.clone())
            .collect()
    }
}

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

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

    #[test]
    fn test_acquire_and_check() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string(), "b.rs".to_string()], "op1").unwrap();
        assert!(mgr.is_locked("a.rs"));
        assert!(mgr.is_locked_by("a.rs", "op1"));
        assert!(!mgr.is_locked_by("a.rs", "op2"));
    }

    #[test]
    fn test_acquire_conflict() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string()], "op1").unwrap();
        let result = mgr.acquire(&["a.rs".to_string()], "op2");
        assert!(result.is_err());
    }

    #[test]
    fn test_acquire_same_op_reacquires() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string()], "op1").unwrap();
        // Re-acquiring by same op should succeed
        mgr.acquire(&["a.rs".to_string()], "op1").unwrap();
    }

    #[test]
    fn test_release_for_operation() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string(), "b.rs".to_string()], "op1").unwrap();
        mgr.acquire(&["c.rs".to_string()], "op2").unwrap();
        mgr.release_for_operation("op1");
        assert!(!mgr.is_locked("a.rs"));
        assert!(!mgr.is_locked("b.rs"));
        assert!(mgr.is_locked("c.rs"));
    }

    #[test]
    fn test_release_file() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string()], "op1").unwrap();
        assert!(mgr.release_file("a.rs"));
        assert!(!mgr.is_locked("a.rs"));
        assert!(!mgr.release_file("nonexistent.rs"));
    }

    #[test]
    fn test_is_locked_by_other() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string()], "op1").unwrap();
        assert!(mgr.is_locked_by_other("a.rs", "op2"));
        assert!(!mgr.is_locked_by_other("a.rs", "op1"));
        assert!(!mgr.is_locked_by_other("b.rs", "op1"));
    }

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

        let mut mgr = LockManager::new(path.clone());
        mgr.acquire(&["a.rs".to_string(), "b.rs".to_string()], "op1").unwrap();
        mgr.save().unwrap();

        let loaded = LockManager::load(path).unwrap();
        assert!(loaded.is_locked("a.rs"));
        assert!(loaded.is_locked("b.rs"));
        assert_eq!(loaded.lock_holder("a.rs"), Some("op1"));
    }

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

    #[test]
    fn test_list_locks_sorted() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["c.rs".to_string()], "op3").unwrap();
        mgr.acquire(&["a.rs".to_string()], "op1").unwrap();
        mgr.acquire(&["b.rs".to_string()], "op2").unwrap();
        let locks = mgr.list_locks();
        assert_eq!(locks[0].0, "a.rs");
        assert_eq!(locks[1].0, "b.rs");
        assert_eq!(locks[2].0, "c.rs");
    }

    #[test]
    fn test_files_for_operation() {
        let (_tmp, mut mgr) = setup();
        mgr.acquire(&["a.rs".to_string(), "b.rs".to_string()], "op1").unwrap();
        mgr.acquire(&["c.rs".to_string()], "op2").unwrap();
        let files = mgr.files_for_operation("op1");
        assert!(files.contains(&"a.rs".to_string()));
        assert!(files.contains(&"b.rs".to_string()));
        assert!(!files.contains(&"c.rs".to_string()));
    }

    #[test]
    fn test_update_atomically_persists_changes() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("locks.json");
        LockManager::update_atomically(path.clone(), |m| {
            m.acquire(&["a.rs".to_string()], "op1")
        })
        .unwrap();
        let loaded = LockManager::load(path.clone()).unwrap();
        assert!(loaded.is_locked_by("a.rs", "op1"));
        assert!(!path.with_extension("lock").exists() && !tmp.path().join("locks.json.lock").exists());
    }

    #[test]
    fn test_update_atomically_conflict_leaves_state_untouched() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("locks.json");
        let mut mgr = LockManager::new(path.clone());
        mgr.acquire(&["x.rs".to_string()], "holder").unwrap();
        mgr.save().unwrap();

        let err = LockManager::update_atomically(path.clone(), |m| {
            m.acquire(&["x.rs".to_string()], "intruder")
        })
        .unwrap_err();
        assert!(err.to_string().contains("locked by operation 'holder'"));
        // Failed acquire must not have corrupted or emptied the lock state.
        let reloaded = LockManager::load(path).unwrap();
        assert!(reloaded.is_locked_by("x.rs", "holder"));
    }

    #[test]
    fn test_update_atomically_concurrent_acquirers() {
        // 4 threads racing through update_atomically; each tries to lock the
        // same file for its own op. Locks.json must end with exactly ONE
        // winner — lost updates are the bug this API exists to prevent.
        let tmp = TempDir::new().unwrap();
        let path = Arc::new(tmp.path().join("locks.json"));
        let mut handles = Vec::new();
        for i in 0..4u32 {
            let p = Arc::clone(&path);
            handles.push(std::thread::spawn(move || {
                LockManager::update_atomically((*p).clone(), |m| {
                    m.acquire(&["shared.rs".to_string()], &format!("op{}", i))
                })
            }));
        }
        let outcomes: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(outcomes.iter().filter(|r| r.is_ok()).count(), 1);
        let loaded = LockManager::load((*path).clone()).unwrap();
        assert_eq!(loaded.list_locks().len(), 1);
    }

    #[test]
    fn test_release_is_atomic_against_concurrent_acquire() {
        // One thread releases while another acquires the same file; the final
        // state must be consistent (either released, or re-acquired — never a
        // lost update leaving a phantom lock).
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("locks.json");
        let p_releaser = path.clone();
        let p_acquirer = path.clone();
        let releaser = std::thread::spawn(move || {
            LockManager::update_atomically(p_releaser, |m| {
                m.release_for_operation("op1");
                Ok(())
            })
            .unwrap();
        });
        let acquirer = std::thread::spawn(move || {
            LockManager::update_atomically(p_acquirer, |m| {
                m.acquire(&["a.rs".to_string()], "op2")
            })
            .unwrap();
        });
        releaser.join().unwrap();
        acquirer.join().unwrap();
        let loaded = LockManager::load(path).unwrap();
        // op2's acquire must survive; op1's release must not resurrect or clobber it.
        assert!(loaded.is_locked_by("a.rs", "op2"));
        assert!(loaded.files_for_operation("op1").is_empty());
    }
}