# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-registry-capability-manifests-as-adversarial-input-rather-than-trusted-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-registry-capability-manifests-as-adversarial-input-rather-than-trusted-metadata.warrant.json
# Markdown SHA-256:   19d13bd111a92e693a7543a8711d5e223b0444252abea32eaff92dd649cf4266
# Code AST SHA-256:   ddb9cefc2d2fde935cfc8e96f9cf85243e77d995cebfb3327e00d3757c239646
# Verified Classes:   ManifestInjectionError, Manifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestInjectionError(RuntimeError):
    """Raised when a registry manifest attempts to route free-text into an
    instruction-bearing context region, or when prompt cache invalidation
    is keyed on tool liveness instead of manifest content hash."""


@dataclass
class Manifest:
    name: str
    schema: dict
    capability_tags: frozenset
    free_text: dict = field(default_factory=dict)  # description, examples, etc.


INSTRUCTION_REGION_FIELDS = {"description", "examples", "when_to_use", "notes"}


def build_tool_preamble(manifests, *, allow_free_text_in_prompt=False):
    """Construct the system-prompt tool block. Only typed capability tags and
    parameter schemas may enter; free-text is quarantined to a retrieval index."""
    retrieval_index = {}
    lines = []
    for m in manifests:
        leaked = INSTRUCTION_REGION_FIELDS & set(m.free_text)
        if leaked and not allow_free_text_in_prompt:
            # free-text is permitted to exist, but only in the retrieval channel
            retrieval_index[m.name] = m.free_text
        elif leaked and allow_free_text_in_prompt:
            raise ManifestInjectionError(
                f"manifest {m.name!r} would inject free-text fields "
                f"{sorted(leaked)} into the instruction region"
            )
        tags = ",".join(sorted(m.capability_tags))
        lines.append(f"- {m.name} tags=[{tags}] params={list(m.schema)}")
    return "\n".join(lines), retrieval_index


def content_hash(manifests):
    h = hashlib.sha256()
    for m in sorted(manifests, key=lambda x: x.name):
        h.update(m.name.encode())
        h.update(repr(sorted(m.capability_tags)).encode())
        h.update(repr(sorted(m.free_text.items())).encode())
    return h.hexdigest()


def invalidate_prompt_cache(cached_hash, manifests, live_tool_names):
    """Prompt must be rebuilt when manifest CONTENT changes, not merely when a
    tool is pruned. Pruning a tool whose prose was already injected leaves the
    injection resident; this guard forces a rebuild on any content delta."""
    current = content_hash(manifests)
    if current != cached_hash:
        return True, current
    # If a tool was pruned but content hash is unchanged, prose may still be
    # resident from a prior build -> force rebuild to be safe.
    manifest_names = {m.name for m in manifests}
    if set(live_tool_names) != manifest_names:
        return True, current
    return False, current
