/**
 * Integration tests for the full certification flow
 */
import { describe, it, expect, beforeEach, afterEach, afterAll } from "vitest";
import { mkdir, rm } from "fs/promises";
import { join } from "path";
import { tmpdir } from "os";
import { generateCertificationId, initializeCertification, startAgent, submitFinding, completeAgent, addCrossVerification, getCertification, saveConsensus, finalizeCertification, } from "../../certification/store.js";
import { calculateConsensus, canFinalize, getCertificationSummary } from "../../certification/consensus.js";
const TEST_BASE = join(tmpdir(), "vaspera-integration-" + Date.now() + "-" + Math.random().toString(36).slice(2));
let testProjectPath;
beforeEach(async () => {
    testProjectPath = join(TEST_BASE, "project-" + Math.random().toString(36).slice(2));
    await mkdir(testProjectPath, { recursive: true });
});
afterEach(async () => {
    try {
        await rm(testProjectPath, { recursive: true, force: true });
    }
    catch {
        // Ignore cleanup errors
    }
});
afterAll(async () => {
    try {
        await rm(TEST_BASE, { recursive: true, force: true });
    }
    catch {
        // Ignore cleanup errors
    }
});
describe("Full Certification Flow", () => {
    it("completes a multi-agent certification", async () => {
        const certId = generateCertificationId(testProjectPath);
        const agents = ["security", "reliability", "quality"];
        // Phase 1: Initialize
        const metadata = await initializeCertification(testProjectPath, certId, [...agents]);
        expect(metadata.status).toBe("in_progress");
        expect(metadata.agents_requested).toEqual([...agents]);
        // Phase 2: Run agents
        for (const agent of agents) {
            await startAgent(testProjectPath, certId, agent);
            // Submit findings
            await submitFinding(testProjectPath, certId, agent, {
                id: `${agent.slice(0, 3)}-001`,
                severity: "medium",
                category: "test",
                description: `Test finding from ${agent}`,
                evidence: "Integration test evidence",
                confidence: 80,
            });
            await completeAgent(testProjectPath, certId, agent, {
                total_findings: 1,
                by_severity: { critical: 0, high: 0, medium: 1, low: 0, info: 0 },
                confidence_score: 80,
                coverage_areas: ["test"],
            });
        }
        // Phase 3: Cross-verification
        await addCrossVerification(testProjectPath, certId, {
            finding_id: "sec-001",
            verifying_agent: "reliability",
            verdict: "confirmed",
            evidence: "Verified during reliability scan",
        });
        // Phase 4: Calculate consensus
        const cert = await getCertification(testProjectPath, certId);
        expect(cert).not.toBeNull();
        const consensus = calculateConsensus(cert);
        expect(consensus.total_findings).toBe(3);
        expect(consensus.overall_score).toBeGreaterThan(0);
        // Phase 5: Check finalization readiness
        const { ready, missing, warnings } = canFinalize(cert);
        expect(ready).toBe(true);
        expect(missing).toHaveLength(0);
        // Phase 6: Save consensus and finalize
        await saveConsensus(testProjectPath, certId, consensus);
        const finalMetadata = await finalizeCertification(testProjectPath, certId, consensus.certification_level, consensus.overall_score);
        expect(finalMetadata.status).toBe("completed");
        expect(finalMetadata.final_score).toBe(consensus.overall_score);
        expect(finalMetadata.expires_at).toBeDefined();
        // Phase 7: Generate summary
        const summary = getCertificationSummary(consensus);
        expect(summary).toContain("Score:");
        expect(summary).toContain("Findings:");
    });
    it("handles critical findings requiring cross-verification", async () => {
        const certId = generateCertificationId(testProjectPath);
        await initializeCertification(testProjectPath, certId, ["security"]);
        await startAgent(testProjectPath, certId, "security");
        // Submit a critical finding
        await submitFinding(testProjectPath, certId, "security", {
            id: "sec-001",
            severity: "critical",
            category: "auth",
            description: "Missing authentication",
            evidence: "No auth check on endpoint",
            confidence: 95,
        });
        await completeAgent(testProjectPath, certId, "security", {
            total_findings: 1,
            by_severity: { critical: 1, high: 0, medium: 0, low: 0, info: 0 },
            confidence_score: 95,
            coverage_areas: ["auth"],
        });
        const cert = await getCertification(testProjectPath, certId);
        const { ready, missing } = canFinalize(cert);
        // Critical finding without cross-verification blocks finalization
        expect(ready).toBe(false);
        expect(missing).toContain("Critical finding sec-001 not cross-verified");
        // After cross-verification, should be ready
        await addCrossVerification(testProjectPath, certId, {
            finding_id: "sec-001",
            verifying_agent: "reliability",
            verdict: "confirmed",
            evidence: "Confirmed - auth is missing",
        });
        const certAfter = await getCertification(testProjectPath, certId);
        const { ready: readyAfter } = canFinalize(certAfter);
        expect(readyAfter).toBe(true);
    });
    it("calculates weighted scores correctly", async () => {
        const certId = generateCertificationId(testProjectPath);
        const agents = ["security", "reliability", "typesafety", "performance", "quality", "redteam"];
        await initializeCertification(testProjectPath, certId, [...agents]);
        // Security (30% weight) - has critical issue
        await startAgent(testProjectPath, certId, "security");
        await submitFinding(testProjectPath, certId, "security", {
            id: "sec-001",
            severity: "high",
            category: "auth",
            description: "High severity auth issue",
            evidence: "Auth vulnerability",
            confidence: 90,
        });
        await completeAgent(testProjectPath, certId, "security", {
            total_findings: 1,
            by_severity: { critical: 0, high: 1, medium: 0, low: 0, info: 0 },
            confidence_score: 90,
            coverage_areas: ["auth"],
        });
        // Other agents - clean
        for (const agent of ["reliability", "typesafety", "performance", "quality", "redteam"]) {
            await startAgent(testProjectPath, certId, agent);
            await submitFinding(testProjectPath, certId, agent, {
                id: `${agent.slice(0, 3)}-001`,
                severity: "info",
                category: "test",
                description: "Informational only",
                evidence: "No issues",
                confidence: 100,
            });
            await completeAgent(testProjectPath, certId, agent, {
                total_findings: 1,
                by_severity: { critical: 0, high: 0, medium: 0, low: 0, info: 1 },
                confidence_score: 100,
                coverage_areas: [],
            });
        }
        const cert = await getCertification(testProjectPath, certId);
        const consensus = calculateConsensus(cert);
        // Security has high finding (10 point penalty * 0.9 confidence = 9 point penalty)
        // Security score: 100 - 9 = 91
        // Other agents: 100 (info has 0 penalty)
        // Weighted: (91 * 0.30) + (100 * 0.25) + (100 * 0.15) + (100 * 0.15) + (100 * 0.10) + (100 * 0.05)
        //         = 27.3 + 25 + 15 + 15 + 10 + 5 = 97.3 ≈ 97 (rounded)
        expect(consensus.overall_score).toBeGreaterThanOrEqual(95);
        expect(consensus.overall_score).toBeLessThanOrEqual(98);
        expect(consensus.by_severity.high).toBe(1);
    });
});
describe("Certification Levels", () => {
    it("assigns BLOCKED for critical findings", async () => {
        const certId = generateCertificationId(testProjectPath);
        await initializeCertification(testProjectPath, certId, ["security"]);
        await startAgent(testProjectPath, certId, "security");
        await submitFinding(testProjectPath, certId, "security", {
            id: "sec-001",
            severity: "critical",
            category: "auth",
            description: "Critical vulnerability",
            evidence: "SQL injection",
            confidence: 100,
        });
        await completeAgent(testProjectPath, certId, "security", {
            total_findings: 1,
            by_severity: { critical: 1, high: 0, medium: 0, low: 0, info: 0 },
            confidence_score: 100,
            coverage_areas: [],
        });
        const cert = await getCertification(testProjectPath, certId);
        const consensus = calculateConsensus(cert);
        expect(consensus.certification_level).toBe("BLOCKED");
    });
    it("assigns APPROVED for good score with high findings", async () => {
        const certId = generateCertificationId(testProjectPath);
        await initializeCertification(testProjectPath, certId, ["security", "reliability"]);
        // Security with high finding
        await startAgent(testProjectPath, certId, "security");
        await submitFinding(testProjectPath, certId, "security", {
            id: "sec-001",
            severity: "high",
            category: "auth",
            description: "High severity issue",
            evidence: "Needs attention",
            confidence: 70,
        });
        await submitFinding(testProjectPath, certId, "security", {
            id: "sec-002",
            severity: "info",
            category: "logging",
            description: "Consider adding logs",
            evidence: "Suggestion",
            confidence: 50,
        });
        await completeAgent(testProjectPath, certId, "security", {
            total_findings: 2,
            by_severity: { critical: 0, high: 1, medium: 0, low: 0, info: 1 },
            confidence_score: 60,
            coverage_areas: [],
        });
        // Reliability clean
        await startAgent(testProjectPath, certId, "reliability");
        await submitFinding(testProjectPath, certId, "reliability", {
            id: "rel-001",
            severity: "info",
            category: "test",
            description: "All good",
            evidence: "Clean audit",
            confidence: 100,
        });
        await completeAgent(testProjectPath, certId, "reliability", {
            total_findings: 1,
            by_severity: { critical: 0, high: 0, medium: 0, low: 0, info: 1 },
            confidence_score: 100,
            coverage_areas: [],
        });
        const cert = await getCertification(testProjectPath, certId);
        const consensus = calculateConsensus(cert);
        // Score should be >= 70 but < 90 due to high finding
        expect(consensus.certification_level).toBe("APPROVED");
        expect(consensus.by_severity.high).toBe(1);
    });
});
//# sourceMappingURL=certification-flow.test.js.map