# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-trust-anchor-chain-has-silently-decohered-mid-handoff-in-cross-org-multi-agent-peering.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-trust-anchor-chain-has-silently-decohered-mid-handoff-in-cross-org-multi-agent-peering.warrant.json
# Markdown SHA-256:   84a2ddd39e63234fdb609ca522c422499a8191bfd6942009637c85e101f5dc99
# Code AST SHA-256:   bb32a6ebe98d18a9ad6725ad2a1d2e806ea376509004a6f784e1269acb43f421
# Verified Classes:   FederationContinuityError, ContinuityContext, Attestation
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FederationContinuityError(RuntimeError):
    """Raised when a transit hop breaks attestation continuity.

    Distinct from signature-validity errors: the credential may be
    cryptographically valid while the chain back to the originating
    trust anchor has been silently re-rooted, shortened, or had its
    policy constraints dropped.
    """


@dataclass(frozen=True)
class ContinuityContext:
    root_anchor_id: str
    delegation_depth: int
    depth_budget_remaining: int
    constraints: frozenset[str]
    expiry_epoch: int


@dataclass(frozen=True)
class Attestation:
    root_anchor_id: str
    delegation_depth: int
    constraints: frozenset[str]
    expiry_epoch: int
    issuer_org: str
    signature_valid: bool  # per-hop crypto check, assumed true here


def verify_transit_continuity(
    inbound: ContinuityContext,
    received: Attestation,
    *,
    is_transit_hop: bool = True,
) -> None:
    """Enforce the handoff-boundary continuity invariant.

    Must be called at every transit hop in addition to (never instead
    of) signature validation. Stateless per-hop validators cannot
    detect these failures because they lack the inbound envelope.
    """
    if not is_transit_hop:
        # Fresh grants are allowed to re-root; transits are not.
        return

    if not received.signature_valid:
        raise FederationContinuityError(
            f"signature invalid at hop issued by {received.issuer_org}"
        )

    # Signal 1: depth must advance by exactly one per transit.
    expected_depth = inbound.delegation_depth + 1
    if received.delegation_depth != expected_depth:
        raise FederationContinuityError(
            "delegation depth discontinuity: "
            f"expected {expected_depth}, received {received.delegation_depth} "
            f"(decrease indicates re-rooting, skip indicates dropped hop)"
        )

    if received.delegation_depth > inbound.delegation_depth + inbound.depth_budget_remaining:
        raise FederationContinuityError(
            f"depth budget exhausted: received depth {received.delegation_depth} "
            f"exceeds budget {inbound.delegation_depth + inbound.depth_budget_remaining}"
        )

    # Signal 2: root anchor is immutable across transit.
    if received.root_anchor_id != inbound.root_anchor_id:
        raise FederationContinuityError(
            "root anchor discontinuity: "
            f"{inbound.root_anchor_id!r} -> {received.root_anchor_id!r} "
            f"at hop issued by {received.issuer_org}; transit may not re-root"
        )

    # Signal 3: constraint set may only grow, never shrink.
    dropped = inbound.constraints - received.constraints
    if dropped:
        raise FederationContinuityError(
            f"constraint shrinkage at hop issued by {received.issuer_org}: "
            f"dropped {sorted(dropped)}; widening requires explicit grant"
        )

    # Signal 4: TTL may only tighten across transit.
    if received.expiry_epoch > inbound.expiry_epoch:
        raise FederationContinuityError(
            f"expiry widened across transit at hop issued by {received.issuer_org}: "
            f"{inbound.expiry_epoch} -> {received.expiry_epoch}"
        )


def verify_terminal_receipt(
    original_grant: ContinuityContext,
    terminal: Attestation,
) -> None:
    """Originator-side check: the terminal receipt must still be rooted
    in the originating anchor and must not exceed the original depth
    budget. Without this, originators never learn the chain broke.
    """
    if terminal.root_anchor_id != original_grant.root_anchor_id:
        raise FederationContinuityError(
            "terminal receipt re-rooted: originating anchor "
            f"{original_grant.root_anchor_id!r} != terminal "
            f"{terminal.root_anchor_id!r}; task succeeded under foreign authority"
        )
    if terminal.delegation_depth > (
        original_grant.delegation_depth + original_grant.depth_budget_remaining
    ):
        raise FederationContinuityError(
            f"terminal depth {terminal.delegation_depth} exceeds original budget "
            f"{original_grant.delegation_depth + original_grant.depth_budget_remaining}"
        )
