# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-lose-task-state-when-it-rewrites-its-own-working-memory-under-a-token-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-lose-task-state-when-it-rewrites-its-own-working-memory-under-a-token-budget.warrant.json
# Markdown SHA-256:   ca8b4cb03c44732bdff4132e06ba001c8fb6f6bd8970c7354240ca33781237bb
# Code AST SHA-256:   c1106be8e70c1ee8b32e1ea8f90bd9c558fd7a1cd28c692fee51056acc7dfad2
# Verified Classes:   UnattestedMemoryError, BudgetViolationError, Residue, SideLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class UnattestedMemoryError(RuntimeError):
    """Raised when a downstream step tries to act on a memory entry
    that has no residue record in the side ledger (i.e., it was
    rewritten without provenance, or the residue was itself rewritten)."""
    pass


class BudgetViolationError(RuntimeError):
    """Raised when a consolidation pass would exceed the token budget
    once residue accounting is included."""
    pass


@dataclass
class Residue:
    source_span_hash: str
    source_tokens: int
    summary_tokens: int
    provenance_retained: tuple
    provenance_dropped: tuple


@dataclass
class SideLedger:
    """Non-rewritable residue store. The self-editing policy may append
    here but may never summarize or evict from it."""
    entries: dict = field(default_factory=dict)

    def record(self, entry_id: str, residue: Residue) -> None:
        self.entries[entry_id] = residue

    def resolve(self, entry_id: str) -> Optional[Residue]:
        return self.entries.get(entry_id)


NO_REWRITE_CLASSES = {"path", "id", "hash", "numeric_literal", "negative_observation"}


def consolidate(
    span_id: str,
    span_tokens: int,
    span_classes: set,
    summary_text: str,
    summary_tokens: int,
    budget_remaining: int,
    ledger: SideLedger,
) -> str:
    """Rewrite a span into a summary, but only if it is safe to do so.

    Returns the summary text on success. Raises if the span contains
    no-rewrite classes, or if residue accounting would blow the budget.
    """
    forbidden = span_classes & NO_REWRITE_CLASSES
    if forbidden:
        # Do not paraphrase identifiers or negative observations.
        # Evict-with-tombstone instead; caller must re-derive.
        raise UnattestedMemoryError(
            f"span {span_id} contains no-rewrite classes {sorted(forbidden)}; "
            f"refusing to summarize. Evict-with-tombstone and re-derive."
        )

    residue_cost = 40  # tokens to record a residue entry
    net_saving = (span_tokens - summary_tokens) - residue_cost
    if net_saving <= 0 or net_saving > budget_remaining:
        raise BudgetViolationError(
            f"consolidation of {span_id} is not a net budget win "
            f"(span={span_tokens}, summary={summary_tokens}, "
            f"residue={residue_cost}, remaining={budget_remaining})"
        )

    ledger.record(
        span_id,
        Residue(
            source_span_hash=hashlib.sha256(summary_text.encode()).hexdigest()[:16],
            source_tokens=span_tokens,
            summary_tokens=summary_tokens,
            provenance_retained=tuple(span_classes - NO_REWRITE_CLASSES),
            provenance_dropped=tuple(forbidden),
        ),
    )
    return summary_text


def act_on_memory(entry_id: str, ledger: SideLedger, action: str) -> None:
    """Any verificational or mutational step must resolve its input to a
    residue record before acting. If it cannot, it must re-derive."""
    residue = ledger.resolve(entry_id)
    if residue is None:
        raise UnattestedMemoryError(
            f"cannot {action} on memory entry {entry_id}: no residue record. "
            f"This entry was rewritten without provenance or its residue was "
            f"itself summarized. Re-derive from a tool call before acting."
        )
    # proceed with action, carrying residue.source_span_hash as attestation
