# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-session-tool-manifest-mutation-that-re-binds-a-previously-audited-skill-to-a-shadowed-handler.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-mid-session-tool-manifest-mutation-that-re-binds-a-previously-audited-skill-to-a-shadowed-handler.warrant.json
# Markdown SHA-256:   2325cd6e0b43c3bb7c3c0e18f985b1b359b8ba17c5810430ed6c11a824ce37a6
# Code AST SHA-256:   cb28fce85305b48d3a6ae15ca13e85c52f0bd4eb9ac7a1d0d51e4bf24512b829
# Verified Classes:   ManifestBindingError, Binding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestBindingError(RuntimeError):
    """Raised when a refreshed manifest shadows or re-binds an audited tool."""
    pass


@dataclass(frozen=True)
class Binding:
    name: str
    handler: str          # content-addressed identity, e.g. "fs_local@sha256:4f2a"
    schema_hash: str      # hash of canonicalized JSON Schema
    transport: str


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


def audit_refresh(audited: dict[str, Binding], refreshed: list[dict]) -> dict[str, Binding]:
    """Apply a manifest refresh against a prior audit. Returns the new audited set.

    Invariants enforced:
      - names within one manifest must be unique (bijection), else reject wholesale
      - a previously audited name whose binding tuple changed is demoted to unapproved
    """
    seen: dict[str, Binding] = {}
    for entry in refreshed:
        b = Binding(
            name=entry["name"],
            handler=entry["handler"],
            schema_hash=_schema_hash(entry["schema"]),
            transport=entry["transport"],
        )
        if b.name in seen:
            raise ManifestBindingError(
                f"duplicate tool name {b.name!r} with divergent binding: "
                f"{seen[b.name].handler} vs {b.handler}; manifest rejected"
            )
        seen[b.name] = b

    new_audited: dict[str, Binding] = {}
    for name, b in seen.items():
        prior = audited.get(name)
        if prior is None:
            continue  # new tool: handled by first-use approval gate, not here
        if prior != b:
            # binding changed under a stable name -> shadowing attempt or drift
            raise ManifestBindingError(
                f"audited binding for {name!r} mutated: "
                f"{prior} -> {b}; re-approval required before dispatch"
            )
        new_audited[name] = b
    return new_audited
