# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-chain-is-transitively-over-broad-at-the-second-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-chain-is-transitively-over-broad-at-the-second-hop.warrant.json
# Markdown SHA-256:   d3a07fe32b68f3a56370511e13b873211f1ffe87f6df569052f20c9fb030d480
# Code AST SHA-256:   442efffd24566417aebec6c83c0740bf945b39b9623b1a0f9fa5195ee0b10dd5
# Verified Classes:   DelegationScopeInflation, RootScopeTamper, Attestation, Chain
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationScopeInflation(RuntimeError):
    """Raised when a delegated AAIF chain grants a capability the root never held."""


class RootScopeTamper(RuntimeError):
    """Raised when a chain header's declared root scope diverges from the signed root grant."""


@dataclass(frozen=True)
class Attestation:
    hop: int
    subject: str
    scoped_capability: FrozenSet[str]
    signature_valid: bool = True


@dataclass(frozen=True)
class Chain:
    attestations: tuple            # ordered root(0) .. terminal(n)
    declared_root_scope: FrozenSet[str]
    signed_root_grant: FrozenSet[str]
    header: dict = field(default_factory=dict)


def effective_cap(chain: Chain, upto: int) -> FrozenSet[str]:
    running = chain.signed_root_grant
    for att in chain.attestations[: upto + 1]:
        running = running & att.scoped_capability
    return running


def verify_chain(chain: Chain) -> str:
    if chain.declared_root_scope != chain.signed_root_grant:
        raise RootScopeTamper(
            f"header root scope {sorted(chain.declared_root_scope)} "
            f"!= signed grant {sorted(chain.signed_root_grant)}"
        )

    n = len(chain.attestations) - 1
    for att in chain.attestations:
        if not att.signature_valid:
            raise DelegationScopeInflation(f"hop {att.hop} signature invalid")

    terminal_cap = effective_cap(chain, n)
    if n < 2:
        return "accept_single_hop"

    unsound_hop = None
    for k in range(1, n):
        if not effective_cap(chain, k).issubset(effective_cap(chain, k - 1)):
            unsound_hop = k
            break

    if unsound_hop is None:
        return "accept_sound"

    injected = effective_cap(chain, n) - chain.signed_root_grant
    if injected:
        raise DelegationScopeInflation(
            f"hop {unsound_hop} re-widened scope; terminal reaches undelegated "
            f"capabilities {sorted(injected)}"
        )
    return "accept_unsound_but_terminal_safe"


if __name__ == "__main__":
    chain = Chain(
        attestations=(
            Attestation(0, "P", frozenset({"spend:approve<=50k", "vendor:read"})),
            Attestation(1, "O", frozenset({"spend:approve<=10k"})),
            Attestation(2, "W", frozenset({"spend:approve<=10k", "vendor:write"})),
            Attestation(3, "S", frozenset({"spend:approve<=8k", "vendor:write"})),
        ),
        declared_root_scope=frozenset({"spend:approve<=50k", "vendor:read", "vendor:write"}),
        signed_root_grant=frozenset({"spend:approve<=50k", "vendor:read"}),
    )
    try:
        verify_chain(chain)
    except RootScopeTamper as e:
        print("REJECT root_scope_tamper:", e)
