# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-skill-s-declared-tool-schema-as-attacker-controlled-input-at-the-moment-of-first-invocation-rather-than-at.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-skill-s-declared-tool-schema-as-attacker-controlled-input-at-the-moment-of-first-invocation-rather-than-at.warrant.json
# Markdown SHA-256:   92179d73f5614ea84cf4f8405a84f3d0df00ce0e155ccc07bf58a0a08cf2d89c
# Code AST SHA-256:   5879288005061f496c3c786dce56e7f1feb69e8b722a0e438ebc693af4a97035
# Verified Classes:   SchemaSurfaceExpansionError, ParamSurface
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SchemaSurfaceExpansionError(RuntimeError):
    """Raised when a skill's callable surface expands after admission."""


@dataclass(frozen=True)
class ParamSurface:
    name: str
    type: str
    constraint: Optional[str]  # e.g. pattern, enum, max_len


def _surface(schema: dict) -> set[ParamSurface]:
    return {
        ParamSurface(
            name=p["name"],
            type=p["type"],
            constraint=p.get("constraint"),
        )
        for p in schema.get("parameters", [])
    }


def assert_surface_monotonic(
    admitted_schema: dict,
    current_schema: dict,
    skill_id: str,
    *,
    re_admitted: bool = False,
) -> None:
    """Invariant: current callable surface must be a subset of the admitted one.

    Call this at first invocation of any skill resolved from a dynamic
    registry, using the schema captured at admission time (not the cache).
    """
    if re_admitted:
        return

    admitted = _surface(admitted_schema)
    current = _surface(current_schema)

    added = current - admitted
    if added:
        details = ", ".join(
            f"{p.name}:{p.type}(constraint={p.constraint!r})" for p in sorted(added, key=lambda x: x.name)
        )
        raise SchemaSurfaceExpansionError(
            f"Skill {skill_id!r} callable surface expanded after admission: "
            f"[{details}]. Refusing invocation; require explicit re-admission."
        )


def invoke_skill(
    skill_id: str,
    admitted_schema: dict,
    live_schema: dict,
    args: dict,
    *,
    re_admitted: bool = False,
) -> dict:
    # Gate BEFORE the tool call, using the admitted snapshot as ground truth.
    assert_surface_monotonic(
        admitted_schema, live_schema, skill_id, re_admitted=re_admitted
    )
    # ... dispatch to the skill executor here ...
    return {"skill": skill_id, "status": "ok"}
