# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-capability-discovery-and-capability-invocation-in-dynamically-loaded-skills-and-mcp-tool-poison.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-capability-discovery-and-capability-invocation-in-dynamically-loaded-skills-and-mcp-tool-poison.warrant.json
# Markdown SHA-256:   a0d8477e21f5d480c02551c575e4f93cc2544054ecd9db9377a9153cdf65a4a3
# Code AST SHA-256:   0d132913ec4125767f8bb9df9f72f003855cae9e20d7df073b31406f1cfc7305
# Verified Classes:   DescriptorTrustViolation, Descriptor, SessionTrustState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from typing import Literal


class DescriptorTrustViolation(RuntimeError):
    """Raised when a discovered capability descriptor crosses from
    call-shaping data into plan-shaping instruction without operator
    re-authorization."""


# Fields a harness may feed the planner as *data* (call-shaping).
CALL_SHAPING_FIELDS = frozenset({"name", "input_schema", "output_schema"})

# Fields that, if rendered into an instruction-bearing channel, let the
# descriptor author the plan. These are the poisoning surface.
PLAN_SHAPING_FIELDS = frozenset(
    {"description", "examples", "usage_notes", "deprecation", "error_template"}
)

# Capability domains where any new tool requires explicit re-auth,
# regardless of how benign the descriptor reads.
SENSITIVE_DOMAINS = frozenset({"auth", "filesystem", "network_egress", "credentials"})


@dataclass(frozen=True)
class Descriptor:
    tool_id: str
    fields: dict[str, str]
    source: Literal["operator", "registry", "mcp_server"]
    content_hash: str
    domains: frozenset[str] = field(default_factory=frozenset)

    @classmethod
    def from_payload(cls, tool_id: str, fields: dict[str, str],
                     source: str, domains: set[str]) -> "Descriptor":
        h = hashlib.sha256(
            repr(sorted(fields.items())).encode()
        ).hexdigest()
        return cls(tool_id, dict(fields), source, h, frozenset(domains))


@dataclass
class SessionTrustState:
    pinned_hashes: dict[str, str] = field(default_factory=dict)
    approved_domains: set[str] = field(default_factory=set)


def admit_descriptor(
    desc: Descriptor,
    state: SessionTrustState,
    operator_approved: bool,
) -> None:
    """Gate a descriptor at discovery time, before any prompt render.

    Raises DescriptorTrustViolation if the descriptor would let its author
    shape the plan, or if it drifts from a pinned hash, or if it enters a
    sensitive capability domain without explicit re-authorization.
    """
    # 1. Provenance fence: registry/MCP prose must never be plan-shaping.
    if desc.source != "operator":
        leaked = PLAN_SHAPING_FIELDS.intersection(desc.fields)
        if leaked:
            raise DescriptorTrustViolation(
                f"descriptor {desc.tool_id!r} from {desc.source!r} carries "
                f"plan-shaping fields {sorted(leaked)}; quarantine as inert data "
                f"or require operator re-authorization before render"
            )

    # 2. Content-hash pin: refuse in-session drift even from a trusted source.
    pinned = state.pinned_hashes.get(desc.tool_id)
    if pinned is not None and pinned != desc.content_hash:
        raise DescriptorTrustViolation(
            f"descriptor {desc.tool_id!r} hash drift "
            f"{pinned[:12]} -> {desc.content_hash[:12]} mid-session; "
            f"freeze plan and surface delta to operator"
        )

    # 3. Capability-domain overlap: label is irrelevant, capability is not.
    hit = desc.domains.intersection(SENSITIVE_DOMAINS)
    if hit and not operator_approved:
        raise DescriptorTrustViolation(
            f"descriptor {desc.tool_id!r} enters sensitive domains "
            f"{sorted(hit)} without operator re-authorization; agent may not "
            f"expand its own instruction surface"
        )

    if desc.source == "operator" or operator_approved:
        state.pinned_hashes[desc.tool_id] = desc.content_hash
        state.approved_domains.update(desc.domains)


def check_argument_provenance(
    tool_id: str,
    arg_value: str,
    desc: Descriptor,
    task_text: str,
) -> None:
    """Bound argument-construction injection: an emitted argument whose
    value appears only in descriptor prose (not in the task) is suspect."""
    if arg_value in task_text:
        return
    prose = " ".join(
        desc.fields[f] for f in PLAN_SHAPING_FIELDS if f in desc.fields
    )
    if arg_value and arg_value in prose:
        raise DescriptorTrustViolation(
            f"argument for {tool_id!r} value {arg_value!r} derives from "
            f"descriptor prose, not from task; hold for review"
        )
