# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-negotiated-capability-scope-as-revoked-when-a-federated-peer-re-signs-its-policy-manifest-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-negotiated-capability-scope-as-revoked-when-a-federated-peer-re-signs-its-policy-manifest-mid-session.warrant.json
# Markdown SHA-256:   9d79641b399c7ae2b142ae8fd487271eb9a79d0af3c161cc93093905bbb7b018
# Code AST SHA-256:   865dde99e167cac0ae1ad6969280dff4d4ca880d805c401d5316345783595557
# Verified Classes:   StaleWarrantError, ScopeDeltaUnmodeledError, Grant, FederatedGrantCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class StaleWarrantError(RuntimeError):
    """Raised when a plan or invocation is issued against a grant whose scope
    has been narrowed by a re-signed manifest that the receiver has not applied."""


class ScopeDeltaUnmodeledError(RuntimeError):
    """Raised when a re-signed manifest introduces a scope constraint dimension
    the receiver cannot interpret; the safe default is revocation, not refresh."""


@dataclass(frozen=True)
class Grant:
    peer_id: str
    capability_name: str
    manifest_version: int
    scope: dict[str, Any]

    @property
    def scope_digest(self) -> str:
        canonical = json.dumps(self.scope, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

    @property
    def cache_key(self) -> tuple[str, str, int, str]:
        return (self.peer_id, self.capability_name, self.manifest_version, self.scope_digest)


def _is_superset(new: dict[str, Any], old: dict[str, Any]) -> bool:
    """True iff every constraint in `old` is equal to or looser than in `new`.
    Only models the dimensions this receiver understands; unknown dimensions
    must be routed to ScopeDeltaUnmodeledError by the caller."""
    for key, old_val in old.items():
        if key not in new:
            raise ScopeDeltaUnmodeledError(f"constraint dimension {key!r} disappeared")
        new_val = new[key]
        if isinstance(old_val, set) and isinstance(new_val, set):
            if not old_val.issubset(new_val):
                return False
        elif isinstance(old_val, (int, float)) and isinstance(new_val, (int, float)):
            if new_val < old_val:  # numeric bound tightened
                return False
        elif old_val != new_val:
            return False
    return True


class FederatedGrantCache:
    def __init__(self) -> None:
        self._grants: dict[tuple[str, str], Grant] = {}
        self._revoked: set[tuple[str, str, int]] = set()

    def install(self, grant: Grant) -> None:
        self._grants[(grant.peer_id, grant.capability_name)] = grant

    def on_manifest_push(self, new: Grant) -> str:
        """Returns 'refreshed' or 'revoked'. Raises on unmodeled delta."""
        prior = self._grants.get((new.peer_id, new.capability_name))
        if prior is None:
            self.install(new)
            return "refreshed"
        if prior.scope_digest == new.scope_digest:
            self.install(new)  # pure refresh: signer/version only
            return "refreshed"
        if _is_superset(new.scope, prior.scope):
            self.install(new)  # monotone widening
            return "refreshed"
        # Non-superset delta: this is a revocation of the prior warrant.
        self._revoked.add((prior.peer_id, prior.capability_name, prior.manifest_version))
        self.install(new)
        return "revoked"

    def assert_invocable(self, peer_id: str, capability_name: str, manifest_version: int) -> Grant:
        grant = self._grants.get((peer_id, capability_name))
        if grant is None:
            raise StaleWarrantError(f"no grant cached for {peer_id}/{capability_name}")
        if (peer_id, capability_name, manifest_version) in self._revoked:
            raise StaleWarrantError(
                f"plan references manifest v{manifest_version} for "
                f"{peer_id}/{capability_name}, which was revoked by a scope narrowing"
            )
        if grant.manifest_version != manifest_version:
            raise StaleWarrantError(
                f"plan built against v{manifest_version}, cache holds v{grant.manifest_version}; "
                f"replan required before retry"
            )
        return grant
