# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-registry-sourced-skill-manifests-from-silently-mutating-an-agent-s-tool-call-authorization-surface-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-registry-sourced-skill-manifests-from-silently-mutating-an-agent-s-tool-call-authorization-surface-mid-session.warrant.json
# Markdown SHA-256:   ec6ca498cefc957c6e8280ce20d6cc5eb61255d166e89542bcae5e618dba11eb
# Code AST SHA-256:   d2300fc680aa86c7437d8e7bb037d232ead0d1d1f4c17b59547028b611b43720
# Verified Classes:   ManifestDriftError, AuthorizationRecord, SkillRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, Optional


class ManifestDriftError(RuntimeError):
    """Raised when a registry refresh mutates a prompt-visible manifest field
    under a name that was already authorized, without re-authorization."""
    pass


PROMPT_VISIBLE_FIELDS = ("name", "description", "schema", "declared_side_effects")


def manifest_hash(entry: dict) -> str:
    payload = {k: entry.get(k) for k in PROMPT_VISIBLE_FIELDS}
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class AuthorizationRecord:
    name: str
    authorized_hash: str


@dataclass
class SkillRegistry:
    authorized: Dict[str, AuthorizationRecord] = field(default_factory=dict)
    quarantined: Dict[str, str] = field(default_factory=dict)

    def authorize(self, entry: dict) -> None:
        """First-time admission. Binds trust to the full manifest hash."""
        self.authorized[entry["name"]] = AuthorizationRecord(
            name=entry["name"], authorized_hash=manifest_hash(entry)
        )

    def refresh(self, entry: dict, reauthorized: bool = False) -> dict:
        """Re-resolve a registry entry. Returns the entry only if it is safe to
        place in the model's tool block this turn."""
        name = entry["name"]
        new_hash = manifest_hash(entry)

        if name not in self.authorized:
            # Unknown skill: must be explicitly authorized before use.
            raise ManifestDriftError(
                f"skill {name!r} refreshed but never authorized; refusing to load"
            )

        record = self.authorized[name]
        if new_hash == record.authorized_hash:
            self.quarantined.pop(name, None)
            return entry

        # Drift detected on a prompt-visible field.
        if reauthorized:
            record.authorized_hash = new_hash
            self.quarantined.pop(name, None)
            return entry

        self.quarantined[name] = (
            f"manifest_drift: {name} {record.authorized_hash[:8]} -> "
            f"{new_hash[:8]} (prompt-visible field changed, schema may be identical)"
        )
        raise ManifestDriftError(
            f"skill {name!r} manifest drifted; quarantined pending re-authorization. "
            f"details={self.quarantined[name]}"
        )

    def callable_set(self, entries: list) -> list:
        """Build the per-turn tool block, excluding quarantined entries."""
        safe = []
        for entry in entries:
            try:
                safe.append(self.refresh(entry))
            except ManifestDriftError:
                # Entry stays out of the callable set for this turn.
                continue
        return safe


def load_turn_tools(registry: SkillRegistry, fetched: list) -> list:
    """Entry point used by the agent loop each turn."""
    tools = registry.callable_set(fetched)
    if not tools:
        raise ManifestDriftError(
            "all fetched skills quarantined or unauthorized; "
            "agent has no callable tools this turn"
        )
    return tools
