# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-trust-its-own-compacted-context-the-reconstruction-witness-invariant-for-lossy-summarization-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-trust-its-own-compacted-context-the-reconstruction-witness-invariant-for-lossy-summarization-boundaries.warrant.json
# Markdown SHA-256:   902487e7dd33a1324277e801a696d8e8e5d441d4d302b392f7746290099973fa
# Code AST SHA-256:   2e7e6f469ace244e43776414012bdeeccbb83d4363b083cd92d21cba2b9c5444
# Verified Classes:   CompactionWitnessError, InFlightOp, NegativeConstraint, ContextState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CompactionWitnessError(RuntimeError):
    """Raised when a lossy compaction would destroy unreconstructable state."""
    pass


@dataclass
class InFlightOp:
    op_id: str
    idempotency_token: str
    retry_count: int
    retry_bound: int
    terminal_ack: bool = False


@dataclass
class NegativeConstraint:
    text: str
    reasserted_in_tool_response: bool = False


@dataclass
class ContextState:
    transcript_tokens: int
    compact_threshold: int
    in_flight: list[InFlightOp] = field(default_factory=list)
    constraints: list[NegativeConstraint] = field(default_factory=list)


def build_reconstruction_witness(state: ContextState) -> dict:
    """
    Produce a machine-checkable witness of the irreducible elements that a
    summary MUST carry verbatim. Refuse compaction if any element cannot be
    witnessed, because dropping it destroys state that has no external home.
    """
    unresolved = [op for op in state.in_flight if not op.terminal_ack]
    active_constraints = [
        c for c in state.constraints if not c.reasserted_in_tool_response
    ]

    if unresolved:
        # Above the boundary: an outcome-unknown write exists. Its idempotency
        # token and retry counter live only in the transcript.
        raise CompactionWitnessError(
            "Cannot compact non-quiescent state: "
            f"{len(unresolved)} in-flight op(s) without terminal ack: "
            + ", ".join(f"{o.op_id}(tok={o.idempotency_token[:8]}...,"
                        f"retry={o.retry_count}/{o.retry_bound})"
                        for o in unresolved)
            + ". Drain or explicitly abandon these before compacting."
        )

    if any(op.retry_count >= op.retry_bound for op in state.in_flight):
        raise CompactionWitnessError(
            "Retry bound reached on a resolved op; escalate before compaction "
            "so the escalation decision is not lost."
        )

    witness = {
        "verbatim_tokens": [op.idempotency_token for op in state.in_flight],
        "retry_bounds": {op.op_id: op.retry_bound for op in state.in_flight},
        "constraints": [c.text for c in active_constraints],
        "digest": hashlib.sha256(
            "|".join(c.text for c in active_constraints).encode()
        ).hexdigest(),
    }
    return witness


def maybe_compact(state: ContextState) -> Optional[dict]:
    if state.transcript_tokens < state.compact_threshold:
        return None  # below threshold, no compaction needed
    # Build witness FIRST. If it raises, we still hold the full transcript
    # and can drain safely — this is the whole point of ordering.
    witness = build_reconstruction_witness(state)
    # Only now is it safe to replace the transcript with a summary that
    # carries the witness verbatim alongside the prose digest.
    return {"summary": "<prose digest>", "witness": witness}
