# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-signed-capability-manifest-that-was-valid-at-admission-but-has-since-been-superseded-by-a-re-signed-manifest-wi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-signed-capability-manifest-that-was-valid-at-admission-but-has-since-been-superseded-by-a-re-signed-manifest-wi.warrant.json
# Markdown SHA-256:   95310c0012cc77e08b5ac51822ca2af8e656f5ab3e0229edc8a3de0f8a53f1f1
# Code AST SHA-256:   eb6d58344490b0b87f1c9566a22c4392ba773841247f1cfaebc368df11225da0
# Verified Classes:   StaleManifestError, Manifest, AdmittedSession, ManifestService
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleManifestError(RuntimeError):
    """Raised when a session attempts a mutating/egress capability under a
    manifest serial that is no longer the issuer's current declaration."""
    pass


@dataclass
class Manifest:
    skill_id: str
    serial: int
    capabilities: frozenset[str]
    issued_at: float
    expiry: float

    def is_expired(self, now: float) -> bool:
        return now >= self.expiry


@dataclass
class AdmittedSession:
    manifest: Manifest
    admitted_at: float
    # serial actually used to derive the current sandbox
    executed_serial: int = field(init=False)

    def __post_init__(self) -> None:
        self.executed_serial = self.manifest.serial


MUTATING_PREFIXES = ("fs.write", "net.", "exec.")


def _is_mutating(cap: str) -> bool:
    return any(cap.startswith(p) for p in MUTATING_PREFIXES)


class ManifestService:
    """Monotonic per (skill_id, issuer_key); never returns an older serial."""

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

    def publish(self, m: Manifest) -> None:
        prev = self._current.get(m.skill_id)
        if prev is not None and m.serial <= prev.serial:
            raise ValueError(
                f"non-monotonic serial for {m.skill_id}: {m.serial} <= {prev.serial}"
            )
        self._current[m.skill_id] = m

    def fetch(self, skill_id: str) -> Manifest:
        return self._current[skill_id]


def authorize_tool_call(
    session: AdmittedSession,
    capability: str,
    svc: ManifestService,
    now: float | None = None,
) -> None:
    """Gate a single tool call. Mutating/egress capabilities must be backed by
    the issuer's *current* serial, not the admission-time serial."""
    now = time.time() if now is None else now

    if session.manifest.is_expired(now):
        raise StaleManifestError(
            f"{session.manifest.skill_id}: manifest expired at {session.manifest.expiry}"
        )

    if not _is_mutating(capability):
        # read-only: admission cache is a sound basis
        if capability not in session.manifest.capabilities:
            raise StaleManifestError(
                f"{session.manifest.skill_id}: {capability} not in admitted manifest"
            )
        return

    # mutating/egress: re-fetch and require the current serial to still grant it
    current = svc.fetch(session.manifest.skill_id)
    if current.serial != session.executed_serial:
        # supersession detected; re-derive before proceeding
        session.manifest = current
        session.executed_serial = current.serial

    if capability not in current.capabilities:
        raise StaleManifestError(
            f"{session.manifest.skill_id}: {capability} was retracted at serial "
            f"{current.serial} (session admitted under serial "
            f"{session.admitted_at and session.executed_serial})"
        )
