# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-orphaning-retrieval-fallback-anchors-in-long-horizon-agent-context.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-auto-compaction-from-silently-orphaning-retrieval-fallback-anchors-in-long-horizon-agent-context.warrant.json
# Markdown SHA-256:   5d7d4231032a90eb47392e4e1cec71716f7e1eadc553cf134da6a009c3410601
# Code AST SHA-256:   4c6342577f12b8d44fa5d3de516f291c0cdbfda07ba010f5044397327774ec73
# Verified Classes:   AnchorOrphaningError, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class AnchorOrphaningError(RuntimeError):
    """Raised when a lossy summary drops an anchor-class token that the
    retrieval fallback depends on, making the evicted span unreachable
    by any query the agent can construct from the summary."""


ANCHOR_CLASS_PATTERNS = (
    "resource_id",   # e.g. proj-7f3a-queue-eu-west
    "exact_numeric", # e.g. 1800, 0.75
    "symbol",        # function/field/error-code names
)


@dataclass
class CompactionResult:
    summary: str
    anchors: list[str] = field(default_factory=list)
    evicted_span_id: str = ""


def extract_anchors(original_span: str, span_id: str) -> list[str]:
    # Real implementation tokenizes and classifies; stub returns declared anchors.
    return _declared_anchors.get(span_id, [])


_declared_anchors: dict[str, list[str]] = {}


def validate_compaction(result: CompactionResult) -> None:
    required = extract_anchors(original_span=result.summary, span_id=result.evicted_span_id)
    missing = [a for a in required if a not in result.anchors and a not in result.summary]
    if missing:
        raise AnchorOrphaningError(
            f"compaction of span {result.evicted_span_id!r} dropped anchor-class "
            f"tokens {missing!r}; retrieval fallback would be unreachable. "
            f"Retain span verbatim instead of committing lossy summary."
        )


def build_fallback_query(result: CompactionResult) -> str:
    if not result.anchors:
        raise AnchorOrphaningError(
            f"span {result.evicted_span_id!r} has no anchors; refusing to build a "
            f"fallback query from summary prose, which cannot match the index."
        )
    return " ".join(result.anchors)


def compact_and_commit(original_span: str, span_id: str, summarizer) -> CompactionResult:
    summary, anchors = summarizer(original_span)
    result = CompactionResult(summary=summary, anchors=anchors, evicted_span_id=span_id)
    validate_compaction(result)  # raises AnchorOrphaningError on any dropped anchor
    return result
