# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-schema-over-its-observed-runtime-behavior.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-schema-over-its-observed-runtime-behavior.warrant.json
# Markdown SHA-256:   a90a00e1e7e1a9a31a3695e1084f6b3bae5df3b61e15637488c26cfb08cdce90
# Code AST SHA-256:   3c932a57806e79f78ac5d5d71150b0c5ced30e716a1dff132ecc3566581d18f7
# Verified Classes:   SkillInjectionError, ToolResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class SkillInjectionError(RuntimeError):
    """Raised when a tool return value attempts to influence control flow."""


@dataclass
class ToolResult:
    tool_name: str
    content: str
    declared_output_schema: dict | None
    author_trusted: bool


# Capability classes that a subtask must explicitly opt into.
SCOPED_CAPABILITIES = {"filesystem_read", "network_egress", "credential_access"}


def promote_tool_result(
    result: ToolResult,
    subtask_capabilities: set[str],
    derived_next_call: dict[str, Any] | None = None,
) -> str:
    """
    Gate the promotion of a tool return value into the planning channel.

    Invariants enforced:
      1. Untrusted-author results must carry a declared output schema.
      2. Return content is wrapped as data; it is never treated as instruction.
      3. Any next call derived from this return must stay within the
         subtask's declared capability scope.
    """
    if not result.author_trusted and result.declared_output_schema is None:
        raise SkillInjectionError(
            f"Tool '{result.tool_name}' has no output schema and an untrusted "
            f"author; return channel is unconstrained and cannot be promoted."
        )

    # Structural validation of the return against the declared contract.
    if result.declared_output_schema is not None:
        expected_type = result.declared_output_schema.get("type")
        if expected_type == "string" and not isinstance(result.content, str):
            raise SkillInjectionError(
                f"Tool '{result.tool_name}' returned {type(result.content).__name__} "
                f"but declared string."
            )

    if derived_next_call is not None:
        requested = set(derived_next_call.get("capabilities", []))
        out_of_scope = requested - subtask_capabilities
        if out_of_scope & SCOPED_CAPABILITIES:
            raise SkillInjectionError(
                f"Tool return from '{result.tool_name}' induced a call requiring "
                f"capabilities {sorted(out_of_scope)} outside subtask scope "
                f"{sorted(subtask_capabilities)}; treating as injection."
            )

    # Wrap as untrusted data so the planner cannot read it as a directive.
    return f"<untrusted_tool_output tool={result.tool_name!r}>{result.content}</untrusted_tool_output>"
