codive-core 0.1.0

Core types, traits, and utilities for Codive
Documentation
//! Verification types
//!
//! This module provides types for verification results. The actual verification
//! logic is handled by the AI agent through prompts - the AI uses tools to
//! discover project type and run appropriate build/test commands.
//!
//! # AI-Driven Verification
//!
//! Instead of hardcoded verification logic, the system prompt instructs the AI to:
//! 1. Identify project type by reading manifest files (Cargo.toml, package.json, etc.)
//! 2. Run appropriate build/check commands after making code changes
//! 3. Fix any errors and re-run until the build passes
//! 4. Only report success when code compiles successfully

use std::time::Duration;

/// Result of running a single verification command
#[derive(Debug, Clone)]
pub struct VerificationResult {
    /// Name of the verification step (e.g., "build", "test", "lint")
    pub name: String,

    /// The command that was executed
    pub command: String,

    /// Whether the verification passed (exit code 0)
    pub passed: bool,

    /// Combined stdout/stderr output
    pub output: String,

    /// Exit code if available
    pub exit_code: Option<i32>,

    /// How long the command took to run
    pub duration: Duration,
}

impl VerificationResult {
    /// Create a passed result
    pub fn passed(name: impl Into<String>, command: impl Into<String>, output: String, duration: Duration) -> Self {
        Self {
            name: name.into(),
            command: command.into(),
            passed: true,
            output,
            exit_code: Some(0),
            duration,
        }
    }

    /// Create a failed result
    pub fn failed(
        name: impl Into<String>,
        command: impl Into<String>,
        output: String,
        exit_code: Option<i32>,
        duration: Duration,
    ) -> Self {
        Self {
            name: name.into(),
            command: command.into(),
            passed: false,
            output,
            exit_code,
            duration,
        }
    }
}

/// Format verification failures into a message
pub fn format_verification_errors(results: &[VerificationResult]) -> String {
    let failed: Vec<_> = results.iter().filter(|r| !r.passed).collect();

    if failed.is_empty() {
        return String::new();
    }

    let mut message = String::new();

    for result in failed {
        message.push_str(&format!(
            "VERIFICATION FAILED: {}\n\n",
            result.name.to_uppercase()
        ));
        message.push_str(&format!("Command: $ {}\n", result.command));

        if let Some(code) = result.exit_code {
            message.push_str(&format!("Exit code: {}\n", code));
        }

        message.push_str("\nOutput:\n```\n");
        message.push_str(&result.output);
        message.push_str("\n```\n\n");
    }

    message.push_str("Please fix the errors above and try again.");

    message
}

/// Format a verification status message
pub fn format_verification_status(attempt: u32, max_attempts: u32, results: &[VerificationResult]) -> String {
    let failed_count = results.iter().filter(|r| !r.passed).count();

    if failed_count == 0 {
        "All verification checks passed".to_string()
    } else {
        format!(
            "Verification failed (attempt {}/{}): {} check(s) failed",
            attempt, max_attempts, failed_count
        )
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_verification_result_creation() {
        let passed = VerificationResult::passed(
            "build",
            "cargo build",
            "Compiling...".to_string(),
            Duration::from_secs(5),
        );
        assert!(passed.passed);
        assert_eq!(passed.exit_code, Some(0));

        let failed = VerificationResult::failed(
            "test",
            "cargo test",
            "test failed".to_string(),
            Some(1),
            Duration::from_secs(10),
        );
        assert!(!failed.passed);
        assert_eq!(failed.exit_code, Some(1));
    }

    #[test]
    fn test_format_verification_errors() {
        let results = vec![
            VerificationResult::passed("build", "cargo build", "ok".to_string(), Duration::from_secs(1)),
            VerificationResult::failed(
                "test",
                "cargo test",
                "error: test failed".to_string(),
                Some(1),
                Duration::from_secs(2),
            ),
        ];

        let message = format_verification_errors(&results);

        assert!(message.contains("VERIFICATION FAILED: TEST"));
        assert!(message.contains("cargo test"));
        assert!(message.contains("error: test failed"));
        assert!(message.contains("Exit code: 1"));
        assert!(message.contains("Please fix the errors"));
    }

    #[test]
    fn test_format_verification_errors_empty() {
        let results = vec![
            VerificationResult::passed("build", "cargo build", "ok".to_string(), Duration::from_secs(1)),
        ];

        let message = format_verification_errors(&results);
        assert!(message.is_empty());
    }

    #[test]
    fn test_format_verification_status() {
        let failed_results = vec![
            VerificationResult::failed("build", "cargo build", "error".to_string(), Some(1), Duration::from_secs(1)),
        ];

        let status = format_verification_status(1, 3, &failed_results);
        assert!(status.contains("attempt 1/3"));
        assert!(status.contains("1 check(s) failed"));

        let passed_results = vec![
            VerificationResult::passed("build", "cargo build", "ok".to_string(), Duration::from_secs(1)),
        ];

        let status = format_verification_status(1, 3, &passed_results);
        assert!(status.contains("passed"));
    }
}