# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegation-chain-has-silently-widened-the-attenuation-inversion-failure-in-a2a-capability-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegation-chain-has-silently-widened-the-attenuation-inversion-failure-in-a2a-capability-handoff.warrant.json
# Markdown SHA-256:   0aadf5f45d7bcdf34f730e433a3ffd307f6ebf4fc8dde5bed5f94758f06399ef
# Code AST SHA-256:   2b1647023023d7016872d4ed7de3da706798820f8f62fe0fb88050f3d87514bc
# Verified Classes:   AttenuationInversionError, Grant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class AttenuationInversionError(RuntimeError):
    """Raised when a delegation chain's effective authority exceeds its nominal grant."""


@dataclass(frozen=True)
class Grant:
    grant_id: str
    scopes: FrozenSet[str]
    parent_id: str | None
    backend_caps: FrozenSet[str]          # true backend operations this scope set can reach
    context_ref: str | None = None        # any live pointer back into parent state
    ttl_s: int = 60


# Backend capability map: scope string -> true backend operations it unlocks.
SCOPE_TO_BACKEND = {
    "fs.read":  frozenset({"fs.open_ro", "fs.stat"}),
    "fs.write": frozenset({"fs.open_rw", "fs.stat"}),
    "fs.rw":    frozenset({"fs.open_ro", "fs.open_rw", "fs.stat"}),  # alias collapse
    "net.fetch": frozenset({"net.connect"}),
}

# Capabilities that, composed, yield a new capability. Registry must deny by default.
COMPOSITION_RULES = {
    frozenset({"net.connect", "fs.open_ro"}): frozenset({"fs.open_rw"}),
}


def effective_caps(grant: Grant) -> FrozenSet[str]:
    caps = set()
    for s in grant.scopes:
        if s not in SCOPE_TO_BACKEND:
            raise AttenuationInversionError(f"unknown scope {s!r} in grant {grant.grant_id}")
        caps |= SCOPE_TO_BACKEND[s]
    # close under composition
    changed = True
    while changed:
        changed = False
        for antecedent, consequent in COMPOSITION_RULES.items():
            if antecedent <= caps and not consequent <= caps:
                caps |= consequent
                changed = True
    return frozenset(caps)


def validate_delegation(parent: Grant, child: Grant) -> None:
    # 1. nominal subset check (the message-layer check that is necessary but not sufficient)
    if not child.scopes <= parent.scopes:
        raise AttenuationInversionError(
            f"nominal widening: {child.scopes} not subset of {parent.scopes}"
        )
    # 2. context handle is a capability channel — must be sanitized
    if child.context_ref is not None:
        raise AttenuationInversionError(
            f"grant {child.grant_id} carries live context_ref {child.context_ref!r}; "
            "this leaks sibling/ancestor grants into child effective authority"
        )
    # 3. effective capability must not exceed parent's effective capability
    parent_eff = effective_caps(parent)
    child_eff = effective_caps(child)
    if not child_eff <= parent_eff:
        raise AttenuationInversionError(
            f"effective widening at {child.grant_id}: {child_eff - parent_eff} "
            f"exceeds parent {parent.grant_id}"
        )
    # 4. revocation reachability: parent must be resolvable for the grant's lifetime
    if child.parent_id != parent.grant_id:
        raise AttenuationInversionError(
            f"grant {child.grant_id} parent_id {child.parent_id!r} does not resolve to "
            f"live parent {parent.grant_id}; revocation walk will orphan this grant"
        )


def revoke(grant_id: str, live_grants: dict[str, Grant]) -> set[str]:
    """Depth-first revocation. Unreachable parent => fail closed (revoke the orphan)."""
    revoked = set()
    stack = [grant_id]
    while stack:
        gid = stack.pop()
        if gid in revoked:
            continue
        revoked.add(gid)
        for g in live_grants.values():
            if g.parent_id == gid:
                stack.append(g.grant_id)
    # any grant whose parent is now revoked but which was not reached => orphan
    for g in live_grants.values():
        if g.parent_id in revoked and g.grant_id not in revoked:
            raise AttenuationInversionError(
                f"orphan grant {g.grant_id} survived revocation of parent {g.parent_id}; "
                "revocation walk is not transitively closed"
            )
    return revoked
