/**
 * RagRetrievalAuditLogger -- Durable forensic trail for every RAG retrieval call.
 *
 * This is the fourth gate in the P3-T1 RAG governance cluster:
 *
 *   PR #18 RagSourceAllowlist (pre-retrieval):
 *     Which sources may the agent query at all?
 *
 *   PR #20 RagCitationEnforcer (post-output, in-memory pool):
 *     Are citations in the per-cycle retrieval pool?
 *
 *   PR #23 SourceOutputChainVerifier (post-citation-enforcement):
 *     Does output text show evidence the cited chunk was actually used?
 *
 *   THIS FILE -- RagRetrievalAuditLogger (durable record, BUILD_PLAN line 249):
 *     Every retrieval call (allowed or blocked) is written to an immutable
 *     SHA-256 audit chain. Source identity is preserved via sourceHash and
 *     sourceKind. Raw URLs and query text NEVER enter the chain.
 *
 * Why this matters:
 *   - Auditors (HIPAA OCR, GDPR DPA, SOC 2 Type II) need "what did this agent
 *     see, when, from which source." The per-cycle pool (PR #20) is in-memory;
 *     this log is the DURABLE record after cycle teardown.
 *   - Memory-poisoning forensics: if PR #22's chain breaks, retrieval audit
 *     events point to which session ingested the rogue content.
 *   - Litigation hold: challenged agent output requires producing the retrieval
 *     trail. This log is that trail.
 *
 * Source identity design (operator mapping):
 *   sourceHash = SHA-256(source URL/URI).
 *   queryHash  = SHA-256(queryText).
 *   Raw values are NEVER logged. The operator retains the plaintext-to-hash
 *   mapping (e.g., in their internal vector-store catalog or source registry).
 *   Auditors with operator cooperation can deanonymize. Without the mapping,
 *   the hash is opaque -- this is intentional: the audit log can be safely
 *   shared with external reviewers without exposing proprietary source topology.
 *   See docs/runtime/rag-retrieval-audit-log.md for the integration recipe.
 *
 * Pairing:
 *   recordRetrievalAttempt() returns a retrievalId (UUID). The caller MUST
 *   pass that retrievalId to recordRetrievalResult() when the retrieval
 *   completes. If result is not recorded within retrievalAuditPairingTimeoutMs
 *   (default 30 s), the logger emits RAG_RETRIEVAL_AUDIT_PAIRING_VIOLATION ERROR.
 *
 * Cycle reconciler:
 *   At cycle teardown call cycleEnd(cycleId). Any retrievalId opened in that
 *   cycle that never received a result emits RAG_RETRIEVAL_AUDIT_INCOMPLETE ERROR.
 *   Strict-pack tenants (HIPAA, GDPR, PCI DSS, HMDA, DORA) MUST call cycleEnd.
 *
 * Cross-cycle and cross-agent pairing security:
 *   Each retrievalId is keyed by (cycleId, agentId, orgId). Attempts to call
 *   recordRetrievalResult() with a retrievalId from a different cycle, agent,
 *   or org throw RetrievalIdNotInCycleError (PT-RAG-AUDIT-2).
 *
 * Audit chain integrity:
 *   Every event carries prevSha (SHA-256 of the previous event's JSON). A
 *   replayed or modified event breaks the chain, detectable via chain verifier
 *   (PT-RAG-AUDIT-3).
 *
 * Hash function:
 *   SHA-256 (crypto.createHash('sha256')). PT-RAG-AUDIT-1 notes that collision
 *   resistance is computationally infeasible for SHA-256; MD5/SHA-1 are
 *   explicitly NOT used (see test assertion).
 *
 * Pack-binding mandatory:
 *   Per feedback_pack_binding_primacy.md: every call must carry at least one
 *   pack. Empty binding throws RagRetrievalAuditUnboundError.
 *
 * Compliance references:
 *   - HIPAA 164.312(b): Audit Controls -- tamper-evident activity logging
 *   - GDPR Art. 5(2): Accountability -- demonstrable compliance records
 *   - PCI DSS Req 10.2: Audit log events per security-related action
 *   - HMDA Reg C 1003.4: data-collection audit trail
 *   - DORA Art. 9: ICT risk -- retrieval traceability for incident forensics
 *   - SOC 2 CC7.2: monitoring of system components
 *
 * BUILD_PLAN reference: line 249 "Retrieval audit logging with source identity
 * preserved".
 *
 * @connexum/ai-governance
 */
/**
 * Packs for which retrieval audit logging is MANDATORY.
 * Matches SOURCE_OUTPUT_STRICT_MODE_PACKS in rag-source-output-chain.ts.
 *
 * hipaa   -- HIPAA 164.312(b): Audit Controls
 * gdpr    -- GDPR Art. 5(2): Accountability
 * pci-dss -- PCI DSS Req 10: Track and monitor all access
 * hmda    -- HMDA Reg C 1003.4: Data collection audit
 * dora    -- DORA Art. 9: ICT risk traceability
 */
export declare const RAG_AUDIT_STRICT_MODE_PACKS: ReadonlySet<string>;
/** Default pairing timeout in milliseconds (30 s). */
export declare const RAG_AUDIT_PAIRING_TIMEOUT_MS = 30000;
export type RagSourceKind = 'vector-store' | 'document-collection' | 'url-prefix' | 'mcp-resource';
/**
 * Thrown when packBinding is empty on any audit call.
 * Every retrieval audit record must carry at least one pack.
 */
export declare class RagRetrievalAuditUnboundError extends Error {
    readonly context: string;
    constructor(context: string);
}
/**
 * Thrown when recordRetrievalResult() is called with a retrievalId that does
 * not belong to the given (cycleId, agentId, orgId) scope.
 *
 * PT-RAG-AUDIT-2: prevents cross-cycle and cross-agent result injection.
 */
export declare class RetrievalIdNotInCycleError extends Error {
    readonly retrievalId: string;
    readonly orgId: string;
    readonly agentId: string;
    readonly cycleId: string;
    constructor(opts: {
        retrievalId: string;
        orgId: string;
        agentId: string;
        cycleId: string;
        reason: string;
    });
}
/**
 * RAG_RETRIEVAL_ATTEMPTED -- emitted by recordRetrievalAttempt().
 *
 * Severity NOTICE when allowedByAllowlist=true (successful gate pass).
 * Severity WARNING when allowedByAllowlist=false (blocked attempt).
 *
 * sourceHash = SHA-256(source URL/URI) -- NEVER the raw URL.
 * queryHash  = SHA-256(queryText)      -- NEVER the raw query.
 */
export interface RagRetrievalAttemptedEvent {
    type: 'RAG_RETRIEVAL_ATTEMPTED';
    severity: 'NOTICE' | 'WARNING';
    orgId: string;
    agentId: string;
    cycleId: string;
    /** UUID returned to caller for pairing with result. */
    retrievalId: string;
    /** SHA-256 of source URL/URI. Raw URL never logged. */
    sourceHash: string;
    sourceKind: RagSourceKind;
    /** SHA-256 of queryText. Raw query text never logged. */
    queryHash: string;
    /** Whether the allowlist gate (PR #18) passed. */
    allowedByAllowlist: boolean;
    /** Populated when allowedByAllowlist=false. */
    rejectReason?: string;
    packBinding: string[];
    /** High-resolution timestamp in nanoseconds (BigInt serialised as string). */
    timestampNs: string;
    /** SHA-256 of the previous audit event (chain linkage). */
    prevSha: string;
}
/**
 * RAG_RETRIEVAL_COMPLETED -- emitted by recordRetrievalResult().
 *
 * Severity NOTICE when providerStatus='ok'.
 * Severity WARNING when providerStatus='error' or 'timeout'.
 *
 * chunkRefHashes = SHA-256 of each chunkRef string. Raw refs never logged.
 */
export interface RagRetrievalCompletedEvent {
    type: 'RAG_RETRIEVAL_COMPLETED';
    severity: 'NOTICE' | 'WARNING';
    orgId: string;
    agentId: string;
    cycleId: string;
    retrievalId: string;
    chunksReturned: number;
    /** SHA-256 of each chunkRef string. Raw refs never logged. */
    chunkRefHashes: string[];
    tookMs: number;
    providerStatus: 'ok' | 'error' | 'timeout';
    /** Populated when providerStatus != 'ok'. */
    errorReason?: string;
    packBinding: string[];
    timestampNs: string;
    prevSha: string;
}
/**
 * RAG_RETRIEVAL_AUDIT_PAIRING_VIOLATION -- emitted when recordRetrievalResult()
 * is NOT called within retrievalAuditPairingTimeoutMs of recordRetrievalAttempt().
 *
 * Severity ERROR. Indicates a retrieval that bypassed the result-logging path.
 */
export interface RagRetrievalPairingViolationEvent {
    type: 'RAG_RETRIEVAL_AUDIT_PAIRING_VIOLATION';
    severity: 'ERROR';
    orgId: string;
    agentId: string;
    cycleId: string;
    retrievalId: string;
    openedAtNs: string;
    detectedAtNs: string;
    pairingTimeoutMs: number;
    packBinding: string[];
    timestampNs: string;
    prevSha: string;
}
/**
 * RAG_RETRIEVAL_AUDIT_INCOMPLETE -- emitted by cycleEnd() for each retrievalId
 * opened in the cycle that never received a recordRetrievalResult() call.
 *
 * Severity ERROR. Fires for every unpaired attempt at cycle teardown.
 */
export interface RagRetrievalAuditIncompleteEvent {
    type: 'RAG_RETRIEVAL_AUDIT_INCOMPLETE';
    severity: 'ERROR';
    orgId: string;
    agentId: string;
    cycleId: string;
    retrievalId: string;
    openedAtNs: string;
    packBinding: string[];
    timestampNs: string;
    prevSha: string;
}
export type RagRetrievalAuditEvent = RagRetrievalAttemptedEvent | RagRetrievalCompletedEvent | RagRetrievalPairingViolationEvent | RagRetrievalAuditIncompleteEvent;
export interface RagRetrievalAuditConfig {
    /**
     * Pairing timeout in milliseconds.
     * If recordRetrievalResult() is not called within this window,
     * a PAIRING_VIOLATION event is emitted (default: 30 000 ms = 30 s).
     *
     * Rationale: 30 s is generous for any plausible retrieval latency.
     * A retrieval that takes longer than 30 s is either hung (timeout event
     * should have fired) or has bypassed the result-logging path. In either
     * case the pairing violation is the correct governance signal.
     */
    retrievalAuditPairingTimeoutMs?: number;
}
/**
 * Durable forensic audit logger for RAG retrieval calls.
 *
 * Integration recipe:
 *
 *   const auditLogger = new RagRetrievalAuditLogger(sink, config);
 *
 *   // Step 1 -- call AFTER PR #18 allowlist decision, BEFORE actual retrieval.
 *   const retrievalId = auditLogger.recordRetrievalAttempt(
 *     orgId, agentId, cycleId,
 *     {
 *       source: 'https://vectordb.internal/collections/patient-notes',
 *       sourceKind: 'vector-store',
 *       queryText: 'elevated glucose levels for patient X',
 *       allowedByAllowlist: true,
 *     },
 *     ['hipaa'],
 *   );
 *
 *   // Step 2 -- dispatch actual retrieval call ...
 *   const chunks = await vectorDb.query(queryText, k=5);
 *
 *   // Step 3 -- call immediately after retrieval returns (or errors/times out).
 *   auditLogger.recordRetrievalResult(
 *     orgId, agentId, cycleId, retrievalId,
 *     {
 *       chunksReturned: chunks.length,
 *       chunkRefs: chunks.map(c => c.id),
 *       tookMs: elapsed,
 *       providerStatus: 'ok',
 *     },
 *     ['hipaa'],
 *   );
 *
 *   // Step 4 -- at cycle teardown (after PR #20 and PR #23 gates run):
 *   auditLogger.cycleEnd(orgId, agentId, cycleId);
 */
export declare class RagRetrievalAuditLogger {
    private readonly config;
    private readonly auditSink;
    /**
     * SHA-256 chain head for tamper-evident linking.
     * Every emitted event advances this value.
     */
    private prevSha;
    /**
     * Pending attempts keyed by retrievalId.
     * Entry exists from recordRetrievalAttempt() until recordRetrievalResult()
     * is called (or cycleEnd() clears unpaired entries).
     */
    private readonly pendingAttempts;
    /**
     * Timer handles for pairing-timeout enforcement.
     * Keyed by retrievalId.
     */
    private readonly pairingTimers;
    constructor(auditSink?: (event: RagRetrievalAuditEvent) => void, config?: RagRetrievalAuditConfig);
    /**
     * Record a retrieval attempt (allowed or blocked).
     *
     * Call AFTER the PR #18 allowlist decision and BEFORE dispatching the actual
     * retrieval call. This ensures every retrieval -- whether it proceeds or is
     * blocked -- has a durable audit record.
     *
     * @returns retrievalId (UUID). Pass to recordRetrievalResult() when the
     *          retrieval completes. MUST NOT be shared across cycles or agents.
     * @throws RagRetrievalAuditUnboundError if packBinding is empty.
     */
    recordRetrievalAttempt(orgId: string, agentId: string, cycleId: string, attempt: {
        /** Source URL or URI. Hashed to SHA-256 before logging. */
        source: string;
        sourceKind: RagSourceKind;
        /** Query text. Hashed to SHA-256 before logging. */
        queryText: string;
        allowedByAllowlist: boolean;
        rejectReason?: string;
    }, packBinding: string[]): string;
    /**
     * Record the outcome of a retrieval call.
     *
     * Call immediately after the retrieval returns (whether ok, error, or timeout).
     * Must be paired with the retrievalId returned by recordRetrievalAttempt().
     *
     * Cross-cycle and cross-agent pairing is rejected: if the (cycleId, agentId,
     * orgId) do not match the scope under which the retrievalId was opened,
     * throws RetrievalIdNotInCycleError (PT-RAG-AUDIT-2).
     *
     * @throws RagRetrievalAuditUnboundError if packBinding is empty.
     * @throws RetrievalIdNotInCycleError if retrievalId is unknown or mismatched.
     */
    recordRetrievalResult(orgId: string, agentId: string, cycleId: string, retrievalId: string, result: {
        chunksReturned: number;
        /** Chunk reference strings. Each is hashed before logging. */
        chunkRefs: string[];
        tookMs: number;
        providerStatus: 'ok' | 'error' | 'timeout';
        errorReason?: string;
    }, packBinding: string[]): void;
    /**
     * Reconcile all open retrievalIds for the given cycle.
     *
     * Any retrievalId opened in this cycle that has NOT received a result emits
     * RAG_RETRIEVAL_AUDIT_INCOMPLETE severity ERROR. This catches retrieval calls
     * that completed but whose result logging was bypassed.
     *
     * Strict-pack tenants (HIPAA, GDPR, PCI DSS, HMDA, DORA) MUST call this at
     * every cycle teardown. Omitting it is itself a governance gap (no automatic
     * enforcement here -- the orchestrator is responsible for wiring this call).
     *
     * @returns Number of INCOMPLETE events emitted.
     */
    cycleEnd(orgId: string, agentId: string, cycleId: string): number;
    /**
     * Current SHA chain head (SHA-256 of the last emitted event's JSON).
     * Exposed for test introspection of chain integrity.
     */
    get currentChainHead(): string;
    /**
     * Number of pending (unmatched) attempts currently tracked.
     */
    get pendingAttemptCount(): number;
    /**
     * Compute SHA-256 of a string.
     *
     * PT-RAG-AUDIT-1: explicitly SHA-256 (not MD5, not SHA-1).
     * Collision resistance is computationally infeasible for SHA-256.
     */
    private sha256;
    /**
     * Emit an audit event and advance the SHA chain.
     * The chain ensures any replay or modification is detectable (PT-RAG-AUDIT-3).
     */
    private emitAndChain;
    /**
     * Return current time as nanoseconds (string) using process.hrtime.bigint().
     * Uses Date.now() * 1e6 as a fallback in environments without hrtime.bigint.
     */
    private nowNs;
    /**
     * Pairing-timeout callback. Fires when recordRetrievalResult() was not
     * called within retrievalAuditPairingTimeoutMs of recordRetrievalAttempt().
     */
    private onPairingTimeout;
}
//# sourceMappingURL=rag-retrieval-audit.d.ts.map