# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-capability-tokens-as-non-transitive-across-output-sanitization-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-capability-tokens-as-non-transitive-across-output-sanitization-boundaries.warrant.json
# Markdown SHA-256:   a22a387f185653bd3b347ef5077e5a6a510fbe7ff5bcefb6df29cf043beb83a0
# Code AST SHA-256:   5243ea85f205dc333b901fe3e61cc3f51d9246c118999e264c67baef760f27a8
# Verified Classes:   ScopeLaunderingError, CapabilityToken, ToolOutput
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeLaunderingError(RuntimeError):
    """Raised when a tool output from one capability scope attempts to
    authorize an action under a disjoint capability scope without an
    out-of-band re-authorization token."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    scope: str          # e.g. "read", "write"
    resource: str       # e.g. "docs", "records"
    ttl_s: int


@dataclass(frozen=True)
class ToolOutput:
    tool: str
    origin_token: CapabilityToken
    sanitized_body: str
    # provenance is structural, not textual; body is never trusted to
    # describe its own authority


def authorize_transition(
    origin: ToolOutput,
    target_token: CapabilityToken,
    reauth_token: str | None,
    controller_minted: FrozenSet[str],
) -> None:
    """Enforce the non-transitivity invariant across the sanitization boundary.

    Same-scope transitions pass. Scope-disjoint transitions require a
    re-authorization token minted by the controller, which the origin
    output could not have produced.
    """
    same_scope = (
        origin.origin_token.scope == target_token.scope
        and origin.origin_token.resource == target_token.resource
    )
    if same_scope:
        return

    if reauth_token is None:
        raise ScopeLaunderingError(
            f"scope-disjoint transition blocked: origin="
            f"({origin.origin_token.scope}:{origin.origin_token.resource}) "
            f"target=({target_token.scope}:{target_token.resource}) "
            f"tool={origin.tool} — no re-authorization token supplied"
        )

    if reauth_token not in controller_minted:
        raise ScopeLaunderingError(
            f"re-authorization token {reauth_token!r} was not minted by the "
            f"controller; agent-originated justifications are not valid "
            f"across the sanitization boundary"
        )


def guarded_invoke(
    origin: ToolOutput,
    target_token: CapabilityToken,
    reauth_token: str | None,
    controller_minted: FrozenSet[str],
    invoke_fn,
):
    authorize_transition(origin, target_token, reauth_token, controller_minted)
    return invoke_fn(target_token)
