/**
 * EUAIActAuditBot -- Automated EU AI Act (Regulation EU 2024/1689) auditing.
 *
 * Covers: prohibited practice monitoring (Art. 5), risk classification,
 * high-risk system documentation (Annex III), GPAI obligations (Art. 53/55),
 * human oversight controls, conformity assessment readiness, and FRIA
 * generation. Does NOT call external APIs.
 *
 * Narrative writing is delegated to an injectable NarrativeWriter.
 *
 * P2A-06
 *
 * @connexum/ai-governance
 */
import * as fs from 'fs';
import * as path from 'path';
import { computeAuditScore, } from './scheduler.js';
export class StubNarrativeWriter {
    write(controlId, context) {
        return `[EU AI Act] Article/Control ${controlId} narrative: ${context.slice(0, 120)}`;
    }
}
export class EUAIActAuditBot {
    logDir;
    governanceDir;
    narrativeWriter;
    constructor(config) {
        this.logDir = config.logDir;
        this.governanceDir = config.governanceDir;
        this.narrativeWriter = config.narrativeWriter ?? new StubNarrativeWriter();
    }
    runAudit() {
        const checks = [
            // Art. 5: Prohibited practices
            this.checkProhibitedPractices(),
            this.checkSubliminalManipulation(),
            // Art. 6 + Annex III: Risk classification
            this.checkRiskClassification(),
            this.checkHighRiskDocumentation(),
            // Art. 9: Risk management system
            this.checkRiskManagementSystem(),
            // Art. 10: Data governance
            this.checkDataGovernance(),
            // Art. 13-15: Transparency + human oversight
            this.checkTransparencyObligations(),
            this.checkHumanOversight(),
            // Art. 17: Quality management system
            this.checkQualityManagementSystem(),
            // Art. 53-55: GPAI obligations
            this.checkGPAITechnicalDocumentation(),
            this.checkGPAISystemicRiskMitigation(),
            // Art. 62: Serious incident reporting
            this.checkSeriousIncidentReporting(),
            // Conformity / registration
            this.checkConformityAssessmentReadiness(),
        ];
        const { score, passed, failed, warnings } = computeAuditScore(checks);
        return {
            auditId: '',
            packId: 'euaiact',
            timestamp: new Date().toISOString(),
            checks,
            score,
            passed,
            failed,
            warnings,
        };
    }
    // --- Art. 5: Prohibited practices ---
    checkProhibitedPractices() {
        const ppFile = path.join(this.governanceDir, 'prohibited-practices.json');
        const exists = fs.existsSync(ppFile);
        return {
            id: 'euaiact-art5-prohibited',
            title: 'Art. 5: Prohibited practice controls active',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Prohibited practices configuration found; subliminal/deceptive AI blocked'
                : 'No prohibited-practices.json -- Art. 5 compliance not configured',
            evidence: exists ? ppFile : undefined,
        };
    }
    checkSubliminalManipulation() {
        const injectorFile = path.join(this.governanceDir, 'transparency-injector.json');
        const capFile = path.join(this.governanceDir, 'capability-bundles.json');
        const exists = fs.existsSync(injectorFile) || fs.existsSync(capFile);
        return {
            id: 'euaiact-art5-subliminal',
            title: 'Art. 5: Subliminal technique prevention',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Transparency injector or capability bundles limit manipulative outputs'
                : 'No transparency-injector.json or capability-bundles.json -- subliminal technique guard not verified',
            evidence: exists
                ? [injectorFile, capFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Art. 6 + Annex III: Risk classification ---
    checkRiskClassification() {
        const riskFile = path.join(this.governanceDir, 'ai-risk-classification.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(riskFile) || fs.existsSync(govFile);
        return {
            id: 'euaiact-art6-classification',
            title: 'Art. 6: AI system risk classification documented',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Risk classification documentation found'
                : 'No ai-risk-classification.json -- prohibited/high-risk/limited/minimal classification required',
            evidence: exists
                ? [riskFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkHighRiskDocumentation() {
        const docFile = path.join(this.governanceDir, 'high-risk-system-doc.json');
        const exists = fs.existsSync(docFile);
        return {
            id: 'euaiact-annexiii-doc',
            title: 'Annex III: High-risk system documentation',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'High-risk system technical documentation found per Art. 11'
                : 'No high-risk-system-doc.json -- if system is Annex III, technical docs are required',
            evidence: exists ? docFile : undefined,
        };
    }
    // --- Art. 9: Risk management ---
    checkRiskManagementSystem() {
        const riskFile = path.join(this.governanceDir, 'risk-assessment.json');
        const anomalyFile = path.join(this.governanceDir, 'anomaly-detection.json');
        const exists = fs.existsSync(riskFile) || fs.existsSync(anomalyFile);
        return {
            id: 'euaiact-art9-risk-mgmt',
            title: 'Art. 9: AI risk management system',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Risk assessment or anomaly detection configuration found'
                : 'No risk-assessment.json or anomaly-detection.json -- Art. 9 risk management system not evidenced',
            evidence: exists
                ? [riskFile, anomalyFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Art. 10: Data governance ---
    checkDataGovernance() {
        const classifierFile = path.join(this.governanceDir, 'data-classifier.json');
        const exists = fs.existsSync(classifierFile);
        return {
            id: 'euaiact-art10-data-governance',
            title: 'Art. 10: Training data governance',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Data classifier configured per Art. 10 data governance requirements'
                : 'No data-classifier.json -- training/operational data classification not evidenced',
            evidence: exists ? classifierFile : undefined,
        };
    }
    // --- Art. 13-15: Transparency and oversight ---
    checkTransparencyObligations() {
        const transparencyFile = path.join(this.governanceDir, 'transparency.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(transparencyFile) || fs.existsSync(govFile);
        return {
            id: 'euaiact-art13-transparency',
            title: 'Art. 13: Transparency and provision of information',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Transparency configuration or governance rules found per Art. 13'
                : 'No transparency.json or governance.json -- AI disclosure obligations not configured',
            evidence: exists
                ? [transparencyFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkHumanOversight() {
        const hitlFile = path.join(this.governanceDir, 'hitl-config.json');
        const approvalFile = path.join(this.governanceDir, 'approval-queue.json');
        const cbFile = path.join(this.governanceDir, 'circuit-breaker.json');
        const exists = fs.existsSync(hitlFile) || fs.existsSync(approvalFile) || fs.existsSync(cbFile);
        return {
            id: 'euaiact-art14-human-oversight',
            title: 'Art. 14: Human oversight measures',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Human-in-the-loop / circuit breaker configuration found per Art. 14'
                : 'No hitl-config.json, approval-queue.json, or circuit-breaker.json -- human oversight not evidenced',
            evidence: exists
                ? [hitlFile, approvalFile, cbFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Art. 17: Quality management ---
    checkQualityManagementSystem() {
        const qmsFile = path.join(this.governanceDir, 'quality-management.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(qmsFile) || fs.existsSync(govFile);
        return {
            id: 'euaiact-art17-qms',
            title: 'Art. 17: Quality management system',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Quality management or governance system configuration found'
                : 'No quality-management.json -- Art. 17 QMS not documented',
            evidence: exists
                ? [qmsFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Art. 53-55: GPAI obligations ---
    checkGPAITechnicalDocumentation() {
        const gpaiFile = path.join(this.governanceDir, 'gpai-technical-doc.json');
        const exists = fs.existsSync(gpaiFile);
        return {
            id: 'euaiact-art53-gpai-doc',
            title: 'Art. 53: GPAI technical documentation',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'GPAI technical documentation found per Art. 53'
                : 'No gpai-technical-doc.json -- if GPAI provider, Art. 53 technical docs are mandatory',
            evidence: exists ? gpaiFile : undefined,
        };
    }
    checkGPAISystemicRiskMitigation() {
        const srmFile = path.join(this.governanceDir, 'systemic-risk-mitigation.json');
        const exists = fs.existsSync(srmFile);
        return {
            id: 'euaiact-art55-systemic-risk',
            title: 'Art. 55: Systemic risk mitigation (GPAI)',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Systemic risk mitigation configuration found per Art. 55'
                : 'No systemic-risk-mitigation.json -- if systemic-risk GPAI, Art. 55 adversarial testing required',
            evidence: exists ? srmFile : undefined,
        };
    }
    // --- Art. 62: Serious incident reporting ---
    checkSeriousIncidentReporting() {
        const irFile = path.join(this.governanceDir, 'incident-response.json');
        const notifyFile = path.join(this.governanceDir, 'incident-notification.json');
        const exists = fs.existsSync(irFile) || fs.existsSync(notifyFile);
        return {
            id: 'euaiact-art62-incident',
            title: 'Art. 62: Serious incident reporting',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Incident response/notification configuration found per Art. 62'
                : 'No incident-response.json or incident-notification.json -- serious incident reporting not configured',
            evidence: exists
                ? [irFile, notifyFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Conformity assessment ---
    checkConformityAssessmentReadiness() {
        const conformityFile = path.join(this.governanceDir, 'conformity-assessment.json');
        const hasLogs = fs.existsSync(this.logDir) &&
            fs.readdirSync(this.logDir).some((f) => f.endsWith('.jsonl'));
        const exists = fs.existsSync(conformityFile) || hasLogs;
        return {
            id: 'euaiact-conformity',
            title: 'Conformity assessment readiness',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Audit trail and/or conformity documentation found for assessment'
                : 'No audit trail or conformity-assessment.json -- conformity assessment evidence insufficient',
            evidence: exists
                ? (fs.existsSync(conformityFile) ? conformityFile : this.logDir)
                : undefined,
        };
    }
    // ---------------------------------------------------------------------------
    // Gap analysis
    // ---------------------------------------------------------------------------
    analyzeGaps(result) {
        return result.checks
            .filter((c) => c.status === 'fail' || c.status === 'warning')
            .map((c) => ({
            article: c.id,
            title: c.title,
            detail: c.detail,
            riskLevel: c.id.includes('art5') || c.id.includes('prohibited')
                ? 'prohibited'
                : c.id.includes('art14') || c.id.includes('art9') || c.id.includes('art62')
                    ? 'high'
                    : 'medium',
        }));
    }
    // ---------------------------------------------------------------------------
    // FRIA generator (Fundamental Rights Impact Assessment stub)
    // ---------------------------------------------------------------------------
    generateFRIA(result) {
        const gaps = this.analyzeGaps(result);
        return {
            document: 'Fundamental Rights Impact Assessment',
            framework: 'EU AI Act Art. 27',
            generatedAt: new Date().toISOString(),
            overallScore: result.score,
            fundamentalRightsImpact: result.score >= 70 ? 'low' : result.score >= 40 ? 'medium' : 'high',
            openGaps: gaps.length,
            criticalGaps: gaps.filter((g) => g.riskLevel === 'prohibited' || g.riskLevel === 'high').length,
            narrative: this.narrativeWriter.write('FRIA', `Score ${result.score}/100. ${gaps.length} gaps identified.`),
        };
    }
    // ---------------------------------------------------------------------------
    // Report generation
    // ---------------------------------------------------------------------------
    generateReport(result, outputDir) {
        if (!fs.existsSync(outputDir))
            fs.mkdirSync(outputDir, { recursive: true });
        const gaps = this.analyzeGaps(result);
        const fria = this.generateFRIA(result);
        const narrative = this.narrativeWriter.write('EU-AI-ACT-2024/1689', `Score: ${result.score}/100. ${result.passed} controls passed, ${result.failed} failed.`);
        const report = {
            framework: 'EU AI Act (Regulation EU 2024/1689)',
            generatedAt: new Date().toISOString(),
            auditId: result.auditId,
            score: result.score,
            passed: result.passed,
            failed: result.failed,
            warnings: result.warnings,
            narrative,
            gaps,
            fria,
            checks: result.checks,
        };
        const filename = `euaiact-report-${Date.now()}.json`;
        const filePath = path.join(outputDir, filename);
        fs.writeFileSync(filePath, JSON.stringify(report, null, 2));
        return filePath;
    }
}
//# sourceMappingURL=euaiact.js.map