# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamically-registered-skill-whose-manifest-signature-validates-but-whose-tool-schema-mutates-the.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamically-registered-skill-whose-manifest-signature-validates-but-whose-tool-schema-mutates-the.warrant.json
# Markdown SHA-256:   c2dab8ec6ccc1538bd3bec5ac641ebb7e77dd7b6c8fb86a2b5dd0002e4e9bf0f
# Code AST SHA-256:   194ed39f7416635f871586d08cef229b8a48d24615a56634df08401cb3bf75a7
# Verified Classes:   SchemaDriftError, SignedSkill
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftError(RuntimeError):
    """Raised when a resolved skill schema does not match its signed hash."""
    pass


@dataclass(frozen=True)
class SignedSkill:
    skill_id: str
    signed_schema_hash: str  # sha256 hex, bound at admission
    signed_schema: dict      # the exact bytes that were approved


def _hash_schema(schema: dict) -> str:
    # Canonical serialization so byte order cannot mask drift.
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def resolve_and_verify(skill: SignedSkill, live_schema: dict) -> dict:
    """
    Resolve the executable schema and enforce the continuity invariant:
    the schema governing argument marshalling MUST equal the signed schema.

    Called on every invocation, not just at admission. A drifted schema
    (added, removed, or retyped parameters) is a quarantine condition even
    when the manifest signature is valid.
    """
    live_hash = _hash_schema(live_schema)

    if live_hash != skill.signed_schema_hash:
        # Drift detected. Do not fall through to the live schema.
        raise SchemaDriftError(
            f"skill {skill.skill_id!r} schema drift: "
            f"signed={skill.signed_schema_hash[:12]}… "
            f"live={live_hash[:12]}… — quarantine and require re-approval"
        )

    # Invariant holds: live schema is byte-identical to the approved artifact.
    return live_schema


def invoke(skill: SignedSkill, live_schema: dict, arguments: dict) -> dict:
    schema = resolve_and_verify(skill, live_schema)

    # Argument-level guard: reject any key not declared in the signed schema.
    allowed = set(schema.get("properties", {}).keys())
    undeclared = set(arguments) - allowed
    if undeclared:
        raise SchemaDriftError(
            f"skill {skill.skill_id!r} received undeclared arguments "
            f"{sorted(undeclared)} — possible argument-surface injection"
        )

    return {"skill_id": skill.skill_id, "arguments": arguments, "status": "dispatched"}
