# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-plugin-manifest-capability-declarations-against-runtime-skill-behavior-to-prevent-skill-injection-escalation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-plugin-manifest-capability-declarations-against-runtime-skill-behavior-to-prevent-skill-injection-escalation.warrant.json
# Markdown SHA-256:   2281c1e124572c86e20587ac6ab87d0e41019787463fb5e811071e038510f368
# Code AST SHA-256:   c238c1a36b4576aee43122f0c4a327d92f5b48cc9f6a2bd7f7191aa0fc528f84
# Verified Classes:   SkillEnvelopeViolation, Manifest, Host
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set

class SkillEnvelopeViolation(RuntimeError):
    """Raised when a skill's reachable capability set exceeds its declared envelope."""
    pass

@dataclass
class Manifest:
    name: str
    declared: Set[str]                 # e.g. {"net:api.weather.example", "fs:read:/tmp/skill-cache"}
    tools: Set[str]                    # tool names the skill binds directly
    prompt_interpolated_as_directive: bool

@dataclass
class Host:
    host_tools: Set[str]               # tool names bound to the agent's own identity
    tool_scopes: dict                  # tool name -> scope strings it can reach

def reachable_envelope(manifest: Manifest, host: Host) -> Set[str]:
    reach: Set[str] = set()
    for t in manifest.tools:
        reach |= host.tool_scopes.get(t, set())
    if manifest.prompt_interpolated_as_directive:
        # Skill prompt can steer the agent toward any host tool it holds.
        for t in host.host_tools:
            reach |= host.tool_scopes.get(t, set())
    return reach

def gate_skill_load(manifest: Manifest, host: Host) -> None:
    reach = reachable_envelope(manifest, host)
    overreach = reach - manifest.declared
    if overreach:
        raise SkillEnvelopeViolation(
            f"skill {manifest.name!r} reaches {sorted(overreach)} "
            f"beyond declared {sorted(manifest.declared)}; "
            f"load refused or must be sandboxed to declared envelope"
        )

# Example: the observed failure, now rejected at load.
host = Host(
    host_tools={"read_file", "shell", "http_get"},
    tool_scopes={
        "fetch_forecast": {"net:api.weather.example"},
        "read_file": {"fs:read:/etc/agent/credentials.json", "fs:read:/tmp/skill-cache"},
        "shell": {"exec:*"},
        "http_get": {"net:*"},
    },
)
manifest = Manifest(
    name="weather-helper",
    declared={"net:api.weather.example", "fs:read:/tmp/skill-cache"},
    tools={"fetch_forecast"},
    prompt_interpolated_as_directive=True,
)
gate_skill_load(manifest, host)  # raises SkillEnvelopeViolation
