# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-poisoned-memory-after-provenance-laundering-through-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-poisoned-memory-after-provenance-laundering-through-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   b0f24b569d04edf40f06c44bc6c7f32c82e2b43e59d1841ac405a73797c53b5a
# Code AST SHA-256:   1560eca2522ccf7bbfca942d871853950708fa248bd21bec09c1d52141d6b5ee
# Verified Classes:   ProvenanceLaunderingError, EpisodicRecord, SemanticFact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic memory is promoted or served at a trust tier
    higher than the minimum trust of its transitive episodic support."""


@dataclass
class EpisodicRecord:
    id: str
    source: str
    trust: str  # "unverified" | "corroborated" | "revoked"


@dataclass
class SemanticFact:
    id: str
    text: str
    derived_from: list[str] = field(default_factory=list)
    declared_trust: str = "consolidated"  # assigned by promotion job -- untrusted


TRUST_RANK = {"revoked": 0, "unverified": 1, "corroborated": 2, "consolidated": 3}


def effective_trust(fact: SemanticFact, episodic: dict[str, EpisodicRecord]) -> str:
    """Derive trust at read time: minimum over transitive episodic support."""
    if not fact.derived_from:
        raise ProvenanceLaunderingError(
            f"fact {fact.id!r} has no provenance edges; cannot derive trust"
        )
    worst = "consolidated"
    for eid in fact.derived_from:
        rec = episodic.get(eid)
        if rec is None:
            raise ProvenanceLaunderingError(
                f"fact {fact.id!r} cites missing episodic record {eid!r}"
            )
        if TRUST_RANK[rec.trust] < TRUST_RANK[worst]:
            worst = rec.trust
    return worst


def admit_for_action(fact: SemanticFact, episodic: dict[str, EpisodicRecord]) -> bool:
    """Gate retrieval results before the agent acts on them."""
    derived = effective_trust(fact, episodic)
    if TRUST_RANK[derived] < TRUST_RANK["corroborated"]:
        # Do not raise here -- quarantine and surface low confidence instead.
        return False
    if TRUST_RANK[derived] < TRUST_RANK[fact.declared_trust]:
        raise ProvenanceLaunderingError(
            f"fact {fact.id!r} declared {fact.declared_trust!r} "
            f"but effective trust is {derived!r}"
        )
    return True


# --- trace of the observed incident ---
episodic = {
    "e1": EpisodicRecord("e1", "user_turn", "corroborated"),
    "e2": EpisodicRecord("e2", "user_turn", "corroborated"),
    "e3": EpisodicRecord("e3", "web_fetch", "unverified"),  # poisoned source
}
poisoned_fact = SemanticFact(
    id="f1",
    text="Deploy key rotates to staging-7 on Fridays.",
    derived_from=["e1", "e2", "e3"],
    declared_trust="consolidated",
)

assert admit_for_action(poisoned_fact, episodic) is False  # quarantined, not acted on

# Retroactive revocation must demote the fact with no re-distillation:
episodic["e1"].trust = "revoked"
assert effective_trust(poisoned_fact, episodic) == "revoked"
