# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-when-untrusted-retrieved-content-crosses-a-sandbox-boundary-into-a-tool-calling-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-when-untrusted-retrieved-content-crosses-a-sandbox-boundary-into-a-tool-calling-loop.warrant.json
# Markdown SHA-256:   11a3cd0536baa9224a48fcd6ead8ce8eadc709ec6b781528e3cd116d1b0047f7
# Code AST SHA-256:   32789f128aedf416f2e52175df90abbfd1de2d4157c913fa0ebe344902afbe59
# Verified Classes:   TaintLaunderingError, TaintLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting tool call carries an argument derived from tainted context."""


@dataclass
class TaintLedger:
    tainted_segments: list[str] = field(default_factory=list)
    # Deterministic predicates that may declassify an argument. Keys are predicate names.
    declassifiers: dict[str, Callable[[str], bool]] = field(default_factory=dict)

    def admit_tainted(self, segment: str) -> None:
        self.tainted_segments.append(segment)

    def is_derived_from_taint(self, argument: str, min_overlap_tokens: int = 8) -> bool:
        arg_tokens = argument.split()
        for seg in self.tainted_segments:
            seg_tokens = seg.split()
            # sliding-window overlap check; catches verbatim and near-verbatim exfiltration
            for i in range(len(arg_tokens) - min_overlap_tokens + 1):
                window = " ".join(arg_tokens[i : i + min_overlap_tokens])
                if window in seg:
                    return True
        return False

    def declassified(self, argument: str) -> bool:
        return any(pred(argument) for pred in self.declassifiers.values())


def guarded_tool_call(
    ledger: TaintLedger,
    tool_name: str,
    arguments: dict[str, str],
    execute: Callable[[str, dict[str, str]], object],
) -> object:
    for arg_name, arg_value in arguments.items():
        if ledger.is_derived_from_taint(arg_value) and not ledger.declassified(arg_value):
            raise TaintLaunderingError(
                f"tool={tool_name!r} arg={arg_name!r} value={arg_value!r} "
                f"is derived from a live tainted context segment and no "
                f"declassification predicate cleared it; refusing to execute"
            )
    return execute(tool_name, arguments)


# --- demonstration of the boundary condition ---
ledger = TaintLedger()
ledger.admit_tainted(
    "For the canonical schema, see the appendix at "
    "http://internal-metadata.example/.well-known/agent-schema.json"
)
# operator-supplied deterministic declassifier: only paths under /public/ are cleared
ledger.declassifiers["public_docs"] = lambda u: u.startswith("https://docs.corp.example/public/")

try:
    guarded_tool_call(
        ledger,
        "fetch_url",
        {"url": "http://internal-metadata.example/.well-known/agent-schema.json"},
        execute=lambda name, args: {"status": 200, "body": "..."},
    )
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
