# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-tool-manifest-mid-session-skill-injection-via-manifest-supplied-instructions-and-the-signed-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-loaded-tool-manifest-mid-session-skill-injection-via-manifest-supplied-instructions-and-the-signed-registry.warrant.json
# Markdown SHA-256:   0546d5d0fd99bb871e7025ef3ebeb6d150d6adca0d641d09c10ebb04150a27c3
# Code AST SHA-256:   0f097b21127016427533d36ca135fc5353943ac065380e0c00f3be2503bce60a
# Verified Classes:   SkillManifestRejected, PinnedSkill
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass


class SkillManifestRejected(RuntimeError):
    """Raised when a dynamically loaded manifest fails the signed-registry invariant."""
    pass


@dataclass(frozen=True)
class PinnedSkill:
    publisher_key: bytes
    manifest_hash: str  # hex digest of canonical full manifest, prose included


def canonicalize(manifest: dict) -> bytes:
    # Deterministic serialization: sorted keys, no whitespace drift.
    import json
    return json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()


def verify_manifest_refresh(
    manifest: dict,
    presented_signature: bytes,
    presented_key: bytes,
    pinned: PinnedSkill,
    refresh_turn: int,
) -> None:
    """
    Enforce the invariant: manifest prose may enter context only if the full
    manifest is signed under the pinned publisher key and matches the pinned hash.
    """
    if not hmac.compare_digest(presented_key, pinned.publisher_key):
        raise SkillManifestRejected(
            f"turn {refresh_turn}: signing key does not match pinned publisher key; "
            "key substitution is not a valid refresh path"
        )

    body = canonicalize(manifest)
    actual_hash = hashlib.sha256(body).hexdigest()
    if actual_hash != pinned.manifest_hash:
        raise SkillManifestRejected(
            f"turn {refresh_turn}: full-manifest hash {actual_hash} != pinned "
            f"{pinned.manifest_hash}; instruction-classified text changed mid-session"
        )

    if not hmac.compare_digest(presented_signature, hmac.new(pinned.publisher_key, body, hashlib.sha256).digest()):
        raise SkillManifestRejected(
            f"turn {refresh_turn}: signature does not cover canonical full manifest"
        )


def assemble_tool_context(manifest: dict, verified: bool) -> str:
    """
    Prose fields are data-classified. Even verified prose is quoted, never directive.
    """
    if not verified:
        raise SkillManifestRejected("unverified manifest may not enter context")
    prose = manifest.get("when_to_use", "")
    return f'[publisher_claim] "{prose}" [end_claim]'
