# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-dynamically-loaded-mcp-tool-whose-manifest-declares-capabilities-broader-than-its-observed-call-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-dynamically-loaded-mcp-tool-whose-manifest-declares-capabilities-broader-than-its-observed-call-graph.warrant.json
# Markdown SHA-256:   64fee75d82daf664449264b5e7a73f1441ca067257e006912746d9274136bb35
# Code AST SHA-256:   60f4484fd2339f33c3013d697f88d76502167e13b816003cd74afdfbc4bb8f37
# Verified Classes:   SkillInjectionBoundaryError, ToolDescriptor, ToolState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a dynamically loaded tool violates the manifest/call-graph invariant."""
    pass


IMPERATIVE_PATTERN = re.compile(
    r"\b(always|before|must|you should|first call|then call|do not)\b",
    re.IGNORECASE,
)

DECLARED_CAPABILITY_KEY = "capabilities"


@dataclass
class ToolDescriptor:
    name: str
    description: str
    declared_capabilities: frozenset
    manifest_hash: str


@dataclass
class ToolState:
    descriptor: ToolDescriptor
    observed_capabilities: set = field(default_factory=set)
    divergence_count: int = 0
    reflection_budget: int = 0
    quarantined: bool = False


def _hash_manifest(raw: bytes) -> str:
    return hashlib.sha256(raw).hexdigest()


def verify_descriptor_integrity(state: ToolState, current_raw: bytes) -> None:
    current_hash = _hash_manifest(current_raw)
    if current_hash != state.descriptor.manifest_hash:
        raise SkillInjectionBoundaryError(
            f"descriptor mutation detected for {state.descriptor.name}: "
            f"pinned={state.descriptor.manifest_hash[:12]} "
            f"current={current_hash[:12]}"
        )


def check_description_for_injection(state: ToolState) -> None:
    match = IMPERATIVE_PATTERN.search(state.descriptor.description)
    if match:
        state.quarantined = True
        raise SkillInjectionBoundaryError(
            f"imperative language in descriptor for {state.descriptor.name}: "
            f"token={match.group(0)!r}; quarantine initiated at load"
        )


def record_invocation(state: ToolState, exercised_capability: str) -> None:
    if state.quarantined:
        raise SkillInjectionBoundaryError(
            f"invocation attempted on quarantined tool {state.descriptor.name}"
        )
    state.observed_capabilities.add(exercised_capability)
    undeclared = state.observed_capabilities - state.descriptor.declared_capabilities
    if undeclared:
        state.divergence_count += 1
        if state.divergence_count >= 2:
            state.quarantined = True
            raise SkillInjectionBoundaryError(
                f"capability expansion for {state.descriptor.name}: "
                f"undeclared={sorted(undeclared)} "
                f"after {state.divergence_count} divergent invocations"
            )


def sanitize_error(tool_name: str, field_name: Optional[str]) -> str:
    # Never echo untrusted values; field name only, no attempted arguments.
    if field_name:
        return f"tool {tool_name!r} rejected field {field_name!r}"
    return f"tool {tool_name!r} invocation rejected"


def record_reflection(state: ToolState, echoed: bool) -> None:
    if echoed:
        state.reflection_budget += 1
        if state.reflection_budget > 0:
            state.quarantined = True
            raise SkillInjectionBoundaryError(
                f"reflection amplification for {state.descriptor.name}: "
                f"error handler echoed untrusted input"
            )


def evict_context_spans(context: list, quarantine_tag: str) -> list:
    # Provenance-tagged eviction: drop every span sourced from the quarantined tool.
    return [span for span in context if span.get("provenance") != quarantine_tag]


def distill_memory(context: list, quarantined_tags: set) -> list:
    promoted = []
    for span in context:
        if span.get("provenance") in quarantined_tags:
            raise SkillInjectionBoundaryError(
                f"refusing to promote span from quarantined source "
                f"{span.get('provenance')!r} to semantic memory"
            )
        promoted.append(span)
    return promoted
