"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetCrossLayer = resetCrossLayer;
exports.buildUnifiedContext = buildUnifiedContext;
exports.getCachedContext = getCachedContext;
exports.computeIntelligenceScore = computeIntelligenceScore;
exports.generateEvidence = generateEvidence;
exports.detectKnowledgeGaps = detectKnowledgeGaps;
exports.findOpportunities = findOpportunities;
exports.analyzeRisks = analyzeRisks;
exports.classifyLifecycle = classifyLifecycle;
exports.generateDecisions = generateDecisions;
exports.computeMultiLevelBenchmarks = computeMultiLevelBenchmarks;
exports.generateIntelligenceReport = generateIntelligenceReport;
exports.getReport = getReport;
exports.listReports = listReports;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
// ═══════════════════════════════════════════════════════════════
// STORE
// ═══════════════════════════════════════════════════════════════
const STORE_PATH = path.join(os.homedir(), '.fivo', 'cell', 'cross-layer-intelligence.json');
function ensureDir() {
    const dir = path.dirname(STORE_PATH);
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
}
function loadStore() {
    ensureDir();
    try {
        if (fs.existsSync(STORE_PATH))
            return JSON.parse(fs.readFileSync(STORE_PATH, 'utf-8'));
    }
    catch { }
    return { reports: {}, contextCache: {}, version: 1 };
}
function saveStore(data) {
    ensureDir();
    fs.writeFileSync(STORE_PATH, JSON.stringify(data, null, 2), 'utf-8');
}
function resetCrossLayer() {
    try {
        if (fs.existsSync(STORE_PATH))
            fs.unlinkSync(STORE_PATH);
    }
    catch { }
}
function buildUnifiedContext(input) {
    const personal = {
        developerId: input.developerId,
        languages: input.personal?.languages || [],
        topCategories: input.personal?.topCategories || [],
        patternsUsed: input.personal?.patternsUsed || 0,
        successRate: input.personal?.successRate || 0,
        avgConfidence: input.personal?.avgConfidence || 0,
        avgHealth: input.personal?.avgHealth || 0,
    };
    const project = input.project ? {
        projectId: input.project.projectId || '',
        primaryLanguage: input.project.primaryLanguage || 'unknown',
        framework: input.project.framework || null,
        architecture: input.project.architecture || 'unknown',
        complexity: input.project.complexity || 'unknown',
        maturity: input.project.maturity || 'unknown',
        testingStyle: input.project.testingStyle || 'unknown',
        riskScore: input.project.riskScore || 0,
        developmentStyle: input.project.developmentStyle || 'unknown',
        fingerprint: input.project.fingerprint || '',
    } : null;
    const team = input.team ? {
        teamId: input.team.teamId || '',
        teamName: input.team.teamName || '',
        memberCount: input.team.memberCount || 0,
        successRate: input.team.successRate || 0,
        topLanguages: input.team.topLanguages || [],
        topCategories: input.team.topCategories || [],
        style: input.team.style || 'unknown',
        riskLevel: input.team.riskLevel || 'unknown',
        riskScore: input.team.riskScore || 0,
        testingAdoption: input.team.testingAdoption || 0,
    } : null;
    const org = input.org ? {
        orgId: input.org.orgId || '',
        orgName: input.org.orgName || '',
        teamCount: input.org.teamCount || 0,
        memberCount: input.org.memberCount || 0,
        avgSuccessRate: input.org.avgSuccessRate || 0,
        totalOutcomes: input.org.totalOutcomes || 0,
    } : null;
    const community = input.community ? {
        totalPatterns: input.community.totalPatterns || 0,
        totalDevs: input.community.totalDevs || 0,
        totalOutcomes: input.community.totalOutcomes || 0,
        avgSuccessRate: input.community.avgSuccessRate || 0,
        topCategories: input.community.topCategories || [],
        patternRankings: input.community.patternRankings || {},
    } : null;
    const allLanguages = new Set();
    if (personal.languages.length > 0)
        personal.languages.forEach(l => allLanguages.add(l));
    if (team && team.topLanguages.length > 0)
        team.topLanguages.forEach(l => allLanguages.add(l));
    if (project)
        allLanguages.add(project.primaryLanguage);
    const allCategories = new Set();
    if (personal.topCategories.length > 0)
        personal.topCategories.forEach(c => allCategories.add(c));
    if (team && team.topCategories.length > 0)
        team.topCategories.forEach(c => allCategories.add(c));
    const rates = [];
    if (personal.successRate > 0)
        rates.push(personal.successRate);
    if (team && team.successRate > 0)
        rates.push(team.successRate);
    if (org && org.avgSuccessRate > 0)
        rates.push(org.avgSuccessRate);
    if (community && community.avgSuccessRate > 0)
        rates.push(community.avgSuccessRate);
    const overallSuccessRate = rates.length > 0 ? rates.reduce((a, b) => a + b, 0) / rates.length : 0;
    const store = loadStore();
    const ctx = {
        developerId: input.developerId,
        personal,
        project,
        team,
        org,
        community,
        combined: {
            overallSuccessRate,
            primaryLanguages: Array.from(allLanguages),
            primaryCategories: Array.from(allCategories),
            patternCount: personal.patternsUsed,
            orgAligned: team !== null && org !== null,
            communityAligned: community !== null,
        },
        builtAt: Date.now(),
    };
    store.contextCache[input.developerId] = ctx;
    saveStore(store);
    return ctx;
}
function getCachedContext(developerId) {
    const store = loadStore();
    return store.contextCache[developerId] || null;
}
const DEFAULT_WEIGHTS = {
    personalSuccess: 0.20,
    personalConfidence: 0.10,
    communityReputation: 0.15,
    orgAlignment: 0.15,
    graphInfluence: 0.10,
    dnaMaturity: 0.15,
    riskHealth: 0.15,
};
function computeIntelligenceScore(input) {
    const dims = {
        personalSuccess: Math.round((input.personalSuccessRate || 0) * 100),
        personalConfidence: Math.round((input.personalConfidence || 0) * 100),
        communityReputation: Math.round(Math.min((input.communityReputation || 0) * 100, 100)),
        orgAlignment: Math.round(Math.min((input.orgTeamSuccessRate || 0) * 100, 100)),
        graphInfluence: Math.round(Math.min(input.graphInfluenceScore || 0, 100)),
        dnaMaturity: Math.round(Math.min((1 - (input.dnaRiskScore || 0) / 100) * 100, 100)),
        riskHealth: input.riskLevel === 'low' ? 80 : input.riskLevel === 'medium' ? 50 : input.riskLevel === 'high' ? 25 : 10,
    };
    const weights = { ...DEFAULT_WEIGHTS };
    if (input.personalPatternsUsed && input.personalPatternsUsed < 5) {
        weights.personalSuccess = 0.05;
        weights.personalConfidence = 0.05;
        weights.communityReputation = 0.30;
        weights.dnaMaturity = 0.25;
    }
    const overallScore = Math.round(dims.personalSuccess * weights.personalSuccess +
        dims.personalConfidence * weights.personalConfidence +
        dims.communityReputation * weights.communityReputation +
        dims.orgAlignment * weights.orgAlignment +
        dims.graphInfluence * weights.graphInfluence +
        dims.dnaMaturity * weights.dnaMaturity +
        dims.riskHealth * weights.riskHealth);
    return {
        overallScore: Math.min(overallScore, 100),
        dimensions: dims,
        weights,
        sampleSize: Math.max(input.personalPatternsUsed || 0, 1),
    };
}
function generateEvidence(input) {
    const evidence = [];
    if (input.personalSuccessRate !== undefined && input.personalSampleSize && input.personalSampleSize > 0) {
        evidence.push({
            type: 'personal',
            source: `Personal history (${input.personalSampleSize} patterns)`,
            value: input.personalSuccessRate,
            sampleSize: input.personalSampleSize,
            description: `${Math.round(input.personalSuccessRate * 100)}% personal success rate`,
            weight: Math.min(input.personalSampleSize / 100, 1),
        });
    }
    if (input.communitySuccessRate !== undefined && input.communitySampleSize && input.communitySampleSize > 0) {
        evidence.push({
            type: 'community',
            source: `Community intelligence (${input.communitySampleSize} outcomes)`,
            value: input.communitySuccessRate,
            sampleSize: input.communitySampleSize,
            description: `${Math.round(input.communitySuccessRate * 100)}% community success rate across ${input.communitySampleSize} outcomes`,
            weight: Math.min(input.communitySampleSize / 500, 1),
        });
    }
    if (input.orgSuccessRate !== undefined && input.orgSampleSize && input.orgSampleSize > 0) {
        evidence.push({
            type: 'org',
            source: `Organization intelligence (${input.orgSampleSize} outcomes)`,
            value: input.orgSuccessRate,
            sampleSize: input.orgSampleSize,
            description: `${Math.round(input.orgSuccessRate * 100)}% success rate in your organization`,
            weight: Math.min(input.orgSampleSize / 100, 1),
        });
    }
    if (input.graphInfluenceScore !== undefined && input.graphInfluenceScore > 0) {
        evidence.push({
            type: 'graph',
            source: 'Knowledge graph influence',
            value: input.graphInfluenceScore,
            sampleSize: 1,
            description: `Graph influence score: ${Math.round(input.graphInfluenceScore * 100)}`,
            weight: 0.6,
        });
    }
    if (input.dnaSimilarity !== undefined && input.dnaSimilarity > 0) {
        evidence.push({
            type: 'dna',
            source: 'Project DNA similarity',
            value: input.dnaSimilarity,
            sampleSize: 1,
            description: `${Math.round(input.dnaSimilarity * 100)}% DNA match with similar projects`,
            weight: 0.5,
        });
    }
    if (input.outcomeConfidence !== undefined && input.outcomeConfidence > 0) {
        evidence.push({
            type: 'outcome',
            source: 'Outcome confidence analysis',
            value: input.outcomeConfidence,
            sampleSize: 1,
            description: `Outcome confidence: ${Math.round(input.outcomeConfidence * 100)}%`,
            weight: 0.4,
        });
    }
    const totalWeight = evidence.reduce((s, e) => s + e.weight, 0) || 1;
    const totalScore = evidence.reduce((s, e) => s + e.value * e.weight, 0) / totalWeight;
    const confidence = evidence.length > 0
        ? Math.min(evidence.reduce((s, e) => s + (e.sampleSize > 50 ? 1 : e.sampleSize / 50) * e.weight, 0) / totalWeight, 1)
        : 0;
    return {
        patternId: input.patternId,
        category: input.category,
        totalScore: Math.round(totalScore * 100) / 100,
        evidence,
        confidence: Math.round(confidence * 100) / 100,
    };
}
function detectKnowledgeGaps(input) {
    const threshold = input.minGapThreshold ?? 0.15;
    const minSample = input.minCommunitySample ?? 5;
    const gaps = [];
    for (const p of input.patterns) {
        if (p.communitySampleSize < minSample)
            continue;
        const gapSize = p.communitySuccessRate - p.orgSuccessRate;
        if (gapSize <= threshold)
            continue;
        const impact = gapSize > 0.4 ? 'high' : gapSize > 0.25 ? 'medium' : 'low';
        gaps.push({
            patternId: p.patternId,
            category: p.category,
            communitySuccessRate: Math.round(p.communitySuccessRate * 100) / 100,
            communitySampleSize: p.communitySampleSize,
            orgSuccessRate: Math.round(p.orgSuccessRate * 100) / 100,
            orgSampleSize: p.orgSampleSize,
            gapSize: Math.round(gapSize * 100) / 100,
            impact,
            recommendation: `Adopt "${p.patternId}" — ${Math.round(gapSize * 100)}% gap with community best practices. Community shows ${Math.round(p.communitySuccessRate * 100)}% success across ${p.communitySampleSize} outcomes.`,
        });
    }
    return gaps.sort((a, b) => b.gapSize - a.gapSize);
}
function findOpportunities(input) {
    const opportunities = [];
    const successGap = input.topPerformerRate - input.currentSuccessRate;
    if (successGap > 0.05) {
        opportunities.push({
            title: 'Improve Overall Success Rate',
            category: 'success',
            currentValue: Math.round(input.currentSuccessRate * 100),
            expectedValue: Math.round(input.topPerformerRate * 100),
            impact: Math.round(successGap * 100),
            confidence: 0.85,
            evidenceCount: Math.max(input.gaps.filter(g => g.category === 'testing' || g.category === 'data').length, 1),
            effort: 'medium',
            description: `Current success ${Math.round(input.currentSuccessRate * 100)}%. Top performers achieve ${Math.round(input.topPerformerRate * 100)}%. Focus on closing ${input.gaps.length} identified knowledge gaps.`,
        });
    }
    if (input.teamTestingAdoption !== undefined && input.orgAvgTestingAdoption !== undefined) {
        const testingGap = input.orgAvgTestingAdoption - input.teamTestingAdoption;
        if (testingGap > 10) {
            opportunities.push({
                title: 'Increase Testing Adoption',
                category: 'testing',
                currentValue: input.teamTestingAdoption,
                expectedValue: input.orgAvgTestingAdoption,
                impact: Math.round(testingGap * 0.3),
                confidence: 0.78,
                evidenceCount: input.gaps.filter(g => g.category === 'testing').length,
                effort: 'low',
                description: `Testing adoption ${input.teamTestingAdoption}% vs org avg ${input.orgAvgTestingAdoption}%. Each +10% testing correlates with ~3% success improvement.`,
            });
        }
    }
    if (input.teamCIRate !== undefined && input.orgAvgCIRate !== undefined) {
        const ciGap = input.orgAvgCIRate - input.teamCIRate;
        if (ciGap > 10) {
            opportunities.push({
                title: 'Adopt CI/CD Pipeline',
                category: 'devops',
                currentValue: input.teamCIRate,
                expectedValue: input.orgAvgCIRate,
                impact: Math.round(ciGap * 0.25),
                confidence: 0.82,
                evidenceCount: 1,
                effort: 'medium',
                description: `CI/CD adoption ${input.teamCIRate}% vs org avg ${input.orgAvgCIRate}%. CI/CD correlates with higher deployment success.`,
            });
        }
    }
    if (input.teamReviewRate !== undefined && input.orgAvgReviewRate !== undefined) {
        const reviewGap = input.orgAvgReviewRate - input.teamReviewRate;
        if (reviewGap > 10) {
            opportunities.push({
                title: 'Increase Code Review Coverage',
                category: 'review',
                currentValue: input.teamReviewRate,
                expectedValue: input.orgAvgReviewRate,
                impact: Math.round(reviewGap * 0.2),
                confidence: 0.75,
                evidenceCount: 1,
                effort: 'low',
                description: `Code review at ${input.teamReviewRate}% vs org avg ${input.orgAvgReviewRate}%. Reviews reduce defect rate.`,
            });
        }
    }
    const communityGap = input.communityAvgSuccessRate - input.currentSuccessRate;
    if (communityGap > 0.1) {
        opportunities.push({
            title: 'Adopt Community Best Practices',
            category: 'community',
            currentValue: Math.round(input.currentSuccessRate * 100),
            expectedValue: Math.round(input.communityAvgSuccessRate * 100),
            impact: Math.round(communityGap * 100),
            confidence: 0.91,
            evidenceCount: input.gaps.length,
            effort: 'high',
            description: `Community avg ${Math.round(input.communityAvgSuccessRate * 100)}% vs current ${Math.round(input.currentSuccessRate * 100)}%. ${input.gaps.length} knowledge gaps to close. Expected impact +${Math.round(communityGap * 100)}pp success rate.`,
        });
    }
    return opportunities.sort((a, b) => b.impact - a.impact).slice(0, 10);
}
function analyzeRisks(input) {
    const risks = [];
    if (input.knowledgeSilos && input.knowledgeSilos.length > 0) {
        const highGaps = input.knowledgeSilos.filter(g => g.impact === 'high');
        if (highGaps.length > 0) {
            risks.push({
                title: `${highGaps.length} Critical Knowledge Gaps`,
                category: 'knowledge',
                rootCause: 'Low adoption of community-proven patterns',
                probability: Math.min(0.5 + highGaps.length * 0.05, 0.95),
                impact: 'high',
                riskScore: Math.round(Math.min(highGaps.length * 15, 100)),
                recommendation: 'Prioritize adopting high-gap patterns. Start with testing category.',
                evidencePoints: highGaps.slice(0, 5).map(g => `${g.patternId}: ${Math.round(g.gapSize * 100)}% gap, ${g.communitySampleSize} community outcomes`),
            });
        }
    }
    if (input.teamSuccessRate !== undefined && input.orgAvgSuccessRate !== undefined) {
        const rateGap = input.orgAvgSuccessRate - input.teamSuccessRate;
        if (rateGap > 0.15) {
            risks.push({
                title: 'Team Success Rate Below Org Average',
                category: 'performance',
                rootCause: 'Inconsistent pattern adoption or skill gaps',
                probability: Math.min(rateGap * 2, 0.9),
                impact: 'high',
                riskScore: Math.round(rateGap * 100),
                recommendation: 'Analyze top-performing team patterns and adopt across team.',
                evidencePoints: [`Team success: ${Math.round(input.teamSuccessRate * 100)}%`, `Org average: ${Math.round(input.orgAvgSuccessRate * 100)}%`],
            });
        }
    }
    if (input.busFactorScore !== undefined && input.busFactorScore > 60) {
        risks.push({
            title: 'High Bus Factor Risk',
            category: 'people',
            rootCause: 'Knowledge concentrated in few individuals',
            probability: Math.min(input.busFactorScore / 100, 0.95),
            impact: 'high',
            riskScore: input.busFactorScore,
            recommendation: 'Implement knowledge sharing sessions. Rotate responsibilities. Document critical patterns.',
            evidencePoints: [`Bus factor score: ${input.busFactorScore}/100`, `${input.memberCount || 0} team members`],
        });
    }
    if (input.teamTestingAdoption !== undefined && input.teamTestingAdoption < 30) {
        risks.push({
            title: 'Low Testing Adoption',
            category: 'quality',
            rootCause: 'Testing not prioritized in workflow',
            probability: 0.7,
            impact: 'medium',
            riskScore: Math.round((30 - input.teamTestingAdoption) * 2),
            recommendation: 'Start with critical path tests. Aim for 30% minimum coverage.',
            evidencePoints: [`Testing adoption: ${input.teamTestingAdoption}%`, 'Teams with <30% testing show 2x defect rate'],
        });
    }
    if (input.teamRiskScore !== undefined && input.teamRiskScore > 50) {
        risks.push({
            title: 'Elevated Team Risk Profile',
            category: 'overall',
            rootCause: 'Combination of low testing, concentrated knowledge, and process gaps',
            probability: Math.min(input.teamRiskScore / 100, 0.9),
            impact: 'high',
            riskScore: input.teamRiskScore,
            recommendation: 'Address top risk factors: testing, knowledge sharing, and CI/CD adoption.',
            evidencePoints: [`Overall risk score: ${input.teamRiskScore}/100`],
        });
    }
    return risks.sort((a, b) => b.riskScore - a.riskScore);
}
function classifyLifecycle(input) {
    return input.patterns.map(p => {
        const trend = p.communityTrend;
        let stage;
        if (trend === 'exploding' || (trend === 'rising' && (p.communityUsage > 50 || (p.orgUsage || 0) > 20))) {
            stage = 'growing';
        }
        else if (trend === 'rising') {
            stage = 'emerging';
        }
        else if (trend === 'stable' && p.communityUsage > 100) {
            stage = 'mature';
        }
        else if (trend === 'declining' || trend === 'dead') {
            stage = trend === 'dead' ? 'dead' : 'declining';
        }
        else if (p.communityUsage > 200) {
            stage = 'mature';
        }
        else if (p.communityUsage > 50) {
            stage = 'growing';
        }
        else if (p.communityUsage > 10) {
            stage = 'emerging';
        }
        else {
            stage = 'emerging';
        }
        const estimatedLifespan = stage === 'emerging' ? '6-12 months' :
            stage === 'growing' ? '12-24 months' :
                stage === 'mature' ? '24-48 months' :
                    stage === 'declining' ? '6-12 months' : '0-3 months';
        return {
            patternId: p.patternId,
            category: p.category,
            stage,
            communityTrend: p.communityTrend || 'stable',
            orgTrend: p.orgTrend || 'unknown',
            personalTrend: p.personalSuccessRate !== undefined ? (p.personalSuccessRate > 0.7 ? 'strong' : p.personalSuccessRate > 0.4 ? 'moderate' : 'weak') : 'unknown',
            totalUsage: p.communityUsage + (p.orgUsage || 0) + (p.personalUsage || 0),
            avgSuccessRate: p.avgSuccessRate || 0,
            confidence: p.confidence || 0,
            estimatedLifespan,
        };
    });
}
function generateDecisions(input) {
    const decisions = [];
    let priority = 1;
    for (const risk of input.risks.filter(r => r.impact === 'high')) {
        decisions.push({
            priority: priority++,
            action: `Mitigate: ${risk.title}`,
            category: risk.category,
            impact: risk.riskScore,
            impactUnit: 'risk points',
            confidence: Math.round((1 - risk.probability) * 100),
            evidenceCount: 1,
            effort: risk.riskScore > 70 ? 'high' : 'medium',
            recommendations: [risk.recommendation],
            keyEvidence: [{
                    type: 'org',
                    source: risk.rootCause,
                    value: risk.probability,
                    sampleSize: 1,
                    description: risk.rootCause,
                    weight: 1,
                }],
        });
    }
    for (const opp of input.opportunities.slice(0, 3)) {
        decisions.push({
            priority: priority++,
            action: opp.title,
            category: opp.category,
            impact: opp.impact,
            impactUnit: 'percentage points',
            confidence: Math.round(opp.confidence * 100),
            evidenceCount: opp.evidenceCount,
            effort: opp.effort,
            recommendations: opp.description ? [opp.description] : [],
            keyEvidence: [{
                    type: 'community',
                    source: 'Opportunity analysis',
                    value: opp.expectedValue / 100,
                    sampleSize: opp.evidenceCount,
                    description: `From ${opp.currentValue}% to ${opp.expectedValue}%`,
                    weight: opp.confidence,
                }],
        });
    }
    for (const gap of input.knowledgeGaps.filter(g => g.impact === 'high').slice(0, 2)) {
        decisions.push({
            priority: priority++,
            action: `Close Knowledge Gap: ${gap.patternId}`,
            category: gap.category,
            impact: Math.round(gap.gapSize * 100),
            impactUnit: 'percentage points',
            confidence: 70,
            evidenceCount: gap.communitySampleSize,
            effort: 'medium',
            recommendations: [gap.recommendation],
            keyEvidence: [{
                    type: 'community',
                    source: `Community (${gap.communitySampleSize} outcomes)`,
                    value: gap.communitySuccessRate,
                    sampleSize: gap.communitySampleSize,
                    description: `Community: ${Math.round(gap.communitySuccessRate * 100)}%, Org: ${Math.round(gap.orgSuccessRate * 100)}%`,
                    weight: Math.min(gap.communitySampleSize / 500, 1),
                }],
        });
    }
    return decisions.sort((a, b) => a.priority - b.priority);
}
function computeMultiLevelBenchmarks(input) {
    return input.metrics.map(m => {
        const levels = [];
        if (m.personalValue !== undefined && m.personalSampleSize !== undefined) {
            levels.push({ level: 'personal', value: m.personalValue, sampleSize: m.personalSampleSize });
        }
        if (m.teamValue !== undefined && m.teamSampleSize !== undefined) {
            levels.push({ level: 'team', value: m.teamValue, sampleSize: m.teamSampleSize });
        }
        if (m.orgValue !== undefined && m.orgSampleSize !== undefined) {
            levels.push({ level: 'org', value: m.orgValue, sampleSize: m.orgSampleSize });
        }
        if (m.communityAvg !== undefined && m.communitySampleSize !== undefined) {
            const percentile = m.personalValue !== undefined
                ? Math.round(Math.min((m.personalValue / Math.max(m.communityP90 || m.communityAvg, 0.01)) * 100, 100))
                : undefined;
            levels.push({
                level: 'community',
                value: m.communityAvg,
                percentile,
                sampleSize: m.communitySampleSize,
            });
        }
        const sorted = [...levels].sort((a, b) => b.value - a.value);
        const gapToNext = levels.length >= 2
            ? Math.round((sorted[0].value - sorted[1].value) * 100) / 100
            : null;
        const gapToBest = levels.length >= 2
            ? Math.round((sorted[0].value - sorted[sorted.length - 1].value) * 100) / 100
            : null;
        return {
            metric: m.name,
            levels,
            gapToNext,
            gapToBest,
            trend: levels.length >= 3 && levels[levels.length - 1].value > levels[levels.length - 2].value ? 'improving' : 'stable',
        };
    });
}
function generateIntelligenceReport(input) {
    const strengths = [];
    const weaknesses = [];
    const ctx = input.unifiedContext;
    const score = input.intelligenceScore;
    if (score.dimensions.personalSuccess >= 70)
        strengths.push(`High personal success rate (${score.dimensions.personalSuccess}%)`);
    else
        weaknesses.push(`Personal success rate below 70% (${score.dimensions.personalSuccess}%)`);
    if (score.dimensions.communityReputation >= 70)
        strengths.push('Strong community reputation');
    else if (score.dimensions.communityReputation > 0)
        weaknesses.push('Below-average community reputation');
    if (score.dimensions.orgAlignment >= 70)
        strengths.push('Well-aligned with organization practices');
    else if (score.dimensions.orgAlignment > 0)
        weaknesses.push('Low alignment with organization practices');
    if (score.dimensions.dnaMaturity >= 70)
        strengths.push('Mature project architecture and practices');
    else if (score.dimensions.dnaMaturity > 0)
        weaknesses.push('Immature project practices');
    if (ctx.personal && ctx.personal.topCategories.length > 2)
        strengths.push(`Broad expertise across ${ctx.personal.topCategories.length} categories`);
    if (ctx.personal && ctx.personal.patternsUsed > 50)
        strengths.push(`Extensive pattern usage (${ctx.personal.patternsUsed} patterns)`);
    if (input.knowledgeGaps.length > 0)
        weaknesses.push(`${input.knowledgeGaps.length} knowledge gaps between team and community`);
    const highRisks = input.risks.filter(r => r.impact === 'high');
    if (highRisks.length > 0)
        weaknesses.push(`${highRisks.length} high-impact risks detected`);
    const summary = `Intelligence report for ${input.targetType} "${input.targetId}": ` +
        `Intelligence score ${score.overallScore}/100. ` +
        `${(input.decisions || []).length} recommended actions. ` +
        `${input.knowledgeGaps.length} knowledge gaps. ` +
        `${input.opportunities.length} opportunities. ` +
        `${input.risks.length} risks. ` +
        `Based on ${score.sampleSize} patterns across ${ctx.combined.primaryLanguages.join(', ') || 'unknown'} languages.`;
    const reportId = `report_${input.targetType}_${input.targetId}_${Date.now()}`;
    const report = {
        reportId,
        targetId: input.targetId,
        targetType: input.targetType,
        generatedAt: Date.now(),
        unifiedContext: input.unifiedContext,
        intelligenceScore: input.intelligenceScore,
        decisions: input.decisions || [],
        gaps: input.knowledgeGaps,
        opportunities: input.opportunities,
        risks: input.risks,
        benchmarks: input.benchmarks,
        strengths,
        weaknesses,
        summary,
    };
    const store = loadStore();
    store.reports[reportId] = report;
    saveStore(store);
    return report;
}
function getReport(reportId) {
    const store = loadStore();
    return store.reports[reportId] || null;
}
function listReports() {
    const store = loadStore();
    return Object.keys(store.reports);
}
//# sourceMappingURL=cross-layer-intelligence.js.map