# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-attestation-freshness-collapse-in-cross-org-a2a-federation-under-bilateral-policy-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-attestation-freshness-collapse-in-cross-org-a2a-federation-under-bilateral-policy-enforcement.warrant.json
# Markdown SHA-256:   99532c183bfea23998780ced624f950a9802fd5c6724a41271d3c45f36027235
# Code AST SHA-256:   4d0260c375944bb96a0c0524f95ede9ef646c54fe4ccd2ec5d8a0e5795a1a08f
# Verified Classes:   StaleAttestationFrontierError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleAttestationFrontierError(RuntimeError):
    """Raised when an attestation's revocation epoch is not causally dominated
    by a receiver-observed frontier snapshot taken after issuance."""
    pass


def validate_attestation(attestation, frontier_cache, now):
    """
    attestation: dict with subject, capability, issued_at, not_after,
                 issuer_sig, revocation_epoch
    frontier_cache: list of signed frontier snapshots observed by receiver,
                    each {epoch, observed_at, issuer_sig, issuer}
    Enforces causal freshness, not temporal closeness.
    """
    if attestation["not_after"] <= now:
        raise StaleAttestationFrontierError(
            f"attestation expired: not_after={attestation['not_after']} now={now}"
        )

    # Candidate frontiers must be signed by the same issuer and observed
    # strictly after the attestation was issued.
    candidates = [
        f for f in frontier_cache
        if f["issuer"] == attestation["issuer_sig"]["issuer"]
        and f["observed_at"] > attestation["issued_at"]
    ]
    if not candidates:
        raise StaleAttestationFrontierError(
            "no frontier snapshot observed after issuance; "
            "cannot establish causal dominance (clock-skew mitigation is insufficient)"
        )

    latest = max(candidates, key=lambda f: (f["epoch"], f["observed_at"]))
    if latest["epoch"] < attestation["revocation_epoch"]:
        raise StaleAttestationFrontierError(
            f"attestation epoch {attestation['revocation_epoch']} exceeds "
            f"receiver frontier {latest['epoch']}; capability may be revoked upstream"
        )

    return {"accepted": True, "frontier_epoch": latest["epoch"]}


def evict_on_frontier_advance(agent_context, new_frontier):
    """Sender-side: revocation must invalidate in-context attestation handles,
    not merely publish to the control plane."""
    evicted = []
    for handle in list(agent_context.attestations):
        if handle["revocation_epoch"] < new_frontier["epoch"]:
            agent_context.remove(handle)
            evicted.append(handle["capability"])
    if not evicted and new_frontier["epoch"] > agent_context.last_frontier_epoch:
        # No handles matched, but frontier advanced: record so replay can
        # reconstruct why a later handoff was or was not accepted.
        agent_context.last_frontier_epoch = new_frontier["epoch"]
    return evicted
