# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-label-laundering-through-agent-tool-output-re-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-label-laundering-through-agent-tool-output-re-serialization.warrant.json
# Markdown SHA-256:   6be83189aaefb2c1bf2657b71d2c88d259b94198757b5d46b12628bd0cbf6c2e
# Code AST SHA-256:   caf2200be9ebbdebe683ed6e962743cffd5d4b0069f4b76d186df377cc49baac
# Verified Classes:   TaintLaunderingError, Span, Derivation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting call's argument provenance omits an
    untrusted (DOC) lineage that is reachable through the derivation DAG."""


@dataclass(frozen=True)
class Span:
    span_id: str
    text: str
    provenance: FrozenSet[str]  # e.g. {"DOC"}, {"SYS"}, {"TOOL"}


@dataclass
class Derivation:
    """Harness-computed derivation record. Never populated by the model."""
    output_span: Span
    input_span_ids: tuple


def union_provenance(deriv: Derivation, spans: dict[str, Span]) -> FrozenSet[str]:
    acc = set(deriv.output_span.provenance)
    for sid in deriv.input_span_ids:
        acc |= spans[sid].provenance
    return frozenset(acc)


def authorize_side_effect(
    call_args: dict[str, str],
    derivations: list[Derivation],
    spans: dict[str, Span],
    doc_spans_in_window: list[Span],
    sys_allowlist: set[str],
) -> None:
    # 1. Recompute provenance as union over the derivation DAG.
    reachable: set[str] = set()
    for d in derivations:
        reachable |= union_provenance(d, spans)

    # 2. Carryover detection: any arg value fuzzy-present in a DOC span
    #    inherits DOC taint even if the derivation graph missed it.
    for arg_val in call_args.values():
        for doc in doc_spans_in_window:
            if arg_val and arg_val in doc.text:
                reachable.add("DOC")
                break

    # 3. Capability floor: side-effecting args must be SYS-allowlisted
    #    OR explicitly declassified; DOC taint blocks otherwise.
    if "DOC" in reachable:
        for arg_val in call_args.values():
            if arg_val not in sys_allowlist:
                raise TaintLaunderingError(
                    f"side-effect blocked: arg {arg_val!r} carries DOC lineage "
                    f"reachable={sorted(reachable)}; not in SYS allowlist"
                )
