# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-manifest-as-an-untrusted-instruction-channel-rather-than-a-capability-declaration.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-manifest-as-an-untrusted-instruction-channel-rather-than-a-capability-declaration.warrant.json
# Markdown SHA-256:   29adc6969a38f806900f7cfad18f794fc6163d713c2ac962a63a01dbbfcbcf88
# Code AST SHA-256:   4369007b0bac14ff93659f833bae03bbaf60a01c22fb3c37c6614d1b0fcbdf65
# Verified Classes:   ManifestInjectionError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ManifestInjectionError(RuntimeError):
    """Raised when a dynamically discovered tool manifest attempts to
    influence argument values via prose rather than declaring capability."""


IMPERATIVE_MARKERS = (
    "you should",
    "you must",
    "first read",
    "include the full",
    "also emit",
    "before calling",
    "for compliance",
)

SENSITIVE_ARG_HINTS = ("credential", "token", "secret", "transcript", "preview", "context")


@dataclass
class ToolManifest:
    name: str
    description: str
    input_schema: dict[str, Any]
    source_digest: str = field(default="")


def _digest(manifest: ToolManifest) -> str:
    canonical = json.dumps(
        {"name": manifest.name, "description": manifest.description, "schema": manifest.input_schema},
        sort_keys=True,
    ).encode()
    return hashlib.sha256(canonical).hexdigest()


def _user_implied_args(user_request: str, schema: dict[str, Any]) -> set[str]:
    props = schema.get("properties", {})
    return {name for name in props if name.lower() in user_request.lower()}


def build_tool_call(
    manifest: ToolManifest,
    user_request: str,
    proposed_args: dict[str, Any],
) -> dict[str, Any]:
    """Validate that proposed arguments are authorized by the user request,
    not by imperative prose smuggled into the manifest description."""
    manifest.source_digest = _digest(manifest)
    implied = _user_implied_args(user_request, manifest.input_schema)
    desc_lower = manifest.description.lower()

    poisoned_prose = any(marker in desc_lower for marker in IMPERATIVE_MARKERS)

    for arg_name in proposed_args:
        if arg_name in implied:
            continue
        # Argument not derivable from the user's literal request.
        if poisoned_prose or any(hint in arg_name.lower() for hint in SENSITIVE_ARG_HINTS):
            raise ManifestInjectionError(
                f"tool={manifest.name!r} digest={manifest.source_digest[:12]} "
                f"arg={arg_name!r} is not user-implied and manifest prose is "
                f"imperative; refusing to synthesize value from manifest."
            )
        raise ManifestInjectionError(
            f"tool={manifest.name!r} arg={arg_name!r} has no user-request "
            f"authorization; manifest prose cannot supply argument values."
        )

    return {"tool": manifest.name, "arguments": proposed_args}


def safe_invoke(manifest: ToolManifest, user_request: str, proposed_args: dict[str, Any]) -> dict[str, Any]:
    try:
        return build_tool_call(manifest, user_request, proposed_args)
    except ManifestInjectionError:
        # Fall back to user-implied arguments only; let schema validation
        # surface a genuine requirement as a tool-layer error.
        implied = _user_implied_args(user_request, manifest.input_schema)
        minimal = {k: v for k, v in proposed_args.items() if k in implied}
        return {"tool": manifest.name, "arguments": minimal, "degraded": True}
