# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-agent-card-whose-issuer-chain-validates-but-whose-capability-scope-was-narrowed-by-an-intermediate-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-agent-card-whose-issuer-chain-validates-but-whose-capability-scope-was-narrowed-by-an-intermediate-hop.warrant.json
# Markdown SHA-256:   369ceda801ba24ec9e957f683d61fefef047912fb2b2d5b97150ecb26a5ebda0
# Code AST SHA-256:   da26f4ac0090f5c0d9b4ae0207c273b7b86a9d95d4dd5a941f3e356401889938
# Verified Classes:   ScopeAttenuationError, AgentCard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeAttenuationError(RuntimeError):
    """Raised when a delegated Agent Card widens or drops an ancestor constraint."""
    pass


@dataclass
class AgentCard:
    issuer: str
    parent_digest: Optional[str]
    scope: set[str]
    constraints: dict[str, object] = field(default_factory=dict)
    waived_by: dict[str, str] = field(default_factory=dict)  # key -> hop issuer


RESTRICTIVENESS = {"max_delegation_depth": lambda a, b: b <= a,
                   "data_residency": lambda a, b: b == a}


def verify_chain(chain: list[AgentCard], requested_tool: str) -> None:
    if not chain or chain[0].parent_digest is not None:
        raise ScopeAttenuationError("chain does not terminate at a self-signed root")

    for i in range(1, len(chain)):
        if chain[i].parent_digest is None:
            raise ScopeAttenuationError(f"hop {chain[i].issuer} has no parent binding (truncated chain)")

    leaf = chain[-1]
    if requested_tool not in leaf.scope:
        raise ScopeAttenuationError(f"tool {requested_tool!r} not in leaf scope")

    inherited: dict[str, object] = {}
    for card in chain:
        for key, val in card.constraints.items():
            inherited.setdefault(key, val)

    for key, origin_val in inherited.items():
        leaf_val = leaf.constraints.get(key)
        if leaf_val is None:
            if key in leaf.waived_by:
                continue
            raise ScopeAttenuationError(
                f"constraint {key!r} present in ancestor but dropped at leaf with no signed waiver"
            )
        check = RESTRICTIVENESS.get(key)
        if check is None:
            raise ScopeAttenuationError(f"constraint {key!r} not in closed registry; attenuation unprovable")
        if not check(origin_val, leaf_val):
            raise ScopeAttenuationError(
                f"constraint {key!r} widened: ancestor={origin_val!r} leaf={leaf_val!r}"
            )
