# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-that-its-own-policy-engine-already-approved-the-delegated-warrant-attenuation-gap-in-cross-or.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-brokered-capability-grant-that-its-own-policy-engine-already-approved-the-delegated-warrant-attenuation-gap-in-cross-or.warrant.json
# Markdown SHA-256:   f02173932da5d5fe73cb7b7e0acc105c7b0b8049ed222b9aa5e891a7f2b61ae3
# Code AST SHA-256:   121bd78add971cc1d6369c4bc85769f49adf0bd5032c969df2982ca58d245c07
# Verified Classes:   ChainGapRefusal, Grant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ChainGapRefusal(RuntimeError):
    """Raised when a brokered grant cannot be evaluated as a delegation."""
    pass


@dataclass(frozen=True)
class Grant:
    scope: frozenset
    issuer: str
    signature_valid: bool
    warrant_digest: Optional[str]      # commits to root warrant; None if broker re-signed flat
    attenuation_ref: Optional[str]     # reference to attenuation predicate A
    remaining_hops: Optional[int]      # signed hop budget; None if not committed


def evaluate_grant(grant: Grant, local_allowlist: frozenset,
                   trusted_brokers: dict, attenuation_store: dict) -> str:
    if not grant.signature_valid or grant.issuer not in trusted_brokers:
        return "DENY_UNTRUSTED"

    trust_class = trusted_brokers[grant.issuer]  # "chain_required" | "flat_scope"

    # Fail closed: a chain_required broker that drops the chain is itself non-compliant.
    if trust_class == "chain_required":
        if grant.warrant_digest is None or grant.attenuation_ref is None:
            raise ChainGapRefusal(
                f"broker {grant.issuer} omitted warrant chain; "
                f"cannot verify attenuation — refusing rather than admitting flat scope"
            )
        att = attenuation_store.get(grant.attenuation_ref)
        if att is None:
            raise ChainGapRefusal(
                f"attenuation_ref {grant.attenuation_ref} unresolvable; "
                f"refusing grant rather than treating absence as no-attenuation"
            )
        if not grant.scope.issubset(att["scope"]):
            return "DENY_ATTENUATION_EXCEEDED"
        if grant.remaining_hops is None or grant.remaining_hops < 0:
            raise ChainGapRefusal(
                "hop budget not committed in signed grant; cannot authorize delegation"
            )

    # Legacy flat-scope broker: downgrade, never treat as authoritative.
    effective = grant.scope & local_allowlist
    if trust_class == "flat_scope":
        return f"APPROVE_DOWNGRADED:{sorted(effective)}"

    return f"APPROVE:{sorted(effective)}"


def spawn_subagent(parent: Grant, child_scope: frozenset,
                   attenuation_store: dict) -> Grant:
    if parent.remaining_hops is None:
        raise ChainGapRefusal(
            "parent grant carries no signed hop budget; re-delegation is unverifiable"
        )
    if parent.remaining_hops <= 0:
        raise ChainGapRefusal(
            f"parent grant hop budget exhausted ({parent.remaining_hops}); "
            f"root warrant forbade further delegation"
        )
    if not child_scope.issubset(parent.scope):
        raise ChainGapRefusal(
            "child scope exceeds parent grant; attenuation would be violated"
        )
    return Grant(
        scope=child_scope,
        issuer=parent.issuer,
        signature_valid=True,
        warrant_digest=parent.warrant_digest,
        attenuation_ref=parent.attenuation_ref,
        remaining_hops=parent.remaining_hops - 1,  # must be re-signed by caller
    )
