# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-state-when-it-prunes-its-own-context-mid-execution-the-self-edit-commit-barrier-and-the-orphaned-tool-call-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-state-when-it-prunes-its-own-context-mid-execution-the-self-edit-commit-barrier-and-the-orphaned-tool-call-invariant.warrant.json
# Markdown SHA-256:   ea2d7fc0372c0f2361522d20b2c5df0fdd363c596aa0ae1b60754d4ec49767de
# Code AST SHA-256:   aae09047bc21369bb3ce09c767595295c8dfc0c6806e93d61feebb63d9310a5f
# Verified Classes:   SelfEditViolation, Msg, ColdLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SelfEditViolation(RuntimeError):
    """Raised when a self-edit would break the closure/anchor/ledger invariant."""
    pass


@dataclass
class Msg:
    kind: str                      # "tool_call" | "tool_result" | "assistant" | "user"
    call_id: Optional[str] = None
    content: str = ""
    is_anchor: bool = False        # referenced by an unexecuted step


@dataclass
class ColdLedger:
    store: dict = field(default_factory=dict)

    def spill(self, call_id: str, payload: str) -> None:
        self.store[call_id] = payload

    def reacquire(self, call_id: str) -> str:
        if call_id not in self.store:
            raise SelfEditViolation(f"reacquire({call_id}) missed: ledger dropped")
        return self.store[call_id]


def validate_self_edit(window: list[Msg], span: slice, ledger: ColdLedger) -> None:
    """Enforce the commit barrier before a lossy self-edit commits."""
    edited = window[span]

    calls = {m.call_id for m in edited if m.kind == "tool_call"}
    results = {m.call_id for m in edited if m.kind == "tool_result"}

    # Invariant 1: never split a call/result pair across the edit boundary.
    for cid in calls ^ results:
        raise SelfEditViolation(
            f"span splits call/result pair for call_id={cid}; "
            f"edit would orphan half the obligation"
        )

    # Invariant 2: no anchor for an unexecuted step may be lossily edited.
    for m in edited:
        if m.is_anchor:
            raise SelfEditViolation(
                f"span contains anchor for unexecuted step (call_id={m.call_id}); "
                f"rewrite losslessly or defer dependent step"
            )

    # Invariant 3: cold ledger must retain every edited call's payload.
    for cid in calls:
        if cid not in ledger.store:
            raise SelfEditViolation(
                f"lossy edit of call_id={cid} without cold-ledger spill; "
                f"edit is unrecoverable within episode"
            )


def commit_prune(window: list[Msg], span: slice, ledger: ColdLedger,
                 summary: str) -> list[Msg]:
    validate_self_edit(window, span, ledger)
    edited = window[span]
    for m in edited:
        if m.kind == "tool_call":
            ledger.spill(m.call_id, m.content)
    stub = Msg(kind="assistant", content=f"[pruned span: {summary}]")
    return window[:span.start] + [stub] + window[span.stop:]
