# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-issuer-chain-is-valid-but-whose-scope-intersection-is-empty-at-depth-3.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-issuer-chain-is-valid-but-whose-scope-intersection-is-empty-at-depth-3.warrant.json
# Markdown SHA-256:   c1760f34571e5d7b7a1eb9437a3f2db3fa13a6ed6664499fdcec4194e9842176
# Code AST SHA-256:   7bad48c9ef9d2552e5145c2b75012370010e1c0a06ba6c0c460a08fbc19b4b0d
# Verified Classes:   FoldDivergenceError, UnwitnessedFoldError, Scope, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class FoldDivergenceError(RuntimeError):
    """Raised when a leaf's recomputed scope fold disagrees with the issuer's signed fold witness."""


class UnwitnessedFoldError(RuntimeError):
    """Raised when a chain hop carries a wildcard/union scope but no signed fold witness."""


@dataclass(frozen=True)
class Scope:
    atoms: frozenset[str]
    has_wildcard_or_union: bool


@dataclass(frozen=True)
class Warrant:
    scope: Scope
    fold_witness: str | None  # sha256 of canonicalized intersection result, signed by issuer
    parent_digests: tuple[str, ...]


def canonical_fold_digest(scope: Scope) -> str:
    payload = "|".join(sorted(scope.atoms)).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def verify_chain(chain: list[Warrant]) -> Scope:
    if not chain:
        raise FoldDivergenceError("empty delegation chain has no effective authority")

    effective = chain[0].scope
    for depth, warrant in enumerate(chain[1:], start=1):
        narrowed = Scope(
            atoms=effective.atoms & warrant.scope.atoms,
            has_wildcard_or_union=effective.has_wildcard_or_union or warrant.scope.has_wildcard_or_union,
        )

        # Guardrail: wildcard/union scopes require a signed fold witness at any depth >= 2.
        if narrowed.has_wildcard_or_union and depth >= 2:
            if warrant.fold_witness is None:
                raise UnwitnessedFoldError(
                    f"hop {depth} carries wildcard/union scope with no fold witness; "
                    f"raw recompute is fold-order dependent and must be rejected"
                )
            expected = canonical_fold_digest(narrowed)
            if warrant.fold_witness != expected:
                raise FoldDivergenceError(
                    f"hop {depth} fold witness {warrant.fold_witness[:12]}... "
                    f"!= leaf recompute {expected[:12]}...; issuer and leaf folded in different orders"
                )

        effective = narrowed
        if not effective.atoms:
            raise FoldDivergenceError(
                f"hop {depth} resolved to empty scope; delegation is valid but grants nothing"
            )

    return effective
