# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-capability-envelope-has-silently-widened-during-agent-to-agent-permission-downgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-capability-envelope-has-silently-widened-during-agent-to-agent-permission-downgrade.warrant.json
# Markdown SHA-256:   cfcce71c9f64ae03408bf925682ff58cbd4a483d3172c7bc57dfa93d6bca6c75
# Code AST SHA-256:   8f6159bf6920382d5a5898e18549044a5866cc2023538b71858e77c73fc521af
# Verified Classes:   CapabilityEnvelopeWidenedError, StaleEnvelopeRestoreError, Envelope, CapabilityResolver
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class CapabilityEnvelopeWidenedError(RuntimeError):
    """Raised when an agent's resolved capability set exceeds its verified envelope."""
    pass


class StaleEnvelopeRestoreError(RuntimeError):
    """Raised when a resumed agent attempts to recover a pre-downgrade envelope."""
    pass


@dataclass(frozen=True)
class Envelope:
    capabilities: FrozenSet[str]
    generation: int
    parent_hash: str


class CapabilityResolver:
    """
    The ONLY writer of effective capability sets.
    Reads exclusively from the verified envelope. Any other channel is inert.
    """

    def __init__(self) -> None:
        self._last_seen_generation: dict[str, int] = {}

    def resolve(self, agent_id: str, verified: Envelope) -> FrozenSet[str]:
        # Envelope is the sole source of truth.
        effective = set(verified.capabilities)

        # Structural invariant check: effective must equal verified, never exceed.
        if not effective.issubset(verified.capabilities):
            raise CapabilityEnvelopeWidenedError(
                f"agent={agent_id} effective={sorted(effective)} "
                f"verified={sorted(verified.capabilities)}"
            )

        # Track generation for restore safety.
        prev = self._last_seen_generation.get(agent_id, -1)
        if verified.generation < prev:
            raise StaleEnvelopeRestoreError(
                f"agent={agent_id} restored generation={verified.generation} "
                f"is below last-seen={prev}; revoked grants may be recovered"
            )
        self._last_seen_generation[agent_id] = verified.generation
        return frozenset(effective)

    def authorize(self, agent_id: str, verified: Envelope, requested: str) -> None:
        effective = self.resolve(agent_id, verified)
        if requested not in effective:
            # Fail closed: never fall back to prose hints, schema defaults, or memory blobs.
            raise CapabilityEnvelopeWidenedError(
                f"agent={agent_id} requested='{requested}' not in verified envelope "
                f"{sorted(verified.capabilities)}; refusing to widen from ambient context"
            )


def handoff(parent: Envelope, child_caps: FrozenSet[str], child_gen: int) -> Envelope:
    # Enforce attenuation: child must be a subset of parent.
    if not child_caps.issubset(parent.capabilities):
        raise CapabilityEnvelopeWidenedError(
            f"handoff would widen: child={sorted(child_caps)} "
            f"parent={sorted(parent.capabilities)}"
        )
    return Envelope(
        capabilities=child_caps,
        generation=child_gen,
        parent_hash=hash(parent),
    )
