# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-compaction-as-a-lossy-state-transition-rather-than-a-cache-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-context-compaction-as-a-lossy-state-transition-rather-than-a-cache-eviction.warrant.json
# Markdown SHA-256:   f75488f05b1013b3fb9c8f4528f0a828982ac33792a935875f03fdda817ed50f
# Code AST SHA-256:   b3a37263102d14c8d51132081d1c70edc2f62ea7adec435f5704ea7a9a6e1a5a
# Verified Classes:   CompactionCueLossError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionCueLossError(RuntimeError):
    """Raised when a compaction summary drops a fact without preserving a retrieval anchor."""
    pass


CONSEQUENTIAL_MARKERS = ("flag", "error_code", "decision", "rationale", "retry")


def validate_compaction(evicted_span: str, summary: str, summary_budget: int) -> dict:
    """Enforce cue-preservation invariant before admitting a compaction event."""
    anchors = [
        tok for tok in evicted_span.split()
        if any(m in tok.lower() for m in CONSEQUENTIAL_MARKERS) or "_" in tok
    ]
    missing = [a for a in anchors if a not in summary]
    used = len(summary.split())

    if missing and used < summary_budget * 0.9:
        return {"action": "regenerate", "missing_anchors": missing}
    if missing:
        raise CompactionCueLossError(
            f"budget {used}/{summary_budget} cannot preserve anchors {missing}; "
            "refusing compaction, spill raw span to retrieval with anchor manifest"
        )
    return {"action": "admit", "missing_anchors": []}


def compact(evicted_span: str, draft_summary: str, budget: int, prior_degraded: bool) -> str:
    if prior_degraded:
        raise CompactionCueLossError(
            "chained compaction on degraded span forbidden; re-summarize from raw retrieval"
        )
    result = validate_compaction(evicted_span, draft_summary, budget)
    if result["action"] == "regenerate":
        raise CompactionCueLossError(
            f"summary must be regenerated to embed anchors {result['missing_anchors']}"
        )
    return draft_summary
