# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-signed-skill-manifest-the-post-verification-activation-window-where-behavioral-diffing-and-runtime-canaries-race-the-lo.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-signed-skill-manifest-the-post-verification-activation-window-where-behavioral-diffing-and-runtime-canaries-race-the-lo.warrant.json
# Markdown SHA-256:   809ed4825bd4bb6a40b1a584f501691a0580e723415b095b4ebeecc9978b6c48
# Code AST SHA-256:   52652984c90fb767590aed3d83a1fd03a974e7748d8d42c7615e33737ed8eb47
# Verified Classes:   SkillActivationError, SkillState, CanaryObservation, SkillManifest, QuarantineGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class SkillActivationError(RuntimeError):
    """Raised when a skill attempts to cross the capability-grant boundary
    before the runtime canary has produced sufficient clean observations."""


class SkillState(Enum):
    QUARANTINE = "quarantine"
    ACTIVE = "active"
    REVOKED = "revoked"


@dataclass
class CanaryObservation:
    clean: bool
    egress_attempted: bool
    context_read_within_declared_scope: bool
    timestamp: float = field(default_factory=time.time)


@dataclass
class SkillManifest:
    name: str
    signature_valid: bool
    diff_label: str  # e.g. "LOW_RISK_ADDITIVE"
    declared_egress: bool = False
    declared_context_scope: frozenset[str] = frozenset()


class QuarantineGate:
    """Enforces: capability_grant_time > first_clean_canary_observation_time.

    Signature validity and diff cleanliness are admission to quarantine only.
    They never authorize capability binding on their own.
    """

    def __init__(self, min_clean_observations: int = 3) -> None:
        self.min_clean = min_clean_observations
        self.state = SkillState.QUARANTINE
        self.observations: list[CanaryObservation] = []
        self._capability_bound = False

    def admit(self, manifest: SkillManifest) -> None:
        # Signed + diff-clean -> quarantine. Nothing more.
        if not manifest.signature_valid:
            raise SkillActivationError(
                f"manifest for {manifest.name!r} failed signature verification; "
                "refusing admission even to quarantine"
            )
        self.state = SkillState.QUARANTINE

    def record_canary(self, obs: CanaryObservation) -> None:
        if self.state is SkillState.REVOKED:
            raise SkillActivationError("cannot record canary on revoked skill")
        self.observations.append(obs)
        if not obs.clean or obs.egress_attempted:
            self.state = SkillState.REVOKED

    def _clean_count(self) -> int:
        return sum(1 for o in self.observations if o.clean and not o.egress_attempted)

    def bind_capability(
        self,
        manifest: SkillManifest,
        capability: str,
        on_grant: Callable[[str], None],
    ) -> None:
        """Bind an irreversible capability (egress handle, full-context read).

        Raises if the canary has not yet produced enough clean observations
        under the skill's real invocation distribution.
        """
        if self.state is SkillState.REVOKED:
            raise SkillActivationError(
                f"skill {manifest.name!r} is revoked; refusing to bind {capability!r}"
            )
        if self._clean_count() < self.min_clean:
            raise SkillActivationError(
                f"refusing to bind capability {capability!r} for {manifest.name!r}: "
                f"only {self._clean_count()} clean canary observations, "
                f"need {self.min_clean}. Signature+diff alone do not authorize binding."
            )
        if capability == "outbound_egress" and not manifest.declared_egress:
            raise SkillActivationError(
                f"skill {manifest.name!r} requests undeclared egress; "
                "treat as capability escalation, not a passive option"
            )
        self._capability_bound = True
        self.state = SkillState.ACTIVE
        on_grant(capability)


def load_skill(manifest: SkillManifest, gate: QuarantineGate) -> None:
    gate.admit(manifest)
    # Adversary scenario: signed + LOW_RISK_ADDITIVE, but no canary yet.
    # Attempting to bind egress here must fail, not silently succeed.
    gate.bind_capability(manifest, "outbound_egress", on_grant=lambda cap: None)
