# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-cannot-locally-re-derive.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-cannot-locally-re-derive.warrant.json
# Markdown SHA-256:   c97238011d2b2efb5a03ef8852d7a7d94ee6edd62d19807a3799d4875683d545
# Code AST SHA-256:   825a969c31eb8ea5958edcd1b2fc50f3b31f9855fffbb1064076049e33bdb673
# Verified Classes:   UnevaluablePolicyPredicateError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnevaluablePolicyPredicateError(RuntimeError):
    """Raised when a federated grant's validity depends on broker-side
    policy predicates the relying party cannot locally re-derive."""
    pass


def verify_federated_grant(grant: dict, local_policy: dict, trust_store: dict) -> bool:
    # Structural checks first: these are cheap and self-contained.
    if grant.get("issuer") not in trust_store:
        raise UnevaluablePolicyPredicateError(
            f"issuer {grant.get('issuer')!r} not in trust store"
        )
    if grant.get("expires_at", 0) < local_policy["now"]:
        return False

    # The boundary: does this grant carry its authorization predicates,
    # or does it point at broker policy we must be able to resolve?
    inline_predicates = grant.get("predicates")
    policy_ref = grant.get("policy_ref")

    if inline_predicates is not None:
        # Self-contained: evaluate locally, no broker context needed.
        return all(local_policy["evaluate"](p) for p in inline_predicates)

    if policy_ref is None:
        raise UnevaluablePolicyPredicateError(
            "grant carries neither inline predicates nor a policy reference; "
            "validity is not re-derivable by the relying party"
        )

    # Context-dependent: require a content hash and resolvable, pinned doc.
    expected_hash = policy_ref.get("content_hash")
    resolved = local_policy["resolve_policy"](policy_ref.get("uri"))
    if expected_hash is None or resolved is None:
        raise UnevaluablePolicyPredicateError(
            f"policy_ref {policy_ref.get('uri')!r} is not hash-bound or not "
            "resolvable; refusing rather than trusting opaque broker judgment"
        )
    if local_policy["hash"](resolved) != expected_hash:
        raise UnevaluablePolicyPredicateError(
            "resolved policy document does not match the hash bound in the grant; "
            "broker evaluated a different policy than the one we can see"
        )

    # Re-derive the broker's decision under the pinned policy.
    return all(local_policy["evaluate_under"](resolved, p) for p in resolved["predicates"])
