# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-peer-s-trust-anchor-negotiation-silently-downgrades-an-inter-domain-policy-warrant-to-a-weaker-self-asser.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-a-federated-peer-s-trust-anchor-negotiation-silently-downgrades-an-inter-domain-policy-warrant-to-a-weaker-self-asser.warrant.json
# Markdown SHA-256:   f439c4b5705c2459a0b74935e0abe643ddd4a64f5448278e7eca60cf55102831
# Code AST SHA-256:   ea742363c743e932f722aa75a43d2bdfe16f89b0354425b1b0fcedf6913be2b2
# Verified Classes:   WarrantDelegationMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class WarrantDelegationMismatch(RuntimeError):
    """Raised when a federated warrant's signer does not match its named delegator
    and no bridging delegation grant can be verified. Halting here prevents a
    false-issuer checkpoint from entering swarm state."""
    pass


def accept_federated_warrant(warrant, session_peer, anchor_root, delegation_grants):
    # Phase 1 already validated the anchor: session_peer is attested by anchor_root.
    # Phase 2 must NOT infer delegation from attestation.
    if warrant.delegator == anchor_root and warrant.signer == anchor_root:
        return warrant  # root-signed directly; safe

    if warrant.delegator != warrant.signer:
        # Signer is the peer; delegator is someone else. Require an explicit grant.
        bridging = [
            g for g in delegation_grants
            if g.grantor == warrant.delegator
            and g.grantee == warrant.signer
            and warrant.capability in g.capabilities
        ]
        if not bridging:
            raise WarrantDelegationMismatch(
                f"warrant claims delegator={warrant.delegator!r} but was signed by "
                f"{warrant.signer!r}; no delegation grant from {warrant.delegator!r} "
                f"to {warrant.signer!r} covers {warrant.capability!r}. "
                f"Attestation is not delegation; refusing to record issuer."
            )
        # Re-verify the warrant signature against the delegator's root, not the session key.
        if not warrant.verify_signature(anchor_root.public_key):
            raise WarrantDelegationMismatch(
                "warrant signature does not verify against named delegator's root"
            )
        return warrant

    # signer == delegator but delegator != anchor_root: verify against delegator's own root.
    if not warrant.verify_signature(warrant.delegator.public_key):
        raise WarrantDelegationMismatch(
            f"warrant signed by {warrant.signer!r} fails verification against its own root"
        )
    return warrant
