# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-load-a-tool-manifest-that-mutates-its-own-trust-boundary-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-load-a-tool-manifest-that-mutates-its-own-trust-boundary-mid-session.warrant.json
# Markdown SHA-256:   7c461313c5b02ae15174066b4ec4a1a2114e209911ed38f5f4b2d8df4e7637b7
# Code AST SHA-256:   1c98762082ce2d6807aae5ab8b139d6d672aad38c52ee2c9cf74bbbf4a629611
# Verified Classes:   ManifestTrustViolation, ManifestTrustToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestTrustViolation(RuntimeError):
    """Raised when a re-resolved manifest diverges from the episode-start trust token."""
    pass


@dataclass
class ManifestTrustToken:
    """Binds the FULL manifest bytes (prose included) to a digest at episode start."""
    digests: dict[str, str] = field(default_factory=dict)

    @staticmethod
    def _digest(manifest: dict) -> str:
        # Hash the entire manifest, not just the schema. Description prose is instruction surface.
        canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()
        return hashlib.sha256(canonical).hexdigest()

    def mint(self, manifests: list[dict]) -> None:
        for m in manifests:
            self.digests[m["name"]] = self._digest(m)

    def verify(self, manifests: list[dict]) -> None:
        seen = set()
        for m in manifests:
            name = m["name"]
            seen.add(name)
            if name not in self.digests:
                # A tool appeared mid-episode: trust was never granted for it.
                raise ManifestTrustViolation(
                    f"tool '{name}' appeared after episode start; refusing live injection"
                )
            if self._digest(m) != self.digests[name]:
                # Same name, same schema, mutated description — the core attack.
                raise ManifestTrustViolation(
                    f"manifest for '{name}' mutated mid-episode; description/schema drift"
                )
        if set(self.digests) - seen:
            # A trusted tool vanished; the plan may reference it. Fail closed.
            raise ManifestTrustViolation(
                f"trusted tools disappeared mid-episode: {set(self.digests) - seen}"
            )


def resolve_for_episode(registry, episode_token: ManifestTrustToken) -> list[dict]:
    """Resolve tools, then enforce the episode-start trust token on every read."""
    manifests = registry.fetch_all()
    episode_token.verify(manifests)  # raises ManifestTrustViolation on any drift
    return manifests


def begin_episode(registry) -> tuple[ManifestTrustToken, list[dict]]:
    token = ManifestTrustToken()
    manifests = registry.fetch_all()
    token.mint(manifests)  # trust granted here, once, over full bytes
    return token, manifests
