# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-consistency-checks-across-episodic-semantic-and-procedural-stores-disagree-on-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-consistency-checks-across-episodic-semantic-and-procedural-stores-disagree-on-provenance.warrant.json
# Markdown SHA-256:   f097d6f420b57034bf6bb493b4dbb173575bb1711a4e81c9c272929dcb76d976
# Code AST SHA-256:   a928c8e16fb084832d4a11ecb111380225885505fb96d211620e3735a281b2a9
# Verified Classes:   ProvenanceGapError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ProvenanceGapError(RuntimeError):
    """Raised when a memory fact's provenance edges do not resolve to live ledger nodes."""
    pass


def validate_fact_provenance(fact, ledger, require_orphan_edges=2):
    """
    fact: dict with keys 'fact_id', 'store', 'provenance_edges' (list of node_ids)
    ledger: dict node_id -> {'seq': int, 'alive': bool}
    Returns True if the fact is safe to act on.
    Raises ProvenanceGapError if the fact is causally orphaned.
    """
    orphan_edges = []
    for node_id in fact.get("provenance_edges", []):
        node = ledger.get(node_id)
        if node is None or not node.get("alive", False):
            orphan_edges.append(node_id)

    if not fact.get("provenance_edges"):
        # No provenance at all is itself a gap, not a pass.
        raise ProvenanceGapError(
            f"fact {fact['fact_id']} in store '{fact['store']}' has empty provenance"
        )

    if len(orphan_edges) >= require_orphan_edges:
        raise ProvenanceGapError(
            f"fact {fact['fact_id']} in store '{fact['store']}' is causally orphaned: "
            f"unresolved edges {orphan_edges} (threshold {require_orphan_edges})"
        )

    return True


def cross_store_check(facts, ledger):
    """
    facts: list of fact dicts across episodic/semantic/procedural stores.
    Consistency of content is NOT sufficient; provenance must resolve.
    """
    quarantined = []
    for fact in facts:
        try:
            validate_fact_provenance(fact, ledger)
        except ProvenanceGapError as e:
            quarantined.append((fact["fact_id"], str(e)))
    if quarantined:
        # Quarantine propagates to all stores sharing these fact_ids.
        raise ProvenanceGapError(f"cross-store quarantine triggered: {quarantined}")
    return True
