# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-whose-verifier-passes-on-a-re-derived-artifact-rather-than-the-artifact-actually-produced.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-whose-verifier-passes-on-a-re-derived-artifact-rather-than-the-artifact-actually-produced.warrant.json
# Markdown SHA-256:   8b3accc986ba3b0f927504366988249f80b4c74e9aa9bb2715aaf7abd4b70503
# Code AST SHA-256:   7e864fb3f8847811d73e4edf2390552b512b465d819156b178fee1a318ac226a
# Verified Classes:   ArtifactHashMismatch, Verdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ArtifactHashMismatch(RuntimeError):
    """Raised when the artifact being committed is not the one the verifier approved."""


@dataclass(frozen=True)
class Verdict:
    branch_id: str
    approved: bool
    verified_artifact_sha256: str  # hash of the exact bytes the verifier saw


def commit_branch(verdict: Verdict, emitted_artifact: bytes, normalize_version: str) -> None:
    if not verdict.approved:
        raise ArtifactHashMismatch(
            f"branch {verdict.branch_id}: verifier did not approve; refusing commit"
        )

    emitted_sha = hashlib.sha256(emitted_artifact).hexdigest()

    if emitted_sha != verdict.verified_artifact_sha256:
        # The verifier validated a re-derived sibling, not this artifact.
        # Do NOT commit. Re-verify against emitted bytes or discard the branch.
        raise ArtifactHashMismatch(
            f"branch {verdict.branch_id}: verified={verdict.verified_artifact_sha256[:12]} "
            f"emitted={emitted_sha[:12]} normalizer={normalize_version}; "
            f"commit refused — artifact drift between verification and commit"
        )

    # Safe: the bytes the verifier judged are the bytes being written.
    _write_durable(verdict.branch_id, emitted_artifact)


def _write_durable(branch_id: str, artifact: bytes) -> None:
    # placeholder for checkpoint/store write
    ...
