# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-widened-by-a-peer-s-re-signature-the-transitive-attenuation-break-in-aaif-delegati.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-widened-by-a-peer-s-re-signature-the-transitive-attenuation-break-in-aaif-delegati.warrant.json
# Markdown SHA-256:   5e6d907fd9e54c64f1858ff61f5ccbc8b8df4e8be7bf8bb315ae21f51a47af4f
# Code AST SHA-256:   4b854e73858c9a1310feeccdb59b20d00cdfd32b398e52df140af1e61d2c8a6b
# Verified Classes:   DelegationEnvelopeIncomplete, ScopeRelationUndecidable, AttenuationViolation, AncestorRevoked, Scope, DelegatedCredential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Optional

class DelegationEnvelopeIncomplete(RuntimeError):
    """Parent scope commitment absent; attenuation uncomputable."""

class ScopeRelationUndecidable(RuntimeError):
    """Subset relation cannot be decided over the scope algebra."""

class AttenuationViolation(RuntimeError):
    """Child scope is not a subset of parent scope; widening detected."""

class AncestorRevoked(RuntimeError):
    """A credential in the delegation chain has been revoked."""


@dataclass(frozen=True)
class Scope:
    tools: FrozenSet[str]
    region: str
    max_calls: int
    dimensions: FrozenSet[str] = field(default_factory=frozenset)

    def subset_of(self, parent: "Scope") -> bool:
        # Monotone attenuation: tools shrink, budget non-increasing, region pinned.
        return (
            self.tools.issubset(parent.tools)
            and self.region == parent.region
            and self.max_calls <= parent.max_calls
            and self.dimensions.issubset(parent.dimensions)
        )


@dataclass(frozen=True)
class DelegatedCredential:
    cred_id: str
    issuer_key: str
    subject: str
    scope: Scope
    parent_scope_hash: Optional[str]   # H(scope) of C_n, signed into C_{n+1}
    parent_scope: Optional[Scope]      # carried so receiver can recompute
    signature_valid: bool
    not_before: int
    expiry: int
    parent_not_before: int
    parent_expiry: int


def verify_delegation(
    child: DelegatedCredential,
    revoked_ids: FrozenSet[str],
    chain_ids: FrozenSet[str],
) -> None:
    if not child.signature_valid:
        raise AttenuationViolation(f"bad signature on {child.cred_id}")

    # Ancestor revocation must poison the whole subtree, not just this node.
    for cid in chain_ids:
        if cid in revoked_ids:
            raise AncestorRevoked(f"ancestor {cid} revoked; {child.cred_id} invalid")

    if child.parent_scope is None or child.parent_scope_hash is None:
        raise DelegationEnvelopeIncomplete(
            f"{child.cred_id} lacks parent scope commitment; cannot prove attenuation"
        )

    recomputed = hashlib.sha256(repr(child.parent_scope).encode()).hexdigest()
    if recomputed != child.parent_scope_hash:
        raise AttenuationViolation(
            f"{child.cred_id} parent scope hash mismatch (tampered parent)"
        )

    if not child.scope.subset_of(child.parent_scope):
        raise AttenuationViolation(
            f"{child.cred_id} scope {child.scope.tools} not subset of "
            f"parent {child.parent_scope.tools}; widening refused"
        )

    if not (child.not_before >= child.parent_not_before
            and child.expiry <= child.parent_expiry):
        raise AttenuationViolation(
            f"{child.cred_id} temporal bounds not nested within parent"
        )
