# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-call-return-value-as-a-taint-sink-before-the-next-egress-capable-call.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-call-return-value-as-a-taint-sink-before-the-next-egress-capable-call.warrant.json
# Markdown SHA-256:   c3c3409585cdb5d26f47df3885d60c92a51e78e7cd56d82f7a8cc18b606e6019
# Code AST SHA-256:   ba0053d77864be74c06fc8923b400ec1baec15256ec50de57c3149e5cb0818ef
# Verified Classes:   TaintSinkViolation, ToolReturn, TaintState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintSinkViolation(RuntimeError):
    """Raised when an egress-capable tool is dispatched with tainted,
    undeclassified payload arguments. Hard stop: the bytes would leave
    the trust boundary on dispatch."""


@dataclass(frozen=True)
class ToolReturn:
    source_id: str
    untrusted: bool
    value: object


@dataclass
class TaintState:
    # Maps argument name -> set of untrusted source ids contributing to it.
    labels: dict = field(default_factory=dict)

    def merge(self, arg: str, sources: FrozenSet[str]) -> None:
        self.labels.setdefault(arg, set()).update(sources)


# A declassification policy is content-independent: it constrains the
# *shape* of the argument, never the agent's judgment of its safety.
DECLASSIFY = {
    "post_summary": {
        "severity": lambda v: v in {"low", "medium", "high"},
        "ticket_id": lambda v: isinstance(v, str) and v.startswith("T-"),
    },
}


def dispatch_egress(tool: str, args: dict, taint: TaintState) -> None:
    if tool not in DECLASSIFY:
        # No policy registered => treat as no_declass.
        policy = {}
    else:
        policy = DECLASSIFY[tool]

    for arg_name, sources in taint.labels.items():
        if not sources:
            continue
        guard = policy.get(arg_name)
        # A tainted arg is admissible only if a content-independent
        # declassification guard exists AND admits the value.
        if guard is None or not guard(args.get(arg_name)):
            raise TaintSinkViolation(
                f"egress tool {tool!r} dispatched with tainted arg "
                f"{arg_name!r} from sources {sorted(sources)}; "
                f"no valid declassification policy. Refusing to send."
            )


def handle_ticket_flow(fetch_return: ToolReturn, post_tool: str,
                       post_args: dict) -> None:
    taint = TaintState()
    if fetch_return.untrusted:
        # Every argument the planner derived from the return inherits taint.
        for arg_name in post_args:
            taint.merge(arg_name, frozenset({fetch_return.source_id}))
    dispatch_egress(post_tool, post_args, taint)


# Example: attacker embeds a token in a "reference" the agent copies into
# the free-text body of an allowlisted telemetry post.
try:
    handle_ticket_flow(
        fetch_return=ToolReturn("ticket:T-4471", True, "..."),
        post_tool="post_summary",
        post_args={"body": "ref https://collector.example/x?d=TOKEN"},
    )
except TaintSinkViolation as e:
    print("blocked:", e)  # body has no declass guard -> hard stop
