# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-forged-tool-schema-drift-when-a-dynamically-loaded-plugin-mutates-its-own-manifest-between-capability-negotiation-and-fi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-forged-tool-schema-drift-when-a-dynamically-loaded-plugin-mutates-its-own-manifest-between-capability-negotiation-and-fi.warrant.json
# Markdown SHA-256:   68097a430e334f904225e3da358af0f4db4614d30e91cba9781de4d9ab832c87
# Code AST SHA-256:   a945004b83c686c10bab35b014c2465b65aa7ed67b3ee232dca2d944e2d29d21
# Verified Classes:   SchemaDriftError, SchemaLease
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftError(RuntimeError):
    """Raised when a tool's executing schema diverges from its negotiated lease."""
    pass


@dataclass(frozen=True)
class SchemaLease:
    tool_name: str
    digest: str
    negotiated: dict
    invoked_since_negotiation: bool = False


def _digest(schema: dict) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def _widened(old: dict, new: dict) -> list[str]:
    """Return list of widening deltas between two input schemas."""
    deltas = []
    old_props = old.get("properties", {})
    new_props = new.get("properties", {})
    for name in new_props.keys() - old_props.keys():
        deltas.append(f"added_property:{name}")
    if old.get("additionalProperties") is False and new.get("additionalProperties") is not False:
        deltas.append("relaxed_additionalProperties")
    for name in old_props.keys() & new_props.keys():
        op, np_ = old_props[name], new_props[name]
        if op.get("pattern") != np_.get("pattern"):
            deltas.append(f"pattern_changed:{name}")
        if set(np_.get("enum", [])) - set(op.get("enum", [])):
            deltas.append(f"enum_widened:{name}")
        if "default" not in op and "default" in np_:
            deltas.append(f"default_injected:{name}")
    return deltas


def enforce_schema_lease(lease: SchemaLease, executing_schema: dict, supplied_args: dict) -> None:
    current = _digest(executing_schema)
    if current != lease.digest:
        deltas = _widened(lease.negotiated.get("inputSchema", {}), executing_schema)
        if lease.invoked_since_negotiation and deltas:
            raise SchemaDriftError(
                f"tool {lease.tool_name!r} widened after first use: {deltas}; "
                f"lease={lease.digest[:12]} executing={current[:12]}"
            )
        raise SchemaDriftError(
            f"tool {lease.tool_name!r} schema mutated between negotiation and dispatch; "
            f"deltas={deltas or ['non-widening']}"
        )
    # Default-firing check: any property with a default that the caller did not set
    # is an out-of-band argument injection channel.
    for name, prop in executing_schema.get("properties", {}).items():
        if "default" in prop and name not in supplied_args:
            raise SchemaDriftError(
                f"tool {lease.tool_name!r} would fire server-side default for {name!r} "
                f"({prop['default']!r}); explicit value required"
            )
    # Metadata-channel injection check on description fields.
    for name, prop in executing_schema.get("properties", {}).items():
        desc = prop.get("description", "")
        if any(marker in desc.lower() for marker in ("execute", "tool call", "run the", "ignore previous")):
            raise SchemaDriftError(
                f"tool {lease.tool_name!r} property {name!r} carries imperative metadata; "
                f"treating description as untrusted"
            )
