# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-peer-s-asserted-agent-id-after-a-valid-a2a-handoff-and-how-does-warrant-chain-rebinding-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-peer-s-asserted-agent-id-after-a-valid-a2a-handoff-and-how-does-warrant-chain-rebinding-fail.warrant.json
# Markdown SHA-256:   2bf1ed2d1e9e120209c49a537cb046bb9fc5810719d719e71e0582635366e1f6
# Code AST SHA-256:   26503534cd87d5690adb746dcea4ba05f0ef38a7addc31c78a79b1aa944a6b44
# Verified Classes:   IdentityRebindingError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class IdentityRebindingError(RuntimeError):
    """Raised when a warrant's asserted agent_id is not bound to the executing key."""
    pass


@dataclass
class Warrant:
    agent_id: str
    issuer: str
    subject_keys: frozenset[str]
    parent_hash: Optional[str]
    delegated_from: Optional[str] = None
    scope: frozenset[str] = frozenset()


def validate_peer_identity(
    leaf: Warrant,
    executing_key: str,
    chain: list[Warrant],
) -> str:
    """
    Return the trustworthy principal for this execution.
    Raises IdentityRebindingError when the agent_id claim is a copy, not a binding.
    """
    if executing_key not in leaf.subject_keys:
        raise IdentityRebindingError(
            f"executing key {executing_key} absent from leaf subject_keys "
            f"for claimed agent_id={leaf.agent_id!r}: spoofing surface"
        )

    for parent, child in zip(chain, chain[1:]):
        if child.agent_id == parent.agent_id and child.subject_keys != parent.subject_keys:
            raise IdentityRebindingError(
                f"claim-copy edge: agent_id={child.agent_id!r} cloned from parent "
                f"while subject_keys rotated; identity is unbound"
            )
        if child.delegated_from != parent.agent_id and child.agent_id != parent.agent_id:
            raise IdentityRebindingError(
                f"broken delegation edge: child delegated_from={child.delegated_from!r} "
                f"does not reference parent agent_id={parent.agent_id!r}"
            )

    siblings = [w for w in chain if w.parent_hash == leaf.parent_hash and w is not leaf]
    if any(s.agent_id == leaf.agent_id for s in siblings):
        raise IdentityRebindingError(
            f"fan-out with copied agent_id={leaf.agent_id!r}: multiple children "
            f"share a claim that only one principal can own"
        )

    return leaf.agent_id if leaf.delegated_from is None else executing_key
