/**
 * Integration test for Antagonist Agent
 * Tests the full pipeline on sample findings
 */
import { describe, it, expect } from "vitest";
import { synthesizeNarrativesDeterministic } from "../agents/antagonist/synthesizer.js";
import { runChallengerDeterministic } from "../agents/antagonist/challenger.js";
import { prioritizeRemediations } from "../agents/antagonist/prioritizer.js";
import { DEFAULT_ANTAGONIST_CONFIG } from "../agents/antagonist/types.js";
// Sample findings that represent real security issues
const sampleFindings = [
    {
        id: "find-001",
        severity: "high",
        category: "command-injection",
        description: "Potential command injection via unsanitized user input",
        evidence: "spawn(cmd, [userInput])",
        confidence: 85,
        verifications: [],
        created_at: new Date().toISOString(),
        file: "src/scanners/custom.ts",
        line: 42,
    },
    {
        id: "find-002",
        severity: "medium",
        category: "hardcoded-secret",
        description: "Hardcoded API key detected",
        evidence: "const API_KEY = 'sk-...'",
        confidence: 90,
        verifications: [],
        created_at: new Date().toISOString(),
        file: "src/config.ts",
        line: 15,
    },
    {
        id: "find-003",
        severity: "high",
        category: "auth-bypass",
        description: "Missing authentication check on admin endpoint",
        evidence: "No auth middleware on /admin route",
        confidence: 75,
        verifications: [],
        created_at: new Date().toISOString(),
        file: "src/routes/admin.ts",
        line: 8,
    },
    {
        id: "find-004",
        severity: "critical",
        category: "sql-injection",
        description: "SQL injection vulnerability in query builder",
        evidence: "db.query(`SELECT * FROM users WHERE id = ${userId}`)",
        confidence: 95,
        verifications: [],
        created_at: new Date().toISOString(),
        file: "src/db/queries.ts",
        line: 22,
    },
    {
        id: "find-005",
        severity: "low",
        category: "xss",
        description: "Potential XSS in user-generated content",
        evidence: "innerHTML = userContent",
        confidence: 60,
        verifications: [],
        created_at: new Date().toISOString(),
        file: "src/components/Comment.tsx",
        line: 55,
    },
];
// Sample exploit chains (matching ExploitChain type)
const sampleChains = [
    {
        id: "chain-001",
        name: "Auth Bypass to Data Exfil",
        steps: [
            {
                findingId: "find-003",
                finding: sampleFindings[2],
                role: "entry",
                enables: "find-004",
                techniques: ["T1190"],
            },
            {
                findingId: "find-004",
                finding: sampleFindings[3],
                role: "target",
                prerequisite: "find-003",
                techniques: ["T1213"],
            },
        ],
        totalSeverity: "critical",
        originalSeverities: ["high", "critical"],
        confidence: 85,
        attackScenario: "Attacker bypasses auth, then exfiltrates data via SQL injection",
        mitreAttackIds: ["T1190", "T1213"],
        impact: "Data breach - full database access",
        difficulty: "easy",
    },
];
// Agent summaries
const agentSummaries = {
    security: { completed: true, findingCount: 5 },
    reliability: { completed: true, findingCount: 2 },
    typesafety: { completed: true, findingCount: 1 },
    performance: { completed: true, findingCount: 0 },
    quality: { completed: true, findingCount: 3 },
    redteam: { completed: true, findingCount: 1 },
    "agent-redteam": { completed: false, findingCount: 0 },
    "agent-privacy": { completed: false, findingCount: 0 },
    "agent-integrity": { completed: false, findingCount: 0 },
    adversary: { completed: false, findingCount: 0 },
    antagonist: { completed: false, findingCount: 0 },
};
// Test config with all required fields
const testConfig = {
    ...DEFAULT_ANTAGONIST_CONFIG,
    maxNarratives: 5,
    minConfidence: 50,
    challengeThreshold: 50,
};
describe("Antagonist Integration", () => {
    describe("synthesizeNarrativesDeterministic", () => {
        it("generates attack narratives from findings", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            expect(narratives.length).toBeGreaterThan(0);
            expect(narratives[0]).toHaveProperty("id");
            expect(narratives[0]).toHaveProperty("name");
            expect(narratives[0]).toHaveProperty("phases");
            expect(narratives[0]).toHaveProperty("narrative");
            expect(narratives[0]).toHaveProperty("findingIds");
            expect(narratives[0]).toHaveProperty("recommendations");
        });
        it("includes MITRE ATT&CK techniques", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const narrativeWithTechniques = narratives.find((n) => n.mitreTechniques.length > 0);
            expect(narrativeWithTechniques).toBeDefined();
        });
        it("maps findings to kill chain phases", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const narrative = narratives[0];
            expect(narrative.phases.length).toBeGreaterThan(0);
            expect(narrative.phases[0]).toHaveProperty("phase");
            expect(narrative.phases[0]).toHaveProperty("description");
        });
        it("prioritizes critical findings in narratives", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const hasCritical = narratives.some((n) => n.findingIds.includes("find-004"));
            expect(hasCritical).toBe(true);
        });
    });
    describe("runChallengerDeterministic", () => {
        it("identifies coverage gaps", () => {
            const result = runChallengerDeterministic(sampleFindings, agentSummaries, testConfig);
            expect(result.assessments).toBeDefined();
            expect(result.gapAnalysis).toBeDefined();
            expect(result.gapAnalysis).toHaveProperty("untestedAttackVectors");
            expect(result.gapAnalysis).toHaveProperty("missingControls");
            expect(result.gapAnalysis).toHaveProperty("coverageScore");
        });
        it("flags potential false positives", () => {
            const findingsWithTestFile = [
                ...sampleFindings,
                {
                    id: "find-test",
                    severity: "medium",
                    category: "sql-injection",
                    description: "SQL injection in test",
                    evidence: "test code",
                    confidence: 60,
                    verifications: [],
                    created_at: new Date().toISOString(),
                    file: "src/__tests__/db.test.ts",
                    line: 10,
                },
            ];
            const result = runChallengerDeterministic(findingsWithTestFile, agentSummaries, testConfig);
            const testChallenge = result.assessments.find((c) => c.targetFindingId === "find-test" && c.type === "false_positive_likely");
            expect(testChallenge).toBeDefined();
            expect(testChallenge?.challenge).toContain("false positive");
        });
        it("warns about agents with zero findings", () => {
            const summariesWithZero = {
                ...agentSummaries,
                performance: { completed: true, findingCount: 0 },
            };
            const result = runChallengerDeterministic(sampleFindings, summariesWithZero, testConfig);
            const zeroFindingChallenge = result.assessments.find((c) => c.type === "missed_check" && c.targetAgent === "performance");
            expect(zeroFindingChallenge).toBeDefined();
        });
    });
    describe("prioritizeRemediations", () => {
        it("generates prioritized remediation list", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const prioritized = prioritizeRemediations(sampleFindings, narratives);
            expect(prioritized.length).toBeGreaterThan(0);
            expect(prioritized[0]).toHaveProperty("order");
            expect(prioritized[0]).toHaveProperty("findingId");
            expect(prioritized[0]).toHaveProperty("reason");
            expect(prioritized[0]).toHaveProperty("effort");
            expect(prioritized[0]).toHaveProperty("impact");
        });
        it("prioritizes critical findings first", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const prioritized = prioritizeRemediations(sampleFindings, narratives);
            const criticalPosition = prioritized.findIndex((p) => p.findingId === "find-004");
            expect(criticalPosition).toBeLessThan(3);
        });
        it("considers bottleneck findings (appear in multiple narratives)", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const prioritized = prioritizeRemediations(sampleFindings, narratives);
            const hasBlocksNarratives = prioritized.some((p) => p.blocksNarratives && p.blocksNarratives.length > 0);
            expect(hasBlocksNarratives).toBe(true);
        });
    });
    describe("Full pipeline", () => {
        it("runs complete antagonist analysis", () => {
            const narratives = synthesizeNarrativesDeterministic(sampleFindings, sampleChains, [], testConfig);
            const challengerResult = runChallengerDeterministic(sampleFindings, agentSummaries, testConfig);
            const prioritized = prioritizeRemediations(sampleFindings, narratives);
            expect(narratives.length).toBeGreaterThan(0);
            expect(challengerResult.assessments).toBeDefined();
            expect(challengerResult.gapAnalysis).toBeDefined();
            expect(prioritized.length).toBeGreaterThan(0);
            console.log("\n=== Antagonist Analysis Summary ===");
            console.log(`Attack Narratives: ${narratives.length}`);
            console.log(`Challenger Assessments: ${challengerResult.assessments.length}`);
            console.log(`Coverage Score: ${challengerResult.gapAnalysis.coverageScore}%`);
            console.log(`Prioritized Remediations: ${prioritized.length}`);
            console.log("\nTop 3 Remediation Priorities:");
            prioritized.slice(0, 3).forEach((p, i) => {
                console.log(`  ${i + 1}. ${p.findingId}: ${p.reason}`);
            });
        });
    });
});
//# sourceMappingURL=antagonist-integration.test.js.map