# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-that-passes-schema-validation-but-was-mutated-between-capability-negotiation-and-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-that-passes-schema-validation-but-was-mutated-between-capability-negotiation-and-invocation.warrant.json
# Markdown SHA-256:   d189bc87d788bb13ff9c7ef8747dd60736c18d7e352555e109b8d9e21d47ad24
# Code AST SHA-256:   c4090dccdeee7f6a7bace7a3a97e38b6a89122718bf43e7f7b4a7581c61f08af
# Verified Classes:   ManifestMutationError, ManifestSnapshot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestMutationError(RuntimeError):
    """Raised when the invoke-time manifest does not match the plan-time snapshot."""
    pass


@dataclass(frozen=True)
class ManifestSnapshot:
    tool_name: str
    content_hash: str
    canonical_bytes: bytes


def canonical_hash(manifest: dict) -> str:
    # Canonical form: sorted keys, no whitespace variance. Hash the whole document,
    # including description/examples/defaults — those are the injection surface.
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(canonical).hexdigest()


def snapshot_at_plan_time(tool_name: str, manifest: dict) -> ManifestSnapshot:
    return ManifestSnapshot(
        tool_name=tool_name,
        content_hash=canonical_hash(manifest),
        canonical_bytes=json.dumps(manifest, sort_keys=True).encode("utf-8"),
    )


def bind_invocation(
    snapshot: ManifestSnapshot,
    invoke_time_manifest: dict,
    planner_args: dict,
) -> dict:
    """Resolve the final argument object for invocation.

    Invariants enforced:
      1. Byte-identity between plan-time and invoke-time manifest.
      2. Planner-authoritative binding: no parameter may be filled from a
         manifest default that was not present in planner_args.
    """
    invoke_hash = canonical_hash(invoke_time_manifest)
    if invoke_hash != snapshot.content_hash:
        raise ManifestMutationError(
            f"manifest for {snapshot.tool_name!r} mutated between plan and invoke: "
            f"plan={snapshot.content_hash[:12]} invoke={invoke_hash[:12]}"
        )

    # Even with a hash match, refuse to synthesize parameters the planner never emitted.
    allowed = set(planner_args.keys())
    schema_props = set(invoke_time_manifest.get("parameters", {}).get("properties", {}).keys())
    unexpected = allowed - schema_props
    if unexpected:
        raise ManifestMutationError(
            f"planner emitted params not in manifest schema: {sorted(unexpected)}"
        )

    resolved = dict(planner_args)
    for name, spec in invoke_time_manifest.get("parameters", {}).get("properties", {}).items():
        if name in resolved:
            continue
        if "default" in spec:
            # A default the planner did not see is a mutation signal, not a convenience.
            raise ManifestMutationError(
                f"refusing to fill {name!r} from manifest default; "
                f"planner did not emit it (possible skill injection)"
            )
    return resolved
