# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-effects-that-leaked-through-a-shared-tool-side-channel-before-merge-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-effects-that-leaked-through-a-shared-tool-side-channel-before-merge-commit.warrant.json
# Markdown SHA-256:   ca547c5aa7ab40679efbe53e0db246d3a58e75d95f881dfee525f37426b4c644
# Code AST SHA-256:   877f8ccf20fd68f60cffcf0d94655db1a0810c298e0d6b44237e7450365ff55d
# Verified Classes:   SpeculativeLeakError, ToolClass, ToolSpec, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class SpeculativeLeakError(RuntimeError):
    """Raised when a discarded branch's effects escaped the overlay boundary."""
    pass


class ToolClass(Enum):
    OVERLAY_CONFINED = "overlay_confined"      # safe: discardable overlay
    DEFERRABLE = "deferrable"                  # journaled, replayed on commit
    ESCAPING = "escaping"                      # touches shared mutable state


@dataclass
class ToolSpec:
    name: str
    cls: ToolClass
    has_inverse: bool = False
    branch_stable_key: bool = False  # idempotency key derived from intent, not branch


@dataclass
class Branch:
    branch_id: str
    declared_effects: set = field(default_factory=set)  # (tool, stable_key)
    observed_effects: set = field(default_factory=set)


def stable_key(node_id: str, target: str) -> str:
    return hashlib.sha256(f"{node_id}:{target}".encode()).hexdigest()


def assert_speculatively_safe(tools: list[ToolSpec]) -> None:
    for t in tools:
        if t.cls is ToolClass.ESCAPING:
            if not (t.has_inverse or t.branch_stable_key):
                raise SpeculativeLeakError(
                    f"tool {t.name!r} escapes the overlay but has neither an "
                    f"inverse nor a branch-stable idempotency key; "
                    f"speculation across it is unsafe"
                )


def reconcile_merge(committed: Branch, discarded: list[Branch]) -> None:
    """Post-merge invariant: environment effects == committed declared effects."""
    leaked = set()
    for b in discarded:
        # any observed effect from a discarded branch that the committed
        # branch did not also declare is a leak, regardless of key stability
        leaked |= b.observed_effects - committed.declared_effects
    if leaked:
        raise SpeculativeLeakError(
            f"merge commit invalid: {len(leaked)} effect(s) leaked from "
            f"discarded branches: {sorted(leaked)}"
        )
    unaccounted = committed.observed_effects - committed.declared_effects
    if unaccounted:
        raise SpeculativeLeakError(
            f"committed branch produced undeclared effects: {sorted(unaccounted)}"
        )
