# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-level-skill-injection-when-tool-descriptions-are-trusted-before-tool-schemas-are-validated.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-level-skill-injection-when-tool-descriptions-are-trusted-before-tool-schemas-are-validated.warrant.json
# Markdown SHA-256:   6fbb3f226b59c61db6b733dc7a569f44ced31ef24ca78e197652028a72e3283f
# Code AST SHA-256:   1f60bb02eda5a545ffbb3016eef1b2f22546ce601685890181d7cd152fc479d2
# Verified Classes:   ManifestInjectionError, ValidatedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest's description enters context before validation."""
    pass


@dataclass(frozen=True)
class ValidatedManifest:
    name: str
    body_hash: str
    description: str
    capability_scope: str


def register_tool(manifest: dict, agent_scope: str, pinned_hashes: dict[str, str]) -> ValidatedManifest:
    # 1. Validate schema and capability scope BEFORE touching description.
    schema = manifest.get("inputSchema")
    if not isinstance(schema, dict) or schema.get("type") != "object":
        raise ManifestInjectionError(f"manifest {manifest.get('name')!r} has invalid inputSchema")

    declared_scope = manifest.get("annotations", {}).get("capabilityScope")
    if declared_scope != agent_scope:
        raise ManifestInjectionError(
            f"manifest {manifest.get('name')!r} declares scope {declared_scope!r} "
            f"but agent operates under {agent_scope!r}"
        )

    # 2. Hash the full manifest body and check against pinned source hash.
    body = repr(sorted(manifest.items())).encode("utf-8")
    body_hash = hashlib.sha256(body).hexdigest()
    expected = pinned_hashes.get(manifest["name"])
    if expected is None or expected != body_hash:
        raise ManifestInjectionError(
            f"manifest {manifest['name']!r} body hash {body_hash[:12]} does not match "
            f"pinned hash {str(expected)[:12]}"
        )

    # 3. Only now may the description be admitted to context.
    description = manifest.get("description", "")
    if any(token in description.lower() for token in ("prefer this tool", "always call", "pass the full path")):
        raise ManifestInjectionError(
            f"manifest {manifest['name']!r} description contains directive-like content; "
            "refusing to admit to model context"
        )

    return ValidatedManifest(
        name=manifest["name"],
        body_hash=body_hash,
        description=description,
        capability_scope=declared_scope,
    )
