# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-capability-grant-when-the-trust-broker-s-policy-translation-silently-widens-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-federated-capability-grant-when-the-trust-broker-s-policy-translation-silently-widens-scope.warrant.json
# Markdown SHA-256:   c5093b0b34c53e0d28a31aa030973a51f125d8364238374b86da714d70aaa295
# Code AST SHA-256:   6f0db212dd4682474cbb76ef22e652e0f589a821d1b3537996b978e0223e494b
# Verified Classes:   ScopeWideningError, Scope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a translated scope is not a provable subset of the caller warrant."""


@dataclass(frozen=True)
class Scope:
    resource: str
    actions: FrozenSet[str]


# Declared domain of the broker's translation table. Anything outside is untranslatable.
TRANSLATION_TABLE: dict[Scope, Scope] = {
    Scope("kb/quarterly", frozenset({"read"})): Scope("kb/*", frozenset({"read"})),
    Scope("kb/quarterly", frozenset({"read", "list"})): Scope("kb/*", frozenset({"read", "list"})),
}


def is_subset(translated: Scope, warrant: Scope) -> bool:
    # Containment must be checked in a shared algebra, not by string equality.
    return translated.actions <= warrant.actions and (
        translated.resource == warrant.resource
        or warrant.resource.endswith("*") and translated.resource.startswith(warrant.resource[:-1])
    )


def translate_and_mint(warrant: Scope, grant_id: str) -> tuple[Scope, str]:
    if warrant not in TRANSLATION_TABLE:
        # The only conservative response to an untranslatable scope is refusal.
        raise ScopeWideningError(
            f"grant {grant_id}: caller scope {warrant} has no translation; "
            f"refusing rather than glob-widening"
        )
    translated = TRANSLATION_TABLE[warrant]
    if not is_subset(translated, warrant):
        raise ScopeWideningError(
            f"grant {grant_id}: translated {translated} is not a subset of warrant {warrant}; "
            f"monotonicity violated, token must not be minted"
        )
    # Both audit logs record the translated scope under the shared grant_id.
    return translated, grant_id


def handle_delegation(warrant: Scope, grant_id: str) -> str:
    try:
        translated, gid = translate_and_mint(warrant, grant_id)
    except ScopeWideningError as exc:
        # Surface the gap to the orchestrator; do not silently approximate.
        return f"DELEGATION_REFUSED: {exc}"
    return f"MINTED grant={gid} scope={translated}"
