/**
 * GovernedAgent -- Simple "front door" factory for @connexum/ai-governance.
 *
 * Instead of wiring 50+ classes together, call createGovernedAgent(config)
 * and get back a governed agent that enforces rules, logs audit trails,
 * and computes compliance scores.
 *
 * @connexum/ai-governance
 */
import * as crypto from 'node:crypto';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { BaseGovernanceAdapter, ActionDecisionType, allow, deny, requireApproval, } from './adapters/index.js';
import { PackRegistry } from './packs/index.js';
import { computePackContentHash } from './packs/pack-content-hash.js';
import { AuditIntegrity } from './audit/audit-integrity.js';
import { EventBus } from './audit/event-bus.js';
import { PackEvaluator } from './governance/pack-evaluator.js';
import { SOC1_PACK } from './packs/soc1.js';
import { SOC2_PACK } from './packs/soc2.js';
import { HIPAA_PACK } from './packs/hipaa.js';
import { HITECH_PACK } from './packs/hitech.js';
import { GLBA_PACK } from './packs/glba.js';
import { ABA_PACK } from './packs/aba.js';
import { FTC5_PACK } from './packs/ftc5.js';
import { SR117_PACK } from './packs/sr117.js';
import { PART11_PACK } from './packs/part11.js';
import { SOX404_PACK } from './packs/sox404.js';
import { BSA_AML_PACK } from './packs/bsa-aml.js';
import { NYDFS500_PACK } from './packs/nydfs500.js';
import { CFPB_2023_03_PACK } from './packs/cfpb-2023-03.js';
import { BIPA_PACK } from './packs/bipa.js';
import { FDA_SAMD_PACK } from './packs/fda-samd.js';
import { PART2_PACK } from './packs/part2.js';
import { GXP_PACK } from './packs/gxp.js';
import { NYC_LL_144_PACK } from './packs/nyc-ll-144.js';
import { EU_AI_LIABILITY_PACK } from './packs/eu-ai-liability.js';
import { ISO_23894_PACK } from './packs/iso-23894.js';
import { LGPD_PACK } from './packs/lgpd.js';
import { PIPL_PACK } from './packs/pipl.js';
// X2 disaggregation (2026-04-24): pipeda.ts deleted -- use ca-pipeda + ca-qc-law25
import { CA_PIPEDA_PACK } from './packs/ca-pipeda.js';
import { QC_LAW25_PACK } from './packs/ca-qc-law25.js';
import { GDPR_PACK } from './packs/gdpr.js';
import { CCPA_PACK } from './packs/ccpa.js';
import { COLORADO_AI_PACK } from './packs/colorado-ai.js';
import { PCIDSS_PACK } from './packs/pcidss.js';
import { DORA_PACK } from './packs/dora.js';
import { EUAIACT_PACK } from './packs/euaiact.js';
import { ISO27001_PACK } from './packs/iso27001.js';
import { NIST_AI_RMF_PACK } from './packs/nist-ai-rmf.js';
import { ISO_42001_PACK } from './packs/iso42001.js';
import { MIFID2_PACK } from './packs/mifid2.js';
import { NAIC_MDL_PACK } from './packs/naic-mdl.js';
import { FRCP26_PACK } from './packs/frcp26.js';
import { FOIA_PACK } from './packs/foia.js';
import { LPO2024_PACK } from './packs/lpo2024.js';
import { FERPA_PACK } from './packs/ferpa.js';
import { FEDRAMP_PACK } from './packs/fedramp.js';
import { STATERAMP_PACK } from './packs/stateramp.js';
import { CJIS_PACK } from './packs/cjis.js';
import { CMMC2_PACK } from './packs/cmmc2.js';
// Mortgage-industry packs (MORTGAGE-PACKS-01, 2026-04-22; X3 split 2026-04-24)
// respa renamed to us-respa; tila-trid split into us-trid + us-tila
import { US_RESPA_PACK } from './packs/us-respa.js';
import { HMDA_PACK } from './packs/hmda.js';
import { US_TRID_PACK } from './packs/us-trid.js';
import { US_TILA_PACK } from './packs/us-tila.js';
import { ECOA_PACK } from './packs/ecoa.js';
import { FCRA_PACK } from './packs/fcra.js';
// BATCH-01: AU packs + extended packs (P0 registry fix, 2026-04-25)
import { AU_ACT_HRPAA_PACK } from './packs/au-act-hrpaa.js';
import { AU_AIETHICS_PACK } from './packs/au-aiethics-framework.js';
import { AU_AML_CTF_PACK } from './packs/au-aml-ctf.js';
import { AU_ASIC_RG271_PACK } from './packs/au-asic-rg-271.js';
import { AU_ASIC_RG274_PACK } from './packs/au-asic-rg-274.js';
import { AU_CDR_PACK } from './packs/au-cdr.js';
import { AU_CPS230_PACK } from './packs/au-cps230.js';
import { AU_CPS234_PACK } from './packs/au-cps234.js';
import { AU_MANDATORY_AI_GUARDRAILS_PACK } from './packs/au-mandatory-ai-guardrails.js';
import { AU_NSW_HRIPA_PACK } from './packs/au-nsw-hripa.js';
import { AU_ONLINE_SAFETY_PACK } from './packs/au-online-safety.js';
import { AU_PRIVACY_ACT_PACK } from './packs/au-privacy-act.js';
import { AU_SOCI_PACK } from './packs/au-soci-act.js';
import { AU_SPAM_ACT_PACK } from './packs/au-spam-act.js';
import { AU_TGA_SAIMD_PACK } from './packs/au-tga-saimd.js';
import { AU_VIC_HRA_PACK } from './packs/au-vic-hra.js';
import { CALIFORNIA_AB2930_PACK } from './packs/california-ab2930.js';
import { CMS_INTEROPERABILITY_PACK } from './packs/cms-interoperability.js';
import { COMMON_RULE_PACK } from './packs/common-rule.js';
import { COPPA_PACK } from './packs/coppa.js';
import { DE_BDSG_PACK } from './packs/de-bdsg.js';
import { EU_LPP_PACK } from './packs/eu-lpp.js';
import { EU_MDR_IVDR_PACK } from './packs/eu-mdr-ivdr.js';
import { FCA_CONSUMER_DUTY_PACK } from './packs/fca-consumer-duty.js';
import { FCA_OP_RESILIENCE_PACK } from './packs/fca-op-resilience.js';
import { FINRA_3110_PACK } from './packs/finra-3110.js';
import { FLORIDA_STUDENT_PRIVACY_PACK } from './packs/florida-student-privacy.js';
import { ILLINOIS_AIVIA_PACK } from './packs/illinois-aivia.js';
import { IN_DPDP_PACK } from './packs/in-dpdp.js';
import { ISO20022_PACK } from './packs/iso20022.js';
import { ISO27701_PACK } from './packs/iso27701.js';
import { JP_APPI_PACK } from './packs/jp-appi.js';
import { KR_PIPA_PACK } from './packs/kr-pipa.js';
import { MARYLAND_HB1202_PACK } from './packs/maryland-hb1202.js';
import { NIS2_PACK } from './packs/nis2.js';
import { NZ_PRIVACY_PACK } from './packs/nz-privacy.js';
import { REG_E_PACK } from './packs/reg-e.js';
import { SG_MODEL_AI_GOV_PACK } from './packs/sg-model-ai-gov.js';
import { TENNESSEE_ELVIS_PACK } from './packs/tennessee-elvis.js';
import { TEXAS_HB4_PACK } from './packs/texas-hb4.js';
import { TITLE_IX_PACK } from './packs/title-ix.js';
import { UK_AI_FRAMEWORK_PACK } from './packs/uk-ai-framework.js';
import { UK_GDPR_PACK } from './packs/uk-gdpr.js';
import { NHS_DSPT_PACK } from './packs/nhs-dspt.js';
import { CYBER_ESSENTIALS_PACK } from './packs/cyber-essentials.js';
import { NHS_CLINICAL_SAFETY_PACK } from './packs/nhs-dcb0129-dcb0160.js';
import { MHRA_SAMD_UKCA_PACK } from './packs/mhra-samd-ukca.js';
import { NHS_DTAC_PACK } from './packs/nhs-dtac.js';
import { CALDICOTT_PRINCIPLES_PACK } from './packs/caldicott-principles.js';
import { NCSC_CAF_PACK } from './packs/ncsc-caf.js';
import { NCSC_AI_SECURITY_PACK } from './packs/ncsc-ai-security.js';
import { UK_EQUALITY_ACT_PACK } from './packs/uk-equality-act.js';
import { UK_EQUALITY_ACT_AI_BIAS_PACK } from './packs/uk-equality-act-ai-bias.js';
import { UK_NIS_REGS_PACK } from './packs/uk-nis-regs.js';
import { UK_CMA_1990_PACK } from './packs/uk-cma-1990.js';
import { UK_FUTURE_AI_LEGISLATION_PACK } from './packs/uk-future-ai-legislation.js';
import { UK_ONLINE_SAFETY_PACK } from './packs/uk-online-safety-act.js';
import { UK_PROCUREMENT_PACK } from './packs/uk-procurement-act.js';
import { CMA_AI_FM_PACK } from './packs/cma-ai-foundation-models.js';
import { NHS_PSIRF_PACK } from './packs/nhs-psirf.js';
import { UK_ICO_OPEN_CASE_PACK } from './packs/uk-ico-open-case.js';
import { NICE_ESF_DHT_PACK } from './packs/nice-esf-dht.js';
import { NI_EQUALITY_PACK } from './packs/ni-equality.js';
import { SCOTLAND_AWI_PACK } from './packs/scotland-awi.js';
import { WALES_WBFG_PACK } from './packs/wales-future-generations.js';
import { SCOTLAND_PSED_PACK } from './packs/scotland-psed.js';
import { NI_HSCNI_PACK } from './packs/ni-hscni.js';
import { EU_DSA_PACK } from './packs/eu-dsa.js';
import { EU_DMA_PACK } from './packs/eu-dma.js';
import { NIST_CSF_PACK } from './packs/nist-csf.js';
import { NIST_800_53_PACK } from './packs/nist-800-53.js';
import { HITRUST_CSF_PACK } from './packs/hitrust-csf.js';
import { EU_DATA_ACT_PACK } from './packs/eu-data-act.js';
import { EU_CRA_PACK } from './packs/eu-cra.js';
import { SCOTLAND_PROCUREMENT_PACK } from './packs/scotland-procurement-reform.js';
import { NI_MCA_PACK } from './packs/ni-mental-capacity.js';
import { HK_PDPO_PACK } from './packs/hk-pdpo.js';
import { VN_PDPD_PACK } from './packs/vn-pdpd.js';
import { TH_PDPA_PACK } from './packs/th-pdpa.js';
import { CN_DSL_CSL_PACK } from './packs/cn-dsl-csl.js';
import { NIH_COC_PACK } from './packs/us-nih-coc.js';
import { NIH_DMS_PACK } from './packs/us-nih-dms.js';
import { NIH_GDS_PACK } from './packs/us-nih-gds.js';
import { NIH_IT_SECURITY_PACK } from './packs/us-nih-it-security.js';
import { US_FDA_21CFR56_PACK } from './packs/us-fda-21cfr56.js';
import { UTAH_AI_POLICY_PACK } from './packs/utah-ai-policy.js';
import { DO_178C_PACK } from './packs/do-178c.js';
import { FDA_21_CFR_820_PACK } from './packs/fda-21-cfr-820.js';
import { IEC_62304_PACK } from './packs/iec-62304.js';
import { ISO_26262_PACK } from './packs/iso-26262.js';
import { IEC_62443_PACK } from './packs/iec-62443.js';
import { NIST_SP_800_82_PACK } from './packs/nist-sp-800-82.js';
import { AS_9100_PACK } from './packs/as-9100.js';
import { FDA_SAMD_PRECERT_PACK } from './packs/fda-samd-precert.js';
import { ISO_15189_PACK } from './packs/iso-15189.js';
import { ISO_IEC_80001_PACK } from './packs/iso-iec-80001.js';
// PR-2: New HARD-REQUIRED pack added for ECPA Title III
import { ECPA_PACK } from './packs/ecpa.js';
// F-NEW-ALL-PACKS-RUNTIME-2026-05-24: 6 Healthcare-US runtime classifier packs
import { CMS_COP_PACK } from './packs/cms-cop.js';
import { B340_DSCSA_PACK } from './packs/340b-dscsa.js';
import { NO_SURPRISES_ACT_PACK } from './packs/no-surprises-act.js';
import { MEDICARE_MEDICAID_BILLING_PACK } from './packs/medicare-medicaid-billing.js';
import { STARK_AKS_PACK } from './packs/stark-aks.js';
import { AI_CDS_PACK } from './packs/ai-clinical-decision-support.js';
// ---------------------------------------------------------------------------
// OperatorSuspendedError — thrown when the operator kill-switch is active
// ---------------------------------------------------------------------------
/**
 * Thrown by execute() when the SDK-path operator kill-switch is active for
 * this agentId. Indicates that an operator has explicitly suspended the agent
 * via POST /api/v1/agents/:id/suspend, and the SuspendStateCache has
 * propagated the state to the local CircuitBreaker.
 *
 * ASI-10 SDK kill-switch. Callers should surface this to the end user as a
 * hard block distinct from a pack policy violation.
 */
export class OperatorSuspendedError extends Error {
    /** The agentId that is currently suspended. */
    agentId;
    constructor(agentId) {
        super(`Agent '${agentId}' is operator-suspended. ` +
            `All tool calls are blocked until the operator resumes the agent ` +
            `(POST /api/v1/agents/${agentId}/resume). ASI-10 SDK kill-switch active.`);
        this.name = 'OperatorSuspendedError';
        this.agentId = agentId;
    }
}
// ---------------------------------------------------------------------------
// PackPolicyViolation error (thrown when pack evaluator returns DENY)
// ---------------------------------------------------------------------------
/**
 * Thrown by execute() when the pack evaluator produces a DENY verdict.
 * Callers should catch this to surface a governance-blocked result.
 */
export class PackPolicyViolation extends Error {
    /** Human-readable explanation from the pack evaluator. */
    packReason;
    /** IDs of packs whose rules produced the DENY verdict. */
    triggeringPackIds;
    /**
     * F-NEW-CRIT-39i-2: classifier IDs (e.g. PHI_MRN, GDPR_DOB) that
     * fired inside the triggering packs. Surfaces from
     * PackEvaluatorVerdict.triggeringClassifierIds so the gov-server
     * audit chain (CRIT-39i regulatoryViolations) can record per-
     * category breadcrumbs instead of pack-level only.
     */
    triggeringClassifierIds;
    /** F-NEW-CRIT-39j-3: true when DENY came from adapter default-deny (no rule matched). */
    defaultDenyTriggered;
    constructor(reason, triggeringPackIds, triggeringClassifierIds = [], defaultDenyTriggered = false) {
        super(`Pack policy violation: ${reason}`);
        this.name = 'PackPolicyViolation';
        this.packReason = reason;
        this.triggeringPackIds = triggeringPackIds;
        this.triggeringClassifierIds = triggeringClassifierIds;
        this.defaultDenyTriggered = defaultDenyTriggered;
    }
}
/**
 * Thrown by createGovernedAgent() when a requested pack ID is not found in
 * BUILT_IN_PACKS. Replaces the previous silent-skip behavior (Task 3 fix).
 *
 * A customer requesting a non-existent pack was silently getting zero
 * enforcement -- indistinguishable from a correctly-configured agent with
 * no restrictions. This error makes the misconfiguration immediately visible.
 *
 * Callers that want softer handling (e.g., during pack catalog migrations)
 * can catch MissingPackError at the call site.
 */
export class MissingPackError extends Error {
    /** The pack ID that was not found. */
    packId;
    constructor(packId, message) {
        super(message);
        this.name = 'MissingPackError';
        this.packId = packId;
    }
}
/**
 * Thrown by createGovernedAgent() when a compliance pack's runtime content
 * does not match its embedded contentHash. This detects monkey-patching of
 * a pack's validators[] or requiredModules[] after the module was loaded.
 *
 * Layer 3 of the third-party pack rejection defence.
 * F-NEW-LAYER3-PACK-CONTENT-HASH-NOT-WIRED-2026-05-25
 *
 * Attack scenario: an attacker clears validators[] on HIPAA_PACK in-memory
 * so it enforces nothing, but the audit chain still says "HIPAA enforced".
 * Layer 3 catches this by re-computing the hash at createGovernedAgent()
 * time and comparing against pack.contentHash (embedded at build time).
 */
export class PackContentTamperedError extends Error {
    /** The id field of the pack whose content hash mismatched. */
    packId;
    /**
     * The hash stored in pack.contentHash (trusted — set at build time).
     * Private: hash values are NOT surfaced publicly to prevent oracle attacks
     * where an attacker reads expected hashes off the wire and crafts a
     * matching tampered pack. Use structured server-side logging instead.
     */
    _expectedHash;
    /**
     * The hash recomputed from the live runtime pack object.
     * Private: same oracle-attack rationale as _expectedHash.
     */
    _actualHash;
    constructor(packId, expectedHash, actualHash) {
        super(`Pack '${packId}' content tampered: runtime content hash does not match ` +
            `the trusted hash embedded at build time. ` +
            `This may indicate a monkey-patch attack on the in-memory pack registry.`);
        this.name = 'PackContentTamperedError';
        this.packId = packId;
        this._expectedHash = expectedHash;
        this._actualHash = actualHash;
    }
}
/**
 * Thrown by createGovernedAgent() when a caller attempts to inject a
 * third-party / custom pack object into the packs array instead of
 * referencing a registry pack by string ID.
 *
 * Security boundary: the @connexum/ai-governance runtime ONLY evaluates
 * packs from the BUILT_IN_PACKS registry. Customers cannot ship custom pack
 * code that would execute inside our runtime and emit audit-chain entries
 * claiming compliance with a standard the runtime did not actually enforce.
 *
 * To request a new pack, contact support or use the dashboard's
 * "Request a new compliance pack" feature (my-cc.io/dashboard/packs/request).
 *
 * Fix: replace custom pack objects with their official string IDs (e.g.
 * 'hipaa', 'soc2', 'gdpr'). See BUILT_IN_PACKS in src/governed-agent.ts for
 * the full list of accepted identifiers.
 *
 * F-NEW-THIRD-PARTY-PACK-REJECTION-2026-05-24 (Layer 1 of 3).
 */
export class ThirdPartyPackRejected extends Error {
    /**
     * The raw value that was rejected (serialized for diagnostics).
     * Could be a non-string type or an unrecognised string ID.
     */
    rejectedValue;
    /**
     * Zero-based index of the rejected entry in config.packs[].
     */
    packIndex;
    constructor(rejectedValue, packIndex) {
        const valueStr = typeof rejectedValue === 'string'
            ? `'${rejectedValue}'`
            : `[${typeof rejectedValue}] ${JSON.stringify(rejectedValue)?.slice(0, 120) ?? String(rejectedValue)}`;
        super(`Third-party pack rejected at packs[${packIndex}]: ${valueStr}. ` +
            `The @connexum/ai-governance runtime only evaluates packs from the ` +
            `BUILT_IN_PACKS registry. Supply a string ID (e.g. 'hipaa', 'soc2', 'gdpr') ` +
            `instead of a custom pack object. ` +
            `To request a new pack: my-cc.io/dashboard/packs/request`);
        this.name = 'ThirdPartyPackRejected';
        this.rejectedValue = rejectedValue;
        this.packIndex = packIndex;
    }
}
// ---------------------------------------------------------------------------
// Built-in pack registry (maps string IDs to pack objects)
// ---------------------------------------------------------------------------
export const BUILT_IN_PACKS = {
    soc1: SOC1_PACK,
    ssae18: SOC1_PACK,
    soc2: SOC2_PACK,
    'soc-2': SOC2_PACK,
    'soc2-type2': SOC2_PACK,
    hipaa: HIPAA_PACK,
    'hipaa-security': HIPAA_PACK,
    'hipaa-privacy': HIPAA_PACK,
    '45-cfr-164': HIPAA_PACK,
    hitech: HITECH_PACK,
    glba: GLBA_PACK,
    'gramm-leach-bliley': GLBA_PACK,
    aba: ABA_PACK,
    'aba-model-rules': ABA_PACK,
    'opinion-512': ABA_PACK,
    ftc5: FTC5_PACK,
    'ftc-5': FTC5_PACK,
    'ftc-act-5': FTC5_PACK,
    'ftc-section-5': FTC5_PACK,
    'sr11-7': SR117_PACK,
    sr117: SR117_PACK,
    'sr-11-7': SR117_PACK,
    'model-risk': SR117_PACK,
    part11: PART11_PACK,
    '21cfr11': PART11_PACK,
    '21-cfr-part-11': PART11_PACK,
    'fda-part-11': PART11_PACK,
    sox404: SOX404_PACK,
    sox: SOX404_PACK,
    'sox-404': SOX404_PACK,
    'sarbanes-oxley': SOX404_PACK,
    'bsa-aml': BSA_AML_PACK,
    bsa: BSA_AML_PACK,
    aml: BSA_AML_PACK,
    'bank-secrecy': BSA_AML_PACK,
    nydfs500: NYDFS500_PACK,
    'ny-dfs-500': NYDFS500_PACK,
    '23-nycrr-500': NYDFS500_PACK,
    nydfs: NYDFS500_PACK,
    'cfpb-2023-03': CFPB_2023_03_PACK,
    cfpb: CFPB_2023_03_PACK,
    'cfpb-circular-2023-03': CFPB_2023_03_PACK,
    'adverse-action-ai': CFPB_2023_03_PACK,
    bipa: BIPA_PACK,
    'illinois-bipa': BIPA_PACK,
    'biometric-info-privacy': BIPA_PACK,
    'fda-samd': FDA_SAMD_PACK,
    samd: FDA_SAMD_PACK,
    'fda-ai-ml': FDA_SAMD_PACK,
    'software-as-medical-device': FDA_SAMD_PACK,
    part2: PART2_PACK,
    '42-cfr-part-2': PART2_PACK,
    'sud-records': PART2_PACK,
    samhsa: PART2_PACK,
    gxp: GXP_PACK,
    gmp: GXP_PACK,
    glp: GXP_PACK,
    gcp: GXP_PACK,
    'nyc-ll-144': NYC_LL_144_PACK,
    'nyc-144': NYC_LL_144_PACK,
    aedt: NYC_LL_144_PACK,
    'nyc-bias-audit': NYC_LL_144_PACK,
    'eu-ai-liability': EU_AI_LIABILITY_PACK,
    'pld-2024': EU_AI_LIABILITY_PACK,
    'product-liability-eu': EU_AI_LIABILITY_PACK,
    'iso-23894': ISO_23894_PACK,
    'iso-iec-23894': ISO_23894_PACK,
    'ai-risk-guidance': ISO_23894_PACK,
    lgpd: LGPD_PACK,
    'brazil-privacy': LGPD_PACK,
    'lei-13709': LGPD_PACK,
    pipl: PIPL_PACK,
    'china-privacy': PIPL_PACK,
    'prc-pipl': PIPL_PACK,
    // X2 disaggregation (2026-04-24): legacy aliases map to ca-pipeda for backward compat
    'ca-pipeda': CA_PIPEDA_PACK,
    'ca-qc-law25': QC_LAW25_PACK,
    pipeda: CA_PIPEDA_PACK,
    'canada-privacy': CA_PIPEDA_PACK,
    'quebec-law-25': QC_LAW25_PACK,
    'pipeda-law25': CA_PIPEDA_PACK,
    gdpr: GDPR_PACK,
    'gdpr-eu': GDPR_PACK,
    'eu-gdpr': GDPR_PACK,
    '2016/679': GDPR_PACK,
    ccpa: CCPA_PACK,
    cpra: CCPA_PACK,
    'ccpa-cpra': CCPA_PACK,
    'colorado-ai': COLORADO_AI_PACK,
    coai: COLORADO_AI_PACK,
    'sb-24-205': COLORADO_AI_PACK,
    pcidss: PCIDSS_PACK,
    'pci-dss': PCIDSS_PACK,
    'pci-dss-4': PCIDSS_PACK,
    'pci-dss-v4': PCIDSS_PACK,
    dora: DORA_PACK,
    'dora-eu': DORA_PACK,
    'regulation-2022-2554': DORA_PACK,
    'digital-operational-resilience': DORA_PACK,
    euaiact: EUAIACT_PACK,
    'eu-ai-act': EUAIACT_PACK,
    'regulation-2024-1689': EUAIACT_PACK,
    'ai-act': EUAIACT_PACK,
    iso27001: ISO27001_PACK,
    'iso-27001': ISO27001_PACK,
    'iso-iec-27001': ISO27001_PACK,
    'iso27001-2022': ISO27001_PACK,
    nist_ai_rmf: NIST_AI_RMF_PACK,
    nistairmf: NIST_AI_RMF_PACK,
    'nist-ai-rmf': NIST_AI_RMF_PACK,
    'nist-ai-100-1': NIST_AI_RMF_PACK,
    iso_42001: ISO_42001_PACK,
    iso42001: ISO_42001_PACK,
    'iso-42001': ISO_42001_PACK,
    'iso-iec-42001': ISO_42001_PACK,
    'iso-42001-2023': ISO_42001_PACK,
    aims: ISO_42001_PACK,
    mifid2: MIFID2_PACK,
    mifid: MIFID2_PACK,
    'mifid-ii': MIFID2_PACK,
    'markets-in-financial-instruments': MIFID2_PACK,
    'naic-mdl': NAIC_MDL_PACK,
    'naic-mdl-668': NAIC_MDL_PACK,
    'insurance-data-security': NAIC_MDL_PACK,
    naic: NAIC_MDL_PACK,
    frcp26: FRCP26_PACK,
    'frcp-26': FRCP26_PACK,
    'federal-rules-civil-procedure-26': FRCP26_PACK,
    ediscovery: FRCP26_PACK,
    foia: FOIA_PACK,
    '5-usc-552': FOIA_PACK,
    'freedom-of-information': FOIA_PACK,
    lpo2024: LPO2024_PACK,
    'lpo-2024': LPO2024_PACK,
    'legal-practitioner-ai-disclosure': LPO2024_PACK,
    // F-PACK-CLEANUP-1 (2026-05-08): appi.ts deleted as duplicate of jp-appi.ts;
    // these aliases now resolve to the canonical JP_APPI_PACK.
    appi: JP_APPI_PACK,
    'appi-japan': JP_APPI_PACK,
    'japan-privacy': JP_APPI_PACK,
    ferpa: FERPA_PACK,
    'family-educational-rights-privacy': FERPA_PACK,
    'student-privacy': FERPA_PACK,
    fedramp: FEDRAMP_PACK,
    'fed-ramp': FEDRAMP_PACK,
    'fedramp-moderate': FEDRAMP_PACK,
    stateramp: STATERAMP_PACK,
    'state-ramp': STATERAMP_PACK,
    cjis: CJIS_PACK,
    'cjis-security-policy': CJIS_PACK,
    'fbi-cjis': CJIS_PACK,
    // PR-2: ECPA (Electronic Communications Privacy Act)
    ecpa: ECPA_PACK,
    'title-iii': ECPA_PACK,
    'wiretap-act': ECPA_PACK,
    sca: ECPA_PACK,
    'stored-communications-act': ECPA_PACK,
    'ecpa-title-iii': ECPA_PACK,
    // F-NEW-ALL-PACKS-RUNTIME-2026-05-24: Healthcare-US runtime classifier packs (Kai 2026-05-24)
    'cms-cop': CMS_COP_PACK,
    'cms-conditions-of-participation': CMS_COP_PACK,
    'conditions-of-participation': CMS_COP_PACK,
    '340b-dscsa': B340_DSCSA_PACK,
    '340b': B340_DSCSA_PACK,
    'dscsa': B340_DSCSA_PACK,
    '340b-drug-pricing': B340_DSCSA_PACK,
    'no-surprises-act': NO_SURPRISES_ACT_PACK,
    'no-surprises': NO_SURPRISES_ACT_PACK,
    'nsa-2020': NO_SURPRISES_ACT_PACK,
    'balance-billing': NO_SURPRISES_ACT_PACK,
    'medicare-medicaid-billing': MEDICARE_MEDICAID_BILLING_PACK,
    'mmb': MEDICARE_MEDICAID_BILLING_PACK,
    'cms-billing': MEDICARE_MEDICAID_BILLING_PACK,
    'stark-aks': STARK_AKS_PACK,
    'stark-law': STARK_AKS_PACK,
    'anti-kickback': STARK_AKS_PACK,
    'aks': STARK_AKS_PACK,
    'ai-clinical-decision-support': AI_CDS_PACK,
    'ai-cds': AI_CDS_PACK,
    'clinical-decision-support': AI_CDS_PACK,
    'ai-clinical-decision': AI_CDS_PACK,
    cmmc2: CMMC2_PACK,
    cmmc: CMMC2_PACK,
    'cmmc-2': CMMC2_PACK,
    'cmmc-level-2': CMMC2_PACK,
    'nist-800-171': CMMC2_PACK,
    // Mortgage-industry packs (MORTGAGE-PACKS-01, 2026-04-22)
    // X3 2026-04-24: respa renamed to us-respa; tila-trid split into us-trid + us-tila
    'us-respa': US_RESPA_PACK,
    respa: US_RESPA_PACK, // backward-compat alias
    'regulation-x': US_RESPA_PACK,
    '12-usc-2601': US_RESPA_PACK,
    '12-cfr-1024': US_RESPA_PACK,
    hmda: HMDA_PACK,
    'regulation-c': HMDA_PACK,
    '12-usc-2801': HMDA_PACK,
    '12-cfr-1003': HMDA_PACK,
    'us-trid': US_TRID_PACK,
    trid: US_TRID_PACK, // backward-compat alias
    'tila-trid': US_TRID_PACK, // backward-compat alias -- routes to TRID pack
    'us-tila': US_TILA_PACK,
    tila: US_TILA_PACK, // backward-compat alias
    'regulation-z': US_TILA_PACK,
    '12-cfr-1026': US_TILA_PACK,
    '15-usc-1601': US_TILA_PACK,
    ecoa: ECOA_PACK,
    'regulation-b': ECOA_PACK,
    '15-usc-1691': ECOA_PACK,
    '12-cfr-1002': ECOA_PACK,
    'equal-credit-opportunity': ECOA_PACK,
    fcra: FCRA_PACK,
    'fair-credit-reporting': FCRA_PACK,
    '15-usc-1681': FCRA_PACK,
    'consumer-report': FCRA_PACK,
    // -------------------------------------------------------------------------
    // BATCH-01: 48 previously-unreachable packs (P0 registry fix, 2026-04-25)
    // -------------------------------------------------------------------------
    // AU state health privacy (X1-disaggregation, 2026-04-24)
    'au-act-hrpaa': AU_ACT_HRPAA_PACK,
    'act-hrpaa': AU_ACT_HRPAA_PACK,
    'au-health-act-hrpaa': AU_ACT_HRPAA_PACK,
    // AU AI Ethics Framework + Voluntary AI Safety Standard
    'au-aiethics-framework': AU_AIETHICS_PACK,
    'au-ai-ethics': AU_AIETHICS_PACK,
    'au-voluntary-ai-safety': AU_AIETHICS_PACK,
    'disr-ai-ethics': AU_AIETHICS_PACK,
    // AU AML/CTF
    'au-aml-ctf': AU_AML_CTF_PACK,
    'au-aml': AU_AML_CTF_PACK,
    'austrac-aml': AU_AML_CTF_PACK,
    // AU ASIC RG 271
    'au-asic-rg-271': AU_ASIC_RG271_PACK,
    'au-asic-rg271': AU_ASIC_RG271_PACK,
    'asic-rg-271': AU_ASIC_RG271_PACK,
    // AU ASIC RG 274
    'au-asic-rg-274': AU_ASIC_RG274_PACK,
    'au-asic-rg274': AU_ASIC_RG274_PACK,
    'asic-rg-274': AU_ASIC_RG274_PACK,
    // AU CDR (Consumer Data Right)
    'au-cdr': AU_CDR_PACK,
    'au-consumer-data-right': AU_CDR_PACK,
    'cdr-au': AU_CDR_PACK,
    // AU CPS 230
    'au-cps230': AU_CPS230_PACK,
    'apra-cps-230': AU_CPS230_PACK,
    'cps-230': AU_CPS230_PACK,
    // AU CPS 234
    'au-cps234': AU_CPS234_PACK,
    'apra-cps-234': AU_CPS234_PACK,
    'cps-234': AU_CPS234_PACK,
    // AU Mandatory AI Guardrails
    'au-mandatory-ai-guardrails': AU_MANDATORY_AI_GUARDRAILS_PACK,
    'au-mandatory-guardrails': AU_MANDATORY_AI_GUARDRAILS_PACK,
    'disr-mandatory-ai-guardrails': AU_MANDATORY_AI_GUARDRAILS_PACK,
    // AU NSW Health Records (HRIPA)
    'au-nsw-hripa': AU_NSW_HRIPA_PACK,
    'nsw-hripa': AU_NSW_HRIPA_PACK,
    'au-nsw-health-records': AU_NSW_HRIPA_PACK,
    // AU Online Safety Act
    'au-online-safety': AU_ONLINE_SAFETY_PACK,
    'au-online-safety-act': AU_ONLINE_SAFETY_PACK,
    'osa-au': AU_ONLINE_SAFETY_PACK,
    // AU Privacy Act 1988
    'au-privacy-act': AU_PRIVACY_ACT_PACK,
    'au-privacy-act-1988': AU_PRIVACY_ACT_PACK,
    'oaic-privacy': AU_PRIVACY_ACT_PACK,
    // AU SOCI Act
    'au-soci-act': AU_SOCI_PACK,
    'au-soci': AU_SOCI_PACK,
    'soci-act-au': AU_SOCI_PACK,
    // AU Spam Act 2003
    'au-spam-act': AU_SPAM_ACT_PACK,
    'au-spam-act-2003': AU_SPAM_ACT_PACK,
    'spam-act-au': AU_SPAM_ACT_PACK,
    // AU TGA SaMD
    'au-tga-saimd': AU_TGA_SAIMD_PACK,
    'au-tga-samd': AU_TGA_SAIMD_PACK,
    'tga-saimd': AU_TGA_SAIMD_PACK,
    // AU VIC Health Records Act
    'au-vic-hra': AU_VIC_HRA_PACK,
    'vic-hra': AU_VIC_HRA_PACK,
    'au-vic-health-records': AU_VIC_HRA_PACK,
    // California AB 2930 (employment AI)
    'california-ab2930': CALIFORNIA_AB2930_PACK,
    'ca-ab-2930': CALIFORNIA_AB2930_PACK,
    'ab-2930': CALIFORNIA_AB2930_PACK,
    'california-employment-ai': CALIFORNIA_AB2930_PACK,
    // CMS Interoperability
    'cms-interoperability': CMS_INTEROPERABILITY_PACK,
    'cms-interop': CMS_INTEROPERABILITY_PACK,
    '45-cfr-170': CMS_INTEROPERABILITY_PACK,
    // Common Rule (45 CFR Part 46)
    'common-rule': COMMON_RULE_PACK,
    '45-cfr-46': COMMON_RULE_PACK,
    'belmont-report': COMMON_RULE_PACK,
    'human-subjects-research': COMMON_RULE_PACK,
    // COPPA
    'coppa': COPPA_PACK,
    'childrens-online-privacy': COPPA_PACK,
    '16-cfr-312': COPPA_PACK,
    // DE BDSG (German Federal Data Protection Act)
    'de-bdsg': DE_BDSG_PACK,
    'bdsg': DE_BDSG_PACK,
    'german-data-protection': DE_BDSG_PACK,
    // EU Legal Professional Privilege
    'eu-lpp': EU_LPP_PACK,
    'eu-legal-privilege': EU_LPP_PACK,
    'legal-professional-privilege': EU_LPP_PACK,
    // EU MDR/IVDR (Medical Device Regulation)
    'eu-mdr-ivdr': EU_MDR_IVDR_PACK,
    'eu-mdr': EU_MDR_IVDR_PACK,
    'eu-ivdr': EU_MDR_IVDR_PACK,
    'regulation-2017-745': EU_MDR_IVDR_PACK,
    // FCA Consumer Duty
    'fca-consumer-duty': FCA_CONSUMER_DUTY_PACK,
    'uk-fca-consumer-duty': FCA_CONSUMER_DUTY_PACK,
    'ps22-9': FCA_CONSUMER_DUTY_PACK,
    // FCA Operational Resilience
    'fca-op-resilience': FCA_OP_RESILIENCE_PACK,
    'fca-operational-resilience': FCA_OP_RESILIENCE_PACK,
    'ps21-3': FCA_OP_RESILIENCE_PACK,
    // FINRA 3110 (Supervision)
    'finra-3110': FINRA_3110_PACK,
    'finra': FINRA_3110_PACK,
    'finra-supervision': FINRA_3110_PACK,
    'wsp': FINRA_3110_PACK,
    // Florida Student Privacy
    'florida-student-privacy': FLORIDA_STUDENT_PRIVACY_PACK,
    'fl-student-privacy': FLORIDA_STUDENT_PRIVACY_PACK,
    'florida-cspa': FLORIDA_STUDENT_PRIVACY_PACK,
    // Illinois AIVIA (video interview AI)
    'illinois-aivia': ILLINOIS_AIVIA_PACK,
    'aivia': ILLINOIS_AIVIA_PACK,
    'il-aivia': ILLINOIS_AIVIA_PACK,
    'illinois-ai-video-interview': ILLINOIS_AIVIA_PACK,
    // India DPDP Act
    'in-dpdp': IN_DPDP_PACK,
    'india-dpdp': IN_DPDP_PACK,
    'dpdp': IN_DPDP_PACK,
    'india-data-protection': IN_DPDP_PACK,
    // ISO 20022 (financial messaging)
    'iso20022': ISO20022_PACK,
    'iso-20022': ISO20022_PACK,
    'iso-iec-20022': ISO20022_PACK,
    // ISO 27701 (privacy extension to 27001)
    'iso27701': ISO27701_PACK,
    'iso-27701': ISO27701_PACK,
    'iso-iec-27701': ISO27701_PACK,
    'pims': ISO27701_PACK,
    // JP APPI
    'jp-appi': JP_APPI_PACK,
    'japan-appi': JP_APPI_PACK,
    'appi-2022': JP_APPI_PACK,
    // KR PIPA
    'kr-pipa': KR_PIPA_PACK,
    'korea-pipa': KR_PIPA_PACK,
    'pipa-kr': KR_PIPA_PACK,
    // Maryland HB 1202 (employment AI)
    'maryland-hb1202': MARYLAND_HB1202_PACK,
    'md-hb-1202': MARYLAND_HB1202_PACK,
    'maryland-ai-employment': MARYLAND_HB1202_PACK,
    // EU NIS 2
    'nis2': NIS2_PACK,
    'eu-nis2': NIS2_PACK,
    'nis-2': NIS2_PACK,
    'network-information-security-2': NIS2_PACK,
    // NZ Privacy Act 2020
    'nz-privacy': NZ_PRIVACY_PACK,
    'nz-privacy-act-2020': NZ_PRIVACY_PACK,
    'privacy-act-nz': NZ_PRIVACY_PACK,
    // Regulation E (electronic fund transfers)
    'reg-e': REG_E_PACK,
    'regulation-e': REG_E_PACK,
    '12-cfr-1005': REG_E_PACK,
    'efta': REG_E_PACK,
    // SG Model AI Governance Framework
    'sg-model-ai-gov': SG_MODEL_AI_GOV_PACK,
    'singapore-ai-governance': SG_MODEL_AI_GOV_PACK,
    'sg-pdpc-ai': SG_MODEL_AI_GOV_PACK,
    // Tennessee ELVIS Act (AI + likeness)
    'tennessee-elvis': TENNESSEE_ELVIS_PACK,
    'elvis-act': TENNESSEE_ELVIS_PACK,
    'tn-elvis': TENNESSEE_ELVIS_PACK,
    'tennessee-ai-likeness': TENNESSEE_ELVIS_PACK,
    // Texas HB 4 (consumer AI data)
    'texas-hb4': TEXAS_HB4_PACK,
    'tx-hb-4': TEXAS_HB4_PACK,
    'texas-consumer-ai': TEXAS_HB4_PACK,
    // Title IX (sex discrimination)
    'title-ix': TITLE_IX_PACK,
    'title-9': TITLE_IX_PACK,
    '34-cfr-106': TITLE_IX_PACK,
    'title-ix-education': TITLE_IX_PACK,
    // UK AI Framework
    'uk-ai-framework': UK_AI_FRAMEWORK_PACK,
    'uk-ai-strategy': UK_AI_FRAMEWORK_PACK,
    'dsit-ai-framework': UK_AI_FRAMEWORK_PACK,
    // UK GDPR
    'uk-gdpr': UK_GDPR_PACK,
    'uk-data-protection-act': UK_GDPR_PACK,
    'dpa-2018': UK_GDPR_PACK,
    // NHS DSPT (Wave 1 Pack 5 — F-NEW-TIER-10-UK-WAVE1-ROADMAP)
    'nhs-dspt': NHS_DSPT_PACK,
    'nhs-data-security-protection-toolkit': NHS_DSPT_PACK,
    'dspt': NHS_DSPT_PACK,
    // Cyber Essentials / CE+ (Wave 1 Pack 6 — F-NEW-TIER-10-UK-WAVE1-ROADMAP)
    'cyber-essentials': CYBER_ESSENTIALS_PACK,
    'cyber-essentials-plus': CYBER_ESSENTIALS_PACK,
    'ce': CYBER_ESSENTIALS_PACK,
    'ce-plus': CYBER_ESSENTIALS_PACK,
    'ncsc-ce': CYBER_ESSENTIALS_PACK,
    // NHS Clinical Safety DCB0129 + DCB0160 (Wave 1 Pack 7 — F-NEW-TIER-10-UK-WAVE1-ROADMAP)
    'nhs-clinical-safety': NHS_CLINICAL_SAFETY_PACK,
    'dcb0129': NHS_CLINICAL_SAFETY_PACK,
    'dcb0160': NHS_CLINICAL_SAFETY_PACK,
    'dcb-0129': NHS_CLINICAL_SAFETY_PACK,
    'dcb-0160': NHS_CLINICAL_SAFETY_PACK,
    'nhs-dcb0129-dcb0160': NHS_CLINICAL_SAFETY_PACK,
    'clinical-safety-case': NHS_CLINICAL_SAFETY_PACK,
    'cscr': NHS_CLINICAL_SAFETY_PACK,
    'nhs-clinical-risk-management': NHS_CLINICAL_SAFETY_PACK,
    // MHRA SaMD / UKCA (Wave 1 Pack 4 — F-NEW-TIER-10-UK-WAVE1-ROADMAP)
    'mhra-samd-ukca': MHRA_SAMD_UKCA_PACK,
    'mhra-samd': MHRA_SAMD_UKCA_PACK,
    'uk-samd': MHRA_SAMD_UKCA_PACK,
    'ukca-medical-device': MHRA_SAMD_UKCA_PACK,
    'mhra-ai-as-medical-device': MHRA_SAMD_UKCA_PACK,
    'mhra-aimd': MHRA_SAMD_UKCA_PACK,
    'uk-mdr-2002': MHRA_SAMD_UKCA_PACK,
    // NHS Innovation Service / DTAC composite (Wave 1 Pack 2 — F-NEW-TIER-10-UK-WAVE1-ROADMAP)
    'nhs-dtac': NHS_DTAC_PACK,
    'dtac': NHS_DTAC_PACK,
    'nhs-innovation-service': NHS_DTAC_PACK,
    'nhs-innovation-service-dtac': NHS_DTAC_PACK,
    'digital-technology-assessment-criteria': NHS_DTAC_PACK,
    // Caldicott Principles 2020 (Wave 2 — DTAC composite drops transitional flag when this pack is registered)
    'caldicott-principles': CALDICOTT_PRINCIPLES_PACK,
    'caldicott': CALDICOTT_PRINCIPLES_PACK,
    'caldicott-principles-2020': CALDICOTT_PRINCIPLES_PACK,
    'caldicott-guardian': CALDICOTT_PRINCIPLES_PACK,
    'ndg-caldicott': CALDICOTT_PRINCIPLES_PACK,
    'uk-caldicott': CALDICOTT_PRINCIPLES_PACK,
    // NCSC Cyber Assessment Framework (CAF) — UK 16-pack item #8
    'ncsc-caf': NCSC_CAF_PACK,
    'caf': NCSC_CAF_PACK,
    'ncsc-cyber-assessment-framework': NCSC_CAF_PACK,
    'cyber-assessment-framework': NCSC_CAF_PACK,
    'govassure': NCSC_CAF_PACK,
    'caf-v3': NCSC_CAF_PACK,
    // NCSC Guidelines for Secure AI System Development (2024) — TIER 10-UK Wave 2
    'ncsc-ai-security': NCSC_AI_SECURITY_PACK,
    'ncsc-ai-security-guidelines': NCSC_AI_SECURITY_PACK,
    'ncsc-secure-ai': NCSC_AI_SECURITY_PACK,
    'ncsc-ai-guidelines-2024': NCSC_AI_SECURITY_PACK,
    'secure-ai-system-development': NCSC_AI_SECURITY_PACK,
    'cisa-ncsc-ai-security': NCSC_AI_SECURITY_PACK,
    'joint-guidelines-ai-security': NCSC_AI_SECURITY_PACK,
    // UK Equality Act 2010 — UK 16-pack item #11
    'uk-equality-act': UK_EQUALITY_ACT_PACK,
    'equality-act': UK_EQUALITY_ACT_PACK,
    'equality-act-2010': UK_EQUALITY_ACT_PACK,
    'uk-equality-act-2010': UK_EQUALITY_ACT_PACK,
    'ehrc': UK_EQUALITY_ACT_PACK,
    'psed': UK_EQUALITY_ACT_PACK,
    'public-sector-equality-duty': UK_EQUALITY_ACT_PACK,
    // UK Equality Act 2010 + ICO-EHRC Joint AI Bias Guidance — Section D.2 TIER 10-UK Wave 2
    'uk-equality-act-ai-bias': UK_EQUALITY_ACT_AI_BIAS_PACK,
    'equality-act-ai-bias': UK_EQUALITY_ACT_AI_BIAS_PACK,
    'ico-ehrc-ai-bias': UK_EQUALITY_ACT_AI_BIAS_PACK,
    'ehrc-ai-guidance': UK_EQUALITY_ACT_AI_BIAS_PACK,
    'uk-ai-equality': UK_EQUALITY_ACT_AI_BIAS_PACK,
    // UK NIS Regulations 2018 — UK 16-pack item #12
    'uk-nis-regs': UK_NIS_REGS_PACK,
    'uk-nis': UK_NIS_REGS_PACK,
    'uk-nis-regulations': UK_NIS_REGS_PACK,
    'uk-nis-regulations-2018': UK_NIS_REGS_PACK,
    'nis-uk': UK_NIS_REGS_PACK,
    'si-2018-506': UK_NIS_REGS_PACK,
    // UK Computer Misuse Act 1990 — UK 16-pack item #17 (Tier 10-UK)
    'uk-cma-1990': UK_CMA_1990_PACK,
    'uk-cma': UK_CMA_1990_PACK,
    'cma-1990': UK_CMA_1990_PACK,
    'computer-misuse-act': UK_CMA_1990_PACK,
    'computer-misuse-act-1990': UK_CMA_1990_PACK,
    'uk-computer-misuse-act': UK_CMA_1990_PACK,
    'uk-c18-1990': UK_CMA_1990_PACK,
    // UK Future AI Legislation Horizon-Scan — UK 16-pack item #16 (last)
    'uk-future-ai-legislation': UK_FUTURE_AI_LEGISLATION_PACK,
    'uk-ai-horizon': UK_FUTURE_AI_LEGISLATION_PACK,
    'uk-future-ai': UK_FUTURE_AI_LEGISLATION_PACK,
    'uk-ai-bill': UK_FUTURE_AI_LEGISLATION_PACK,
    'dsit-ai-bill': UK_FUTURE_AI_LEGISLATION_PACK,
    // UK Online Safety Act 2023 — UK 16-pack item #13
    'uk-online-safety-act': UK_ONLINE_SAFETY_PACK,
    'online-safety-act': UK_ONLINE_SAFETY_PACK,
    'online-safety-act-2023': UK_ONLINE_SAFETY_PACK,
    'osa': UK_ONLINE_SAFETY_PACK,
    'ofcom-osa': UK_ONLINE_SAFETY_PACK,
    'uk-osa': UK_ONLINE_SAFETY_PACK,
    // UK Procurement Act 2023 — UK 16-pack item #14
    'uk-procurement-act': UK_PROCUREMENT_PACK,
    'procurement-act': UK_PROCUREMENT_PACK,
    'procurement-act-2023': UK_PROCUREMENT_PACK,
    'uk-procurement-act-2023': UK_PROCUREMENT_PACK,
    'pa-2023': UK_PROCUREMENT_PACK,
    'procurement-review-unit': UK_PROCUREMENT_PACK,
    'pru': UK_PROCUREMENT_PACK,
    // CMA AI Foundation Models + DMCC Act 2024 — UK 16-pack item #15
    'cma-ai-foundation-models': CMA_AI_FM_PACK,
    'cma-ai-fm': CMA_AI_FM_PACK,
    'cma-ai': CMA_AI_FM_PACK,
    'cma-foundation-models': CMA_AI_FM_PACK,
    'uk-cma-ai': CMA_AI_FM_PACK,
    'dmcc-act': CMA_AI_FM_PACK,
    'digital-markets-competition-consumers-act': CMA_AI_FM_PACK,
    'sms-designation': CMA_AI_FM_PACK,
    'dmu': CMA_AI_FM_PACK,
    // NHS PSIRF (Patient Safety Incident Response Framework) — UK 16-pack item #2 (NHS slot)
    'nhs-psirf': NHS_PSIRF_PACK,
    'psirf': NHS_PSIRF_PACK,
    'psirp': NHS_PSIRF_PACK,
    'psirs': NHS_PSIRF_PACK,
    'nhs-patient-safety-incident-response-framework': NHS_PSIRF_PACK,
    'patient-safety-incident-response-framework': NHS_PSIRF_PACK,
    'nhs-incident-response': NHS_PSIRF_PACK,
    // UK ICO Open Case (legal-hold posture) — UK 16-pack item #1
    'uk-ico-open-case': UK_ICO_OPEN_CASE_PACK,
    'uk-ico': UK_ICO_OPEN_CASE_PACK,
    'ico-open-case': UK_ICO_OPEN_CASE_PACK,
    'ico-investigation': UK_ICO_OPEN_CASE_PACK,
    'ico-legal-hold': UK_ICO_OPEN_CASE_PACK,
    'ico-enforcement': UK_ICO_OPEN_CASE_PACK,
    // NICE ESF for Digital Health Technologies — UK 16-pack item #3 (TGA slot, UK has no TGA equivalent)
    'nice-esf-dht': NICE_ESF_DHT_PACK,
    'nice-esf': NICE_ESF_DHT_PACK,
    'nice-evidence-standards-framework': NICE_ESF_DHT_PACK,
    'nice-dht': NICE_ESF_DHT_PACK,
    'esf-dht': NICE_ESF_DHT_PACK,
    'nice-digital-health': NICE_ESF_DHT_PACK,
    'uk-hta-dht': NICE_ESF_DHT_PACK,
    // Northern Ireland Equality (s.75 NI Act 1998 + Equality NI Orders + FETO) — devolved-substantive #1
    'ni-equality': NI_EQUALITY_PACK,
    'ni-equality-act': NI_EQUALITY_PACK,
    'northern-ireland-equality': NI_EQUALITY_PACK,
    'section-75': NI_EQUALITY_PACK,
    's75-ni': NI_EQUALITY_PACK,
    'ni-s75': NI_EQUALITY_PACK,
    'feto': NI_EQUALITY_PACK,
    'fair-employment-treatment-ni': NI_EQUALITY_PACK,
    'ecni': NI_EQUALITY_PACK,
    // Adults with Incapacity (Scotland) Act 2000 — devolved-substantive #2
    'scotland-awi': SCOTLAND_AWI_PACK,
    'scotland-awi-act': SCOTLAND_AWI_PACK,
    'awi-scotland': SCOTLAND_AWI_PACK,
    'adults-with-incapacity-scotland': SCOTLAND_AWI_PACK,
    'awi-2000': SCOTLAND_AWI_PACK,
    // Wellbeing of Future Generations (Wales) Act 2015 — devolved-substantive #3
    'wales-future-generations': WALES_WBFG_PACK,
    'wales-wbfg': WALES_WBFG_PACK,
    'wbfg': WALES_WBFG_PACK,
    'wbfg-wales': WALES_WBFG_PACK,
    'wellbeing-of-future-generations-wales': WALES_WBFG_PACK,
    'future-generations-wales': WALES_WBFG_PACK,
    // Scotland Specific Duties (PSED Scotland — SSI 2012/162) — devolved-substantive #4
    'scotland-psed': SCOTLAND_PSED_PACK,
    'scotland-specific-duties': SCOTLAND_PSED_PACK,
    'psed-scotland': SCOTLAND_PSED_PACK,
    'ssi-2012-162': SCOTLAND_PSED_PACK,
    'scottish-equality-specific-duties': SCOTLAND_PSED_PACK,
    // Health and Social Care Northern Ireland (HSCNI) — devolved-substantive #5
    'ni-hscni': NI_HSCNI_PACK,
    'hscni': NI_HSCNI_PACK,
    'hsc-ni': NI_HSCNI_PACK,
    'health-and-social-care-northern-ireland': NI_HSCNI_PACK,
    'doh-ni': NI_HSCNI_PACK,
    'rqia': NI_HSCNI_PACK,
    // EU Digital Services Act — direct EU mirror of UK Online Safety Act
    'eu-dsa': EU_DSA_PACK,
    'dsa': EU_DSA_PACK,
    'digital-services-act': EU_DSA_PACK,
    'regulation-2022-2065': EU_DSA_PACK,
    'eu-digital-services-act': EU_DSA_PACK,
    // EU Digital Markets Act
    'eu-dma': EU_DMA_PACK,
    'dma': EU_DMA_PACK,
    'digital-markets-act': EU_DMA_PACK,
    'regulation-2022-1925': EU_DMA_PACK,
    'eu-digital-markets-act': EU_DMA_PACK,
    // NIST CSF 2.0
    'nist-csf': NIST_CSF_PACK,
    'nist-csf-2': NIST_CSF_PACK,
    'nist-csf-2.0': NIST_CSF_PACK,
    'nist-cybersecurity-framework': NIST_CSF_PACK,
    'csf': NIST_CSF_PACK,
    // NIST SP 800-53 Rev. 5
    'nist-800-53': NIST_800_53_PACK,
    'nist-sp-800-53': NIST_800_53_PACK,
    'sp-800-53': NIST_800_53_PACK,
    '800-53': NIST_800_53_PACK,
    'nist-800-53-rev5': NIST_800_53_PACK,
    // HITRUST CSF
    'hitrust-csf': HITRUST_CSF_PACK,
    'hitrust': HITRUST_CSF_PACK,
    'hitrust-common-security-framework': HITRUST_CSF_PACK,
    'hitrust-e1': HITRUST_CSF_PACK,
    'hitrust-i1': HITRUST_CSF_PACK,
    'hitrust-r2': HITRUST_CSF_PACK,
    // EU Data Act
    'eu-data-act': EU_DATA_ACT_PACK,
    'data-act': EU_DATA_ACT_PACK,
    'eu-data-act-2023': EU_DATA_ACT_PACK,
    'regulation-2023-2854': EU_DATA_ACT_PACK,
    // EU Cyber Resilience Act
    'eu-cra': EU_CRA_PACK,
    'cra': EU_CRA_PACK,
    'cyber-resilience-act': EU_CRA_PACK,
    'eu-cyber-resilience-act': EU_CRA_PACK,
    'regulation-2024-2847': EU_CRA_PACK,
    // Procurement Reform (Scotland) Act 2014
    'scotland-procurement-reform': SCOTLAND_PROCUREMENT_PACK,
    'scotland-procurement': SCOTLAND_PROCUREMENT_PACK,
    'procurement-reform-scotland': SCOTLAND_PROCUREMENT_PACK,
    'procurement-reform-scotland-act-2014': SCOTLAND_PROCUREMENT_PACK,
    'asp-2014-12': SCOTLAND_PROCUREMENT_PACK,
    // Mental Capacity (NI) Act 2016
    'ni-mental-capacity': NI_MCA_PACK,
    'ni-mca': NI_MCA_PACK,
    'ni-mca-2016': NI_MCA_PACK,
    'mental-capacity-ni-2016': NI_MCA_PACK,
    'mental-capacity-northern-ireland-act': NI_MCA_PACK,
    // Hong Kong PDPO
    'hk-pdpo': HK_PDPO_PACK,
    'hong-kong-pdpo': HK_PDPO_PACK,
    'pdpo-hk': HK_PDPO_PACK,
    'cap-486': HK_PDPO_PACK,
    'personal-data-privacy-ordinance': HK_PDPO_PACK,
    // Vietnam PDPD
    'vn-pdpd': VN_PDPD_PACK,
    'vietnam-pdpd': VN_PDPD_PACK,
    'vietnam-personal-data-protection': VN_PDPD_PACK,
    'decree-13-2023': VN_PDPD_PACK,
    'pdpd-vietnam': VN_PDPD_PACK,
    // Thailand PDPA
    'th-pdpa': TH_PDPA_PACK,
    'thailand-pdpa': TH_PDPA_PACK,
    'pdpa-thailand': TH_PDPA_PACK,
    'thailand-personal-data-protection-act': TH_PDPA_PACK,
    // China DSL + CSL
    'cn-dsl-csl': CN_DSL_CSL_PACK,
    'china-dsl': CN_DSL_CSL_PACK,
    'china-csl': CN_DSL_CSL_PACK,
    'china-dsl-csl': CN_DSL_CSL_PACK,
    'data-security-law-china': CN_DSL_CSL_PACK,
    'cybersecurity-law-china': CN_DSL_CSL_PACK,
    'mlps-china': CN_DSL_CSL_PACK,
    // NIH Certificate of Confidentiality
    'us-nih-coc': NIH_COC_PACK,
    'nih-coc': NIH_COC_PACK,
    'nih-certificate-of-confidentiality': NIH_COC_PACK,
    // NIH Data Management and Sharing
    'us-nih-dms': NIH_DMS_PACK,
    'nih-dms': NIH_DMS_PACK,
    'nih-data-management': NIH_DMS_PACK,
    // NIH Genomic Data Sharing
    'us-nih-gds': NIH_GDS_PACK,
    'nih-gds': NIH_GDS_PACK,
    'nih-genomic-data-sharing': NIH_GDS_PACK,
    // NIH IT Security
    'us-nih-it-security': NIH_IT_SECURITY_PACK,
    'nih-it-security': NIH_IT_SECURITY_PACK,
    'nih-fisma': NIH_IT_SECURITY_PACK,
    // Utah AI Policy Act
    'utah-ai-policy': UTAH_AI_POLICY_PACK,
    'ut-ai-policy': UTAH_AI_POLICY_PACK,
    'utah-ai': UTAH_AI_POLICY_PACK,
    // RTCA DO-178C / EUROCAE ED-12C — Software Considerations in Airborne Systems
    'do-178c': DO_178C_PACK,
    'do178c': DO_178C_PACK,
    'rtca-do-178c': DO_178C_PACK,
    'ed-12c': DO_178C_PACK,
    'avionics-software': DO_178C_PACK,
    // FDA 21 CFR Part 820 — Quality System Regulation (QSR / QMSR)
    'fda-21-cfr-820': FDA_21_CFR_820_PACK,
    'fda-820': FDA_21_CFR_820_PACK,
    'fda-qsr': FDA_21_CFR_820_PACK,
    'fda-qmsr': FDA_21_CFR_820_PACK,
    '21-cfr-820': FDA_21_CFR_820_PACK,
    // IEC 62304 — Medical Device Software Life Cycle Processes
    'iec-62304': IEC_62304_PACK,
    'iec62304': IEC_62304_PACK,
    'medical-device-software': IEC_62304_PACK,
    // FDA 21 CFR Part 56 (IRB Regulations)
    'us-fda-21cfr56': US_FDA_21CFR56_PACK,
    'fda-21cfr56': US_FDA_21CFR56_PACK,
    '21-cfr-56': US_FDA_21CFR56_PACK,
    'fda-irb': US_FDA_21CFR56_PACK,
    // ISO 26262 — Automotive Functional Safety
    'iso-26262': ISO_26262_PACK,
    'iso26262': ISO_26262_PACK,
    'automotive-functional-safety': ISO_26262_PACK,
    // IEC 62443 — Industrial Automation and Control Systems Security
    'iec-62443': IEC_62443_PACK,
    'iec62443': IEC_62443_PACK,
    'industrial-control-systems-security': IEC_62443_PACK,
    // NIST SP 800-82 — US Federal Operational Technology Security
    'nist-sp-800-82': NIST_SP_800_82_PACK,
    'nist80082': NIST_SP_800_82_PACK,
    'us-ot-security': NIST_SP_800_82_PACK,
    // AS9100D / AS9110C / AS9120B — Aerospace Quality Management Systems
    'as-9100': AS_9100_PACK,
    'as9100': AS_9100_PACK,
    'aerospace-qms': AS_9100_PACK,
    'as9110': AS_9100_PACK,
    'as9120': AS_9100_PACK,
    // FDA Software Pre-Cert + SaMD TPLC + AI/ML Action Plan
    'fda-samd-precert': FDA_SAMD_PRECERT_PACK,
    'fdaSamdPrecert': FDA_SAMD_PRECERT_PACK,
    // ISO 15189:2022 Medical Laboratory Quality and Competence
    'iso-15189': ISO_15189_PACK,
    'iso15189': ISO_15189_PACK,
    'medical-laboratory': ISO_15189_PACK,
    'clinical-laboratory': ISO_15189_PACK,
    // ISO/IEC 80001 Medical IT Network Risk Management
    'iso-iec-80001': ISO_IEC_80001_PACK,
    'iso80001': ISO_IEC_80001_PACK,
    'medical-it-network': ISO_IEC_80001_PACK,
    'hospital-it-risk': ISO_IEC_80001_PACK,
};
// ---------------------------------------------------------------------------
// Internal adapter that applies GovernanceRule[] (rule-based, no filesystem)
// ---------------------------------------------------------------------------
class RuleBasedAdapter extends BaseGovernanceAdapter {
    rules;
    defaultDeny;
    constructor(rules, defaultDeny) {
        super();
        this.rules = rules;
        this.defaultDeny = defaultDeny;
    }
    preAction(context) {
        // Evaluate rules in order; first match wins
        for (const rule of this.rules) {
            if (this.matchesTool(rule.tool, context.toolName)) {
                if (rule.conditions && !this.matchesConditions(rule.conditions, context)) {
                    continue;
                }
                switch (rule.decision) {
                    case 'allow':
                        return allow(rule.reason);
                    case 'deny':
                        return this.applyHumanInTheLoop(deny(rule.reason));
                    case 'require_approval':
                        return requireApproval(rule.reason);
                }
            }
        }
        // No rule matched: apply default
        if (this.defaultDeny) {
            // F-NEW-CRIT-39j-3: tag as adapter default-deny so execute() can convert
            // to PackPolicyViolation (DENY) instead of routing through HITL to
            // REQUIRE_APPROVAL. See execute() comment for rationale.
            return this.applyHumanInTheLoop(deny('No matching rule. Default deny.', { isAdapterDefaultDeny: true }));
        }
        return allow('No matching rule. Default allow.');
    }
    getCapabilities() {
        return {
            preAction: true,
            postAction: true,
            auditLogging: true,
            circuitBreaker: false,
            approvalQueue: true,
            tamperDetection: false,
        };
    }
    matchesTool(pattern, toolName) {
        if (typeof pattern === 'string') {
            // Support wildcard '*' as a catch-all
            if (pattern === '*')
                return true;
            return pattern === toolName;
        }
        return pattern.test(toolName);
    }
    matchesConditions(conditions, context) {
        for (const [key, expected] of Object.entries(conditions)) {
            const actual = context.input[key];
            if (actual !== expected)
                return false;
        }
        return true;
    }
}
// ---------------------------------------------------------------------------
// Factory function
// ---------------------------------------------------------------------------
export function createGovernedAgent(config) {
    const { name, rules = [], defaultDeny = true, humanInTheLoop = true, onDecision, onError, auditDir, packs: packIds = [], eventBusDir, _packEvaluator: injectedEvaluator, pendingApprovalSubmitter, circuitBreaker: sdkCircuitBreaker, } = config;
    // 1. Create rule-based adapter with HITL enabled
    const adapter = new RuleBasedAdapter(rules, defaultDeny);
    adapter.initialize({
        adapterName: name,
        platform: config.platform,
        humanInTheLoop,
    });
    // 2. Load compliance packs
    //
    // REGISTRY ALLOWLIST ENFORCEMENT (Layer 1 of 3)
    // F-NEW-THIRD-PARTY-PACK-REJECTION-2026-05-24
    //
    // Each entry in packIds MUST be a plain string referencing a known
    // BUILT_IN_PACKS key. Accepting non-string values (e.g. custom pack
    // objects injected at the JavaScript runtime level) would allow a
    // customer to bypass governance by supplying a pack whose rules always
    // ALLOW every action, then emit audit-chain entries claiming "soc2
    // enforced" when no real enforcement occurred.
    //
    // This check runs as the FIRST thing in pack loading, before any
    // normalisation or registry lookup, so the error is thrown immediately
    // with a clear remediation message.
    for (let _i = 0; _i < packIds.length; _i++) {
        const _entry = packIds[_i];
        if (typeof _entry !== 'string') {
            throw new ThirdPartyPackRejected(_entry, _i);
        }
    }
    const packRegistry = new PackRegistry();
    for (const packId of packIds) {
        const normalizedId = packId.toLowerCase().replace(/[\s-_]/g, '');
        // Try direct match first, then normalized
        const pack = BUILT_IN_PACKS[packId] ?? BUILT_IN_PACKS[normalizedId];
        if (pack) {
            // PLACEHOLDER packs must not auto-activate without explicit operator opt-in.
            // A PLACEHOLDER pack bundles multiple jurisdictions whose per-jurisdiction
            // obligations have not yet been confirmed by Vera + counsel. Activating a
            // PLACEHOLDER pack without the explicit opt-in flag throws so the operator
            // is forced to make a conscious decision.
            // F-NEW-VERA-PACK-FINAL-004 (2026-05-03): lpo2024 downgraded to PLACEHOLDER.
            // PLACEHOLDER status is signalled by the pack description containing
            // 'PLACEHOLDER STATUS' (set in pack file when Vera files a FINAL-004-class finding).
            const isPlaceholder = typeof pack.description === 'string' &&
                pack.description.includes('PLACEHOLDER STATUS');
            if (isPlaceholder && !config.allowPlaceholderPacks) {
                throw new Error(`Pack '${pack.id}' has status PLACEHOLDER and cannot be auto-activated without ` +
                    `explicit operator opt-in. Set allowPlaceholderPacks: true in createGovernedAgent() ` +
                    `options after completing Vera + counsel sign-off per the pack file's ` +
                    `OPERATOR_VERIFICATION_REQUIRED notice.`);
            }
            // CONTENT-HASH VERIFICATION (Layer 3 of 3) — FAIL-CLOSED
            // F-NEW-LAYER3-PACK-CONTENT-HASH-NOT-WIRED-2026-05-25
            //
            // Re-compute the SHA-256 hash from the live in-memory pack object and
            // compare against pack.contentHash (embedded at build time by
            // scripts/compute-pack-content-hashes.mjs, wired into npm run prebuild).
            // A mismatch means the pack was monkey-patched after module load —
            // e.g. validators[] cleared so the pack enforces nothing while the
            // audit chain claims enforcement.
            //
            // FAIL-CLOSED policy (Stern HIGH 2026-05-25 review): a pack without
            // contentHash is treated as suspicious, not trusted. Every active pack
            // in BUILT_IN_PACKS carries a hash after the 2026-05-25 rollout
            // (scripts/compute-pack-content-hashes.mjs ran against all 152 unique
            // pack objects). A missing contentHash on a built-in pack indicates
            // a broken build (prebuild didn't run) or a deliberately-injected
            // unhashed pack — both warrant fail-closed.
            if (!pack.contentHash) {
                console.error(`[PackContentTamperedError] pack=${pack.id} ` +
                    `reason=missing-content-hash — prebuild script must run before agent boot`);
                throw new PackContentTamperedError(pack.id, '<expected>', '<missing>');
            }
            const actualHash = computePackContentHash(pack);
            // Use timing-safe comparison to prevent timing side-channel attacks
            // (SHA-256 hex strings are always 64 chars — no length padding needed).
            const hashesMatch = crypto.timingSafeEqual(Buffer.from(actualHash, 'utf8'), Buffer.from(pack.contentHash, 'utf8'));
            if (!hashesMatch) {
                // Log both hashes to stderr (private — never reaches the wire).
                // The error object itself does NOT expose hash values publicly.
                console.error(`[PackContentTamperedError] pack=${pack.id} ` +
                    `expected=${pack.contentHash} actual=${actualHash}`);
                throw new PackContentTamperedError(pack.id, pack.contentHash, actualHash);
            }
            packRegistry.register(pack);
            packRegistry.activate(pack.id);
        }
        else {
            // MissingPackError: fail loud instead of silently ignoring.
            // A customer requesting a non-existent pack gets zero enforcement with
            // no feedback otherwise -- that is a worse outcome than throwing.
            // If backwards-compat requires softer handling, catch MissingPackError
            // at the call site and demote to a warning.
            const knownKeys = Object.keys(BUILT_IN_PACKS).slice(0, 20).join(', ');
            throw new MissingPackError(packId, `Pack '${packId}' is not registered in BUILT_IN_PACKS. ` +
                `Known pack keys (sample): ${knownKeys}... ` +
                `Check src/governed-agent.ts BUILT_IN_PACKS for the full list.`);
        }
    }
    // 3. Set up PackEvaluator for synchronous pack-policy enforcement.
    //    The evaluator runs BEFORE adapter.preAction() in execute().
    //    When packIds is empty, getActive() returns [] and every call produces
    //    ALLOW -- preserving full backward compat for agents without packs.
    let packEvaluator;
    if (injectedEvaluator) {
        // Test injection: use the provided evaluator directly.
        packEvaluator = injectedEvaluator;
    }
    else {
        // Production path: create evaluator from the packRegistry built above.
        const ebDir = eventBusDir ?? auditDir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'ga-eb-'));
        const eventBus = new EventBus({ eventDir: ebDir, agentName: name });
        packEvaluator = new PackEvaluator(packRegistry, eventBus);
    }
    // 4. Set up audit trail
    const auditTrail = [];
    // 5. Ensure audit directory if specified
    if (auditDir) {
        try {
            if (!fs.existsSync(auditDir)) {
                fs.mkdirSync(auditDir, { recursive: true });
            }
        }
        catch (err) {
            if (onError) {
                onError(err);
            }
        }
    }
    // 5a. Tamper-evident JSONL writer.
    //
    // AuditIntegrity manages the hash chain: reads the last line of today's file
    // on construction (crash recovery), then appends entries with _seq, _prevHash,
    // and _hash fields. The prefix 'audit' matches the existing file-naming
    // convention (audit-{date}.jsonl) so new chained entries continue in the same
    // per-day files. Legacy flat entries (pre-fix) have no _hash field; the
    // initializeFromExisting guard detects this and resets the chain to seq=0 /
    // prevHash=''. Those legacy entries will report TAMPERED in verify-chain --
    // that is expected and documented; only entries written after this fix carry
    // integrity fields.
    const auditIntegrity = auditDir
        ? new AuditIntegrity({ logDir: auditDir, prefix: 'audit' })
        : null;
    // 6. Track decisions for compliance scoring
    let totalDecisions = 0;
    let allowedDecisions = 0;
    let deniedDecisions = 0;
    function writeAuditEntry(entry) {
        if (!auditDir || !auditIntegrity)
            return;
        try {
            // Cast AuditEntry to Record<string, unknown> for the integrity layer.
            // The chained wrapper adds _seq / _prevHash / _hash on top of the entry
            // data, which the verify-chain CLI expects under the 'data' key.
            auditIntegrity.append(entry);
        }
        catch (err) {
            if (onError) {
                onError(err);
            }
        }
    }
    // 7. Build and return the GovernedAgent
    const agent = {
        async execute(context) {
            try {
                // --- ASI-10 SDK kill-switch gate (runs FIRST, before pack evaluator) ---
                //
                // Check the local circuit breaker's per-agent forced-OPEN state.
                // No network call — purely in-memory (Locked Invariant 3).
                // The SuspendStateCache background refresher keeps the forced set current
                // by polling GET /api/v1/agents/:id on a configurable TTL (default 30 s).
                //
                // If the agentId is in the forced-OPEN set (operatorSuspended=true was
                // fetched and propagated), deny the tool call immediately and throw
                // OperatorSuspendedError so the caller receives a clear governance signal.
                const agentId = context.agent?.name ?? name;
                if (sdkCircuitBreaker !== undefined) {
                    if (!sdkCircuitBreaker.allowExecutionForAgent(agentId)) {
                        // Emit audit entry for the blocked tool call before throwing.
                        const suspendedDecision = deny(`Agent '${agentId}' is operator-suspended (ASI-10 SDK kill-switch).`);
                        totalDecisions++;
                        deniedDecisions++;
                        const suspendedEntry = {
                            timestamp: new Date().toISOString(),
                            agentName: name,
                            toolName: context.toolName,
                            decision: suspendedDecision,
                            context,
                        };
                        auditTrail.push(suspendedEntry);
                        writeAuditEntry(suspendedEntry);
                        if (onDecision)
                            onDecision(suspendedDecision);
                        throw new OperatorSuspendedError(agentId);
                    }
                }
                // --- Pack evaluator gate (runs BEFORE adapter.preAction) ---
                // Derive tenantId from context; fall back to agent name for single-tenant use.
                const tenantId = context.orgId ?? context.agent?.orgId ?? name;
                const packVerdict = packEvaluator.evaluate(tenantId, agentId, context, 
                // Phase 2 SE Blocker #1: thread the per-request entitlement filter.
                // Set by the check-action handler after computing JWT ∩ bound-packs.
                // Undefined for legacy tokens and direct caller paths (no-op).
                context._allowedPackIds);
                if (packVerdict.verdict === 'DENY') {
                    // Hard block: throw so the caller receives a clear governance signal.
                    // Do NOT call adapter.preAction() -- the pack already decided.
                    throw new PackPolicyViolation(packVerdict.reason, packVerdict.triggeringPackIds, 
                    // F-NEW-CRIT-39i-2: surface classifier IDs to the chain.
                    packVerdict.triggeringClassifierIds ?? []);
                }
                if (packVerdict.verdict === 'PENDING') {
                    // Human review required. Return REQUIRE_APPROVAL with the pending
                    // approval ID surfaced in metadata. Do NOT call adapter.preAction().
                    // The pack-verdict-adapter submits the record to storage asynchronously;
                    // we await it here so the caller can pluck the ID immediately.
                    //
                    // DI path: if a pendingApprovalSubmitter was injected at construction
                    // time (multi-package deployments), call it directly. This eliminates
                    // the async dynamic-import boundary in the hot path.
                    //
                    // Fallback path: dynamic import of pack-verdict-adapter for single-
                    // package / unit-test deployments where no submitter is injected.
                    // The graceful degrade (try/catch) preserves backward compat.
                    let pendingApprovalId;
                    const verdictPayload = {
                        ...packVerdict,
                        tenantId,
                        agentId,
                        actionContext: {
                            toolName: context.toolName,
                            args: context.input,
                        },
                    };
                    try {
                        if (pendingApprovalSubmitter) {
                            // Injected DI: synchronous call, no dynamic import.
                            const record = await pendingApprovalSubmitter(verdictPayload);
                            pendingApprovalId = record.id;
                        }
                        else {
                            // Legacy dynamic-import path: keeps single-package deployments working.
                            const { submitPendingApprovalForPackVerdict } = await import('../packages/governance-server/src/pack-verdict-adapter.js');
                            const record = await submitPendingApprovalForPackVerdict(verdictPayload);
                            pendingApprovalId = record.id;
                        }
                    }
                    catch {
                        // Storage unavailable (e.g., in unit tests without a server running).
                        // Still return REQUIRE_APPROVAL -- just without a tracked approval ID.
                    }
                    const pendingDecision = {
                        type: ActionDecisionType.REQUIRE_APPROVAL,
                        reason: packVerdict.reason,
                        metadata: {
                            source: 'pack-evaluator',
                            pendingApprovalId,
                            triggeringPackIds: packVerdict.triggeringPackIds,
                            triggeringClassifierIds: packVerdict.triggeringClassifierIds,
                        },
                    };
                    totalDecisions++;
                    deniedDecisions++;
                    const pendingEntry = {
                        timestamp: new Date().toISOString(),
                        agentName: name,
                        toolName: context.toolName,
                        decision: pendingDecision,
                        context,
                    };
                    auditTrail.push(pendingEntry);
                    writeAuditEntry(pendingEntry);
                    if (onDecision)
                        onDecision(pendingDecision);
                    return pendingDecision;
                }
                // packVerdict.verdict === 'ALLOW': fall through to adapter.preAction().
                const decision = adapter.preAction(context);
                // F-NEW-CRIT-39j-3: detect adapter default-deny (no rule matched).
                // When isAdapterDefaultDeny=true in metadata (set by RuleBasedAdapter),
                // convert to PackPolicyViolation so the check-action handler returns
                // DENY (not REQUIRE_APPROVAL via HITL). Rationale:
                //   (a) No rule matched = no compliance context for a reviewer.
                //   (b) REQUIRE_APPROVAL creates a dead-letter approval record.
                //   (c) Fail-closed: DENY is the correct answer when nothing allows it.
                // Explicit rule deny (e.g. { tool:'Bash', decision:'deny' }) does NOT
                // set isAdapterDefaultDeny and continues to REQUIRE_APPROVAL as before.
                const isAdapterDefaultDeny = decision.metadata
                    ?.isAdapterDefaultDeny === true;
                if (isAdapterDefaultDeny) {
                    throw new PackPolicyViolation('No compliance rule or pack policy covers this action. ' +
                        'Default deny in effect. Add an explicit allow rule or activate a pack.', [], [], true);
                }
                totalDecisions++;
                if (decision.type === ActionDecisionType.ALLOW) {
                    allowedDecisions++;
                }
                else {
                    deniedDecisions++;
                }
                const entry = {
                    timestamp: new Date().toISOString(),
                    agentName: name,
                    toolName: context.toolName,
                    decision,
                    context,
                };
                auditTrail.push(entry);
                writeAuditEntry(entry);
                if (onDecision) {
                    onDecision(decision);
                }
                return decision;
            }
            catch (err) {
                // PackPolicyViolation and OperatorSuspendedError are intentional --
                // re-throw so callers can distinguish governance blocks from unexpected
                // runtime errors.
                if (err instanceof PackPolicyViolation) {
                    throw err;
                }
                if (err instanceof OperatorSuspendedError) {
                    throw err;
                }
                const error = err;
                if (onError) {
                    onError(error);
                }
                // On unexpected error, default to deny for safety
                return deny(`Governance error: ${error.message}`);
            }
        },
        getAuditTrail() {
            return [...auditTrail];
        },
        getComplianceScore() {
            if (totalDecisions === 0)
                return 100;
            // Compliance score:
            // - Every decision (allow or deny) that followed a rule is compliant
            // - The score reflects how well governance is being enforced
            // - A system that correctly denies bad actions scores high
            // - Factor in pack validation results
            let score = 100;
            // Pack validation contributes to score
            const packResults = packRegistry.validate();
            if (packResults.length > 0) {
                const avgPackScore = packResults.reduce((sum, r) => sum + r.score, 0) / packResults.length;
                // Weight: 50% governance activity, 50% pack compliance
                score = Math.round((score + avgPackScore) / 2);
            }
            return Math.max(0, Math.min(100, score));
        },
        async shutdown() {
            // Flush any remaining audit entries
            if (auditDir && auditTrail.length > 0) {
                const summaryFile = path.join(auditDir, `session-summary-${Date.now()}.json`);
                const summary = {
                    agentName: name,
                    platform: config.platform,
                    totalDecisions,
                    allowedDecisions,
                    deniedDecisions,
                    complianceScore: agent.getComplianceScore(),
                    shutdownTime: new Date().toISOString(),
                };
                try {
                    fs.writeFileSync(summaryFile, JSON.stringify(summary, null, 2));
                }
                catch (err) {
                    if (onError) {
                        onError(err);
                    }
                }
            }
        },
    };
    return agent;
}
//# sourceMappingURL=governed-agent.js.map