# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-compaction-as-a-lossy-checkpoint-with-a-declared-fidelity-budget-rather-than-a-transparent-memory-opt.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-compaction-as-a-lossy-checkpoint-with-a-declared-fidelity-budget-rather-than-a-transparent-memory-opt.warrant.json
# Markdown SHA-256:   36ace8b393e2475432a87fb8d56c0d9eebddca314c3c58fcf4eb10a9b2cc8ad2
# Code AST SHA-256:   5e9499f761a9c455978ee537c9539bb3704a6ea49a48d135ab2337daa9546068
# Verified Classes:   RetentionClass, CompactionFidelityError, Span, CompactionManifest
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RetentionClass(Enum):
    COMMITMENT = "commitment"      # verbatim, never summarized
    DERIVATION = "derivation"      # payload droppable, call replayable
    NARRATIVE = "narrative"        # freely summarizable


class CompactionFidelityError(RuntimeError):
    """Raised when compaction or rehydration would violate the declared fidelity budget."""
    pass


@dataclass
class Span:
    span_id: str
    retention: RetentionClass
    verbatim: str | None = None
    replay_handle: str | None = None   # tool-call signature for DERIVATION
    summary: str | None = None         # only for NARRATIVE


@dataclass
class CompactionManifest:
    commitment_cap: int
    spans: dict[str, Span] = field(default_factory=dict)
    obligations: set[str] = field(default_factory=set)  # span_ids referenced by active plan

    def classify(self, span: Span) -> None:
        # A span referenced by an active plan node may never be demoted below commitment.
        if span.span_id in self.obligations and span.retention is not RetentionClass.COMMITMENT:
            raise CompactionFidelityError(
                f"span {span.span_id} is plan-referenced but classified "
                f"{span.retention.value}; demotion would create an unrecoverable obligation"
            )
        self.spans[span.span_id] = span

    def admit_commitment(self, span: Span) -> None:
        current = sum(1 for s in self.spans.values()
                      if s.retention is RetentionClass.COMMITMENT)
        if current + 1 > self.commitment_cap:
            # Correct behavior: refuse compaction, escalate. Never summarize commitments.
            raise CompactionFidelityError(
                f"commitment budget {self.commitment_cap} exhausted; "
                f"refusing to compact span {span.span_id} — escalate to external spill"
            )
        self.classify(span)


def rehydrate(manifest: CompactionManifest, span_id: str, purpose: str) -> str:
    span = manifest.spans.get(span_id)
    if span is None:
        raise CompactionFidelityError(f"rehydration miss: span {span_id} absent from manifest")

    if span.retention is RetentionClass.COMMITMENT:
        assert span.verbatim is not None
        return span.verbatim

    if span.retention is RetentionClass.DERIVATION:
        if span.replay_handle is None:
            raise CompactionFidelityError(
                f"derivation span {span_id} has no replay handle; "
                f"payload was dropped without a recovery path"
            )
        # Caller must replay the tool call; we refuse to return a cached payload.
        raise CompactionFidelityError(
            f"derivation span {span_id} requires replay via {span.replay_handle}, "
            f"not trust — do not act on un-replayed derivation"
        )

    # NARRATIVE: only admissible if the span is NOT plan-referenced.
    if span_id in manifest.obligations:
        raise CompactionFidelityError(
            f"classification violation: rehydration query '{purpose}' hit narrative "
            f"span {span_id} that is plan-referenced; halt rather than confabulate"
        )
    assert span.summary is not None
    return span.summary


def compact(manifest: CompactionManifest, span: Span) -> None:
    if span.retention is RetentionClass.COMMITMENT:
        manifest.admit_commitment(span)
    else:
        manifest.classify(span)
