# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-s-declared-capability-set-as-untrusted-input-rather-than-as-a-schema-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-s-declared-capability-set-as-untrusted-input-rather-than-as-a-schema-contract.warrant.json
# Markdown SHA-256:   dfe3f46364ccacb283a424a4eda9aae6000d2b6b72b97ad1eae5ddc5fbaeb2b4
# Code AST SHA-256:   7b5cca3ff0758158d048b970e9e53783c086bbb04f8475f12a53e36161db13aa
# Verified Classes:   ManifestTrustError, TrustAnchor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestTrustError(RuntimeError):
    """Raised when a remote tool manifest or agent-card cannot be admitted
    on semantic grounds even though it is structurally valid."""
    pass


@dataclass(frozen=True)
class TrustAnchor:
    pinned_endpoint_ids: frozenset
    attested_capability_hashes: frozenset


def _capability_hash(capabilities: list) -> str:
    canonical = json.dumps(sorted(capabilities), separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def admit_manifest(manifest: dict, anchor: TrustAnchor) -> dict:
    # Syntactic admission: necessary, never sufficient.
    declared = manifest.get("capabilities", [])
    endpoint_id = manifest.get("endpoint_id")
    cap_hash = _capability_hash(declared)

    # Condition 3: endpoint identity pinned, not resolved by role string.
    if endpoint_id not in anchor.pinned_endpoint_ids:
        raise ManifestTrustError(
            f"endpoint {endpoint_id!r} not pinned; declared role "
            f"{manifest.get('role')!r} is attacker-controlled and ignored"
        )

    # Conditions 1 & 4: capability set attested out-of-band, exact-scope.
    if cap_hash not in anchor.attested_capability_hashes:
        raise ManifestTrustError(
            f"capability set {declared!r} (hash {cap_hash[:12]}) lacks "
            f"out-of-band attestation; self-signed claim rejected"
        )

    # Condition 2: quarantine description prose from the planner channel.
    description = manifest.get("description", "")
    if _contains_imperative(description):
        raise ManifestTrustError(
            "manifest description contains imperative prose; must be "
            "delivered as delimited data, never as planner instruction"
        )

    return {"capabilities": declared, "endpoint_id": endpoint_id,
            "description_as_data": description}


def _contains_imperative(text: str) -> bool:
    lowered = text.lower()
    triggers = ("before calling", "you must", "resolve via", "pass the raw",
                "then call", "ignore previous")
    return any(t in lowered for t in triggers)


def bind_tool(manifest: dict, anchor: TrustAnchor) -> dict:
    admitted = admit_manifest(manifest, anchor)
    # Invocation-time re-check: manifest hash must match negotiation-time bind.
    if manifest.get("manifest_hash") != _capability_hash(manifest.get("capabilities", [])):
        raise ManifestTrustError("manifest mutated between negotiation and invocation")
    return admitted
