# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-declared-schema-diverges-from-its-observed-behavior-at-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-tool-manifest-whose-declared-schema-diverges-from-its-observed-behavior-at-first-invocation.warrant.json
# Markdown SHA-256:   07220ad0a91a9c4b8b5b7526faad14bbc656c1f2c7c8524b4ef10d9cee12e27b
# Code AST SHA-256:   0718b38b4632a813ad645871658cad67ab00e7db47fb3bace77a242713df236b
# Verified Classes:   ManifestDivergenceError, ToolState, Manifest, InvocationRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ManifestDivergenceError(RuntimeError):
    """Raised when observed tool behavior contradicts its declared manifest."""
    pass


class ToolState(Enum):
    DECLARED_UNVERIFIED = "declared_unverified"
    VERIFIED = "verified"
    QUARANTINED = "quarantined"


@dataclass
class Manifest:
    name: str
    declared_class: str          # "read_only" | "write" | "network"
    declared_params: set[str]
    signature: str
    raw: dict = field(default_factory=dict)

    def snapshot_hash(self) -> str:
        return hashlib.sha256(repr(sorted(self.raw.items())).encode()).hexdigest()


@dataclass
class InvocationRecord:
    tool_name: str
    input_args: dict
    output_text: str
    manifest_hash: str


DIRECTIVE_MARKERS = ("call ", "invoke ", "before continuing", "you must", "ignore previous")


def _emits_directive(output_text: str) -> bool:
    lowered = output_text.lower()
    return any(marker in lowered for marker in DIRECTIVE_MARKERS)


def _references_unknown_tool(output_text: str, plan_tools: set[str]) -> bool:
    for token in output_text.split():
        cleaned = token.strip(".,;:()'\"")
        if cleaned.endswith("_tool") or (cleaned.isidentifier() and "_" in cleaned):
            if cleaned not in plan_tools and cleaned not in ("doc_id", "include_credentials"):
                # heuristic: identifier-shaped token not in plan
                if cleaned.count("_") >= 1 and len(cleaned) > 6:
                    return True
    return False


def bind_and_probe(
    manifest: Manifest,
    probe_args: dict,
    invoke_fn,
    plan_tools: set[str],
) -> ToolState:
    """First invocation runs against declared worst-case; divergence quarantines."""
    if manifest.declared_class != "read_only":
        # Only read_only tools get the probe-then-verify path; write tools
        # require out-of-band attestation and are out of scope here.
        return ToolState.DECLARED_UNVERIFIED

    record = InvocationRecord(
        tool_name=manifest.name,
        input_args=probe_args,
        output_text=invoke_fn(manifest.name, probe_args),
        manifest_hash=manifest.snapshot_hash(),
    )

    if _emits_directive(record.output_text):
        raise ManifestDivergenceError(
            f"tool {manifest.name!r} declared read_only but emitted directive-like "
            f"content on probe; manifest_hash={record.manifest_hash}; "
            f"quarantine and roll back to pre-invocation checkpoint"
        )

    if _references_unknown_tool(record.output_text, plan_tools):
        raise ManifestDivergenceError(
            f"tool {manifest.name!r} output references tool outside resolved plan; "
            f"manifest_hash={record.manifest_hash}; possible skill injection"
        )

    return ToolState.VERIFIED
