codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
use crate::error::{Context, Result};
use crate::provenance::{ProvenanceEntry, ProvenanceLog};
use crate::vcs::VcsManager;

/// Everything `codetree why` reports about a file (or file:line).
#[derive(Debug, Clone, serde::Serialize)]
pub struct WhyInfo {
    pub file: String,
    /// 1-based line number, when the target was `path:line`.
    pub line: Option<usize>,
    /// Full commit hash that introduced the file (or line).
    pub commit: String,
    pub timestamp: i64,
    pub message: String,
    /// Operation (branch) that produced the commit, from the provenance sidecar.
    pub operation: Option<String>,
    /// Agent that produced the commit, if known.
    pub agent_id: Option<String>,
    /// Prompt/intent that produced the commit, if captured via `save --prompt`.
    pub prompt: Option<String>,
}

/// Parse `path` or `path:line` (1-based). The suffix counts as a line number
/// only when it parses as a positive integer — Windows drive prefixes
/// (`C:\...`) don't parse, so they stay part of the path.
pub fn parse_target(target: &str) -> (String, Option<usize>) {
    match target.rsplit_once(':') {
        Some((path, suffix)) if !path.is_empty() => match suffix.parse::<usize>() {
            Ok(n) if n > 0 => (path.to_string(), Some(n)),
            _ => (target.to_string(), None),
        },
        _ => (target.to_string(), None),
    }
}

/// Resolve provenance for a file or file:line.
/// With a line number: blame finds the commit that introduced that line.
/// Without: the newest commit that touched the file (file_log).
pub async fn lookup_why(
    manager: &VcsManager,
    provenance: &ProvenanceLog,
    target: &str,
) -> Result<WhyInfo> {
    let (file, line) = parse_target(target);
    let branch = manager.get_current_branch().await?;
    let history = manager.get_commit_history(&branch, usize::MAX)?;

    let commit_info = if let Some(line_no) = line {
        let annotations = manager.blame(&file)?;
        let short = annotations
            .iter()
            .find(|(l, _, _)| *l == line_no)
            .map(|(_, c, _)| c.clone())
            .ok_or_else(|| format!("Line {} not found in '{}'", line_no, file))?;
        history
            .iter()
            .find(|c| c.hash.starts_with(&short))
            .cloned()
            .ok_or_else(|| format!("Commit '{}' not found in history", short))?
    } else {
        let file_hist = manager.file_log(&file)?;
        let (newest, _, _) = file_hist
            .first()
            .cloned()
            .ok_or_else(|| format!("No history found for '{}'", file))?;
        history
            .iter()
            .find(|c| c.hash == newest)
            .cloned()
            .ok_or_else(|| format!("Commit '{}' not found in history", newest))?
    };

    let entry: Option<ProvenanceEntry> = provenance.get(&commit_info.hash).cloned();

    Ok(WhyInfo {
        operation: entry.as_ref().map(|e| e.operation.clone()),
        agent_id: entry.as_ref().and_then(|e| e.agent_id.clone()),
        prompt: entry.as_ref().and_then(|e| e.prompt.clone()),
        file,
        line,
        commit: commit_info.hash,
        timestamp: commit_info.timestamp,
        message: commit_info.message,
    })
}

/// Show provenance for a file or line: which commit, operation, agent, and
/// prompt produced it (TODO Round 13: prompt/intent provenance).
pub async fn why_command(target: String) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let provenance = ProvenanceLog::load(&current_dir)?;

    let info = lookup_why(&git_manager, &provenance, &target).await?;

    let short = &info.commit[..7.min(info.commit.len())];
    let location = match info.line {
        Some(l) => format!("{}:{}", info.file, l),
        None => info.file.clone(),
    };
    println!("File: {}", location);
    println!("Commit: {} ({})", short, format_ts(info.timestamp));
    println!("Message: {}", info.message.lines().next().unwrap_or(""));
    match &info.operation {
        Some(op) => println!("Operation: {}", op),
        None => println!("Operation: (unrecorded)"),
    }
    match &info.agent_id {
        Some(a) => println!("Agent: {}", a),
        None => println!("Agent: (unrecorded)"),
    }
    match &info.prompt {
        Some(p) => println!("Prompt: {}", p),
        None => println!("Prompt: (not captured — save with --prompt to record intent)"),
    }

    Ok(())
}

/// Format a Unix timestamp (seconds) as YYYY-MM-DD HH:MM without chrono
/// (same approach as `format_timestamp` in commands/status.rs).
fn format_ts(ts: i64) -> String {
    let secs = ts.max(0) as u64;
    let days = secs / 86400;
    let time = secs % 86400;
    // Civil-from-days (Howard Hinnant's algorithm)
    let z = days as i64 + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!(
        "{:04}-{:02}-{:02} {:02}:{:02}",
        y,
        m,
        d,
        time / 3600,
        (time % 3600) / 60
    )
}