# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-tool-side-effects-before-branch-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-tool-side-effects-before-branch-reconciliation.warrant.json
# Markdown SHA-256:   bd35684e608febe956cd7c0fbb32cd9b805bcf90f28ad24f4cbfd54db0cdc4f2
# Code AST SHA-256:   3b15db688d441872c680b23494cc8ac98fb4c74ec91c0fa05198e451812766dd
# Verified Classes:   UnsafeSpeculativeCommit, StalePrecondition, WriteIntent, CommitLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

"""Speculative branch commit guard.

Enforces the invariant: no speculative branch may commit an externally
observable side effect unless the effect is branch-scoped or guarded by a
precondition that the commit phase re-validates.
"""

from dataclasses import dataclass, field
from typing import Optional


class UnsafeSpeculativeCommit(RuntimeError):
    """Raised when a branch attempts an unguarded shared-state mutation."""
    pass


class StalePrecondition(RuntimeError):
    """Raised when a commit-phase precondition no longer matches world state."""
    pass


@dataclass
class WriteIntent:
    branch_id: str
    resource: str
    payload: str
    precondition: Optional[str]  # expected content hash, or None if unguarded
    branch_scoped: bool


@dataclass
class CommitLedger:
    # resource -> list of intents in arrival order
    intents: dict[str, list[WriteIntent]] = field(default_factory=dict)
    world: dict[str, str] = field(default_factory=dict)  # resource -> current content

    def record_speculative(self, intent: WriteIntent) -> None:
        if not intent.branch_scoped and intent.precondition is None:
            raise UnsafeSpeculativeCommit(
                f"branch {intent.branch_id} attempted unguarded write to shared "
                f"resource {intent.resource!r}; serialize or add a precondition"
            )
        self.intents.setdefault(intent.resource, []).append(intent)

    def commit(self, winner_branch: str) -> dict[str, str]:
        applied: dict[str, str] = {}
        for resource, intents in self.intents.items():
            winner = next(
                (i for i in intents if i.branch_id == winner_branch), None
            )
            if winner is None:
                continue
            if not winner.branch_scoped and winner.precondition is not None:
                current = self.world.get(resource)
                if current is not None and _hash(current) != winner.precondition:
                    raise StalePrecondition(
                        f"winner {winner_branch} precondition for {resource!r} "
                        f"is stale; a sibling branch mutated it after drafting"
                    )
            self.world[resource] = winner.payload
            applied[resource] = winner.payload
        return applied


def _hash(s: str) -> str:
    import hashlib
    return hashlib.sha256(s.encode()).hexdigest()


def reconcile(branches: list[str], ledger: CommitLedger, winner: str) -> dict[str, str]:
    if winner not in branches:
        raise UnsafeSpeculativeCommit(f"winner {winner!r} not among forks")
    return ledger.commit(winner)
