codetree 0.1.2

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

/// Provenance entry: which operation, agent, and prompt produced a commit.
///
/// Stored in a sidecar (`.codetree/provenance.json`) keyed by commit hash —
/// **never** inside the hashed commit object. SHA-1 content addressing is the
/// Git-compatibility contract (`hash_object` in `src/vcs/objects.rs`); adding
/// fields to the commit would break `export`/`import` object mapping.
///
/// Competitive context (TODO Round 13, MEMORY.md §6): Merget/Regent/Supafork
/// made "which prompt wrote this line" the core question for agent-written
/// code. The sidecar answers it without touching the object format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceEntry {
    /// Full commit hash this entry describes.
    pub commit: String,
    /// Operation (branch) name the commit was saved to.
    pub operation: String,
    /// Agent that created the commit, if known (`start --agent`).
    pub agent_id: Option<String>,
    /// The prompt/intent that produced the commit (`save --prompt`).
    pub prompt: Option<String>,
    /// Unix timestamp (seconds).
    pub timestamp: u64,
}

/// Provenance log: commit hashes → provenance entries.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProvenanceLog {
    pub entries: Vec<ProvenanceEntry>,
}

impl ProvenanceLog {
    /// Load the provenance log from `.codetree/provenance.json`.
    /// Missing file → empty log (provenance is optional metadata).
    pub fn load(root: &Path) -> Result<Self> {
        let path = root.join(".codetree").join("provenance.json");
        if path.exists() {
            let content = std::fs::read_to_string(&path)?;
            Ok(serde_json::from_str(&content)?)
        } else {
            Ok(Self::default())
        }
    }

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

    /// Record provenance for a commit. Replaces any existing entry for the
    /// same commit (e.g. branchless amend) so the log stays one entry per
    /// commit hash.
    pub fn record(
        &mut self,
        commit: &str,
        operation: &str,
        agent_id: Option<String>,
        prompt: Option<String>,
    ) {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let entry = ProvenanceEntry {
            commit: commit.to_string(),
            operation: operation.to_string(),
            agent_id,
            prompt,
            timestamp,
        };
        match self.entries.iter_mut().find(|e| e.commit == entry.commit) {
            Some(existing) => *existing = entry,
            None => self.entries.push(entry),
        }
    }

    /// Look up an entry by full **or** abbreviated commit hash — `blame`
    /// returns 7-character prefixes, so prefix lookup must work.
    pub fn get(&self, commit: &str) -> Option<&ProvenanceEntry> {
        self.entries
            .iter()
            .find(|e| e.commit == commit)
            .or_else(|| self.entries.iter().find(|e| e.commit.starts_with(commit)))
    }
}

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

    #[test]
    fn test_record_and_get_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let mut log = ProvenanceLog::default();
        log.record(
            "aabbccdd",
            "codetree_op_fix_login",
            Some("agent-1".to_string()),
            Some("fix the login bug".to_string()),
        );
        log.record("ddeeff00", "codetree_op_fix_login", None, None);
        log.save(tmp.path()).unwrap();

        let loaded = ProvenanceLog::load(tmp.path()).unwrap();
        assert_eq!(loaded.entries.len(), 2);

        let e = loaded.get("aabbccdd").unwrap();
        assert_eq!(e.operation, "codetree_op_fix_login");
        assert_eq!(e.agent_id.as_deref(), Some("agent-1"));
        assert_eq!(e.prompt.as_deref(), Some("fix the login bug"));

        // blame returns 7-char prefixes — prefix lookup must work
        assert!(loaded.get("ddeeff").is_some());
        assert!(loaded.get("1234").is_none());
    }

    #[test]
    fn test_record_replaces_same_commit() {
        let mut log = ProvenanceLog::default();
        log.record("aabbccdd", "op1", None, Some("first".to_string()));
        log.record("aabbccdd", "op1", None, Some("amended".to_string()));
        assert_eq!(log.entries.len(), 1);
        assert_eq!(log.entries[0].prompt.as_deref(), Some("amended"));
    }

    #[test]
    fn test_load_missing_returns_default() {
        let tmp = tempfile::tempdir().unwrap();
        let log = ProvenanceLog::load(tmp.path()).unwrap();
        assert!(log.entries.is_empty());
    }
}