"use strict";
/**
 * CMS Conditions of Participation (CoP) Compliance Pack
 *
 * 42 CFR Part 482 — Conditions of Participation for Hospitals
 * 42 CFR Part 484 — Home Health Agencies
 * 42 CFR Part 416 — Ambulatory Surgical Centers
 *
 * Enforces 9 of 10 rules from rules.md:
 *   BLOCK: CMS-COP-001 (doc auth), CMS-COP-005 (infection control),
 *          CMS-COP-008 (OASIS consistency), CMS-COP-010 (restraints)
 *   WARN:  CMS-COP-002 (patient rights), CMS-COP-003 (advance directive),
 *          CMS-COP-004 (discharge planning), CMS-COP-006 (staffing ratio),
 *          CMS-COP-007 (QAPI projections)
 *   SKIP:  CMS-COP-009 — human-attestation (ASC pre-procedure), not wired here
 *
 * @connexum/ai-governance | Kai (CXNI-005) | 2026-05-24
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.CMS_COP_PACK = exports.CMS_COP_CATEGORY_CLASSIFIERS = void 0;
/**
 * CategoryClassifiers for CMS Conditions of Participation.
 *
 * The PackDrivenClassifier engine loads these at boot time and evaluates them
 * on every agent output that passes through the GovernedAgent PreToolUse hook.
 *
 * Enforcement_pattern mapping from rules.md:
 *   - regex:<pattern> rules → pattern field
 *   - semantic:<tag> rules  → classifier function (structural heuristics; full
 *     semantic embedding comparison is a future-tier enhancement; the classifier
 *     implements the structural signal described in the enforcement_pattern)
 */
exports.CMS_COP_CATEGORY_CLASSIFIERS = {
    /**
     * CMS-COP-001 — BLOCK
     * Clinical documentation must include physician/practitioner authentication
     * for discharge summaries, operative reports, H&P, and progress notes.
     * 42 CFR §482.24(c)(2)(viii)
     *
     * enforcement_pattern: semantic:clinical-doc-auth-missing
     * Structural signal: document contains a clinical document type header
     * but lacks an authentication/signature block.
     */
    CLINICAL_DOC_AUTH_MISSING: {
        references: ['42 CFR §482.24(c)(2)(viii) — Medical record authentication'],
        classifier: (input) => {
            // Must be a relevant clinical document type
            const isClinicalDoc = /\b(discharge\s+summary|operative\s+report|history\s+and\s+physical|h\s*&\s*p|progress\s+note|procedure\s+note)\b/i.test(input);
            if (!isClinicalDoc)
                return false;
            // Check for authentication signature.
            // BUGFIX (F-NEW-CLASSIFIER-FIRE-RATE-FRAMEWORK-2026-05-24): changed [A-Za-z\s,]+ to
            // [A-Za-z\s,\.]+ so that titles like "Dr." (containing a period) are accepted in
            // the signer name. Without the period, any signature line with "Dr. Firstname Lastname,
            // MD" failed to match and the classifier false-flagged compliant documents.
            const hasAuth = /(authenticated|electronically\s+signed|e-?signed|attested|signed)\s+by[:\s]+[A-Za-z\s,\.]+\s*(MD|DO|PA|NP|CRNP|CNM|APRN|RN|PharmD|DPM|DC|OD)/i.test(input);
            return !hasAuth;
        },
    },
    /**
     * CMS-COP-002 — WARN
     * Patient rights notification must be documented at admission.
     * 42 CFR §482.13(b)
     *
     * enforcement_pattern: regex for patient rights language in admission docs
     */
    PATIENT_RIGHTS_MISSING: {
        references: ['42 CFR §482.13(b) — Patient rights notification at admission'],
        classifier: (input) => {
            // Only flag admission documents
            const isAdmissionDoc = /\b(admission\s+note|admit\s+note|admitting\s+note|intake\s+assessment|admission\s+assessment|admit\s+diagnosis|admitting\s+diagnosis)\b/i.test(input);
            if (!isAdmissionDoc)
                return false;
            // Check for patient rights documentation
            const hasRights = /(patient\s+rights|notice\s+of\s+rights|rights\s+notification|informed\s+of\s+rights|rights\s+(provided|given|offered|reviewed))/i.test(input);
            return !hasRights;
        },
    },
    /**
     * CMS-COP-003 — WARN
     * Advance Directive status must be documented in the medical record at admission.
     * 42 CFR §482.13(k)
     *
     * enforcement_pattern: regex for advance directive language in admission docs
     */
    ADVANCE_DIRECTIVE_MISSING: {
        references: ['42 CFR §482.13(k) — Advance directive documentation at admission'],
        classifier: (input) => {
            // Only flag admission / intake documents
            const isAdmissionDoc = /\b(admission\s+note|admit\s+note|admitting\s+note|intake\s+assessment|admission\s+assessment)\b/i.test(input);
            if (!isAdmissionDoc)
                return false;
            // Check for advance directive documentation
            const hasAdvDir = /(advance\s+directive|living\s+will|healthcare\s+proxy|health\s+care\s+proxy|POLST|DNR\s+status|do\s+not\s+resuscitate|durable\s+power\s+of\s+attorney)/i.test(input);
            return !hasAdvDir;
        },
    },
    /**
     * CMS-COP-004 — WARN
     * Discharge planning must document patient choice of post-acute provider
     * and written discharge instructions.
     * 42 CFR §482.43(c)(7) and (c)(8)
     *
     * enforcement_pattern: semantic:discharge-plan-completeness
     */
    DISCHARGE_PLAN_INCOMPLETE: {
        references: ['42 CFR §482.43(c)(7), (c)(8) — Discharge planning patient choice + written instructions'],
        classifier: (input) => {
            // Only flag discharge plan documents
            const isDischargeDoc = /\b(discharge\s+plan|discharge\s+planning|discharge\s+summary|patient\s+discharge)\b/i.test(input);
            if (!isDischargeDoc)
                return false;
            const hasPatientChoice = /(patient\s+(choice|chose|selected|preference|right\s+to\s+choose)|right\s+to\s+choose|provider\s+options|facility\s+options|post.?acute\s+(options|choice|selection))/i.test(input);
            const hasWrittenInstructions = /(written\s+(discharge\s+)?(instructions|instructions\s+provided)|discharge\s+instructions\s+(provided|given)|instructions\s+provided\s+in\s+writing)/i.test(input);
            return !hasPatientChoice || !hasWrittenInstructions;
        },
    },
    /**
     * CMS-COP-005 — BLOCK
     * Infection control recommendations must be consistent with CDC guidelines.
     * 42 CFR §482.42(a)
     *
     * enforcement_pattern: semantic:infection-control-non-standard
     * Structural signal: output contains infection control instructions that
     * contradict standard CDC Standard Precautions patterns.
     */
    INFECTION_CONTROL_NON_STANDARD: {
        references: ['42 CFR §482.42(a) — Infection control aligned with nationally recognized practices'],
        classifier: (input) => {
            // Must be an infection control recommendation
            const isInfectionControl = /\b(infection\s+control|isolation\s+precautions?|PPE\s+(requirements?|recommendation)|standard\s+precautions?|transmission.?based\s+precautions?|contact\s+precautions?|droplet\s+precautions?|airborne\s+precautions?)\b/i.test(input);
            if (!isInfectionControl)
                return false;
            // Flag if it recommends skipping PPE or contradicts standard precautions
            const contradictsStandard = /(no\s+(PPE|mask|gloves|gown)\s+(needed|required|necessary)|skip\s+(PPE|hand\s+hygiene|isolation)|hand\s+hygiene\s+(not\s+required|unnecessary)|mask\s+(not\s+required|not\s+needed)\s+for\s+(COVID|TB|measles|SARS|airborne))/i.test(input);
            return contradictsStandard;
        },
    },
    /**
     * CMS-COP-006 — WARN
     * Staffing calculations must not produce ratios below the minimum sufficient-care threshold.
     * 42 CFR §482.23(b)
     *
     * enforcement_pattern: semantic:staffing-ratio-threshold
     * Structural signal: staffing output contains a nurse-to-patient ratio
     * that appears to exceed safe limits (uses numeric pattern to detect ratios).
     */
    STAFFING_RATIO_THRESHOLD: {
        references: ['42 CFR §482.23(b) — Nursing services sufficient to meet patient needs'],
        classifier: (input) => {
            // Must be a staffing schedule/calculation output
            const isStaffing = /\b(staffing\s+(schedule|calculation|ratio|assignment|plan)|nurse.?to.?patient\s+ratio|RN\s+to\s+patient|patient\s+(load|assignment|ratio))\b/i.test(input);
            if (!isStaffing)
                return false;
            // Flag if any ratio appears dangerously high (>1:8 as a catch-all signal)
            // Ratios like "1:10", "1:12" in staffing outputs are flagged
            const hasHighRatio = /\b1\s*:\s*(9|10|11|12|13|14|15|16|17|18|19|20)\b/.test(input);
            return hasHighRatio;
        },
    },
    /**
     * CMS-COP-007 — WARN
     * QAPI data must not present projections as actual measured outcomes.
     * 42 CFR §482.21(b)
     *
     * enforcement_pattern: regex for projection language in QAPI reports
     */
    QAPI_PROJECTION_MISLABEL: {
        references: ['42 CFR §482.21(b) — QAPI program must use measured data, not projections'],
        pattern: /(projected|estimated|modeled|simulated|forecast(ed)?)\s+(outcome|result|rate|improvement|performance|metric|data)/i,
    },
    /**
     * CMS-COP-008 — BLOCK
     * OASIS assessment must not contain internally inconsistent functional status responses.
     * 42 CFR §484.55
     *
     * enforcement_pattern: semantic:oasis-internal-consistency
     * Structural signal: detects M-item responses that are contradictory.
     * Classic contradiction: M1800=0 (independent) while M1810=3 (total assistance).
     */
    OASIS_INTERNAL_INCONSISTENCY: {
        references: ['42 CFR §484.55 — OASIS assessment accuracy and internal consistency'],
        classifier: (input) => {
            // Must be an OASIS assessment output
            const isOasis = /\b(OASIS|M1800|M1810|M1820|M1830|M1840|M-item)\b/.test(input);
            if (!isOasis)
                return false;
            // Detect classic contradiction: M1800=0 (independent) with M1810=3 (total)
            const m1800IndependentMatch = /M1800[^:]*:\s*0\b|M1800[:\s]+(0\s*[-–—]\s*(independent|able\s+to\s+groom))/i.test(input);
            const m1810TotalMatch = /M1810[^:]*:\s*3\b|M1810[:\s]+(3\s*[-–—]\s*(total\s+assistance|unable))/i.test(input);
            if (m1800IndependentMatch && m1810TotalMatch)
                return true;
            // Detect bathing=independent with dressing=total
            const bathingIndependent = /M1830[^:]*:\s*0\b/i.test(input);
            const dressingTotal = /M181[02][^:]*:\s*3\b/i.test(input);
            if (bathingIndependent && dressingTotal)
                return true;
            return false;
        },
    },
    /**
     * CMS-COP-010 — BLOCK
     * Restraint/seclusion recommendations must include clinical justification,
     * time limit, and monitoring frequency.
     * 42 CFR §482.13(e)
     *
     * enforcement_pattern: regex for restraint/seclusion context combined with
     * semantic check for required elements
     */
    RESTRAINT_MISSING_ELEMENTS: {
        references: ['42 CFR §482.13(e) — Restraint and seclusion use requirements'],
        classifier: (input) => {
            // Must contain restraint/seclusion terminology in a clinical order context
            const isRestraintContext = /\b(restraint?s?|restraining|seclusion|seclude|physical\s+hold|immobilize)\b/i.test(input);
            if (!isRestraintContext)
                return false;
            // Check that all three required elements are present
            const hasJustification = /(clinical\s+justification|least.?restrictive\s+alternative|alternatives?\s+(attempted|tried|failed)|justification\s+for|clinical\s+basis)/i.test(input);
            const hasTimeLimit = /(time.?limited|time\s+limit|\d+\s*hour(s)?\s+(order|limit|maximum)|reassessment\s+in\s+\d+)/i.test(input);
            const hasMonitoring = /(monitoring\s+frequency|monitor\s+every\s+\d+\s*min|check\s+every\s+\d+\s*min|assessment\s+every\s+\d+\s*min)/i.test(input);
            return !hasJustification || !hasTimeLimit || !hasMonitoring;
        },
    },
};
exports.CMS_COP_PACK = {
    categoryClassifiers: exports.CMS_COP_CATEGORY_CLASSIFIERS,
    id: 'cms-cop',
    name: 'CMS Conditions of Participation',
    version: '1.0.0',
    contentHash: '3df38a4cf4e1bdda1e09b4c189c1c6c100767981472a78cb886a7cf66fbe2a48',
    description: 'CMS Conditions of Participation (CoP) for Hospitals (42 CFR Part 482), Home Health Agencies (42 CFR Part 484), and Ambulatory Surgical Centers (42 CFR Part 416). Runtime enforcement for AI agents generating clinical documentation in CMS-certified facilities.',
    authority: 'Centers for Medicare & Medicaid Services (CMS)',
    industries: ['healthcare', 'hospital', 'home-health', 'ambulatory-surgical-center', 'health-it'],
    requiredModules: [
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Clinical documentation audit trail for CoP survey readiness',
            reference: '42 CFR §482.24 — Medical Record Services',
        },
        {
            name: 'governance-runtime',
            required: true,
            reason: 'Deny-by-default enforcement on unauthenticated clinical documents',
            reference: '42 CFR §482.24(c)(2)(viii)',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'Human review routing for flagged QAPI and discharge planning outputs',
            reference: '42 CFR §482.21, §482.43',
        },
    ],
    moduleConfig: {
        'audit-integrity': {
            retentionDays: 1825, // 5 years per CMS medical record retention guidance
        },
        'governance-runtime': {
            denyByDefaultRequired: true,
        },
    },
    providerPolicy: {
        blockedProviders: [],
        requiredCapabilities: [],
        blockReasons: {},
    },
    dataPolicy: {
        scanCategories: [
            'CLINICAL_DOC_AUTH_MISSING',
            'PATIENT_RIGHTS_MISSING',
            'ADVANCE_DIRECTIVE_MISSING',
            'DISCHARGE_PLAN_INCOMPLETE',
            'INFECTION_CONTROL_NON_STANDARD',
            'STAFFING_RATIO_THRESHOLD',
            'QAPI_PROJECTION_MISLABEL',
            'OASIS_INTERNAL_INCONSISTENCY',
            'RESTRAINT_MISSING_ELEMENTS',
        ],
        categoryActions: {
            CLINICAL_DOC_AUTH_MISSING: 'BLOCK',
            PATIENT_RIGHTS_MISSING: 'WARN',
            ADVANCE_DIRECTIVE_MISSING: 'WARN',
            DISCHARGE_PLAN_INCOMPLETE: 'WARN',
            INFECTION_CONTROL_NON_STANDARD: 'BLOCK',
            STAFFING_RATIO_THRESHOLD: 'WARN',
            QAPI_PROJECTION_MISLABEL: 'WARN',
            OASIS_INTERNAL_INCONSISTENCY: 'BLOCK',
            RESTRAINT_MISSING_ELEMENTS: 'BLOCK',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
    },
    retentionPolicy: {
        auditLogRetentionDays: 1825, // 5 years
        sessionRetentionDays: 1825,
        incidentRetentionDays: 1825,
        reference: 'CMS medical record retention guidance; 42 CFR §482.24',
        forceDelete: false,
        requiresLegalHoldSupport: true,
        sovereignty: ['us'],
    },
    incidentPolicy: {
        notificationDeadlineHours: 24,
        reference: '42 CFR §482.13 — Patient rights; immediate jeopardy notification',
        requiredRecipients: ['compliance-officer', 'cms-regional-office'],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'cms-cop-doc-auth',
            description: 'Clinical documentation authentication classifier active',
            reference: '42 CFR §482.24(c)(2)(viii)',
            check: 'data_classifier_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'cms-cop-oasis-consistency',
            description: 'OASIS internal consistency checker active',
            reference: '42 CFR §484.55',
            check: 'data_classifier_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'cms-cop-restraint-check',
            description: 'Restraint documentation element checker active',
            reference: '42 CFR §482.13(e)',
            check: 'data_classifier_active',
            failSeverity: 'HIGH',
        },
    ],
    requiresRetrievalAuditLogging: true,
    requiresCitations: true,
    maxAutonomyLevelWithoutAttestation: 2,
    recommendedHookProfile: 'strict',
};
//# sourceMappingURL=cms-cop.js.map