# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-self-editing-context-policies-as-a-checkpointable-transaction-rather-than-a-lossy-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-self-editing-context-policies-as-a-checkpointable-transaction-rather-than-a-lossy-rewrite.warrant.json
# Markdown SHA-256:   22c9d9394510efad2f97d0b3614fa9a1f1a6468210e08baeaea6957fce61805e
# Code AST SHA-256:   011a55227f8d2a5d8a466e6175c327d5fdbfcdf4790ccc0322efdda249145ac5
# Verified Classes:   UnauditableSelfEditError, DroppedConstraintError, WorkingMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class UnauditableSelfEditError(RuntimeError):
    """Raised when a self-edit would commit without a retained oracle or validation pass."""
    pass


class DroppedConstraintError(UnauditableSelfEditError):
    """Raised when validation finds a load-bearing fact missing from the post-edit state."""
    pass


@dataclass
class WorkingMemory:
    transcript: str
    pinned_facts: list = field(default_factory=list)  # negative/modal facts, non-compressible
    committed_state: dict = field(default_factory=dict)  # value -> derivation

    def digest(self) -> str:
        return hashlib.sha256(
            (self.transcript + repr(sorted(self.pinned_facts)) + repr(sorted(self.committed_state.items()))).encode()
        ).hexdigest()


def self_edit(memory: WorkingMemory, compress_fn, budget: int, retain_oracle: bool) -> WorkingMemory:
    if len(memory.transcript) <= budget:
        return memory  # below the band, no choice forced, trivially safe

    # C1: refuse to edit without a retained oracle
    if not retain_oracle:
        raise UnauditableSelfEditError(
            "self-edit under binding budget requires a retained pre-edit oracle; "
            "lossy in-place rewrite is not permitted for this task class"
        )

    pre_digest = memory.digest()
    pre_pinned = set(memory.pinned_facts)
    pre_derivations = dict(memory.committed_state)

    # compress, but never touch pinned facts or committed derivations
    compressed = compress_fn(memory.transcript, budget, pinned=memory.pinned_facts)
    candidate = WorkingMemory(
        transcript=compressed,
        pinned_facts=list(memory.pinned_facts),
        committed_state=dict(memory.committed_state),
    )

    # C4: validate against oracle before commit
    missing_pinned = pre_pinned - set(candidate.pinned_facts)
    if missing_pinned:
        raise DroppedConstraintError(
            f"post-edit state dropped non-compressible facts: {sorted(missing_pinned)}; "
            f"pre-edit digest {pre_digest[:12]}"
        )
    for value, derivation in pre_derivations.items():
        if value not in candidate.committed_state or candidate.committed_state[value] != derivation:
            raise DroppedConstraintError(
                f"committed state {value!r} lost its derivation under compression; "
                "pin without justification is not committable"
            )

    # commit only after validation passes
    return candidate
