# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-warrant-attenuation-drift-across-a-delegated-aaif-attestation-chain-when-an-intermediate-hop-re-signs-with-a-broader-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-warrant-attenuation-drift-across-a-delegated-aaif-attestation-chain-when-an-intermediate-hop-re-signs-with-a-broader-scope.warrant.json
# Markdown SHA-256:   d3e46d5ada39bdbaa78d4033a7af5ef2f76feb79e59724c65ef090e9f04389b1
# Code AST SHA-256:   f42966194a3af65a6d41b87e3fd4c8d8fde9e538bfd20d02df8745f2afc5c8be
# Verified Classes:   AttenuationViolation, Hop
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AttenuationViolation(RuntimeError):
    """Raised when a downstream warrant's scope is not a subset of its grantor's."""


@dataclass(frozen=True)
class Hop:
    instance_id: str
    scope: FrozenSet[str]
    signature_valid: bool


def verify_chain(canonical_chain: list[Hop]) -> None:
    """Verify scope monotonicity over a canonically ordered root->leaf chain.

    Rejects on any hop whose scope is not a subset of its immediate grantor's.
    Signature validity is assumed already checked; this function checks the
    orthogonal containment invariant that signatures cannot express.
    """
    if not canonical_chain:
        raise AttenuationViolation("empty attestation chain")

    for i in range(len(canonical_chain) - 1):
        grantor = canonical_chain[i]
        grantee = canonical_chain[i + 1]
        if not grantee.signature_valid:
            raise AttenuationViolation(
                f"hop {i + 1} ({grantee.instance_id}) has invalid signature"
            )
        widened = grantee.scope - grantor.scope
        if widened:
            raise AttenuationViolation(
                f"hop {i + 1} ({grantee.instance_id}) widened scope by "
                f"{sorted(widened)} relative to grantor "
                f"{grantor.instance_id} ({sorted(grantor.scope)})"
            )


# Reproduction of the observed escalation:
chain = [
    Hop("orchestrator", frozenset({"read_repo", "write_plan"}), True),
    Hop("planner", frozenset({"read_repo", "write_plan"}), True),
    Hop("worker", frozenset({"read_repo", "write_plan", "exec_shell"}), True),
]
verify_chain(chain)  # raises AttenuationViolation on the worker hop
