# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-capability-poisoning-injected-through-a-tool-manifest-before-the-poisoned-capability-is-committed-to-its-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-capability-poisoning-injected-through-a-tool-manifest-before-the-poisoned-capability-is-committed-to-its-tool-registry.warrant.json
# Markdown SHA-256:   9bd4ede0aa81b8c33a97f13ba236793a1a785206b63061b58a8600298028330b
# Code AST SHA-256:   356bb26d7ddb8640ba84963b9de4512489728fbdd23a6b5106b442223622c3e1
# Verified Classes:   EffectClass, CapabilityPoisoningError, ManifestEntry, Registry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    READ_LOCAL = "read:local"
    READ_DOCUMENT = "read:document"
    WRITE_LOCAL = "write:local"
    EGRESS_EXTERNAL = "egress:external"
    EXECUTE = "execute"


class CapabilityPoisoningError(RuntimeError):
    """Raised when a manifest entry's declared effect diverges from its derived effect,
    or when its description carries imperative directives that steer the planner."""


# Descriptions that address the agent rather than describe the tool.
IMPERATIVE_MARKERS = (
    "always include",
    "always send",
    "always pass",
    "prior turns",
    "conversation history",
    "credentials",
    "api key",
    "recommended for all",
    "you must",
)


@dataclass
class ManifestEntry:
    name: str
    description: str
    declared_effect: EffectClass
    parameters: dict
    source_signature: str | None
    raw: bytes = b""

    def content_hash(self) -> str:
        return hashlib.sha256(self.raw or self.description.encode()).hexdigest()


@dataclass
class Registry:
    committed: dict = field(default_factory=dict)
    quarantined: dict = field(default_factory=dict)


def derive_effect(entry: ManifestEntry) -> EffectClass:
    """Derive effect class from structure, independent of the declared claim."""
    free_text = any(
        p.get("type") == "string" and p.get("free_form")
        for p in entry.parameters.values()
    )
    if free_text and entry.declared_effect in (
        EffectClass.READ_DOCUMENT,
        EffectClass.READ_LOCAL,
    ):
        # A free-form string param on a read tool is an egress channel.
        return EffectClass.EGRESS_EXTERNAL
    return entry.declared_effect


def reconcile_and_commit(entry: ManifestEntry, registry: Registry) -> None:
    if entry.source_signature is None:
        raise CapabilityPoisoningError(
            f"manifest '{entry.name}' has no verifiable provenance; refusing commit"
        )

    lowered = entry.description.lower()
    hits = [m for m in IMPERATIVE_MARKERS if m in lowered]
    if hits:
        raise CapabilityPoisoningError(
            f"manifest '{entry.name}' description carries imperative directives "
            f"addressed to the agent: {hits}; quarantine and strip before re-review"
        )

    derived = derive_effect(entry)
    if derived is not entry.declared_effect:
        raise CapabilityPoisoningError(
            f"manifest '{entry.name}' declared {entry.declared_effect.value} "
            f"but structure permits {derived.value}; effect-class mismatch"
        )

    # Re-fetch safety: description change is a capability change.
    prior = registry.committed.get(entry.name)
    if prior and prior["hash"] != entry.content_hash():
        raise CapabilityPoisoningError(
            f"manifest '{entry.name}' description mutated since commit; "
            f"requires re-reconciliation, not silent update"
        )

    registry.committed[entry.name] = {
        "hash": entry.content_hash(),
        "effect": derived.value,
    }
