# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-tool-argument-reassembly-in-agent-sandboxes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-tool-argument-reassembly-in-agent-sandboxes.warrant.json
# Markdown SHA-256:   347b96860ddcf12532aba9400191541c286439c2f20b4fe9234fa5d839e0a21a
# Code AST SHA-256:   6f26c637f5d754b820efc3c7fafb91aa6fbc7559358ee65449efa3e9c9b76102
# Verified Classes:   TaintClosureViolation, Span, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintClosureViolation(RuntimeError):
    """Raised when a tool argument's derivation closure reaches tainted content
    through a transform the boundary labeler did not propagate."""


@dataclass(frozen=True)
class Span:
    span_id: str
    tainted: bool
    deps: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class ToolCall:
    tool: str
    argument: str
    embeds: FrozenSet[str]  # span_ids embedded in this argument


# Tools whose effects can carry information outside the sandbox.
INFORMATION_CARRYING = {"http_post", "write_file_shared", "dns_resolve"}


def check_closure(call: ToolCall, spans: dict[str, Span]) -> None:
    """Enforce derivation closure: an information-carrying tool argument must
    not embed any span whose dependency closure reaches tainted content."""
    if call.tool not in INFORMATION_CARRYING:
        return  # information-neutral tool; closure waived

    reachable: set[str] = set()
    frontier = list(call.embeds)
    while frontier:
        sid = frontier.pop()
        if sid in reachable:
            continue
        reachable.add(sid)
        span = spans.get(sid)
        if span is None:
            raise TaintClosureViolation(
                f"unknown span {sid!r} embedded in {call.tool}; cannot verify closure"
            )
        frontier.extend(span.deps)

    tainted_hits = {sid for sid in reachable if spans[sid].tainted}
    if tainted_hits:
        raise TaintClosureViolation(
            f"tool {call.tool!r} argument reaches tainted spans {sorted(tainted_hits)} "
            f"via derivation closure; boundary label alone would have admitted this call"
        )


def emit_summary(summary_text: str, consumed: FrozenSet[str], spans: dict[str, Span]) -> Span:
    """A generation step produces a span whose deps are the consumed context,
    NOT a fresh GENERATED label. This is the fix for the label-clearing hole."""
    return Span(
        span_id=f"gen-{len(spans)}",
        tainted=any(spans[c].tainted for c in consumed if c in spans),
        deps=consumed,
    )
