# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-and-the-rewrite-is-not-idempotent-self-editing-compaction-corruption-via-lossy-summariza.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-working-memory-and-the-rewrite-is-not-idempotent-self-editing-compaction-corruption-via-lossy-summariza.warrant.json
# Markdown SHA-256:   dcf43131d30035c796b3d454f427952ffa59b466596376244e889cfe02752ae8
# Code AST SHA-256:   3e03b1e27d824a401d47b2b38deae7704020f653fd9e0e54972f63f7d39744e4
# Verified Classes:   FrameState, CallFrame, WorkingMemory, CompactionCorruptionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class FrameState(Enum):
    PENDING = "PENDING"
    RESOLVED = "RESOLVED"
    ABANDONED = "ABANDONED"


@dataclass
class CallFrame:
    call_id: str
    state: FrameState
    tombstone: bool = False  # set when abandoned; keeps call_id matchable


@dataclass
class WorkingMemory:
    frames: dict[str, CallFrame] = field(default_factory=dict)
    obligations: list[str] = field(default_factory=list)


class CompactionCorruptionError(RuntimeError):
    """Raised when a self-edit would orphan a live obligation or open frame."""


def validate_self_edit(
    memory: WorkingMemory,
    span_frame_ids: list[str],
    summary_carried_obligations: list[str],
) -> None:
    """
    Enforce the three conditions before committing a substitutive edit.
    Raises CompactionCorruptionError if any condition is violated.
    """
    # Condition 1: frame closure -- no PENDING frames inside the span.
    for fid in span_frame_ids:
        frame = memory.frames.get(fid)
        if frame is None:
            raise CompactionCorruptionError(
                f"span references unknown frame {fid!r}"
            )
        if frame.state is FrameState.PENDING:
            raise CompactionCorruptionError(
                f"span cuts through open frame {fid!r}; shrink span to "
                f"frame-closed prefix or abandon-with-tombstone first"
            )

    # Condition 2 + 3: obligation sufficiency -- every obligation the span
    # carries must be echoed by the summary, else the edit is lossy.
    span_set = set(span_frame_ids)
    carried = [
        ob for ob in memory.obligations
        if any(fid in ob for fid in span_set)
    ]
    missing = [ob for ob in carried if ob not in summary_carried_obligations]
    if missing:
        raise CompactionCorruptionError(
            f"summary dropped carried obligations {missing!r}; "
            f"roll back the self-edit"
        )


def bind_late_result(memory: WorkingMemory, call_id: str, ok: bool) -> str:
    """
    Bind a tool result to its originating frame. If the frame was compacted
    away without a tombstone, the result is orphaned -- the exact failure
    this article describes.
    """
    frame = memory.frames.get(call_id)
    if frame is None:
        raise CompactionCorruptionError(
            f"late result for {call_id!r} has no frame and no tombstone; "
            f"a prior self-edit deleted the binding slot"
        )
    if frame.state is FrameState.ABANDONED:
        if not frame.tombstone:
            raise CompactionCorruptionError(
                f"abandoned frame {call_id!r} lacks tombstone; late result "
                f"would be silently dropped"
            )
        return f"late_result_for_abandoned_call:{call_id}"
    if frame.state is FrameState.RESOLVED:
        raise CompactionCorruptionError(
            f"double-bind on {call_id!r}; result frame replayed"
        )
    frame.state = FrameState.RESOLVED
    return f"bound:{call_id}:ok={ok}"
