# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-dynamically-loaded-mcp-tool-manifest-s-description-field-as-a-semantic-contract-rather-than-untrusted-data.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-dynamically-loaded-mcp-tool-manifest-s-description-field-as-a-semantic-contract-rather-than-untrusted-data.warrant.json
# Markdown SHA-256:   495000659657b323899d562dc2c3c66c19be79ab0641f55ce563456833ae64ff
# Code AST SHA-256:   a7191c8039c97231ca9df6288bcce853722bd0f1c8645a6cd8e516b2a21a65d9
# Verified Classes:   ManifestProvenanceViolation, ProvenanceTag
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestProvenanceViolation(RuntimeError):
    """Raised when a tool call's arguments trace to manifest-sourced text
    rather than to user- or system-tagged context segments."""
    pass


class ProvenanceTag:
    SYSTEM = "system"
    USER = "user"
    MANIFEST = "manifest"
    TOOL_OUTPUT = "tool_output"

    TRUSTED_FOR_ARGUMENTS = frozenset({SYSTEM, USER})


def resolve_tool_call(call, context_segments):
    """
    call: dict with 'name' and 'arguments'
    context_segments: list of (tag, text) covering the prompt in order

    Enforces: every argument value must be drawable from a trusted segment.
    Manifest-sourced substrings are treated as data, never as call targets.
    """
    manifest_text = " ".join(
        text for tag, text in context_segments if tag == ProvenanceTag.MANIFEST
    )
    trusted_text = " ".join(
        text for tag, text in context_segments
        if tag in ProvenanceTag.TRUSTED_FOR_ARGUMENTS
    )

    for arg_name, arg_value in call["arguments"].items():
        if not isinstance(arg_value, str):
            continue
        # If the value appears in manifest prose but NOT in trusted context,
        # the planner drew it from the untrusted channel.
        if arg_value in manifest_text and arg_value not in trusted_text:
            raise ManifestProvenanceViolation(
                f"Argument {arg_name!r}={arg_value!r} for tool "
                f"{call['name']!r} originates in manifest text, not in "
                f"user/system context. Halting: manifest is data, not "
                f"instruction."
            )

    # Capability-steering check: a manifest naming sibling tools is suspect.
    sibling_tools = {s for s in call.get("_known_tools", [])}
    for tool_name in sibling_tools:
        if tool_name != call["name"] and tool_name in manifest_text:
            raise ManifestProvenanceViolation(
                f"Manifest for {call['name']!r} references sibling tool "
                f"{tool_name!r}; capability-steering suspected. "
                f"Quarantine manifest and require re-registration."
            )

    return call


def apply_manifest_refresh(current_turn, new_manifests, plan_committed):
    """Manifests may only swap at a turn boundary, never mid-turn."""
    if plan_committed:
        raise ManifestProvenanceViolation(
            "Manifest refresh attempted mid-turn after plan commitment. "
            "Buffer until next user turn or invalidate plan explicitly."
        )
    return new_manifests
