# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-self-prune-its-own-context-window-into-a-hallucinated-summary-of-its-own-past-actions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-self-prune-its-own-context-window-into-a-hallucinated-summary-of-its-own-past-actions.warrant.json
# Markdown SHA-256:   424c4b6db35ddaaafa990365f6b783f71bf35dd3c1fc8d2adbce5804d3f8aa10
# Code AST SHA-256:   8bf9550ce5e85d020af28f150df739de9522297c212821306eef5583b628ef44
# Verified Classes:   LedgerMismatchError, ClaimKind, LedgerEntry, NarrativeClaim, SelfEditingContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class LedgerMismatchError(RuntimeError):
    """Raised when a narrative claim cannot be reconciled with the evidence ledger."""
    pass


class ClaimKind(Enum):
    NARRATIVE = "narrative"      # safe to summarize/evict
    COMPLETED_STATE = "completed_state"  # must resolve to ledger evidence


@dataclass
class LedgerEntry:
    turn: int
    tool: str
    path: str
    result: str          # verbatim, never paraphrased


@dataclass
class NarrativeClaim:
    text: str
    kind: ClaimKind
    evidence_ref: Optional[int] = None  # ledger turn id, required if COMPLETED_STATE


@dataclass
class SelfEditingContext:
    ledger: dict[int, LedgerEntry] = field(default_factory=dict)
    narrative: list[NarrativeClaim] = field(default_factory=list)

    def record_evidence(self, entry: LedgerEntry) -> None:
        # Append-only. Never scored, never summarized, never evicted.
        self.ledger[entry.turn] = entry

    def add_claim(self, claim: NarrativeClaim) -> None:
        if claim.kind is ClaimKind.COMPLETED_STATE and claim.evidence_ref is None:
            raise LedgerMismatchError(
                f"completed-state claim {claim.text!r} has no evidence_ref; "
                "refusing to admit an unverifiable assertion into memory"
            )
        self.narrative.append(claim)

    def compact(self, relevance_scores: dict[int, float]) -> None:
        """Evict low-relevance NARRATIVE claims only. Evidence is untouchable."""
        keep = []
        for i, claim in enumerate(self.narrative):
            if claim.kind is ClaimKind.COMPLETED_STATE:
                keep.append(claim)  # never evicted by relevance
            elif relevance_scores.get(i, 1.0) >= 0.3:
                keep.append(claim)
        self.narrative = keep

    def verify_before_action(self, claim_text: str) -> LedgerEntry:
        for claim in self.narrative:
            if claim.text == claim_text and claim.kind is ClaimKind.COMPLETED_STATE:
                entry = self.ledger.get(claim.evidence_ref)
                if entry is None:
                    raise LedgerMismatchError(
                        f"claim {claim_text!r} references missing ledger entry "
                        f"{claim.evidence_ref}"
                    )
                # The claim is only actionable if the recorded outcome is success.
                if "Error" in entry.result or "exit 0" not in entry.result:
                    raise LedgerMismatchError(
                        f"claim {claim_text!r} asserts completion, but ledger "
                        f"turn {entry.turn} records {entry.result!r}"
                    )
                return entry
        raise LedgerMismatchError(f"no resolvable completed-state claim: {claim_text!r}")


# Failure trace reproduced under the guardrail:
ctx = SelfEditingContext()
ctx.record_evidence(LedgerEntry(31, "edit", "db/migrate_0042.py", "PermissionError"))
ctx.add_claim(NarrativeClaim("migration script updated", ClaimKind.COMPLETED_STATE, 31))
ctx.compact(relevance_scores={})  # eviction attempts cannot touch the claim
ctx.verify_before_action("migration script updated")  # raises LedgerMismatchError
