# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-sandbox-re-enters-the-agent-s-own-context.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-sandbox-re-enters-the-agent-s-own-context.warrant.json
# Markdown SHA-256:   f7012a89abd6776021d5629041c6bdc78635b12aecc1477fefa1338e464dfce0
# Code AST SHA-256:   97904def2fe8bef93d5082019e85cf0e725638d482ba7e8a524be4bde1a59823
# Verified Classes:   TaintDeclassificationError, TaintLabel
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TaintDeclassificationError(RuntimeError):
    """Raised when sandbox output crosses into the reasoning context without a
    valid declassification event, or when a sanitizer attempts to declassify
    based on shape rather than provenance."""
    pass


class TaintLabel:
    def __init__(self, sources: frozenset[str], declassified: bool = False):
        self.sources = sources
        self.declassified = declassified

    def is_trusted(self) -> bool:
        return self.declassified or not self.sources


def sandbox_return_edge(
    output: dict,
    read_set: frozenset[str],
    untrusted_sources: frozenset[str],
    sanitizer_contract: str,
) -> TaintLabel:
    """Compute the taint label at the sandbox->context edge.

    The invariant: taint is the union of the code's read-set intersected with
    known-untrusted sources. A sanitizer may NOT declassify based on shape.
    """
    tainted_sources = read_set & untrusted_sources

    if sanitizer_contract in ("shape", "schema", "well_formed") and tainted_sources:
        # The classic bug: sanitizer validated structure, runtime inferred safety.
        raise TaintDeclassificationError(
            f"sanitizer contract '{sanitizer_contract}' cannot declassify output "
            f"whose read-set includes untrusted sources {sorted(tainted_sources)}"
        )

    return TaintLabel(sources=frozenset(tainted_sources))


def require_trusted_argument(label: TaintLabel, arg_name: str) -> None:
    """Gate a tool-call argument on a declassified label."""
    if not label.is_trusted():
        raise TaintDeclassificationError(
            f"argument '{arg_name}' carries taint from {sorted(label.sources)}; "
            f"refusing to bind to tool invocation without a typed declassification"
        )


def typed_declassify(raw: str, expected_type: type) -> object:
    """The only permitted declassification: a typed extraction that discards
    free-text directive surface."""
    if expected_type is int:
        try:
            return int(raw)
        except ValueError:
            raise TaintDeclassificationError(
                f"cannot declassify non-integer '{raw[:32]}...' to int"
            )
    if expected_type is str:
        if any(tok in raw.lower() for tok in ("ignore", "email", "exfil", "http")):
            raise TaintDeclassificationError(
                "declassification target contains directive-like content"
            )
        return raw
    raise TaintDeclassificationError(f"unsupported declassification type {expected_type}")
