# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-authorization-token-whose-agent-identity-binding-silently-degrades-under-aaif-exchange-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-authorization-token-whose-agent-identity-binding-silently-degrades-under-aaif-exchange-chains.warrant.json
# Markdown SHA-256:   69271ae0a6a1b0c78c960d3dcd470a8db70d3dd399e1f2a150a1bf395735b75c
# Code AST SHA-256:   d5fded009f81b35f799d8c3f45ce3b12ac482748c7e227f735a9c2abc585fc93
# Verified Classes:   ActorChainCollapseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ActorChainCollapseError(RuntimeError):
    """Raised when a delegated token's actor claim does not match the
    transport-authenticated holder, or when the delegation chain length
    disagrees with the observed hop count. Either condition means the
    token is self-consistent but its identity attribution is unreliable."""


def verify_delegated_token(
    token: dict,
    authenticated_holder: str,
    observed_hop_count: int,
) -> dict:
    """
    Enforce the actor-holder agreement and chain-monotonicity invariants
    before executing on a delegated AAIF token.

    token fields expected:
      sub        : root delegator identity
      act_chain  : ordered list [act_1, act_2, ..., act_k] of holders,
                   each the delegator of the next; last element is the
                   principal that must be presenting this token now.
      aud        : audience (this service)
      scope      : granted scopes
    """
    act_chain = token.get("act_chain") or []
    if not act_chain:
        raise ActorChainCollapseError(
            "token carries no actor chain; identity attribution impossible"
        )

    # Invariant 1: the terminal actor must be the live presenter.
    if act_chain[-1] != authenticated_holder:
        raise ActorChainCollapseError(
            f"actor-holder mismatch: token names act={act_chain[-1]!r} "
            f"but presenter is {authenticated_holder!r}; "
            "delegation chain was collapsed or token replayed"
        )

    # Invariant 2: chain length must equal observed hops. A short chain
    # means an intermediate exchange overwrote rather than appended.
    if len(act_chain) != observed_hop_count:
        raise ActorChainCollapseError(
            f"chain truncation: token chain length {len(act_chain)} "
            f"!= observed hop count {observed_hop_count}; "
            "an exchange dropped actor history"
        )

    # Invariant 3: chain must be internally monotonic (each act_i is the
    # delegator of act_{i+1}); a non-monotonic chain indicates splicing.
    for i in range(len(act_chain) - 1):
        if act_chain[i] == act_chain[i + 1]:
            raise ActorChainCollapseError(
                f"non-monotonic chain at position {i}: "
                f"repeated actor {act_chain[i]!r}"
            )

    return token  # safe to execute; attribute to act_chain[-1]
