# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-truncate-into-a-coherent-but-false-working-memory-the-compaction-commit-boundary-in-self-editing-context-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-truncate-into-a-coherent-but-false-working-memory-the-compaction-commit-boundary-in-self-editing-context-agents.warrant.json
# Markdown SHA-256:   758e7d6465fa767b3076a412de249eccb8d099a9dec3ec19c7567855ae89158c
# Code AST SHA-256:   e7bb5fb6fe7d675308a3061b23024c68d2bf6d0ce0606f230742eebcb926f86f
# Verified Classes:   CompactionCommitError, WorkingMemory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionCommitError(RuntimeError):
    """Raised when a lossy rewrite is about to be promoted to authoritative state
    without a passing load-bearing-span preservation audit."""
    pass


@dataclass
class WorkingMemory:
    # Load-bearing spans: identifiers, constraints, deadlines, open-call keys.
    spans: dict[str, str] = field(default_factory=dict)
    # Narrative/derived text that may be lossily reduced.
    narrative: list[str] = field(default_factory=list)


def audit_preservation(pre: WorkingMemory, candidate_text: str) -> list[str]:
    """Return load-bearing spans missing or paraphrased in the candidate."""
    violations = []
    for key, value in pre.spans.items():
        if value not in candidate_text:
            violations.append(key)
    return violations


def commit_rewrite(
    pre: WorkingMemory,
    candidate_text: str,
    budget_utilization: float,
    provenance_ref: str | None,
) -> WorkingMemory:
    # Below headroom: rewriting is gratuitous loss. Refuse.
    if budget_utilization < 0.50:
        raise CompactionCommitError(
            f"rewrite refused at {budget_utilization:.0%} utilization: "
            f"no budget pressure justifies loss"
        )

    # Audit MUST run against the pre-rewrite buffer, before eviction.
    violations = audit_preservation(pre, candidate_text)
    if violations:
        raise CompactionCommitError(
            f"load-bearing spans lost or paraphrased across rewrite: {violations}; "
            f"spill pre-rewrite buffer to {provenance_ref!r} before retrying"
        )

    # Audit must be affordable; if we cannot verify, we cannot commit.
    if provenance_ref is None:
        raise CompactionCommitError(
            "no provenance reference for pre-rewrite buffer; "
            "commit is unverifiable and therefore unsafe"
        )

    # Only now does the candidate become authoritative.
    return WorkingMemory(spans=dict(pre.spans), narrative=[candidate_text])


def run_turn(memory: WorkingMemory, new_text: str, utilization: float) -> WorkingMemory:
    candidate = new_text  # produced by summarizer under budget pressure
    return commit_rewrite(
        pre=memory,
        candidate_text=candidate,
        budget_utilization=utilization,
        provenance_ref="spill://wm/pre-rewrite",
    )
