# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-manifest-provenance-signature-as-non-transferable-across-skill-re-registration.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-manifest-provenance-signature-as-non-transferable-across-skill-re-registration.warrant.json
# Markdown SHA-256:   477ac1606c54a04e3440582369a3bd3bb87009d1205e3beb278cc9a7ef768c7d
# Code AST SHA-256:   943b36b27ddf36c8753385308c781adbb2cf879677735fb46b1ec1b4609d8ea5
# Verified Classes:   ManifestProvenanceError, SignedManifest, RegistrationRequest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Mapping


class ManifestProvenanceError(RuntimeError):
    """Raised when a tool manifest's signature does not bind the exact bytes
    the model will read, at a fresh-enough registration epoch."""


def canonicalize(manifest: Mapping) -> bytes:
    """Single pinned canonicalization. Signer and verifier MUST share this."""
    return json.dumps(
        manifest, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    ).encode("utf-8")


@dataclass(frozen=True)
class SignedManifest:
    tool_id: str
    manifest: Mapping          # includes 'description'
    signature: bytes           # Ed25519 over canonicalize(manifest)
    registration_epoch: int
    payload_hash: str          # H(canonicalize(manifest)) at signing time


@dataclass(frozen=True)
class RegistrationRequest:
    tool_id: str
    manifest: Mapping          # what the registry will actually serve
    claimed_signature: bytes
    claimed_epoch: int


def admit_tool(
    req: RegistrationRequest,
    *,
    trusted_keys: Mapping[str, bytes],
    verify_sig,                       # (pubkey, payload, sig) -> bool
    publisher_key_for: Mapping[str, bytes],
    last_admitted: Mapping[str, SignedManifest],
) -> SignedManifest:
    payload = canonicalize(req.manifest)
    payload_hash = hashlib.sha256(payload).hexdigest()

    pubkey = publisher_key_for.get(req.tool_id)
    if pubkey is None or pubkey not in trusted_keys.values():
        raise ManifestProvenanceError(
            f"no trusted publisher key for tool_id={req.tool_id!r}"
        )

    if not verify_sig(pubkey, payload, req.claimed_signature):
        raise ManifestProvenanceError(
            f"signature does not verify over canonical bytes of {req.tool_id!r}"
        )

    prior = last_admitted.get(req.tool_id)
    if prior is not None:
        if payload_hash == prior.payload_hash:
            # Idempotent re-registration: same bytes, reuse epoch.
            return prior
        if req.claimed_epoch <= prior.registration_epoch:
            # THE LAUNDERING CASE: bytes changed, epoch did not advance.
            raise ManifestProvenanceError(
                f"tool {req.tool_id!r} re-registered with new bytes "
                f"(hash {payload_hash[:12]} != {prior.payload_hash[:12]}) "
                f"at non-advancing epoch {req.claimed_epoch} "
                f"(prior {prior.registration_epoch}); refusing transfer of "
                f"prior signature's trust"
            )

    # Description must be present and byte-identical to what was hashed.
    if "description" not in req.manifest:
        raise ManifestProvenanceError(
            f"manifest for {req.tool_id!r} lacks description; model would "
            f"read unsigned text"
        )

    return SignedManifest(
        tool_id=req.tool_id,
        manifest=dict(req.manifest),
        signature=req.claimed_signature,
        registration_epoch=req.claimed_epoch,
        payload_hash=payload_hash,
    )
