/**
 * Unit tests for Enterprise Certification Consensus Algorithm
 */
import { describe, it, expect } from "vitest";
import { calculateConsensus, canFinalize, getCertificationSummary } from "./consensus.js";
// Helper to create a mock finding
function createFinding(overrides = {}) {
    return {
        id: "test-001",
        severity: "medium",
        category: "test",
        description: "Test finding",
        evidence: "Test evidence",
        confidence: 80,
        verifications: [],
        created_at: new Date().toISOString(),
        ...overrides,
    };
}
// Helper to create mock agent findings
function createAgentFindings(agent, findings = []) {
    return {
        agent,
        started_at: new Date().toISOString(),
        completed_at: new Date().toISOString(),
        status: "completed",
        findings,
        summary: {
            total_findings: findings.length,
            by_severity: {
                critical: findings.filter((f) => f.severity === "critical").length,
                high: findings.filter((f) => f.severity === "high").length,
                medium: findings.filter((f) => f.severity === "medium").length,
                low: findings.filter((f) => f.severity === "low").length,
                info: findings.filter((f) => f.severity === "info").length,
            },
            confidence_score: 85,
            coverage_areas: ["test"],
        },
    };
}
// Helper to create a full certification
function createCertification(agentData = {}) {
    return {
        metadata: {
            id: "cert-test-123",
            project_name: "test-project",
            project_path: "/test/path",
            started_at: new Date().toISOString(),
            status: "in_progress",
            agents_requested: ["security", "reliability", "typesafety", "performance", "quality", "redteam"],
            agents_completed: Object.keys(agentData),
        },
        agents: agentData,
        cross_verifications: [],
        red_team_challenges: [],
    };
}
describe("calculateConsensus", () => {
    it("returns 100 score with no findings from all agents", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [createFinding({ severity: "info" })]),
            reliability: createAgentFindings("reliability", [createFinding({ severity: "info" })]),
            typesafety: createAgentFindings("typesafety", [createFinding({ severity: "info" })]),
            performance: createAgentFindings("performance", [createFinding({ severity: "info" })]),
            quality: createAgentFindings("quality", [createFinding({ severity: "info" })]),
            redteam: createAgentFindings("redteam", [createFinding({ severity: "info" })]),
        });
        const result = calculateConsensus(certification);
        // Info findings have 0 penalty, so score should be 100
        expect(result.overall_score).toBe(100);
        expect(result.certification_level).toBe("CERTIFIED");
    });
    it("penalizes critical findings heavily", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [
                createFinding({ id: "sec-001", severity: "critical", confidence: 100 }),
            ]),
        });
        const result = calculateConsensus(certification);
        // Critical penalty is 25, with 100% confidence = 25 points off
        // Score = 100 - 25 = 75
        expect(result.agent_scores.security).toBe(75);
        expect(result.by_severity.critical).toBe(1);
    });
    it("applies verification multipliers correctly", () => {
        const confirmedFinding = createFinding({
            id: "sec-001",
            severity: "high",
            confidence: 100,
            verifications: [
                { verifying_agent: "reliability", verdict: "confirmed", evidence: "confirmed", created_at: new Date().toISOString() },
                { verifying_agent: "typesafety", verdict: "confirmed", evidence: "confirmed", created_at: new Date().toISOString() },
            ],
        });
        const certification = createCertification({
            security: createAgentFindings("security", [confirmedFinding]),
        });
        const result = calculateConsensus(certification);
        // High penalty = 10, confidence = 100%, 2 confirmations = 1.4x multiplier
        // Penalty = 10 * 1.0 * 1.4 = 14
        // Score = 100 - 14 = 86
        expect(result.agent_scores.security).toBe(86);
    });
    it("reduces penalty for disputed findings", () => {
        const disputedFinding = createFinding({
            id: "sec-001",
            severity: "high",
            confidence: 100,
            verifications: [
                { verifying_agent: "reliability", verdict: "disputed", evidence: "not reproducible", created_at: new Date().toISOString() },
                { verifying_agent: "typesafety", verdict: "disputed", evidence: "false positive", created_at: new Date().toISOString() },
            ],
        });
        const certification = createCertification({
            security: createAgentFindings("security", [disputedFinding]),
        });
        const result = calculateConsensus(certification);
        // High penalty = 10, confidence = 100%, 2 disputes = 0.4x multiplier
        // Penalty = 10 * 1.0 * 0.4 = 4
        // Score = 100 - 4 = 96
        expect(result.agent_scores.security).toBe(96);
    });
    it("calculates weighted overall score", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [createFinding({ severity: "info" })]), // 100
            reliability: createAgentFindings("reliability", [createFinding({ severity: "info" })]), // 100
            typesafety: createAgentFindings("typesafety", [createFinding({ severity: "info" })]), // 100
            performance: createAgentFindings("performance", [createFinding({ severity: "info" })]), // 100
            quality: createAgentFindings("quality", [createFinding({ severity: "info" })]), // 100
            redteam: createAgentFindings("redteam", [createFinding({ severity: "info" })]), // 100
        });
        const result = calculateConsensus(certification);
        // All agents at 100, weighted average = 100
        expect(result.overall_score).toBe(100);
    });
    it("determines BLOCKED for critical findings", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [
                createFinding({ severity: "critical", confidence: 100 }),
            ]),
        });
        const result = calculateConsensus(certification);
        expect(result.certification_level).toBe("BLOCKED");
        expect(result.by_severity.critical).toBe(1);
    });
    it("determines APPROVED for high score with high findings", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [
                createFinding({ severity: "high", confidence: 50 }),
                createFinding({ severity: "info" }),
            ]),
            reliability: createAgentFindings("reliability", [createFinding({ severity: "info" })]),
            typesafety: createAgentFindings("typesafety", [createFinding({ severity: "info" })]),
            performance: createAgentFindings("performance", [createFinding({ severity: "info" })]),
            quality: createAgentFindings("quality", [createFinding({ severity: "info" })]),
            redteam: createAgentFindings("redteam", [createFinding({ severity: "info" })]),
        });
        const result = calculateConsensus(certification);
        // Should be APPROVED since there's a high finding but score is above 70
        expect(result.overall_score).toBeGreaterThanOrEqual(70);
        expect(result.certification_level).toBe("APPROVED");
    });
    it("counts total findings correctly", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [
                createFinding({ id: "sec-001" }),
                createFinding({ id: "sec-002" }),
            ]),
            reliability: createAgentFindings("reliability", [
                createFinding({ id: "rel-001" }),
            ]),
        });
        const result = calculateConsensus(certification);
        expect(result.total_findings).toBe(3);
    });
    it("gives low confidence for zero-finding agents", () => {
        const certification = createCertification({
            security: createAgentFindings("security", []), // Zero findings - suspicious
        });
        const result = calculateConsensus(certification);
        // Zero findings should result in low confidence (50)
        expect(result.agent_confidences.security).toBe(50);
    });
    it("reduces weighted score for low-confidence agents", () => {
        // Agent with zero findings (low confidence) should contribute less to overall score
        const certWithZeroFindings = createCertification({
            security: createAgentFindings("security", []), // Zero findings = 50% confidence
            reliability: createAgentFindings("reliability", [
                createFinding({ id: "rel-001", severity: "medium" }),
            ]),
        });
        // Agent with real findings (high confidence)
        const certWithFindings = createCertification({
            security: createAgentFindings("security", [
                createFinding({ id: "sec-001", severity: "info" }), // Info finding, still high confidence
            ]),
            reliability: createAgentFindings("reliability", [
                createFinding({ id: "rel-001", severity: "medium" }),
            ]),
        });
        const resultZero = calculateConsensus(certWithZeroFindings);
        const resultWithFindings = calculateConsensus(certWithFindings);
        // The certification with a zero-findings agent should have the low-confidence
        // agent contribute less weight, resulting in different overall scoring behavior
        expect(resultZero.agent_confidences.security).toBe(50);
        expect(resultWithFindings.agent_confidences.security).toBeGreaterThan(50);
    });
    it("handles empty certification gracefully", () => {
        const certification = createCertification({});
        const result = calculateConsensus(certification);
        expect(result.overall_score).toBe(0);
        expect(result.total_findings).toBe(0);
    });
});
describe("canFinalize", () => {
    it("returns ready when all requested agents completed", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [createFinding()]),
            reliability: createAgentFindings("reliability", [createFinding()]),
        });
        certification.metadata.agents_requested = ["security", "reliability"];
        certification.metadata.agents_completed = ["security", "reliability"];
        const result = canFinalize(certification);
        expect(result.ready).toBe(true);
        expect(result.missing).toHaveLength(0);
    });
    it("returns not ready when agents missing", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [createFinding()]),
        });
        certification.metadata.agents_requested = ["security", "reliability"];
        certification.metadata.agents_completed = ["security"];
        const result = canFinalize(certification);
        expect(result.ready).toBe(false);
        expect(result.missing).toContain("Agent reliability not completed");
    });
    it("requires cross-verification for critical findings", () => {
        const certification = createCertification({
            security: createAgentFindings("security", [
                createFinding({ id: "sec-001", severity: "critical", verifications: [] }),
            ]),
        });
        certification.metadata.agents_requested = ["security"];
        certification.metadata.agents_completed = ["security"];
        const result = canFinalize(certification);
        expect(result.ready).toBe(false);
        expect(result.missing).toContain("Critical finding sec-001 not cross-verified");
    });
    it("warns about zero-finding agents", () => {
        const certification = createCertification({
            security: createAgentFindings("security", []),
        });
        certification.metadata.agents_requested = ["security"];
        certification.metadata.agents_completed = ["security"];
        const result = canFinalize(certification);
        expect(result.warnings).toContain("Agent security reported zero findings - audit may be incomplete");
    });
    it("warns when total findings is zero", () => {
        const certification = createCertification({
            security: createAgentFindings("security", []),
            reliability: createAgentFindings("reliability", []),
        });
        certification.metadata.agents_requested = ["security", "reliability"];
        certification.metadata.agents_completed = ["security", "reliability"];
        const result = canFinalize(certification);
        expect(result.warnings).toContain("No findings across all agents - certification may not be trustworthy");
    });
});
describe("getCertificationSummary", () => {
    it("formats summary correctly", () => {
        const consensus = {
            overall_score: 85,
            certification_level: "APPROVED",
            agent_scores: {
                security: 80,
                reliability: 90,
                typesafety: 85,
                performance: 88,
                quality: 82,
                redteam: 95,
                "agent-redteam": 0,
                "agent-privacy": 0,
                "agent-integrity": 0,
                adversary: 0,
                antagonist: 0,
            },
            agent_confidences: {
                security: 90,
                reliability: 88,
                typesafety: 85,
                performance: 92,
                quality: 80,
                redteam: 95,
                "agent-redteam": 0,
                "agent-privacy": 0,
                antagonist: 0,
                "agent-integrity": 0,
                adversary: 0,
            },
            total_findings: 15,
            by_severity: {
                critical: 0,
                high: 2,
                medium: 5,
                low: 5,
                info: 3,
            },
            cross_verification_rate: 0.8,
            red_team_challenges_accepted: 1,
            red_team_challenges_total: 3,
            calculated_at: new Date().toISOString(),
        };
        const summary = getCertificationSummary(consensus);
        expect(summary).toContain("APPROVED");
        expect(summary).toContain("Score: 85/100");
        expect(summary).toContain("Findings: 15");
        expect(summary).toContain("Critical: 0");
        expect(summary).toContain("High: 2");
        expect(summary).toContain("Cross-verification: 80%");
        expect(summary).toContain("Red team: 1/3");
    });
    it("uses correct emoji for each level", () => {
        const baseConsensus = {
            overall_score: 0,
            certification_level: "BLOCKED",
            agent_scores: {},
            agent_confidences: {},
            total_findings: 0,
            by_severity: { critical: 0, high: 0, medium: 0, low: 0, info: 0 },
            cross_verification_rate: 0,
            red_team_challenges_accepted: 0,
            red_team_challenges_total: 0,
            calculated_at: new Date().toISOString(),
        };
        expect(getCertificationSummary({ ...baseConsensus, certification_level: "CERTIFIED" }))
            .toContain("\uD83D\uDFE2");
        expect(getCertificationSummary({ ...baseConsensus, certification_level: "APPROVED" }))
            .toContain("\uD83D\uDFE1");
        expect(getCertificationSummary({ ...baseConsensus, certification_level: "REVIEW_REQUIRED" }))
            .toContain("\uD83D\uDFE0");
        expect(getCertificationSummary({ ...baseConsensus, certification_level: "BLOCKED" }))
            .toContain("\uD83D\uDD34");
    });
});
//# sourceMappingURL=consensus.test.js.map