# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-warrant-has-silently-re-scoped-to-the-delegate-s-authority-ceiling.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-aaif-warrant-has-silently-re-scoped-to-the-delegate-s-authority-ceiling.warrant.json
# Markdown SHA-256:   d70dce66cbb3eea95abf63f636e59f1e78905b9f3c813d292dd69889ce843f55
# Code AST SHA-256:   c26c39a75d359f436d6b6b53e99219b737c76153bb3c4460d80091bb813cf616
# Verified Classes:   WarrantAttenuationGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class WarrantAttenuationGapError(RuntimeError):
    """Raised when a delegated AAIF warrant cannot be folded from
    delegator-signed attenuation records and would otherwise be
    admitted via leaf-scope intersection (silent re-scoping)."""


def fold_effective_scope(root_scope: frozenset, attenuation_records: list[dict]) -> frozenset:
    """Fold delegator-authored narrowing records root->leaf.

    Each record must be a dict: {"from": cap_set, "to": cap_set,
    "removed": cap_set, "signer": str, "parent_sig": str}.
    Refuses to proceed if any hop is missing or widens.
    """
    caps = frozenset(root_scope)
    for i, rec in enumerate(attenuation_records):
        if rec.get("signer") is None or rec.get("parent_sig") is None:
            raise WarrantAttenuationGapError(
                f"hop {i} lacks delegator signature; cannot fold chain"
            )
        removed = frozenset(rec["removed"])
        if not removed.issubset(caps):
            raise WarrantAttenuationGapError(
                f"hop {i} removes capabilities not present in parent: "
                f"{removed - caps}"
            )
        caps = caps - removed
    return caps


def admit_warrant(root_scope, attenuation_records, leaf_declared_scope, chain_depth: int):
    if chain_depth == 1:
        # Single hop: leaf-declared intersection is equivalent to folding.
        return frozenset(leaf_declared_scope).intersection(frozenset(root_scope))
    folded = fold_effective_scope(root_scope, attenuation_records)
    if not frozenset(leaf_declared_scope).issubset(folded):
        raise WarrantAttenuationGapError(
            "leaf declares capabilities beyond folded chain; "
            f"excess={frozenset(leaf_declared_scope) - folded}"
        )
    if len(attenuation_records) != chain_depth - 1:
        raise WarrantAttenuationGapError(
            f"chain depth {chain_depth} but only {len(attenuation_records)} "
            "attenuation records present; refusing leaf-intersection fallback"
        )
    return folded
