# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-escape-its-tool-allowlist-when-a-tool-result-re-enters-the-planner-as-a-new-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-escape-its-tool-allowlist-when-a-tool-result-re-enters-the-planner-as-a-new-turn.warrant.json
# Markdown SHA-256:   cca0cfec380d1ef699d08473057011e00a9be876508004e029db44f9dd88db9b
# Code AST SHA-256:   71bd219119e3e3ca98d362928966dc849d42fe62ea14625434e7e0fd6dd60558
# Verified Classes:   CapabilityEscapeError, ToolCall, ScopeGrant, ProvenanceGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Iterable

class CapabilityEscapeError(RuntimeError):
    """Raised when a tool call's arguments are provenance-tainted by an
    untrusted source and the call crosses a scope boundary that the tainting
    tool was not authorized to influence."""


@dataclass(frozen=True)
class ToolCall:
    tool: str
    args: dict
    # provenance: map of arg name -> frozenset of source labels that
    # contributed to the argument's value (e.g. {"untrusted:filesystem"}).
    provenance: dict


@dataclass(frozen=True)
class ScopeGrant:
    tool: str
    # predicate over resolved args; returns True if the call is in-scope.
    predicate: Callable[[dict], bool]
    # scopes this tool's *output* is permitted to influence. If a downstream
    # call's scope is not in this set, taint from this tool must not reach it.
    output_influence: frozenset


class ProvenanceGate:
    def __init__(self, grants: Iterable[ScopeGrant]):
        self._grants = {g.tool: g for g in grants}

    def authorize(self, call: ToolCall, taint_origins: dict[str, str]) -> None:
        grant = self._grants.get(call.tool)
        if grant is None:
            raise CapabilityEscapeError(f"tool {call.tool!r} not allowlisted")

        # Primary control: argument-granular scope predicate.
        if not grant.predicate(call.args):
            raise CapabilityEscapeError(
                f"args for {call.tool!r} outside granted scope: {call.args!r}"
            )

        # Secondary control: provenance re-authorization.
        for arg_name, sources in call.provenance.items():
            for src in sources:
                if not src.startswith("untrusted:"):
                    continue
                origin_tool = taint_origins.get(src)
                if origin_tool is None:
                    raise CapabilityEscapeError(
                        f"unresolved taint origin {src!r} on {call.tool}.{arg_name}"
                    )
                origin_grant = self._grants[origin_tool]
                if call.tool not in origin_grant.output_influence:
                    raise CapabilityEscapeError(
                        f"taint from {origin_tool!r} ({src}) reached "
                        f"{call.tool}.{arg_name} outside its influence set"
                    )


def demo() -> None:
    grants = [
        ScopeGrant(
            tool="read_file",
            predicate=lambda a: a["path"].startswith("/data/tickets/"),
            output_influence=frozenset({"summarize", "read_file"}),
        ),
        ScopeGrant(
            tool="write_file",
            predicate=lambda a: a["path"].startswith("/data/out/"),
            output_influence=frozenset(),
        ),
    ]
    gate = ProvenanceGate(grants)
    taint_origins = {"untrusted:filesystem": "read_file"}

    # Step 2: benign read, in scope, no taint.
    gate.authorize(
        ToolCall("read_file", {"path": "/data/tickets/0042.txt"}, {}),
        taint_origins,
    )

    # Step 4: credential read. Path is outside scope -> primary control fires.
    try:
        gate.authorize(
            ToolCall(
                "read_file",
                {"path": "/etc/agent/credentials.env"},
                {"path": frozenset({"untrusted:filesystem"})},
            ),
            taint_origins,
        )
    except CapabilityEscapeError as e:
        print(f"blocked (scope): {e}")

    # Variant: scope is broad enough to admit the path, so the primary control
    # passes; the provenance control is what stops the escape.
    broad = [
        ScopeGrant(
            tool="read_file",
            predicate=lambda a: True,  # coarse capability, the enabling condition
            output_influence=frozenset({"summarize"}),
        ),
        ScopeGrant(
            tool="write_file",
            predicate=lambda a: a["path"].startswith("/data/out/"),
            output_influence=frozenset(),
        ),
    ]
    gate2 = ProvenanceGate(broad)
    try:
        gate2.authorize(
            ToolCall(
                "write_file",
                {"path": "/data/out/summary.md", "content": "token=..."},
                {"content": frozenset({"untrusted:filesystem"})},
            ),
            taint_origins,
        )
    except CapabilityEscapeError as e:
        print(f"blocked (provenance): {e}")


if __name__ == "__main__":
    demo()
