# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-capability-scoped-delegation-token-has-been-silently-widened-by-an-intermediate-agent-in-the-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-capability-scoped-delegation-token-has-been-silently-widened-by-an-intermediate-agent-in-the-chain.warrant.json
# Markdown SHA-256:   058cb36cdcf9e55b5865cf1eae522e653783652dc347235bf422c529724cecf4
# Code AST SHA-256:   9f62b14f608a688df5fca7e103a9140fa21e7f35bd3c2c66d16e96ceba0b5ae9
# Verified Classes:   DelegationChainViolation, CDT
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationChainViolation(RuntimeError):
    """Raised when a CDT chain fails scope-lattice or constraint verification."""


@dataclass(frozen=True)
class CDT:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    constraints: FrozenSet[str]  # e.g. {"subset", "no-redelegate"}
    signature_valid: bool


_IMPLEMENTED_CONSTRAINTS = frozenset({"subset"})


def verify_chain(chain: list[CDT], required_capability: str) -> None:
    if not chain:
        raise DelegationChainViolation("empty delegation chain")

    for i, token in enumerate(chain):
        if not token.signature_valid:
            raise DelegationChainViolation(f"hop {i}: invalid signature")

        unknown = token.constraints - _IMPLEMENTED_CONSTRAINTS
        if unknown:
            # RFC-8693-style critical-constraint rule: reject what you cannot evaluate.
            raise DelegationChainViolation(
                f"hop {i}: unparseable critical constraint(s) {sorted(unknown)}"
            )

        if i == 0:
            continue

        parent, child = chain[i - 1], token
        if child.issuer != parent.subject:
            raise DelegationChainViolation(
                f"hop {i}: issuer {child.issuer} != parent subject {parent.subject}"
            )
        if "no-redelegate" in parent.constraints:
            raise DelegationChainViolation(
                f"hop {i}: parent forbids re-delegation but child exists"
            )
        if "subset" in parent.constraints and not child.scope.issubset(parent.scope):
            widened = child.scope - parent.scope
            raise DelegationChainViolation(
                f"hop {i}: scope widened by {sorted(widened)} "
                f"(child={sorted(child.scope)}, parent={sorted(parent.scope)})"
            )

    leaf = chain[-1]
    if required_capability not in leaf.scope:
        raise DelegationChainViolation(
            f"leaf scope {sorted(leaf.scope)} lacks required capability "
            f"{required_capability!r}"
        )


def pre_tool_call(chain: list[CDT], capability: str) -> None:
    try:
        verify_chain(chain, capability)
    except DelegationChainViolation:
        # Do not execute, do not retry with a wider token, do not fall back.
        raise
