# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-staleness-is-corrupting-boundary-crossing-attestations-in-cross-org-agent-federations.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-staleness-is-corrupting-boundary-crossing-attestations-in-cross-org-agent-federations.warrant.json
# Markdown SHA-256:   2ecb56705207a662359e6cc2dc0ebe5ab7da320a297c89373e2260d018115ff6
# Code AST SHA-256:   abe7a0e346a437646b9e9f8437c0017e6b7533cdbae1cc19ca9228c75c0b18df
# Verified Classes:   StaleAnchorAttestationError, Attestation, AnchorView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAnchorAttestationError(RuntimeError):
    """Raised when a boundary-crossing attestation's policy epoch does not
    match the issuing org's currently published trust-anchor epoch, or when
    the verifier's cached view of that epoch is older than the staleness
    window. This is NOT a signature failure: the attestation is
    cryptographically sound and the anchor is not revoked."""


@dataclass(frozen=True)
class Attestation:
    issuer_org: str
    anchor_id: str
    policy_epoch: int
    signed_at: float
    signature_valid: bool  # assumed checked upstream


@dataclass(frozen=True)
class AnchorView:
    anchor_id: str
    current_epoch: int
    fetched_at: float


MAX_STALENESS_SECONDS = 120.0  # Delta: bounded anchor-cache freshness


def verify_boundary_attestation(
    att: Attestation,
    anchor: AnchorView,
    now: float,
) -> None:
    # 1. Cryptographic predicate (necessary, not sufficient).
    if not att.signature_valid:
        raise StaleAnchorAttestationError(
            f"signature invalid for anchor {att.anchor_id}"
        )
    if att.anchor_id != anchor.anchor_id:
        raise StaleAnchorAttestationError(
            f"anchor mismatch: attestation cites {att.anchor_id}, "
            f"verifier holds {anchor.anchor_id}"
        )

    # 2. Freshness predicate: the verifier's view of the anchor must be live.
    if (now - anchor.fetched_at) > MAX_STALENESS_SECONDS:
        raise StaleAnchorAttestationError(
            f"anchor view for {anchor.anchor_id} is stale by "
            f"{now - anchor.fetched_at:.1f}s (max {MAX_STALENESS_SECONDS}s); "
            f"cannot assert current policy epoch"
        )

    # 3. Epoch-equality predicate: the semantic predicate the whole
    #    federation silently skips. A past-valid epoch is NOT current.
    if att.policy_epoch != anchor.current_epoch:
        raise StaleAnchorAttestationError(
            f"epoch discontinuity: attestation minted under "
            f"epoch={att.policy_epoch} but {att.issuer_org} now publishes "
            f"epoch={anchor.current_epoch}; refusing to honor stale policy "
            f"semantics (likely a post-rotation agent cache)"
        )


def broker_forward(
    att: Attestation,
    anchor: AnchorView,
    now: float,
) -> Attestation:
    """Broker must be the epoch-enforcement point: it is the last hop with a
    direct line to the issuing org. It must FAIL CLOSED on discontinuity,
    never re-sign a stale epoch under its own fresh countersignature."""
    try:
        verify_boundary_attestation(att, anchor, now)
    except StaleAnchorAttestationError:
        # Do not launder. Re-raise so the chain aborts at the broker.
        raise
    # Only reached if epoch is current and anchor view is fresh.
    return att  # broker countersignature applied downstream
