# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-history-under-a-lossy-summarizer-without-a-fidelity-floor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-history-under-a-lossy-summarizer-without-a-fidelity-floor.warrant.json
# Markdown SHA-256:   c38525dfb8505552ab2d8fdd19e9a18971ee87981965d03076fce818456c465c
# Code AST SHA-256:   5a9dc319076ea648670879925992f0204123297db317f18c63507275fbe27bb7
# Verified Classes:   CompactionFidelityError, Obligation, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionFidelityError(RuntimeError):
    """Raised when a summary fails to preserve an extracted live obligation."""
    pass


@dataclass(frozen=True)
class Obligation:
    kind: str          # "constraint" | "identifier" | "pending_intent" | "negation"
    payload: str       # verbatim text or ID that must survive compaction

    def resolve(self, durable_state: Iterable[str]) -> bool:
        # Valid if the obligation appears verbatim in the post-compaction
        # context OR is resolvable via a durable artifact the agent can re-read.
        return self.payload in durable_state


@dataclass
class CompactionResult:
    summary: str
    obligations: list[Obligation] = field(default_factory=list)


def compact_with_fidelity_floor(
    discarded_span: str,
    summarize_fn,
    durable_state: Iterable[str],
    max_retries: int = 2,
) -> CompactionResult:
    # 1. Extract obligations structurally BEFORE the probabilistic pass.
    obligations = extract_obligations(discarded_span)
    durable = list(durable_state)

    for attempt in range(max_retries + 1):
        summary = summarize_fn(discarded_span, attempt=attempt)
        post_context = durable + [summary]

        unresolved = [
            ob for ob in obligations
            if not ob.resolve(post_context)
        ]
        if not unresolved:
            return CompactionResult(summary=summary, obligations=obligations)

        # A summary that merely mentions the topic is not fidelity.
        # Reject and retry with a larger retained window.
        if attempt == max_retries:
            raise CompactionFidelityError(
                f"Compaction rejected after {max_retries + 1} attempts: "
                f"{len(unresolved)} obligation(s) lost or inverted, e.g. "
                f"{unresolved[0].kind}={unresolved[0].payload!r}. "
                f"Refusing to accept a lossy summary as ground truth."
            )

    # unreachable, but keeps the contract explicit
    raise CompactionFidelityError("compaction loop exited without resolution")


def extract_obligations(span: str) -> list[Obligation]:
    # Structural pass: IDs, imperatives/negations, dangling tool intents.
    # Deterministic; runs on raw tokens, not on model output.
    obs: list[Obligation] = []
    for token in span.split():
        if token.startswith("TCK-") or token.startswith("INC-"):
            obs.append(Obligation(kind="identifier", payload=token))
    for phrase in ("do not", "must not", "frozen", "read-only"):
        if phrase in span.lower():
            obs.append(Obligation(kind="constraint", payload=phrase))
    # pending intents are supplied by the tool-call ledger, not parsed here
    return obs
