# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-whose-policy-predicate-it-cannot-evaluate-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-whose-policy-predicate-it-cannot-evaluate-locally.warrant.json
# Markdown SHA-256:   73b51e1e40c0d349438af9eb2f732f7b73ad8ec53be4647784d9dbeeac3ad9f2
# Code AST SHA-256:   7ce5b28ee0738ef14463f6336e8b87d263ac7e4429d49853809b7111cd0d9dc4
# Verified Classes:   PredicateClosureError, Decision, CapabilityGrant, GranteePolicyEngine
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class PredicateClosureError(RuntimeError):
    """Raised when a federated capability predicate cannot be fully
    evaluated by the grantee's local policy engine."""


class Decision(Enum):
    ALLOW = "allow"
    DENY = "deny"
    UNKNOWN = "unknown"


@dataclass
class CapabilityGrant:
    issuer_domain: str
    grantee_id: str
    capability: str
    predicate_symbols: set[str]          # symbols referenced by the predicate
    predicate: Callable[[dict], bool]


@dataclass
class GranteePolicyEngine:
    # Symbols this engine can resolve to a definite value.
    resolvers: set[str] = field(default_factory=set)
    operators: set[str] = field(default_factory=set)

    def closure_check(self, grant: CapabilityGrant) -> None:
        """Admission-time gate: reject grants with unresolvable symbols.
        Fails closed BEFORE the token enters the capability store."""
        unresolvable = grant.predicate_symbols - (self.resolvers | self.operators)
        if unresolvable:
            raise PredicateClosureError(
                f"grant {grant.capability!r} from {grant.issuer_domain!r} "
                f"references symbols not evaluable locally: {sorted(unresolvable)}; "
                f"renegotiation required before use"
            )

    def evaluate(self, grant: CapabilityGrant, env: dict) -> Decision:
        """Use-time evaluation. UNKNOWN must never collapse to ALLOW."""
        try:
            result = grant.predicate(env)
        except (KeyError, TypeError, ValueError):
            # A symbol resolved at admission but failed at use time
            # (stale resolver, rotated vocabulary) -> hard stop.
            return Decision.UNKNOWN
        return Decision.ALLOW if result else Decision.DENY

    def admit_and_execute(self, grant: CapabilityGrant, env: dict) -> Decision:
        self.closure_check(grant)               # fail-closed at admission
        decision = self.evaluate(grant, env)
        if decision is Decision.UNKNOWN:
            # Do NOT default to allow; surface for renegotiation.
            raise PredicateClosureError(
                f"predicate for {grant.capability!r} became unevaluable at use time; "
                f"grant suspended pending issuer re-attestation"
            )
        return decision


# --- demonstration of the failure mode being prevented ---

def demo() -> None:
    engine = GranteePolicyEngine(
        resolvers={"trust_tier", "now"},
        operators={">=", "within"},
    )
    # Foreign predicate references org_clearance (unknown to engine).
    foreign = CapabilityGrant(
        issuer_domain="alpha",
        grantee_id="bravo-agent-7",
        capability="read:telemetry",
        predicate_symbols={"org_clearance", "classification", "within"},
        predicate=lambda env: env["org_clearance"] >= env["classification"],
    )
    try:
        engine.admit_and_execute(foreign, env={})
    except PredicateClosureError as e:
        print(f"BLOCKED (fail-closed): {e}")


if __name__ == "__main__":
    demo()
