# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-in-its-own-episodic-store-when-poisoned-entries-arrive-pre-reinforced-by-peer-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-provenance-laundering-in-its-own-episodic-store-when-poisoned-entries-arrive-pre-reinforced-by-peer-agents.warrant.json
# Markdown SHA-256:   a6959222d0f0cc579ba3fa594908d1cc80d5d134141b8d9d1b74e7772a296e5b
# Code AST SHA-256:   1a1a0f03e6e8c99bca9010163253095a0776144f8dd7fa760c73cde8109c30d9
# Verified Classes:   ProvenanceLaunderingError, CitationCycleError, MemoryRecord, ProvenanceStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a memory write would inflate effective warrant above its ancestry."""
    pass


class CitationCycleError(ProvenanceLaunderingError):
    """Raised when resolving citation ancestry encounters a cycle (non-well-founded reinforcement)."""
    pass


@dataclass
class MemoryRecord:
    rid: str
    content: str
    warrant: int  # 0=none/untrusted tool output, 1=derived, 2=verified, 3=human-attested
    cites: list[str] = field(default_factory=list)


class ProvenanceStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}

    def _ancestry(self, rid: str, seen: Optional[set] = None) -> set[str]:
        seen = seen or set()
        if rid in seen:
            raise CitationCycleError(f"citation cycle through {rid!r}")
        seen.add(rid)
        rec = self._records[rid]
        for parent in rec.cites:
            self._ancestry(parent, seen)
        return seen

    def effective_warrant(self, rid: str) -> int:
        # Resolve to fixed point; raises CitationCycleError on non-termination.
        ancestry = self._ancestry(rid)
        return min(self._records[a].warrant for a in ancestry)

    def independent_corroboration(self, rid: str) -> int:
        target_ancestry = self._ancestry(rid)
        count = 0
        for other_id, other in self._records.items():
            if other_id == rid:
                continue
            if rid in other.cites:
                other_ancestry = self._ancestry(other_id)
                # Independent only if ancestry is disjoint from target's.
                if other_ancestry.isdisjoint(target_ancestry):
                    count += 1
        return count

    def write(self, rec: MemoryRecord) -> None:
        if rec.cites:
            # Invariant: derived warrant cannot exceed the min of cited ancestry.
            min_parent = min(self.effective_warrant(c) for c in rec.cites)
            if rec.warrant > min_parent:
                raise ProvenanceLaunderingError(
                    f"record {rec.rid!r} claims warrant={rec.warrant} but "
                    f"citation ancestry caps it at {min_parent}"
                )
        self._records[rec.rid] = rec

    def promote_to_semantic(self, rid: str, min_warrant: int = 2, min_independent: int = 2) -> MemoryRecord:
        try:
            eff = self.effective_warrant(rid)
        except CitationCycleError as e:
            raise ProvenanceLaunderingError(
                f"record {rid!r} not promotable: {e}"
            ) from e
        if eff < min_warrant:
            raise ProvenanceLaunderingError(
                f"record {rid!r} effective_warrant={eff} < {min_warrant}; quarantined"
            )
        indep = self.independent_corroboration(rid)
        if indep < min_independent:
            raise ProvenanceLaunderingError(
                f"record {rid!r} has only {indep} independent corroborators "
                f"(< {min_independent}); apparent support is same-origin propagation"
            )
        return self._records[rid]
