# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-poisoned-episodic-memory-whose-provenance-tag-was-laundered-through-a-semantic-distillation-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-inherits-a-poisoned-episodic-memory-whose-provenance-tag-was-laundered-through-a-semantic-distillation-pass.warrant.json
# Markdown SHA-256:   573dfee7ae5522dbae5282201ae2487ddcb587ea6b1c7205be0e08422d898197
# Code AST SHA-256:   5833b63847a999c3179fc4e67de143d375252d2477504fe11d56dfee76972ac6
# Verified Classes:   ProvenanceLaunderingError, MissingLineageError, Episodic, Semantic
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived record would claim trust exceeding its sources."""
    pass


class MissingLineageError(ProvenanceLaunderingError):
    """Raised when a distiller emits an assertion without source IDs."""
    pass


TRUST_ORDER = {"untrusted": 0, "quarantined": 1, "trusted": 2}


@dataclass
class Episodic:
    id: str
    content: str
    trust: str  # "untrusted" | "quarantined" | "trusted"


@dataclass
class Semantic:
    id: str
    content: str
    trust: str
    derived_from: list[str] = field(default_factory=list)


def promote(
    assertion: str,
    claimed_source_ids: Iterable[str],
    episodic_store: dict[str, Episodic],
    prompt_window_ids: set[str],
) -> Semantic:
    """
    Enforce taint monotonicity at the promotion gate.

    The distiller's *claimed* sources are advisory only. The harness knows
    which episodics were actually in the prompt window; lineage is the
    intersection, and trust is the min over that set.
    """
    claimed = set(claimed_source_ids)

    if not claimed:
        # A distiller that emits an assertion with no source IDs is
        # laundering by omission -- reject rather than default to trusted.
        raise MissingLineageError(
            f"assertion {assertion!r} has no declared lineage; "
            "cannot compute trust"
        )

    # Lineage must be a subset of what was actually shown to the model.
    phantom = claimed - prompt_window_ids
    if phantom:
        raise ProvenanceLaunderingError(
            f"assertion cites sources never in prompt window: {sorted(phantom)}"
        )

    missing = claimed - episodic_store.keys()
    if missing:
        raise ProvenanceLaunderingError(
            f"assertion cites unknown episodic ids: {sorted(missing)}"
        )

    source_trusts = [episodic_store[sid].trust for sid in claimed]
    worst = min(source_trusts, key=lambda t: TRUST_ORDER[t])

    # The invariant: derived trust may not exceed min source trust.
    # If a caller tries to force "trusted" over untrusted sources, refuse.
    computed_trust = worst

    return Semantic(
        id=f"sem-{abs(hash(assertion)) % 10**8}",
        content=assertion,
        trust=computed_trust,
        derived_from=sorted(claimed),
    )


def assert_no_laundering(record: Semantic) -> None:
    """Read-time backstop for records written before the invariant existed."""
    if record.trust == "trusted" and record.derived_from:
        # Cannot verify min-trust without the source store here, but a
        # trusted record with declared lineage is suspicious enough to flag.
        raise ProvenanceLaunderingError(
            f"semantic {record.id} claims trusted with lineage "
            f"{record.derived_from}; verify sources before acting"
        )
