# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-transcript-whose-summarized-prefix-has-already-been-re-summarized-across-a-lossy-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-transcript-whose-summarized-prefix-has-already-been-re-summarized-across-a-lossy-bound.warrant.json
# Markdown SHA-256:   5ba80490c18823771569bc9337e3ab28de0c1b9af58754659cbf930755b128b0
# Code AST SHA-256:   cf034e3f5009f9de0165590125b7a1138be2ff5539297f61ee23afcbf361d889
# Verified Classes:   LossyCompactionRefused, SummaryArtifact, CompactionRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class LossyCompactionRefused(RuntimeError):
    """Raised when a compaction would compose loss without a preservation contract."""
    pass


@dataclass
class SummaryArtifact:
    generation: int
    protected_fields: dict
    reconstructible: bool
    text: str


@dataclass
class CompactionRequest:
    prior_summary: Optional[SummaryArtifact]
    new_turns: list
    protected_fields: dict
    raw_store_handle: Optional[str]
    freed_tokens: int
    expected_turn_growth: int
    headroom_alpha: int = 3


def compact(req: CompactionRequest) -> SummaryArtifact:
    prior = req.prior_summary
    next_gen = 0 if prior is None else prior.generation + 1

    # Validity axis 1: generation depth vs contract presence vs fallback.
    if prior is not None and prior.generation >= 1:
        has_contract = bool(req.protected_fields)
        has_fallback = req.raw_store_handle is not None
        if not has_contract and not has_fallback:
            raise LossyCompactionRefused(
                f"Refusing generation-{next_gen} compaction: prior summary is "
                f"generation {prior.generation} with no protected fields and no "
                f"verbatim fallback; loss would compose unbounded."
            )

    # Validity axis 2: compaction must free enough headroom to be net-positive.
    if req.freed_tokens < req.headroom_alpha * req.expected_turn_growth:
        raise LossyCompactionRefused(
            f"Compaction frees {req.freed_tokens} tokens but needs "
            f">= {req.headroom_alpha * req.expected_turn_growth} to avoid "
            f"immediate re-saturation and a second generation within a few turns."
        )

    # Carry protected fields verbatim; never let the summarizer drop them.
    carried = dict(req.protected_fields)
    if prior is not None:
        for k, v in prior.protected_fields.items():
            carried.setdefault(k, v)

    return SummaryArtifact(
        generation=next_gen,
        protected_fields=carried,
        reconstructible=req.raw_store_handle is not None,
        text="<summary>",
    )
