# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-delegated-capability-attenuation-failure-in-aaif-token-chains-under-transitive-consent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-delegated-capability-attenuation-failure-in-aaif-token-chains-under-transitive-consent.warrant.json
# Markdown SHA-256:   a806f56dad79eb7527acf37d039ef08a9476dacac98ef73237097775a75dfcca
# Code AST SHA-256:   f935afc624d18627822193e4e8de4d6edf2ed6ce33c28262ee6d738bba8ce966
# Verified Classes:   ConsentChainIntegrityError, AttenuationProof, VerifiedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ConsentChainIntegrityError(RuntimeError):
    """Raised when a delegated AAIF token's consent chain is structurally invalid."""


@dataclass
class AttenuationProof:
    delegation_depth: int
    consent_depth: int
    parent_consent_issuer: str   # DID of the issuer of the referenced consent record
    delegating_agent_did: str    # DID of the agent emitting this hop
    purpose_annotations: frozenset[str]


@dataclass
class VerifiedToken:
    hops: list[AttenuationProof]
    required_annotations: frozenset[str]
    consent_ttl_seconds: int


def verify_transitive_consent_closure(token: VerifiedToken, registry_reachable: bool) -> None:
    if not registry_reachable:
        if token.consent_ttl_seconds > 0:
            # Do NOT trust embedded claims; quarantine instead of accept.
            raise ConsentChainIntegrityError(
                "consent registry unreachable and token still live: quarantine, do not accept"
            )
        raise ConsentChainIntegrityError("consent registry unreachable and token expired")

    accumulated: set[str] = set()
    for i, hop in enumerate(token.hops):
        if hop.consent_depth != hop.delegation_depth:
            raise ConsentChainIntegrityError(
                f"hop {i}: consent_depth={hop.consent_depth} != "
                f"delegation_depth={hop.delegation_depth} (attenuation drift signal)"
            )
        if hop.parent_consent_issuer == hop.delegating_agent_did:
            raise ConsentChainIntegrityError(
                f"hop {i}: self-issued consent node by {hop.delegating_agent_did} "
                f"(consent re-rooting signal)"
            )
        accumulated |= set(hop.purpose_annotations)

    if not token.required_annotations.issubset(accumulated):
        missing = token.required_annotations - accumulated
        raise ConsentChainIntegrityError(
            f"transitive consent closure missing required annotations: {sorted(missing)}"
        )
