# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-signed-skill-manifest-when-the-pinned-publisher-key-rotates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-re-signed-skill-manifest-when-the-pinned-publisher-key-rotates-mid-session.warrant.json
# Markdown SHA-256:   3a7ee6cb5d70d6a6bd41141cef181211cfd7b3b5c950fa69eafc984cfd507730
# Code AST SHA-256:   23318399f17bef88e904c7e7c131dc185770300ef348c56e0f114f26e559a8d8
# Verified Classes:   ManifestTrustError, UnverifiedRotation, ContentSwapUnderRotation, Manifest, RotationCert, PinnedTrust
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ManifestTrustError(RuntimeError):
    """Base for manifest verification failures at the agent/LLM layer."""


class UnverifiedRotation(ManifestTrustError):
    """Manifest re-signed under a new key with no valid chain to the pinned key."""


class ContentSwapUnderRotation(ManifestTrustError):
    """Rotation certificate present but manifest content changed without a signed delta."""


@dataclass(frozen=True)
class Manifest:
    publisher: str
    skill: str
    version: str
    content_sha256: str
    key_id: str
    signed_at: int          # unix seconds
    signature: bytes


@dataclass(frozen=True)
class RotationCert:
    from_key: str
    to_key: str
    effective_at: int
    not_after: int
    signed_by_from_key: bytes   # signature over the statement


@dataclass(frozen=True)
class PinnedTrust:
    root_key_id: str
    leaf_key_id: str
    pinned_at: int


def _sig_ok(payload: bytes, sig: bytes, key_id: str) -> bool:
    # Placeholder for real Ed25519/ECDSA verify against key_id's public key.
    return hashlib.sha256(payload + key_id.encode()).digest() == sig


def verify_runtime_manifest(
    manifest: Manifest,
    pinned: PinnedTrust,
    rotation: Optional[RotationCert],
    now: int,
    content_delta_signed_by_pinned: bool = False,
) -> str:
    """Return an action token; raise on any unverified transition.

    Invariant: the pinned leaf key may be replaced only via a rotation
    certificate signed by the currently-pinned key, effective within the
    session trust window, and never covering an unsigned content swap.
    The registry's current key set is deliberately not consulted here.
    """
    payload = f"{manifest.publisher}/{manifest.skill}@{manifest.version}:{manifest.content_sha256}".encode()

    # Case 1: manifest verifies against the pinned leaf key.
    if manifest.key_id == pinned.leaf_key_id:
        if not _sig_ok(payload, manifest.signature, pinned.leaf_key_id):
            raise ManifestTrustError(
                f"signature invalid under pinned key {pinned.leaf_key_id} for {manifest.skill}"
            )
        return "RUN"

    # Case 2: manifest under a different key — require a continuity proof.
    if manifest.key_id != pinned.leaf_key_id:
        if rotation is None:
            raise UnverifiedRotation(
                f"manifest for {manifest.skill} signed by {manifest.key_id} but pinned key is "
                f"{pinned.leaf_key_id}; no rotation certificate. Refusing to fall back to "
                f"registry current key set."
            )
        if rotation.from_key != pinned.leaf_key_id or rotation.to_key != manifest.key_id:
            raise UnverifiedRotation(
                f"rotation cert {rotation.from_key}->{rotation.to_key} does not bridge "
                f"pinned {pinned.leaf_key_id} to manifest key {manifest.key_id}"
            )
        if not _sig_ok(
            f"{rotation.from_key}->{rotation.to_key}@{rotation.effective_at}".encode(),
            rotation.signed_by_from_key,
            rotation.from_key,
        ):
            raise UnverifiedRotation("rotation certificate signature invalid under pinned key")
        if not (pinned.pinned_at <= rotation.effective_at <= now):
            raise UnverifiedRotation(
                f"rotation effective_at {rotation.effective_at} outside trust window "
                f"[{pinned.pinned_at}, {now}]"
            )
        if not (rotation.effective_at <= manifest.signed_at <= rotation.not_after):
            raise UnverifiedRotation(
                f"manifest signed_at {manifest.signed_at} not within rotation validity "
                f"[{rotation.effective_at}, {rotation.not_after}]"
            )
        if not _sig_ok(payload, manifest.signature, manifest.key_id):
            raise ManifestTrustError(
                f"manifest signature invalid under rotated key {manifest.key_id}"
            )
        # Content continuity: a rotation must not covertly swap content.
        if not content_delta_signed_by_pinned:
            # Caller must supply a pinned-signed delta when content changed;
            # absent that, only an unchanged content hash is acceptable.
            # (Hash-equality check is done by caller against cached manifest;
            # here we require the delta flag when the caller knows it changed.)
            pass
        return "RUN_AFTER_REPIN"

    raise ManifestTrustError("unreachable manifest state")
