# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-scoped-token-s-attenuation-chain-when-aaif-verifiable-credentials-cross-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-scoped-token-s-attenuation-chain-when-aaif-verifiable-credentials-cross-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   c135a723e297e3d970e7f15ee1635153866dfa16bcce44f538f8a7ca945675e4
# Code AST SHA-256:   eaa88a03aebde9c1b0a9435aa239427954d15b3a6a69725812368a930d833780
# Verified Classes:   AttenuationCompositionError, Scope, Token
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class AttenuationCompositionError(RuntimeError):
    """Raised when a delegated token chain is per-hop valid but the composed
    predicate is not entailed by the root verifiable credential's predicate."""
    def __init__(self, hop: str, dimension: str, reason: str):
        self.hop = hop
        self.dimension = dimension
        self.reason = reason
        super().__init__(f"hop={hop} dimension={dimension} reason={reason}")

@dataclass
class Scope:
    resource: Optional[str] = None
    action: Optional[str] = None
    window: Optional[tuple[int, int]] = None       # (start_hour, end_hour)
    depth: Optional[int] = None
    conditioned_on: Optional[str] = None            # dimension this one depends on
    defaulted: bool = False

@dataclass
class Token:
    iss: str
    sub: str
    scope: Scope
    issuance_meta: dict = field(default_factory=dict)

def _window_subset(child: tuple[int, int], parent: tuple[int, int]) -> bool:
    return parent[0] <= child[0] and child[1] <= parent[1]

def _entails(child: Scope, parent: Scope) -> tuple[bool, str]:
    # resource: glob subset (child pattern must be covered by parent pattern)
    if parent.resource and child.resource:
        if not child.resource.startswith(parent.resource.rstrip("*")):
            return False, "resource_not_covered"
    # action: set subset
    if parent.action and child.action:
        pset = set(parent.action.split("|"))
        cset = set(child.action.split("|"))
        if not cset.issubset(pset):
            return False, "action_not_subset"
    # window: interval subset — the dimension that broke
    if parent.window and child.window:
        if not _window_subset(child.window, parent.window):
            return False, "interval_widened"
    # depth: child depth must be < parent depth (attenuation consumes depth)
    if parent.depth is not None and child.depth is not None:
        if child.depth >= parent.depth:
            return False, "depth_not_attenuated"
    return True, "ok"

def verify_chain(chain: list[Token], root_scope: Scope) -> None:
    """chain[0] is the presented token, chain[-1] is the token minted by root holder."""
    # 1. structural invariant: no gap in iss/sub linkage
    for i in range(len(chain) - 1):
        if chain[i].iss != chain[i + 1].sub:
            raise AttenuationCompositionError(
                hop=f"{chain[i+1].iss}->{chain[i].iss}",
                dimension="linkage",
                reason="iss_sub_gap",
            )
    # 2. provenance: unknown or defaulted issuance is non-composable
    for i, tok in enumerate(chain[:-1]):
        if tok.scope.defaulted or not tok.issuance_meta:
            raise AttenuationCompositionError(
                hop=f"hop_{i}",
                dimension="provenance",
                reason="defaulted_or_unknown_issuance",
            )
    # 3. composed entailment against root VC
    for i, tok in enumerate(chain):
        parent = root_scope if i == len(chain) - 1 else chain[i + 1].scope
        ok, reason = _entails(tok.scope, parent)
        if not ok:
            raise AttenuationCompositionError(
                hop=f"hop_{i}",
                dimension=reason.split("_")[0],
                reason=reason,
            )

# Observed failure replay:
root = Scope(resource="repo:acme/*", action="read|write", window=(9, 17), depth=2)
p_tok = Token(iss="O", sub="P",
              scope=Scope(resource="repo:acme/svc-a", action="read|write",
                          window=(9, 17), depth=1),
              issuance_meta={"lib": "aaif-mint/1.2"})
x_tok = Token(iss="P", sub="X",
              scope=Scope(resource="repo:acme/svc-a", action="read",
                          window=(0, 24), depth=0),
              issuance_meta={"lib": "aaif-mint/1.2", "defaulted": True})

verify_chain([x_tok, p_tok], root)
# -> AttenuationCompositionError: hop=hop_0 dimension=provenance reason=defaulted_or_unknown_issuance
