# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-poisoned-skill-injection-from-silently-re-binding-an-agent-s-tool-identity-across-a-capability-registry-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-poisoned-skill-injection-from-silently-re-binding-an-agent-s-tool-identity-across-a-capability-registry-refresh.warrant.json
# Markdown SHA-256:   886c21a38a967a2fea69924715cda7631d19f378108d062ee03c19bed23c7b3f
# Code AST SHA-256:   d414558ee63eb147ec99b3997caf2874f69e7e9848b22405af613a0920a39e44
# Verified Classes:   ManifestIdentityDriftError, ManifestSnapshot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ManifestIdentityDriftError(RuntimeError):
    """Raised when a tool manifest's content digest changes mid-task
    under a stable tool name, indicating capability re-binding."""
    pass


@dataclass(frozen=True)
class ManifestSnapshot:
    name: str
    digest: str
    schema: dict[str, Any]
    description: str


def _digest(manifest: dict[str, Any]) -> str:
    # Canonicalize so field ordering cannot mask a semantic change.
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def pin_manifest(manifest: dict[str, Any]) -> ManifestSnapshot:
    return ManifestSnapshot(
        name=manifest["name"],
        digest=_digest(manifest),
        schema=manifest.get("inputSchema", {}),
        description=manifest.get("description", ""),
    )


def resolve_and_authorize(
    pinned: ManifestSnapshot,
    refreshed: dict[str, Any],
    require_reauthorization: bool = True,
) -> ManifestSnapshot:
    """Resolve a refreshed manifest against the task-pinned snapshot.

    Invariant: trust is keyed on (name, digest), never on name alone.
    A digest mismatch under a stable name is a capability boundary
    crossing, not a cache miss.
    """
    if refreshed.get("name") != pinned.name:
        raise ManifestIdentityDriftError(
            f"manifest name changed: pinned={pinned.name!r} "
            f"refreshed={refreshed.get('name')!r}"
        )

    new_digest = _digest(refreshed)
    if new_digest == pinned.digest:
        return pinned  # no-op refresh, trust transfers safely

    # Digest drift: the referent behind the name has changed.
    if require_reauthorization:
        raise ManifestIdentityDriftError(
            f"capability re-binding under stable name {pinned.name!r}: "
            f"pinned_digest={pinned.digest[:12]} "
            f"refreshed_digest={new_digest[:12]}; "
            f"re-vetting required before invocation"
        )

    # Fallback: intersect schemas so relaxed constraints cannot widen
    # the authorized input surface.
    intersected = _intersect_schema(pinned.schema, refreshed.get("inputSchema", {}))
    return ManifestSnapshot(
        name=pinned.name,
        digest=new_digest,
        schema=intersected,
        description="[UNTRUSTED: description quarantined on digest drift]",
    )


def _intersect_schema(old: dict[str, Any], new: dict[str, Any]) -> dict[str, Any]:
    """Conservative intersection: keep only parameters present in both
    with identical constraints. Dropped params cannot be supplied."""
    old_props = old.get("properties", {})
    new_props = new.get("properties", {})
    shared = {
        k: old_props[k]
        for k in old_props.keys() & new_props.keys()
        if old_props[k] == new_props[k]
    }
    return {
        "type": old.get("type", "object"),
        "properties": shared,
        "required": [r for r in old.get("required", []) if r in shared],
        "additionalProperties": False,
    }


def invoke_tool(
    pinned: ManifestSnapshot,
    refreshed: dict[str, Any],
    arguments: dict[str, Any],
) -> dict[str, Any]:
    authorized = resolve_and_authorize(pinned, refreshed)
    # Validate against the authorized (possibly intersected) schema.
    allowed = authorized.schema.get("properties", {})
    for key in arguments:
        if key not in allowed:
            raise ManifestIdentityDriftError(
                f"argument {key!r} not authorized under pinned schema "
                f"for tool {pinned.name!r}"
            )
    return {"tool": authorized.name, "args": arguments, "status": "dispatched"}
