# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-poisoned-tool-manifests-from-silently-widening-an-agent-s-capability-surface-at-registration-time.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-poisoned-tool-manifests-from-silently-widening-an-agent-s-capability-surface-at-registration-time.warrant.json
# Markdown SHA-256:   97e48f11eaee6226bd3e9bd0bcaf3118bb56ac86d234970da56f923b1b23231f
# Code AST SHA-256:   512821f552ef00449af9822714b1ad480fcabec9c3653eafc1f2fb44a045538a
# Verified Classes:   ManifestLaunderingError, ToolManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping

class ManifestLaunderingError(RuntimeError):
    """Raised when a tool manifest attempts to smuggle authority via descriptive text."""
    pass

SCOPE_CLAIM_TOKENS = (
    "may read", "has access to", "delegated", "trusted to",
    "is authorized", "should be given", "operates with",
)

@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    schema_fields: frozenset[str]
    publisher_key: str

def register_tool(
    manifest: ToolManifest,
    *,
    pinned_keys: Mapping[str, str],
    policy_capabilities: Mapping[str, frozenset[str]],
    median_description_len: int,
) -> None:
    # 1. Provenance: publisher must match the pinned key for this server identity.
    if pinned_keys.get(manifest.name) != manifest.publisher_key:
        raise ManifestLaunderingError(
            f"{manifest.name}: publisher key not pinned; refusing registration"
        )

    # 2. Description size bound: oversized prose is the primary laundering vector.
    if len(manifest.description) > 2 * max(median_description_len, 1):
        raise ManifestLaunderingError(
            f"{manifest.name}: description {len(manifest.description)} chars exceeds "
            f"2x median; quarantined as inert"
        )

    # 3. Scope-claiming language is a permission assertion, never honored from a manifest.
    lowered = manifest.description.lower()
    for token in SCOPE_CLAIM_TOKENS:
        if token in lowered:
            raise ManifestLaunderingError(
                f"{manifest.name}: description asserts scope via '{token}'; "
                f"authority must come from policy layer, not metadata"
            )

    # 4. Schema must not introduce capabilities the policy layer never granted.
    granted = policy_capabilities.get(manifest.name, frozenset())
    undeclared = manifest.schema_fields - granted
    if undeclared:
        raise ManifestLaunderingError(
            f"{manifest.name}: schema fields {sorted(undeclared)} not present in "
            f"policy grant; tool registered as inert pending operator review"
        )
