# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-edit-the-working-memory-rewrite-commit-barrier-and-the-policy-consistency-deadlock.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-self-edit-the-working-memory-rewrite-commit-barrier-and-the-policy-consistency-deadlock.warrant.json
# Markdown SHA-256:   643edffa258b62dbc273c6bc8a89c7cd071f89e41628bb54654c002224660b15
# Code AST SHA-256:   0093a8012be825b2aefbb5f8f3f9c474fc38212b1b63bf22c7845ed49b39a87b
# Verified Classes:   UnjustifiableCommitError, Slot, WorkingMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnjustifiableCommitError(RuntimeError):
    """Raised when a self-edit would commit a state whose retained slots
    cannot be justified using only slots present in that same state."""


@dataclass
class Slot:
    name: str
    covers: Optional[frozenset] = None  # declared provenance coverage


@dataclass
class WorkingMemory:
    slots: dict = field(default_factory=dict)
    constraints: list = field(default_factory=list)  # each: (text, source_slot)


MAX_EPOCHS = 2


def check_self_contained(wm: WorkingMemory) -> bool:
    """The invariant: every retained constraint's source must exist in wm,
    and any synthesized slot it cites must declare coverage of the original
    sources. Returns True only if decidable in isolation."""
    for text, source in wm.constraints:
        if source not in wm.slots:
            return False
        slot = wm.slots[source]
        if slot.covers is not None and not slot.covers:
            return False  # synthesized slot with empty coverage: undecidable
    return True


def commit_self_edit(current: WorkingMemory, candidate: WorkingMemory,
                     epoch: int) -> WorkingMemory:
    if epoch > MAX_EPOCHS:
        # Escalation: lossless fallback. Spill raw slots behind opaque handles
        # so provenance survives without keeping full text in context.
        fallback = WorkingMemory(slots=dict(current.slots),
                                 constraints=list(current.constraints))
        for name, slot in list(fallback.slots.items()):
            if slot.covers is None:
                fallback.slots[name] = Slot(name=name,
                                            covers=frozenset({name}))
        if not check_self_contained(fallback):
            raise UnjustifiableCommitError(
                f"lossless fallback also unjustifiable at epoch {epoch}")
        return fallback

    if not check_self_contained(candidate):
        raise UnjustifiableCommitError(
            f"candidate at epoch {epoch} cites slots absent from itself; "
            f"derivation must emit coverage before commit")

    return candidate
