"use strict";
/**
 * MiFID II Compliance Pack
 *
 * Markets in Financial Instruments Directive II (Directive 2014/65/EU)
 * and its implementing regulation MiFIR (Regulation 600/2014/EU).
 * Current consolidated state: as amended by the MiFID II Quick Fix
 * (Directive 2021/338/EU) and the Investment Firms Regulation (IFR/IFD,
 * effective June 2021). ESMA Guidelines on AI/ML in investment advice
 * and suitability assessments are in force from 2023.
 *
 * Key obligations for AI systems:
 *   - Best-execution policy (Art. 27): AI routing/trading must document
 *     and achieve best execution on a consistent basis.
 *   - Product governance / target market (Arts. 16(3), 24): AI must not
 *     distribute products outside the manufacturer's identified target
 *     market.
 *   - Suitability / appropriateness (Arts. 25, 54-56 MiFID II Delegated
 *     Reg 2017/565): AI investment advice requires suitability check
 *     per client; aggregated AI recommendations are non-compliant without
 *     per-client assessment.
 *   - Algo trading / HFT (Art. 17): Algorithmic trading systems require
 *     kill-switch, annual self-assessment, and regulator notification.
 *   - Record keeping (Art. 16(6), Art. 25(5)): minimum 5 years; ESMA
 *     may extend to 7 years. All AI interactions on a client matter
 *     constitute "records of communications".
 *   - Transparency / reporting: pre- and post-trade transparency
 *     obligations where AI is involved in price formation.
 *
 * Sovereignty: EU (EEA adoption). Equivalent third-country regimes apply
 * to UK (UK MiFID), Switzerland (FinSA), and others by reference.
 *
 * // TODO verify citation with Vera: specific ESMA Guidelines on algo
 * // trading self-assessment frequency (currently understood as annual).
 *
 * @connexum/ai-governance
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.MIFID2_PACK = exports.MIFID2_CATEGORY_CLASSIFIERS = void 0;
/**
 * MiFID II (EU 2014/65) category classifiers.
 * Markets in Financial Instruments Directive -- covers client financial data,
 * suitability profiles, order data, and personal data of EU investors.
 * Note: BEST_EXECUTION_FAILURE is a process-flow category not detectable
 * via pattern; it is detected at the business-logic layer.
 */
exports.MIFID2_CATEGORY_CLASSIFIERS = {
    CLIENT_FINANCIAL_DATA: {
        references: ['MiFID II Art. 25 -- suitability and appropriateness; client financial information'],
        classifier: (input) => {
            if (/\bclient\s+financial\b/i.test(input))
                return true;
            if (/\b(?:portfolio\s+(?:value|data)|investment\s+(?:profile|objective|horizon)|risk\s+tolerance|AUM|assets\s+under\s+management)\b/i.test(input))
                return true;
            if (/\b(?:client\s+(?:account|financial|investment)\s+(?:data|record|information))\b/i.test(input))
                return true;
            return false;
        },
    },
    SUITABILITY_PROFILE: {
        references: ['MiFID II Art. 25(2) -- suitability assessment requirements'],
        classifier: (input) => {
            if (/\b(?:suitability\s+(?:assessment|profile|report|test|check)|appropriateness\s+test)\b/i.test(input))
                return true;
            if (/\b(?:investment\s+knowledge|financial\s+experience|risk\s+profile)\b/i.test(input))
                return true;
            return false;
        },
    },
    ORDER_DATA: {
        references: ['MiFID II Art. 26 -- transaction reporting; order record-keeping'],
        classifier: (input) => {
            if (/\b(?:order\s+(?:book|record|execution|ticket|data)|trade\s+(?:ticket|record|execution)|transaction\s+report)\b/i.test(input))
                return true;
            if (/\b(?:buy|sell)\s+(?:order|instruction)\s+(?:at\s+(?:market|limit)|ISIN|CUSIP)\b/i.test(input))
                return true;
            return false;
        },
    },
    PERSONAL_DATA: {
        references: ['MiFID II Art. 16(6) + GDPR -- personal data of clients in investment context'],
        classifier: (input) => {
            if (/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/.test(input))
                return true;
            if (/\b\d{3}-\d{2}-\d{4}\b/.test(input))
                return true;
            if (/\b(?:client\s+(?:name|address|date\s+of\s+birth|ID|LEI))\b/i.test(input))
                return true;
            return false;
        },
    },
    /**
     * F-NEW-VERA-PACK-C2-08 fix (CRITICAL)
     *
     * MiFID II Art. 24(2) + Delegated Directive 2017/593 Arts. 8-10:
     * Manufacturers must define a target market; distributors must only
     * distribute to clients within that target market. AI systems that
     * distribute investment products to clients outside the manufacturer's
     * identified target market are in direct violation.
     *
     * ESMA product-governance vocabulary detected:
     *   - "out of target market" / "outside target market" / "out-of-target-market"
     *   - "negative target market" / "incompatible target market"
     *   - "target market mismatch"
     *   - "client outside target market"
     *   - "distributing to clients outside the manufacturer's target market"
     *   - References to ESMA Q&As 32/33 on product governance
     *   - Manufacturer target market + distributor + mismatch signal
     *
     * Action (via moduleConfig outOfTargetMarketAction): BLOCK
     */
    PRODUCT_GOVERNANCE_TARGET_MARKET: {
        references: [
            'MiFID II Art. 24(2) -- product governance; target-market identification',
            'Delegated Directive 2017/593 Arts. 8-10 -- manufacturer and distributor obligations',
            'ESMA Q&A on MiFID II investor protection (Q32, Q33) -- product governance',
        ],
        classifier: (input) => {
            // "out of target market" / "outside target market" / "out-of-target-market"
            if (/\bout[\s-]of[\s-]target[\s-]market\b/i.test(input))
                return true;
            if (/\boutside\s+(?:the\s+)?(?:manufacturer['']?s?\s+)?target\s+market\b/i.test(input))
                return true;
            // "negative target market"
            if (/\bnegative\s+target\s+market\b/i.test(input))
                return true;
            // "incompatible target market"
            if (/\bincompatible\s+target\s+market\b/i.test(input))
                return true;
            // "target market mismatch"
            if (/\btarget\s+market\s+mismatch\b/i.test(input))
                return true;
            // "client outside target market"
            if (/\bclient\s+outside\s+(?:the\s+)?(?:manufacturer['']?s?\s+)?target\s+market\b/i.test(input))
                return true;
            // ESMA Q&A 32 / 33 on product governance
            if (/\bESMA\s+Q&?A\s*(?:32|33)\b/i.test(input))
                return true;
            if (/\bproduct\s+governance\s+Q&?A\s*(?:32|33)\b/i.test(input))
                return true;
            // manufacturer target market + distributor + mismatch signal
            if (/\bmanufacturer['']?s?\s+target\s+market\b/i.test(input) &&
                /\bdistribut(?:or|ing|ion|ed)\b/i.test(input) &&
                /\b(?:mismatch|incompatible|outside|negative|breach|violat|wrong|non[-\s]compliant)\b/i.test(input))
                return true;
            return false;
        },
    },
};
exports.MIFID2_PACK = {
    categoryClassifiers: exports.MIFID2_CATEGORY_CLASSIFIERS,
    id: 'mifid2',
    name: 'MiFID II / MiFIR',
    version: '1.0.0',
    description: 'Markets in Financial Instruments Directive II (2014/65/EU) + MiFIR (600/2014/EU) compliance for AI systems in investment services. Covers best-execution, suitability/appropriateness, product governance, algorithmic trading controls, record-keeping, and investor-protection obligations under ESMA guidelines.',
    authority: 'European Securities and Markets Authority (ESMA) + national competent authorities (NCAs)',
    industries: ['fintech', 'investment-management', 'wealth-management', 'trading', 'banking', 'insurance', 'financial-services'],
    requiredModules: [
        {
            name: 'governance-runtime',
            required: true,
            reason: 'Best-execution policy enforcement; kill-switch for algo trading; target-market distribution controls',
            reference: 'Art. 27 MiFID II (best execution); Art. 17 (algo trading); Art. 24(2) (product governance)',
        },
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Tamper-evident records of all AI-driven client interactions and order routing decisions (5-7 year retention)',
            reference: 'Art. 16(6) MiFID II; Art. 25(5) MiFID II; Arts. 72-76 Delegated Reg 2017/565',
        },
        {
            name: 'data-classifier',
            required: true,
            reason: 'Classify client financial data, suitability profiles, and order data; detect out-of-target-market distribution',
            reference: 'Art. 25(2) MiFID II (suitability); Art. 16(3) (product governance)',
        },
        {
            name: 'session-persistence',
            required: true,
            reason: 'Per-client suitability/appropriateness state; informed consent for AI-driven advice; conflict-of-interest tracking',
            reference: 'Arts. 25, 54-56 Delegated Reg 2017/565; Art. 23 MiFID II (conflicts)',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'Human review gate for suitability decisions outside normal parameters; pre-trade transparency checks; algo trading approval',
            reference: 'Art. 17(1) MiFID II (annual self-assessment); Art. 54(5) Delegated Reg 2017/565',
        },
        {
            name: 'agent-auth',
            required: true,
            reason: 'Unique identification of AI agent as acting on behalf of investment firm; access control for client data',
            reference: 'Art. 16(2) MiFID II (internal controls); ESMA AI Guidelines',
        },
        {
            name: 'transparency-injector',
            required: true,
            reason: 'Mandatory disclosure to clients when advice is AI-generated; best-execution policy communication',
            reference: 'Art. 24(3) MiFID II (disclosures); Art. 27(5) (best-execution policy publication)',
        },
        {
            name: 'event-bus',
            required: true,
            reason: 'Real-time monitoring of algo trading activity; transaction reporting streams; incident detection',
            reference: 'Art. 26 MiFIR (transaction reporting); Art. 17(2) MiFID II (real-time monitoring)',
        },
        {
            name: 'circuit-breaker',
            required: true,
            reason: 'Kill-switch for algo trading systems to prevent runaway orders; market disruption prevention',
            reference: 'Art. 17(1) MiFID II (ability to cancel or limit orders; kill-switch)',
        },
        {
            name: 'bias-monitor',
            required: true,
            reason: 'Detect systematic bias in suitability assessments and product recommendations; ESMA AI fairness guidelines',
            reference: 'Art. 25(2) MiFID II; ESMA Guidelines on AI in investment advice (2023)',
        },
        {
            name: 'attestation-manager',
            required: true,
            reason: 'Annual algo-trading self-assessment; product governance target-market sign-off; suitability assessment documentation; 5-year record retention for compliance attestations',
            reference: 'Art. 17(1) MiFID II (annual self-assessment); Art. 16(3) product governance; Arts. 72-76 Delegated Reg 2017/565 record retention',
        },
    ],
    moduleConfig: {
        'data-classifier': {
            enabledCategories: [
                'CLIENT_FINANCIAL_DATA',
                'SUITABILITY_PROFILE',
                'ORDER_DATA',
                'PRODUCT_GOVERNANCE_TARGET_MARKET',
            ],
            outOfTargetMarketAction: 'BLOCK',
            sensitiveFinancialAction: 'WARN',
        },
        'session-persistence': {
            perClientSuitabilityRequired: true,
            conflictOfInterestTrackingRequired: true,
            informedConsentForAiAdviceRequired: true,
        },
        'approval-queue': {
            suitabilityOutOfBoundsReviewRequired: true,
            algoTradingAnnualSelfAssessmentRequired: true,
            preTradeTransparencyCheckRequired: true,
        },
        'governance-runtime': {
            bestExecutionPolicyEnforced: true,
            algoTradingKillSwitchRequired: true,
            targetMarketDistributionControlRequired: true,
        },
        'transparency-injector': {
            aiAdviceDisclosureRequired: true,
            bestExecutionPolicyPublicationRequired: true,
        },
        'event-bus': {
            transactionReportingStreamRequired: true,
            algoTradingRealTimeMonitoringRequired: true,
        },
        'circuit-breaker': {
            killSwitchRequired: true,
            marketDisruptionPreventionRequired: true,
        },
        'bias-monitor': {
            suitabilityAssessmentBiasMonitoringRequired: true,
            productRecommendationFairnessRequired: true,
        },
        'attestation-manager': {
            algoTradingAnnualSelfAssessmentRequired: true,
            bestExecutionAnnualReviewRequired: true,
        },
    },
    providerPolicy: {
        blockedProviders: [],
        requiredCapabilities: ['AUDIT-TRAIL', 'DATA-RESIDENCY-EU'],
        blockReasons: {},
    },
    dataPolicy: {
        scanCategories: [
            'CLIENT_FINANCIAL_DATA',
            'SUITABILITY_PROFILE',
            'ORDER_DATA',
            'PERSONAL_DATA',
            // F-NEW-VERA-PACK-C2-08: product-governance target-market category added
            'PRODUCT_GOVERNANCE_TARGET_MARKET',
        ],
        categoryActions: {
            CLIENT_FINANCIAL_DATA: 'BLOCK',
            SUITABILITY_PROFILE: 'BLOCK',
            ORDER_DATA: 'LOG',
            PERSONAL_DATA: 'WARN',
            // F-NEW-VERA-PACK-C2-08: BLOCK matches moduleConfig outOfTargetMarketAction intent
            // MiFID II Art. 24(2) / Delegated Directive 2017/593 -- out-of-target-market distribution blocked
            PRODUCT_GOVERNANCE_TARGET_MARKET: 'BLOCK',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256',
        minimumClassification: 'CONFIDENTIAL',
    },
    // F-NEW-VERA-PACK-C2-09: subject-keyed categories for GDPR Art. 17 erasure + MiFID II Art. 16(6) NCA audit access
    // CLIENT_FINANCIAL_DATA and SUITABILITY_PROFILE are inherently per-client; data-subject-id attribution required.
    subjectKeyedCategories: ['CLIENT_FINANCIAL_DATA', 'SUITABILITY_PROFILE'],
    retentionPolicy: {
        sovereignty: ['EU'],
        // Art. 16(6) MiFID II: minimum 5 years; ESMA may extend to 7.
        auditLogRetentionDays: 2555,
        sessionRetentionDays: 1825,
        incidentRetentionDays: 2555,
        reference: 'Art. 16(6) MiFID II (5 years; ESMA extension to 7 where applicable); Art. 25(5)',
    },
    incidentPolicy: {
        // NCAs require prompt notification of algo trading incidents; ESMA guidance: within 24h for market-disruption events.
        notificationDeadlineHours: 24,
        reference: 'Art. 17(2) MiFID II (prompt notification of disorderly trading conditions); NCA-specific incident reporting rules',
        requiredRecipients: ['compliance-officer', 'national-competent-authority', 'affected-clients'],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'mifid2-best-execution',
            description: 'Best-execution policy active and enforced for all AI-routed orders',
            reference: 'Art. 27 MiFID II; Delegated Reg 2017/565 Arts. 64-65',
            check: 'mifid2_best_execution_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'mifid2-suitability',
            description: 'Per-client suitability assessment required before AI investment advice',
            reference: 'Art. 25(2) MiFID II; Delegated Reg 2017/565 Arts. 54-56',
            check: 'mifid2_suitability_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'mifid2-product-governance',
            description: 'Target-market distribution controls prevent AI from distributing products outside target market',
            reference: 'Art. 24(2) MiFID II; Delegated Directive 2017/593 Arts. 8-10',
            check: 'mifid2_product_governance_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'mifid2-algo-kill-switch',
            description: 'Kill-switch active for algorithmic trading systems',
            reference: 'Art. 17(1) MiFID II',
            check: 'mifid2_algo_kill_switch_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'mifid2-algo-self-assessment',
            description: 'Annual self-assessment of algorithmic trading system scheduled',
            reference: 'Art. 17(1) MiFID II; ESMA Guidelines on Algo Trading',
            check: 'mifid2_algo_self_assessment_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'mifid2-record-retention',
            description: 'AI interaction records retained for minimum 5 years',
            reference: 'Art. 16(6) MiFID II',
            check: 'mifid2_record_retention_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'mifid2-transaction-reporting',
            description: 'Transaction reporting stream active for AI-involved orders',
            reference: 'Art. 26 MiFIR',
            check: 'mifid2_transaction_reporting_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'mifid2-ai-disclosure',
            description: 'Client disclosure active when advice is AI-generated',
            reference: 'Art. 24(3) MiFID II; ESMA AI in Investment Advice Guidelines (2023)',
            check: 'mifid2_ai_disclosure_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'mifid2-suitability-bias',
            description: 'Bias monitoring active for suitability assessment and product recommendations',
            reference: 'Art. 25(2) MiFID II; ESMA AI Guidelines',
            check: 'mifid2_suitability_bias_active',
            failSeverity: 'MEDIUM',
        },
    ],
};
//# sourceMappingURL=mifid2.js.map