# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-outlived-its-consent-grant-in-aaif-per-tool-scoping.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-outlived-its-consent-grant-in-aaif-per-tool-scoping.warrant.json
# Markdown SHA-256:   c1120410a2107b5b3454cde0151f53df743ff89a64c3f19fb5e5f050ed587a3a
# Code AST SHA-256:   f26d11086c37b55a062434328d1f1f1378837a67390e0f518925aafe61849c69
# Verified Classes:   StaleConsentGrant, ConsentGrant, DelegatedToken, GrantStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class StaleConsentGrant(RuntimeError):
    """Raised when a delegated token's embedded grant snapshot no longer
    matches the grant store's current state. Terminal: do NOT retry with
    the same token, and do NOT re-mint from cached orchestrator state."""


@dataclass
class ConsentGrant:
    grant_id: str
    version: int
    scopes: dict[str, str]  # scope_name -> resource_binding
    revoked: bool = False

    def digest(self) -> str:
        payload = f"{self.grant_id}|{self.version}|" + "|".join(
            f"{k}={v}" for k, v in sorted(self.scopes.items())
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class DelegatedToken:
    token_id: str
    grant_id: str
    grant_version: int
    grant_digest: str
    scopes: dict[str, str]
    exp: int


class GrantStore:
    def __init__(self) -> None:
        self._grants: dict[str, ConsentGrant] = {}

    def put(self, grant: ConsentGrant) -> None:
        self._grants[grant.grant_id] = grant

    def get(self, grant_id: str) -> ConsentGrant:
        return self._grants[grant_id]


def authorize_tool_call(
    token: DelegatedToken,
    tool_scope: str,
    requested_binding: str,
    store: GrantStore,
    now: int,
) -> None:
    # Envelope checks (signature verification elided; assumed to pass).
    if now >= token.exp:
        raise StaleConsentGrant(f"token {token.token_id} expired")

    # Consumption-time re-binding: the token is a POINTER, not the truth.
    grant = store.get(token.grant_id)

    if grant.revoked:
        raise StaleConsentGrant(
            f"grant {grant.grant_id} revoked; token {token.token_id} is stale"
        )

    if token.grant_version != grant.version:
        raise StaleConsentGrant(
            f"grant_version mismatch: token={token.grant_version} "
            f"grant={grant.version} for token {token.token_id}; "
            f"re-mint required against current grant"
        )

    if token.grant_digest != grant.digest():
        raise StaleConsentGrant(
            f"grant_digest mismatch for token {token.token_id}; "
            f"scope set or bindings mutated since mint"
        )

    # Narrowing check: set-inclusion is NOT sufficient. Binding must match.
    if tool_scope not in grant.scopes:
        raise StaleConsentGrant(
            f"scope {tool_scope} no longer granted by {grant.grant_id}"
        )
    if grant.scopes[tool_scope] != requested_binding:
        raise StaleConsentGrant(
            f"binding mismatch for {tool_scope}: "
            f"granted={grant.scopes[tool_scope]} requested={requested_binding}"
        )


# Demonstration: revocation-after-mint produces a typed, terminal denial
# instead of a silent authorized call.
store = GrantStore()
store.put(ConsentGrant(
    grant_id="g-4471", version=3,
    scopes={"fs.read": "vol-a", "shell.exec": "sandbox-1"},
))
tok = DelegatedToken(
    token_id="t-9912", grant_id="g-4471", grant_version=3,
    grant_digest=store.get("g-4471").digest(),
    scopes={"fs.read": "vol-a", "shell.exec": "sandbox-1"}, exp=10_000,
)
store.put(ConsentGrant(
    grant_id="g-4471", version=4,
    scopes={"fs.read": "vol-a"},  # shell.exec revoked
))
try:
    authorize_tool_call(tok, "shell.exec", "sandbox-1", store, now=100)
except StaleConsentGrant as e:
    print(f"DENIED (terminal): {e}")
