# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-before-it-has-verified-the-peer-s-policy-epoch-and-how-does-that-create-a-silent-trust-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-capability-grant-before-it-has-verified-the-peer-s-policy-epoch-and-how-does-that-create-a-silent-trust-anchor.warrant.json
# Markdown SHA-256:   459b52951a4ca52338e6e5a51cae215ad83539d68b63ebca9d40f06b2a88ace2
# Code AST SHA-256:   e9e444945af2f840187ecb56bc04d60ed85c6b5a60ae6ff415dfc64883b54241
# Verified Classes:   StalePolicyEpochError, FederatedGrantEvaluator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StalePolicyEpochError(RuntimeError):
    """Raised when a federated grant's signing epoch does not match the
    grantee's active policy epoch at evaluation time."""
    pass


class FederatedGrantEvaluator:
    def __init__(self, active_policy_epoch: int, active_constraints: dict):
        self.active_policy_epoch = active_policy_epoch
        self.active_constraints = active_constraints

    def evaluate(self, grant: dict, policy_fetched_live: bool) -> bool:
        # grant: {"epoch": int, "key_id": str, "constraints": dict, "sig": str}
        if not policy_fetched_live:
            # Restored-from-checkpoint policy is never authoritative for acceptance.
            raise StalePolicyEpochError(
                "policy manifest was restored from checkpoint, not fetched live; "
                "cannot bind grant epoch to active epoch"
            )
        if grant["epoch"] != self.active_policy_epoch:
            raise StalePolicyEpochError(
                f"grant signed under epoch {grant['epoch']} but active policy "
                f"epoch is {self.active_policy_epoch}; refusing to accept a "
                f"grant whose signing epoch does not match the live manifest"
            )
        for k, v in grant["constraints"].items():
            if k not in self.active_constraints or v != self.active_constraints[k]:
                raise StalePolicyEpochError(
                    f"grant constraint {k}={v} is not a subset of active "
                    f"policy constraint {k}={self.active_constraints.get(k)}"
                )
        # signature verified separately against live key set; epoch binding is the guard
        return True
