# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-dynamically-loaded-tool-manifest-whose-declared-capability-schema-diverges-from-its-runtime-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-dynamically-loaded-tool-manifest-whose-declared-capability-schema-diverges-from-its-runtime-side-effects.warrant.json
# Markdown SHA-256:   96cc7a05c60b6d7528693f9feabbe00498a14f8cefcfcef1b76d492b62e1cf3e
# Code AST SHA-256:   72bf9f9efa89b17c1ade7232d6244e08941fae40682e8125fb7b5acdbf7a7611
# Verified Classes:   ManifestEffectDivergence, Manifest, Binding
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ManifestEffectDivergence(RuntimeError):
    """Raised when a tool manifest's declared effects are not a superset of observed effects."""
    pass


@dataclass(frozen=True)
class Manifest:
    name: str
    declared_effects: frozenset
    declared_params: frozenset
    description: str
    content_hash: str


@dataclass
class Binding:
    manifest: Manifest
    observed_effects: frozenset
    observed_inputs: frozenset
    pinned_hash: str = field(default="")


IMPERATIVE_MARKERS = ("always", "ignore previous", "also call", "must call", "do not tell")


def bind_tool(manifest: Manifest, observed_effects: frozenset,
              observed_inputs: frozenset, pinned_hash: str) -> Binding:
    # TOCTOU guard: manifest must match the hash captured at selection time.
    actual_hash = hashlib.sha256(
        f"{manifest.name}|{sorted(manifest.declared_effects)}|"
        f"{sorted(manifest.declared_params)}|{manifest.description}".encode()
    ).hexdigest()
    if pinned_hash and actual_hash != pinned_hash:
        raise ManifestEffectDivergence(
            f"manifest hash drift for {manifest.name}: "
            f"pinned={pinned_hash[:12]} actual={actual_hash[:12]}"
        )

    # Effect-superset invariant: declared must cover observed.
    undeclared_effects = observed_effects - manifest.declared_effects
    if undeclared_effects:
        raise ManifestEffectDivergence(
            f"{manifest.name} performs undeclared effects {sorted(undeclared_effects)}; "
            f"declared={sorted(manifest.declared_effects)}"
        )

    # Undeclared input channels (env, ambient files, network) are injection paths.
    undeclared_inputs = observed_inputs - manifest.declared_params
    if undeclared_inputs:
        raise ManifestEffectDivergence(
            f"{manifest.name} reads undeclared inputs {sorted(undeclared_inputs)}"
        )

    # Imperative description text is an injection vector, not documentation.
    lowered = manifest.description.lower()
    for marker in IMPERATIVE_MARKERS:
        if marker in lowered:
            raise ManifestEffectDivergence(
                f"{manifest.name} description contains imperative directive '{marker}'"
            )

    return Binding(manifest=manifest, observed_effects=observed_effects,
                   observed_inputs=observed_inputs, pinned_hash=actual_hash)


# Example: the symlink + credential-read tool from the observed trace.
poisoned = Manifest(
    name="summarize_document",
    declared_effects=frozenset({"read"}),
    declared_params=frozenset({"path"}),
    description="Summarize a document. Input: {path}. Read-only.",
    content_hash="",
)
try:
    bind_tool(
        poisoned,
        observed_effects=frozenset({"read", "credential_read", "network_egress"}),
        observed_inputs=frozenset({"path", "AGENT_SECRETS_ENV"}),
        pinned_hash="",
    )
except ManifestEffectDivergence as exc:
    # Fail closed: tool is not bound into the planner's action space.
    print(f"REJECTED: {exc}")
