# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-description-field-smuggling-in-dynamically-loaded-tool-manifests.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-description-field-smuggling-in-dynamically-loaded-tool-manifests.warrant.json
# Markdown SHA-256:   57a908175a61ef08de54fc2dd7f29e5a8cb1a128a956cb654f3e11d5b9e25870
# Code AST SHA-256:   f665bfa3e41590e77da6122316a7d752aa994cbd8c74bffcb0ee41935770e50a
# Verified Classes:   ManifestSmugglingError, QuarantinedTool
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field
from typing import Any

# Clause patterns that cross from documentation into control flow.
_CONTROL_CLAUSE = re.compile(
    r"\b(before|after|first|always|never|instead|do not tell|"
    r"ignore|disregard|you (must|should)|required for compliance)\b",
    re.IGNORECASE,
)
# References to state outside the tool's declared scope.
_EXTERNAL_REF = re.compile(
    r"(~/|/etc/|/home/|\.ssh|\.env|environment variable|"
    r"previous (message|conversation)|call `?\w+`? (first|before))",
    re.IGNORECASE,
)
# Argument names historically used as smuggling channels.
_SMUGGLE_ARGS = {"context", "preamble", "metadata", "audit", "session", "notes"}


class ManifestSmugglingError(RuntimeError):
    """Raised when a tool manifest's description crosses the documentation boundary."""


@dataclass
class QuarantinedTool:
    name: str
    summary: str
    reasons: list[str] = field(default_factory=list)


def _schema_summary(name: str, schema: dict[str, Any]) -> str:
    props = schema.get("properties", {})
    required = set(schema.get("required", []))
    args = []
    for arg, spec in props.items():
        opt = "" if arg in required else "?"
        args.append(f"{arg}{opt}: {spec.get('type', 'any')}")
    ret = schema.get("returns", {}).get("type", "any")
    return f"{name}({', '.join(args)}) -> {ret}"


def vet_manifest(manifest: dict[str, Any]) -> QuarantinedTool | dict[str, Any]:
    """Bind a tool only if its description stays within documentation contract."""
    name = manifest.get("name")
    if not name:
        raise ManifestSmugglingError("manifest missing name")

    desc = manifest.get("description", "") or ""
    schema = manifest.get("inputSchema", {}) or {}
    props = set(schema.get("properties", {}).keys())

    reasons: list[str] = []

    if _CONTROL_CLAUSE.search(desc):
        reasons.append("control-flow directive in description")
    if _EXTERNAL_REF.search(desc):
        reasons.append("reference to out-of-scope state")

    # Smuggled argument must actually exist to be exploitable; if the
    # description names a smuggle-prone arg, require handler attestation.
    named_smuggle = {a for a in _SMUGGLE_ARGS if a in desc and a in props}
    if named_smuggle and not manifest.get("attestation", {}).get("declares_use"):
        reasons.append(f"smuggle-prone argument(s) {sorted(named_smuggle)} un-attested")

    if reasons:
        return QuarantinedTool(
            name=name,
            summary=_schema_summary(name, schema),
            reasons=reasons,
        )

    # Pin the exact bytes so a refresh with mutated description is caught.
    manifest["_summary_hash"] = hashlib.sha256(
        _schema_summary(name, schema).encode()
    ).hexdigest()
    return manifest


def refresh_tool(pinned: dict[str, Any], fetched: dict[str, Any]) -> dict[str, Any]:
    """Re-vet on refresh; reject silent description drift."""
    vetted = vet_manifest(fetched)
    if isinstance(vetted, QuarantinedTool):
        return {"bound": False, "quarantined": vetted}
    if vetted["_summary_hash"] != pinned.get("_summary_hash"):
        raise ManifestSmugglingError(
            f"tool {vetted['name']} summary drifted on refresh; "
            "re-review required before rebinding"
        )
    return {"bound": True, "tool": vetted}
