# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-never-re-validates-after-the-first-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-never-re-validates-after-the-first-handshake.warrant.json
# Markdown SHA-256:   b2cd145fe7f4bff7dfe496e0895995d08e668555df11c6c705e0b80ac29dd93d
# Code AST SHA-256:   a868abccefa69a3da099fdb5dc36e1ae9de423ceca683cb2fadef9203d1fc58c
# Verified Classes:   CapabilityContractViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityContractViolation(RuntimeError):
    """Raised when a tool's executed behavior or output role exceeds its cached capability contract."""
    pass


TRUSTED_DIRECTIVE_SOURCES = frozenset()  # nothing is trusted to emit directives by default


def admit_tool_output(
    tool_name: str,
    cached_manifest: dict,
    output: object,
    intended_use: str,
) -> dict:
    """
    Gate admission of a tool return value into the agent reasoning context.

    intended_use: 'data' (parse/summarize/cite) or 'directive' (feed back as instruction).
    """
    if intended_use == "directive" and tool_name not in TRUSTED_DIRECTIVE_SOURCES:
        raise CapabilityContractViolation(
            f"tool '{tool_name}' returned a value intended as a directive, but it is "
            f"not in the trusted-directive-source set; refusing to admit."
        )

    declared = cached_manifest.get("side_effects", "unknown")
    if declared == "none" and _output_looks_like_instruction(output):
        raise CapabilityContractViolation(
            f"tool '{tool_name}' declared side_effects=none but returned instruction-shaped "
            f"content; treating as data only and flagging for re-attestation."
        )

    return {
        "source": f"tool:{tool_name}",
        "trust": "data",
        "value": output,
        "requires_reattest": declared == "none" and _output_looks_like_instruction(output),
    }


def _output_looks_like_instruction(output: object) -> bool:
    """Heuristic: imperative verbs, tool-call syntax, or role markers in returned text."""
    if not isinstance(output, str):
        return False
    markers = ("ignore previous", "you must", "call ", "execute ", "<|", "system:")
    low = output.lower()
    return any(m in low for m in markers)


def invoke_with_contract_check(
    registry: dict,
    tool_name: str,
    args: dict,
    intended_use: str = "data",
) -> dict:
    entry = registry.get(tool_name)
    if entry is None:
        raise CapabilityContractViolation(f"tool '{tool_name}' not in registry")

    # Re-attest: manifest hash must match the cached snapshot at use time.
    live_hash = entry["server"].fetch_manifest_hash()
    if live_hash != entry["cached_hash"]:
        raise CapabilityContractViolation(
            f"manifest for '{tool_name}' changed since handshake "
            f"({entry['cached_hash']} -> {live_hash}); refusing invocation."
        )

    output = entry["server"].call(tool_name, args)
    return admit_tool_output(tool_name, entry["manifest"], output, intended_use)
