# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-anchor-collapse-during-cross-org-agent-federation-capability-re-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-transitive-trust-anchor-collapse-during-cross-org-agent-federation-capability-re-attestation.warrant.json
# Markdown SHA-256:   c09610d03b848b721bb9490b486d695b48787cf0dd51dbcc034659f212af43a9
# Code AST SHA-256:   a63cea0f2e8f8378f76fb42a5f79df421b9e44a22e1e243977df5ce8a92f6d7e
# Verified Classes:   TrustAnchorCollapseError, DispatchRecord, ReAttestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class TrustAnchorCollapseError(RuntimeError):
    """Raised when a re-attested capability's authority scope exceeds the
    authority authorized at task dispatch, without an explicit widening record."""


@dataclass(frozen=True)
class DispatchRecord:
    anchor_id: str
    policy_version: int
    scope: FrozenSet[str]
    dispatch_ts: float


@dataclass(frozen=True)
class ReAttestation:
    anchor_id: str
    policy_version: int
    scope: FrozenSet[str]
    issued_ts: float


def validate_re_attestation(
    dispatch: DispatchRecord,
    re_att: ReAttestation,
    widening_authorization_present: bool,
) -> None:
    # Invariant 1: anchor identity must not change mid-task.
    if re_att.anchor_id != dispatch.anchor_id:
        raise TrustAnchorCollapseError(
            f"anchor identity changed mid-task: dispatched {dispatch.anchor_id!r}, "
            f"re-attested {re_att.anchor_id!r}"
        )

    # Invariant 2: scope must be non-widening (subset of dispatched scope),
    # unless an explicit widening authorization record is presented.
    widened = re_att.scope - dispatch.scope
    if widened and not widening_authorization_present:
        raise TrustAnchorCollapseError(
            f"transitive trust-anchor collapse: re-attestation widened scope by "
            f"{sorted(widened)} under anchor {re_att.anchor_id!r} "
            f"(policy_version {dispatch.policy_version} -> {re_att.policy_version}) "
            f"with no signed ScopeWideningAuthorization"
        )

    # Invariant 3: scope must be non-regressing on dispatched capabilities,
    # otherwise the task breaks mid-execution (capability regression).
    regressed = dispatch.scope - re_att.scope
    if regressed:
        raise TrustAnchorCollapseError(
            f"capability regression: re-attestation dropped dispatched capabilities "
            f"{sorted(regressed)}; task cannot continue under reduced authority"
        )

    # Invariant 4: if policy_version drifted, flag for audit reconciliation
    # even when scopes happen to match, because validator and issuer were
    # operating on different policy views.
    if re_att.policy_version != dispatch.policy_version:
        # Non-fatal but must be recorded; escalation is a policy decision.
        # In strict mode this is a hard failure.
        raise TrustAnchorCollapseError(
            f"policy_version drift without scope change: "
            f"{dispatch.policy_version} -> {re_att.policy_version}; "
            f"audit replay will disagree on effective authority"
        )
