# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-tool-manifest-by-name-and-the-registry-returns-a-same-name-sibling-with-a-widened-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-tool-manifest-by-name-and-the-registry-returns-a-same-name-sibling-with-a-widened-schema.warrant.json
# Markdown SHA-256:   883a9592092d397bc1fe900b74653cf5cd0acd3c6a94c8fa32c1a057b58295e0
# Code AST SHA-256:   fd925b0f3cfb10482ede99ac7fdbdd6db32de6024a7296c461f2d007b4585e57
# Verified Classes:   SchemaDriftUnauthorizedError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftUnauthorizedError(RuntimeError):
    """Raised when a tool is invoked against a manifest whose digest differs
    from the one that was capability-adjudicated, or when a name collides."""
    pass


@dataclass(frozen=True)
class Manifest:
    name: str
    server_id: str
    auth_scope: str
    fields: tuple  # sorted field names; additions here are the injection surface

    def digest(self) -> str:
        blob = json.dumps(
            {"name": self.name, "server": self.server_id,
             "scope": self.auth_scope, "fields": list(self.fields)},
            sort_keys=True,
        ).encode()
        return hashlib.sha256(blob).hexdigest()


def resolve_and_authorize(
    requested_name: str,
    registry: dict,               # fully-qualified key -> Manifest
    adjudicated: dict,            # name -> digest that was capability-adjudicated
) -> Manifest:
    # Collision check: name must map to exactly one fully-qualified entry.
    matches = [m for m in registry.values() if m.name == requested_name]
    if len(matches) != 1:
        raise SchemaDriftUnauthorizedError(
            f"ambiguous resolution for {requested_name!r}: "
            f"{len(matches)} registry entries share this name"
        )
    live = matches[0]

    prior = adjudicated.get(requested_name)
    if prior is None:
        raise SchemaDriftUnauthorizedError(
            f"no adjudicated digest for {requested_name!r}; "
            f"capability approval required before first call"
        )

    if live.digest() != prior:
        # Additive schema widening (new fields / widened scope) is the exact
        # condition under which a cached planner can emit an injected arg.
        raise SchemaDriftUnauthorizedError(
            f"schema drift for {requested_name!r}: adjudicated={prior[:12]} "
            f"live={live.digest()[:12]}; re-adjudicate capability before call"
        )
    return live


def invoke_tool(requested_name, args, registry, adjudicated):
    manifest = resolve_and_authorize(requested_name, registry, adjudicated)
    # Only now is it safe to hand args to the handler: the manifest we call
    # against is byte-identical to the one that was approved.
    return {"tool": manifest.name, "server": manifest.server_id, "args": args}
