# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-bootstrapping-has-silently-diverged-from-policy-exchange-in-cross-org-agent-federations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-bootstrapping-has-silently-diverged-from-policy-exchange-in-cross-org-agent-federations.warrant.json
# Markdown SHA-256:   9ce0ca8512c6554188f9c7e18c9462ccd2685f6f1c2decd22996ce7bba81eacb
# Code AST SHA-256:   ab7ba17ab7eccc8f136f2f468a4bd4eef826eeda774e7dc66be50d9d3125a1ed
# Verified Classes:   PolicySkewError, TrustAnchor, PolicyBundle, FederatedAuthorizer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class PolicySkewError(RuntimeError):
    """Raised when a peer's advertised policy digest disagrees with the
    digest bound in the locally cached trust anchor. This is a continuity
    invariant failure, not a cryptographic one: both the anchor and the
    policy bundle may be individually signature-valid while their binding
    is stale."""


@dataclass(frozen=True)
class TrustAnchor:
    org_id: str
    root_pubkey: bytes
    policy_digest: str          # sha256 hex of the bundle this anchor binds
    rotation_interval_s: int    # peer's declared rotation cadence
    fetched_at: float


@dataclass(frozen=True)
class PolicyBundle:
    digest: str
    permits: frozenset[str]     # allowed action names


class FederatedAuthorizer:
    def __init__(self, anchor: TrustAnchor, bundle: PolicyBundle):
        if anchor.policy_digest != bundle.digest:
            raise PolicySkewError(
                f"bootstrap inconsistent: anchor binds {anchor.policy_digest} "
                f"but bundle is {bundle.digest}"
            )
        self._anchor = anchor
        self._bundle = bundle

    def authorize(
        self,
        action: str,
        peer_advertised_digest: Optional[str],
        now: float,
    ) -> None:
        # 1. TTL must not exceed the peer's declared rotation cadence.
        age = now - self._anchor.fetched_at
        if age > self._anchor.rotation_interval_s:
            raise PolicySkewError(
                f"anchor age {age:.0f}s exceeds peer rotation cadence "
                f"{self._anchor.rotation_interval_s}s; re-bootstrap required"
            )

        # 2. The relational check: does the peer's current view match ours?
        if peer_advertised_digest is None:
            raise PolicySkewError(
                "peer did not advertise policy digest; cannot verify binding"
            )
        if peer_advertised_digest != self._anchor.policy_digest:
            raise PolicySkewError(
                f"policy skew: peer advertises {peer_advertised_digest}, "
                f"anchor binds {self._anchor.policy_digest}; "
                f"re-bootstrap before authorizing '{action}'"
            )

        # 3. Only now is the cached bundle trustworthy for this action.
        if action not in self._bundle.permits:
            raise PolicySkewError(
                f"action '{action}' not permitted under current policy "
                f"{self._bundle.digest}"
            )


def handle_peer_response(
    authorizer: FederatedAuthorizer,
    action: str,
    response_headers: dict[str, str],
    now: float,
) -> None:
    """Call on every outbound delegated action before trusting the cached policy."""
    authorizer.authorize(
        action=action,
        peer_advertised_digest=response_headers.get("x-policy-digest"),
        now=now,
    )
