# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-third-party-safety-endorsements-from-vouching-for-a-mutated-agent-after-receipt-chain-re-anchoring.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-third-party-safety-endorsements-from-vouching-for-a-mutated-agent-after-receipt-chain-re-anchoring.warrant.json
# Markdown SHA-256:   d12d4ef1c9adb3808b3458745bc27823ca121885be644e932d350181c8d22be4
# Code AST SHA-256:   a3cb8b99b7f67be49ed491fa093a63b1db2d85bae5d7230dd045f8ed3358dc28
# Verified Classes:   EndorsementReAnchorError, Receipt, Endorsement
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Iterable, Optional


class EndorsementReAnchorError(RuntimeError):
    """Raised when an endorsement cannot be carried forward to the current head."""


@dataclass(frozen=True)
class Receipt:
    index: int
    effect_classes: FrozenSet[str]


@dataclass(frozen=True)
class Endorsement:
    agent_id: str
    endorsed_head: int
    policy: str
    sensitive_effects: FrozenSet[str]
    expires_at: float


def admit_agent(
    endorsement: Endorsement,
    chain: Iterable[Receipt],
    current_head: int,
    now: float,
) -> None:
    chain = list(chain)
    if now >= endorsement.expires_at:
        raise EndorsementReAnchorError(
            f"endorsement for {endorsement.agent_id} expired at {endorsement.expires_at}"
        )
    if endorsement.endorsed_head > current_head:
        raise EndorsementReAnchorError(
            f"endorsed head {endorsement.endorsed_head} is ahead of current head {current_head}"
        )

    segment = [r for r in chain if endorsement.endorsed_head < r.index <= current_head]
    if not segment and endorsement.endorsed_head != current_head:
        raise EndorsementReAnchorError(
            f"receipt chain has a gap between {endorsement.endorsed_head} and {current_head}"
        )

    for r in segment:
        overlap = r.effect_classes & endorsement.sensitive_effects
        if overlap:
            raise EndorsementReAnchorError(
                f"endorsement for {endorsement.agent_id} is stale: receipt {r.index} "
                f"introduces sensitive effects {sorted(overlap)} for policy "
                f"{endorsement.policy}; re-endorsement required at head {current_head}"
            )
    # Endorsement carries forward: segment is policy-inert for this policy.
