# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-cross-org-capability-negotiation-has-silently-widened-an-agent-s-effective-authority-beyond-the-warrant-s-declar.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-cross-org-capability-negotiation-has-silently-widened-an-agent-s-effective-authority-beyond-the-warrant-s-declar.warrant.json
# Markdown SHA-256:   0a3f4fb99085cbd2945c5f556ce56e760b2e08f3ec433d28dcbadef7ef125fc4
# Code AST SHA-256:   9ed88e936020d8879418ab7e6e8e6df1c727d9664dd0b6b7a55392856c6a24fb
# Verified Classes:   ClosureMismatchError, UnattestableGrantError, Warrant, Grant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ClosureMismatchError(RuntimeError):
    """Raised when a peer grant's resolved capability closure exceeds the warrant's permitted closure."""


class UnattestableGrantError(RuntimeError):
    """Raised when a composite grant arrives without signed closure evidence."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    permitted_primitives: FrozenSet[str]   # explicit leaf-level authority
    max_calls: int
    expiry: float


@dataclass(frozen=True)
class Grant:
    grant_id: str
    requested_id: str
    resolved_primitives: FrozenSet[str] | None   # None => peer did not attest closure
    is_composite: bool
    closure_signature: str | None
    echoed_constraints: dict = field(default_factory=dict)


def admit_grant(warrant: Warrant, grant: Grant, now: float) -> None:
    """Enforce closure(subset) at grant time. Refuse, do not downgrade."""
    if now >= warrant.expiry:
        raise ClosureMismatchError(
            f"warrant {warrant.warrant_id} expired at {warrant.expiry}, now={now}"
        )

    # Leaf-to-leaf with matching id: identifier equality is sufficient.
    if not grant.is_composite and grant.resolved_primitives is not None:
        resolved = grant.resolved_primitives
    else:
        # Composite grant: closure evidence is mandatory and must be signed.
        if grant.resolved_primitives is None or not grant.closure_signature:
            raise UnattestableGrantError(
                f"grant {grant.grant_id} (requested={grant.requested_id}) is composite "
                f"but carries no signed closure attestation; treating as unbounded"
            )
        resolved = grant.resolved_primitives

    excess = resolved - warrant.permitted_primitives
    if excess:
        raise ClosureMismatchError(
            f"grant {grant.grant_id} resolves to primitives {sorted(excess)} "
            f"outside warrant {warrant.warrant_id} permitted closure "
            f"{sorted(warrant.permitted_primitives)}"
        )

    # Constraint echo must be binding, not descriptive: budget must be echoed.
    if "max_calls" not in grant.echoed_constraints:
        raise ClosureMismatchError(
            f"grant {grant.grant_id} did not echo max_calls; budget is unenforced "
            f"across the grant's lifetime"
        )
    if grant.echoed_constraints["max_calls"] > warrant.max_calls:
        raise ClosureMismatchError(
            f"grant {grant.grant_id} echoes max_calls="
            f"{grant.echoed_constraints['max_calls']} exceeding warrant cap "
            f"{warrant.max_calls}"
        )


# --- Example: the observed incident, replayed under the guardrail ---
if __name__ == "__main__":
    w = Warrant(
        warrant_id="A-W-7741",
        permitted_primitives=frozenset({"read_object"}),
        max_calls=40,
        expiry=1000.0,
    )
    # Peer resolved cap:read:records to a 3-primitive bundle, echoed no budget.
    g = Grant(
        grant_id="B-G-0092",
        requested_id="cap:read:records",
        resolved_primitives=frozenset({"read_object", "enumerate_keys", "stream_export"}),
        is_composite=True,
        closure_signature="sig:peerB:policy:0x9af...",
        echoed_constraints={"resource_glob": "records/*"},
    )
    try:
        admit_grant(w, g, now=120.0)
    except ClosureMismatchError as e:
        print(f"REFUSED (closure): {e}")
    except UnattestableGrantError as e:
        print(f"REFUSED (attestation): {e}")
