# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-context-compaction-fidelity-collapse-in-long-horizon-agent-tasks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-context-compaction-fidelity-collapse-in-long-horizon-agent-tasks.warrant.json
# Markdown SHA-256:   b930872733494ff4e64cd9adcecbe70f5eb2c0273765f44fb46430bf3000f21a
# Code AST SHA-256:   0068bf3a462ce6515818a41ae32122c89281fa1a7b58604ccd8f8f68e417bc5e
# Verified Classes:   CompactionFidelityError, Commitment, CommitmentLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction boundary separates a minted commitment
    from a consumer that still needs it (forward-sufficiency violation)."""
    pass


@dataclass
class Commitment:
    kind: Literal["minted_id", "decision", "negative_constraint"]
    value: str
    minted_at_step: int
    consumed_by: set[int] = field(default_factory=set)


class CommitmentLedger:
    """Append-only, compaction-immune store of load-bearing facts."""

    def __init__(self) -> None:
        self._entries: list[Commitment] = []

    def mint(self, kind: str, value: str, step: int) -> None:
        self._entries.append(Commitment(kind=kind, value=value, minted_at_step=step))

    def register_consumer(self, value: str, step: int) -> None:
        for e in self._entries:
            if e.value == value:
                e.consumed_by.add(step)
                return
        # A consumer referencing an unknown value is itself a signal:
        # the agent is about to reconstruct/re-mint it.
        raise CompactionFidelityError(
            f"consumer at step {step} references unminted value {value!r}"
        )

    def open_commitments(self) -> list[Commitment]:
        return [e for e in self._entries if e.consumed_by]

    def assert_compaction_safe(self, evict_before_step: int, now_step: int) -> None:
        """Call before evicting any span ending before `evict_before_step`.
        Fails if a minted value would be evicted while a future consumer
        still lies beyond the retained window."""
        for e in self._entries:
            minted_in_evict = e.minted_at_step < evict_before_step
            live_consumer = any(c >= now_step for c in e.consumed_by)
            if minted_in_evict and live_consumer:
                raise CompactionFidelityError(
                    f"evicting step<{evict_before_step} would drop "
                    f"{e.kind} {e.value!r} minted at {e.minted_at_step} "
                    f"with live consumers {sorted(e.consumed_by)}"
                )

    def forward_probe(self, retained_text: str) -> None:
        """Post-compaction gate: every open commitment must be reproducible
        from retained context alone. Judge scores on the evicted span are
        irrelevant to this check."""
        for e in self.open_commitments():
            if e.value not in retained_text:
                raise CompactionFidelityError(
                    f"forward-sufficiency failure: open {e.kind} {e.value!r} "
                    f"absent from retained context after compaction"
                )
