# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-its-delegated-capability-scope-from-tool-output-instead-of-the-signed-warrant-scope-laundering-across-the-aai.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-its-delegated-capability-scope-from-tool-output-instead-of-the-signed-warrant-scope-laundering-across-the-aai.warrant.json
# Markdown SHA-256:   163cb1f1bf0e442f30639560076a1a9e1bb0f8eee823dd72877a325b1e4a72b1
# Code AST SHA-256:   1b551fee30a0e5134100ac00c969b953e06c692229273d38e62e62f50b4a61da
# Verified Classes:   ScopeLaunderingError, Warrant, AgentScope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeLaunderingError(RuntimeError):
    """Raised when an agent's authorization scope diverges from its signed warrant."""
    pass


import hmac
import hashlib


class Warrant:
    """Immutable, attenuable capability token. Caveats can only be added (narrowing)."""

    def __init__(self, caveats, signature):
        self._caveats = frozenset(caveats)
        self._signature = signature

    def caveats(self):
        return frozenset(self._caveats)

    def verify(self, secret):
        expected = hmac.new(
            secret, b"|".join(sorted(self._caveats)), hashlib.sha256
        ).hexdigest()
        if not hmac.compare_digest(expected, self._signature):
            raise ScopeLaunderingError("warrant signature invalid")


class AgentScope:
    """Authorization state. Writable ONLY by re-parsing the signed warrant."""

    def __init__(self, warrant, secret):
        self._warrant = warrant
        self._secret = secret
        self._scope = None
        self.rederive()

    def rederive(self):
        # The ONLY legitimate writer of scope: the warrant itself.
        self._warrant.verify(self._secret)
        self._scope = frozenset(self._warrant.caveats())

    def authorize(self, capability):
        # Re-derive on every decision; never trust a cached belief.
        self.rederive()
        if capability not in self._scope:
            # Contraction, not rerouting: caller must re-plan within remainder.
            self._scope = self._scope - {capability}
            raise ScopeLaunderingError(
                f"capability {capability!r} outside warrant closure; "
                f"scope contracted to {sorted(self._scope)}"
            )
        return True


def ingest_tool_output(scope: AgentScope, payload: dict):
    """Tool output is inert data. Capability-shaped fields are quarantined."""
    if any(k in payload for k in ("capabilities", "tools", "scopes", "permissions")):
        # Do NOT merge. This is the boundary. Refuse to let it touch scope.
        raise ScopeLaunderingError(
            "tool output contains capability-shaped fields; "
            "refusing to mutate authorization state from observation"
        )
    return payload


def guarded_call(scope: AgentScope, capability: str, fn, *args):
    scope.authorize(capability)  # raises ScopeLaunderingError on divergence
    return fn(*args)
