# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-registry-signed-skill-whose-behavior-diverges-from-its-signed-manifest-at-the-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-registry-signed-skill-whose-behavior-diverges-from-its-signed-manifest-at-the-tool-call-boundary.warrant.json
# Markdown SHA-256:   6635d73473511cc99c832308940d66110448dce8a62ad06524e16079945a8fdc
# Code AST SHA-256:   542e0f3570c3827c2604640ae290111bff93d6cd4e2e6cb778d429cda04b5bf9
# Verified Classes:   SkillAdmissionError, SignedManifest, DispatchAttempt
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class SkillAdmissionError(RuntimeError):
    """Raised when a signed skill violates the closed-surface / covered-baseline invariant."""
    pass


@dataclass(frozen=True)
class SignedManifest:
    skill_id: str
    version: str
    declared_tools: FrozenSet[str]
    capability_scopes: FrozenSet[str]
    baseline_input_classes: FrozenSet[str]  # e.g. {"short_text", "code_fenced", "long_text"}


@dataclass
class DispatchAttempt:
    tool_name: str
    path: str | None
    input_class: str


def admit_skill(manifest: SignedManifest, signature_valid: bool, diff_clean: bool) -> None:
    if not signature_valid:
        raise SkillAdmissionError(f"{manifest.skill_id}: signature invalid, refuse admission")
    if not diff_clean:
        raise SkillAdmissionError(f"{manifest.skill_id}: behavior diff non-zero, refuse admission")
    # Signature + diff are necessary but not sufficient; surface closure is required.
    if not manifest.declared_tools:
        raise SkillAdmissionError(
            f"{manifest.skill_id}: empty declared tool set; surface is open, refuse admission"
        )


def enforce_dispatch(manifest: SignedManifest, attempt: DispatchAttempt) -> None:
    # Guardrail that catches call 41: membership in the SIGNED tool set, not live process names.
    if attempt.tool_name not in manifest.declared_tools:
        raise SkillAdmissionError(
            f"{manifest.skill_id}: emitted undeclared tool '{attempt.tool_name}' "
            f"(declared: {sorted(manifest.declared_tools)}); refusing dispatch"
        )
    # Coverage gate: uncovered input class means diff-clean is untested, not safe.
    if attempt.input_class not in manifest.baseline_input_classes:
        raise SkillAdmissionError(
            f"{manifest.skill_id}: input class '{attempt.input_class}' outside baseline "
            f"coverage {sorted(manifest.baseline_input_classes)}; fail closed"
        )
    # Scope gate remains, but only after surface and coverage are closed.
    if attempt.path is not None:
        if not any(attempt.path.startswith(s.split(":", 1)[1]) for s in manifest.capability_scopes if ":" in s):
            raise SkillAdmissionError(
                f"{manifest.skill_id}: path '{attempt.path}' outside declared scopes"
            )


# Reproduction of the observed failure: signed + diff-clean, yet undeclared tool on call 41.
manifest = SignedManifest(
    skill_id="summarize_and_file",
    version="3.2.1",
    declared_tools=frozenset({"summarize", "file"}),
    capability_scopes=frozenset({"read:input", "write:workspace"}),
    baseline_input_classes=frozenset({"short_text", "long_text"}),
)
admit_skill(manifest, signature_valid=True, diff_clean=True)  # passes: authentic + sample-clean

# Call 41: undeclared tool, uncovered input class. Naive runtime allowed it via scope check.
enforce_dispatch(
    manifest,
    DispatchAttempt(tool_name="file", path="/workspace/.cache/sync", input_class="code_fenced"),
)
