/**
 * ISO42001AuditBot -- Automated ISO/IEC 42001:2023 AIMS compliance auditing.
 *
 * Covers AI Management System Clauses 4-10, AI policy enforcement evidence,
 * AI resource management, AI risk control tracking, internal audit + management
 * review log, and AIMS documentation generator. Does NOT call external APIs.
 *
 * Narrative writing is delegated to an injectable NarrativeWriter.
 *
 * P2A-10
 *
 * @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 `[ISO 42001] Clause ${controlId}: ${context.slice(0, 120)}`;
    }
}
export class ISO42001AuditBot {
    logDir;
    governanceDir;
    narrativeWriter;
    constructor(config) {
        this.logDir = config.logDir;
        this.governanceDir = config.governanceDir;
        this.narrativeWriter = config.narrativeWriter ?? new StubNarrativeWriter();
    }
    runAudit() {
        const checks = [
            // Clause 4: Context of the organisation
            this.checkClause4Context(),
            this.checkClause4InterestedParties(),
            // Clause 5: Leadership
            this.checkClause5Leadership(),
            this.checkClause5AIPolicy(),
            // Clause 6: Planning
            this.checkClause6AIRisks(),
            this.checkClause6AIObjectives(),
            // Clause 7: Support (resources, competence, awareness, documented info)
            this.checkClause7Resources(),
            this.checkClause7DocumentedInformation(),
            // Clause 8: Operation
            this.checkClause8AISystemLifecycle(),
            this.checkClause8DataGovernance(),
            this.checkClause8AIImpactAssessment(),
            // Clause 9: Performance evaluation
            this.checkClause9InternalAudit(),
            this.checkClause9ManagementReview(),
            this.checkClause9MonitoringMeasurement(),
            // Clause 10: Improvement
            this.checkClause10NonconformityCorrection(),
            // Annex A controls
            this.checkAnnexA6DataManagement(),
            this.checkAnnexA8InformationSecurity(),
            this.checkAnnexA9AccessControl(),
        ];
        const { score, passed, failed, warnings } = computeAuditScore(checks);
        return {
            auditId: '',
            packId: 'iso42001',
            timestamp: new Date().toISOString(),
            checks,
            score,
            passed,
            failed,
            warnings,
        };
    }
    // --- Clause 4: Context ---
    checkClause4Context() {
        const govFile = path.join(this.governanceDir, 'governance.json');
        const contextFile = path.join(this.governanceDir, 'ai-system-context.json');
        const exists = fs.existsSync(govFile) || fs.existsSync(contextFile);
        return {
            id: 'iso42001-clause4-context',
            title: 'Clause 4: AI management system context',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'AIMS context documentation found per Clause 4'
                : 'No governance.json or ai-system-context.json -- AIMS scope/context not documented',
            evidence: exists
                ? [govFile, contextFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkClause4InterestedParties() {
        const stakeholderFile = path.join(this.governanceDir, 'stakeholder-engagement.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(stakeholderFile) || fs.existsSync(govFile);
        return {
            id: 'iso42001-clause4-interested-parties',
            title: 'Clause 4.2: Needs and expectations of interested parties',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Stakeholder engagement or governance file found per Clause 4.2'
                : 'No stakeholder-engagement.json -- interested parties register not evidenced',
            evidence: exists
                ? [stakeholderFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Clause 5: Leadership ---
    checkClause5Leadership() {
        const rolesFile = path.join(this.governanceDir, 'roles.json');
        const authFile = path.join(this.governanceDir, 'agent-auth.json');
        const exists = fs.existsSync(rolesFile) || fs.existsSync(authFile);
        return {
            id: 'iso42001-clause5-leadership',
            title: 'Clause 5: Top management leadership for AIMS',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Roles or authentication configuration evidences leadership accountability per Clause 5'
                : 'No roles.json or agent-auth.json -- management accountability for AIMS not evidenced',
            evidence: exists
                ? [rolesFile, authFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkClause5AIPolicy() {
        const policyFile = path.join(this.governanceDir, 'ai-policy.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(policyFile) || fs.existsSync(govFile);
        return {
            id: 'iso42001-clause5-policy',
            title: 'Clause 5.2: AI policy established',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'AI policy or governance configuration found per Clause 5.2'
                : 'No ai-policy.json or governance.json -- AI policy not documented',
            evidence: exists
                ? [policyFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Clause 6: Planning ---
    checkClause6AIRisks() {
        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: 'iso42001-clause6-risks',
            title: 'Clause 6: AI risks and opportunities addressed',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Risk assessment or anomaly detection configuration found per Clause 6'
                : 'No risk-assessment.json or anomaly-detection.json -- AI risk planning not evidenced',
            evidence: exists
                ? [riskFile, anomalyFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkClause6AIObjectives() {
        const objectivesFile = path.join(this.governanceDir, 'ai-objectives.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(objectivesFile) || fs.existsSync(govFile);
        return {
            id: 'iso42001-clause6-objectives',
            title: 'Clause 6.2: AI management objectives',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'AI objectives or governance file found per Clause 6.2'
                : 'No ai-objectives.json -- measurable AI management objectives not documented',
            evidence: exists
                ? [objectivesFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Clause 7: Support ---
    checkClause7Resources() {
        const capFile = path.join(this.governanceDir, 'capability-bundles.json');
        const exists = fs.existsSync(capFile);
        return {
            id: 'iso42001-clause7-resources',
            title: 'Clause 7.1: Resources for AI management',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Capability bundles configure AI resource management per Clause 7.1'
                : 'No capability-bundles.json -- AI resource management not configured',
            evidence: exists ? capFile : undefined,
        };
    }
    checkClause7DocumentedInformation() {
        const fileCount = fs.existsSync(this.governanceDir)
            ? fs.readdirSync(this.governanceDir).filter((f) => f.endsWith('.json') || f.endsWith('.md')).length
            : 0;
        const sufficient = fileCount >= 4;
        return {
            id: 'iso42001-clause7-docs',
            title: 'Clause 7.5: Documented information (4+ governance files)',
            status: sufficient ? 'pass' : 'warning',
            detail: sufficient
                ? `${fileCount} governance documents found per Clause 7.5`
                : `Only ${fileCount} governance files -- ISO 42001 requires comprehensive documented information`,
            evidence: sufficient ? this.governanceDir : undefined,
        };
    }
    // --- Clause 8: Operation ---
    checkClause8AISystemLifecycle() {
        const lcFile = path.join(this.governanceDir, 'ai-lifecycle.json');
        const govFile = path.join(this.governanceDir, 'governance.json');
        const exists = fs.existsSync(lcFile) || fs.existsSync(govFile);
        return {
            id: 'iso42001-clause8-lifecycle',
            title: 'Clause 8: AI system lifecycle management',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'AI lifecycle or governance configuration found per Clause 8'
                : 'No ai-lifecycle.json or governance.json -- AI system lifecycle not documented',
            evidence: exists
                ? [lcFile, govFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkClause8DataGovernance() {
        const classifierFile = path.join(this.governanceDir, 'data-classifier.json');
        const exists = fs.existsSync(classifierFile);
        return {
            id: 'iso42001-clause8-data',
            title: 'Clause 8 / A.6: AI data management',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Data classifier configuration found per Clause 8 / Annex A.6'
                : 'No data-classifier.json -- AI data governance not configured',
            evidence: exists ? classifierFile : undefined,
        };
    }
    checkClause8AIImpactAssessment() {
        const impactFile = path.join(this.governanceDir, 'ai-impact-assessment.json');
        const riskFile = path.join(this.governanceDir, 'risk-assessment.json');
        const exists = fs.existsSync(impactFile) || fs.existsSync(riskFile);
        return {
            id: 'iso42001-clause8-impact',
            title: 'Clause 8 / Annex C: AI system impact assessment',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Impact or risk assessment found per Clause 8 / Annex C'
                : 'No ai-impact-assessment.json -- AI system impact assessment not evidenced',
            evidence: exists
                ? [impactFile, riskFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Clause 9: Performance evaluation ---
    checkClause9InternalAudit() {
        const hasLogs = fs.existsSync(this.logDir) &&
            fs.readdirSync(this.logDir).some((f) => f.endsWith('.jsonl'));
        return {
            id: 'iso42001-clause9-audit',
            title: 'Clause 9.2: Internal audit',
            status: hasLogs ? 'pass' : 'fail',
            detail: hasLogs
                ? 'JSONL audit logs provide internal audit evidence per Clause 9.2'
                : 'No JSONL audit logs -- internal audit evidence not present',
            evidence: hasLogs ? this.logDir : undefined,
        };
    }
    checkClause9ManagementReview() {
        const reviewFile = path.join(this.governanceDir, 'management-review.json');
        const exists = fs.existsSync(reviewFile);
        return {
            id: 'iso42001-clause9-mgmt-review',
            title: 'Clause 9.3: Management review',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Management review record found per Clause 9.3'
                : 'No management-review.json -- periodic management review not evidenced',
            evidence: exists ? reviewFile : undefined,
        };
    }
    checkClause9MonitoringMeasurement() {
        const monitorFile = path.join(this.governanceDir, 'monitoring.json');
        const anomalyFile = path.join(this.governanceDir, 'anomaly-detection.json');
        const exists = fs.existsSync(monitorFile) || fs.existsSync(anomalyFile);
        return {
            id: 'iso42001-clause9-monitoring',
            title: 'Clause 9.1: AI performance monitoring and measurement',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Monitoring or anomaly detection found per Clause 9.1'
                : 'No monitoring.json or anomaly-detection.json -- AI performance monitoring not configured',
            evidence: exists
                ? [monitorFile, anomalyFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Clause 10: Improvement ---
    checkClause10NonconformityCorrection() {
        const irFile = path.join(this.governanceDir, 'incident-response.json');
        const cbFile = path.join(this.governanceDir, 'circuit-breaker.json');
        const exists = fs.existsSync(irFile) || fs.existsSync(cbFile);
        return {
            id: 'iso42001-clause10-nonconformity',
            title: 'Clause 10: Nonconformity and corrective action',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Incident response or circuit breaker enables corrective action per Clause 10'
                : 'No incident-response.json or circuit-breaker.json -- nonconformity handling not configured',
            evidence: exists
                ? [irFile, cbFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // --- Annex A controls ---
    checkAnnexA6DataManagement() {
        const classifierFile = path.join(this.governanceDir, 'data-classifier.json');
        const retentionFile = path.join(this.governanceDir, 'retention-manager.json');
        const exists = fs.existsSync(classifierFile) || fs.existsSync(retentionFile);
        return {
            id: 'iso42001-annexa6-data-mgmt',
            title: 'Annex A.6: AI data management',
            status: exists ? 'pass' : 'warning',
            detail: exists
                ? 'Data classifier or retention manager found per Annex A.6'
                : 'No data-classifier.json or retention-manager.json -- Annex A.6 data management gap',
            evidence: exists
                ? [classifierFile, retentionFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkAnnexA8InformationSecurity() {
        const encFile = path.join(this.governanceDir, 'encryption.json');
        const hashFile = path.join(this.governanceDir, 'hash-manifest.json');
        const exists = fs.existsSync(encFile) || fs.existsSync(hashFile);
        return {
            id: 'iso42001-annexa8-infosec',
            title: 'Annex A.8: Information security for AI systems',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Encryption or hash manifest found per Annex A.8.4'
                : 'No encryption.json or hash-manifest.json -- AI system information security not configured',
            evidence: exists
                ? [encFile, hashFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    checkAnnexA9AccessControl() {
        const authFile = path.join(this.governanceDir, 'agent-auth.json');
        const rolesFile = path.join(this.governanceDir, 'roles.json');
        const exists = fs.existsSync(authFile) || fs.existsSync(rolesFile);
        return {
            id: 'iso42001-annexa9-access',
            title: 'Annex A.9: AI system access control',
            status: exists ? 'pass' : 'fail',
            detail: exists
                ? 'Authentication and roles configuration found per Annex A.9'
                : 'No agent-auth.json or roles.json -- AI system access control not configured',
            evidence: exists
                ? [authFile, rolesFile].filter((f) => fs.existsSync(f)).join(', ')
                : undefined,
        };
    }
    // ---------------------------------------------------------------------------
    // Gap analysis
    // ---------------------------------------------------------------------------
    analyzeGaps(result) {
        return result.checks
            .filter((c) => c.status === 'fail' || c.status === 'warning')
            .map((c) => ({
            clause: c.id,
            title: c.title,
            detail: c.detail,
        }));
    }
    // ---------------------------------------------------------------------------
    // AIMS documentation generator
    // ---------------------------------------------------------------------------
    generateAIMSDocumentation(result) {
        const gaps = this.analyzeGaps(result);
        return {
            document: 'AIMS Documentation Package',
            standard: 'ISO/IEC 42001:2023',
            generatedAt: new Date().toISOString(),
            overallScore: result.score,
            totalControls: result.checks.length,
            implemented: result.passed,
            partiallyImplemented: result.warnings,
            notImplemented: result.failed,
            openGaps: gaps.length,
            certificationReadiness: result.score >= 80 ? 'High' : result.score >= 60 ? 'Medium' : 'Low',
            narrative: this.narrativeWriter.write('AIMS', `Score ${result.score}/100. ${result.passed}/${result.checks.length} controls implemented. ${gaps.length} gaps.`),
        };
    }
    // ---------------------------------------------------------------------------
    // Report generation
    // ---------------------------------------------------------------------------
    generateReport(result, outputDir) {
        if (!fs.existsSync(outputDir))
            fs.mkdirSync(outputDir, { recursive: true });
        const aimsDocs = this.generateAIMSDocumentation(result);
        const narrative = this.narrativeWriter.write('ISO-42001-2023', `Score: ${result.score}/100. ${result.passed} controls passed, ${result.failed} failed.`);
        const report = {
            framework: 'ISO/IEC 42001:2023 (AIMS)',
            generatedAt: new Date().toISOString(),
            auditId: result.auditId,
            score: result.score,
            passed: result.passed,
            failed: result.failed,
            warnings: result.warnings,
            narrative,
            aimsDocumentation: aimsDocs,
            checks: result.checks,
        };
        const filename = `iso42001-report-${Date.now()}.json`;
        const filePath = path.join(outputDir, filename);
        fs.writeFileSync(filePath, JSON.stringify(report, null, 2));
        return filePath;
    }
}
//# sourceMappingURL=iso42001.js.map