# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-summarization-induced-invariant-loss-when-auto-compaction-rewrites-its-own-transcript.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-summarization-induced-invariant-loss-when-auto-compaction-rewrites-its-own-transcript.warrant.json
# Markdown SHA-256:   416ca97616f3be978de42d29d40c566afd3414ac1447d648fa0ddc26d5b857e7
# Code AST SHA-256:   08f08fed63f3ffd23b69e4548f187bb0050d623ba056bfbe83765dd26efc927f
# Verified Classes:   CompactionInvariantError, Survival, Constraint, StagedCompaction
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionInvariantError(RuntimeError):
    """Raised when a staged compaction would drop an active constraint."""


class Survival(Enum):
    VERBATIM = "verbatim"
    REFERENCE = "reference"
    RESTATED = "restated"
    LOST = "lost"


@dataclass
class Constraint:
    cid: str
    text: str
    source_turn: int
    active: bool = True


@dataclass
class StagedCompaction:
    # turn indices consumed by the summarizer
    compacted_turns: set[int]
    # the candidate post-compaction transcript text
    new_transcript: str
    # constraint ids the compactor explicitly re-asserted or referenced
    referenced_ids: set[str] = field(default_factory=set)


def audit_compaction(
    constraints: list[Constraint],
    staged: StagedCompaction,
) -> dict[str, Survival]:
    """Per-constraint survival test. Pure check; does not mutate."""
    results: dict[str, Survival] = {}
    for c in constraints:
        if not c.active or c.source_turn not in staged.compacted_turns:
            continue  # not at risk from this compaction
        if c.text in staged.new_transcript:
            results[c.cid] = Survival.VERBATIM
        elif c.cid in staged.referenced_ids:
            results[c.cid] = Survival.REFERENCE
        elif f"[constraint:{c.cid}]" in staged.new_transcript:
            results[c.cid] = Survival.REFERENCE
        else:
            results[c.cid] = Survival.LOST
    return results


def commit_compaction(
    constraints: list[Constraint],
    staged: StagedCompaction,
    max_repair_attempts: int = 1,
) -> dict[str, Survival]:
    """Guard the transcript swap. Raises if any active constraint is lost."""
    survival = audit_compaction(constraints, staged)
    lost = [cid for cid, s in survival.items() if s is Survival.LOST]

    if lost:
        # Repair path: pin lost constraints as mandatory-retain spans and retry.
        pinned = {c.cid for c in constraints if c.cid in lost}
        repaired = StagedCompaction(
            compacted_turns=staged.compacted_turns,
            new_transcript=(
                staged.new_transcript
                + "\n[retained constraints]\n"
                + "\n".join(
                    f"[constraint:{c.cid}] {c.text}"
                    for c in constraints
                    if c.cid in pinned
                )
            ),
            referenced_ids=staged.referenced_ids | pinned,
        )
        survival = audit_compaction(constraints, repaired)
        still_lost = [cid for cid, s in survival.items() if s is Survival.LOST]
        if still_lost:
            raise CompactionInvariantError(
                f"compaction unsafe: active constraints {still_lost} "
                f"have no surviving representation after repair; "
                f"refusing to commit lossy transcript"
            )
        return survival

    return survival
