# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-before-a-downstream-tool-call-inherits-tainted-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-before-a-downstream-tool-call-inherits-tainted-authority.warrant.json
# Markdown SHA-256:   b5f7592814819cd8dcf1d36b11c41f1d26cd90ff9b2bc9afb92fe44f4215be4b
# Code AST SHA-256:   eedf7e5a663b52093a3ae690b4ca6a16ebdb06daf660b08e40f4c85ca45f3701
# Verified Classes:   Trust, TaintLaunderingError, ProvenanceSpan, ToolResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class Trust(Enum):
    UNTRUSTED = 0
    TRUSTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a label upgrade would let untrusted authority reach a side-effecting call."""


@dataclass(frozen=True)
class ProvenanceSpan:
    span_id: str
    trust: Trust
    instruction_capable: bool  # can this span's content encode imperative text?


@dataclass
class ToolResult:
    producer_trust: Trust
    inputs: FrozenSet[ProvenanceSpan]
    output_instruction_capable: bool
    effective_provenance: FrozenSet[ProvenanceSpan] = field(default_factory=frozenset)


# Transformations whose output range cannot encode instructions may upgrade trust.
INSTRUCTION_INCAPABLE_TOOLS = {"schema_validator", "hash", "length_counter"}


def compute_effective_provenance(
    tool_name: str,
    producer_trust: Trust,
    inputs: FrozenSet[ProvenanceSpan],
    output_instruction_capable: bool,
) -> FrozenSet[ProvenanceSpan]:
    """Meet over the transitive closure of contributing spans.

    The output's trust is the minimum of the producer's trust and every input's
    trust — UNLESS the tool is provably instruction-incapable, in which case the
    input taint is destroyed and only the producer's trust survives.
    """
    if tool_name in INSTRUCTION_INCAPABLE_TOOLS and not output_instruction_capable:
        # Legitimate upgrade: output alphabet cannot carry injected imperatives.
        return frozenset({ProvenanceSpan(f"{tool_name}:out", producer_trust, False)})

    # Natural-language-capable transformation: inherit the full tainted closure.
    inherited = set(inputs)
    inherited.add(ProvenanceSpan(f"{tool_name}:out", producer_trust, output_instruction_capable))
    return frozenset(inherited)


def effective_trust(spans: FrozenSet[ProvenanceSpan]) -> Trust:
    if any(s.trust is Trust.UNTRUSTED for s in spans):
        return Trust.UNTRUSTED
    return Trust.TRUSTED


def authorize_side_effecting_call(
    tool_name: str,
    argument_spans: FrozenSet[ProvenanceSpan],
    declassified: bool,
) -> None:
    """Gate a side-effecting tool call on the effective trust of its argument spans."""
    trust = effective_trust(argument_spans)
    if trust is Trust.UNTRUSTED and not declassified:
        tainted = sorted(s.span_id for s in argument_spans if s.trust is Trust.UNTRUSTED)
        raise TaintLaunderingError(
            f"Refusing side-effecting call to {tool_name!r}: arguments influenced by "
            f"untrusted spans {tainted} without explicit declassification. "
            f"Laundering chain must be surfaced to the orchestrator."
        )


# --- Demonstration of the observed failure ---
external_doc = ProvenanceSpan("retrieval:doc42", Trust.UNTRUSTED, True)

# Trusted summarizer over untrusted input: natural-language-capable, so it inherits taint.
summary_spans = compute_effective_provenance(
    tool_name="summarize",
    producer_trust=Trust.TRUSTED,
    inputs=frozenset({external_doc}),
    output_instruction_capable=True,
)

# The next call's arguments were shaped by the summary. The meet rule catches it:
authorize_side_effecting_call("read_env", summary_spans, declassified=False)
# -> raises TaintLaunderingError, as required.

# A validator would have legitimately upgraded:
validator_spans = compute_effective_provenance(
    tool_name="schema_validator",
    producer_trust=Trust.TRUSTED,
    inputs=frozenset({external_doc}),
    output_instruction_capable=False,
)
authorize_side_effecting_call("read_env", validator_spans, declassified=False)  # passes
