# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-lossy-compaction-has-silently-dropped-a-load-bearing-fact-from-agent-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-lossy-compaction-has-silently-dropped-a-load-bearing-fact-from-agent-context.warrant.json
# Markdown SHA-256:   965a13ce33da0f4a6e4d53ee06f8331b8d826c606651a2463550ae71dd4426c5
# Code AST SHA-256:   270d868cc4602e626d1ae52a789f97d8624692a06424eca748f2fdbba85cbf01
# Verified Classes:   CompactionFidelityError, Span, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionFidelityError(RuntimeError):
    """Raised when compaction would drop a non-re-derivable, single-occurrence fact."""


@dataclass
class Span:
    text: str
    provenance: str          # "user" | "tool" | "inference" | "peer"
    occurrences: int         # times this fact is restated in surviving context
    has_pointer: bool        # re-fetchable via id/path/handle
    constraint_bearing: bool # negation, bound, id, enum, unit, temporal


@dataclass
class ConstraintLedger:
    pinned: list[str] = field(default_factory=list)

    def pin(self, span: Span) -> None:
        if span.text not in self.pinned:
            self.pinned.append(span.text)

    def inject_head(self, summary: str) -> str:
        return "\n".join(self.pinned) + "\n---\n" + summary


def compact(spans: Iterable[Span], summarizer, ledger: ConstraintLedger) -> str:
    summarizable: list[Span] = []
    for s in spans:
        re_derivable = s.has_pointer or s.occurrences >= 2
        if s.constraint_bearing and not re_derivable:
            # Non-recoverable load-bearing fact: pin, never summarize.
            ledger.pin(s)
            continue
        if s.constraint_bearing and s.provenance == "tool" and not s.has_pointer:
            # Ambiguous provenance/constraint: default to pin.
            ledger.pin(s)
            continue
        summarizable.append(s)

    summary = summarizer([s.text for s in summarizable])

    # Post-compaction invariant check: every pinned constraint must survive
    # verbatim in the injected context, and no summary may fabricate one.
    injected = ledger.inject_head(summary)
    for pinned in ledger.pinned:
        if pinned not in injected:
            raise CompactionFidelityError(
                f"pinned constraint dropped from post-compaction context: {pinned!r}"
            )
    return injected


def verify_no_fabrication(summary: str, ledger: ConstraintLedger) -> None:
    # Detect summarizer hallucination of constraints not in the ledger.
    for token in ("never", "exclude", "only", "must not"):
        if token in summary and not any(token in p for p in ledger.pinned):
            raise CompactionFidelityError(
                f"summary asserts constraint token {token!r} absent from ledger"
            )
