# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-ambient-authority-resurrection-when-a-sandboxed-skill-is-re-injected-across-a-capability-downgrade-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-ambient-authority-resurrection-when-a-sandboxed-skill-is-re-injected-across-a-capability-downgrade-boundary.warrant.json
# Markdown SHA-256:   b6a555ec40afe10e448f525246c5550067fde00e3c64d7da448cd0837316229b
# Code AST SHA-256:   6250045708e50f327ea07e880719634a10171ce798576da56e384a4aed41ce10
# Verified Classes:   AmbientAuthorityResurrection, Manifest, Handle, Snapshot, Sandbox
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class AmbientAuthorityResurrection(RuntimeError):
    """Raised when a restored handle table would grant authority the current manifest does not."""


@dataclass(frozen=True)
class Manifest:
    version: int
    capabilities: frozenset[str]


@dataclass
class Handle:
    capability: str
    live: bool = True


@dataclass
class Snapshot:
    manifest_version: int
    handles: list[Handle] = field(default_factory=list)
    cached_schema: dict[str, str] = field(default_factory=dict)


@dataclass
class Sandbox:
    manifest: Manifest
    handles: dict[str, Handle] = field(default_factory=dict)

    def revoke(self, capability: str) -> None:
        # Revocation removes the handle; it does not merely flag a registry entry.
        self.handles.pop(capability, None)
        self.manifest = Manifest(
            version=self.manifest.version + 1,
            capabilities=self.manifest.capabilities - {capability},
        )

    def snapshot(self) -> Snapshot:
        return Snapshot(
            manifest_version=self.manifest.version,
            handles=list(self.handles.values()),
            cached_schema={c: c for c in self.manifest.capabilities},
        )


def restore(sandbox: Sandbox, snap: Snapshot) -> Sandbox:
    """Restore task state, but re-derive authority from the CURRENT manifest.

    The handle table is never taken from the snapshot when the manifest has
    changed: a snapshot may carry handles only across a manifest-identical
    resume. Any version drift forces re-derivation.
    """
    if snap.manifest_version != sandbox.manifest.version:
        # Downgrade (or upgrade) boundary crossed: discard snapshot handles,
        # rebuild from current manifest, and reject stale cached schema.
        restored = Sandbox(manifest=sandbox.manifest)
        for cap in sandbox.manifest.capabilities:
            restored.handles[cap] = Handle(capability=cap, live=True)
        for cap in snap.cached_schema:
            if cap not in sandbox.manifest.capabilities:
                raise AmbientAuthorityResurrection(
                    f"cached schema advertises {cap!r} but manifest v{sandbox.manifest.version} "
                    f"does not grant it; refusing to restore resurrected authority"
                )
        return restored

    # Manifest-identical resume: handle identity may be preserved.
    restored = Sandbox(manifest=sandbox.manifest)
    for h in snap.handles:
        if h.capability not in sandbox.manifest.capabilities:
            raise AmbientAuthorityResurrection(
                f"snapshot handle {h.capability!r} not in manifest "
                f"v{sandbox.manifest.version}; invariant live_handles ⊆ capabilities violated"
            )
        restored.handles[h.capability] = h
    return restored
