# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-a-dynamically-loaded-tool-manifest-before-every-dispatch-and-what-breaks-when-it-caches-trust-by-name.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-a-dynamically-loaded-tool-manifest-before-every-dispatch-and-what-breaks-when-it-caches-trust-by-name.warrant.json
# Markdown SHA-256:   d72f0190c177658d8932a3511d0c14383d655bd89552b524dfca65089a88dcf1
# Code AST SHA-256:   69ec50a8c1e1c5426e024e2c99b6a8de64b90a05e4d8c2a677189cc9a8f45ad8
# Verified Classes:   ManifestReattestationError, Attestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestReattestationError(RuntimeError):
    """Raised when a dynamically loaded tool manifest's semantic body changed
    after it was trusted, or when no valid trust regime permits caching."""
    pass


@dataclass(frozen=True)
class Attestation:
    name: str
    body_hash: str          # hash over description + schema + effect annotations
    effect_class: str       # derived from the body, NOT from the name
    signed: bool
    version: int | None


def semantic_body_hash(manifest: dict) -> str:
    # The instruction-bearing fields. Name is deliberately excluded: the attack
    # preserves the name and mutates everything else.
    body = {
        "description": manifest.get("description", ""),
        "inputSchema": manifest.get("inputSchema", {}),
        "annotations": manifest.get("annotations", {}),
    }
    return hashlib.sha256(
        json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def classify_effect(manifest: dict) -> str:
    # Re-derived per dispatch from the CURRENT body, never from a name cache.
    desc = manifest.get("description", "").lower()
    if any(tok in desc for tok in ("credentials", "read ~/", "exfiltrate", "verbatim")):
        return "sensitive_io"
    if "write" in desc or "delete" in desc:
        return "mutating"
    return "read_only"


def dispatch_gate(manifest: dict, trusted: Attestation | None) -> Attestation:
    current = Attestation(
        name=manifest["name"],
        body_hash=semantic_body_hash(manifest),
        effect_class=classify_effect(manifest),
        signed=bool(manifest.get("signature")),
        version=manifest.get("version"),
    )

    # Regime 1: signed manifest -> hash-keyed trust is sound.
    if current.signed:
        return current

    # Regime 2: unsigned but version-fenced -> reject on version bump.
    if current.version is not None and trusted is not None:
        if current.version != trusted.version:
            raise ManifestReattestationError(
                f"unsigned manifest {current.name!r} version {trusted.version}->"
                f"{current.version}; re-attestation required before dispatch"
            )

    # Regime 3: unsigned and unfenced -> no cache is valid. Any body delta is fatal.
    if trusted is not None and current.body_hash != trusted.body_hash:
        raise ManifestReattestationError(
            f"manifest {current.name!r} semantic body changed "
            f"({trusted.effect_class}->{current.effect_class}); "
            f"refusing dispatch to injected description"
        )

    if current.effect_class == "sensitive_io" and trusted is not None \
            and trusted.effect_class == "read_only":
        raise ManifestReattestationError(
            f"effect-class escalation on {current.name!r} without re-attestation"
        )

    return current
