# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-anchor-coverage-invariant-and-the-silent-falsification-of-retrieval-anchored-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-auto-compact-the-anchor-coverage-invariant-and-the-silent-falsification-of-retrieval-anchored-reconstruction.warrant.json
# Markdown SHA-256:   6afb956bcc06fa522cfdfc068d128de4642d4fdbf214035fcafe31635b2cfaab
# Code AST SHA-256:   7b3f517c65eb8ffe812413470a7c637f50fd6ed3524ce78c2344da49307e6d34
# Verified Classes:   CompactionFalsificationError, Span, CompactionPlan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionFalsificationError(RuntimeError):
    """Raised when auto-compaction would drop a span whose loss the
    retrieval layer cannot soundly reconstruct (supersession or
    relative-anchor origin). Refusal is mandatory; silent compaction
    here produces confident-but-wrong reconstruction downstream."""


@dataclass
class Span:
    step: int
    text: str
    kind: str          # "assertion" | "retraction" | "relative_ref" | "tool_output" | "dead_end"
    entity: str | None = None
    supersedes: int | None = None   # step this span corrects, if any


@dataclass
class CompactionPlan:
    retained: list[Span] = field(default_factory=list)
    dropped: list[Span] = field(default_factory=list)
    anchors: dict[str, int] = field(default_factory=dict)  # key -> step


def gate_compaction(plan: CompactionPlan, generation: int) -> CompactionPlan:
    # 1. Supersession blind spot: any dropped retraction whose target
    #    assertion is also dropped (or whose anchor keys on the entity,
    #    not the proposition) is unreconstructable.
    dropped_steps = {s.step for s in plan.dropped}
    for span in plan.dropped:
        if span.kind == "retraction":
            raise CompactionFalsificationError(
                f"step {span.step}: dropping a retraction of step "
                f"{span.supersedes}; anchor would resolve to the "
                f"superseded assertion. Externalize verbatim instead."
            )
        if span.supersedes is not None and span.supersedes in dropped_steps:
            raise CompactionFalsificationError(
                f"step {span.step}: supersedes dropped step {span.supersedes} "
                f"but is itself dropped; correction is lost while the "
                f"original remains indexed. Retain both or neither."
            )

    # 2. Relative-anchor origin collapse: a relative ref is only safe to
    #    drop if its origin step is retained.
    retained_steps = {s.step for s in plan.retained}
    for span in plan.dropped:
        if span.kind == "relative_ref":
            origin = span.supersedes  # reuse field: origin step
            if origin is not None and origin not in retained_steps:
                raise CompactionFalsificationError(
                    f"step {span.step}: relative reference '{span.text}' "
                    f"drops its origin (step {origin}); post-compaction "
                    f"the delta will be recomputed against the wrong "
                    f"clock. Rewrite to absolute form before dropping."
                )

    # 3. Query reachability: every anchored entity must appear in the
    #    post-compaction summary vocabulary, else the anchor is orphaned.
    summary_vocab = {tok.lower() for s in plan.retained for tok in s.text.split()}
    for key, step in plan.anchors.items():
        if key.lower() not in summary_vocab:
            raise CompactionFalsificationError(
                f"anchor '{key}' (step {step}) is orphaned: its key does "
                f"not appear in the retained summary, so the agent cannot "
                f"generate a query that reaches it. Drop the anchor or "
                f"retain the key."
            )

    # 4. Generation guard: re-summarizing a summary must re-validate
    #    against the original transcript, not the prior summary.
    if generation > 1:
        raise CompactionFalsificationError(
            f"generation {generation}: re-compaction of a prior summary "
            f"amplifies the supersession blind spot. Re-validate anchors "
            f"against the original transcript before proceeding."
        )

    return plan
