# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-resolves-a-skill-manifest-mid-session-the-description-field-injection-surface-in-dynamic-skill-loading.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-resolves-a-skill-manifest-mid-session-the-description-field-injection-surface-in-dynamic-skill-loading.warrant.json
# Markdown SHA-256:   43db335c4a382ae69fae978e2f46dcef841c46e661998c53b7d7def0150387b8
# Code AST SHA-256:   e1decd9bdd429ca5d70660468c195698a272c530fc94ea3d9dbfbd1a78c0e5dc
# Verified Classes:   ManifestInjectionError, ManifestRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestInjectionError(RuntimeError):
    """Raised when a re-resolved manifest mutates interpreted fields on a lower-trust channel."""
    pass


INTERPRETED_FIELDS = ("description", "title", "annotations", "examples")


def _hash_manifest(manifest: dict[str, Any]) -> str:
    # Hash the FULL manifest, including free-text fields — not just the schema.
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _interpreted_delta(old: dict[str, Any], new: dict[str, Any]) -> list[str]:
    changed = []
    for name, tool in new.get("tools", {}).items():
        prev = old.get("tools", {}).get(name, {})
        for f in INTERPRETED_FIELDS:
            if prev.get(f) != tool.get(f):
                changed.append(f"{name}.{f}")
    return changed


@dataclass
class ManifestRegistry:
    trust_level: str
    manifest: dict[str, Any] = field(default_factory=dict)
    manifest_hash: str = ""

    def load_initial(self, manifest: dict[str, Any]) -> None:
        self.manifest = manifest
        self.manifest_hash = _hash_manifest(manifest)

    def re_resolve(self, incoming: dict[str, Any], channel_trust: str) -> None:
        if channel_trust != self.trust_level:
            # A lower-trust channel may not silently rewrite the live skill set.
            delta = _interpreted_delta(self.manifest, incoming)
            if delta:
                raise ManifestInjectionError(
                    f"interpreted-field mutation on lower-trust channel: {delta}; "
                    f"channel={channel_trust} registry={self.trust_level}"
                )
        if _hash_manifest(incoming) == self.manifest_hash:
            return  # no-op refresh, safe
        # Full-manifest hash changed: require explicit re-approval for interpreted deltas.
        delta = _interpreted_delta(self.manifest, incoming)
        if delta:
            raise ManifestInjectionError(
                f"manifest integrity gate tripped; interpreted fields changed: {delta}"
            )
        self.manifest = incoming
        self.manifest_hash = _hash_manifest(incoming)


def guarded_refresh(registry: ManifestRegistry, incoming: dict[str, Any], channel_trust: str) -> None:
    try:
        registry.re_resolve(incoming, channel_trust)
    except ManifestInjectionError:
        # Quarantine: keep prior manifest live, do not splice injected description.
        raise
