codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Evolution log entry: tracks how a commit was rewritten.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EvologEntry {
    /// The new commit hash (after rewrite).
    pub new_hash: String,
    /// The old commit hash (before rewrite).
    pub old_hash: String,
    /// What operation caused the rewrite.
    pub operation: String,
    /// Timestamp of the rewrite.
    pub timestamp: u64,
}

/// Evolution log: maps commit hashes to their predecessor chains.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EvologLog {
    /// Maps a new commit hash to its predecessor.
    pub entries: Vec<EvologEntry>,
}

impl EvologLog {
    /// Load the evolution log from `.codetree/evolog.json`.
    pub fn load(root: &Path) -> Result<Self> {
        let path = root.join(".codetree").join("evolog.json");
        if path.exists() {
            let content = std::fs::read_to_string(&path)?;
            Ok(serde_json::from_str(&content)?)
        } else {
            Ok(Self::default())
        }
    }

    /// Save the evolution log to `.codetree/evolog.json`.
    pub fn save(&self, root: &Path) -> Result<()> {
        let path = root.join(".codetree").join("evolog.json");
        crate::atomic::write_atomic(&path, serde_json::to_string_pretty(self)?.as_bytes())?;
        Ok(())
    }

    /// Record a commit rewrite.
    pub fn record(&mut self, old_hash: &str, new_hash: &str, operation: &str) {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        self.entries.push(EvologEntry {
            new_hash: new_hash.to_string(),
            old_hash: old_hash.to_string(),
            operation: operation.to_string(),
            timestamp,
        });
    }

    /// Get the evolution history for a commit (predecessors).
    pub fn history(&self, commit: &str) -> Vec<&EvologEntry> {
        let mut result = Vec::new();
        let mut current = commit.to_string();
        while let Some(entry) = self.entries.iter().find(|e| e.new_hash == current) {
            result.push(entry);
            current = entry.old_hash.clone();
        }
        result
    }
}