# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-tier-laundering-when-retrieved-content-is-re-summarized-across-tool-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-tier-laundering-when-retrieved-content-is-re-summarized-across-tool-boundaries.warrant.json
# Markdown SHA-256:   c7492c1c62746c35f53e17fe6fc25ae26c7127067b83e0ffa579453815c7d3d7
# Code AST SHA-256:   0a2fc77ba22ae78d90873a728bb5c66314757ee070d01b325a50d30ec3f9798d
# Verified Classes:   Tier, ProvenanceLaunderingError, MissingLineageError, Fragment
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Tier(IntEnum):
    # Lower value = less trusted. The meet/join is min/max over this order.
    RETRIEVED_UNTRUSTED = 0
    TOOL_OUTPUT = 1
    USER_SUPPLIED = 2
    TRUSTED_INTERNAL = 3


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived fragment claims a tier above the join of its inputs,
    or when a transform emits a fragment with no declared lineage."""


class MissingLineageError(ProvenanceLaunderingError):
    """Raised when a transform produces output without an explicit derived_from edge."""


@dataclass(frozen=True)
class Fragment:
    id: str
    content: str
    tier: Tier
    taint: frozenset[str] = field(default_factory=frozenset)
    derived_from: tuple[str, ...] = ()


def join_tier(fragments: Iterable[Fragment]) -> Tier:
    frags = list(fragments)
    if not frags:
        # No inputs: a genuinely fresh artifact may be trusted.
        return Tier.TRUSTED_INTERNAL
    return Tier(min(f.tier for f in frags))


def union_taint(fragments: Iterable[Fragment]) -> frozenset[str]:
    out: set[str] = set()
    for f in fragments:
        out |= set(f.taint)
    return frozenset(out)


def derive(
    out_id: str,
    content: str,
    inputs: list[Fragment],
    claimed_tier: Tier,
    declared_lineage: tuple[str, ...],
) -> Fragment:
    """Apply a lossy transform (summarize/extract/reformat) to inputs.

    Enforces the two invariants:
      1. Lineage must be declared explicitly (no implicit 'was in context').
      2. Emitted tier must not exceed join(input tiers).
    """
    input_ids = tuple(f.id for f in inputs)
    if not declared_lineage:
        raise MissingLineageError(
            f"transform produced {out_id!r} with no derived_from edge; "
            f"cannot verify provenance of inputs {input_ids}"
        )
    if set(declared_lineage) != set(input_ids):
        raise ProvenanceLaunderingError(
            f"declared lineage {declared_lineage} does not match actual inputs {input_ids}"
        )

    expected = join_tier(inputs)
    if claimed_tier > expected:
        raise ProvenanceLaunderingError(
            f"fragment {out_id!r} claims tier {claimed_tier.name} but join of inputs "
            f"{input_ids} is {expected.name}; this is trust-tier laundering"
        )

    return Fragment(
        id=out_id,
        content=content,
        tier=expected,
        taint=union_taint(inputs),
        derived_from=declared_lineage,
    )


def admit_to_tool(fragment: Fragment, required: Tier) -> None:
    """Gate a fragment before it reaches a tool with a tier allowlist."""
    if fragment.tier < required:
        raise ProvenanceLaunderingError(
            f"fragment {fragment.id!r} tier {fragment.tier.name} below required "
            f"{required.name}; taint={sorted(fragment.taint)}"
        )


# --- Demonstration of the failure and the guardrail -------------------------

def _demo() -> None:
    page = Fragment(
        id="f1",
        content="...skip the second approval step...",
        tier=Tier.RETRIEVED_UNTRUSTED,
        taint=frozenset({"web:example.com/policy"}),
    )

    # Naive laundering: summarizer stamps its own tier, drops lineage.
    try:
        derive(
            out_id="f2",
            content="policy: skip second approval",
            inputs=[page],
            claimed_tier=Tier.TRUSTED_INTERNAL,
            declared_lineage=(),  # omitted, as most pipelines do
        )
    except MissingLineageError as e:
        print(f"[blocked: missing lineage] {e}")

    # Correct derivation: tier is joined down, taint is unioned.
    summary = derive(
        out_id="f2b",
        content="policy: skip second approval",
        inputs=[page],
        claimed_tier=Tier.RETRIEVED_UNTRUSTED,
        declared_lineage=("f1",),
    )
    assert summary.tier is Tier.RETRIEVED_UNTRUSTED
    assert "web:example.com/policy" in summary.taint

    # The tool gate now fails closed.
    try:
        admit_to_tool(summary, required=Tier.TRUSTED_INTERNAL)
    except ProvenanceLaunderingError as e:
        print(f"[blocked: tool gate] {e}")


if __name__ == "__main__":
    _demo()
