# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-aaif-credential-after-a-scope-narrowing-handoff-and-why-naive-attenuation-silently-widens-authority.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-aaif-credential-after-a-scope-narrowing-handoff-and-why-naive-attenuation-silently-widens-authority.warrant.json
# Markdown SHA-256:   b5c3f446f451db937a5fb924bcf7ff056f277e665dbc0e4f4c4c5efa4fa9d497
# Code AST SHA-256:   a09076e7f7bcab03b93e815eaed869f829ad97cd0795bfd968ec2689b4d4601d
# Verified Classes:   DelegationRefused, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class DelegationRefused(RuntimeError):
    """Raised when a minting agent cannot underwrite the credential it is about to issue."""


@dataclass(frozen=True)
class Scope:
    classes: FrozenSet[str]
    constraints: FrozenSet[str]  # e.g. "path_prefix=/data/tenant-a"
    runtime_reachable: bool = True


def probe_effective_scope(declared: Scope, reachable_classes: FrozenSet[str],
                          enforced_constraints: FrozenSet[str]) -> Scope:
    """Intersect declared envelope with what the runtime will actually honor right now."""
    return Scope(
        classes=declared.classes & reachable_classes,
        constraints=declared.constraints | enforced_constraints,
        runtime_reachable=True,
    )


def mint_delegated_credential(parent_declared: Scope,
                              probe_ok: bool,
                              reachable_classes: FrozenSet[str],
                              enforced_constraints: FrozenSet[str],
                              requested: Scope) -> Scope:
    if not probe_ok:
        # Cold start, mid-run revocation, or ambiguous tool state: fail closed.
        raise DelegationRefused(
            "self-capability probe unavailable; refusing to mint credential "
            "the parent cannot currently underwrite"
        )
    effective = probe_effective_scope(parent_declared, reachable_classes, enforced_constraints)

    if not requested.classes <= effective.classes:
        raise DelegationRefused(
            f"class escalation: requested {sorted(requested.classes)} "
            f"exceeds effective {sorted(effective.classes)}"
        )
    if not effective.constraints <= requested.constraints:
        dropped = effective.constraints - requested.constraints
        raise DelegationRefused(
            f"constraint non-propagation: child drops {sorted(dropped)} "
            f"present in parent's effective scope"
        )
    return requested
