# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-fidelity-score-is-computed-against-the-post-compaction-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-fidelity-score-is-computed-against-the-post-compaction-state.warrant.json
# Markdown SHA-256:   6cad18ea5a799bf0cc916c14abbc357bf1e8added26d5a941b59f1b7d8e994e4
# Code AST SHA-256:   451f9800384cc03993ac15cda6f84ddc92d84c4dea2241e4e7cb5186817985d7
# Verified Classes:   CompactionFidelityError, EvictedSpan, CompactionAttempt
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction commit would release evicted state without
    a valid pre-release obligation check, or when obligations are missing."""
    pass


@dataclass
class EvictedSpan:
    raw: str
    tool_ledger: list[str] = field(default_factory=list)
    reasoning_notes: list[str] = field(default_factory=list)

    def extract_obligations(self) -> set[str]:
        # Negative obligations and pinned identifiers are the load-bearing,
        # easily-dropped facts. Extract mechanically, not via summarizer.
        obligations: set[str] = set()
        for note in self.reasoning_notes:
            for m in re.finditer(r"do not ([a-z_]+) on ([a-z_.]+)", note, re.I):
                obligations.add(f"NEG:{m.group(1).lower()}:{m.group(2).lower()}")
            for m in re.finditer(r"\b([a-z_]+/[a-z0-9_]+\.sql)\b", note, re.I):
                obligations.add(f"PIN:{m.group(1).lower()}")
        return obligations


@dataclass
class CompactionAttempt:
    evicted: Optional[EvictedSpan]          # None if already released
    summary: str
    tail: str
    global_score: float                     # LLM-judge over (S, T)


def commit_compaction(attempt: CompactionAttempt, threshold: float = 0.80) -> None:
    # Invariant: score is valid only if computed before E is released.
    if attempt.evicted is None:
        raise CompactionFidelityError(
            "fidelity gate ran post-release: evicted span not addressable; "
            "score is coherence-only and cannot detect obligation loss. "
            "Restore from last durable checkpoint and re-compact."
        )

    obligations = attempt.evicted.extract_obligations()
    haystack = (attempt.summary + "\n" + attempt.tail).lower()

    missing = {
        ob for ob in obligations
        if ob.split(":", 1)[1].replace(":", " ") not in haystack
        and ob.split(":", 1)[1] not in haystack
    }

    if missing:
        raise CompactionFidelityError(
            f"obligation loss on compaction: {sorted(missing)} absent from "
            f"summary+tail (global_score={attempt.global_score:.2f}). "
            f"Hard fail regardless of score; roll back to pre-compaction state."
        )

    if attempt.global_score < threshold:
        raise CompactionFidelityError(
            f"narrative fidelity {attempt.global_score:.2f} below {threshold}; "
            f"re-summarize with obligations pinned."
        )
    # Commit is safe: obligations covered and E was addressable at score time.
