# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-its-delegated-authority-closure-before-each-privileged-tool-call-and-why-aaif-scope-attenuation-fails.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-its-delegated-authority-closure-before-each-privileged-tool-call-and-why-aaif-scope-attenuation-fails.warrant.json
# Markdown SHA-256:   7dda2ee8aecfd5b70b79ca84953762c725e1da48acac3bccff60cc2fc01ee86d
# Code AST SHA-256:   85538423764c727da3ec0b779d0fcbfa77aa330b7a65536244c09ba16350008f
# Verified Classes:   AuthorityClosureError, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class AuthorityClosureError(RuntimeError):
    """Raised when a delegated credential's scope is not reachable from the root issuer."""


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject: str
    scope: frozenset[str]
    constraints: frozenset[str] = field(default_factory=frozenset)
    parent_issuer: str | None = None


def fold_effective_scope(chain: list[Credential], active_constraints: Iterable[str]) -> frozenset[str]:
    """Walk a delegation chain root-first, intersecting scopes and applying constraints.

    chain[0] must be the root-issued credential (parent_issuer is None).
    """
    if not chain or chain[0].parent_issuer is not None:
        raise AuthorityClosureError("chain does not terminate at a root issuer")

    active = frozenset(active_constraints)
    effective = frozenset(chain[0].scope)

    for i, cred in enumerate(chain[1:], start=1):
        if cred.parent_issuer != chain[i - 1].issuer:
            raise AuthorityClosureError(
                f"broken delegation edge at hop {i}: issuer {cred.issuer!r} "
                f"claims parent {cred.parent_issuer!r} but previous issuer is {chain[i-1].issuer!r}"
            )
        # Subset invariant: a delegator cannot grant what it does not effectively hold.
        if not cred.scope <= effective:
            raise AuthorityClosureError(
                f"scope escalation at hop {i}: {cred.issuer!r} granted "
                f"{sorted(cred.scope - effective)} not held by delegator"
            )
        # Lapsed constraints silently strip authority even when scope arrays match.
        if not cred.constraints <= active:
            raise AuthorityClosureError(
                f"constraint violation at hop {i}: {sorted(cred.constraints - active)} not active"
            )
        effective = effective & cred.scope

    return effective


def authorize_privileged_call(
    chain: list[Credential],
    requested: str,
    active_constraints: Iterable[str],
    epoch_folded: bool,
) -> None:
    """Gate a privileged tool call on a freshly derived authority witness."""
    if not epoch_folded:
        # Cached closure from a prior checkpoint/handoff epoch is not admissible.
        raise AuthorityClosureError(
            f"refusing privileged call {requested!r}: authority witness is stale "
            "(not folded in current execution epoch)"
        )

    effective = fold_effective_scope(chain, active_constraints)
    if requested not in effective:
        raise AuthorityClosureError(
            f"refusing privileged call {requested!r}: not in effective scope "
            f"{sorted(effective)} (leaf declared {sorted(chain[-1].scope)})"
        )
