/**
 * NHS Clinical Safety Standards: DCB0129 + DCB0160 Compliance Pack
 *
 * Standards:
 *   - DCB0129 (Clinical Risk Management: its Application in the Manufacture
 *     of Health IT Systems) — applies to the MANUFACTURER (the customer
 *     building the AI agent / health IT system).
 *   - DCB0160 (Clinical Risk Management: its Application in the Deployment
 *     and Use of Health IT Systems) — applies to the DEPLOYER (the NHS
 *     trust or health organisation running the AI agent in production).
 *
 * Both standards are mandatory for any clinical IT system used in the NHS,
 * issued under the Health and Social Care Act 2012 s250. They are NOT
 * optional and they are NOT alternatives — a clinical IT system used in
 * the NHS must comply with BOTH (manufacturer evidence flows to deployer,
 * deployer adds operational evidence on top).
 *
 * Jurisdiction: GB (United Kingdom — England-led; equivalent practice
 *   followed in Scotland / Wales / Northern Ireland)
 * Authority: NHS England (publishes both standards); previously NHS Digital
 * Regulator overlap: MHRA (when the system is also a SaMD under UKCA);
 *   ICO (when personal data is processed); CQC (well-led KLOE evidence)
 *
 * Why this pack:
 *   - Required for any clinical IT system in the NHS — including AI agents
 *     issuing or supporting clinical recommendations, triage, scheduling,
 *     summarisation of clinical content, or any decision affecting patient
 *     care.
 *   - The Clinical Safety Officer (CSO) role is a contractual gate: a
 *     suitably qualified clinician must be named for the manufacturer side
 *     AND for each deployer organisation.
 *   - Unblocks Pack 4 (MHRA UK SaMD) per F-NEW-TIER-10-UK-WAVE1-ROADMAP —
 *     MHRA SaMD evidence inherits the DCB0129 clinical-safety-case spine.
 *   - Depends on Pack 5 (NHS DSPT, PR #395) for the NHS-data classification
 *     substrate (NHS Number, SNOMED-CT, ICD-10).
 *
 * Key obligations encoded in this pack:
 *   1. Clinical Safety Officer (CSO) named for both manufacturer and each
 *      deployer; sign-off captured on the Clinical Safety Case Report.
 *   2. Hazard log: every clinical hazard identified, scored (likelihood ×
 *      severity → risk level), mitigated, residual-risk assessed, and
 *      reviewed at every release / configuration change.
 *   3. Clinical Safety Case Report (CSCR) — the single document that
 *      assembles hazards, mitigations, residual risk, deployment context,
 *      training and operational instructions, and the CSO sign-off. CSCR
 *      is the contractual artefact a deploying NHS organisation requires
 *      before procuring or going live with a clinical IT system.
 *   4. Change-control gate: any change to a clinical IT system requires
 *      hazard-log re-review and CSCR update before deployment.
 *   5. Incident response: clinical safety incidents reported to the CSO,
 *      logged in the hazard log, and where harm reached or could reach a
 *      patient, escalated to the deploying organisation's Patient Safety
 *      Incident Response Framework (PSIRF) and (if applicable) MHRA Yellow
 *      Card / Field Safety Notice.
 *   6. Manufacturer-deployer evidence handoff: the manufacturer's CSCR is
 *      the deployer's input; the deployer's DCB0160 evidence layers on
 *      operational context (local config, training records, integration
 *      hazards).
 *   7. AI-specific overlays: model-version logging, drift monitoring as a
 *      named hazard, prompt / output sample retention for forensic review.
 *
 * Out of scope:
 *   - MHRA SaMD UKCA marking (separate pack: forthcoming Wave 1 Pack 4)
 *   - NHS DSPT data security baseline (separate pack: nhs-dspt PR #395)
 *   - Cyber Essentials technical-control evidence (separate pack:
 *     cyber-essentials PR #397)
 *   - UK GDPR personal-data handling (separate pack: uk-gdpr)
 *
 * @connexum/ai-governance
 */
/**
 * DCB0129/DCB0160 category classifiers.
 *
 * Pack scope is clinical-safety evidence: hazards, mitigations, CSCR
 * artefacts, CSO sign-off records, change-control reviews, and AI-model
 * audit metadata. Personal-data classification is delegated to nhs-dspt
 * and uk-gdpr packs which a clinical-IT customer must run alongside.
 */
export const NHS_CLINICAL_SAFETY_CATEGORY_CLASSIFIERS = {
    HAZARD_LOG_ENTRY: {
        references: [
            'DCB0129 §5 hazard identification + analysis; DCB0160 §5 deployment hazard log',
        ],
        classifier: (input) => {
            if (/\b(?:hazard\s+(?:log|entry|id|register)|haz[\s-]?\d{2,5})\b/i.test(input))
                return true;
            if (/\b(?:clinical\s+hazard|patient[\s-]?safety\s+hazard|hazard\s+(?:identification|analysis|review))\b/i.test(input))
                return true;
            if (/\b(?:likelihood\s*[x×]\s*severity|risk\s+(?:matrix|score|rating)\s+(?:catastrophic|major|moderate|minor|negligible))\b/i.test(input))
                return true;
            if (/\b(?:residual\s+risk|mitigation\s+(?:control|action|measure))\b/i.test(input))
                return true;
            return false;
        },
    },
    CSCR_DOCUMENT: {
        references: [
            'DCB0129 §6 Clinical Safety Case Report; DCB0160 §6 Deployment Clinical Safety Case Report',
        ],
        classifier: (input) => {
            if (/\b(?:clinical\s+safety\s+case\s+(?:report|cscr)|cscr\s+v\d|safety\s+case\s+(?:document|file))\b/i.test(input))
                return true;
            if (/\b(?:dcb\s*0129\s+(?:report|evidence)|dcb\s*0160\s+(?:report|evidence)|dcb0129|dcb0160)\b/i.test(input))
                return true;
            if (/\b(?:nhs\s+england\s+clinical\s+risk\s+management|clinical\s+risk\s+management\s+system)\b/i.test(input))
                return true;
            return false;
        },
    },
    CSO_SIGNOFF: {
        references: [
            'DCB0129 §4.1 Clinical Safety Officer competence; DCB0160 §4.1 deployer CSO',
        ],
        classifier: (input) => {
            if (/\b(?:clinical\s+safety\s+officer|cso)\s+(?:sign[\s-]?off|approval|attestation|appointment|delegation)\b/i.test(input))
                return true;
            if (/\b(?:cso\s+(?:gmc|nmc|hcpc)|cso\s+name|appointed\s+cso|named\s+clinical\s+safety\s+officer)\b/i.test(input))
                return true;
            return false;
        },
    },
    CLINICAL_INCIDENT: {
        references: [
            'DCB0129/0160 §7 incident management; PSIRF (Patient Safety Incident Response Framework) 2022',
        ],
        classifier: (input) => {
            if (/\b(?:patient[\s-]?safety[\s-]?incident|psi\s+report|psirf|sirio?-)\b/i.test(input))
                return true;
            if (/\b(?:clinical\s+incident|never\s+event|sui\s+(?:incident|investigation)|moderate\s+harm|severe\s+harm)\b/i.test(input))
                return true;
            if (/\b(?:yellow\s+card|field\s+safety\s+notice|fsn|mhra\s+report)\b/i.test(input))
                return true;
            return false;
        },
    },
    AI_MODEL_AUDIT: {
        references: [
            'DCB0129 AI overlay: model version, drift monitoring; NHS England AI Lab guidance',
        ],
        classifier: (input) => {
            if (/\b(?:model\s+version|model[\s-]?id|prompt\s+template\s+v\d|inference\s+(?:trace|transcript))\b/i.test(input))
                return true;
            if (/\b(?:drift\s+(?:detected|alert|threshold)|distribution\s+shift|recalibration\s+required)\b/i.test(input))
                return true;
            if (/\b(?:ai\s+model\s+(?:lifecycle|deployment\s+log)|inference\s+log\s+retained)\b/i.test(input))
                return true;
            return false;
        },
    },
    CLINICAL_RECORD: {
        references: [
            'NHS Records Management Code of Practice 2021 (overlap with nhs-dspt pack); DCB0129/0160 evidence may include patient-identifying material',
        ],
        classifier: (input) => {
            if (/\b(?:patient\s+(?:record|notes|encounter|consultation))\b/i.test(input))
                return true;
            if (/\b(?:clinical\s+(?:record|notes|history|finding|impression))\b/i.test(input))
                return true;
            return false;
        },
    },
    CREDENTIALS: {
        references: ['Cross-pack secrets safety; CSO sign-off artefacts must not embed credentials'],
        classifier: (input) => {
            if (/\b(?:api[_-]?key|apikey)\s*[=:]\s*["']?[A-Za-z0-9_\-\/+]{16,}["']?/i.test(input))
                return true;
            if (/\bpassword\s*[=:]\s*["']?[A-Za-z0-9!@#$%^&*_\-]{8,}["']?/i.test(input))
                return true;
            if (/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/.test(input))
                return true;
            return false;
        },
    },
};
export const NHS_CLINICAL_SAFETY_PACK = {
    categoryClassifiers: NHS_CLINICAL_SAFETY_CATEGORY_CLASSIFIERS,
    id: 'nhs-clinical-safety',
    aliases: [
        'dcb0129',
        'dcb0160',
        'dcb-0129',
        'dcb-0160',
        'nhs-dcb0129-dcb0160',
        'clinical-safety-case',
        'cscr',
        'nhs-clinical-risk-management',
    ],
    name: 'NHS Clinical Safety (DCB0129 manufacturer + DCB0160 deployer)',
    version: '1.0.0',
    contentHash: 'a20ad2aea8b68290442acf828d57a872f614f09fe050c3e7d748c864a92fe09e',
    description: 'NHS England clinical safety standards DCB0129 (manufacturer / health IT vendor) and DCB0160 (deployer / NHS trust) covering hazard log, Clinical Safety Case Report (CSCR), Clinical Safety Officer (CSO) named-role sign-off gate, change-control re-review, and clinical incident escalation per PSIRF + MHRA Yellow Card / FSN. Mandatory for any clinical IT system used in the NHS, including AI agents issuing or supporting clinical recommendations. AI overlay: model-version logging, drift monitoring as a named hazard, inference trace retention. Depends on NHS DSPT (Pack 5) for NHS-data classification substrate; unblocks MHRA SaMD UKCA (Pack 4) per the UK Wave 1 roadmap.',
    authority: 'NHS England (publisher of DCB0129 + DCB0160) + Clinical Safety Officer (named role) + MHRA (for SaMD-overlapping systems) + ICO (UK GDPR overlay) + CQC (well-led KLOE evidence)',
    industries: ['healthcare', 'pharma', 'public-sector', 'digital-health', 'clinical-research', 'medical-devices'],
    requiredModules: [
        {
            name: 'attestation-manager',
            required: true,
            reason: 'CSO designation + Clinical Safety Case Report (CSCR) registration; per-version CSCR + hazard-log attestation; manufacturer-deployer evidence chain.',
            reference: 'DCB0129 §4.1 CSO competence + §6 CSCR; DCB0160 §4.1 deployer CSO + §6 deployment CSCR',
        },
        {
            name: 'governance-runtime',
            required: true,
            reason: 'Clinical-decision gate: AI agent must not issue clinical recommendation without an active CSCR + hazard log covering the recommendation type. Default-deny on uncovered clinical paths.',
            reference: 'DCB0129 §5 hazard identification; DCB0160 §5 deployment hazard log',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'CSO sign-off gate (T2 named-clinician review) on (a) CSCR initial issue and revisions, (b) every change-control event affecting clinical paths, (c) clinical incident classifications above LOW severity.',
            reference: 'DCB0129 §6.4 CSCR sign-off; DCB0160 §7 incident management',
        },
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Tamper-evident audit chain for hazard-log entries, CSO sign-off events, CSCR version history, change-control reviews, and clinical incident records — required as evidence for CQC inspection and PSIRF investigations.',
            reference: 'DCB0129/0160 §7 evidence retention; PSIRF 2022 evidence requirements',
        },
        {
            name: 'event-bus',
            required: true,
            reason: 'Clinical incident detection, model-drift alerts, and Yellow Card / FSN escalation routing; CSO notification on every uncovered hazard path.',
            reference: 'DCB0129/0160 §7 incident management; MHRA Yellow Card scheme; PSIRF',
        },
        {
            name: 'session-persistence',
            required: true,
            reason: 'Inference-trace retention for forensic review of clinical-decision incidents; hazard-log retention beyond product lifecycle (DCB0129 retains for product life + 10 years).',
            reference: 'DCB0129 §8 evidence retention — product lifecycle + 10 years',
        },
        {
            name: 'data-classifier',
            required: true,
            reason: 'Surface hazard-log entries, CSCR documents, CSO sign-off, clinical incidents, AI-model audit records, and clinical-record context for evidence collection.',
            reference: 'DCB0129/0160 evidence categorisation',
        },
        {
            name: 'attestation-manager',
            required: true,
            reason: 'Per-deployment training-records attestation (DCB0160 §6 deployer must show clinicians trained on the system before go-live).',
            reference: 'DCB0160 §6 training records evidence',
        },
        {
            name: 'supply-chain',
            required: true,
            reason: 'Manufacturer-to-deployer evidence handoff: vendor CSCR + DCB0129 evidence flows to each deploying NHS trust which then layers DCB0160 deployer evidence on top.',
            reference: 'DCB0129/0160 manufacturer-deployer interface; NHS Digital procurement guidance',
        },
        {
            name: 'transparency-injector',
            required: true,
            reason: 'Patient-facing AI use disclosure where the AI agent participates in the patient-care pathway; uncertainty / confidence display for clinical-decision support outputs.',
            reference: 'DCB0129/0160 patient-facing transparency overlay; NHS England AI Lab guidance',
        },
        {
            name: 'encryption-layer',
            required: true,
            reason: 'CSCR evidence chain encrypted; clinical incident records encrypted; consistent with DSPT and UK GDPR Art. 32 expectations.',
            reference: 'NHS DSPT Section 7 secure systems; UK GDPR Art. 32(1)(a)',
        },
    ],
    moduleConfig: {
        'attestation-manager': {
            csoDesignationRequired: true,
            cscrRegistrationRequired: true,
            hazardLogPerVersionRequired: true,
            manufacturerDeployerEvidenceChainRequired: true,
            trainingRecordsRequired: true,
            retentionYearsAfterEol: 10,
        },
        'governance-runtime': {
            clinicalDecisionGateRequired: true,
            defaultDenyOnUncoveredClinicalPath: true,
            modelVersionLoggingRequired: true,
            driftMonitoringHazardRequired: true,
        },
        'approval-queue': {
            csoSignOffOnCscrRequired: true,
            csoSignOffOnChangeControlRequired: true,
            csoSignOffOnIncidentClassificationRequired: true,
            reviewTier: 'T2',
            reviewerCompetence: 'CLINICAL_SAFETY_OFFICER',
        },
        'event-bus': {
            clinicalIncidentRoutingRequired: true,
            modelDriftAlertsRequired: true,
            mhraYellowCardEscalationRequired: true,
            fieldSafetyNoticeWorkflowRequired: true,
        },
        'session-persistence': {
            retentionDaysAfterProductEol: 3650, // 10 years post-EoL
            inferenceTraceRetentionRequired: true,
        },
        'data-classifier': {
            enabledCategories: [
                'HAZARD_LOG_ENTRY',
                'CSCR_DOCUMENT',
                'CSO_SIGNOFF',
                'CLINICAL_INCIDENT',
                'AI_MODEL_AUDIT',
                'CLINICAL_RECORD',
                'CREDENTIALS',
            ],
            hazardLogAction: 'WARN',
            cscrDocumentAction: 'WARN',
            csoSignoffAction: 'WARN',
            clinicalIncidentAction: 'WARN',
            aiModelAuditAction: 'WARN',
            credentialsAction: 'BLOCK',
        },
        'supply-chain': {
            vendorCscrEvidenceRequired: true,
            deployerEvidenceLayerRequired: true,
        },
        'transparency-injector': {
            patientFacingAiDisclosureRequired: true,
            confidenceDisplayRequired: true,
        },
        'encryption-layer': {
            algorithm: 'aes-256-gcm',
            encryptionRequiredForClinicalEvidence: true,
        },
    },
    providerPolicy: {
        blockedProviders: ['deepseek', 'baidu', 'alibaba'],
        requiredCapabilities: ['DATA-RESIDENCY-UK-OR-EU', 'PROCESSOR-CONTRACT', 'NHS-DSPT-SUBSCRIBED', 'CLINICAL-SAFETY-EVIDENCE-EXPORT'],
        blockReasons: {
            deepseek: 'PRC jurisdiction. Clinical-safety evidence chain must be UK-resident; no UK adequacy for PRC. Incompatible with DCB0129/0160 evidence retention requirements.',
            baidu: 'PRC jurisdiction. NHS clinical-safety evidence cannot route through PRC infrastructure.',
            alibaba: 'PRC jurisdiction. NHS clinical-safety evidence cannot route through PRC infrastructure.',
        },
    },
    dataPolicy: {
        scanCategories: [
            'HAZARD_LOG_ENTRY',
            'CSCR_DOCUMENT',
            'CSO_SIGNOFF',
            'CLINICAL_INCIDENT',
            'AI_MODEL_AUDIT',
            'CLINICAL_RECORD',
            'CREDENTIALS',
        ],
        categoryActions: {
            HAZARD_LOG_ENTRY: 'WARN',
            CSCR_DOCUMENT: 'WARN',
            CSO_SIGNOFF: 'WARN',
            CLINICAL_INCIDENT: 'WARN',
            AI_MODEL_AUDIT: 'WARN',
            CLINICAL_RECORD: 'WARN',
            CREDENTIALS: 'BLOCK',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
    },
    retentionPolicy: {
        // DCB0129 §8: clinical-safety evidence retained for product lifecycle
        // plus 10 years. We use the 10-year post-EoL window as the policy
        // floor and require legal-hold support for active investigations.
        auditLogRetentionDays: 3650, // 10 years
        sessionRetentionDays: 3650,
        incidentRetentionDays: 3650,
        reference: 'DCB0129 §8 evidence retention (product lifecycle + 10 years); NHS Records Management Code of Practice 2021 alignment',
        forceDelete: false,
        requiresLegalHoldSupport: true,
        sovereignty: ['gb'],
    },
    incidentPolicy: {
        // Clinical-safety incident notification windows are not statutorily
        // fixed in DCB0129/0160 themselves — they delegate to PSIRF and MHRA
        // (Yellow Card for adverse events, FSN for field safety). 72 hours
        // remains the practical baseline aligning with UK GDPR + NHS England.
        notificationDeadlineHours: 72,
        reference: 'DCB0129/0160 §7 incident management; PSIRF 2022; MHRA Yellow Card scheme; MHRA Field Safety Notice (FSN) workflow',
        requiredRecipients: [
            'clinical-safety-officer',
            'caldicott-guardian',
            'senior-information-risk-owner',
            'mhra-yellow-card-scheme',
            'deploying-organisation-cso',
        ],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'nhs-clinical-safety-cso-named',
            description: 'Clinical Safety Officer named (manufacturer side) + per-deployment CSO named (deployer side); credentials (GMC / NMC / HCPC) recorded.',
            reference: 'DCB0129 §4.1 CSO competence; DCB0160 §4.1 deployer CSO',
            check: 'attestation_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-clinical-safety-cscr-current',
            description: 'Clinical Safety Case Report (CSCR) registered, current (no overdue change-control review), and signed off by named CSO.',
            reference: 'DCB0129 §6 CSCR; DCB0160 §6 deployment CSCR',
            check: 'attestation_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-clinical-safety-hazard-log-active',
            description: 'Hazard log active with at least one entry per identified clinical hazard; likelihood × severity score recorded; mitigation + residual risk captured.',
            reference: 'DCB0129 §5 hazard identification; DCB0160 §5 deployment hazard log',
            check: 'attestation_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-clinical-safety-clinical-decision-gate',
            description: 'Default-deny on AI clinical-decision actions where no covering hazard-log entry + CSCR section exists. CSO sign-off gate engaged on uncovered clinical paths.',
            reference: 'DCB0129 §5 hazard identification; default-deny clinical-safety overlay',
            check: 'governance_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-clinical-safety-change-control',
            description: 'Every change to a clinical IT system triggers hazard-log re-review and CSCR update before deployment; CSO sign-off gates the rollout.',
            reference: 'DCB0129/0160 §6 change control',
            check: 'approval_queue_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'nhs-clinical-safety-incident-routing',
            description: 'Clinical incidents route to CSO + Caldicott Guardian + SIRO; PSIRF investigation pathway available; MHRA Yellow Card + FSN escalation wired.',
            reference: 'DCB0129/0160 §7 incident management; PSIRF 2022; MHRA Yellow Card',
            check: 'monitoring_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-clinical-safety-model-version-logging',
            description: 'AI model version + prompt template version + inference-trace ID recorded on every clinical recommendation for forensic review.',
            reference: 'DCB0129 AI overlay; NHS England AI Lab guidance',
            check: 'audit_trail_exists',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-clinical-safety-drift-monitoring',
            description: 'AI model drift monitoring active and named as a hazard in the hazard log; recalibration / retraining workflow defined.',
            reference: 'DCB0129 AI overlay; NHS England AI lifecycle guidance',
            check: 'monitoring_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-clinical-safety-evidence-retention',
            description: 'Clinical-safety evidence retained for product lifecycle plus 10 years; legal-hold support active for incident investigations.',
            reference: 'DCB0129 §8 evidence retention',
            check: 'retention_policy_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-clinical-safety-deployer-training',
            description: 'Deployer-side training records captured before go-live; clinicians attested as trained on the clinical IT system.',
            reference: 'DCB0160 §6 training records',
            check: 'attestation_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-clinical-safety-manufacturer-deployer-handoff',
            description: 'Manufacturer CSCR + DCB0129 evidence package available to deploying organisation; deployer DCB0160 evidence layered on top.',
            reference: 'DCB0129/0160 manufacturer-deployer interface',
            check: 'subservice_registry_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'nhs-clinical-safety-encryption',
            description: 'Clinical-safety evidence chain encrypted at rest and in transit; consistent with NHS DSPT Section 7 and UK GDPR Art. 32.',
            reference: 'NHS DSPT Section 7; UK GDPR Art. 32(1)(a)',
            check: 'encryption_active',
            failSeverity: 'MEDIUM',
        },
    ],
};
//# sourceMappingURL=nhs-dcb0129-dcb0160.js.map