# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-agent-identity-credential-whose-issuer-chain-re-anchors-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-delegated-agent-identity-credential-whose-issuer-chain-re-anchors-mid-session.warrant.json
# Markdown SHA-256:   0a6185aa6f62a143ab083cf1f8ffc42f8177eb30512cdf706dd1edbfe4c2b901
# Code AST SHA-256:   558b18b2854caa41d0e5c31fe11236b7510fd99cb1ea75c83892a99a9d92df1a
# Verified Classes:   AnchorDiscontinuityError, BindingRecord, ResolvedChain
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AnchorDiscontinuityError(RuntimeError):
    """Raised when a re-verified credential chain no longer re-anchors to the
    root fingerprint and scope vector recorded at admission time."""
    pass


@dataclass(frozen=True)
class BindingRecord:
    leaf_cred_id: str
    root_fingerprint: str
    scope_vector: tuple[str, ...]
    chain_depth: int
    admission_time: float


@dataclass
class ResolvedChain:
    leaf_cred_id: str
    root_fingerprint: str
    scopes: tuple[str, ...]
    depth: int
    signatures_valid: bool


def verify_continuity(
    admitted: Optional[BindingRecord],
    resolved: ResolvedChain,
    now: float,
) -> BindingRecord:
    """Re-verify a delegated credential against its admission-time binding.

    Returns the (possibly narrowed) binding to carry forward. Raises
    AnchorDiscontinuityError when the chain re-anchors to a different root,
    widens scope, or changes depth — all of which require fresh admission,
    not in-session continuation.
    """
    if not resolved.signatures_valid:
        raise AnchorDiscontinuityError(
            f"leaf {resolved.leaf_cred_id}: signature verification failed"
        )

    if admitted is None:
        # First admission: pin the tuple. Caller must have made an
        # authorization decision before this point.
        return BindingRecord(
            leaf_cred_id=resolved.leaf_cred_id,
            root_fingerprint=resolved.root_fingerprint,
            scope_vector=resolved.scopes,
            chain_depth=resolved.depth,
            admission_time=now,
        )

    if resolved.root_fingerprint != admitted.root_fingerprint:
        raise AnchorDiscontinuityError(
            f"leaf {resolved.leaf_cred_id}: root re-anchored "
            f"{admitted.root_fingerprint} -> {resolved.root_fingerprint}; "
            f"requires fresh admission, not session continuation"
        )

    if resolved.depth != admitted.chain_depth:
        raise AnchorDiscontinuityError(
            f"leaf {resolved.leaf_cred_id}: chain depth changed "
            f"{admitted.chain_depth} -> {resolved.depth}; "
            f"intermediary set altered under existing session"
        )

    admitted_scopes = set(admitted.scope_vector)
    resolved_scopes = set(resolved.scopes)
    if not resolved_scopes.issubset(admitted_scopes):
        widened = resolved_scopes - admitted_scopes
        raise AnchorDiscontinuityError(
            f"leaf {resolved.leaf_cred_id}: scope widened under existing "
            f"session by {sorted(widened)}; effective authority must be "
            f"the intersection, not the union"
        )

    # Same root, non-expanding scopes: carry forward the narrowed intersection.
    return BindingRecord(
        leaf_cred_id=admitted.leaf_cred_id,
        root_fingerprint=admitted.root_fingerprint,
        scope_vector=tuple(sorted(resolved_scopes)),
        chain_depth=admitted.chain_depth,
        admission_time=admitted.admission_time,
    )
