# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-rollback-divergence-when-speculative-sibling-agents-share-a-mutable-external-world.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-rollback-divergence-when-speculative-sibling-agents-share-a-mutable-external-world.warrant.json
# Markdown SHA-256:   0f4e801d720426bca4636623df20953031d694c23cb805afa24a24e56fcb11d1
# Code AST SHA-256:   70adb8d03422abbaa475766518216deee86183c3d6d2b6bc052e0cc5b558f5d9
# Verified Classes:   UnreconciledEffectError, EffectManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconciledEffectError(RuntimeError):
    """Raised when a divergent branch's external effects cannot be attributed
    or inverted, so the fork cannot safely advance to a sibling branch."""
    pass


READ_ONLY = "read_only"
INVERTIBLE = "invertible_write"
OPAQUE = "opaque_write"


class EffectManifest:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.effects: list[dict] = []  # {"tool", "resource", "class", "inverse"}

    def record(self, tool: str, resource: str, effect_class: str, inverse=None):
        self.effects.append(
            {"tool": tool, "resource": resource,
             "class": effect_class, "inverse": inverse}
        )

    def opaque_effects(self) -> list[dict]:
        return [e for e in self.effects if e["class"] == OPAQUE]

    def touched_resources(self) -> set[str]:
        return {e["resource"] for e in self.effects}


def reconcile_divergent_branch(manifest: EffectManifest, world) -> None:
    """Invert an invertible effect set; refuse to proceed on any opaque effect.

    The invariant: a fork may advance only if every divergent branch's effect
    set is empty or fully inverted. An opaque effect is not a warning; it is a
    hard stop, because the orchestrator cannot prove the world was restored.
    """
    opaque = manifest.opaque_effects()
    if opaque:
        raise UnreconciledEffectError(
            f"branch {manifest.branch_id} left {len(opaque)} opaque effect(s) "
            f"on {sorted({e['resource'] for e in opaque})}; "
            f"fork cannot advance, restore pre-fork snapshot"
        )
    for effect in reversed(manifest.effects):
        if effect["class"] == INVERTIBLE and effect["inverse"] is not None:
            world.apply(effect["inverse"])


def guard_sibling_read(manifest: EffectManifest, resource: str,
                       prior_divergent: list[EffectManifest]) -> None:
    """Reject a read that touches a resource written by a divergent sibling.

    Read-your-sibling's-writes is the contamination vector: a committed branch
    that reads a dead branch's partial write inherits it silently.
    """
    for dead in prior_divergent:
        if resource in dead.touched_resources():
            raise UnreconciledEffectError(
                f"branch {manifest.branch_id} read {resource!r}, which was "
                f"written by divergent branch {dead.branch_id}; "
                f"restart from pre-fork snapshot"
            )
