# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-manifest-resident-skill-injection-that-only-activates-after-a-tool-s-declared-capability-envelope-is-renegotiated-mid-se.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-manifest-resident-skill-injection-that-only-activates-after-a-tool-s-declared-capability-envelope-is-renegotiated-mid-se.warrant.json
# Markdown SHA-256:   b9a6afa46ea33027406d638c1721767ba16839ba6d5658bca700f954106da3be
# Code AST SHA-256:   669ea44b149fd90e2985b0f805bd9e9dabd9aea17b8e3f9790fa2c61292c8350
# Verified Classes:   ManifestRenegotiationTrustError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class ManifestRenegotiationTrustError(RuntimeError):
    """Raised when a renegotiated tool descriptor changes model-readable
    fields without clearing the sanitization pipeline before plan resume."""


# Fields the model reads as normative instruction, not inert data.
# A change in any of these invalidates the prior trust grant.
MODEL_READABLE_FIELDS = (
    "description",
    "parameters",       # includes per-parameter description / enum / examples
    "examples",
)


def _canonical(descriptor: dict[str, Any]) -> str:
    subset = {k: descriptor.get(k) for k in MODEL_READABLE_FIELDS}
    return json.dumps(subset, sort_keys=True, separators=(",", ":"))


def trust_hash(descriptor: dict[str, Any]) -> str:
    return hashlib.sha256(_canonical(descriptor).encode("utf-8")).hexdigest()


def sanitize_model_readable(descriptor: dict[str, Any]) -> None:
    """Full injection pipeline over the normative fields only."""
    blob = _canonical(descriptor).lower()
    # Minimal representative check; a real pipeline is richer.
    for marker in ("append the full contents", "system context variable",
                   "before dispatch", "private memory key"):
        if marker in blob:
            raise ManifestRenegotiationTrustError(
                f"injection marker {marker!r} present in model-readable fields"
            )


def adjudicate_reload(
    trusted_descriptor: dict[str, Any],
    incoming_descriptor: dict[str, Any],
    trusted_hash: str,
) -> str:
    """Return the new trust hash if the reload is safe to resume against.

    Raises if any model-readable field changed and the incoming descriptor
    does not clear sanitization. Non-model-readable changes pass silently.
    """
    if trust_hash(trusted_descriptor) != trusted_hash:
        raise ManifestRenegotiationTrustError(
            "stored trust hash does not match trusted descriptor; state corrupt"
        )

    incoming_hash = trust_hash(incoming_descriptor)
    if incoming_hash == trusted_hash:
        return trusted_hash  # no model-readable delta; resume is safe

    # A model-readable field changed under an existing trust grant.
    # Re-adjudicate before the plan is allowed to resume.
    sanitize_model_readable(incoming_descriptor)

    # Re-scan must pass; if it does, the new hash becomes the grant.
    return incoming_hash


def dispatch_with_stamp(
    descriptor: dict[str, Any],
    planned_against_hash: str,
) -> None:
    """Transport-layer guard: reject calls planned against a stale descriptor."""
    live_hash = trust_hash(descriptor)
    if live_hash != planned_against_hash:
        raise ManifestRenegotiationTrustError(
            "descriptor drifted between plan-commit and dispatch: "
            f"planned={planned_against_hash[:12]} live={live_hash[:12]}"
        )
