# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-of-its-own-transcript-as-a-lossy-non-invertible-state-transition-rather-than-a-cache-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-of-its-own-transcript-as-a-lossy-non-invertible-state-transition-rather-than-a-cache-eviction.warrant.json
# Markdown SHA-256:   27d418c9e933a945fbbd6c0ff8def4eb7fcfc6ea72394d66322b76eec1f2a1c6
# Code AST SHA-256:   4fe435410bb4700c581f72ea13b74d061f77ab1457f47146d49c94fa9c882d93
# Verified Classes:   CompactionSafetyError, ElementClass, TranscriptElement, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionSafetyError(RuntimeError):
    """Raised when auto-compaction would drop an unrecoverable constraint."""


class ElementClass(Enum):
    NARRATIVE = "narrative"          # summarizable
    PROHIBITION = "prohibition"      # must pin verbatim
    NEGATIVE_RESULT = "negative"     # must pin verbatim
    OPEN_ASSERTION = "open"          # must pin verbatim


@dataclass
class TranscriptElement:
    text: str
    kind: ElementClass
    provenance: str  # "user" | "model" | "tool:untrusted" | ...


@dataclass
class CompactionResult:
    summary: str
    pinned_residue: list[TranscriptElement] = field(default_factory=list)


PROHIBITION_MARKERS = ("never", "must not", "do not", "pending", "before")


def classify(element: TranscriptElement) -> ElementClass:
    low = element.text.lower()
    if any(m in low for m in PROHIBITION_MARKERS):
        return ElementClass.PROHIBITION
    if "failed" in low or "invalid" in low or "timed out" in low:
        return ElementClass.NEGATIVE_RESULT
    return ElementClass.NARRATIVE


def compact(elements: list[TranscriptElement],
            pinned_carryover: list[TranscriptElement],
            budget_tokens: int,
            summarize_fn) -> CompactionResult:
    narrative, pinned = [], list(pinned_carryover)
    for el in elements:
        kind = classify(el)
        if kind is ElementClass.NARRATIVE:
            narrative.append(el)
        else:
            pinned.append(TranscriptElement(el.text, kind, el.provenance))

    # Barrier: pinned residue must survive verbatim. If it cannot fit,
    # we must halt rather than summarize a constraint.
    pinned_tokens = sum(len(p.text.split()) for p in pinned)
    if pinned_tokens > budget_tokens:
        raise CompactionSafetyError(
            f"Pinned residue ({pinned_tokens} tok) exceeds budget "
            f"({budget_tokens} tok); refusing to summarize constraints. "
            f"Checkpoint and halt instead."
        )

    # Only narrative may be lossily summarized.
    summary = summarize_fn([n.text for n in narrative])
    return CompactionResult(summary=summary, pinned_residue=pinned)


def guard_action(action: str, residue: list[TranscriptElement]) -> None:
    """Detect post-compaction divergence before executing a mutating action."""
    for p in residue:
        if p.kind is ElementClass.PROHIBITION:
            for marker in PROHIBITION_MARKERS:
                if marker in p.text.lower():
                    forbidden = p.text.split(marker, 1)[1].strip(" .;:")
                    if forbidden and forbidden in action:
                        raise CompactionSafetyError(
                            f"Action {action!r} violates pinned prohibition "
                            f"from {p.provenance}: {p.text!r}"
                        )
