# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-through-episodic-memory-re-summarization-in-long-horizon-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-through-episodic-memory-re-summarization-in-long-horizon-agents.warrant.json
# Markdown SHA-256:   f82cea2ffa1bcdb61c654f55e0e030da1bdacca3b2fa02f5e8f9af3ef6c146f3
# Code AST SHA-256:   a5bb04eb6ca2d07e86f4959df1a3b013639de28b58c4adc1b5ea08824942f50a
# Verified Classes:   ProvenanceLaunderingError, UnresolvableProvenanceError, Memory
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory's stored trust exceeds the min-trust of its ancestor chain."""
    pass

class UnresolvableProvenanceError(ProvenanceLaunderingError):
    """Raised when an ancestor chain cannot be resolved to roots within the hop bound."""
    pass

@dataclass
class Memory:
    id: str
    content: str
    stored_trust: float
    derived_from: list[str] = field(default_factory=list)
    synthesized_spans: list[str] = field(default_factory=list)

MAX_HOPS = 8
LAUNDER_TOLERANCE = 0.05

def resolve_root_trust(mem: Memory, index: dict[str, Memory], _seen: Optional[set[str]] = None) -> float:
    seen = _seen or set()
    if mem.id in seen:
        raise UnresolvableProvenanceError(f"cycle in provenance chain at {mem.id}")
    seen.add(mem.id)
    if len(seen) > MAX_HOPS:
        raise UnresolvableProvenanceError(f"provenance chain exceeds {MAX_HOPS} hops at {mem.id}")
    if not mem.derived_from:
        return mem.stored_trust  # root: episode or direct observation
    ancestor_trusts = []
    for aid in mem.derived_from:
        if aid not in index:
            raise UnresolvableProvenanceError(f"dangling ancestor {aid} referenced by {mem.id}")
        ancestor_trusts.append(resolve_root_trust(index[aid], index, seen))
    return min(ancestor_trusts)

def verify_on_retrieval(mem: Memory, index: dict[str, Memory]) -> float:
    """Returns effective trust. Raises if stored trust has been laundered above ancestor min."""
    if mem.synthesized_spans:
        # synthesized content cannot inherit ancestor trust for those spans
        return 0.0
    effective = resolve_root_trust(mem, index)
    if mem.stored_trust - effective > LAUNDER_TOLERANCE:
        raise ProvenanceLaunderingError(
            f"memory {mem.id} stored_trust={mem.stored_trust:.2f} "
            f"exceeds ancestor min={effective:.2f} (delta={mem.stored_trust - effective:.2f})"
        )
    return effective

def compact(inputs: list[Memory], new_id: str, summary: str, index: dict[str, Memory]) -> Memory:
    """Compactor MUST inherit min-trust; it may not author its own confidence."""
    effective = min(verify_on_retrieval(m, index) for m in inputs)
    derived = Memory(
        id=new_id,
        content=summary,
        stored_trust=effective,          # inherited, never authored by summarizer
        derived_from=[m.id for m in inputs],
    )
    index[new_id] = derived
    return derived
