# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundering-when-retrieved-context-is-re-summarized-across-a-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-provenance-laundering-when-retrieved-context-is-re-summarized-across-a-trust-boundary.warrant.json
# Markdown SHA-256:   26ae4ad420251ca146fce770ac12d9153cb4de4b4245261b0afd4bb63f34bf32
# Code AST SHA-256:   0d24327bb3d7bbcb35e9fd1c9618e1bd79113aaab8a881d7a5937413f0e648e5
# Verified Classes:   ProvenanceLaunderingError, UnresolvableProvenanceError, Fragment, DerivedFragment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

# Total order of trust tiers; lower rank = stronger authority.
TIER_RANK = {"system": 0, "user": 1, "memory": 2, "peer": 3, "tool": 4}
INSTRUCTION_ADMISSIBLE = {"system", "user", "memory"}


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived fragment's tier exceeds the meet of its sources."""


class UnresolvableProvenanceError(RuntimeError):
    """Raised when a transform cannot attest the fragments it drew on."""


@dataclass(frozen=True)
class Fragment:
    fragment_id: str
    tier: str
    text: str


@dataclass
class DerivedFragment:
    text: str
    tier: str
    derivation_set: tuple[str, ...]


def meet_tier(sources: Iterable[Fragment]) -> str:
    used = list(sources)
    if not used:
        raise UnresolvableProvenanceError("derivation_set is empty; cannot compute meet")
    for f in used:
        if f.tier not in TIER_RANK:
            raise UnresolvableProvenanceError(f"unknown tier on fragment {f.fragment_id}")
    weakest = max(used, key=lambda f: TIER_RANK[f.tier])
    return weakest.tier


def assemble_derived(
    text: str,
    claimed_source_ids: tuple[str, ...],
    registry: dict[str, Fragment],
) -> DerivedFragment:
    if not claimed_source_ids:
        raise UnresolvableProvenanceError("transform must attest at least one source")
    try:
        sources = [registry[sid] for sid in claimed_source_ids]
    except KeyError as exc:
        raise UnresolvableProvenanceError(f"attested source not in registry: {exc}") from exc

    derived_tier = meet_tier(sources)
    # Invariant: the derived fragment may never be assigned a tier stronger
    # than the weakest source it drew on. The stage's own authority is irrelevant.
    return DerivedFragment(text=text, tier=derived_tier, derivation_set=claimed_source_ids)


def admit_as_instruction(frag: DerivedFragment, registry: dict[str, Fragment]) -> bool:
    if frag.tier not in INSTRUCTION_ADMISSIBLE:
        return False
    # Re-verify the meet at admission time; a lying transform is caught here if
    # the attested set does not actually support the claimed tier.
    sources = [registry[sid] for sid in frag.derivation_set]
    recomputed = meet_tier(sources)
    if TIER_RANK[frag.tier] < TIER_RANK[recomputed]:
        raise ProvenanceLaunderingError(
            f"fragment claims tier {frag.tier!r} but meet of sources is {recomputed!r}"
        )
    return True


def compact_and_write(
    summary_text: str,
    claimed_source_ids: tuple[str, ...],
    registry: dict[str, Fragment],
) -> DerivedFragment:
    derived = assemble_derived(summary_text, claimed_source_ids, registry)
    # A summarizer that "preserves actionable directives" must not upgrade tier.
    if "pre-approved" in derived.text.lower() and derived.tier not in INSTRUCTION_ADMISSIBLE:
        # Content is retained as context but flagged non-admissible; do not raise,
        # because the summary is still useful data — but it must never execute.
        derived = DerivedFragment(
            text=derived.text,
            tier="unverified_derived",
            derivation_set=derived.derivation_set,
        )
    return derived
