codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
//! Working-copy snapshots — automatic safety net for agents.
//!
//! Before commands that could overwrite the working tree (switch, rebase,
//! merge, finish, withdraw, undo, redo, resolve), CodeTree snapshots the
//! current working tree as an anonymous commit. If the agent crashes before
//! `save`, the work is recoverable via `codetree restore-snapshot`.
//!
//! Snapshots are cleared when `save` succeeds (the real commit supersedes
//! them) and pruned to the last [`MAX_SNAPSHOTS`] entries.

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

/// Maximum number of snapshots to retain after pruning.
pub const MAX_SNAPSHOTS: usize = 20;

/// A single snapshot entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotEntry {
    pub id: usize,
    pub commit_hash: String,
    pub timestamp: u64,
    pub branch: String,
    pub file_count: usize,
    /// Label for explicit checkpoints (`codetree checkpoint`). `None` for
    /// automatic pre-command snapshots. Labeled checkpoints survive `save`
    /// (TODO Round 13: turn-level rewind targets).
    #[serde(default)]
    pub label: Option<String>,
}

/// In-memory snapshot list backed by `.codetree/snapshots.json`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SnapshotManager {
    next_id: usize,
    snapshots: Vec<SnapshotEntry>,
}

impl SnapshotManager {
    /// Load from a JSON file. Returns an empty manager if the file doesn't exist.
    pub async fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let data = fs::read_to_string(path)
            .await
            .with_context(|| format!("Failed to read snapshots: {:?}", path))?;
        if data.trim().is_empty() {
            return Ok(Self::default());
        }
        serde_json::from_str(&data)
            .with_context(|| format!("Failed to parse snapshots: {:?}", 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 snapshots")?;
        crate::atomic::write_atomic(path, data.as_bytes())
            .with_context(|| format!("Failed to write snapshots: {:?}", path))?;
        Ok(())
    }

    /// Record a new automatic (unlabeled) snapshot. Returns the assigned id.
    pub fn add(&mut self, commit_hash: String, timestamp: u64, branch: String, file_count: usize) -> usize {
        self.add_labeled(commit_hash, timestamp, branch, file_count, None)
    }

    /// Record a snapshot with an optional label (explicit checkpoints).
    /// Labeled entries survive `save` and show up in `codetree snapshots`.
    pub fn add_labeled(&mut self, commit_hash: String, timestamp: u64, branch: String, file_count: usize, label: Option<String>) -> usize {
        let id = self.next_id;
        self.next_id += 1;
        self.snapshots.push(SnapshotEntry {
            id,
            commit_hash,
            timestamp,
            branch,
            file_count,
            label,
        });
        id
    }

    /// List all snapshots (newest last).
    pub fn list(&self) -> &[SnapshotEntry] {
        &self.snapshots
    }

    /// Get a snapshot by id.
    pub fn get(&self, id: usize) -> Option<&SnapshotEntry> {
        self.snapshots.iter().find(|s| s.id == id)
    }

    /// Remove all snapshots (called when `save` supersedes them).
    pub fn clear(&mut self) {
        self.snapshots.clear();
    }

    /// Remove only unlabeled (automatic) snapshots — called when `save`
    /// succeeds. Labeled checkpoints persist until pruned, so `codetree
    /// rewind` targets stay valid across saves.
    pub fn clear_unlabeled(&mut self) {
        self.snapshots.retain(|s| s.label.is_some());
    }

    /// Whether there are no snapshots.
    pub fn is_empty(&self) -> bool {
        self.snapshots.is_empty()
    }

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

    /// Prune to the last `max` snapshots (keep newest).
    pub fn prune(&mut self, max: usize) {
        if self.snapshots.len() > max {
            let drop = self.snapshots.len() - max;
            self.snapshots.drain(0..drop);
        }
    }
}

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

    #[test]
    fn test_add_and_list() {
        let mut mgr = SnapshotManager::default();
        assert!(mgr.is_empty());

        let id0 = mgr.add("hash0".to_string(), 100, "main".to_string(), 5);
        let id1 = mgr.add("hash1".to_string(), 200, "feature".to_string(), 3);
        assert_eq!(id0, 0);
        assert_eq!(id1, 1);
        assert_eq!(mgr.len(), 2);

        let list = mgr.list();
        assert_eq!(list[0].commit_hash, "hash0");
        assert_eq!(list[1].branch, "feature");
    }

    #[test]
    fn test_get_by_id() {
        let mut mgr = SnapshotManager::default();
        mgr.add("hash0".to_string(), 100, "main".to_string(), 5);
        mgr.add("hash1".to_string(), 200, "feature".to_string(), 3);

        assert!(mgr.get(0).is_some());
        assert!(mgr.get(1).is_some());
        assert!(mgr.get(99).is_none());
    }

    #[test]
    fn test_clear() {
        let mut mgr = SnapshotManager::default();
        mgr.add("h".to_string(), 1, "b".to_string(), 1);
        assert!(!mgr.is_empty());
        mgr.clear();
        assert!(mgr.is_empty());
    }

    #[test]
    fn test_add_labeled_and_clear_unlabeled() {
        let mut mgr = SnapshotManager::default();
        mgr.add("auto1".to_string(), 1, "main".to_string(), 1);
        mgr.add_labeled("ckpt".to_string(), 2, "main".to_string(), 1, Some("before refactor".to_string()));
        mgr.add("auto2".to_string(), 3, "main".to_string(), 1);
        assert_eq!(mgr.len(), 3);

        // save supersedes the auto-snapshots but keeps the labeled checkpoint
        mgr.clear_unlabeled();
        assert_eq!(mgr.len(), 1);
        assert_eq!(mgr.list()[0].commit_hash, "ckpt");
        assert_eq!(mgr.list()[0].label.as_deref(), Some("before refactor"));
    }

    #[tokio::test]
    async fn test_legacy_json_without_label_loads() -> Result<()> {
        let temp = tempfile::TempDir::new()?;
        let path = temp.path().join("snapshots.json");
        std::fs::write(&path,
            r#"{"next_id":1,"snapshots":[{"id":0,"commit_hash":"h0","timestamp":1,"branch":"main","file_count":2}]}"#
        )?;
        let mgr = SnapshotManager::load(&path).await?;
        assert_eq!(mgr.len(), 1);
        assert_eq!(mgr.list()[0].label, None);
        Ok(())
    }

    #[test]
    fn test_prune_keeps_newest() {
        let mut mgr = SnapshotManager::default();
        for i in 0..25 {
            mgr.add(format!("hash{}", i), i as u64, "main".to_string(), i);
        }
        assert_eq!(mgr.len(), 25);
        mgr.prune(MAX_SNAPSHOTS);
        assert_eq!(mgr.len(), MAX_SNAPSHOTS);
        // Newest 20 should be ids 5..24
        assert_eq!(mgr.list().first().unwrap().id, 5);
        assert_eq!(mgr.list().last().unwrap().id, 24);
    }

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

        let mut mgr = SnapshotManager::default();
        mgr.add("hash0".to_string(), 100, "main".to_string(), 5);
        mgr.save(&path).await?;

        let loaded = SnapshotManager::load(&path).await?;
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded.list()[0].commit_hash, "hash0");

        Ok(())
    }

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