codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
//! Operation log for undo/redo support.

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

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Operation {
    Start { branch: String, timestamp: u64, agent_id: Option<String> },
    Save { branch: String, message: String, timestamp: u64 },
    Merge { branch: String, into: String, timestamp: u64 },
    Withdraw { branch: String, timestamp: u64 },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperationLog {
    ops: Vec<Operation>,
    #[serde(default)]
    redo_stack: Vec<Operation>,
}

impl OperationLog {
    pub async fn new(path: &std::path::Path) -> Result<Self> {
        if path.exists() {
            let content = fs::read_to_string(path)
                .await
                .with_context(|| format!("Failed to read operation log: {:?}", path))?;
            let log: Self = serde_json::from_str(&content)
                .with_context(|| format!("Failed to parse operation log: {:?}", path))?;
            Ok(log)
        } else {
            Ok(Self { ops: Vec::new(), redo_stack: Vec::new() })
        }
    }

    pub async fn save(&self, path: &std::path::Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).await
                .with_context(|| format!("Failed to create ops directory: {:?}", parent))?;
        }
        let content = serde_json::to_string_pretty(self)
            .context("Failed to serialize operation log")?;
        crate::atomic::write_atomic(path, content.as_bytes())
            .with_context(|| format!("Failed to write operation log: {:?}", path))?;
        Ok(())
    }

    pub fn push(&mut self, op: Operation) {
        self.redo_stack.clear();
        self.ops.push(op);
    }

    /// Push an operation without clearing the redo stack (used by redo itself).
    pub fn push_no_clear(&mut self, op: Operation) {
        self.ops.push(op);
    }

    pub fn last(&self) -> Option<&Operation> {
        self.ops.last()
    }

    pub fn pop(&mut self) -> Option<Operation> {
        self.ops.pop()
    }

    pub fn is_empty(&self) -> bool {
        self.ops.is_empty()
    }

    pub fn len(&self) -> usize {
        self.ops.len()
    }

    pub fn iter(&self) -> impl Iterator<Item = (usize, &Operation)> {
        self.ops.iter().enumerate()
    }

    pub fn get(&self, index: usize) -> Option<&Operation> {
        self.ops.get(index)
    }

    pub fn remove(&mut self, index: usize) -> Option<Operation> {
        if index < self.ops.len() {
            Some(self.ops.remove(index))
        } else {
            None
        }
    }

    /// Push an operation onto the redo stack
    pub fn push_redo(&mut self, op: Operation) {
        self.redo_stack.push(op);
    }

    /// Pop an operation from the redo stack
    pub fn pop_redo(&mut self) -> Option<Operation> {
        self.redo_stack.pop()
    }

    /// Remove an operation from the redo stack at the given index (0-based, oldest first)
    pub fn remove_redo(&mut self, index: usize) -> Option<Operation> {
        if index < self.redo_stack.len() {
            Some(self.redo_stack.remove(index))
        } else {
            None
        }
    }

    /// Check if the redo stack is empty
    pub fn is_redo_empty(&self) -> bool {
        self.redo_stack.is_empty()
    }

    /// Get the number of redoable operations
    pub fn redo_len(&self) -> usize {
        self.redo_stack.len()
    }

    /// Iterate over the redo stack
    pub fn redo_iter(&self) -> impl Iterator<Item = (usize, &Operation)> {
        self.redo_stack.iter().enumerate()
    }

    /// Clear the redo stack (called when a new operation is pushed)
    pub fn clear_redo(&mut self) {
        self.redo_stack.clear();
    }
}

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

    #[tokio::test]
    async fn test_operation_log_new_empty() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("nonexistent.json");
        let log = OperationLog::new(&path).await.unwrap();
        assert!(log.is_empty());
        assert_eq!(log.len(), 0);
    }

    #[tokio::test]
    async fn test_operation_log_push_and_last() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("ops.json");
        let mut log = OperationLog::new(&path).await.unwrap();

        log.push(Operation::Start {
            branch: "feature-test".to_string(),
            timestamp: 1000,
            agent_id: None,
        });
        assert_eq!(log.len(), 1);

        let last = log.last().unwrap();
        match last {
            Operation::Start { branch, timestamp, .. } => {
                assert_eq!(branch, "feature-test");
                assert_eq!(*timestamp, 1000);
            }
            _ => panic!("Expected Start operation"),
        }
    }

    #[tokio::test]
    async fn test_operation_log_save_and_load() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("ops.json");
        let mut log = OperationLog::new(&path).await.unwrap();

        log.push(Operation::Save {
            branch: "feature".to_string(),
            message: "test commit".to_string(),
            timestamp: 2000,
        });
        log.save(&path).await.unwrap();

        let loaded = OperationLog::new(&path).await.unwrap();
        assert_eq!(loaded.len(), 1);
        match loaded.last().unwrap() {
            Operation::Save { branch, message, timestamp } => {
                assert_eq!(branch, "feature");
                assert_eq!(message, "test commit");
                assert_eq!(*timestamp, 2000);
            }
            _ => panic!("Expected Save operation"),
        }
    }

    #[tokio::test]
    async fn test_operation_log_pop() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().join("ops.json");
        let mut log = OperationLog::new(&path).await.unwrap();

        log.push(Operation::Start { branch: "a".to_string(), timestamp: 1, agent_id: None });
        log.push(Operation::Start { branch: "b".to_string(), timestamp: 2, agent_id: None });

        let popped = log.pop().unwrap();
        match popped {
            Operation::Start { branch, .. } => assert_eq!(branch, "b"),
            _ => panic!("Expected Start"),
        }
        assert_eq!(log.len(), 1);
    }
}