# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-attenuation-replay-across-mcp-capability-token-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-attenuation-replay-across-mcp-capability-token-boundaries.warrant.json
# Markdown SHA-256:   734ca079524bfb0e111517dffa2014637c3238582280c3a193e451e8bb18b73c
# Code AST SHA-256:   27b779cab66a3b1010db470edf2a0a29c6d950df8251d219259ab7b94df33c3d
# Verified Classes:   CapabilityReplayError, CapabilityToken, TokenService, McpSandbox
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from time import monotonic


class CapabilityReplayError(RuntimeError):
    """Raised when a tool-call admission presents a token whose ancestry is not live."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    parent_id: str | None
    scopes: frozenset[str]
    issued_at: float
    expiry: float


class TokenService:
    def __init__(self) -> None:
        self._tokens: dict[str, CapabilityToken] = {}
        self._revoked: set[str] = set()

    def mint(
        self,
        parent: CapabilityToken | None,
        scopes: frozenset[str],
        requested_ttl: float,
        now: float,
    ) -> CapabilityToken:
        if parent is not None:
            if not scopes.issubset(parent.scopes):
                raise CapabilityReplayError(
                    f"scope escalation: {scopes} not subset of {parent.scopes}"
                )
            # Invariant (1): TTL monotonicity under derivation.
            expiry = min(parent.expiry, now + requested_ttl)
        else:
            expiry = now + requested_ttl
        tok = CapabilityToken(
            token_id=f"tok-{len(self._tokens):04d}",
            parent_id=parent.token_id if parent else None,
            scopes=scopes,
            issued_at=now,
            expiry=expiry,
        )
        self._tokens[tok.token_id] = tok
        return tok

    def revoke(self, token_id: str) -> None:
        # Invariant (3): cascade is enforced at admission, not here, but we
        # record the root so the ancestry walk can see it.
        self._revoked.add(token_id)

    def ancestry_is_live(self, token: CapabilityToken, now: float) -> None:
        # Invariant (2): live-chain validation at enforcement.
        cur: CapabilityToken | None = token
        seen: set[str] = set()
        while cur is not None:
            if cur.token_id in seen:
                raise CapabilityReplayError(f"cycle in ancestry at {cur.token_id}")
            seen.add(cur.token_id)
            if cur.token_id in self._revoked:
                raise CapabilityReplayError(
                    f"ancestor {cur.token_id} revoked; token {token.token_id} is dead"
                )
            if cur.expiry <= now:
                raise CapabilityReplayError(
                    f"ancestor {cur.token_id} expired at {cur.expiry}; now={now}"
                )
            cur = self._tokens.get(cur.parent_id) if cur.parent_id else None


class McpSandbox:
    def __init__(self, service: TokenService) -> None:
        self.service = service

    def admit(self, token: CapabilityToken, required_scope: str, now: float) -> None:
        if required_scope not in token.scopes:
            raise CapabilityReplayError(
                f"scope {required_scope} absent from {token.token_id}"
            )
        self.service.ancestry_is_live(token, now)


def demo() -> None:
    svc = TokenService()
    t0 = svc.mint(None, frozenset({"fs:read:/sandbox", "net:fetch:api.internal"}), 60.0, now=0.0)
    t1 = svc.mint(t0, frozenset({"fs:read:/sandbox/inputs"}), 600.0, now=1.0)
    # t1.expiry is clamped to t0.expiry == 60.0, not 601.0
    assert t1.expiry == 60.0, "TTL monotonicity violated"

    sandbox = McpSandbox(svc)
    sandbox.admit(t1, "fs:read:/sandbox/inputs", now=30.0)  # ok

    svc.revoke(t0.token_id)  # orchestrator retires the root
    try:
        sandbox.admit(t1, "fs:read:/sandbox/inputs", now=31.0)
    except CapabilityReplayError as exc:
        print("replay blocked:", exc)
    else:
        raise CapabilityReplayError("ancestry walk failed to catch revoked root")


if __name__ == "__main__":
    demo()
