# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-warrant-substitution-failure-in-cross-org-federated-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-warrant-substitution-failure-in-cross-org-federated-agent-handoffs.warrant.json
# Markdown SHA-256:   bf1df45e4278b292ffd6440cf9fbc9c246eb6ef1b9c62187d9972445a1a4536a
# Code AST SHA-256:   015b66291b97ccd9b98f066014af1c0c031bffab1f5a3376d2c92a37b6e038ed
# Verified Classes:   WarrantProvenanceError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class WarrantProvenanceError(RuntimeError):
    """Raised when a presented warrant is cryptographically valid but its
    subject/chain does not bind to the transport principal or the recorded
    delegation history. Distinct from signature or scope failure."""
    pass


def verify_federated_handoff(
    transport_principal: str,
    presented_warrant: dict,
    parent_warrant: dict | None,
    consumed_warrants: set[str],
    max_depth: int,
) -> None:
    subject = presented_warrant["subject"]
    chain = presented_warrant["delegation_chain"]
    wid = presented_warrant["warrant_id"]

    # Invariant 1: transport identity must equal the warrant subject.
    if transport_principal != subject:
        raise WarrantProvenanceError(
            f"transport principal {transport_principal!r} presented warrant "
            f"scoped to subject {subject!r}; audit attribution would be corrupt"
        )

    # Invariant 2: chain must be contiguous with the parent's chain.
    if parent_warrant is not None:
        expected = parent_warrant["delegation_chain"] + [subject]
        if chain != expected:
            raise WarrantProvenanceError(
                f"non-contiguous delegation chain: got {chain}, expected {expected}; "
                f"a hop is unrecorded (likely grandparent warrant replay)"
            )
    elif len(chain) != 1:
        raise WarrantProvenanceError(
            f"root warrant must have single-element chain, got {chain}"
        )

    # Invariant 3: depth bound.
    if len(chain) > max_depth:
        raise WarrantProvenanceError(
            f"delegation depth {len(chain)} exceeds max_depth {max_depth}"
        )

    # Invariant 4: parent warrant must be consumed by this attenuation,
    # preventing the attenuator (or a context-copied sub-agent) from
    # re-presenting the parent directly.
    if parent_warrant is not None and parent_warrant["warrant_id"] not in consumed_warrants:
        raise WarrantProvenanceError(
            f"parent warrant {parent_warrant['warrant_id']!r} not marked consumed; "
            f"replay of parent by attenuator subtree is possible"
        )

    if wid in consumed_warrants:
        raise WarrantProvenanceError(
            f"warrant {wid!r} already consumed; single-use violation"
        )
