# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-forged-skill-provenance-chain-when-the-registering-agent-re-signs-its-own-manifest-after-a-partial-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-forged-skill-provenance-chain-when-the-registering-agent-re-signs-its-own-manifest-after-a-partial-rollback.warrant.json
# Markdown SHA-256:   5d2ff79ef61533e6196bf3307dd661471e5ad8473b3d146ac43f3f97f5aa9f8c
# Code AST SHA-256:   a234b73f386bb5554b2f7ae28a1b354d9df415fbc728e184767b5dc193d75d3e
# Verified Classes:   ProvenanceBreak, Chain
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceBreak(RuntimeError):
    """Raised when a manifest hash diverges from the attested chain without an origin extension."""
    pass


@dataclass
class Chain:
    skill_id: str
    manifest_hash: str          # hash the origin warrant actually attested
    origin_extension_hashes: frozenset  # hashes the origin has co-signed


def _h(body: bytes) -> str:
    return hashlib.sha256(body).hexdigest()


def verify_registration(
    chain: Chain,
    stored_body: bytes,
    incoming_body: bytes,
    agent_signature_valid: bool,
    origin_extension_valid: bool,
) -> str:
    """Enforce: manifest-hash change requires origin-signed extension, and rollback desync is fatal."""
    stored_hash = _h(stored_body)
    incoming_hash = _h(incoming_body)

    # Rollback / snapshot-divergence guard: body store must agree with the chain.
    if stored_hash != chain.manifest_hash:
        raise ProvenanceBreak(
            f"registry desync for {chain.skill_id}: stored={stored_hash[:12]} "
            f"chain={chain.manifest_hash[:12]}; refusing all registrations until reconciled"
        )

    if not agent_signature_valid:
        raise ProvenanceBreak(f"invalid agent signature for {chain.skill_id}")

    # Idempotent path: same bytes, already attested.
    if incoming_hash == chain.manifest_hash:
        return "idempotent"

    # Hash changed: only an origin-signed extension may authorize new bytes.
    if incoming_hash in chain.origin_extension_hashes and origin_extension_valid:
        return "extended"

    # Agent signed new bytes but origin never attested them -> forged provenance.
    raise ProvenanceBreak(
        f"provenance break for {chain.skill_id}: agent re-signed {incoming_hash[:12]} "
        f"but origin attested {chain.manifest_hash[:12]} with no extension"
    )
