# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-attestation-chain-that-verifies-cryptographically-but-violates-scope-narrowing-monotonicity.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-aaif-attestation-chain-that-verifies-cryptographically-but-violates-scope-narrowing-monotonicity.warrant.json
# Markdown SHA-256:   e3d1e854cdf359ac1e6b2b32e788e733ffa2274bda3f32763f9cd40c89127e3c
# Code AST SHA-256:   488b15a92c01984aed869d2eaa76bfa7e8d963b2764ae48d1a6980c64fa3ff37
# Verified Classes:   AttestationScopeViolation, Scope, Link
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

# Scope dimensions are sets (tools, paths) or bounded numerics (max_tokens, max_depth).
# An absent dimension at the leaf is treated as EMPTY, never as unbounded,
# unless the root explicitly declared it unbounded.


class AttestationScopeViolation(RuntimeError):
    """Raised when a delegated AAIF chain widens authority along any link."""


@dataclass
class Scope:
    tools: Optional[frozenset] = None          # None => dimension omitted
    paths: Optional[frozenset] = None
    max_tokens: Optional[int] = None
    unbounded: frozenset = field(default_factory=frozenset)  # dimensions root declares unbounded


@dataclass
class Link:
    subject: str
    scope: Scope
    signature_ok: bool
    not_after_ok: bool
    revoked: bool


def _dim(scope: Scope, name: str):
    val = getattr(scope, name)
    if val is None:
        # Omitted dimension: empty set for set-dims, 0 for numeric, unless root said unbounded.
        if name in scope.unbounded:
            return None  # sentinel: unbounded
        return frozenset() if name in ("tools", "paths") else 0
    return val


def _is_subset(child, parent, name: str) -> bool:
    if parent is None:      # parent unbounded
        return True
    if child is None:       # child unbounded but parent bounded -> widening
        return False
    if name in ("tools", "paths"):
        return child <= parent
    return child <= parent  # numeric limit


def verify_chain(chain: list[Link], runtime_subject: str) -> Scope:
    if not chain:
        raise AttestationScopeViolation("empty attestation chain")

    for i, link in enumerate(chain):
        if not link.signature_ok:
            raise AttestationScopeViolation(f"link {i}: bad signature")
        if not link.not_after_ok:
            raise AttestationScopeViolation(f"link {i}: expired")
        if link.revoked:
            raise AttestationScopeViolation(f"link {i}: revoked")

    # Root establishes the ceiling. Its own scope is authoritative.
    root = chain[0].scope
    effective = {d: _dim(root, d) for d in ("tools", "paths", "max_tokens")}

    for i in range(1, len(chain)):
        child = chain[i].scope
        for d in effective:
            c = _dim(child, d)
            if not _is_subset(c, effective[d], d):
                raise AttestationScopeViolation(
                    f"link {i}: scope widening on dimension '{d}' "
                    f"(child={c!r}, effective_parent={effective[d]!r})"
                )
            # Narrow the running effective scope for subsequent links.
            if effective[d] is None:
                effective[d] = c
            elif c is None:
                effective[d] = None
            elif d in ("tools", "paths"):
                effective[d] = effective[d] & c
            else:
                effective[d] = min(effective[d], c)

    if chain[-1].subject != runtime_subject:
        raise AttestationScopeViolation(
            f"leaf subject {chain[-1].subject!r} != runtime {runtime_subject!r}"
        )

    return Scope(
        tools=effective["tools"],
        paths=effective["paths"],
        max_tokens=effective["max_tokens"],
        unbounded=frozenset(),
    )
