# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-credential-chain-when-a-scoped-capability-token-s-attenuation-proof-is-valid-but-its-scope-lattice-has-be.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-credential-chain-when-a-scoped-capability-token-s-attenuation-proof-is-valid-but-its-scope-lattice-has-be.warrant.json
# Markdown SHA-256:   c69dfb65106557d8e6ef1ce3265fcc7db25232816d56f15fbe42c3433799018a
# Code AST SHA-256:   297613142688f6010f2e199279e8ecb49c12d4dc3463da7b65d38a4e97cf7dfd
# Verified Classes:   ScopeLatticeWideningError, ScopeTerm, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class ScopeLatticeWideningError(RuntimeError):
    """Raised when a delegated credential chain's transitive meet does not
    bound the requested scope term under a single canonical encoding."""


@dataclass(frozen=True)
class ScopeTerm:
    kind: str          # "literal" | "wildcard" | "negated"
    value: str


@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    subject: str
    declared_scope: FrozenSet[ScopeTerm]
    encoding_version: str
    witness_signature_valid: bool


def _is_literal(term: ScopeTerm) -> bool:
    return term.kind == "literal"


def verify_chain_exercise(
    chain: list[CapabilityToken],
    root_scope: Optional[FrozenSet[ScopeTerm]],
    requested: ScopeTerm,
    canonical_encoding: str,
) -> None:
    # Hop-by-hop signature validity is necessary but not sufficient.
    for hop in chain:
        if not hop.witness_signature_valid:
            raise ScopeLatticeWideningError(
                f"invalid witness signature at hop {hop.issuer}->{hop.subject}"
            )
        if hop.encoding_version != canonical_encoding:
            raise ScopeLatticeWideningError(
                f"hop {hop.issuer}->{hop.subject} uses encoding "
                f"{hop.encoding_version!r}, canonical is {canonical_encoding!r}"
            )

    # Non-literal terms require root-meet recomputation; refuse otherwise.
    if not _is_literal(requested):
        if root_scope is None:
            raise ScopeLatticeWideningError(
                "cannot exercise non-literal scope term without root lattice: "
                "chain is widening-unsafe"
            )
        transitive_meet = set(root_scope)
        for hop in chain:
            transitive_meet &= set(hop.declared_scope)
        if requested not in transitive_meet:
            raise ScopeLatticeWideningError(
                f"requested term {requested} not bounded by transitive meet; "
                f"widening introduced downstream of root grant"
            )
        return

    # Literal terms: last hop's declared scope must contain the literal.
    if requested not in chain[-1].declared_scope:
        raise ScopeLatticeWideningError(
            f"requested literal {requested} absent from terminal hop scope"
        )
