# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-across-episodic-re-derivation-in-persistent-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-laundering-across-episodic-re-derivation-in-persistent-agent-memory-stores.warrant.json
# Markdown SHA-256:   18148215cb37b8105f5feb3f3808b39604f91e28de652a133e056153c24676b6
# Code AST SHA-256:   c7669d311c3ce7ae3226fdcf0468c9d1a474d3f3bee5257993933c5aa5a0f63b
# Verified Classes:   ProvenanceLaunderingError, Source, DerivedFact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived memory fact would be attested at a trust level
    exceeding the minimum trust of its cited source episodes/facts."""


@dataclass(frozen=True)
class Source:
    id: str
    trust: float          # 0.0 .. 1.0
    taint: bool
    origin: str           # e.g. "tool:web_fetch", "human", "episode"


@dataclass
class DerivedFact:
    body: str
    model_confidence: float
    derived_from: list[str] = field(default_factory=list)
    trust: float = 0.0
    taint: bool = False
    attestation_hash: str | None = None


def attest_derived_fact(
    fact: DerivedFact,
    source_index: dict[str, Source],
    *,
    reattestation_authority: str | None = None,
) -> DerivedFact:
    """Compute trust as the join over lineage and stamp taint stickily.

    Rejects the write if lineage is empty (unattributable derivation) or if a
    caller attempts to clear taint without an explicit re-attestation authority.
    """
    if not fact.derived_from:
        raise ProvenanceLaunderingError(
            f"derived fact has empty lineage; cannot attest trust above floor: {fact.body!r}"
        )

    missing = [sid for sid in fact.derived_from if sid not in source_index]
    if missing:
        raise ProvenanceLaunderingError(
            f"derived fact cites unknown sources {missing}; lineage integrity violated"
        )

    sources = [source_index[sid] for sid in fact.derived_from]
    joined_trust = min(s.trust for s in sources)
    joined_taint = any(s.taint for s in sources)

    # Model confidence may never raise trust above the source floor.
    if fact.trust > joined_trust + 1e-9:
        raise ProvenanceLaunderingError(
            f"attestation would launder trust: proposed={fact.trust:.3f} "
            f"exceeds source floor={joined_trust:.3f} for {fact.body!r}"
        )

    # Taint is sticky; only an explicit authority may clear it.
    if joined_taint and not fact.taint and reattestation_authority is None:
        raise ProvenanceLaunderingError(
            f"attempt to clear taint without re-attestation authority on {fact.body!r}"
        )

    fact.trust = joined_trust
    fact.taint = joined_taint if reattestation_authority is None else False
    fact.attestation_hash = (
        f"sha256(author=distiller, ts=..., body={fact.body!r}, "
        f"lineage={sorted(fact.derived_from)}, trust={fact.trust:.3f}, "
        f"taint={fact.taint})"
    )
    return fact


def _demo() -> None:
    index = {
        "ep_88213": Source("ep_88213", trust=0.15, taint=True, origin="tool:web_fetch"),
    }
    poisoned = DerivedFact(
        body="Production credentials are stored under /secrets/prod",
        model_confidence=0.91,
        derived_from=["ep_88213"],
        trust=0.91,  # caller tries to launder
    )
    try:
        attest_derived_fact(poisoned, index)
    except ProvenanceLaunderingError as exc:
        print(f"write rejected as expected: {exc}")

    # Correct path: trust is joined down to 0.15 and taint is carried forward.
    honest = DerivedFact(
        body="Production credentials are stored under /secrets/prod",
        model_confidence=0.91,
        derived_from=["ep_88213"],
    )
    attested = attest_derived_fact(honest, index)
    assert attested.trust == 0.15 and attested.taint is True


if __name__ == "__main__":
    _demo()
