# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-provenance-aware-retrieval-pipeline-from-silently-degrading-into-a-prompt-injection-conduit.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-provenance-aware-retrieval-pipeline-from-silently-degrading-into-a-prompt-injection-conduit.warrant.json
# Markdown SHA-256:   1a94b0f77ae1c16c9f144fef1e4ef1f3e78640e38e6d10aa45d0b9ecbc71e009
# Code AST SHA-256:   5aa23b1e8832af24a6371249c73245f71f6554b82ff5b83283cfbe1fa7d4874f
# Verified Classes:   TrustLevel, Span, ProvenanceLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TrustLevel(IntEnum):
    UNTRUSTED = 0
    DERIVED = 1
    TRUSTED = 2


@dataclass(frozen=True)
class Span:
    span_id: str
    origin_id: str          # immutable document/source identity
    content: str
    trust: TrustLevel
    injection_flag: bool = False
    derived_from: tuple[str, ...] = field(default_factory=tuple)


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a transformation mints trust it is not entitled to."""


def derive(parents: Iterable[Span], new_id: str, new_content: str) -> Span:
    """Create a derived span whose trust is the minimum of its parents.

    Invariant: trust(derived) <= min(trust(p) for p in parents).
    A derived span inherits any injection flag from its lineage.
    """
    parents = tuple(parents)
    if not parents:
        raise ProvenanceLaunderingError(
            f"span {new_id}: derivation with no parents cannot be assigned trust"
        )
    min_trust = min(p.trust for p in parents)
    inherited_flag = any(p.injection_flag for p in parents)
    origin = parents[0].origin_id
    if any(p.origin_id != origin for p in parents):
        # Cross-origin derivation is allowed only at UNTRUSTED.
        min_trust = min(min_trust, TrustLevel.UNTRUSTED)
    return Span(
        span_id=new_id,
        origin_id=origin,
        content=new_content,
        trust=min_trust,
        injection_flag=inherited_flag,
        derived_from=tuple(p.span_id for p in parents),
    )


def assemble(span: Span, claimed_trust: TrustLevel) -> Span:
    """Context-assembly gate: reject any span whose claimed trust exceeds lineage."""
    if claimed_trust > span.trust:
        raise ProvenanceLaunderingError(
            f"span {span.span_id}: claimed trust {claimed_trust.name} exceeds "
            f"lineage-derived trust {span.trust.name} "
            f"(derived_from={span.derived_from})"
        )
    if span.injection_flag and claimed_trust >= TrustLevel.TRUSTED:
        raise ProvenanceLaunderingError(
            f"span {span.span_id}: flagged span cannot be assembled as trusted; "
            f"quarantine required"
        )
    return span
