# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-auto-compaction-is-about-to-evict-task-critical-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-auto-compaction-is-about-to-evict-task-critical-state.warrant.json
# Markdown SHA-256:   74bca3fe0d7aae5f36d8e2ce022057db45f357473daeed117e56060a579c9fad
# Code AST SHA-256:   aa2366f3b9e34c56ba3dbfde6f2094bdc5d76cc1fe327aef2c17e1f225678010
# Verified Classes:   CompactionInvariantError, Region
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass, field


class CompactionInvariantError(RuntimeError):
    """Raised when a compaction pass would silently evict live task state."""
    pass


@dataclass
class Region:
    text: str
    # identifiers introduced exactly once in the session so far
    single_occurrence_ids: set[str] = field(default_factory=set)

    def live_constraints(self) -> list[str]:
        # negative/limit constraints are load-bearing and paraphrase-fragile
        pat = re.compile(
            r"\b(do not|don't|must not|never|must stay|budget is|limit is|"
            r"under \d+|at most|no more than)\b",
            re.IGNORECASE,
        )
        return [m.group(0) for m in pat.finditer(self.text)]

    def dangling_anaphora(self) -> list[str]:
        # references that point to an antecedent inside this region
        pat = re.compile(r"\b(it|that file|the same|this config|the above)\b",
                         re.IGNORECASE)
        return [m.group(0) for m in pat.finditer(self.text)]


def guard_compaction(region: Region, pinned: set[str]) -> None:
    """Fail closed if compaction would drop unpinned live state."""
    unpinned_constraints = [c for c in region.live_constraints()
                            if c.lower() not in {p.lower() for p in pinned}]
    unpinned_ids = region.single_occurrence_ids - pinned
    dangling = region.dangling_anaphora()

    if unpinned_constraints or unpinned_ids or dangling:
        raise CompactionInvariantError(
            "refusing to compact: would evict live state "
            f"constraints={unpinned_constraints} "
            f"ids={sorted(unpinned_ids)} "
            f"dangling={dangling}"
        )


def compact(region: Region, pinned: set[str]) -> str:
    guard_compaction(region, pinned)  # fail closed before summarizing
    # ... summarize region.text, with pinned spans re-inserted verbatim ...
    return region.text
