# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-confusion-injection-when-a-poisoned-mcp-tool-description-redefines-a-sibling-capability-at-discovery-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-confusion-injection-when-a-poisoned-mcp-tool-description-redefines-a-sibling-capability-at-discovery-time.warrant.json
# Markdown SHA-256:   bb6e837032d738585853676d109802fe8231d02aa8dd9f05af0de012d133617b
# Code AST SHA-256:   3d7b1b5793bdfb268dcbb5b92d86735536cff2d0a5efe3b62a5d3a3afeec7355
# Verified Classes:   CapabilityConfusionError, ToolManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

from dataclasses import dataclass
from typing import Literal

EffectClass = Literal["read-only", "network-egress", "write"]


class CapabilityConfusionError(RuntimeError):
    """Raised when a tool's prose description asserts a capability its
    structured metadata does not declare, or when two near-duplicate tools
    with divergent effect classes compete for the same intent."""


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    declared_capabilities: frozenset[str]   # from signed registry, not self-declared
    schema_properties: frozenset[str]
    effect_class: EffectClass


# Action verbs that must be backed by a structured capability token.
_ACTION_TO_CAPABILITY = {
    "read": "fs.read",
    "fetch": "net.fetch",
    "list": "fs.list",
    "write": "fs.write",
}


def validate_discovery(manifest: ToolManifest) -> None:
    prose = manifest.description.lower()

    # Invariant 1: prose may narrow, never widen, the capability set.
    for verb, required_cap in _ACTION_TO_CAPABILITY.items():
        if verb in prose and required_cap not in manifest.declared_capabilities:
            raise CapabilityConfusionError(
                f"tool {manifest.name!r} description asserts {verb!r} "
                f"but capability {required_cap!r} is not declared; "
                f"declared={sorted(manifest.declared_capabilities)}"
            )

    # Invariant 2: any noun in prose implying a parameter must exist in schema.
    # (Simplified: check that 'file' prose implies a path-like property.)
    if "file" in prose and not ({"path", "filepath", "uri"} & manifest.schema_properties):
        raise CapabilityConfusionError(
            f"tool {manifest.name!r} description references files but schema "
            f"declares no path-like property: {sorted(manifest.schema_properties)}"
        )


def select_tool(
    intent_scores: dict[str, float],
    manifests: dict[str, ToolManifest],
    similarity_threshold: float = 0.85,
) -> str:
    for m in manifests.values():
        validate_discovery(m)  # reject poisoned manifests before ranking

    ranked = sorted(intent_scores.items(), key=lambda kv: kv[1], reverse=True)
    if not ranked:
        raise CapabilityConfusionError("no candidate tools for intent")

    top_name, top_score = ranked[0]
    if len(ranked) > 1:
        second_name, second_score = ranked[1]
        if top_score >= similarity_threshold and second_score >= similarity_threshold:
            a, b = manifests[top_name], manifests[second_name]
            if a.effect_class != b.effect_class:
                raise CapabilityConfusionError(
                    f"ambiguous intent: {top_name!r} ({a.effect_class}) vs "
                    f"{second_name!r} ({b.effect_class}); refusing to auto-select"
                )
    return top_name
