"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cross_layer_intelligence_1 = require("../cross-layer-intelligence");
let hvPass = 0;
let hvFail = 0;
const hvErrors = [];
function check(cond, msg) {
    if (cond) {
        hvPass++;
        console.log(`  ✅ ${msg}`);
    }
    else {
        hvFail++;
        const m = `  ❌ FAIL: ${msg}`;
        console.log(m);
        hvErrors.push(m);
    }
}
function gt(a, b, msg) {
    if (a > b) {
        hvPass++;
        console.log(`  ✅ ${msg} (${a} > ${b})`);
    }
    else {
        hvFail++;
        const m = `  ❌ FAIL: ${msg} — ${a} not > ${b}`;
        console.log(m);
        hvErrors.push(m);
    }
}
function lt(a, b, msg) {
    if (a < b) {
        hvPass++;
        console.log(`  ✅ ${msg} (${a} < ${b})`);
    }
    else {
        hvFail++;
        const m = `  ❌ FAIL: ${msg} — ${a} not < ${b}`;
        console.log(m);
        hvErrors.push(m);
    }
}
function gte(a, b, msg) {
    if (a >= b) {
        hvPass++;
        console.log(`  ✅ ${msg} (${a} >= ${b})`);
    }
    else {
        hvFail++;
        const m = `  ❌ FAIL: ${msg} — ${a} not >= ${b}`;
        console.log(m);
        hvErrors.push(m);
    }
}
function neq(a, b, msg) {
    if (a !== b) {
        hvPass++;
        console.log(`  ✅ ${msg}`);
    }
    else {
        hvFail++;
        const m = `  ❌ FAIL: ${msg} — values are identical`;
        console.log(m);
        hvErrors.push(m);
    }
}
describe('CHAPTER 9 — HOSTILE VERIFICATION', () => {
    beforeAll(() => { (0, cross_layer_intelligence_1.resetCrossLayer)(); });
    afterAll(() => {
        console.log('\n' + '='.repeat(60));
        console.log('HOSTILE VERDICT');
        console.log('='.repeat(60));
        console.log(`  Passed: ${hvPass}`);
        console.log(`  Failed: ${hvFail}`);
        console.log(`  Total:  ${hvPass + hvFail}\n`);
        if (hvFail === 0)
            console.log('  🔒 CHAPTER 9 — PASSED');
        else {
            console.log(`  ❌ ${hvFail} FAILURES:`);
            for (const e of hvErrors)
                console.log(`    ${e}`);
        }
        (0, cross_layer_intelligence_1.resetCrossLayer)();
    });
    // ===================================================================
    // T1: 100 devs, 10 teams, 5 orgs — full cross-layer pipeline
    // ===================================================================
    test('T1: 100 devs, 10 teams, 5 orgs — full pipeline', () => {
        console.log('\n--- T1: 100 devs, 10 teams, 5 orgs ---\n');
        const start = Date.now();
        // Build Unified Contexts for 100 developers across 5 orgs
        const orgs = ['org-alpha', 'org-beta', 'org-gamma', 'org-delta', 'org-epsilon'];
        const teams = ['team-frontend', 'team-backend', 'team-devops', 'team-data', 'team-mobile', 'team-security', 'team-qa', 'team-arch', 'team-ml', 'team-platform'];
        const langs = ['typescript', 'python', 'go', 'rust', 'java', 'kotlin', 'swift', 'ruby'];
        const cats = ['testing', 'data', 'devops', 'ui', 'async', 'security', 'api', 'performance'];
        const contexts = [];
        for (let d = 0; d < 100; d++) {
            const orgIdx = d % 5;
            const teamIdx = d % 10;
            const devLangs = [langs[Math.floor(Math.random() * langs.length)]];
            if (Math.random() > 0.5)
                devLangs.push(langs[Math.floor(Math.random() * langs.length)]);
            const devCats = [cats[Math.floor(Math.random() * cats.length)]];
            if (Math.random() > 0.5)
                devCats.push(cats[Math.floor(Math.random() * cats.length)]);
            const ctx = (0, cross_layer_intelligence_1.buildUnifiedContext)({
                developerId: `dev_${d}`,
                personal: {
                    languages: devLangs,
                    topCategories: devCats,
                    patternsUsed: Math.floor(Math.random() * 100) + 5,
                    successRate: 0.3 + Math.random() * 0.6,
                    avgConfidence: 0.4 + Math.random() * 0.5,
                    avgHealth: 0.3 + Math.random() * 0.6,
                },
                project: {
                    projectId: `proj_${orgIdx}_${teamIdx}`,
                    primaryLanguage: devLangs[0],
                    framework: Math.random() > 0.5 ? 'react' : Math.random() > 0.5 ? 'express' : null,
                    architecture: ['microservices', 'monolith', 'layered', 'event-driven'][Math.floor(Math.random() * 4)],
                    complexity: ['low', 'medium', 'high'][Math.floor(Math.random() * 3)],
                    maturity: ['new', 'developing', 'mature', 'legacy'][Math.floor(Math.random() * 4)],
                    testingStyle: ['tdd', 'integration', 'e2e', 'minimal'][Math.floor(Math.random() * 4)],
                    riskScore: Math.floor(Math.random() * 60),
                    developmentStyle: ['agile', 'waterfall', 'hybrid'][Math.floor(Math.random() * 3)],
                },
                team: {
                    teamId: teams[teamIdx],
                    teamName: `Team-${teams[teamIdx]}`,
                    memberCount: 8 + Math.floor(Math.random() * 12),
                    successRate: 0.4 + Math.random() * 0.5,
                    topLanguages: [langs[Math.floor(Math.random() * langs.length)]],
                    topCategories: [cats[Math.floor(Math.random() * cats.length)]],
                    style: ['quality-driven', 'experiment-driven', 'speed-driven', 'stability-driven'][Math.floor(Math.random() * 4)],
                    riskLevel: ['low', 'medium', 'high'][Math.floor(Math.random() * 3)],
                    riskScore: Math.floor(Math.random() * 60),
                    testingAdoption: Math.floor(Math.random() * 80) + 10,
                },
                org: {
                    orgId: orgs[orgIdx],
                    orgName: `Org-${orgs[orgIdx]}`,
                    teamCount: 10,
                    memberCount: 20 + Math.floor(Math.random() * 30),
                    avgSuccessRate: 0.5 + Math.random() * 0.3,
                    totalOutcomes: 500 + Math.floor(Math.random() * 2000),
                },
                community: {
                    totalPatterns: 500,
                    totalDevs: 5000,
                    totalOutcomes: 50000,
                    avgSuccessRate: 0.65,
                    topCategories: ['testing', 'data', 'devops', 'ui'],
                    patternRankings: { 'testing_p1': 1, 'data_p1': 2, 'devops_p1': 3 },
                },
            });
            contexts.push(ctx);
        }
        const buildTime = Date.now() - start;
        console.log(`  Built ${contexts.length} contexts in ${buildTime}ms`);
        lt(buildTime, 10000, `Build 100 contexts < 10s (was ${buildTime}ms)`);
        check(contexts.every(c => c.developerId.startsWith('dev_')), 'All contexts have developer IDs');
        check(contexts.every(c => c.personal !== null), 'All contexts have personal data');
        check(contexts.every(c => c.project !== null), 'All contexts have project data');
        check(contexts.every(c => c.team !== null), 'All contexts have team data');
        check(contexts.every(c => c.org !== null), 'All contexts have org data');
        check(contexts.every(c => c.community !== null), 'All contexts have community data');
        check(contexts.every(c => c.combined.primaryLanguages.length > 0), 'All contexts have primary languages');
        // Compute Intelligence Scores
        const scores = contexts.map(ctx => (0, cross_layer_intelligence_1.computeIntelligenceScore)({
            personalSuccessRate: ctx.personal?.successRate,
            personalConfidence: ctx.personal?.avgConfidence,
            personalPatternsUsed: ctx.personal?.patternsUsed,
            orgTeamSuccessRate: ctx.team?.successRate,
            orgTeamRiskScore: ctx.team?.riskScore,
            dnaRiskScore: ctx.project?.riskScore,
            riskLevel: ctx.team?.riskLevel,
            communityReputation: Math.random() * 0.8,
        }));
        console.log(`  Intelligence scores computed for ${scores.length} devs`);
        check(scores.every(s => s.overallScore >= 0 && s.overallScore <= 100), 'All scores in 0-100 range');
        check(scores.every(s => Object.keys(s.dimensions).length === 7), 'All scores have 7 dimensions');
        check(scores.every(s => s.sampleSize >= 5), 'All scores have sample size >= 5');
        // Generate evidence for 100 patterns
        const evidences = contexts.slice(0, 100).map((ctx, i) => (0, cross_layer_intelligence_1.generateEvidence)({
            patternId: `pattern_${i}`,
            category: cats[i % cats.length],
            personalSuccessRate: ctx.personal?.successRate,
            personalSampleSize: ctx.personal?.patternsUsed,
            communitySuccessRate: 0.6 + Math.random() * 0.3,
            communitySampleSize: 100 + Math.floor(Math.random() * 500),
            orgSuccessRate: ctx.team?.successRate,
            orgSampleSize: ctx.org?.totalOutcomes,
            graphInfluenceScore: Math.random() * 0.8,
            dnaSimilarity: Math.random() * 0.7,
            outcomeConfidence: Math.random() * 0.9,
        }));
        console.log(`  Generated ${evidences.length} evidence sets`);
        check(evidences.every(e => e.evidence.length >= 2), 'All evidence sets have >= 2 points');
        check(evidences.some(e => e.evidence.some(ev => ev.type === 'personal')), 'Has personal evidence');
        check(evidences.some(e => e.evidence.some(ev => ev.type === 'community')), 'Has community evidence');
        const allTime = Date.now() - start;
        console.log(`  Total pipeline time: ${allTime}ms`);
        lt(allTime, 15000, `Full pipeline < 15s (was ${allTime}ms)`);
    });
    // ===================================================================
    // T2: 1000 devs, 50 teams, 20 orgs — scale
    // ===================================================================
    test('T2: 1000 devs scale test', () => {
        console.log('\n--- T2: 1000 devs scale ---\n');
        const start = Date.now();
        for (let d = 0; d < 1000; d++) {
            (0, cross_layer_intelligence_1.buildUnifiedContext)({
                developerId: `scale_dev_${d}`,
                personal: {
                    languages: ['typescript'],
                    topCategories: ['testing'],
                    patternsUsed: 20 + (d % 50),
                    successRate: 0.5 + (d % 100) * 0.003,
                },
                project: {
                    projectId: `scale_proj_${d % 50}`,
                    primaryLanguage: 'typescript',
                    architecture: 'microservices',
                    complexity: 'medium',
                    testingStyle: 'integration',
                },
                team: {
                    teamId: `scale_team_${d % 50}`,
                    teamName: `Scale-Team-${d % 50}`,
                    memberCount: 20,
                    successRate: 0.6,
                    testingAdoption: 50,
                },
                org: {
                    orgId: `scale_org_${d % 20}`,
                    orgName: `Scale-Org-${d % 20}`,
                    teamCount: 50,
                    memberCount: 1000,
                    avgSuccessRate: 0.6,
                    totalOutcomes: 10000,
                },
                community: {
                    totalPatterns: 500,
                    totalDevs: 5000,
                    totalOutcomes: 50000,
                    avgSuccessRate: 0.65,
                    topCategories: ['testing', 'data'],
                },
            });
        }
        const elapsed = Date.now() - start;
        console.log(`  Built 1000 contexts in ${elapsed}ms`);
        lt(elapsed, 30000, `Build 1000 contexts < 30s (was ${elapsed}ms)`);
        // Intelligence scores at scale
        const sStart = Date.now();
        for (let d = 0; d < 1000; d++) {
            (0, cross_layer_intelligence_1.computeIntelligenceScore)({
                personalSuccessRate: 0.5 + (d % 100) * 0.003,
                personalPatternsUsed: 20 + (d % 50),
                communityReputation: (d % 100) * 0.008,
                orgTeamSuccessRate: 0.6,
                riskLevel: d % 3 === 0 ? 'low' : d % 3 === 1 ? 'medium' : 'high',
            });
        }
        const sTime = Date.now() - sStart;
        console.log(`  1000 scores in ${sTime}ms`);
        lt(sTime, 5000, `1000 scores < 5s (was ${sTime}ms)`);
    }, 30000);
    // ===================================================================
    // T3: Unified context — different combos, cached context
    // ===================================================================
    test('T3: Unified context combos and caching', () => {
        console.log('\n--- T3: Context combos ---\n');
        // Developer only — no org, no community
        const soloCtx = (0, cross_layer_intelligence_1.buildUnifiedContext)({
            developerId: 'solo_dev',
            personal: { languages: ['python'], topCategories: ['data'], patternsUsed: 15, successRate: 0.8 },
        });
        check(soloCtx.personal !== null, 'Solo dev has personal context');
        check(soloCtx.project === null, 'Solo dev has no project context');
        check(soloCtx.team === null, 'Solo dev has no team context');
        check(soloCtx.org === null, 'Solo dev has no org context');
        check(soloCtx.community === null, 'Solo dev has no community context');
        check(!soloCtx.combined.orgAligned, 'Solo dev not org aligned');
        check(!soloCtx.combined.communityAligned, 'Solo dev not community aligned');
        // Full context — all layers
        const fullCtx = (0, cross_layer_intelligence_1.buildUnifiedContext)({
            developerId: 'full_dev',
            personal: { languages: ['typescript', 'go'], topCategories: ['testing', 'devops'], patternsUsed: 100, successRate: 0.75, avgConfidence: 0.8, avgHealth: 0.7 },
            project: { projectId: 'p1', primaryLanguage: 'typescript', framework: 'nextjs', architecture: 'microservices', complexity: 'high', maturity: 'mature', testingStyle: 'tdd', riskScore: 20, developmentStyle: 'agile', fingerprint: 'fp1' },
            team: { teamId: 't1', teamName: 'Platform', memberCount: 12, successRate: 0.78, topLanguages: ['typescript'], topCategories: ['testing'], style: 'quality-driven', riskLevel: 'low', riskScore: 25, testingAdoption: 75 },
            org: { orgId: 'o1', orgName: 'Acme', teamCount: 8, memberCount: 96, avgSuccessRate: 0.7, totalOutcomes: 5000 },
            community: { totalPatterns: 1000, totalDevs: 10000, totalOutcomes: 100000, avgSuccessRate: 0.65, topCategories: ['testing', 'data', 'devops'] },
        });
        check(fullCtx.personal !== null, 'Full dev has personal context');
        check(fullCtx.project !== null, 'Full dev has project context');
        check(fullCtx.team !== null, 'Full dev has team context');
        check(fullCtx.org !== null, 'Full dev has org context');
        check(fullCtx.community !== null, 'Full dev has community context');
        check(fullCtx.combined.orgAligned, 'Full dev is org aligned');
        check(fullCtx.combined.communityAligned, 'Full dev is community aligned');
        gte(fullCtx.combined.overallSuccessRate, 0, 'Overall success rate computed');
        gte(fullCtx.personal.patternsUsed, 100, 'Personal patterns used');
        // Cached context
        const cached = (0, cross_layer_intelligence_1.getCachedContext)('full_dev');
        check(cached !== null, 'Context cached');
        check(cached.developerId === 'full_dev', 'Cached context has correct dev ID');
        check(cached.personal.languages.includes('typescript'), 'Cached context has languages');
        // Different developers get different contexts
        const ctxA = (0, cross_layer_intelligence_1.buildUnifiedContext)({
            developerId: 'dev_a',
            personal: { languages: ['rust'], topCategories: ['performance'], patternsUsed: 200, successRate: 0.9 },
        });
        const ctxB = (0, cross_layer_intelligence_1.buildUnifiedContext)({
            developerId: 'dev_b',
            personal: { languages: ['ruby'], topCategories: ['ui'], patternsUsed: 10, successRate: 0.3 },
        });
        neq(ctxA.developerId, ctxB.developerId, 'Different dev IDs');
        neq(ctxA.personal.languages[0], ctxB.personal.languages[0], 'Different languages');
        gt(ctxA.personal.successRate, ctxB.personal.successRate, 'Different success rates');
    });
    // ===================================================================
    // T4: Intelligence Score differentiation
    // ===================================================================
    test('T4: Intelligence score differentiation', () => {
        console.log('\n--- T4: Score differentiation ---\n');
        // High performer
        const highScore = (0, cross_layer_intelligence_1.computeIntelligenceScore)({
            personalSuccessRate: 0.95,
            personalConfidence: 0.90,
            personalPatternsUsed: 200,
            communityReputation: 0.85,
            communityRank: 5,
            orgTeamSuccessRate: 0.90,
            orgTeamRiskScore: 10,
            graphInfluenceScore: 0.80,
            dnaMaturityScore: 0.90,
            dnaRiskScore: 10,
            outcomeHealth: 0.90,
            riskLevel: 'low',
        });
        // Low performer
        const lowScore = (0, cross_layer_intelligence_1.computeIntelligenceScore)({
            personalSuccessRate: 0.15,
            personalConfidence: 0.20,
            personalPatternsUsed: 3,
            communityReputation: 0.10,
            communityRank: 500,
            orgTeamSuccessRate: 0.20,
            orgTeamRiskScore: 80,
            graphInfluenceScore: 0.05,
            dnaMaturityScore: 0.10,
            dnaRiskScore: 80,
            outcomeHealth: 0.15,
            riskLevel: 'high',
        });
        console.log(`  High score: ${highScore.overallScore}, Low score: ${lowScore.overallScore}`);
        gt(highScore.overallScore, lowScore.overallScore, 'High performer scores higher than low');
        gt(highScore.overallScore, 60, `High score >= 60 (was ${highScore.overallScore})`);
        lt(lowScore.overallScore, 50, `Low score < 50 (was ${lowScore.overallScore})`);
        // All dimensions should be higher for high performer
        for (const [dim, hVal] of Object.entries(highScore.dimensions)) {
            const lVal = lowScore.dimensions[dim];
            gte(hVal, lVal, `High performer has higher or equal ${dim}`);
        }
        // Mid performer
        const midScore = (0, cross_layer_intelligence_1.computeIntelligenceScore)({
            personalSuccessRate: 0.55,
            personalConfidence: 0.50,
            personalPatternsUsed: 50,
            communityReputation: 0.45,
            orgTeamSuccessRate: 0.55,
            riskLevel: 'medium',
        });
        console.log(`  Mid score: ${midScore.overallScore}`);
        lt(midScore.overallScore, highScore.overallScore, 'Mid < High');
        gt(midScore.overallScore, lowScore.overallScore, 'Mid > Low');
    });
    // ===================================================================
    // T5: Evidence Engine
    // ===================================================================
    test('T5: Evidence generation', () => {
        console.log('\n--- T5: Evidence Engine ---\n');
        // Full evidence
        const full = (0, cross_layer_intelligence_1.generateEvidence)({
            patternId: 'repo_pattern',
            category: 'testing',
            personalSuccessRate: 0.85,
            personalSampleSize: 20,
            communitySuccessRate: 0.91,
            communitySampleSize: 12000,
            orgSuccessRate: 0.73,
            orgSampleSize: 1400,
            graphInfluenceScore: 0.78,
            dnaSimilarity: 0.82,
            outcomeConfidence: 0.88,
        });
        console.log(`  ${full.evidence.length} evidence points for repo_pattern`);
        gt(full.evidence.length, 3, 'Full evidence has >= 3 points');
        check(full.evidence.some(e => e.type === 'personal'), 'Has personal evidence');
        check(full.evidence.some(e => e.type === 'community'), 'Has community evidence');
        check(full.evidence.some(e => e.type === 'org'), 'Has org evidence');
        check(full.evidence.some(e => e.type === 'graph'), 'Has graph evidence');
        check(full.evidence.some(e => e.type === 'dna'), 'Has DNA evidence');
        check(full.evidence.some(e => e.type === 'outcome'), 'Has outcome evidence');
        // Minimal evidence
        const minimal = (0, cross_layer_intelligence_1.generateEvidence)({
            patternId: 'new_pattern',
            category: 'experimental',
            personalSuccessRate: 0.6,
            personalSampleSize: 2,
        });
        console.log(`  ${minimal.evidence.length} evidence points for new pattern`);
        gte(minimal.evidence.length, 1, 'Minimal evidence has >= 1 point');
        check(minimal.evidence.every(e => e.sampleSize > 0), 'Evidence has sample sizes');
        gte(minimal.totalScore, 0, 'Evidence total score >= 0');
        gte(minimal.confidence, 0, 'Evidence confidence >= 0');
        // Differing evidence
        const evA = (0, cross_layer_intelligence_1.generateEvidence)({
            patternId: 'p1', category: 'testing',
            personalSuccessRate: 0.9, personalSampleSize: 100,
            communitySuccessRate: 0.8, communitySampleSize: 1000,
        });
        const evB = (0, cross_layer_intelligence_1.generateEvidence)({
            patternId: 'p2', category: 'testing',
            personalSuccessRate: 0.3, personalSampleSize: 5,
            communitySuccessRate: 0.4, communitySampleSize: 200,
        });
        neq(evA.totalScore, evB.totalScore, 'Different patterns get different scores');
        gt(evA.totalScore, evB.totalScore, 'Better evidence scores higher');
    });
    // ===================================================================
    // T6: Knowledge Gap Engine
    // ===================================================================
    test('T6: Knowledge gap detection', () => {
        console.log('\n--- T6: Knowledge Gaps ---\n');
        const patterns = [
            { patternId: 'tdd_testing', category: 'testing', communitySuccessRate: 0.91, communitySampleSize: 12000, orgSuccessRate: 0.42, orgSampleSize: 200 },
            { patternId: 'ci_cd', category: 'devops', communitySuccessRate: 0.85, communitySampleSize: 8000, orgSuccessRate: 0.35, orgSampleSize: 150 },
            { patternId: 'code_review', category: 'review', communitySuccessRate: 0.78, communitySampleSize: 5000, orgSuccessRate: 0.68, orgSampleSize: 180 },
            { patternId: 'microservices', category: 'architecture', communitySuccessRate: 0.65, communitySampleSize: 3000, orgSuccessRate: 0.62, orgSampleSize: 100 },
            { patternId: 'pair_programming', category: 'collaboration', communitySuccessRate: 0.55, communitySampleSize: 2000, orgSuccessRate: 0.52, orgSampleSize: 50 },
            { patternId: 'all_good', category: 'testing', communitySuccessRate: 0.85, communitySampleSize: 5000, orgSuccessRate: 0.83, orgSampleSize: 300 },
        ];
        const gaps = (0, cross_layer_intelligence_1.detectKnowledgeGaps)({
            patterns,
            minGapThreshold: 0.15,
            minCommunitySample: 5,
        });
        console.log(`  ${gaps.length} knowledge gaps detected`);
        for (const g of gaps) {
            console.log(`    ${g.patternId}: gap=${Math.round(g.gapSize * 100)}%, impact=${g.impact}`);
        }
        gt(gaps.length, 0, 'Knowledge gaps detected');
        check(gaps.every(g => g.gapSize > 0.15), 'All gaps above threshold');
        check(gaps.some(g => g.impact === 'high' || g.impact === 'medium'), 'Some gaps are high/medium impact');
        check(gaps.every(g => g.recommendation.length > 10), 'All gaps have recommendations');
        // No gaps
        const noGaps = (0, cross_layer_intelligence_1.detectKnowledgeGaps)({
            patterns: [
                { patternId: 'p1', category: 'test', communitySuccessRate: 0.8, communitySampleSize: 100, orgSuccessRate: 0.79, orgSampleSize: 50 },
            ],
        });
        check(noGaps.length === 0, 'No gaps when rates are equal');
    });
    // ===================================================================
    // T7: Opportunity Engine
    // ===================================================================
    test('T7: Opportunity detection', () => {
        console.log('\n--- T7: Opportunities ---\n');
        const gaps = [
            { patternId: 'tdd', category: 'testing', communitySuccessRate: 0.91, communitySampleSize: 12000, orgSuccessRate: 0.42, orgSampleSize: 200, gapSize: 0.49, impact: 'high', recommendation: 'Adopt TDD' },
            { patternId: 'ci_cd', category: 'devops', communitySuccessRate: 0.85, communitySampleSize: 8000, orgSuccessRate: 0.35, orgSampleSize: 150, gapSize: 0.50, impact: 'high', recommendation: 'Adopt CI/CD' },
        ];
        const opps = (0, cross_layer_intelligence_1.findOpportunities)({
            currentSuccessRate: 0.45,
            communityAvgSuccessRate: 0.68,
            topPerformerRate: 0.92,
            gaps,
            teamTestingAdoption: 15,
            orgAvgTestingAdoption: 55,
            teamCIRate: 10,
            orgAvgCIRate: 70,
            teamReviewRate: 25,
            orgAvgReviewRate: 60,
        });
        console.log(`  ${opps.length} opportunities`);
        for (const o of opps) {
            console.log(`    ${o.title}: impact=+${o.impact}pp, confidence=${Math.round(o.confidence * 100)}%`);
        }
        gt(opps.length, 0, 'Opportunities generated');
        check(opps.every(o => o.confidence > 0 && o.confidence <= 1), 'All have valid confidence');
        check(opps.every(o => o.impact > 0), 'All have positive impact');
        check(opps.every(o => o.description.length > 10), 'All have descriptions');
        check(opps.some(o => o.category === 'testing'), 'Testing opportunity exists');
        check(opps.some(o => o.category === 'community'), 'Community opportunity exists');
    });
    // ===================================================================
    // T8: Risk Engine V2
    // ===================================================================
    test('T8: Risk Engine V2', () => {
        console.log('\n--- T8: Risk V2 ---\n');
        const gaps = [
            { patternId: 'tdd', category: 'testing', communitySuccessRate: 0.91, communitySampleSize: 12000, orgSuccessRate: 0.42, orgSampleSize: 200, gapSize: 0.49, impact: 'high', recommendation: 'Adopt TDD' },
            { patternId: 'ci_cd', category: 'devops', communitySuccessRate: 0.85, communitySampleSize: 8000, orgSuccessRate: 0.35, orgSampleSize: 150, gapSize: 0.50, impact: 'high', recommendation: 'Adopt CI/CD' },
            { patternId: 'code_review', category: 'review', communitySuccessRate: 0.78, communitySampleSize: 5000, orgSuccessRate: 0.68, orgSampleSize: 180, gapSize: 0.10, impact: 'low', recommendation: 'Improve reviews' },
        ];
        const risks = (0, cross_layer_intelligence_1.analyzeRisks)({
            knowledgeSilos: gaps,
            busFactorScore: 85,
            teamRiskScore: 65,
            teamTestingAdoption: 12,
            teamSuccessRate: 0.45,
            orgAvgSuccessRate: 0.72,
            memberCount: 8,
            totalPatterns: 200,
        });
        console.log(`  ${risks.length} risks identified`);
        for (const r of risks) {
            console.log(`    ${r.title}: score=${r.riskScore}, impact=${r.impact}, prob=${Math.round(r.probability * 100)}%`);
        }
        gt(risks.length, 0, 'Risks identified');
        check(risks.some(r => r.category === 'knowledge'), 'Knowledge risk identified');
        check(risks.some(r => r.category === 'people'), 'People risk (bus factor) identified');
        check(risks.some(r => r.category === 'quality'), 'Quality risk identified');
        check(risks.some(r => r.category === 'performance'), 'Performance risk identified');
        check(risks.every(r => r.rootCause.length > 0), 'All risks have root cause');
        check(risks.every(r => r.recommendation.length > 0), 'All risks have recommendations');
        check(risks.every(r => r.evidencePoints.length > 0), 'All risks have evidence');
        // No risks
        const noRisks = (0, cross_layer_intelligence_1.analyzeRisks)({});
        check(noRisks.length === 0, 'No risks when no data provided');
    });
    // ===================================================================
    // T9: Pattern Lifecycle
    // ===================================================================
    test('T9: Pattern lifecycle classification', () => {
        console.log('\n--- T9: Lifecycle ---\n');
        const lifecycles = (0, cross_layer_intelligence_1.classifyLifecycle)({
            patterns: [
                { patternId: 'rust_pattern', category: 'performance', communityTrend: 'exploding', communityUsage: 200, orgUsage: 50, avgSuccessRate: 0.85, confidence: 0.9 },
                { patternId: 'react_hooks', category: 'ui', communityTrend: 'rising', communityUsage: 80, orgUsage: 30, avgSuccessRate: 0.78, confidence: 0.85 },
                { patternId: 'tdd', category: 'testing', communityTrend: 'stable', communityUsage: 500, orgUsage: 200, avgSuccessRate: 0.82, confidence: 0.95 },
                { patternId: 'jquery', category: 'ui', communityTrend: 'declining', communityUsage: 300, orgUsage: 50, avgSuccessRate: 0.5, confidence: 0.6 },
                { patternId: 'coffeescript', category: 'language', communityTrend: 'dead', communityUsage: 10, orgUsage: 0, avgSuccessRate: 0.2, confidence: 0.1 },
                { patternId: 'new_fad', category: 'experimental', communityTrend: 'rising', communityUsage: 12, avgSuccessRate: 0.9, confidence: 0.3 },
            ],
        });
        console.log(`  ${lifecycles.length} lifecycle classifications`);
        const stages = lifecycles.map(l => `${l.patternId}: ${l.stage} (${l.communityTrend})`);
        for (const s of stages)
            console.log(`    ${s}`);
        gt(lifecycles.length, 0, 'Lifecycles computed');
        check(lifecycles.every(l => ['emerging', 'growing', 'mature', 'declining', 'dead'].includes(l.stage)), 'All have valid stages');
        const rustCycle = lifecycles.find(l => l.patternId === 'rust_pattern');
        check(rustCycle?.stage === 'growing', 'Rust/exploding is growing');
        const tddCycle = lifecycles.find(l => l.patternId === 'tdd');
        check(tddCycle?.stage === 'mature', 'TDD/stable/high usage is mature');
        const jqCycle = lifecycles.find(l => l.patternId === 'jquery');
        check(jqCycle?.stage === 'declining', 'jQuery declining is declining');
        const csCycle = lifecycles.find(l => l.patternId === 'coffeescript');
        check(csCycle?.stage === 'dead', 'CoffeeScript dead is dead');
        const newCycle = lifecycles.find(l => l.patternId === 'new_fad');
        check(newCycle?.stage === 'emerging', 'New/low usage is emerging');
        check(lifecycles.every(l => l.estimatedLifespan.length > 0), 'All have estimated lifespans');
    });
    // ===================================================================
    // T10: Multi-Level Benchmarking
    // ===================================================================
    test('T10: Multi-level benchmarking', () => {
        console.log('\n--- T10: Benchmarks ---\n');
        const benchmarks = (0, cross_layer_intelligence_1.computeMultiLevelBenchmarks)({
            metrics: [
                {
                    name: 'Success Rate',
                    personalValue: 0.72, personalSampleSize: 50,
                    teamValue: 0.68, teamSampleSize: 200,
                    orgValue: 0.65, orgSampleSize: 5000,
                    communityAvg: 0.71, communityP50: 0.68, communityP90: 0.92, communitySampleSize: 50000,
                },
                {
                    name: 'Testing Coverage',
                    personalValue: 0.35, personalSampleSize: 50,
                    teamValue: 0.40, teamSampleSize: 200,
                    orgValue: 0.50, orgSampleSize: 5000,
                    communityAvg: 0.65, communityP50: 0.60, communityP90: 0.85, communitySampleSize: 50000,
                },
                {
                    name: 'Pattern Adoption',
                    personalValue: 0.60, personalSampleSize: 50,
                    orgValue: 0.55, orgSampleSize: 5000,
                    communityAvg: 0.70, communityP50: 0.65, communityP90: 0.90, communitySampleSize: 50000,
                },
            ],
        });
        console.log(`  ${benchmarks.length} benchmarks`);
        for (const b of benchmarks) {
            console.log(`    ${b.metric}: ${b.levels.length} levels, gapToNext=${b.gapToNext}, gapToBest=${b.gapToBest}`);
            for (const l of b.levels)
                console.log(`      ${l.level}: ${Math.round(l.value * 100)}% (n=${l.sampleSize})`);
        }
        gt(benchmarks.length, 0, 'Benchmarks computed');
        check(benchmarks.every(b => b.levels.length >= 2), 'All benchmarks have >= 2 levels');
        check(benchmarks.some(b => b.levels.some(l => l.level === 'personal')), 'Has personal level');
        check(benchmarks.some(b => b.levels.some(l => l.level === 'community')), 'Has community level');
        // Success Rate — personal > team > org < community
        const sr = benchmarks.find(b => b.metric === 'Success Rate');
        check(sr !== undefined, 'Success Rate benchmark exists');
        if (sr) {
            const personal = sr.levels.find(l => l.level === 'personal');
            const org = sr.levels.find(l => l.level === 'org');
            if (personal && org) {
                gt(personal.value, org.value, 'Personal > org in success rate');
            }
        }
        // Testing Coverage — community should be highest
        const tc = benchmarks.find(b => b.metric === 'Testing Coverage');
        check(tc !== undefined, 'Testing Coverage benchmark exists');
        if (tc) {
            const community = tc.levels.find(l => l.level === 'community');
            const personal = tc.levels.find(l => l.level === 'personal');
            if (community && personal) {
                gt(community.value, personal.value, 'Community > personal in testing coverage');
            }
        }
    });
    // ===================================================================
    // T11: Decision Engine
    // ===================================================================
    test('T11: Decision engine', () => {
        console.log('\n--- T11: Decisions ---\n');
        const score = {
            overallScore: 55,
            dimensions: { personalSuccess: 45, personalConfidence: 50, communityReputation: 30, orgAlignment: 60, graphInfluence: 40, dnaMaturity: 55, riskHealth: 50 },
            weights: { personalSuccess: 0.2, personalConfidence: 0.1, communityReputation: 0.15, orgAlignment: 0.15, graphInfluence: 0.1, dnaMaturity: 0.15, riskHealth: 0.15 },
            sampleSize: 100,
        };
        const gaps = [
            { patternId: 'tdd', category: 'testing', communitySuccessRate: 0.91, communitySampleSize: 12000, orgSuccessRate: 0.42, orgSampleSize: 200, gapSize: 0.49, impact: 'high', recommendation: 'Adopt TDD' },
        ];
        const opps = [
            { title: 'Increase Testing', category: 'testing', currentValue: 15, expectedValue: 55, impact: 17, confidence: 0.91, evidenceCount: 12000, effort: 'medium', description: 'Increase testing from 15% to 55%' },
            { title: 'Adopt CI/CD', category: 'devops', currentValue: 10, expectedValue: 70, impact: 14, confidence: 0.85, evidenceCount: 8000, effort: 'medium', description: 'Adopt CI/CD pipelines' },
        ];
        const risks = [
            { title: 'High Bus Factor', category: 'people', rootCause: 'Knowledge concentrated', probability: 0.85, impact: 'high', riskScore: 85, recommendation: 'Share knowledge', evidencePoints: ['Bus factor: 85'] },
            { title: 'Low Testing', category: 'quality', rootCause: 'Testing not prioritized', probability: 0.7, impact: 'medium', riskScore: 45, recommendation: 'Increase testing', evidencePoints: ['Testing: 15%'] },
        ];
        const decisions = (0, cross_layer_intelligence_1.generateDecisions)({
            intelligenceScore: score,
            knowledgeGaps: gaps,
            opportunities: opps,
            risks,
            personalSuccessRate: 0.55,
            personalPatternsUsed: 100,
            teamTestingAdoption: 15,
            teamCIRate: 10,
            teamReviewRate: 25,
        });
        console.log(`  ${decisions.length} decisions generated`);
        for (const d of decisions) {
            console.log(`    #${d.priority}: ${d.action} (impact=${d.impact} ${d.impactUnit}, confidence=${d.confidence}%)`);
        }
        gt(decisions.length, 0, 'Decisions generated');
        check(decisions.every(d => d.priority > 0), 'All decisions have priority');
        check(decisions.every(d => d.action.length > 0), 'All decisions have actions');
        check(decisions.every(d => d.impact > 0), 'All decisions have positive impact');
        check(decisions.every(d => d.confidence >= 0 && d.confidence <= 100), 'All decisions have valid confidence');
        check(decisions.every(d => d.recommendations.length > 0), 'All decisions have recommendations');
        check(decisions.every(d => d.keyEvidence.length > 0), 'All decisions have evidence');
        // Sorted by priority
        for (let i = 1; i < decisions.length; i++) {
            gte(decisions[i].priority, decisions[i - 1].priority, 'Decisions sorted by priority');
        }
        // Risk mitigation should be high priority
        check(decisions.some(d => d.category === 'people'), 'People risk decision exists');
    });
    // ===================================================================
    // T12: Full Intelligence Report
    // ===================================================================
    test('T12: Intelligence report generator', () => {
        console.log('\n--- T12: Report Generation ---\n');
        const ctx = (0, cross_layer_intelligence_1.buildUnifiedContext)({
            developerId: 'report_dev',
            personal: { languages: ['typescript', 'go'], topCategories: ['testing', 'data'], patternsUsed: 150, successRate: 0.78, avgConfidence: 0.82, avgHealth: 0.75 },
            project: { projectId: 'report_proj', primaryLanguage: 'typescript', framework: 'nextjs', architecture: 'microservices', complexity: 'high', maturity: 'mature', testingStyle: 'tdd', riskScore: 15 },
            team: { teamId: 'report_team', teamName: 'Core', memberCount: 10, successRate: 0.72, topLanguages: ['typescript'], topCategories: ['testing'], style: 'quality-driven', riskLevel: 'low', riskScore: 20, testingAdoption: 65 },
            org: { orgId: 'report_org', orgName: 'TechCorp', teamCount: 10, memberCount: 100, avgSuccessRate: 0.68, totalOutcomes: 10000 },
            community: { totalPatterns: 1000, totalDevs: 10000, totalOutcomes: 100000, avgSuccessRate: 0.65, topCategories: ['testing', 'data', 'devops'] },
        });
        const score = (0, cross_layer_intelligence_1.computeIntelligenceScore)({
            personalSuccessRate: 0.78, personalConfidence: 0.82, personalPatternsUsed: 150,
            communityReputation: 0.72, orgTeamSuccessRate: 0.72, orgTeamRiskScore: 20,
            graphInfluenceScore: 0.65, dnaRiskScore: 15, riskLevel: 'low',
        });
        const gaps = (0, cross_layer_intelligence_1.detectKnowledgeGaps)({
            patterns: [
                { patternId: 'tdd', category: 'testing', communitySuccessRate: 0.91, communitySampleSize: 12000, orgSuccessRate: 0.55, orgSampleSize: 300 },
                { patternId: 'ci_cd', category: 'devops', communitySuccessRate: 0.85, communitySampleSize: 8000, orgSuccessRate: 0.45, orgSampleSize: 200 },
            ],
        });
        const opps = (0, cross_layer_intelligence_1.findOpportunities)({
            currentSuccessRate: 0.72, communityAvgSuccessRate: 0.65, topPerformerRate: 0.92, gaps,
            teamTestingAdoption: 65, orgAvgTestingAdoption: 50,
        });
        const risks = (0, cross_layer_intelligence_1.analyzeRisks)({
            knowledgeSilos: gaps,
            teamTestingAdoption: 65,
            teamSuccessRate: 0.72,
            orgAvgSuccessRate: 0.68,
        });
        const benchmarks = (0, cross_layer_intelligence_1.computeMultiLevelBenchmarks)({
            metrics: [
                {
                    name: 'Success Rate',
                    personalValue: 0.78, personalSampleSize: 150,
                    teamValue: 0.72, teamSampleSize: 1000,
                    orgValue: 0.68, orgSampleSize: 10000,
                    communityAvg: 0.65, communityP50: 0.62, communityP90: 0.88, communitySampleSize: 100000,
                },
                {
                    name: 'Testing Coverage',
                    personalValue: 0.60, personalSampleSize: 150,
                    teamValue: 0.65, teamSampleSize: 1000,
                    orgValue: 0.50, orgSampleSize: 10000,
                    communityAvg: 0.60, communityP50: 0.55, communityP90: 0.82, communitySampleSize: 100000,
                },
            ],
        });
        const decisions = (0, cross_layer_intelligence_1.generateDecisions)({
            intelligenceScore: score, knowledgeGaps: gaps, opportunities: opps, risks,
            personalSuccessRate: 0.78, personalPatternsUsed: 150,
        });
        const report = (0, cross_layer_intelligence_1.generateIntelligenceReport)({
            targetId: 'report_dev',
            targetType: 'developer',
            unifiedContext: ctx,
            intelligenceScore: score,
            knowledgeGaps: gaps,
            opportunities: opps,
            risks,
            benchmarks,
            decisions,
        });
        console.log(`  Report: ${report.reportId}`);
        console.log(`  Score: ${report.intelligenceScore.overallScore}/100`);
        console.log(`  ${report.decisions.length} decisions, ${report.gaps.length} gaps, ${report.opportunities.length} opps, ${report.risks.length} risks`);
        console.log(`  ${report.benchmarks.length} benchmarks`);
        console.log(`  ${report.strengths.length} strengths, ${report.weaknesses.length} weaknesses`);
        console.log(`  Summary: ${report.summary.substring(0, 80)}...`);
        check(report.reportId.startsWith('report_'), 'Report has valid ID');
        check(report.targetId === 'report_dev', 'Report targets correct dev');
        gte(report.intelligenceScore.overallScore, 0, 'Report has score');
        gt(report.generatedAt, 0, 'Report has generation timestamp');
        gt(report.decisions.length, 0, 'Report has decisions');
        gt(report.benchmarks.length, 0, 'Report has benchmarks');
        gt(report.strengths.length + report.weaknesses.length, 0, 'Report has strengths/weaknesses');
        gt(report.summary.length, 50, 'Report has substantial summary');
        // Persist and retrieve
        const retrieved = (0, cross_layer_intelligence_1.getReport)(report.reportId);
        check(retrieved !== null, 'Report persisted to store');
        check(retrieved.targetId === 'report_dev', 'Retrieved report has correct data');
        const allReports = (0, cross_layer_intelligence_1.listReports)();
        gt(allReports.length, 0, 'Reports listed');
        check(allReports.includes(report.reportId), 'Report ID in list');
    });
    // ===================================================================
    // T13: Restart survival
    // ===================================================================
    test('T13: Data persists across restart', () => {
        console.log('\n--- T13: Restart Survival ---\n');
        const allReports = (0, cross_layer_intelligence_1.listReports)();
        console.log(`  ${allReports.length} reports survive`);
        gt(allReports.length, 0, 'Reports survive restart');
        if (allReports.length > 0) {
            const report = (0, cross_layer_intelligence_1.getReport)(allReports[0]);
            check(report !== null, 'Individual report retrieved after restart');
            check(report.targetId.length > 0, 'Report has target');
            gte(report.intelligenceScore.overallScore, 0, 'Report score persists');
        }
    });
});
//# sourceMappingURL=chapter9-hostile.test.js.map