# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-context-compaction-fidelity-loss-silently-corrupt-downstream-agent-decisions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-context-compaction-fidelity-loss-silently-corrupt-downstream-agent-decisions.warrant.json
# Markdown SHA-256:   dc30ad6f021935b0c9db39c15a0c848482865f50a59757bc136c304f479871c3
# Code AST SHA-256:   e7541fd2cb820595a142a3a7464332f88d65ca5a93450173f3631343ae34f388
# Verified Classes:   CompactionDecisionDivergenceError, CriticalToken, CompactionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Callable, Iterable


class CompactionDecisionDivergenceError(RuntimeError):
    """Raised when a compaction passes aggregate fidelity but flips the next action."""


DECISION_CRITICAL_KINDS = frozenset(
    {"bound", "negation", "unit", "prior_rejection", "ordering", "disambiguator"}
)


@dataclass
class CriticalToken:
    kind: str
    text: str
    source_span: tuple[int, int]


@dataclass
class CompactionRecord:
    source_context: str
    compacted_context: str
    aggregate_fidelity: float          # e.g. judge faithfulness, 0..1
    retained_critical: list[CriticalToken] = field(default_factory=list)


def extract_critical_tokens(context: str) -> list[CriticalToken]:
    # Placeholder for a real extractor (regex/parser/LLM-with-schema).
    # Must return every bound, negation, unit, prior rejection, ordering
    # constraint, and identity disambiguator present in `context`.
    raise NotImplementedError("wire to your decision-critical extractor")


def replay_next_action(
    context: str, policy: Callable[[str], Any]
) -> Any:
    return policy(context)


def assert_decision_preserved(
    record: CompactionRecord,
    policy: Callable[[str], Any],
    required_critical: Iterable[CriticalToken],
    fidelity_floor: float = 0.85,
) -> None:
    """
    Gate a compaction before the agent continues.

    Aggregate fidelity is necessary but NOT sufficient. The compaction must
    also (a) retain every decision-critical token and (b) replay to the same
    next action as the pre-compaction context.
    """
    if record.aggregate_fidelity < fidelity_floor:
        raise CompactionDecisionDivergenceError(
            f"aggregate fidelity {record.aggregate_fidelity:.3f} below floor "
            f"{fidelity_floor:.3f}; compaction rejected"
        )

    retained = {(t.kind, t.text) for t in record.retained_critical}
    dropped = [
        t for t in required_critical
        if t.kind in DECISION_CRITICAL_KINDS and (t.kind, t.text) not in retained
    ]
    if dropped:
        raise CompactionDecisionDivergenceError(
            "decision-critical tokens dropped by compaction despite passing "
            f"aggregate fidelity ({record.aggregate_fidelity:.3f}): "
            + "; ".join(f"{t.kind}:{t.text!r}" for t in dropped)
        )

    pre_action = replay_next_action(record.source_context, policy)
    post_action = replay_next_action(record.compacted_context, policy)
    if pre_action != post_action:
        raise CompactionDecisionDivergenceError(
            "next-action divergence after compaction: "
            f"pre={pre_action!r} post={post_action!r} "
            f"(aggregate fidelity was {record.aggregate_fidelity:.3f})"
        )
