# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-lose-task-critical-facts-when-auto-compaction-summarizes-its-own-transcript-mid-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-lose-task-critical-facts-when-auto-compaction-summarizes-its-own-transcript-mid-horizon.warrant.json
# Markdown SHA-256:   1d8317890b58cc1ee3792daae1f46b6635136cb1077f0f03c9c48a9bf3359726
# Code AST SHA-256:   f5444e34850a0ac04d1b84d63bbb5fd5fb0eacd9018f187bc193b9c30da95b1f
# Verified Classes:   CompactionFidelityError, Span, PinnedStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction pass would drop a provenance-bearing literal
    or negative result without a pinned copy, violating the fidelity invariant."""


@dataclass
class Span:
    text: str
    literals: list[str] = field(default_factory=list)      # IDs, keys, versions, sigs
    negative_results: list[str] = field(default_factory=list)  # "did X, got Y, don't repeat"
    re_derivable: bool = False


@dataclass
class PinnedStore:
    pinned: dict[str, str] = field(default_factory=dict)

    def pin(self, key: str, value: str) -> None:
        self.pinned[key] = value

    def has(self, key: str) -> bool:
        return key in self.pinned


def compact(spans: list[Span], store: PinnedStore) -> str:
    """Compact spans, refusing to summarize any span whose literals or negative
    results are not already pinned. Returns the summary-safe residue only."""
    residue: list[str] = []
    for i, span in enumerate(spans):
        critical = span.literals or span.negative_results
        if critical and not span.re_derivable:
            for lit in critical:
                if not store.has(lit):
                    raise CompactionFidelityError(
                        f"span {i} carries unpinned critical literal "
                        f"{lit!r}; refusing to summarize (source would be lost)"
                    )
        if span.re_derivable or not critical:
            residue.append(span.text)
    return " ".join(residue)


def run_compaction(spans: list[Span], store: PinnedStore) -> str:
    try:
        return compact(spans, store)
    except CompactionFidelityError as e:
        # Correct recovery is deferral + external spill, never "summarize anyway".
        raise CompactionFidelityError(
            f"compaction deferred; spill raw span to external store and retry: {e}"
        ) from e


# Example trigger: step-6 schema response and step-19 negative result unpinned.
spans = [
    Span(text="Retrieved schema; v3 in use.",
         literals=["schema_version=v3", "key_id=k-8842", "signing=hmac-sha256"]),
    Span(text="Hit a conflict; handled it.",
         negative_results=["idem-7f3a returns cached 409 for 10 min; do not reuse"]),
]
store = PinnedStore()
run_compaction(spans, store)  # raises CompactionFidelityError
