# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-when-the-trust-anchor-validates-but-the-negotiation-transcript-is-not-causa.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-when-the-trust-anchor-validates-but-the-negotiation-transcript-is-not-causa.warrant.json
# Markdown SHA-256:   7ba5f402d16a3ca07906a17c8563f442ed9ee8b34fe47305d32ee7bf37afec97
# Code AST SHA-256:   a457f206ef202f8e5fd69f1c81a9b76958275d886a617944870386134c36c392
# Verified Classes:   CausalClosureViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class CausalClosureViolation(RuntimeError):
    """Raised when a federated grant's terms cannot be traced to an
    introduction and acceptance in the local transcript, or when a
    mutable term's revocation authority cannot be derived."""
    pass


MUTABLE_TERM_KINDS = {"rate_cap", "residency", "retention", "audit_obligation"}


def evaluate_federated_grant(grant, transcript, trust_store):
    # Conditions 1 and 2: trust anchor and signature.
    if not trust_store.verifies(grant.peer_discovery_record):
        raise CausalClosureViolation("trust anchor invalid for peer")
    if not trust_store.verifies_signature(grant.terms, grant.signature, grant.peer_key):
        raise CausalClosureViolation("grant signature does not verify")

    # Conditions 3-5: causal closure, origin, revocation authority.
    for term in grant.terms:
        chain = transcript.trace_term(term.name)
        if chain is None:
            if term.kind in MUTABLE_TERM_KINDS:
                raise CausalClosureViolation(
                    f"mutable term {term.name!r} has no causal chain in transcript; "
                    f"cannot derive revocation authority; refusing grant"
                )
            # Immutable term with unknown origin: degraded mode, non-revocable.
            transcript.record_degraded(term.name, reason="origin_unknown_immutable")
            continue

        if not chain.is_causally_linked():
            raise CausalClosureViolation(
                f"term {term.name!r} chain is not hash-linked end to end"
            )

        origin = chain.introducing_party()
        if origin is None:
            raise CausalClosureViolation(
                f"term {term.name!r} has no identifiable introducing party"
            )
        if not chain.establishes_revocation_authority(origin):
            raise CausalClosureViolation(
                f"term {term.name!r} introduced by {origin} but transcript "
                f"does not establish {origin}'s authority to withdraw it"
            )

    return grant.honor(transcript=transcript)
