# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-manifest-replay-window-during-hot-reload-of-an-allowlisted-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-manifest-replay-window-during-hot-reload-of-an-allowlisted-capability-set.warrant.json
# Markdown SHA-256:   c182d09bf8744c164c5af941b527bb856515ca3811c9cb8996268e9641ee7907
# Code AST SHA-256:   854ccd1779888ccce95f660036e0cd5c4fff9226c33c39a7fb29b5df6dabb926
# Verified Classes:   StaleManifestReplay, UntrustedManifest, Manifest, CapabilityGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class StaleManifestReplay(RuntimeError):
    """Raised when a validly-signed manifest is superseded by a higher serial."""


class UntrustedManifest(RuntimeError):
    """Raised when a manifest's signature or issuer key fails verification."""


@dataclass(frozen=True)
class Manifest:
    issuer: str
    skill: str
    serial: int
    capabilities: frozenset[str]
    signature: bytes


def verify_signature(m: Manifest, pinned_keys: dict[str, bytes]) -> bool:
    # Placeholder for real asymmetric verification against the pinned issuer key.
    key = pinned_keys.get(m.issuer)
    return key is not None and m.signature == key  # toy equality; real impl verifies bytes


@dataclass
class CapabilityGate:
    pinned_keys: dict[str, bytes]
    # Persisted across restarts in production; in-memory here for illustration.
    high_water: dict[tuple[str, str], int] = field(default_factory=dict)
    allowlist: dict[tuple[str, str], frozenset[str]] = field(default_factory=dict)

    def apply(self, manifests: Iterable[Manifest]) -> None:
        # Replace-per-pair, never union across serials of the same (issuer, skill).
        staged: dict[tuple[str, str], Manifest] = {}
        for m in manifests:
            if not verify_signature(m, self.pinned_keys):
                raise UntrustedManifest(f"{m.issuer}/{m.skill} serial {m.serial}: bad signature")
            key = (m.issuer, m.skill)
            prev = staged.get(key)
            if prev is None or m.serial > prev.serial:
                staged[key] = m

        for key, m in staged.items():
            seen = self.high_water.get(key, -1)
            if m.serial <= seen:
                # Valid signature, but superseded: this is the replay window.
                raise StaleManifestReplay(
                    f"{key[0]}/{key[1]} serial {m.serial} <= high-water {seen}; "
                    f"refusing to merge stale capability set"
                )
            # Advance the mark BEFORE mutating the allowlist so a crash cannot
            # leave a granted-but-unrecorded capability.
            self.high_water[key] = m.serial
            self.allowlist[key] = m.capabilities

    def permits(self, issuer: str, skill: str, capability: str) -> bool:
        return capability in self.allowlist.get((issuer, skill), frozenset())


def reload_from_mirrors(gate: CapabilityGate, primary: list[Manifest], mirror: list[Manifest]) -> None:
    """Enumerating two sources and unioning is the classic trigger; we stage both
    and let supersession resolve, but a stale mirror must not resurrect a grant."""
    gate.apply([*primary, *mirror])
    # Post-condition: a capability dropped by the highest serial must be absent.
    for (issuer, skill), caps in gate.allowlist.items():
        top = gate.high_water[(issuer, skill)]
        if any(m.serial == top and "net:outbound" not in m.capabilities
               for m in (*primary, *mirror) if (m.issuer, m.skill) == (issuer, skill)) \
           and "net:outbound" in caps:
            raise StaleManifestReplay(
                f"{issuer}/{skill}: revoked capability 'net:outbound' present after reload"
            )
