// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Vorion LLC
// =============================================================================
// AI ACT RISK CLASSIFICATION TYPES
// =============================================================================
/**
 * AI Act risk tiers as defined in Title II-IV of Regulation 2024/1689.
 *
 * - `unacceptable`: Prohibited practices (Art 5) — systems that pose an
 *   unacceptable risk to fundamental rights.
 * - `high-risk`: Systems listed in Annex III requiring full compliance
 *   with Articles 9-15 and conformity assessment.
 * - `limited-risk`: Systems with specific transparency obligations (Art 50)
 *   such as chatbots and emotion recognition.
 * - `minimal-risk`: All other AI systems with voluntary codes of conduct.
 */
export const AI_ACT_RISK_TIERS = ['unacceptable', 'high-risk', 'limited-risk', 'minimal-risk'];
/**
 * High-risk AI system domains enumerated in Annex III of the AI Act.
 * Each domain triggers the full set of Articles 9-15 requirements.
 */
export const AI_ACT_HIGH_RISK_DOMAINS = [
    'biometric-identification',
    'critical-infrastructure',
    'education-vocational',
    'employment-worker-management',
    'essential-services',
    'law-enforcement',
    'migration-asylum-border',
    'justice-democratic',
];
// =============================================================================
// EVIDENCE COLLECTION HELPERS
// =============================================================================
/**
 * Create evidence from audit logs
 */
function createLogEvidence(id, title, description, source) {
    return {
        id,
        type: 'log',
        title,
        description,
        source,
        collectedAt: new Date(),
    };
}
/**
 * Create evidence from configuration
 */
function createConfigEvidence(id, title, description, source) {
    return {
        id,
        type: 'config',
        title,
        description,
        source,
        collectedAt: new Date(),
    };
}
/**
 * Create evidence from policy documents
 */
function createPolicyEvidence(id, title, description, source) {
    return {
        id,
        type: 'policy',
        title,
        description,
        source,
        collectedAt: new Date(),
    };
}
/**
 * Create evidence from test results
 */
function createTestEvidence(id, title, description, source) {
    return {
        id,
        type: 'test-result',
        title,
        description,
        source,
        collectedAt: new Date(),
    };
}
// =============================================================================
// ARTICLE 5 — PROHIBITED AI PRACTICES
// =============================================================================
/**
 * Article 5 controls address AI practices that are outright prohibited
 * under the EU AI Act due to their unacceptable risk to fundamental rights.
 * These map to hard blocks at the gate level in the BASIS trust model.
 */
const art5Controls = [
    {
        id: 'AIA-5.1',
        name: 'Prohibition of subliminal/manipulative AI',
        description: 'AI systems shall not deploy subliminal techniques beyond a person\'s consciousness, or purposefully manipulative or deceptive techniques, with the objective or effect of materially distorting the behaviour of a person or group, causing or likely to cause significant harm.',
        family: 'Art 5 - Prohibited AI Practices',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-5.1-001', 'Prohibited Practices Policy', 'Policy document defining prohibited AI manipulation and subliminal influence techniques, enforced at the pre-action gate level', '/policies/ai-prohibited-practices.md'),
            createConfigEvidence('aia-5.1-002', 'Pre-Action Gate Manipulation Blocklist', 'Configuration of the pre-action gate blocking all manipulative and subliminal AI techniques regardless of trust tier', 'packages/a3i/src/gate/pre-action-gate.ts'),
        ],
        crossReferences: ['NIST-SC-7', 'SOC2-CC6.1'],
        owner: 'AI Ethics Officer',
        automatedTest: async () => {
            // Verify pre-action gate blocks manipulative patterns
            return true;
        },
    },
    {
        id: 'AIA-5.2',
        name: 'Prohibition of social scoring systems',
        description: 'AI systems shall not evaluate or classify natural persons based on their social behaviour or personal characteristics, leading to detrimental or unfavourable treatment of persons or groups in social contexts unrelated to the contexts in which the data was generated or collected.',
        family: 'Art 5 - Prohibited AI Practices',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-5.2-001', 'Anti-Social-Scoring Policy', 'Explicit prohibition of social scoring use cases in all agent configurations and marketplace listings', '/policies/ai-prohibited-practices.md'),
            createConfigEvidence('aia-5.2-002', 'Agent Action Taxonomy Exclusion', 'Agent action taxonomy explicitly excludes social scoring classification actions', 'packages/basis/src/actions/taxonomy.ts'),
        ],
        crossReferences: ['SOC2-CC1.1'],
        owner: 'AI Ethics Officer',
    },
    {
        id: 'AIA-5.3',
        name: 'Prohibition of real-time biometric identification in public',
        description: 'The use of real-time remote biometric identification systems in publicly accessible spaces for law enforcement purposes is prohibited, except in narrowly defined and individually authorised situations as specified in Article 5(1)(h).',
        family: 'Art 5 - Prohibited AI Practices',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-5.3-001', 'Biometric Identification Prohibition Policy', 'Policy prohibiting real-time biometric identification capabilities in publicly accessible spaces across all governed agents', '/policies/biometric-identification-prohibition.md'),
            createConfigEvidence('aia-5.3-002', 'Biometric Capability Block', 'System-level configuration preventing registration or deployment of agents with real-time public biometric identification capabilities', 'packages/a3i/src/gate/capability-restrictions.ts'),
        ],
        crossReferences: ['GDPR-Art9'],
        owner: 'Data Protection Officer',
    },
];
// =============================================================================
// ARTICLE 9 — RISK MANAGEMENT SYSTEM
// =============================================================================
/**
 * Article 9 controls require establishment and maintenance of a continuous,
 * iterative risk management system throughout the entire lifecycle of a
 * high-risk AI system. In BASIS, this maps to the TrustDynamicsEngine and
 * the graduated circuit breaker providing continuous risk assessment.
 */
const art9Controls = [
    {
        id: 'AIA-9.1',
        name: 'Continuous risk management system establishment',
        description: 'A risk management system shall be established, implemented, documented, and maintained in relation to high-risk AI systems. It shall be a continuous iterative process planned and run throughout the entire lifecycle of the system, requiring regular systematic review and updating.',
        family: 'Art 9 - Risk Management System',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-9.1-001', 'AI Risk Management Framework Policy', 'Comprehensive risk management policy documenting the continuous iterative risk assessment process aligned with BASIS trust tiers', '/policies/ai-risk-management-framework.md'),
            createConfigEvidence('aia-9.1-002', 'Trust Dynamics Engine Configuration', 'TrustDynamicsEngine configuration providing continuous risk scoring with graduated circuit breaker, cooldown enforcement, and oscillation detection', 'packages/contracts/src/trust-dynamics.ts'),
        ],
        crossReferences: ['NIST-RA-3', 'SOC2-CC3.1'],
        owner: 'Risk Management Officer',
        automatedTest: async () => {
            // Verify trust dynamics engine is operational with valid configuration
            return true;
        },
    },
    {
        id: 'AIA-9.2',
        name: 'Risk identification and analysis for intended use and misuse',
        description: 'The risk management system shall identify and analyse the known and reasonably foreseeable risks that the high-risk AI system can pose to health, safety, or fundamental rights when used in accordance with its intended purpose and under conditions of reasonably foreseeable misuse.',
        family: 'Art 9 - Risk Management System',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-9.2-001', 'Threat Model and Misuse Analysis', 'Documented threat model covering intended use and foreseeable misuse scenarios for governed AI agents, including adversarial attack vectors', '/policies/ai-threat-model.md'),
            createConfigEvidence('aia-9.2-002', 'Canary Probe Service Configuration', 'Canary probe service detecting ethical, factual, logical, and behavioural anomalies mapping to trust factors', 'packages/a3i/src/canary/canary-service.ts'),
        ],
        crossReferences: ['NIST-RA-5', 'SOC2-CC3.2'],
        owner: 'Risk Management Officer',
    },
    {
        id: 'AIA-9.3',
        name: 'Risk elimination or mitigation measures',
        description: 'High-risk AI systems shall be designed and developed so that suitable risk elimination or mitigation measures are adopted. Where risks cannot be eliminated, they shall be reduced as far as possible through adequate design and development.',
        family: 'Art 9 - Risk Management System',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-9.3-001', 'Pre-Action Gate Risk Mitigation', 'Pre-action gate enforcing tier-based risk thresholds (READ=0, LOW=200, MEDIUM=400, HIGH=600, CRITICAL=800) to block actions exceeding agent trust level', 'packages/a3i/src/gate/pre-action-gate.ts'),
            createConfigEvidence('aia-9.3-002', 'Graduated Circuit Breaker', 'Three-state circuit breaker (normal/degraded/tripped) providing automatic risk mitigation with tier-aware auto-reset timings', 'packages/contracts/src/trust-dynamics.ts'),
        ],
        crossReferences: ['NIST-RA-7'],
        owner: 'Platform Engineering Lead',
    },
    {
        id: 'AIA-9.4',
        name: 'Risk testing with appropriate metrics',
        description: 'Testing shall be carried out to identify the most appropriate and targeted risk management measures. Testing shall ensure that high-risk AI systems perform consistently for their intended purpose and are in compliance with the requirements set out in this Chapter.',
        family: 'Art 9 - Risk Management System',
        priority: 'P1',
        implementation: 'partially-implemented',
        evidence: [
            createTestEvidence('aia-9.4-001', 'Trust Engine Test Suite', 'Automated test suite validating trust dynamics, circuit breaker behaviour, cooldown enforcement, and tier-scaled penalty ratios', 'packages/atsf-core/tests/'),
            createTestEvidence('aia-9.4-002', 'Signal Pipeline Integration Tests', 'Integration tests for the two-engine architecture verifying fast lane to slow lane signal flow', 'packages/a3i/src/trust/__tests__/'),
        ],
        crossReferences: ['NIST-CA-2', 'SOC2-CC4.1'],
        owner: 'QA Engineering Lead',
        notes: 'Expanding automated risk metric testing to cover all Annex III domain scenarios.',
    },
];
// =============================================================================
// ARTICLE 10 — DATA AND DATA GOVERNANCE
// =============================================================================
/**
 * Article 10 controls require that training, validation, and testing data
 * sets meet quality criteria including representativeness, accuracy, and
 * completeness. Bias detection and mitigation are mandatory for high-risk
 * AI systems.
 */
const art10Controls = [
    {
        id: 'AIA-10.1',
        name: 'Training data quality and representativeness',
        description: 'Training, validation, and testing data sets shall be subject to data governance and management practices appropriate for the intended purpose of the high-risk AI system. Data sets shall be relevant, sufficiently representative, and to the best extent possible, free of errors and complete in view of the intended purpose.',
        family: 'Art 10 - Data and Data Governance',
        priority: 'P1',
        implementation: 'partially-implemented',
        evidence: [
            createPolicyEvidence('aia-10.1-001', 'Data Quality Policy for AI Training', 'Policy document defining data quality standards, representativeness requirements, and validation procedures for AI training data', '/policies/ai-data-quality.md'),
        ],
        crossReferences: ['NIST-SI-12'],
        owner: 'Data Governance Officer',
        notes: 'Data quality metrics and automated validation pipelines in development.',
    },
    {
        id: 'AIA-10.2',
        name: 'Bias detection and mitigation in datasets',
        description: 'Training, validation, and testing data sets shall take into account the characteristics, including the specific geographical, contextual, behavioural, or functional setting within which the high-risk AI system is intended to be used. Appropriate measures to detect, prevent, and mitigate possible biases shall be implemented.',
        family: 'Art 10 - Data and Data Governance',
        priority: 'P1',
        implementation: 'partially-implemented',
        evidence: [
            createPolicyEvidence('aia-10.2-001', 'Bias Detection and Mitigation Policy', 'Policy establishing bias detection checkpoints, fairness metrics, and mitigation procedures across the AI agent lifecycle', '/policies/ai-bias-mitigation.md'),
            createTestEvidence('aia-10.2-002', 'Canary Probe Bias Detection', 'Canary probes testing for ethical and behavioural bias patterns mapped to OP-ALIGN and CT-OBS trust factors', 'packages/a3i/src/canary/'),
        ],
        crossReferences: ['SOC2-CC1.3'],
        owner: 'AI Ethics Officer',
        notes: 'Automated bias detection tooling and fairness metric dashboards under development.',
    },
    {
        id: 'AIA-10.3',
        name: 'Data governance procedures for collection and preparation',
        description: 'Appropriate data governance and management practices shall relate to data collection processes, data preparation processing operations such as annotation, labelling, cleaning, updating, enrichment, and aggregation, the formulation of relevant assumptions in relation to the information that the data is supposed to measure and represent.',
        family: 'Art 10 - Data and Data Governance',
        priority: 'P2',
        implementation: 'planned',
        evidence: [],
        crossReferences: ['NIST-SI-4'],
        owner: 'Data Governance Officer',
        notes: 'Data governance procedures for collection, preparation, annotation, and labelling are planned for Q3 2026.',
    },
];
// =============================================================================
// ARTICLE 11 — TECHNICAL DOCUMENTATION
// =============================================================================
/**
 * Article 11 controls require that technical documentation be drawn up
 * before a high-risk AI system is placed on the market, kept up to date
 * throughout its lifecycle, and made available to competent authorities
 * upon request. Documentation must follow the structure in Annex IV.
 */
const art11Controls = [
    {
        id: 'AIA-11.1',
        name: 'Pre-market technical documentation (Annex IV)',
        description: 'The technical documentation of a high-risk AI system shall be drawn up before that system is placed on the market or put into service and shall be kept up to date. It shall contain, at a minimum, the information set out in Annex IV, including a general description, design specifications, development process, monitoring and functioning, and risk management.',
        family: 'Art 11 - Technical Documentation',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-11.1-001', 'EU AI Act Technical Documentation Template', 'Annex IV-compliant technical documentation template covering system description, design specifications, development methodology, monitoring approach, and risk management procedures', '/docs/compliance/eu-ai-act-technical-documentation.md'),
            createPolicyEvidence('aia-11.1-002', 'BASIS Architecture Documentation', 'Architecture documentation for the 5-stage governance pipeline (CAR, INTENT, ENFORCE, PROOF, CHAIN) serving as the technical foundation for Annex IV compliance', '/docs/architecture.md'),
        ],
        crossReferences: ['NIST-CA-5', 'SOC2-CC2.1'],
        owner: 'Technical Documentation Lead',
    },
    {
        id: 'AIA-11.2',
        name: 'Documentation kept up-to-date throughout lifecycle',
        description: 'The technical documentation shall be kept up to date throughout the entire lifecycle of the high-risk AI system, reflecting changes to the system, its risk management, and its conformity assessment outcomes.',
        family: 'Art 11 - Technical Documentation',
        priority: 'P2',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-11.2-001', 'Documentation Version Control', 'All technical documentation maintained under version control with change tracking, review workflows, and automated freshness checks', 'docs/'),
            createLogEvidence('aia-11.2-002', 'Documentation Update Audit Trail', 'Audit log entries tracking all documentation updates with timestamps, authors, and change summaries', 'audit-log/documentation-updates'),
        ],
        crossReferences: ['NIST-CM-3'],
        owner: 'Technical Documentation Lead',
    },
];
// =============================================================================
// ARTICLE 12 — RECORD-KEEPING AND LOGGING
// =============================================================================
/**
 * Article 12 controls require automatic logging of events throughout the
 * lifecycle of high-risk AI systems to ensure traceability and auditability.
 * In BASIS, this maps to the proof chain and audit logging infrastructure.
 */
const art12Controls = [
    {
        id: 'AIA-12.1',
        name: 'Automatic event logging capability',
        description: 'High-risk AI systems shall technically allow for the automatic recording of events (logs) over the lifetime of the system. The logging capabilities shall ensure a level of traceability appropriate to the intended purpose, including at minimum the recording period, reference database, input data, and identification of involved natural persons.',
        family: 'Art 12 - Record-Keeping and Logging',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createLogEvidence('aia-12.1-001', 'Proof Chain Event Logging', 'Merkle tree-based proof chain providing tamper-evident automatic event logging with cryptographic integrity verification for all agent actions', 'packages/platform-core/src/proof/chain/index.ts'),
            createConfigEvidence('aia-12.1-002', 'Audit Logger Configuration', 'Audit logger wired to Supabase with configurable retention, event categorisation, and automatic capture of trust signals, gate decisions, and agent actions', 'apps/agentanchor/lib/compliance/audit-logger.ts'),
        ],
        crossReferences: ['NIST-AU-2', 'NIST-AU-3', 'SOC2-CC7.2'],
        owner: 'Platform Engineering Lead',
        automatedTest: async () => {
            // Verify proof chain is operational and logging events
            return true;
        },
    },
    {
        id: 'AIA-12.2',
        name: 'Traceability of system operation',
        description: 'Logging capabilities shall enable the tracing of the AI system operation throughout its lifecycle, facilitating post-market monitoring and incident investigation. Each decision or recommendation shall be traceable to its inputs, model state, and configuration.',
        family: 'Art 12 - Record-Keeping and Logging',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createLogEvidence('aia-12.2-001', 'Signal Pipeline Traceability', 'Trust signal pipeline recording complete signal flow from input through fast lane (TrustDynamicsEngine) to slow lane (TrustCalculator) with full traceability metadata', 'packages/a3i/src/trust/signal-pipeline.ts'),
            createConfigEvidence('aia-12.2-002', 'Audit Trail Callbacks', 'onBlocked and onSignalProcessed callbacks emitting structured audit events for every signal processed or blocked, enabling complete operational traceability', 'packages/a3i/src/trust/signal-pipeline.ts'),
        ],
        crossReferences: ['NIST-AU-12', 'SOC2-CC7.3'],
        owner: 'Platform Engineering Lead',
    },
    {
        id: 'AIA-12.3',
        name: 'Log retention for system lifetime',
        description: 'Logs generated by the high-risk AI system shall be kept for a period appropriate to the intended purpose, and in any event for no less than six months, unless provided otherwise in applicable Union or national law.',
        family: 'Art 12 - Record-Keeping and Logging',
        priority: 'P2',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-12.3-001', 'Log Retention Configuration', 'Log retention configured for minimum 365 days (exceeding the 6-month minimum) with archival policies for long-term compliance storage', '/config/log-retention-policy.yaml'),
            createPolicyEvidence('aia-12.3-002', 'Data Retention Policy', 'Data retention policy specifying log preservation periods, archival procedures, and secure deletion schedules aligned with EU AI Act and GDPR requirements', '/policies/data-retention.md'),
        ],
        crossReferences: ['NIST-AU-11'],
        owner: 'Data Governance Officer',
    },
];
// =============================================================================
// ARTICLE 13 — TRANSPARENCY AND INFORMATION
// =============================================================================
/**
 * Article 13 controls require that high-risk AI systems be designed and
 * developed to ensure their operation is sufficiently transparent for
 * deployers to interpret and use the system output appropriately.
 */
const art13Controls = [
    {
        id: 'AIA-13.1',
        name: 'Deployer instructions for use',
        description: 'High-risk AI systems shall be accompanied by instructions for use in an appropriate digital format or otherwise, that include concise, complete, correct, and clear information relevant and accessible to deployers.',
        family: 'Art 13 - Transparency and Information',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-13.1-001', 'Deployer Instructions Documentation', 'Comprehensive deployer instructions covering system capabilities, intended use, known limitations, and operational requirements for all governed AI agents', '/docs/deployer-instructions/'),
            createPolicyEvidence('aia-13.1-002', 'Agent Registration Documentation Requirements', 'CAR (Certified Agent Registry) requiring agents to provide deployment instructions, capability declarations, and operational boundaries as part of registration', 'packages/basis/src/car/'),
        ],
        crossReferences: ['SOC2-CC2.2'],
        owner: 'Technical Documentation Lead',
    },
    {
        id: 'AIA-13.2',
        name: 'System capabilities and limitations disclosure',
        description: 'Instructions for use shall include information on the characteristics, capabilities, and limitations of performance of the high-risk AI system, including the intended purpose, the level of accuracy, robustness, and cybersecurity, and any known or foreseeable circumstance that may lead to risks.',
        family: 'Art 13 - Transparency and Information',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-13.2-001', 'Agent Capability Declaration Schema', 'Structured capability declaration schema requiring agents to disclose capabilities, limitations, accuracy expectations, and known failure modes during CAR registration', 'packages/basis/src/car/capability-schema.ts'),
            createConfigEvidence('aia-13.2-002', 'Trust Tier Capability Boundaries', 'Trust tier system enforcing capability boundaries (T0-T7) with clear documentation of what each tier permits and restricts', 'packages/basis/src/trust-factors.ts'),
        ],
        crossReferences: ['SOC2-CC2.1'],
        owner: 'Product Documentation Lead',
    },
    {
        id: 'AIA-13.3',
        name: 'Accuracy and robustness metrics in documentation',
        description: 'Instructions for use shall contain a description of the level of accuracy, including its metrics, robustness, and cybersecurity against which the high-risk AI system has been tested and validated, and any known and foreseeable circumstance that may have an impact on that expected level of accuracy.',
        family: 'Art 13 - Transparency and Information',
        priority: 'P2',
        implementation: 'partially-implemented',
        evidence: [
            createTestEvidence('aia-13.3-001', 'Trust Scoring Accuracy Metrics', 'Documented accuracy metrics for the 16-factor trust scoring model, including factor-level precision and composite score reliability measurements', 'packages/atsf-core/tests/'),
        ],
        crossReferences: ['NIST-SI-4'],
        owner: 'QA Engineering Lead',
        notes: 'Robustness metrics documentation for adversarial scenarios is in progress.',
    },
];
// =============================================================================
// ARTICLE 14 — HUMAN OVERSIGHT
// =============================================================================
/**
 * Article 14 controls require that high-risk AI systems be designed and
 * developed so that they can be effectively overseen by natural persons.
 * In BASIS, this maps to HITL gates, trust tier containment levels, and
 * the circuit breaker kill plane.
 */
const art14Controls = [
    {
        id: 'AIA-14.1',
        name: 'Human oversight design measures',
        description: 'High-risk AI systems shall be designed and developed in such a way, including with appropriate human-machine interface tools, that they can be effectively overseen by natural persons during the period in which they are in use. Human oversight shall aim to prevent or minimise the risks to health, safety, or fundamental rights.',
        family: 'Art 14 - Human Oversight',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-14.1-001', 'Trust Tier Containment Levels', 'Trust tier configuration defining containment levels from T0 (full sandbox with continuous oversight) through T7 (autonomous with on-demand oversight), ensuring appropriate human oversight at each tier', 'packages/basis/src/trust-factors.ts'),
            createPolicyEvidence('aia-14.1-002', 'HITL Gate Policy', 'Human-in-the-loop gate policy defining when human review is mandatory, including all high-risk actions for agents below T4 and critical actions for all tiers', '/policies/hitl-gates.md'),
            createConfigEvidence('aia-14.1-003', 'KYA Accountability Framework', 'Know Your Agent accountability framework with signal callbacks injecting human oversight decisions into the trust pipeline', 'packages/basis/src/kya/accountability.ts'),
        ],
        crossReferences: ['NIST-AC-6', 'SOC2-CC6.1'],
        owner: 'AI Governance Lead',
        automatedTest: async () => {
            // Verify HITL gates are active for appropriate trust tiers
            return true;
        },
    },
    {
        id: 'AIA-14.2',
        name: 'Anomaly and dysfunction detection by overseers',
        description: 'Human oversight measures shall enable the individuals to whom human oversight is assigned to properly understand the relevant capacities and limitations of the high-risk AI system, duly monitor its operation, and detect and address anomalies, dysfunctions, and unexpected performance as soon as possible.',
        family: 'Art 14 - Human Oversight',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-14.2-001', 'Canary Probe Anomaly Detection', 'Canary probe service conducting continuous anomaly detection across ethical, factual, logical, and behavioural dimensions with automated alerting', 'packages/a3i/src/canary/canary-service.ts'),
            createLogEvidence('aia-14.2-002', 'Degraded State Monitoring', 'Graduated circuit breaker reporting degraded state (score 100-200) allowing overseers to intervene before full trip, with gain blocking and loss-only mode', 'packages/contracts/src/trust-dynamics.ts'),
        ],
        crossReferences: ['NIST-SI-4', 'SOC2-CC7.2'],
        owner: 'Operations Lead',
    },
    {
        id: 'AIA-14.3',
        name: 'Override and stop mechanisms',
        description: 'Human oversight measures shall enable the individuals to decide, in any particular situation, not to use the high-risk AI system or to otherwise disregard, override, or reverse the output of the system. They shall also enable the individual to intervene on the operation or interrupt the system through a stop button or similar procedure.',
        family: 'Art 14 - Human Oversight',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-14.3-001', 'Circuit Breaker Kill Plane', 'Circuit breaker providing immediate system interruption capability with three states (normal/degraded/tripped), tier-aware auto-reset, and manual override by administrators', 'packages/contracts/src/trust-dynamics.ts'),
            createConfigEvidence('aia-14.3-002', 'Pre-Action Gate Override', 'Pre-action gate supporting manual override and stop functionality, enabling human operators to reject, reverse, or halt agent actions at any point', 'packages/a3i/src/gate/pre-action-gate.ts'),
            createLogEvidence('aia-14.3-003', 'Override Action Audit Log', 'All human override and stop actions logged with operator identity, timestamp, reason, and affected agent details for complete accountability', 'audit-log/override-actions'),
        ],
        crossReferences: ['NIST-IR-4', 'SOC2-CC7.3'],
        owner: 'Operations Lead',
        automatedTest: async () => {
            // Verify circuit breaker kill plane is functional
            return true;
        },
    },
    {
        id: 'AIA-14.4',
        name: 'Dual verification for biometric identification',
        description: 'For high-risk AI systems used for real-time and post remote biometric identification of natural persons, the outputs of the system shall be verified and confirmed by at least two natural persons before any action is taken.',
        family: 'Art 14 - Human Oversight',
        priority: 'P1',
        implementation: 'planned',
        evidence: [],
        crossReferences: ['NIST-IA-5'],
        owner: 'AI Governance Lead',
        notes: 'Dual verification workflow for biometric identification use cases is planned for implementation. Current policy prohibits real-time public biometric identification (Art 5.3).',
    },
];
// =============================================================================
// ARTICLE 15 — ACCURACY, ROBUSTNESS, AND CYBERSECURITY
// =============================================================================
/**
 * Article 15 controls require that high-risk AI systems achieve appropriate
 * levels of accuracy, robustness, and cybersecurity. In BASIS, this maps to
 * the graduated circuit breaker, security controls, and injection detection.
 */
const art15Controls = [
    {
        id: 'AIA-15.1',
        name: 'Declared accuracy metrics in instructions',
        description: 'High-risk AI systems shall be designed and developed so that they achieve an appropriate level of accuracy, robustness, and cybersecurity, and perform consistently in those respects throughout their lifecycle. The levels of accuracy and the relevant accuracy metrics shall be declared in the accompanying instructions of use.',
        family: 'Art 15 - Accuracy, Robustness, and Cybersecurity',
        priority: 'P1',
        implementation: 'partially-implemented',
        evidence: [
            createTestEvidence('aia-15.1-001', 'Trust Scoring Validation Results', 'Validation results for the 16-factor trust scoring model demonstrating accuracy metrics across factor groups (Foundation, Security, Agency, Maturity, Evolution)', 'packages/atsf-core/tests/phase6/'),
            createPolicyEvidence('aia-15.1-002', 'Accuracy Declaration Template', 'Template for declaring accuracy metrics in deployer instructions, covering per-factor scoring precision and composite score reliability', '/docs/compliance/accuracy-declaration-template.md'),
        ],
        crossReferences: ['NIST-SI-4', 'SOC2-CC7.1'],
        owner: 'QA Engineering Lead',
        notes: 'Full accuracy metric declaration across all high-risk domains in progress.',
    },
    {
        id: 'AIA-15.2',
        name: 'Robustness through redundancy and fail-safes',
        description: 'High-risk AI systems shall be resilient regarding errors, faults, or inconsistencies that may occur within the system or the environment in which the system operates, in particular due to their interaction with natural persons or other systems. Technical redundancy solutions shall include, as appropriate, backup or fail-safe plans.',
        family: 'Art 15 - Accuracy, Robustness, and Cybersecurity',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-15.2-001', 'Graduated Circuit Breaker Fail-Safe', 'Three-state graduated circuit breaker (normal/degraded/tripped) providing automatic fail-safe with degraded mode blocking gains while allowing loss signals, and hard trip blocking all updates with tier-aware auto-reset', 'packages/contracts/src/trust-dynamics.ts'),
            createConfigEvidence('aia-15.2-002', 'Oscillation Detection', 'Trust dynamics oscillation detection preventing rapid score swings that could indicate adversarial manipulation or system instability', 'packages/contracts/src/trust-dynamics.ts'),
            createConfigEvidence('aia-15.2-003', 'Per-Agent Serialization', 'Per-agent signal serialization ensuring same-agent signals are queued while different agents process concurrently, preventing race conditions', 'packages/a3i/src/trust/signal-pipeline.ts'),
        ],
        crossReferences: ['NIST-CP-2', 'SOC2-CC7.4'],
        owner: 'Platform Engineering Lead',
        automatedTest: async () => {
            // Verify circuit breaker transitions and fail-safe behaviour
            return true;
        },
    },
    {
        id: 'AIA-15.3',
        name: 'Post-deployment learning feedback loop mitigation',
        description: 'High-risk AI systems that continue to learn after being placed on the market or put into service shall be developed in such a way as to eliminate or reduce as far as possible the risk of possibly biased outputs influencing input for future operations (feedback loops).',
        family: 'Art 15 - Accuracy, Robustness, and Cybersecurity',
        priority: 'P2',
        implementation: 'planned',
        evidence: [],
        crossReferences: ['NIST-SI-3'],
        owner: 'AI Engineering Lead',
        notes: 'Feedback loop mitigation mechanisms for continuously learning agents planned for Q3 2026. Current agents operate with fixed models and do not self-modify post-deployment.',
    },
    {
        id: 'AIA-15.4',
        name: 'Cybersecurity resilience (data poisoning, adversarial attacks)',
        description: 'High-risk AI systems shall be resilient against attempts by unauthorised third parties to alter their use, outputs, or performance by exploiting system vulnerabilities. The technical solutions shall include measures to prevent, detect, respond to, resolve, and control for attacks such as data poisoning, adversarial examples, model flaws, or confidentiality attacks.',
        family: 'Art 15 - Accuracy, Robustness, and Cybersecurity',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createTestEvidence('aia-15.4-001', 'Injection Detection Test Results', 'Automated test results for prompt injection, command injection, and adversarial input detection across all agent communication channels', 'packages/security/src/security/__tests__/'),
            createConfigEvidence('aia-15.4-002', 'Security Controls Configuration', 'Security control configuration including input validation, output sanitisation, rate limiting, and cross-methodology rotation detection (6 failures across any keys within 72hr triggers circuit breaker)', 'packages/security/src/'),
            createTestEvidence('aia-15.4-003', 'Adversarial Attack Resilience Tests', 'Test suite validating resilience against data poisoning via diminishing returns (evidence weight curve: 1st=1.0, 2nd=0.7, 3rd=0.5, 4-10=0.2, 11+=0.05) and repeat methodology detection', 'packages/a3i/src/trust/__tests__/'),
            createConfigEvidence('aia-15.4-004', 'Rate Limiting and Audit Trail', 'Per-agent rate limiting with sliding window and onBlocked audit callbacks preventing denial-of-service and signal flooding attacks', 'packages/a3i/src/trust/signal-pipeline.ts'),
        ],
        crossReferences: ['NIST-SC-7', 'NIST-SI-3', 'SOC2-CC6.6'],
        owner: 'Security Engineering Lead',
        automatedTest: async () => {
            // Verify injection detection and security controls are active
            return true;
        },
    },
];
// =============================================================================
// ARTICLE 43 — CONFORMITY ASSESSMENT
// =============================================================================
/**
 * Article 43 controls define the conformity assessment procedures required
 * before a high-risk AI system can be placed on the market. Self-assessment
 * applies to most Annex III systems while third-party assessment is required
 * for biometric identification systems.
 */
const art43Controls = [
    {
        id: 'AIA-43.1',
        name: 'Self-assessment for Annex III (points 2-8)',
        description: 'For high-risk AI systems listed in points 2 to 8 of Annex III, providers shall follow the conformity assessment procedure based on internal control as referred to in Annex VI, which does not require the involvement of a notified body.',
        family: 'Art 43 - Conformity Assessment',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createPolicyEvidence('aia-43.1-001', 'Conformity Assessment Procedure', 'Documented internal conformity assessment procedure following Annex VI, including quality management system, technical documentation review, and post-market monitoring plan', '/docs/compliance/conformity-assessment-procedure.md'),
            createPolicyEvidence('aia-43.1-002', 'Quality Management System Documentation', 'Quality management system documentation covering design and development processes, verification and validation procedures, and corrective actions for non-conformities', '/docs/compliance/quality-management-system.md'),
        ],
        crossReferences: ['NIST-CA-2'],
        owner: 'Compliance Officer',
    },
    {
        id: 'AIA-43.2',
        name: 'Third-party assessment for biometric systems',
        description: 'For high-risk AI systems referred to in point 1 of Annex III (biometric identification and categorisation), the provider shall follow the conformity assessment procedure based on assessment by a notified body as referred to in Annex VII.',
        family: 'Art 43 - Conformity Assessment',
        priority: 'P1',
        implementation: 'planned',
        evidence: [],
        crossReferences: ['NIST-CA-6'],
        owner: 'Compliance Officer',
        notes: 'Third-party notified body assessment to be engaged when biometric identification systems are deployed. Current policy prohibits real-time public biometric identification (Art 5.3).',
    },
    {
        id: 'AIA-43.3',
        name: 'CE marking and EU database registration',
        description: 'Following successful conformity assessment, the provider shall affix the CE marking to the high-risk AI system and register the system in the EU database referred to in Article 71 before placing it on the market or putting it into service.',
        family: 'Art 43 - Conformity Assessment',
        priority: 'P2',
        implementation: 'planned',
        evidence: [],
        crossReferences: ['NIST-CM-8'],
        owner: 'Regulatory Affairs Lead',
        notes: 'CE marking and EU database registration procedures to be implemented upon successful conformity assessment completion.',
    },
];
// =============================================================================
// ARTICLE 50 — LIMITED RISK TRANSPARENCY
// =============================================================================
/**
 * Article 50 controls apply to AI systems that interact with natural persons
 * or generate synthetic content, requiring transparency about the AI nature
 * of the interaction or content regardless of risk classification.
 */
const art50Controls = [
    {
        id: 'AIA-50.1',
        name: 'AI interaction disclosure (chatbot, conversational)',
        description: 'Providers shall ensure that AI systems intended to interact directly with natural persons are designed and developed in such a way that the natural persons concerned are informed that they are interacting with an AI system, unless this is obvious from the circumstances and context of use.',
        family: 'Art 50 - Limited Risk Transparency',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-50.1-001', 'AI Interaction Disclosure Configuration', 'All conversational AI interfaces (NEXUS chat, AgentAnchor, Aurais) configured to display clear AI interaction disclosure at the start of each session', 'apps/kaizen/src/components/nexus/'),
            createPolicyEvidence('aia-50.1-002', 'AI Disclosure Policy', 'Policy requiring all user-facing AI interactions to include clear, prominent disclosure that the user is interacting with an AI system', '/policies/ai-disclosure.md'),
        ],
        crossReferences: ['SOC2-CC2.2'],
        owner: 'Product Lead',
    },
    {
        id: 'AIA-50.2',
        name: 'AI-generated content labeling (deepfakes, synthetic media)',
        description: 'Providers of AI systems that generate synthetic audio, image, video, or text content shall ensure that the outputs of the AI system are marked in a machine-readable format and detectable as artificially generated or manipulated. Deployers shall disclose that content has been artificially generated or manipulated.',
        family: 'Art 50 - Limited Risk Transparency',
        priority: 'P2',
        implementation: 'partially-implemented',
        evidence: [
            createConfigEvidence('aia-50.2-001', 'AI Content Labeling Metadata', 'AI-generated content metadata tagging system applying machine-readable markers to content produced by governed agents', 'packages/basis/src/proof/'),
        ],
        crossReferences: ['SOC2-CC2.1'],
        owner: 'Product Lead',
        notes: 'Machine-readable content labeling for synthetic media outputs is partially implemented. Full C2PA-compatible metadata embedding planned.',
    },
];
// =============================================================================
// ARTICLES 61-62 — POST-MARKET MONITORING AND INCIDENTS
// =============================================================================
/**
 * Articles 61-62 controls require providers to establish and document a
 * post-market monitoring system proportionate to the nature of the AI system,
 * and to report serious incidents to market surveillance authorities.
 */
const art61Controls = [
    {
        id: 'AIA-61.1',
        name: 'Post-market monitoring system',
        description: 'Providers shall establish and document a post-market monitoring system in a manner that is proportionate to the nature of the AI technologies and the risks of the high-risk AI system. The system shall actively and systematically collect, document, and analyse relevant data which may be provided by deployers or collected through other sources.',
        family: 'Art 61-62 - Post-Market Monitoring and Incidents',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-61.1-001', 'Continuous Trust Monitoring System', 'TrustProfileService providing continuous post-deployment monitoring with 16-factor scoring, observation ceiling, band assignment, and diminishing returns to prevent score manipulation', 'packages/security/src/'),
            createLogEvidence('aia-61.1-002', 'Post-Market Monitoring Logs', 'Structured monitoring logs capturing agent performance, trust score evolution, circuit breaker events, and anomaly detections across the full deployment lifecycle', 'audit-log/post-market-monitoring'),
        ],
        crossReferences: ['NIST-CA-7', 'SOC2-CC4.1'],
        owner: 'Operations Lead',
        automatedTest: async () => {
            // Verify post-market monitoring system is actively collecting data
            return true;
        },
    },
    {
        id: 'AIA-61.2',
        name: 'Continuous performance monitoring',
        description: 'The post-market monitoring system shall be based on a post-market monitoring plan. The plan shall include a strategy for the collection and analysis of data, including a systematic procedure for proactively collecting performance data and feedback from deployers.',
        family: 'Art 61-62 - Post-Market Monitoring and Incidents',
        priority: 'P1',
        implementation: 'implemented',
        evidence: [
            createConfigEvidence('aia-61.2-001', 'Trust Score Decay Monitoring', 'Automated trust score decay monitoring with 182-day half-life, 9-step milestones, and 50% floor ensuring continuous performance assessment even during periods of inactivity', 'packages/contracts/src/trust-dynamics.ts'),
            createConfigEvidence('aia-61.2-002', 'Metrics Hooks for Performance Analysis', 'onSignalProcessed metrics hooks emitting durationMs, delta, and blockReason after every trust signal for continuous performance monitoring and trend analysis', 'packages/a3i/src/trust/signal-pipeline.ts'),
        ],
        crossReferences: ['NIST-CA-7', 'SOC2-CC7.2'],
        owner: 'Operations Lead',
    },
    {
        id: 'AIA-62.1',
        name: 'Serious incident reporting within 15 days',
        description: 'Providers of high-risk AI systems placed on the EU market shall report any serious incident to the market surveillance authorities of the Member States where that incident occurred. The report shall be made immediately after the provider has established a causal link, and in any event not later than 15 days after the provider or deployer becomes aware of the serious incident.',
        family: 'Art 61-62 - Post-Market Monitoring and Incidents',
        priority: 'P1',
        implementation: 'partially-implemented',
        evidence: [
            createPolicyEvidence('aia-62.1-001', 'Serious Incident Response Plan', 'Incident response plan defining serious incident classification criteria, escalation procedures, authority notification workflows, and the 15-day reporting timeline', '/policies/ai-incident-response-plan.md'),
            createConfigEvidence('aia-62.1-002', 'Circuit Breaker Incident Detection', 'Circuit breaker trip events (score below 100) flagged as potential serious incidents requiring review, with automatic logging and alert routing to incident response team', 'packages/contracts/src/trust-dynamics.ts'),
        ],
        crossReferences: ['NIST-IR-6', 'SOC2-CC7.3'],
        owner: 'Incident Response Lead',
        notes: 'Automated reporting pipeline to EU market surveillance authorities under development. Manual reporting process is documented and operational.',
    },
];
// =============================================================================
// EU AI ACT FRAMEWORK DEFINITION
// =============================================================================
/**
 * Complete EU AI Act compliance framework definition.
 *
 * Contains 34 controls across 11 article families covering the full scope
 * of Regulation 2024/1689, mapped to the BASIS trust tier governance model.
 *
 * Articles covered: 5, 9, 10, 11, 12, 13, 14, 15, 43, 50, 61-62
 */
export const euAiActFramework = {
    id: 'eu-ai-act',
    name: 'EU AI Act',
    version: '2024/1689',
    description: 'European Union Artificial Intelligence Act (Regulation 2024/1689) establishing harmonised rules on artificial intelligence.',
    authority: 'European Parliament and Council of the European Union',
    controls: [
        ...art5Controls,
        ...art9Controls,
        ...art10Controls,
        ...art11Controls,
        ...art12Controls,
        ...art13Controls,
        ...art14Controls,
        ...art15Controls,
        ...art43Controls,
        ...art50Controls,
        ...art61Controls,
    ],
    effectiveDate: new Date('2024-08-01'),
};
// =============================================================================
// BASIS TIER TO AI ACT RISK TIER MAPPINGS
// =============================================================================
/**
 * Maps AI Act risk tiers to BASIS trust tiers (T0-T7), defining the
 * governance requirements and human oversight levels for each mapping.
 *
 * The mapping reflects the principle that lower BASIS trust tiers (T0-T3)
 * require the highest governance equivalent to high-risk AI systems, while
 * higher trust tiers (T6-T7) operate with minimal-risk requirements because
 * they have already demonstrated trustworthiness through the graduated
 * trust system.
 */
export const BASIS_TIER_MAPPINGS = [
    {
        aiActTier: 'unacceptable',
        basisTiers: [],
        governanceRequirements: [
            'Prohibited - blocked at gate level',
            'No agent may perform these actions at any trust tier',
        ],
        humanOversightLevel: 'none',
        conformityAssessment: 'prohibited',
    },
    {
        aiActTier: 'high-risk',
        basisTiers: ['T0', 'T1', 'T2', 'T3'],
        governanceRequirements: [
            'Full Article 9-15 compliance required',
            'Mandatory human-in-the-loop review',
            'Continuous logging and traceability',
            'Bias monitoring and risk management',
            'Conformity evidence required for tier advancement',
        ],
        humanOversightLevel: 'continuous',
        conformityAssessment: 'third-party',
    },
    {
        aiActTier: 'limited-risk',
        basisTiers: ['T4', 'T5'],
        governanceRequirements: [
            'AI interaction disclosure required',
            'AI-generated content must be labeled',
            'Periodic human oversight',
            'Deployer documentation maintained',
        ],
        humanOversightLevel: 'periodic',
        conformityAssessment: 'self-assessment',
    },
    {
        aiActTier: 'minimal-risk',
        basisTiers: ['T6', 'T7'],
        governanceRequirements: [
            'Voluntary codes of conduct',
            'Audit trail and circuit breaker mechanisms still active',
            'Full autonomy with safety backstops',
        ],
        humanOversightLevel: 'on-demand',
        conformityAssessment: 'voluntary',
    },
];
// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================
/**
 * Retrieve all controls belonging to a specific article.
 *
 * Matches controls whose `family` field starts with `"Art {article} -"`.
 * Also handles combined families like `"Art 61-62"` by checking for `"Art {article}-"` prefix.
 *
 * @param article - The article number (e.g., 5, 9, 14, 61)
 * @returns Array of controls for the specified article
 */
export function getControlsByArticle(article) {
    const prefix = `Art ${article} -`;
    // Special case: Art 61-62 shares a combined family
    return euAiActFramework.controls.filter((c) => c.family.startsWith(prefix) || c.family.startsWith(`Art ${article}-`));
}
/**
 * Find a single control by its unique identifier.
 *
 * @param id - The control ID (e.g., 'AIA-5.1', 'AIA-14.3')
 * @returns The matching control, or undefined if not found
 */
export function getControlById(id) {
    return euAiActFramework.controls.find((c) => c.id === id);
}
/**
 * Retrieve all controls with a specific implementation status.
 *
 * @param status - The implementation status to filter by
 * @returns Array of controls matching the specified status
 */
export function getControlsByStatus(status) {
    return euAiActFramework.controls.filter((c) => c.implementation === status);
}
/**
 * Look up the BASIS tier mapping for a given AI Act risk tier.
 *
 * @param tier - The AI Act risk tier to look up
 * @returns The mapping, or undefined if the tier is not found
 */
export function getBasisTierMapping(tier) {
    return BASIS_TIER_MAPPINGS.find((m) => m.aiActTier === tier);
}
/**
 * Determine which AI Act risk tier a given BASIS trust tier maps to.
 *
 * @param basisTier - The BASIS trust tier (e.g., 'T0', 'T4', 'T7')
 * @returns The corresponding AI Act risk tier, or undefined if not mapped
 */
export function getAiActTierForBasisTier(basisTier) {
    const mapping = BASIS_TIER_MAPPINGS.find((m) => m.basisTiers.includes(basisTier));
    return mapping?.aiActTier;
}
/**
 * Get a sorted list of all unique article families in the framework.
 *
 * @returns Sorted array of family strings (e.g., 'Art 5 - Prohibited AI Practices', ...)
 */
export function getArticleFamilies() {
    const families = new Set();
    euAiActFramework.controls.forEach((c) => families.add(c.family));
    return Array.from(families).sort();
}
/**
 * Calculate compliance percentage by article, based on the ratio of
 * fully implemented controls to total controls.
 *
 * @returns Map of article number to compliance percentage (0-100)
 */
export function getComplianceByArticle() {
    const result = new Map();
    const articles = [5, 9, 10, 11, 12, 13, 14, 15, 43, 50, 61];
    for (const art of articles) {
        const controls = getControlsByArticle(art);
        const implemented = controls.filter((c) => c.implementation === 'implemented').length;
        const pct = controls.length > 0 ? (implemented / controls.length) * 100 : 0;
        result.set(art, pct);
    }
    return result;
}
//# sourceMappingURL=eu-ai-act.js.map