# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-cross-issuer-attestation-collapse-when-a-delegated-agent-credential-s-issuer-chain-re-signs-under-a-rotated-root-mid-han.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-cross-issuer-attestation-collapse-when-a-delegated-agent-credential-s-issuer-chain-re-signs-under-a-rotated-root-mid-han.warrant.json
# Markdown SHA-256:   4c8a2c7dac6a8383f0fce6ba91d87e2585818f1874819c5ab510fee9c2f88af9
# Code AST SHA-256:   6946223912b4e85f2c9ce05615498cdfaae9b58c90f3f062a5a0062bd8e3afd1
# Verified Classes:   AttestationCollapseError, ResolvedChain
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AttestationCollapseError(RuntimeError):
    """Raised when a live credential's resolved delegation constraints
    diverge from those recorded at admission, despite all signatures
    verifying under currently-published issuer keys."""
    pass


@dataclass(frozen=True)
class ResolvedChain:
    chain_digest: str
    max_depth: int
    scopes: FrozenSet[str]
    root_version: str


def verify_live_call(
    admitted: ResolvedChain,
    resolved_now: ResolvedChain,
    signature_valid: bool,
) -> None:
    # Signature validity is necessary but NOT sufficient.
    if not signature_valid:
        raise AttestationCollapseError(
            f"signature invalid for chain {resolved_now.chain_digest}"
        )

    # The binding invariant: resolved constraints must match admission.
    # A digest mismatch alone is merely suspicious; a *constraint* drift
    # means the credential is unauthorized under current root policy.
    if resolved_now.max_depth < admitted.max_depth:
        raise AttestationCollapseError(
            "delegation depth narrowed by root rotation: "
            f"admitted depth={admitted.max_depth} "
            f"resolved depth={resolved_now.max_depth} "
            f"(root {admitted.root_version} -> {resolved_now.root_version}); "
            "cached credential is no longer covered by current warrant"
        )

    if not resolved_now.scopes.issuperset(admitted.scopes):
        missing = admitted.scopes - resolved_now.scopes
        raise AttestationCollapseError(
            f"scope revoked under rotated root: missing={sorted(missing)} "
            f"(root {admitted.root_version} -> {resolved_now.root_version})"
        )

    if resolved_now.chain_digest != admitted.chain_digest:
        # Digest drift with stable constraints: log for replay audit,
        # but do not admit silently if the task is side-effecting.
        raise AttestationCollapseError(
            "chain re-parented under rotated root without constraint "
            f"change; require re-attestation (digest {admitted.chain_digest} "
            f"-> {resolved_now.chain_digest})"
        )
