# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-when-a-trust-broker-s-policy-closure-is-wider-than-the-negotiating-org-s-own-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-capability-when-a-trust-broker-s-policy-closure-is-wider-than-the-negotiating-org-s-own-policy.warrant.json
# Markdown SHA-256:   bbe9bc3e5787b1898be5a8911e64bd306ea397bae33fa3bae23cce001541a196
# Code AST SHA-256:   02d1a8c5a85be05b2d6c8e3daaf125c10dc6a47ae41add53b545f65ac1e8fcc9
# Verified Classes:   ScopeClosureMismatch, Warrant, CustodianPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Tuple

Tuple3 = Tuple[str, str, str]  # (principal, resource, action)


class ScopeClosureMismatch(RuntimeError):
    """Raised when a broker warrant's scope, re-closed under the custodian's
    policy, is wider than the custodian's admitted closure."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    broker: str
    scope_symbolic: str            # e.g. "read:case_file:*"
    tuples: FrozenSet[Tuple3] | None  # None => symbolic, not reified


@dataclass(frozen=True)
class CustodianPolicy:
    admitted: FrozenSet[Tuple3]    # the custodian's own closure


def resolve_symbol(symbol: str, policy: CustodianPolicy) -> FrozenSet[Tuple3]:
    # Custodian re-resolves the broker's symbol under ITS OWN schema.
    # A wildcard over a class the custodian partitions yields only the
    # tuples the custodian's policy actually admits for that class.
    cls = symbol.split(":")[1]
    return frozenset(t for t in policy.admitted if t[1].startswith(cls))


def accept_warrant(w: Warrant, policy: CustodianPolicy) -> FrozenSet[Tuple3]:
    if w.tuples is None:
        # Symbolic scope: must re-close under custodian policy, never trust broker.
        broker_closure = resolve_symbol(w.scope_symbolic, policy)
        narrowed = broker_closure & policy.admitted
        dropped = broker_closure - narrowed
        if dropped:
            # Divergence is the signal: narrow, record, notify broker.
            _record_divergence(w.warrant_id, dropped)
            raise ScopeClosureMismatch(
                f"warrant {w.warrant_id} from {w.broker}: "
                f"{len(dropped)} tuples outside custodian closure; "
                f"narrowed grant issued, broker notified"
            )
        return narrowed
    # Reified scope: verify subset of custodian closure.
    if not w.tuples <= policy.admitted:
        excess = w.tuples - policy.admitted
        raise ScopeClosureMismatch(
            f"warrant {w.warrant_id}: {len(excess)} reified tuples "
            f"not admitted by custodian policy"
        )
    return w.tuples


def _record_divergence(warrant_id: str, dropped: FrozenSet[Tuple3]) -> None:
    # Emit to audit + broker feedback channel; do not swallow.
    ...
