/**
 * RagConfidenceThresholdEnforcer -- Confidence threshold enforcement before
 * RAG-grounded decision gates.
 *
 * DESIGN CONCEPT -- "Decision Gate" vs. "Action Gate"
 * ---------------------------------------------------
 * A *decision gate* fires when the agent commits to a state-change based on
 * retrieved context: "chunk X says drug Y has interaction Z, therefore I will
 * write a prescription note." The commit is the decision -- the gate evaluates
 * whether the retrieval grounding is strong enough to warrant that commit.
 *
 * This is distinct from the autonomy-spectrum gate (src/governance/autonomy-
 * spectrum.ts, PR #24) which fires at the *action* point -- after the decision
 * has already been made but before side-effects are executed.  Both may fire
 * for the same agent event.  Integration recipe:
 *   1. Retrieval adapter records chunks + confidence scores into the cycle's
 *      retrieval pool (via recordRetrieval, which is the PR #25 audit hook).
 *   2. Before committing a state-change decision the orchestrator calls
 *      `RagConfidenceThresholdEnforcer.evaluateDecision(...)`.
 *   3. If the result is 'approval-required', the caller submits to the
 *      ApprovalQueue and halts execution until resolved.
 *   4. If the result is 'denied', the caller aborts without queuing.
 *   5. The autonomy-spectrum gate then fires at the action point independently.
 *
 * THREE-BAND RULE
 * ---------------
 * confidence >= threshold                         -> execute     (NOTICE)
 * threshold * 0.7 <= confidence < threshold       -> approval-required (WARNING)
 * confidence < threshold * 0.7  OR empty chunks  -> denied       (ERROR)
 *
 * WEAKEST-LINK SEMANTICS
 * ----------------------
 * The effective decision confidence is the MINIMUM confidence across all
 * cited chunks.  A chain is only as strong as its weakest link.  An
 * adversary who inflates one chunk's confidence score cannot rescue a
 * decision grounded on a weak chunk.
 *
 * PACK-DEFINED DEFAULTS (ragConfidenceThreshold field on CompliancePack)
 * -----------------------------------------------------------------------
 * HIPAA   0.85  -- clinical context; high-certainty bar for PHI decisions
 * GDPR    0.80  -- significant decisions on personal data require good grounding
 * PCI DSS 0.85  -- financial audit trail demands strong retrieval confidence
 * HMDA    0.80  -- fair-lending decisions must be well-grounded
 * DORA    0.85  -- operational resilience; ICT incidents need accurate context
 * (all other packs) 0.70 non-strict default or operator may leave unset to
 *   opt out of enforcement entirely.
 *
 * INTEGRATION WITH PR #20 (chain-of-custody)
 * -------------------------------------------
 * chunks not present in the cycle's retrieval pool are handled by
 * RagCitationEnforcer (PR #20).  This enforcer defers pool-membership
 * checking to that module -- see `PT-RAG-CONF-3` test.  The dependency
 * is explicit: callers should run RagCitationEnforcer BEFORE
 * RagConfidenceThresholdEnforcer if both are active.
 *
 * AUDIT EVENTS
 * ------------
 * Every `evaluateDecision` call emits exactly one structured audit event.
 * Payloads carry chunk hashes (SHA-256 of chunkRef), never raw text.
 *
 * SECURITY NOTES
 * --------------
 * PT-RAG-CONF-1: confidence inflation -- the gate trusts pool data written
 *   by allowlisted code paths.  If an adversary can write to the pool they
 *   already have broader access.  Compensating control: pool writes are
 *   restricted to recordRetrieval() call sites.
 * PT-RAG-CONF-2: threshold-at-runtime tampering -- configureThreshold()
 *   requires governance.configure permission (OperatorRoles.checkPermission).
 *   Agent-runtime identities (not registered as ADMIN operators) are rejected.
 * PT-RAG-CONF-3: fabricated chunkRefs -- unknown refs produce a denial via
 *   the PR #20 pool-membership guard (RagCitationEnforcer integration).
 *
 * Compliance bindings:
 *   HIPAA 164.308(a)(1)(ii)(D): information system activity review
 *   GDPR Art. 22: automated decision-making safeguards
 *   PCI DSS Req 10.2: log all access to system components
 *   HMDA 12 CFR 1003: fair-lending decision auditability
 *   DORA Art. 9: ICT risk management -- accuracy of automated decisions
 *
 * BUILD_PLAN reference: line 250 -- "Confidence threshold enforcement before
 * decision gates".
 *
 * @connexum/ai-governance
 */
import { ApprovalQueue } from './approval-queue';
import { OperatorRoles } from '../security/operator-roles';
export declare class InvalidThresholdError extends Error {
    constructor(value: number);
}
export declare class RagConfidenceUnboundError extends Error {
    constructor();
}
export declare class RagConfidenceThresholdPermissionError extends Error {
    constructor(identityId: string, reason: string);
}
export interface RetrievalPoolEntry {
    /** Opaque chunk reference (e.g., vector-store document ID + chunk index). */
    chunkRef: string;
    /** Cosine / BM25 / hybrid similarity score normalised to [0, 1]. */
    confidence: number;
    /** SHA-256 hash of the raw chunk text -- for audit-event payloads. */
    chunkHash: string;
    /** Source URI / document ID (for chain-of-custody, not audit payload). */
    source?: string;
    /** ISO timestamp when this chunk was retrieved. */
    retrievedAt: string;
}
/**
 * PreDecisionGate -- interface that orchestrator adapters implement to
 * integrate the RAG confidence threshold check.
 *
 * Integration recipe:
 *   1. Implement this interface in your orchestrator adapter.
 *   2. Call `RagConfidenceThresholdEnforcer.evaluateDecision(...)` inside
 *      `beforeDecision`.
 *   3. If result.decision === 'approval-required': submit to ApprovalQueue,
 *      halt execution, await human resolution.
 *   4. If result.decision === 'denied': throw or return an error to the
 *      orchestrator loop -- do NOT proceed with the state change.
 *   5. If result.decision === 'execute': proceed normally.
 *
 * Example adapter stub (LlamaIndex):
 *   class LlamaIndexDecisionGate implements PreDecisionGate {
 *     async beforeDecision(ctx: DecisionContext): Promise<DecisionGateResult> {
 *       return enforcer.evaluateDecision(ctx.orgId, ctx.agentId, ctx.cycleId,
 *         { kind: ctx.decisionKind, basedOnChunks: ctx.retrievedChunkRefs },
 *         ctx.activePackIds);
 *     }
 *   }
 */
export interface PreDecisionGate {
    beforeDecision(context: DecisionContext): Promise<DecisionGateResult>;
}
export interface DecisionContext {
    orgId: string;
    agentId: string;
    cycleId: string;
    decisionKind: string;
    retrievedChunkRefs: string[];
    activePackIds: string[];
}
export type DecisionVerdict = 'execute' | 'approval-required' | 'denied';
export type RagConfidenceEventType = 'RAG_CONFIDENCE_PASSED' | 'RAG_CONFIDENCE_LOW' | 'RAG_CONFIDENCE_TOO_LOW_FOR_APPROVAL';
export type RagConfidenceEventSeverity = 'NOTICE' | 'WARNING' | 'ERROR';
export interface DecisionGateResult {
    decision: DecisionVerdict;
    confidence: number;
    threshold: number;
    reason: string;
    /** Approval queue request ID -- only present when decision === 'approval-required'. */
    approvalRequestId?: string;
}
export interface RagConfidenceAuditEvent {
    type: RagConfidenceEventType;
    severity: RagConfidenceEventSeverity;
    orgId: string;
    agentId: string;
    cycleId: string;
    decisionKind: string;
    /** SHA-256 hashes of chunkRefs -- never raw text or chunkRef strings. */
    chunksConsidered: string[];
    confidence: number;
    threshold: number;
    decision: DecisionVerdict;
    reason: string;
    packBinding: string[];
    /** SHA-256 of the previous audit event JSON -- chain-of-custody linking. */
    prevSha: string;
    timestamp: string;
}
export interface RagConfidenceThresholdConfig {
    /**
     * Callback invoked for every audit event.  Callers should chain this into
     * the same audit sink as other governance events.
     */
    onAuditEvent?: (event: RagConfidenceAuditEvent) => void;
    /**
     * ApprovalQueue instance for routing low-confidence decisions.
     * Required only when the enforcer will route to approval-required verdicts.
     */
    approvalQueue?: ApprovalQueue;
    /**
     * OperatorRoles instance for permission checks on configureThreshold.
     * Required when configureThreshold will be called.
     */
    operatorRoles?: OperatorRoles;
    /**
     * Retrieval pool lookup function.  Given (orgId, cycleId, chunkRef) returns
     * the pool entry or null if the chunk is not in the pool for that cycle.
     *
     * When null is returned the chunk is treated as not-in-pool.  Callers
     * integrating with PR #20 (RagCitationEnforcer) should wire pool-membership
     * checks there rather than duplicating logic here.
     */
    resolvePoolEntry?: (orgId: string, cycleId: string, chunkRef: string) => RetrievalPoolEntry | null;
}
export declare class RagConfidenceThresholdEnforcer {
    private readonly config;
    /** Per-(orgId, agentId) operator threshold overrides. */
    private readonly overrides;
    /** SHA-256 of the last emitted audit event per (orgId, agentId), for chain. */
    private readonly lastEventSha;
    constructor(config?: RagConfidenceThresholdConfig);
    /**
     * Evaluate whether the agent may execute a RAG-grounded decision.
     *
     * @param orgId       Organisation / tenant identifier.
     * @param agentId     Agent identifier.
     * @param cycleId     Current execution cycle identifier.
     * @param decision    Decision descriptor: kind string + cited chunk refs.
     * @param packBinding Active compliance pack IDs.  Must be non-empty.
     * @returns DecisionGateResult with verdict, effective confidence, threshold,
     *          and human-readable reason.
     */
    evaluateDecision(orgId: string, agentId: string, cycleId: string, decision: {
        kind: string;
        basedOnChunks: string[];
    }, packBinding: string[]): DecisionGateResult;
    /**
     * Configure a per-agent threshold override.
     *
     * Requires governance.configure permission.  Agent-runtime identities
     * (not registered as ADMIN operators) are rejected.
     *
     * @param orgId            Organisation / tenant identifier.
     * @param agentId          Agent identifier.
     * @param threshold        New threshold value in [0, 1].
     * @param approverIdentity Operator ID of the human authorising the change.
     * @param packBinding      Active pack IDs (mandatory).
     */
    configureThreshold(orgId: string, agentId: string, threshold: number, approverIdentity: string, packBinding: string[]): void;
    /**
     * Returns the threshold currently in effect for the given agent.
     *
     * Resolution order:
     *   1. Operator override (configureThreshold)
     *   2. Strictest pack-defined threshold from packBinding
     *   3. Non-strict default (0.70) if no pack defines a threshold
     */
    getEffectiveThreshold(orgId: string, agentId: string, packBinding?: string[]): number;
    private _agentKey;
    private _effectiveThreshold;
    private _applyBandRule;
    private _emitAuditEvent;
    private _hashRef;
}
export declare const RAG_CONFIDENCE_PACK_THRESHOLDS: Record<string, number>;
export declare const RAG_CONFIDENCE_NON_STRICT_DEFAULT = 0.7;
//# sourceMappingURL=rag-confidence-threshold.d.ts.map