# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-widened-scope-in-a-delegated-aaif-capability-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-widened-scope-in-a-delegated-aaif-capability-chain.warrant.json
# Markdown SHA-256:   08137d48de18aff93c281104a12f27047dc1ce37ab6f17075c946185943a2ffd
# Code AST SHA-256:   71e06d082bac4c3f80cc7fcaa8f6e4b8dda6a183afa667dda52cbc1bc3e18691
# Verified Classes:   ScopeWideningError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ScopeWideningError(RuntimeError):
    """Raised when a delegated capability chain confers more authority than
    the intersection of its links permits, or when a link's leaf scope claim
    does not equal the recomputed intersection."""
    pass


def verify_chain(chain):
    # chain: list of token dicts ordered root -> leaf.
    # Each token MUST carry 'held_scope' and 'conferred_scope' (sets of str).
    if not chain:
        raise ScopeWideningError("empty capability chain")

    effective = None
    for i, tok in enumerate(chain):
        if "conferred_scope" not in tok or "held_scope" not in tok:
            raise ScopeWideningError(
                f"hop {i} ({tok.get('iss','?')}) missing held/conferred scope; "
                "cannot verify delegation intent"
            )
        held = set(tok["held_scope"])
        conferred = set(tok["conferred_scope"])

        # A delegator may only confer authority it actually holds.
        if not conferred <= held:
            raise ScopeWideningError(
                f"hop {i} ({tok.get('iss','?')}) confers {sorted(conferred - held)} "
                "which it does not hold"
            )

        effective = conferred if effective is None else (effective & conferred)
        if not effective:
            raise ScopeWideningError(
                f"hop {i} ({tok.get('iss','?')}) intersection is empty; chain confers nothing"
            )

    leaf = chain[-1]
    leaf_claim = set(leaf.get("scope", []))
    if leaf_claim != effective:
        raise ScopeWideningError(
            f"leaf scope claim {sorted(leaf_claim)} != recomputed intersection "
            f"{sorted(effective)}; chain is widened or narrowed in transit"
        )
    return effective
