# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-scope-narrowing-failure-in-aaif-cross-issuer-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-credential-scope-narrowing-failure-in-aaif-cross-issuer-exchange.warrant.json
# Markdown SHA-256:   c00ebc4917c42dbc930085ccaae7e75ac2539770eea283e910a8e51689908cf2
# Code AST SHA-256:   fd813198d527e641a134f7a13e83ac17891d099af32794538eb943025527ef75
# Verified Classes:   ScopeWideningError, Credential, NormalizationTable
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class ScopeWideningError(RuntimeError):
    """Raised when a delegated-credential chain widens effective scope."""
    pass

@dataclass(frozen=True)
class Credential:
    issuer: str
    scope: FrozenSet[str]
    delegation_depth: int
    is_empty_scope: bool = False  # distinguishes [] from absent field

@dataclass
class NormalizationTable:
    # maps raw token -> replacement; MUST be narrowing
    rules: dict = field(default_factory=dict)

    def load(self, rule: str, replacement: str, lattice_subset) -> None:
        if not lattice_subset(replacement, rule):
            raise ScopeWideningError(
                f"non-narrowing mapping {rule!r} -> {replacement!r} rejected at load"
            )
        self.rules[rule] = replacement

def verify_chain(chain, table: NormalizationTable, lattice_subset) -> FrozenSet[str]:
    if not chain:
        raise ScopeWideningError("empty chain")
    # depth must match observed chain length
    if chain[0].delegation_depth != len(chain):
        raise ScopeWideningError(
            f"declared depth {chain[0].delegation_depth} != chain length {len(chain)}"
        )
    # raw-token intersection first
    effective = set(chain[0].scope)
    for cred in chain[1:]:
        if cred.is_empty_scope:
            # empty set is the null grant, not "absent"
            effective &= set()
        else:
            effective &= set(cred.scope)
        if not effective:
            return frozenset()
    # apply normalization only if provably narrowing
    normalized = set()
    for tok in effective:
        repl = table.rules.get(tok, tok)
        if not lattice_subset(repl, tok):
            raise ScopeWideningError(
                f"normalization widened {tok!r} -> {repl!r} mid-pipeline"
            )
        normalized.add(repl)
    result = frozenset(normalized)
    # final assertion: result must be subset of every hop's raw scope
    for cred in chain:
        if not result <= cred.scope:
            raise ScopeWideningError(
                f"effective scope {result} exceeds hop scope {cred.scope}"
            )
    return result
