# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-self-editing-context-windows-that-prune-their-own-audit-trail-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-self-editing-context-windows-that-prune-their-own-audit-trail-mid-task.warrant.json
# Markdown SHA-256:   3185b529b00947695d44a41018ab8620d95d7de8a59faf80e0039a1a57f79048
# Code AST SHA-256:   088bcd307b04af632dcb072bd3fd96d0b7ab27fa1da77b14a5d59cdefc45617d
# Verified Classes:   AuditRegionExhausted, UnauditablePrune, LossRecord, SelfEditingWindow
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class AuditRegionExhausted(RuntimeError):
    """Raised when pruning would consume the reserved audit region."""
    pass

class UnauditablePrune(RuntimeError):
    """Raised when a prune/rewrite would remove the last record of a superseded goal state or a cited evidence span."""
    pass

@dataclass
class LossRecord:
    removed_hash: str
    goal_state_hash: str
    score: float
    kind: str  # "prune" | "rewrite"

@dataclass
class SelfEditingWindow:
    tokens: list = field(default_factory=list)          # (id, text, goal_hash)
    audit: list = field(default_factory=list)           # append-only LossRecord
    cited_spans: set = field(default_factory=set)
    audit_capacity: int = 64
    max_prune_ratio: float = 0.40
    pruned_since_checkpoint: int = 0
    total_at_checkpoint: int = 0

    def _hash(self, s: str) -> str:
        return hashlib.sha256(s.encode()).hexdigest()[:16]

    def prune(self, token_id: str, current_goal_hash: str) -> None:
        tok = next((t for t in self.tokens if t[0] == token_id), None)
        if tok is None:
            return
        # Boundary 1: never prune the sole record of a superseded goal state.
        superseded = [t for t in self.tokens if t[2] != current_goal_hash]
        if tok[2] != current_goal_hash and len(superseded) == 1:
            raise UnauditablePrune(
                f"refusing to prune {token_id}: sole record of superseded goal {tok[2]}"
            )
        # Boundary 2: never prune a span cited by an open claim.
        if token_id in self.cited_spans:
            raise UnauditablePrune(f"refusing to prune cited evidence span {token_id}")
        # Boundary 3: audit region is append-only and finite.
        if len(self.audit) >= self.audit_capacity:
            raise AuditRegionExhausted(
                "audit region full; halt pruning and checkpoint, do not prune the log"
            )
        # Boundary 4: cumulative prune ratio guard.
        if self.total_at_checkpoint and (
            self.pruned_since_checkpoint / self.total_at_checkpoint > self.max_prune_ratio
        ):
            raise UnauditablePrune(
                "cumulative prune ratio exceeded; checkpoint required before further edits"
            )
        self.audit.append(
            LossRecord(self._hash(tok[1]), current_goal_hash, 0.0, "prune")
        )
        self.tokens.remove(tok)
        self.pruned_since_checkpoint += 1

    def replay_contradictions(self, claim_hash: str) -> list:
        """Verification hook: does any loss record contradict the open claim?"""
        return [r for r in self.audit if r.removed_hash == claim_hash]
