# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-in-agent-long-term-memory-during-trust-scored-recall-and-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-in-agent-long-term-memory-during-trust-scored-recall-and-rollback.warrant.json
# Markdown SHA-256:   401dfbd3b1964f44cf0f792e5e54d2c79255eff7a486841552323da20070ef80
# Code AST SHA-256:   ee740a0be36918c0e267c6cd389a6cfaac6d5e62cd92ef076c0b28d48b0d3a4e
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry, ProvenanceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a write would claim trust exceeding its inputs' floor,
    or when rollback would leave a laundered descendant live."""
    pass


@dataclass
class MemoryEntry:
    id: str
    content: str
    source_class: str
    origin_id: str
    trust: float
    inputs: list[str] = field(default_factory=list)   # derivation edges i -> this
    evicted: bool = False


class ProvenanceStore:
    def __init__(self, theta_admit: float = 0.7, theta_quarantine: float = 0.4):
        self.entries: dict[str, MemoryEntry] = {}
        self.theta_admit = theta_admit
        self.theta_quarantine = theta_quarantine

    def _effective_trust(self, entry_id: str, _seen: Optional[set] = None) -> float:
        seen = _seen or set()
        if entry_id in seen:
            raise ProvenanceLaunderingError(f"cycle in derivation graph at {entry_id}")
        seen.add(entry_id)
        e = self.entries[entry_id]
        if not e.inputs:
            return e.trust
        floor = min(self._effective_trust(i, seen) for i in e.inputs)
        return min(e.trust, floor)

    def write(self, entry: MemoryEntry) -> None:
        # Enforce transitive trust floor at write time over the *actual* input set.
        if entry.inputs:
            input_floor = min(self._effective_trust(i) for i in entry.inputs)
            if entry.trust > input_floor + 1e-9:
                raise ProvenanceLaunderingError(
                    f"write {entry.id} claims trust={entry.trust} but input floor={input_floor}"
                )
        self.entries[entry.id] = entry

    def admit(self, entry_id: str) -> bool:
        # Admission uses recomputed floor, never the stored scalar.
        eff = self._effective_trust(entry_id)
        if eff < self.theta_quarantine:
            return False
        return eff >= self.theta_admit

    def rollback(self, root_id: str) -> list[str]:
        # Closure: evict root and all reachable descendants.
        to_evict, stack = [], [root_id]
        while stack:
            nid = stack.pop()
            if nid in self.entries and not self.entries[nid].evicted:
                self.entries[nid].evicted = True
                to_evict.append(nid)
                stack.extend(
                    e.id for e in self.entries.values()
                    if nid in e.inputs and not e.evicted
                )
        # Post-condition: no live entry may derive from an evicted node.
        for e in self.entries.values():
            if not e.evicted and any(i in to_evict for i in e.inputs):
                raise ProvenanceLaunderingError(
                    f"rollback of {root_id} left live descendant {e.id}"
                )
        return to_evict
