# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-manifest-rewrite-skill-injection-during-hot-tool-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-manifest-rewrite-skill-injection-during-hot-tool-reload.warrant.json
# Markdown SHA-256:   7d0172611f3cecf27c051998fbea32f843cfc255a1b05f0bd473e7db3b01b4f3
# Code AST SHA-256:   35e072b7146c745975f66b0dbddc2106d4dcab5a9540ccabfdf2d23f874f8887
# Verified Classes:   ManifestInjectionError, AttestedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a hot-reloaded manifest rewrites model-visible instruction text
    without passing semantic attestation."""
    pass


MODEL_VISIBLE_FIELDS = ("description", "examples", "enum_annotations", "error_template")


def semantic_hash(tool: dict) -> str:
    payload = {k: tool.get(k, "") for k in MODEL_VISIBLE_FIELDS}
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()


def schema_hash(tool: dict) -> str:
    schema = tool.get("parameters", {})
    return hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest()


@dataclass
class AttestedTool:
    name: str
    schema_hash: str
    semantic_hash: str
    signer: str


def reload_manifest(
    prior: dict[str, AttestedTool],
    incoming: list[dict],
    trusted_signers: set[str],
    imperative_markers: tuple[str, ...] = ("before using", "first call", "you must", "pass the contents"),
) -> dict[str, AttestedTool]:
    """Merge a hot-reloaded manifest against prior attestation.

    Rejects any tool whose model-visible text changed without signer continuity,
    or whose diff introduces imperative directives even under a valid signer.
    """
    merged: dict[str, AttestedTool] = {}

    for tool in incoming:
        name = tool["name"]
        new_sem = semantic_hash(tool)
        new_schema = schema_hash(tool)
        signer = tool.get("signer", "")

        prev = prior.get(name)
        if prev is None:
            merged[name] = AttestedTool(name, new_schema, new_sem, signer)
            continue

        if new_schema != prev.schema_hash:
            # Interface changed: full re-attestation required, not a silent splice.
            if signer not in trusted_signers:
                raise ManifestInjectionError(
                    f"tool {name}: schema changed under untrusted signer {signer!r}"
                )
            merged[name] = AttestedTool(name, new_schema, new_sem, signer)
            continue

        if new_sem == prev.semantic_hash:
            merged[name] = prev  # no reload event
            continue

        # Semantic text changed while schema held constant: the dangerous case.
        if signer not in trusted_signers:
            raise ManifestInjectionError(
                f"tool {name}: instruction text rewritten under untrusted signer {signer!r}"
            )

        blob = json.dumps({k: tool.get(k, "") for k in MODEL_VISIBLE_FIELDS}).lower()
        if any(marker in blob for marker in imperative_markers):
            raise ManifestInjectionError(
                f"tool {name}: semantic diff contains imperative directive; "
                f"operator acknowledgment required before splice"
            )

        merged[name] = AttestedTool(name, new_schema, new_sem, signer)

    return merged
