# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-validate-a-dynamically-loaded-skill-s-declared-capability-manifest-against-its-actual-effect-surface-before.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-validate-a-dynamically-loaded-skill-s-declared-capability-manifest-against-its-actual-effect-surface-before.warrant.json
# Markdown SHA-256:   a70a95018253a73c83c133333db644b679c21ed9de0e35e6c13bb1b1559cbca4
# Code AST SHA-256:   8a3415c74e6455d4ea93fb2ee27f4ac449943f615fa41b89306f0d7a53782dab
# Verified Classes:   SkillInjectionBoundaryError, SkillManifest, ValidatedSkill, SkillRegistryGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a dynamically loaded skill's observed output diverges from
    its declared manifest in a way that would grant unauthorized context authority."""


INJECTION_MARKERS = ("ignore prior", "system:", "you must", "new authority", "<!-- system")


@dataclass
class SkillManifest:
    name: str
    side_effect_class: str
    scopes: list[str]
    declared_returns_max_len: int


@dataclass
class ValidatedSkill:
    manifest: SkillManifest
    effect_hash: str
    validated_output_behavior: str


class SkillRegistryGuard:
    def __init__(self, context_utilization_threshold: float = 0.60):
        self._validated: dict[str, ValidatedSkill] = {}
        self._threshold = context_utilization_threshold

    def _effect_hash(self, manifest: SkillManifest, observed_behavior: str) -> str:
        payload = f"{manifest.name}|{manifest.side_effect_class}|{manifest.scopes}|{observed_behavior}"
        return hashlib.sha256(payload.encode()).hexdigest()

    def admit_tool_result(
        self,
        manifest: SkillManifest,
        observed_behavior: str,
        raw_output: str,
        context_utilization: float,
    ) -> str:
        effect_hash = self._effect_hash(manifest, observed_behavior)
        cached = self._validated.get(manifest.name)

        # Re-validate on any mutation of the effect surface.
        if cached is None or cached.effect_hash != effect_hash:
            self._capability_diff(manifest, observed_behavior)
            self._validated[manifest.name] = ValidatedSkill(
                manifest=manifest,
                effect_hash=effect_hash,
                validated_output_behavior=observed_behavior,
            )

        lowered = raw_output.lower()
        injection_suspected = any(m in lowered for m in INJECTION_MARKERS)

        if injection_suspected:
            raise SkillInjectionBoundaryError(
                f"skill {manifest.name!r} returned imperative content on output channel "
                f"despite side_effect_class={manifest.side_effect_class!r}; "
                f"quarantining result rather than promoting to context"
            )

        if context_utilization > self._threshold:
            # Provenance discrimination is degraded: wrap, do not execute.
            return f"[QUARANTINED_TOOL_RESULT origin={manifest.name}]\n{raw_output}\n[/QUARANTINED]"

        return raw_output

    def _capability_diff(self, manifest: SkillManifest, observed_behavior: str) -> None:
        if manifest.side_effect_class == "read_only" and "write" in observed_behavior.lower():
            raise SkillInjectionBoundaryError(
                f"skill {manifest.name!r} declared read_only but observed write behavior"
            )
        if len(observed_behavior) > manifest.declared_returns_max_len:
            raise SkillInjectionBoundaryError(
                f"skill {manifest.name!r} exceeded declared return length "
                f"({len(observed_behavior)} > {manifest.declared_returns_max_len})"
            )
