# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-surface-in-dynamically-loaded-tool-registries-description-field-provenance-collapse-as-the-load-bea.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-skill-injection-surface-in-dynamically-loaded-tool-registries-description-field-provenance-collapse-as-the-load-bea.warrant.json
# Markdown SHA-256:   26c1f05c3266013ffc84adb569c6e973ac6d6dc6feaa333c0f51cbbccc5604a9
# Code AST SHA-256:   99f738cc8aec95e301ac7af4d9d25a67c69cad0a4d808527b795ccd8af285915
# Verified Classes:   DescriptionBoundaryViolation, Provenance, ToolManifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from enum import Enum


class DescriptionBoundaryViolation(RuntimeError):
    """Raised when a tool description claims authority it does not have."""


class Provenance(Enum):
    FIRST_PARTY_REVIEWED = "first_party_reviewed"
    THIRD_PARTY_MANIFEST = "third_party_manifest"


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    provenance: Provenance
    registry_tool_names: frozenset[str]


# Structural markers that indicate a description is referencing the registry,
# another tool's identity, or caller behavior rather than its own contract.
_AUTHORITY_CLAIM_MARKERS = (
    "supersede",
    "route ",
    "instead call",
    "for compatibility",
    "deprecated by",
    "should call",
    "migrate to",
)


def _references_peer(description: str, peers: frozenset[str]) -> bool:
    lowered = description.lower()
    return any(peer.lower() in lowered for peer in peers if peer)


def enforce_description_boundary(manifest: ToolManifest) -> str:
    """Return a model-safe description, or raise if the manifest is out of contract."""
    if manifest.provenance is Provenance.FIRST_PARTY_REVIEWED:
        return manifest.description

    lowered = manifest.description.lower()
    claims_authority = any(marker in lowered for marker in _AUTHORITY_CLAIM_MARKERS)
    references_peer = _references_peer(manifest.description, manifest.registry_tool_names)

    if claims_authority or references_peer:
        raise DescriptionBoundaryViolation(
            f"tool {manifest.name!r} description claims registry/peer authority; "
            f"strip to structural summary before model exposure "
            f"(sha256={hashlib.sha256(manifest.description.encode()).hexdigest()[:12]})"
        )

    return manifest.description


def build_selection_context(manifests: list[ToolManifest]) -> str:
    peers = frozenset(m.name for m in manifests)
    lines: list[str] = []
    for manifest in manifests:
        scoped = ToolManifest(
            name=manifest.name,
            description=manifest.description,
            provenance=manifest.provenance,
            registry_tool_names=peers,
        )
        safe_description = enforce_description_boundary(scoped)
        lines.append(f"[{manifest.provenance.value}] {manifest.name}: {safe_description}")
    return "\n".join(lines)
