# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-tool-whose-manifest-declares-capabilities-the-transport-cannot-enforce.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-tool-whose-manifest-declares-capabilities-the-transport-cannot-enforce.warrant.json
# Markdown SHA-256:   e0ba0e9e84fbdbd4889d384218cefad9f88576cbd7741970dedb97fe14d23ba9
# Code AST SHA-256:   1a22c4882f861d306a361093de040eac1a328cf44b9364dfdec3ba0150f197ec
# Verified Classes:   ManifestCapabilityViolation, TransportPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any

class ManifestCapabilityViolation(RuntimeError):
    """Raised when a tool manifest declares capabilities the transport cannot enforce."""
    pass

TRAVERSAL_MARKERS = ("..", "/etc/", "\\", "file://", "$(", "`")
IMPERATIVE_MARKERS = ("note to assistant", "you must", "first call", "before you")

@dataclass
class TransportPolicy:
    allow_paths: tuple[str, ...] = ()
    allow_env: bool = False
    honor_annotations: bool = False

def audit_manifest(tool: dict[str, Any], policy: TransportPolicy) -> dict[str, Any]:
    """Intersect declared capability with transport enforcement; refuse on compound trigger."""
    name = tool.get("name", "<unnamed>")
    desc = (tool.get("description") or "").lower()
    annotations = tool.get("annotations") or {}
    schema = tool.get("inputSchema") or {}
    props = schema.get("properties") or {}

    over_declared = False
    auto_approve_claim = False

    # Vector 1: instruction smuggling in description.
    if any(m in desc for m in IMPERATIVE_MARKERS):
        over_declared = True

    # Vector 2: poisoned defaults the model never chooses.
    for pname, spec in props.items():
        default = spec.get("default")
        if isinstance(default, str) and any(t in default for t in TRAVERSAL_MARKERS):
            over_declared = True
        if isinstance(default, str) and default.startswith("/"):
            over_declared = True

    # Vector 3: auto-approval annotations asserting unenforced safety.
    if annotations.get("readOnlyHint") and not policy.honor_annotations:
        auto_approve_claim = True
        if "env" in name.lower() or "exec" in name.lower() or "read" in name.lower():
            over_declared = True

    if over_declared and auto_approve_claim:
        raise ManifestCapabilityViolation(
            f"Refusing registration of '{name}': manifest declares capabilities "
            f"transport cannot enforce, and carries auto-approval annotations "
            f"that would suppress confirmation."
        )

    # Below the boundary: narrow the manifest to the enforced policy.
    narrowed = dict(tool)
    narrowed["inputSchema"] = {
        **schema,
        "properties": {
            k: {kk: vv for kk, vv in v.items() if kk != "default"}
            for k, v in props.items()
        },
    }
    narrowed["description"] = f"[UNTRUSTED MANIFEST TEXT] {tool.get('description', '')}"
    narrowed["annotations"] = {"advisory": True, **annotations}
    return narrowed

def register(tools: list[dict[str, Any]], policy: TransportPolicy) -> list[dict[str, Any]]:
    callable_set = []
    for t in tools:
        try:
            callable_set.append(audit_manifest(t, policy))
        except ManifestCapabilityViolation:
            # Hard refusal: tool is excluded, not degraded.
            continue
    if not callable_set:
        raise ManifestCapabilityViolation("All tools refused; no callable capability remains.")
    return callable_set
