# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-plan-branch-divergence-from-leaking-into-committed-agent-state.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-plan-branch-divergence-from-leaking-into-committed-agent-state.warrant.json
# Markdown SHA-256:   ccb1b602e73456ac649863193a9d685abc99de4f3a723d35ae7007421a1ba598
# Code AST SHA-256:   ded047c32558e9d123790f8a2c3fab40c3935e3ecde29a8986c70f54dab88dc3
# Verified Classes:   SpeculationLeakError, Effect, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class SpeculationLeakError(RuntimeError):
    """Raised when a committed branch's replay inputs diverge from its verified inputs,
    indicating a sibling speculative write leaked into the commit path."""


@dataclass(frozen=True)
class Effect:
    key: str
    value: str


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect]
    verified_input_digest: str | None = None
    approved: bool = False


def _digest(effects: list[Effect]) -> str:
    h = hashlib.sha256()
    for e in sorted(effects, key=lambda x: x.key):
        h.update(f"{e.key}={e.value};".encode())
    return h.hexdigest()


def verify(branch: Branch, branch_scoped_store: dict[str, dict[str, str]]) -> None:
    """Verifier reads ONLY the branch-scoped namespace. Pins the input digest."""
    scope = branch_scoped_store.get(branch.branch_id, {})
    resolved = [Effect(k, scope.get(k, "")) for k in (e.key for e in branch.effects)]
    branch.verified_input_digest = _digest(resolved)
    branch.approved = True


def commit(
    branch: Branch,
    branch_scoped_store: dict[str, dict[str, str]],
    committed_store: dict[str, str],
) -> None:
    """Committer recomputes the input digest from the same branch-scoped path and
    aborts on any mismatch with the verification-time digest."""
    if not branch.approved:
        raise SpeculationLeakError(f"branch {branch.branch_id} has no approval")
    scope = branch_scoped_store.get(branch.branch_id, {})
    resolved = [Effect(k, scope.get(k, "")) for k in (e.key for e in branch.effects)]
    commit_digest = _digest(resolved)
    if commit_digest != branch.verified_input_digest:
        raise SpeculationLeakError(
            f"branch {branch.branch_id} input drift: verified "
            f"{branch.verified_input_digest} != commit {commit_digest}; "
            f"a sibling speculative write leaked into the commit path"
        )
    for e in branch.effects:
        committed_store[e.key] = e.value


def run_swarm() -> None:
    # Branch-scoped namespaces: B2's write to S.key cannot shadow B1's.
    scoped: dict[str, dict[str, str]] = {
        "B1": {"S.key": "v1"},
        "B2": {"S.key": "v2"},
    }
    committed: dict[str, str] = {}

    b1 = Branch("B1", [Effect("S.key", "v1"), Effect("S.cfg", "cfgA")])
    b2 = Branch("B2", [Effect("S.key", "v2"), Effect("S.cfg", "cfgB")])

    verify(b1, scoped)
    verify(b2, scoped)
    b2.approved = False  # genuine tool-configuration mismatch on B2

    commit(b1, scoped, committed)  # passes: B1 sees only B1's namespace

    # Simulate the leak: a sibling write lands in B1's scope after verification.
    scoped["B1"]["S.key"] = "v2"
    try:
        commit(b1, scoped, committed)
    except SpeculationLeakError as exc:
        # Hard abort; do NOT re-verify against drifted inputs.
        raise SpeculationLeakError(
            "aborting swarm: rejected sibling write reached commit input path"
        ) from exc


if __name__ == "__main__":
    run_swarm()
