# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-trust-anchor-chain-has-silently-re-rooted-during-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-trust-anchor-chain-has-silently-re-rooted-during-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   003cbaed79016e4cdad8005bb3079bcca391b8e25f02cf04aa246c6b5db940cd
# Code AST SHA-256:   af5e29ec6ebb46e89df4fd938366441f3168b55d986b01d4729ce0d5794d767a
# Verified Classes:   TrustAnchorDriftError, Hop, Manifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class TrustAnchorDriftError(RuntimeError):
    """Raised when a verified capability path does not match the signed delegation path."""


@dataclass(frozen=True)
class Hop:
    org: str
    key_id: str
    is_cross_cert: bool = False


@dataclass(frozen=True)
class Manifest:
    body_digest: str
    declared_anchor_key_id: str
    delegation_path: Sequence[str]  # orgs the originator authorized, in order
    signature: bytes


def verify_federated_capability(
    manifest: Manifest,
    verified_hops: Sequence[Hop],
    local_trust_store: frozenset[str],
) -> str:
    """
    Enforce: verified certificate path MUST terminate at the originator-declared
    anchor, and the orgs in the verified path MUST equal the signed delegation_path.
    Fails closed on any divergence, including cross-cert edges not enumerated.
    """
    if not verified_hops:
        raise TrustAnchorDriftError("empty verified path; cannot establish authority")

    terminal = verified_hops[-1]

    # 1. Terminal anchor must be the originator's declared anchor, not merely
    #    *an* anchor present in the flat trust store.
    if terminal.key_id != manifest.declared_anchor_key_id:
        raise TrustAnchorDriftError(
            f"chain re-rooted: declared anchor {manifest.declared_anchor_key_id!r} "
            f"but verified path terminates at {terminal.key_id!r}"
        )
    if terminal.key_id not in local_trust_store:
        raise TrustAnchorDriftError(
            f"declared anchor {terminal.key_id!r} absent from local trust store"
        )

    # 2. Path/chain isomorphism: every cross-cert edge must be enumerated in the
    #    signed delegation_path; otherwise the originator never authorized it.
    for hop in verified_hops:
        if hop.is_cross_cert and hop.org not in manifest.delegation_path:
            raise TrustAnchorDriftError(
                f"un-enumerated cross-cert edge through org {hop.org!r}: "
                f"originator authorized {list(manifest.delegation_path)!r}"
            )

    # 3. Ordered org set of the cryptographic path must equal the signed path.
    crypto_orgs = [h.org for h in verified_hops]
    if crypto_orgs != list(manifest.delegation_path):
        raise TrustAnchorDriftError(
            f"delegation_path/chain divergence: signed={list(manifest.delegation_path)!r} "
            f"verified={crypto_orgs!r}"
        )

    return terminal.key_id


def replay_check(manifest: Manifest, hops_at_t1: Sequence[Hop], hops_at_t2: Sequence[Hop],
                 trust_t1: frozenset[str], trust_t2: frozenset[str]) -> None:
    """Replay determinism: same manifest bytes must resolve to same anchor across trust refreshes."""
    a1 = verify_federated_capability(manifest, hops_at_t1, trust_t1)
    a2 = verify_federated_capability(manifest, hops_at_t2, trust_t2)
    if a1 != a2:
        raise TrustAnchorDriftError(
            f"non-idempotent verification: anchor {a1!r} at T1 vs {a2!r} at T2"
        )
