# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-when-a-dynamically-loaded-skill-s-manifest-and-its-runtime-behavior-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-when-a-dynamically-loaded-skill-s-manifest-and-its-runtime-behavior-disagree.warrant.json
# Markdown SHA-256:   247a688dd3eeb45a2b29fd59d7072ab248e17e5899a49badd11cab0921b7bb71
# Code AST SHA-256:   b911498df1d2bfcc8e747ac67a1693f2716d3401be6e7000d53f00dde958d456
# Verified Classes:   SkillInjectionError, SkillManifest, SkillSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class SkillInjectionError(RuntimeError):
    """Raised when a dynamically loaded skill's runtime behavior escapes the
    authority envelope declared by its manifest."""


@dataclass(frozen=True)
class SkillManifest:
    skill_id: str
    body_sha256: str
    declared_scopes: frozenset[str]
    declared_outputs: frozenset[str]
    allowed_hosts: frozenset[str]
    side_effects: bool


@dataclass
class SkillSession:
    manifest: SkillManifest
    registered_tools: set[str] = field(default_factory=set)
    pending_tools: set[str] = field(default_factory=set)
    observed_effects: list[str] = field(default_factory=list)


_CONTROL_PLANE_TOKENS = ("[SYSTEM]", "[INST]", "<|im_start|>", "role\":\"system")


def _contains_control_directive(payload: str) -> bool:
    lowered = payload.lower()
    return any(tok.lower() in lowered for tok in _CONTROL_PLANE_TOKENS)


def enforce_manifest_envelope(
    session: SkillSession,
    body_digest: str,
    declared_output_keys: set[str],
    returned_payload: str,
    egress_hosts: set[str],
) -> None:
    """Validate one skill invocation against its manifest before its output
    reaches the prompt assembler or the tool registry.

    Raises SkillInjectionError on any widening of authority.
    """
    manifest = session.manifest

    # 1. Body must match the digest the manifest committed to.
    if body_digest != manifest.body_sha256:
        raise SkillInjectionError(
            f"skill {manifest.skill_id!r}: body digest {body_digest!r} "
            f"does not match manifest commitment {manifest.body_sha256!r}"
        )

    # 2. Outputs must be a subset of declared outputs.
    undeclared = declared_output_keys - manifest.declared_outputs
    if undeclared:
        raise SkillInjectionError(
            f"skill {manifest.skill_id!r}: returned undeclared outputs "
            f"{sorted(undeclared)!r}; manifest declares "
            f"{sorted(manifest.declared_outputs)!r}"
        )

    # 3. Data-plane output must not carry control-plane directives.
    if _contains_control_directive(returned_payload):
        raise SkillInjectionError(
            f"skill {manifest.skill_id!r}: output payload contains a "
            f"control-plane directive; skill has widened from data-plane "
            f"to control-plane authority"
        )

    # 4. Egress must stay within declared hosts.
    rogue_hosts = egress_hosts - manifest.allowed_hosts
    if rogue_hosts:
        raise SkillInjectionError(
            f"skill {manifest.skill_id!r}: attempted egress to undeclared "
            f"hosts {sorted(rogue_hosts)!r}; allowed "
            f"{sorted(manifest.allowed_hosts)!r}"
        )

    # 5. Post-handshake tool-list deltas are pending, never live.
    if session.pending_tools:
        raise SkillInjectionError(
            f"skill {manifest.skill_id!r}: pending capability request "
            f"{sorted(session.pending_tools)!r} requires re-authorization "
            f"before the planner may call it"
        )

    session.observed_effects.append(
        f"invoked {manifest.skill_id} within declared envelope"
    )


def handle_tools_list_changed(session: SkillSession, new_tools: set[str]) -> None:
    """Route post-handshake capability deltas through the pending gate rather
    than merging them into the live registry."""
    additions = new_tools - session.registered_tools
    if not additions:
        return
    session.pending_tools.update(additions)
    # Deliberately do NOT add to registered_tools. The planner cannot see
    # these until enforce_manifest_envelope has been satisfied by an
    # explicit re-authorization event.
