# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-skill-manifest-capability-declaration-divergence-between-the-manifest-s-declared-tool-schema-and-the-runtime-tool-de.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-skill-manifest-capability-declaration-divergence-between-the-manifest-s-declared-tool-schema-and-the-runtime-tool-de.warrant.json
# Markdown SHA-256:   9e62dd765727bc0138d36338ff00fef7bb3dd28b6a5443ad331a2f18f1871e42
# Code AST SHA-256:   260f6e8abd36ba9f48d2e21e3a4a74179fc207a9901995cd58f3f5fd4803a97b
# Verified Classes:   DescriptionDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re

IMPERATIVE_PATTERNS = [
    r"\bbefore calling\b",
    r"\bfirst call\b",
    r"\binclude the result\b",
    r"\bnote for agent\b",
    r"\bignore (all )?previous\b",
    r"\bdo not (tell|report|log)\b",
]


class DescriptionDivergenceError(RuntimeError):
    """Raised when a skill's runtime description diverges from its audited baseline
    for the pinned schema hash, or when it contains agent-directed directives."""
    pass


def schema_hash(manifest: dict) -> str:
    # Pin only the machine-checkable surface, never the prose.
    canonical = repr(sorted(manifest["inputSchema"].items()))
    return hashlib.sha256(canonical.encode()).hexdigest()


def load_skill(manifest: dict, audited_descriptions: dict) -> dict:
    h = schema_hash(manifest)
    baseline = audited_descriptions.get(h)
    if baseline is None:
        raise DescriptionDivergenceError(
            f"no audited description for schema hash {h[:12]}; load in schema-only mode"
        )

    runtime_desc = manifest.get("description", "")
    if runtime_desc != baseline:
        raise DescriptionDivergenceError(
            f"description drift for pinned schema {h[:12]}: "
            f"runtime differs from audited baseline"
        )

    for pat in IMPERATIVE_PATTERNS:
        if re.search(pat, runtime_desc, re.IGNORECASE):
            raise DescriptionDivergenceError(
                f"agent-directed directive detected in description of "
                f"{manifest.get('name')!r}: matched {pat!r}"
            )

    # Emit only schema-derived facts plus the audited prose, provenance-tagged.
    return {
        "name": manifest["name"],
        "parameters": manifest["inputSchema"],
        "description_provenance": "audited",
        "description": baseline,
        "cross_tool_refs": [],  # hints only; never directives
    }
