# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-failure-in-taint-aware-tool-routing-quarantine-bypass-via-derived-context-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-failure-in-taint-aware-tool-routing-quarantine-bypass-via-derived-context-re-entry.warrant.json
# Markdown SHA-256:   c5567d33febaddb3e79410b635e0f79fb646fa9353f7c780f26d402e52896b76
# Code AST SHA-256:   c77c162d059ef13d034aa28350d67e0beefd23e9eda3a1a00e534d05b7fd0af7
# Verified Classes:   TaintLaunderingError, ProvId, Emission, Invocation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when an argument's provenance set is smaller than the union of
    provenance present in the context window that generated it, with no
    intervening declassification event. Indicates a laundering path."""
    pass


@dataclass(frozen=True)
class ProvId:
    origin: str          # e.g. "web_fetch", "operator", "memory:episodic"
    untrusted: bool


@dataclass
class Emission:
    text: str
    context_prov: FrozenSet[ProvId]   # union of provenance in window at gen time


@dataclass
class Invocation:
    tool: str
    args: dict
    arg_prov: FrozenSet[ProvId]        # provenance attached to the argument value
    declassified: bool = False         # operator-signed clearing event


DANGEROUS_SINKS = {"send_email", "http_post", "write_file", "shell_exec"}


def route(inv: Invocation, generating_context: FrozenSet[ProvId]) -> str:
    # Invariant: taint is monotonic under derivation.
    # arg_prov must be a superset of the untrusted origins in generating_context,
    # unless an explicit declassification event occurred.
    context_untrusted = frozenset(p for p in generating_context if p.untrusted)
    if not inv.declassified:
        missing = context_untrusted - inv.arg_prov
        if missing:
            raise TaintLaunderingError(
                f"provenance discontinuity on tool={inv.tool!r}: "
                f"argument claims {sorted(p.origin for p in inv.arg_prov)} "
                f"but generating context held untrusted {sorted(p.origin for p in missing)}; "
                f"no declassification event recorded"
            )

    effective = inv.arg_prov if not inv.declassified else frozenset()
    if inv.tool in DANGEROUS_SINKS and any(p.untrusted for p in effective):
        return "quarantine"
    return "allow"


def memory_write(value: str, prov: FrozenSet[ProvId]) -> dict:
    # Lineage-preserving write: provenance travels with the value.
    return {"value": value, "prov": prov}


def memory_read(record: dict) -> tuple[str, FrozenSet[ProvId]]:
    # Return provenance, never a channel-derived clean label.
    return record["value"], record["prov"]


def guarded_emit(emission: Emission) -> Invocation:
    # A model emission inherits the union of its context provenance.
    # Any argument derived from it must carry that union.
    inherited = frozenset(emission.context_prov)
    if any(p.untrusted for p in inherited):
        # Caller must not strip this; if they do, route() will catch it.
        return Invocation(
            tool="pending",
            args={"text": emission.text},
            arg_prov=inherited,
        )
    return Invocation(tool="pending", args={"text": emission.text}, arg_prov=inherited)
