# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundering-in-a-persistent-agent-store-when-a-trusted-writer-memory-is-rewritten-through-a-derived-summary-pa.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundering-in-a-persistent-agent-store-when-a-trusted-writer-memory-is-rewritten-through-a-derived-summary-pa.warrant.json
# Markdown SHA-256:   772ae19d96ed240eb6c67a2b5bab3c6206d4783c3aae0d89659541de7a4421da
# Code AST SHA-256:   babf948f2ce8e2b45a9e0f845ca1df6250035db45586c60496e485b3f916bc48
# Verified Classes:   ProvenanceLaunderingError, MemoryEntry, Store
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory's trust exceeds its least-trusted contributing source,
    or when its recorded sources do not match its actual contributing inputs."""
    pass

@dataclass
class MemoryEntry:
    entry_id: str
    writer_id: str
    trust_tier: int
    source_ids: list[str] = field(default_factory=list)
    closed_book: bool = True  # distillation consumed only enumerated sources

@dataclass
class Store:
    entries: dict[str, MemoryEntry] = field(default_factory=dict)

    def _closure(self, entry_id: str, seen: set[str] | None = None) -> set[str]:
        seen = seen or set()
        if entry_id in seen:
            return seen
        seen.add(entry_id)
        for sid in self.entries[entry_id].source_ids:
            if sid in self.entries:
                self._closure(sid, seen)
        return seen

    def derived_trust(self, entry_id: str) -> int:
        """Trust of a derived entry is min() over the transitive source closure.
        Untrusted (tier 0) if any contributing distillation was open-book."""
        e = self.entries[entry_id]
        if not e.closed_book:
            return 0
        closure = self._closure(entry_id) - {entry_id}
        if not closure:
            return e.trust_tier
        return min(self.entries[s].trust_tier for s in closure)

    def admit_derived(self, entry: MemoryEntry, contributing_ids: set[str]) -> None:
        """Write-time guard: recorded sources must equal actual contributing inputs,
        and inherited tier must not exceed min() over sources."""
        recorded = set(entry.source_ids)
        if recorded != contributing_ids:
            raise ProvenanceLaunderingError(
                f"entry {entry.entry_id}: recorded sources {recorded} != "
                f"contributing inputs {contributing_ids} (invisible source)"
            )
        if not entry.closed_book:
            if entry.trust_tier > 0:
                raise ProvenanceLaunderingError(
                    f"entry {entry.entry_id}: open-book distillation "
                    f"cannot inherit tier {entry.trust_tier}"
                )
            return
        if recorded:
            floor = min(self.entries[s].trust_tier for s in recorded)
            if entry.trust_tier > floor:
                raise ProvenanceLaunderingError(
                    f"entry {entry.entry_id}: inherited tier {entry.trust_tier} "
                    f"exceeds min source tier {floor} (max-inheritance laundering)"
                )
        self.entries[entry.entry_id] = entry

    def retrieve(self, entry_id: str, required_tier: int) -> MemoryEntry:
        e = self.entries[entry_id]
        effective = self.derived_trust(entry_id)
        if effective < required_tier:
            raise ProvenanceLaunderingError(
                f"entry {entry_id}: effective trust {effective} "
                f"< required {required_tier}"
            )
        return e
