/**
 * SourceOutputChainVerifier -- RAG source-to-output chain verification.
 *
 * This is the third and strictest gate in the three-layer RAG governance
 * chain introduced by the P3-T1 RAG cluster:
 *
 *   PR #18 RagSourceAllowlist (pre-retrieval):
 *     Which sources may the agent query at all?
 *
 *   PR #20 RagCitationEnforcer (post-output, pre-finalisation):
 *     Are every citation's (sourceId, chunkRef) pairs provably in the
 *     retrieval pool for this cycle?
 *
 *   THIS FILE -- SourceOutputChainVerifier (post-citation-enforcement):
 *     Does the agent's output text show evidence it actually USED the
 *     cited chunk content? Jaccard 5-gram character-shingle similarity
 *     between the output text and each cited chunk's text must meet a
 *     minimum threshold of 0.10 (10% overlap). Additionally, any
 *     explicitly quoted span must be a verbatim substring of the chunk.
 *
 * Problem being solved (OWASP LLM A05 -- Cascading Hallucination, deeper):
 *   An agent can pass the first two gates and still fabricate:
 *     - Allowlist: source is approved.
 *     - Citation enforcer: citation is in the retrieval pool.
 *     - But the output TEXT could be entirely disconnected from the chunk.
 *   This file closes that gap with a similarity floor and exact-span check.
 *
 * Similarity threshold rationale:
 *   0.10 (10% 5-gram character overlap) is a deliberately low floor.
 *   Empirical RAG benchmarks show:
 *     - Paraphrased summaries of a chunk typically score 0.30 -- 0.70.
 *     - Outright fabrication that merely appends a citation typically
 *       scores below 0.05 (near-zero n-gram overlap with chunk content).
 *     - The 0.10 floor is the "no overlap whatsoever" sentinel -- it
 *       catches agents that cite a chunk they provably did not use.
 *
 *   Known limitation (floor, not ceiling):
 *     The threshold is a FLOOR. An adversarial agent could pad output with
 *     verbatim chunk text to clear 0.10 while still hallucinating the
 *     substantive claim (see PT-RAG-CHAIN-1). This is a known v0 false-
 *     negative. Higher-fidelity factual grounding checks (entailment
 *     models, semantic similarity) are planned for v1. The floor is
 *     sufficient to catch outright fabrication; it does not enforce
 *     paraphrase fidelity. This limitation is documented here and in
 *     docs/runtime/rag-source-output-chain.md.
 *
 * Quoted-span matching:
 *   When a citation includes a quotedSpan, the span is verified as a
 *   verbatim substring of the chunk text using:
 *     - Unicode NFKC normalization of both sides (PT-RAG-CHAIN-2:
 *       Cyrillic/homoglyph lookalike bypass).
 *     - Lowercase comparison.
 *     - Whitespace-run collapse (multiple spaces/tabs/newlines -> one space).
 *   String.prototype.includes() is used, NOT regex. Operator-controlled
 *   span text could be hostile if regex-interpreted.
 *
 * Strict-mode packs:
 *   hipaa, gdpr, pci-dss, hmda, dora -- same five as PR #18 and PR #20.
 *   For these packs, pool entries MUST supply chunkText. Missing chunkText
 *   on a strict pack throws ChunkTextRequiredForStrictPackError (no graceful
 *   degradation). For lenient packs, missing chunkText emits a WARNING event
 *   and the gate passes.
 *
 * Audit events emitted:
 *   SOURCE_OUTPUT_DISCONNECTED          severity ERROR   -- similarity < 0.10
 *   QUOTED_SPAN_MISMATCH                severity ERROR   -- span not in chunk
 *   SOURCE_OUTPUT_VERIFICATION_DEFERRED severity WARNING -- no chunkText, lenient
 *   SOURCE_OUTPUT_VERIFIED              severity NOTICE  -- all citations ok
 *
 * Output text is NEVER written to audit payloads. SHA-256 hash only.
 * Pack-binding is mandatory on every call (SourceOutputUnboundError if empty).
 *
 * Pen-test gates:
 *   PT-RAG-CHAIN-1: similarity-stuffing -- padding with chunk verbatim text
 *     clears 0.10 despite hallucinated claim. Floor behaviour is deterministic.
 *   PT-RAG-CHAIN-2: Unicode-normalization bypass -- Cyrillic lookalikes in
 *     quotedSpan evaded by NFKC normalization on both sides.
 *   PT-RAG-CHAIN-3: chunk-text-injection -- adversarial chunk text containing
 *     prompt injection strings; verifier MUST NOT execute or interpret chunk
 *     content, only compute similarity.
 *
 * BUILD_PLAN reference: line 248 "Source-to-output chain verification (did the
 * agent actually ground in the retrieved source?)".
 *
 * @connexum/ai-governance
 */
/**
 * Packs that require chunkText to be present for every pool entry.
 * For these packs, missing chunkText is a hard error, not a degradation.
 *
 * hipaa   -- HIPAA §164.312(a)(1): PHI claim provenance must be traceable.
 * gdpr    -- GDPR Art. 5(1)(a)/(d): claims about data subjects must be
 *            grounded in verified record text.
 * pci-dss -- PCI DSS Req 12.3: risk claims must cite specific evidence.
 * hmda    -- HMDA Reg C §1003: GMI data usage must derive from the
 *            verified collection text.
 * dora    -- DORA Art. 9 ICT risk: incident claims must ground in retrieved
 *            ICT register or incident record text.
 */
export declare const SOURCE_OUTPUT_STRICT_MODE_PACKS: ReadonlySet<string>;
/**
 * Jaccard similarity threshold for source-to-output verification.
 * An output text and a cited chunk text must share at least this fraction
 * of their 5-gram character shingle sets to be considered grounded.
 *
 * 0.10 is a floor (outright-fabrication sentinel), not a ceiling.
 * See file header for rationale.
 */
export declare const SOURCE_OUTPUT_JACCARD_THRESHOLD = 0.1;
/**
 * Source kind -- forward-compat local copy.
 * When PR #18 (RagSourceAllowlist) merges, this should be re-exported from
 * that module. Until then this local definition keeps this PR independent.
 */
export type RagSourceKind = 'vector-store' | 'document-collection' | 'url-prefix' | 'mcp-resource';
/**
 * A citation as declared in agent output.
 * Forward-compat local definition -- mirrors PR #20's Citation type.
 */
export interface Citation {
    /** Source identifier -- matches a pool entry. */
    sourceId: string;
    /** Source kind. */
    sourceKind: RagSourceKind;
    /**
     * Specific chunk reference within the source. Must be non-empty.
     * Citation enforcement (PR #20) has already validated this before this
     * gate is called.
     */
    chunkRef: string;
    /**
     * Optional verbatim excerpt. When provided, verified as a substring of
     * the chunk text using NFKC + lowercase + whitespace-collapse comparison.
     */
    quotedSpan?: string;
}
/**
 * A retrieval pool entry -- the set of chunks actually fetched in this cycle.
 * Forward-compat local definition -- mirrors PR #20's RetrievalPoolEntry.
 *
 * For strict-mode packs, chunkTexts MUST be populated. For lenient packs,
 * missing chunkTexts causes a deferred-warning rather than an error.
 */
export interface RetrievalPoolEntry {
    orgId: string;
    agentId: string;
    cycleId: string;
    sourceId: string;
    sourceKind: RagSourceKind;
    /** Chunk references retrieved from this source this cycle. */
    chunkRefs: string[];
    /**
     * Optional map of chunkRef -> raw chunk text for verification.
     * Required for strict-mode packs (hipaa, gdpr, pci-dss, hmda, dora).
     */
    chunkTexts?: Record<string, string>;
    packBinding: string[];
    retrievedAt: string;
}
/** The output to verify: text the agent produced plus its citations. */
export interface VerificationOutput {
    /** Output text -- SHA-256 hashed for audit. NEVER stored raw. */
    text: string;
    /** Citations declared by the agent. */
    citations: Citation[];
}
/** Verdict for a single citation. */
export type CitationVerdict = 'verified' | 'disconnected' | 'deferred' | 'quoted-span-mismatch';
/** Per-citation result returned by verifyOutput(). */
export interface CitationResult {
    citation: Citation;
    /** Jaccard similarity (0.0 -- 1.0). -1 if chunkText was absent (deferred). */
    similarity: number;
    verdict: CitationVerdict;
}
/** Full result returned when all citations pass (no throws). */
export interface VerificationResult {
    orgId: string;
    agentId: string;
    cycleId: string;
    citationResults: CitationResult[];
    allVerified: boolean;
}
/**
 * Thrown when pack-binding is empty on any verifyOutput() call.
 * Per feedback_pack_binding_primacy.md: every record must carry a binding.
 */
export declare class SourceOutputUnboundError extends Error {
    readonly context: string;
    constructor(context: string);
}
/**
 * Thrown when Jaccard 5-gram similarity between output text and cited chunk
 * text is below SOURCE_OUTPUT_JACCARD_THRESHOLD (0.10).
 * The output text is provably disconnected from the cited chunk.
 * OWASP LLM A05 (Cascading Hallucination) cite-then-fabricate prevention.
 */
export declare class SourceOutputDisconnectedError extends Error {
    readonly orgId: string;
    readonly agentId: string;
    readonly cycleId: string;
    readonly citationIndex: number;
    readonly sourceId: string;
    readonly chunkRef: string;
    readonly similarity: number;
    readonly threshold: number;
    constructor(opts: {
        orgId: string;
        agentId: string;
        cycleId: string;
        citationIndex: number;
        sourceId: string;
        chunkRef: string;
        similarity: number;
        threshold: number;
    });
}
/**
 * Thrown when a citation provides a quotedSpan but the span is not found as
 * a verbatim (NFKC + lowercase + whitespace-collapsed) substring of the chunk.
 * The agent fabricated or misquoted the excerpt.
 */
export declare class QuotedSpanNotInChunkError extends Error {
    readonly orgId: string;
    readonly agentId: string;
    readonly cycleId: string;
    readonly citationIndex: number;
    readonly sourceId: string;
    readonly chunkRef: string;
    constructor(opts: {
        orgId: string;
        agentId: string;
        cycleId: string;
        citationIndex: number;
        sourceId: string;
        chunkRef: string;
    });
}
/**
 * Thrown when a strict-mode pack (hipaa, gdpr, pci-dss, hmda, dora) is
 * active and a pool entry's chunkTexts map does not include the cited
 * chunkRef's text. For strict packs, chunkText is mandatory -- graceful
 * degradation is not permitted. Retrieval adapters must populate chunkTexts
 * for all chunks when any strict pack is bound.
 *
 * Migration path for retrieval adapters:
 *   recordRetrieval() on RagCitationEnforcer (PR #20) accepts an optional
 *   chunkTexts map. Adapters targeting strict-pack tenants must supply this
 *   map. See docs/runtime/rag-source-output-chain.md for the migration guide.
 */
export declare class ChunkTextRequiredForStrictPackError extends Error {
    readonly orgId: string;
    readonly agentId: string;
    readonly cycleId: string;
    readonly citationIndex: number;
    readonly sourceId: string;
    readonly chunkRef: string;
    readonly strictPacks: string[];
    constructor(opts: {
        orgId: string;
        agentId: string;
        cycleId: string;
        citationIndex: number;
        sourceId: string;
        chunkRef: string;
        strictPacks: string[];
    });
}
export interface SourceOutputDisconnectedAuditEvent {
    type: 'SOURCE_OUTPUT_DISCONNECTED';
    severity: 'ERROR';
    orgId: string;
    agentId: string;
    cycleId: string;
    citationIndex: number;
    /** SHA-256 of output text. Raw text never logged. */
    outputHash: string;
    sourceId: string;
    chunkRef: string;
    similarity: number;
    threshold: number;
    /** SHA-256 of the previous audit event (chain linkage). */
    prevSha: string;
    timestamp: string;
}
export interface QuotedSpanMismatchAuditEvent {
    type: 'QUOTED_SPAN_MISMATCH';
    severity: 'ERROR';
    orgId: string;
    agentId: string;
    cycleId: string;
    citationIndex: number;
    /** SHA-256 of output text. Raw text never logged. */
    outputHash: string;
    sourceId: string;
    chunkRef: string;
    /** SHA-256 of the previous audit event (chain linkage). */
    prevSha: string;
    timestamp: string;
}
export interface SourceOutputVerificationDeferredAuditEvent {
    type: 'SOURCE_OUTPUT_VERIFICATION_DEFERRED';
    severity: 'WARNING';
    orgId: string;
    agentId: string;
    cycleId: string;
    citationIndex: number;
    sourceId: string;
    chunkRef: string;
    timestamp: string;
}
export interface SourceOutputVerifiedAuditEvent {
    type: 'SOURCE_OUTPUT_VERIFIED';
    severity: 'NOTICE';
    orgId: string;
    agentId: string;
    cycleId: string;
    citationCount: number;
    /** SHA-256 of output text. Raw text never logged. */
    outputHash: string;
    timestamp: string;
}
export type SourceOutputAuditEvent = SourceOutputDisconnectedAuditEvent | QuotedSpanMismatchAuditEvent | SourceOutputVerificationDeferredAuditEvent | SourceOutputVerifiedAuditEvent;
/**
 * Post-citation-enforcement source-to-output chain verifier.
 *
 * Call AFTER RagCitationEnforcer.validateOutput() passes and BEFORE the
 * agent output is finalised. The pipeline order is:
 *
 *   [PR #18] RagSourceAllowlist.guardPreRetrieval()  -- pre-retrieval
 *   --> retrieve chunks -->
 *   [PR #20] RagCitationEnforcer.validateOutput()   -- post-output
 *   --> [THIS] SourceOutputChainVerifier.verifyOutput() -- post-citation
 *   --> output finalised
 *
 * Usage:
 *
 *   const verifier = new SourceOutputChainVerifier(auditSink);
 *
 *   // retrievalPool comes from the same pool used by RagCitationEnforcer.
 *   // It must include chunkTexts for strict-pack tenants.
 *   const result = verifier.verifyOutput(
 *     'org-a', 'agent-1', 'cycle-42',
 *     {
 *       text: 'The patient record shows elevated glucose...',
 *       citations: [{
 *         sourceId: 'vs_acme_pubmed',
 *         sourceKind: 'vector-store',
 *         chunkRef: 'c001',
 *         quotedSpan: 'elevated glucose',
 *       }],
 *     },
 *     retrievalPool,   // RetrievalPoolEntry[] for this cycle
 *     ['hipaa'],
 *   );
 */
export declare class SourceOutputChainVerifier {
    /** SHA-256 of the last ERROR audit event (chain linkage). */
    private prevSha;
    private readonly auditSink;
    constructor(auditSink?: (event: SourceOutputAuditEvent) => void);
    /**
     * Verify that each cited chunk's text shows measurable overlap with the
     * output text (Jaccard 5-gram >= 0.10) and that any quotedSpan is a
     * verbatim substring.
     *
     * Precondition: RagCitationEnforcer.validateOutput() has already passed.
     *   This means every (sourceId, chunkRef) in citations is guaranteed to
     *   be present in retrievalPool. This verifier does NOT re-check pool
     *   membership (not its responsibility). If a pool entry is unexpectedly
     *   absent, CitationOutsidePoolError is NOT re-thrown -- this verifier
     *   treats absent pool entry as a programming error and skips it safely.
     *
     * Per-citation behaviour:
     *   1. Find pool entry for (sourceId, chunkRef).
     *   2. If chunkText is available:
     *      a. Compute Jaccard similarity.
     *      b. If similarity < threshold: throw SourceOutputDisconnectedError.
     *      c. If quotedSpan provided: verify verbatim substring.
     *         Mismatch: throw QuotedSpanNotInChunkError.
     *   3. If chunkText is NOT available:
     *      a. Strict pack bound: throw ChunkTextRequiredForStrictPackError.
     *      b. Lenient pack: emit DEFERRED warning, pass.
     *
     * Aggregate: any 'disconnected' or 'quoted-span-mismatch' verdict throws.
     * Any 'deferred' verdict in strict mode throws (handled per-citation above).
     *
     * @param orgId          Operator/tenant identifier.
     * @param agentId        Agent identifier.
     * @param cycleId        Cycle identifier.
     * @param output         Output text and citations.
     * @param retrievalPool  Pool entries for this cycle (from RagCitationEnforcer).
     * @param packBinding    Pack IDs governing this output. Must be non-empty.
     * @returns VerificationResult with per-citation results.
     * @throws SourceOutputUnboundError if packBinding is empty.
     * @throws SourceOutputDisconnectedError if similarity < threshold.
     * @throws QuotedSpanNotInChunkError if quotedSpan not in chunk.
     * @throws ChunkTextRequiredForStrictPackError if strict pack + missing chunkText.
     */
    verifyOutput(orgId: string, agentId: string, cycleId: string, output: VerificationOutput, retrievalPool: RetrievalPoolEntry[], packBinding: string[]): VerificationResult;
    /**
     * Find the pool entry for (sourceId, chunkRef).
     * Assumes citation enforcement has already validated membership.
     * Returns null if not found (programming error / test scenario).
     */
    private findPoolEntry;
    /**
     * Emit an ERROR audit event and advance the SHA chain.
     * WARNING and NOTICE events are emitted directly without advancing the chain
     * (they are not tamper-evidence targets).
     */
    private emitError;
    /**
     * Compute SHA-256 of a string.
     * Used to hash output text for audit logs -- raw content never enters
     * the audit chain.
     */
    private sha256;
}
//# sourceMappingURL=rag-source-output-chain.d.ts.map