# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-inflicted-context-loss-when-its-own-pruning-policy-deletes-the-evidence-it-needs-to-notice-the-loss.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-inflicted-context-loss-when-its-own-pruning-policy-deletes-the-evidence-it-needs-to-notice-the-loss.warrant.json
# Markdown SHA-256:   43de350cb1c0eb8b76c289a8f5917439f5e443d876aa375cee532f90189865ba
# Code AST SHA-256:   cd93424f6bcd1f961027eb1bd466547c03d2765ae50eeab806cac05717558ef7
# Verified Classes:   ContextLossUndetected, ContextUnit, Witness, SelfPruningWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
import re


class ContextLossUndetected(RuntimeError):
    """Raised when a self-pruning agent cannot prove it retains a witness for an evicted identity-bearing unit."""
    pass


@dataclass
class ContextUnit:
    unit_id: str
    text: str
    identity_fields: dict = field(default_factory=dict)


@dataclass
class Witness:
    evicted_unit_id: str
    identity_fields: dict
    recover_handle: str


IDENTITY_PATTERNS = {
    "holder_id": re.compile(r"holder[ _]?id[=: ]+([0-9a-fA-F]+)"),
    "http_code": re.compile(r"\b(4[0-9]{2}|5[0-9]{2})\b"),
    "resource": re.compile(r"resource[=: ]+([A-Za-z0-9_\-]+)"),
}


def extract_identity(text: str) -> dict:
    found = {}
    for name, pat in IDENTITY_PATTERNS.items():
        m = pat.search(text)
        if m:
            found[name] = m.group(1)
    return found


class SelfPruningWindow:
    def __init__(self, max_tokens: int = 32000):
        self.max_tokens = max_tokens
        self.units: dict[str, ContextUnit] = {}
        self.witnesses: list[Witness] = []
        self.pinned: set[str] = set()

    def add(self, unit: ContextUnit) -> None:
        unit.identity_fields = extract_identity(unit.text)
        self.units[unit.unit_id] = unit
        if unit.identity_fields:
            self.pinned.add(unit.unit_id)

    def compact(self, scorer) -> None:
        # scorer: callable(unit) -> float, the model-driven relevance function.
        # Pinned units are never passed to the scorer; only unpinned are prunable.
        for uid in list(self.units):
            if uid in self.pinned:
                continue
            if scorer(self.units[uid]) < 0.2:
                unit = self.units.pop(uid)
                self.witnesses.append(
                    Witness(
                        evicted_unit_id=unit.unit_id,
                        identity_fields=unit.identity_fields,
                        recover_handle=f"store://{unit.unit_id}",
                    )
                )

    def detect_recurrence(self, incoming: ContextUnit) -> Optional[Witness]:
        for w in self.witnesses:
            if incoming.identity_fields and all(
                incoming.identity_fields.get(k) == v
                for k, v in w.identity_fields.items()
                if k in incoming.identity_fields
            ):
                return w
        return None

    def assert_witness_coverage(self) -> None:
        # Invariant: every evicted unit with identity fields MUST have a witness.
        # If this fails, the instance has pruned evidence of its own pruning.
        witnessed = {w.evicted_unit_id for w in self.witnesses}
        for uid, unit in self.units.items():
            if unit.identity_fields and uid not in witnessed and uid not in self.pinned:
                raise ContextLossUndetected(
                    f"unit {uid} carries identity {unit.identity_fields} "
                    f"but has no witness and is not pinned; "
                    f"self-pruning has made loss undetectable"
                )
        if len(self.witnesses) > 64:
            raise ContextLossUndetected(
                "witness store overflow: unresolved recurrence loop, escalate"
            )


def run_compaction_cycle(window: SelfPruningWindow, incoming: ContextUnit, scorer) -> None:
    window.add(incoming)
    hit = window.detect_recurrence(incoming)
    if hit is not None:
        # Recurrence detected before the loop can restart; halt for escalation.
        raise ContextLossUndetected(
            f"recurrence of {hit.identity_fields} from evicted unit "
            f"{hit.evicted_unit_id}; refusing to re-plan as fresh work"
        )
    window.compact(scorer)
    window.assert_witness_coverage()
