"use strict";
/**
 * ComplianceReporter -- Generates audit-ready compliance reports.
 *
 * Reads from audit logs, token tracking, and file change logs
 * to produce structured reports for SOC 2, HIPAA, GDPR, etc.
 *
 * @connexum/ai-governance
 */
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.ComplianceReporter = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class ComplianceReporter {
    config;
    constructor(config) {
        this.config = config;
    }
    /**
     * Generate a full compliance report.
     */
    generate() {
        const auditEntries = this.loadJsonl(this.config.auditDir, 'audit-');
        const tokenEntries = this.config.tokenDir
            ? this.loadJsonl(this.config.tokenDir, 'tokens-')
            : [];
        const fileChanges = this.config.fileChangeDir
            ? this.loadJsonl(this.config.fileChangeDir, 'changes-')
            : [];
        // Filter to report period
        const periodAudit = this.filterByPeriod(auditEntries);
        const periodTokens = this.filterByPeriod(tokenEntries);
        const periodFiles = this.filterByPeriod(fileChanges);
        const uniqueAgents = new Set(periodAudit.map((e) => e.agent));
        const totalTokens = periodTokens.reduce((sum, e) => sum + (e.tokens || 0), 0);
        // Count blocked actions from audit entries that indicate denial
        const blockedCount = periodAudit.filter((e) => {
            const entry = e;
            return entry.result === 'blocked' || entry.result === 'denied' ||
                (typeof entry.tool === 'string' && entry.tool.startsWith('BLOCKED:'));
        }).length;
        const summary = {
            totalToolCalls: periodAudit.length,
            uniqueAgents: uniqueAgents.size,
            blockedActions: blockedCount,
            anomaliesDetected: 0,
            filesModified: periodFiles.length,
            totalTokensUsed: totalTokens,
            complianceScore: this.computeComplianceScore(periodAudit, periodFiles),
        };
        const sections = [
            this.buildAccessControlSection(periodAudit),
            this.buildActivitySection(periodAudit),
            this.buildTokenUsageSection(periodTokens),
            this.buildFileIntegritySection(periodFiles),
            this.buildAgentBehaviorSection(periodAudit),
        ];
        return {
            title: `AI Governance Compliance Report`,
            generatedAt: new Date().toISOString(),
            period: {
                start: this.config.periodStart.toISOString(),
                end: this.config.periodEnd.toISOString(),
            },
            company: this.config.companyName,
            summary,
            sections,
        };
    }
    /**
     * Export report as Markdown.
     */
    toMarkdown(report) {
        let md = `# ${report.title}\n\n`;
        md += `**Company**: ${report.company}\n`;
        md += `**Period**: ${report.period.start.split('T')[0]} to ${report.period.end.split('T')[0]}\n`;
        md += `**Generated**: ${report.generatedAt}\n\n`;
        md += `## Executive Summary\n\n`;
        md += `| Metric | Value |\n|--------|-------|\n`;
        md += `| Total Tool Calls | ${report.summary.totalToolCalls} |\n`;
        md += `| Unique Agents | ${report.summary.uniqueAgents} |\n`;
        md += `| Blocked Actions | ${report.summary.blockedActions} |\n`;
        md += `| Anomalies Detected | ${report.summary.anomaliesDetected} |\n`;
        md += `| Files Modified | ${report.summary.filesModified} |\n`;
        md += `| Total Tokens Used | ${report.summary.totalTokensUsed.toLocaleString()} |\n`;
        md += `| Compliance Score | ${report.summary.complianceScore}% |\n\n`;
        for (const section of report.sections) {
            md += `## ${section.title}\n\n`;
            md += `${section.content}\n\n`;
            if (section.data && section.data.length > 0) {
                const keys = Object.keys(section.data[0]);
                md += `| ${keys.join(' | ')} |\n`;
                md += `| ${keys.map(() => '---').join(' | ')} |\n`;
                for (const row of section.data.slice(0, 50)) {
                    md += `| ${keys.map((k) => String(row[k] ?? '')).join(' | ')} |\n`;
                }
                md += '\n';
            }
        }
        return md;
    }
    buildAccessControlSection(entries) {
        const agentToolMap = new Map();
        for (const entry of entries) {
            const tools = agentToolMap.get(entry.agent) || new Set();
            tools.add(entry.tool);
            agentToolMap.set(entry.agent, tools);
        }
        const data = Array.from(agentToolMap.entries()).map(([agent, tools]) => ({
            Agent: agent,
            'Tools Used': Array.from(tools).join(', '),
            'Call Count': entries.filter((e) => e.agent === agent).length,
        }));
        return {
            title: 'Access Control',
            content: 'Agent tool access patterns during the reporting period. All access governed by deny-by-default PERMISSIONS.md files.',
            data,
        };
    }
    buildActivitySection(entries) {
        // Group by day
        const daily = new Map();
        for (const entry of entries) {
            const day = entry.timestamp?.split('T')[0] || 'unknown';
            daily.set(day, (daily.get(day) || 0) + 1);
        }
        const data = Array.from(daily.entries())
            .sort()
            .map(([date, count]) => ({ Date: date, 'Tool Calls': count }));
        return {
            title: 'Daily Activity',
            content: 'Tool call volume by day across all agents.',
            data,
        };
    }
    buildTokenUsageSection(entries) {
        const agentTokens = new Map();
        for (const entry of entries) {
            agentTokens.set(entry.agent, (agentTokens.get(entry.agent) || 0) + (entry.tokens || 0));
        }
        const data = Array.from(agentTokens.entries())
            .sort((a, b) => b[1] - a[1])
            .map(([agent, tokens]) => ({
            Agent: agent,
            'Total Tokens': tokens.toLocaleString(),
        }));
        return {
            title: 'Token Usage by Agent',
            content: 'API token consumption per agent. Used for cost allocation and anomaly detection.',
            data,
        };
    }
    buildFileIntegritySection(entries) {
        const fileCounts = new Map();
        for (const entry of entries) {
            fileCounts.set(entry.file, (fileCounts.get(entry.file) || 0) + 1);
        }
        const data = Array.from(fileCounts.entries())
            .sort((a, b) => b[1] - a[1])
            .slice(0, 20)
            .map(([file, count]) => ({
            File: file,
            'Modification Count': count,
        }));
        return {
            title: 'File Integrity',
            content: 'Most frequently modified files. All changes tracked with SHA-256 hashes for rollback.',
            data,
        };
    }
    buildAgentBehaviorSection(entries) {
        const agents = new Set(entries.map((e) => e.agent));
        return {
            title: 'Agent Behavioral Analysis',
            content: `${agents.size} agents were active during this period. ` +
                `All agents operated under deny-by-default permission model. ` +
                `Governance files verified via SHA-256 tamper detection on every session start.`,
        };
    }
    /**
     * Compute governance activity score based on measurable criteria.
     *
     * DISCLAIMER: This is a governance activity metric, NOT a compliance
     * certification score. It measures the presence and activity of
     * governance controls, not legal or regulatory compliance status.
     * Actual compliance requires independent audit assessment.
     */
    computeComplianceScore(audit, files) {
        let score = 0;
        let maxScore = 0;
        // 1. Audit trail exists and has entries (20 points)
        maxScore += 20;
        if (audit.length > 0)
            score += 20;
        // 2. Multiple agents are governed (20 points)
        maxScore += 20;
        const agents = new Set(audit.map(e => e.agent));
        if (agents.size >= 3)
            score += 20;
        else if (agents.size >= 1)
            score += 10;
        // 3. File changes are tracked (20 points)
        maxScore += 20;
        if (files.length > 0)
            score += 20;
        // 4. Blocked actions exist (governance is enforcing, 20 points)
        maxScore += 20;
        const blocked = audit.filter(e => {
            const entry = e;
            return entry.result === 'blocked' || entry.result === 'denied';
        });
        if (blocked.length > 0)
            score += 20;
        // 5. Consistent daily activity (20 points)
        maxScore += 20;
        const days = new Set(audit.map(e => e.timestamp?.split('T')[0]).filter(Boolean));
        const periodDays = Math.max(1, Math.ceil((this.config.periodEnd.getTime() - this.config.periodStart.getTime()) / 86400000));
        const coverageRatio = days.size / periodDays;
        if (coverageRatio >= 0.8)
            score += 20;
        else if (coverageRatio >= 0.5)
            score += 10;
        return Math.round((score / maxScore) * 100);
    }
    loadJsonl(dir, prefix) {
        if (!fs.existsSync(dir))
            return [];
        const entries = [];
        const files = fs.readdirSync(dir).filter((f) => f.startsWith(prefix) && f.endsWith('.jsonl'));
        for (const file of files) {
            try {
                const lines = fs.readFileSync(path.join(dir, file), 'utf-8')
                    .trim()
                    .split('\n')
                    .filter(Boolean);
                for (const line of lines) {
                    try {
                        entries.push(JSON.parse(line));
                    }
                    catch {
                        // Skip malformed lines
                    }
                }
            }
            catch {
                // Skip unreadable files
            }
        }
        return entries;
    }
    /**
     * Export report as JSON string.
     */
    toJSON(report) {
        return JSON.stringify(report, null, 2);
    }
    /**
     * Export report as HTML.
     */
    toHTML(report) {
        let html = '<!DOCTYPE html>\n<html lang="en">\n<head>\n';
        html += '<meta charset="UTF-8">\n';
        html += `<title>${this.escapeHtml(report.title)}</title>\n`;
        html += '<style>\n';
        html += 'body { font-family: -apple-system, BlinkMacSystemFont, sans-serif; max-width: 960px; margin: 0 auto; padding: 20px; color: #333; }\n';
        html += 'h1 { color: #1a1a1a; border-bottom: 2px solid #0066cc; padding-bottom: 8px; }\n';
        html += 'h2 { color: #333; margin-top: 32px; }\n';
        html += 'table { border-collapse: collapse; width: 100%; margin: 16px 0; }\n';
        html += 'th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }\n';
        html += 'th { background: #f5f5f5; font-weight: 600; }\n';
        html += 'tr:nth-child(even) { background: #fafafa; }\n';
        html += '.meta { color: #666; font-size: 14px; }\n';
        html += '.score { font-size: 24px; font-weight: bold; }\n';
        html += '.score.high { color: #2d8a2d; }\n';
        html += '.score.medium { color: #cc8800; }\n';
        html += '.score.low { color: #cc2200; }\n';
        html += '</style>\n</head>\n<body>\n';
        html += `<h1>${this.escapeHtml(report.title)}</h1>\n`;
        html += `<p class="meta"><strong>Company:</strong> ${this.escapeHtml(report.company)}</p>\n`;
        html += `<p class="meta"><strong>Period:</strong> ${report.period.start.split('T')[0]} to ${report.period.end.split('T')[0]}</p>\n`;
        html += `<p class="meta"><strong>Generated:</strong> ${report.generatedAt}</p>\n`;
        // Summary
        html += '<h2>Executive Summary</h2>\n';
        const scoreClass = report.summary.complianceScore >= 80 ? 'high' : report.summary.complianceScore >= 50 ? 'medium' : 'low';
        html += `<p>Governance Activity Score: <span class="score ${scoreClass}">${report.summary.complianceScore}%</span></p>\n`;
        html += '<table>\n<tr><th>Metric</th><th>Value</th></tr>\n';
        html += `<tr><td>Total Tool Calls</td><td>${report.summary.totalToolCalls}</td></tr>\n`;
        html += `<tr><td>Unique Agents</td><td>${report.summary.uniqueAgents}</td></tr>\n`;
        html += `<tr><td>Blocked Actions</td><td>${report.summary.blockedActions}</td></tr>\n`;
        html += `<tr><td>Anomalies Detected</td><td>${report.summary.anomaliesDetected}</td></tr>\n`;
        html += `<tr><td>Files Modified</td><td>${report.summary.filesModified}</td></tr>\n`;
        html += `<tr><td>Total Tokens Used</td><td>${report.summary.totalTokensUsed.toLocaleString()}</td></tr>\n`;
        html += '</table>\n';
        // Sections
        for (const section of report.sections) {
            html += `<h2>${this.escapeHtml(section.title)}</h2>\n`;
            html += `<p>${this.escapeHtml(section.content)}</p>\n`;
            if (section.data && section.data.length > 0) {
                const keys = Object.keys(section.data[0]);
                html += '<table>\n<tr>';
                for (const key of keys)
                    html += `<th>${this.escapeHtml(key)}</th>`;
                html += '</tr>\n';
                for (const row of section.data.slice(0, 50)) {
                    html += '<tr>';
                    for (const key of keys)
                        html += `<td>${this.escapeHtml(String(row[key] ?? ''))}</td>`;
                    html += '</tr>\n';
                }
                html += '</table>\n';
            }
        }
        html += `<p class="meta" style="margin-top: 40px; border-top: 1px solid #ddd; padding-top: 16px;">Generated by @connexum/ai-governance</p>\n`;
        html += '</body>\n</html>';
        return html;
    }
    /**
     * Generate a framework-specific report.
     * Adds framework-relevant sections to the base report.
     */
    generateForFramework(framework) {
        const baseReport = this.generate();
        const frameworkSections = this.getFrameworkSections(framework, baseReport);
        baseReport.title = `${FRAMEWORK_TITLES[framework]} Compliance Report`;
        baseReport.sections = [...frameworkSections, ...baseReport.sections];
        return baseReport;
    }
    getFrameworkSections(framework, report) {
        switch (framework) {
            case 'soc2':
                return [
                    {
                        title: 'SOC 2 Type II: Common Criteria',
                        content: 'Assessment of Trust Services Criteria coverage through AI governance controls.',
                        data: [
                            { Criterion: 'CC6.1', Description: 'Logical and Physical Access Controls', Status: report.summary.uniqueAgents > 0 ? 'Implemented' : 'Not Active', Evidence: 'Deny-by-default PERMISSIONS.md per agent' },
                            { Criterion: 'CC6.3', Description: 'Access Authorization', Status: report.summary.blockedActions > 0 ? 'Active Enforcement' : 'Monitoring Only', Evidence: 'Tool access filtering + approval queue' },
                            { Criterion: 'CC7.2', Description: 'System Monitoring', Status: report.summary.totalToolCalls > 0 ? 'Active' : 'Not Active', Evidence: 'JSONL audit trail + anomaly detection' },
                            { Criterion: 'CC8.1', Description: 'Change Management', Status: report.summary.filesModified > 0 ? 'Tracked' : 'No Changes', Evidence: 'SHA-256 file change tracking' },
                        ],
                    },
                ];
            case 'hipaa':
                return [
                    {
                        title: 'HIPAA Security Rule: Technical Safeguards',
                        content: 'Assessment of HIPAA technical safeguard requirements through AI governance controls.',
                        data: [
                            { Safeguard: '164.312(a)(1)', Description: 'Access Control', Status: 'Implemented', Evidence: 'Deny-by-default permissions, agent-specific access' },
                            { Safeguard: '164.312(b)', Description: 'Audit Controls', Status: report.summary.totalToolCalls > 0 ? 'Active' : 'Configured', Evidence: 'Hash-chained JSONL audit logs' },
                            { Safeguard: '164.312(c)(1)', Description: 'Integrity', Status: 'Implemented', Evidence: 'SHA-256 tamper detection on governance files' },
                            { Safeguard: '164.312(e)(1)', Description: 'Transmission Security', Status: 'Implemented', Evidence: 'AES-256-GCM encryption for data at rest' },
                        ],
                    },
                ];
            case 'gdpr':
                return [
                    {
                        title: 'GDPR: Data Protection Principles',
                        content: 'Assessment of GDPR compliance requirements through AI governance controls.',
                        data: [
                            { Article: 'Art. 5(1)(f)', Principle: 'Integrity and Confidentiality', Status: 'Implemented', Evidence: 'Encrypted storage, secret scanning' },
                            { Article: 'Art. 25', Principle: 'Data Protection by Design', Status: 'Implemented', Evidence: 'DataClassifier with PHI/PII detection' },
                            { Article: 'Art. 30', Principle: 'Records of Processing', Status: report.summary.totalToolCalls > 0 ? 'Active' : 'Configured', Evidence: 'Complete audit trail of all AI agent actions' },
                            { Article: 'Art. 32', Principle: 'Security of Processing', Status: 'Implemented', Evidence: 'Hook-based enforcement, circuit breaker' },
                        ],
                    },
                ];
            case 'pcidss':
                return [
                    {
                        title: 'PCI DSS v4.0: Requirements',
                        content: 'Assessment of PCI DSS requirements through AI governance controls.',
                        data: [
                            { Requirement: 'Req 7', Description: 'Restrict Access', Status: 'Implemented', Evidence: 'Deny-by-default access model' },
                            { Requirement: 'Req 8', Description: 'Identify Users and Authenticate', Status: 'Implemented', Evidence: 'Agent authentication with HKDF + nonce replay protection' },
                            { Requirement: 'Req 10', Description: 'Log and Monitor', Status: report.summary.totalToolCalls > 0 ? 'Active' : 'Configured', Evidence: 'JSONL audit trail with hash chain' },
                            { Requirement: 'Req 12', Description: 'Information Security Policy', Status: 'Implemented', Evidence: 'Governance rules with tamper detection' },
                        ],
                    },
                ];
            case 'dora':
                return [
                    {
                        title: 'DORA: ICT Risk Management',
                        content: 'Assessment of DORA requirements for digital operational resilience.',
                        data: [
                            { Article: 'Art. 6', Requirement: 'ICT Risk Management Framework', Status: 'Implemented', Evidence: 'Governance runtime with enforcement hooks' },
                            { Article: 'Art. 9', Requirement: 'Detection', Status: 'Implemented', Evidence: 'Anomaly detection, circuit breaker' },
                            { Article: 'Art. 10', Requirement: 'Response and Recovery', Status: 'Implemented', Evidence: 'Circuit breaker auto-suspension, DR plan' },
                            { Article: 'Art. 15', Requirement: 'ICT Third-Party Risk', Status: 'Implemented', Evidence: 'Provider compliance checks, DeepSeek blocking' },
                        ],
                    },
                ];
            case 'euaiact':
                return [
                    {
                        title: 'EU AI Act: High-Risk AI System Requirements',
                        content: 'Assessment of EU AI Act requirements for high-risk AI systems.',
                        data: [
                            { Article: 'Art. 5', Requirement: 'Prohibited Practices', Status: 'Implemented', Evidence: 'ProhibitedPractices scanner' },
                            { Article: 'Art. 9', Requirement: 'Risk Management', Status: 'Implemented', Evidence: 'Bias monitoring, anomaly detection' },
                            { Article: 'Art. 12', Requirement: 'Record-Keeping', Status: report.summary.totalToolCalls > 0 ? 'Active' : 'Configured', Evidence: 'Hash-chained audit logs' },
                            { Article: 'Art. 50', Requirement: 'Transparency', Status: 'Implemented', Evidence: 'TransparencyInjector for AI content labeling' },
                            { Article: 'Art. 72', Requirement: 'Post-Market Monitoring', Status: 'Implemented', Evidence: 'PostMarketMonitor with drift detection' },
                        ],
                    },
                ];
            default:
                return [];
        }
    }
    escapeHtml(text) {
        return text
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }
    filterByPeriod(entries) {
        const start = this.config.periodStart.getTime();
        const end = this.config.periodEnd.getTime();
        return entries.filter((e) => {
            const ts = new Date(e.timestamp).getTime();
            return ts >= start && ts <= end;
        });
    }
}
exports.ComplianceReporter = ComplianceReporter;
const FRAMEWORK_TITLES = {
    soc2: 'SOC 2 Type II',
    hipaa: 'HIPAA',
    gdpr: 'GDPR',
    pcidss: 'PCI DSS v4.0',
    dora: 'DORA',
    euaiact: 'EU AI Act',
};
//# sourceMappingURL=compliance-reporter.js.map