# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-s-scope-attestation-lattice-has-silently-collapsed-under-intersection-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-s-scope-attestation-lattice-has-silently-collapsed-under-intersection-semantics.warrant.json
# Markdown SHA-256:   676e7bf18898fa927fed93db05716d6ec67530e978101dd2e42d21697e98697c
# Code AST SHA-256:   2442c54125e85220ac4ea8e65f64cef28086c475d63a116e1c5140b236a39ae7
# Verified Classes:   LatticeCollapseError, Hop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class LatticeCollapseError(RuntimeError):
    """Raised when a delegated credential's effective scope is a strict superset
    of the recomputed ancestor intersection, despite passing per-hop checks."""
    pass


@dataclass(frozen=True)
class Hop:
    hop_id: str
    # The scope the issuer's policy engine actually granted at this hop.
    granted: FrozenSet[str]
    # The scope the child *requested* (persisted, signed, part of provenance).
    requested: FrozenSet[str]
    # The scope field as serialized into the credential (may be widened by encoder).
    serialized_attested: FrozenSet[str]


def recompute_boundary(root_attested: FrozenSet[str], chain: list[Hop]) -> FrozenSet[str]:
    """Recompute the authoritative grant boundary from root attestation and the
    chain of narrowing requests. Ignores each hop's serialized_attested field."""
    boundary = root_attested
    for hop in chain:
        boundary = boundary & hop.requested
    return boundary


def verify_delegation(
    root_attested: FrozenSet[str],
    chain: list[Hop],
    leaf_effective: FrozenSet[str],
) -> None:
    # Per-hop schema/signature checks are assumed to have passed upstream.
    # The only check here is the lattice invariant.
    recomputed = recompute_boundary(root_attested, chain)

    if not leaf_effective <= recomputed:
        widening = leaf_effective - recomputed
        # Diagnose whether the collapse originated from a widened serialized field.
        culprits = [
            h.hop_id for h in chain
            if h.serialized_attested - (h.granted & h.requested)
        ]
        raise LatticeCollapseError(
            f"Leaf effective scope exceeds recomputed ancestor boundary. "
            f"Unauthorized capabilities: {sorted(widening)}. "
            f"Widened serialized_attested fields at hops: {culprits or ['<root>']}. "
            f"Recomputed boundary: {sorted(recomputed)}; "
            f"leaf held: {sorted(leaf_effective)}."
        )

    # Also assert per-capability ancestry membership for monotonicity.
    for cap in leaf_effective:
        for hop in chain:
            if cap not in hop.granted:
                raise LatticeCollapseError(
                    f"Capability {cap!r} present in leaf but not granted at hop "
                    f"{hop.hop_id}; monotonicity violated across ancestry."
                )


# --- Illustrating the observed collapse ---
root = frozenset({"read:docs/**", "read:index", "summarize"})
chain = [
    Hop("hop1", granted=frozenset({"read:docs/**", "summarize"}),
        requested=frozenset({"read:docs/**", "summarize"}),
        serialized_attested=frozenset({"read:docs/**", "summarize"})),
    Hop("hop2", granted=frozenset({"read:docs/**", "summarize"}),
        requested=frozenset({"read:docs/**", "read:index", "summarize"}),
        # encoder emitted granted | requested:
        serialized_attested=frozenset({"read:docs/**", "read:index", "summarize"})),
    Hop("hop3", granted=frozenset({"read:index"}),
        requested=frozenset({"read:index"}),
        serialized_attested=frozenset({"read:index"})),
]
leaf = frozenset({"read:index"})

verify_delegation(root, chain, leaf)  # raises LatticeCollapseError
