# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-a-trace-it-cannot-re-derive-the-summarization-witness-boundary-in-long-horizon-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-a-trace-it-cannot-re-derive-the-summarization-witness-boundary-in-long-horizon-agent-memory.warrant.json
# Markdown SHA-256:   9714cbb69e5e81749c8c8bc5d8dd9cd453a5782678cfb05751d17dfcbde8d6a2
# Code AST SHA-256:   955c3445e692639de22f4c7c6d7ecfa2b5d085ee0445eead70c5f45e15ace963
# Verified Classes:   WitnessClass, WitnessBoundaryViolation, TraceSegment, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class WitnessClass(Enum):
    W1_RETAINED = "w1_retained"          # witness present verbatim in compacted form
    W2_REHYDRATABLE = "w2_rehydratable"  # pointer to raw segment retained
    W3_IRRELEVANT = "w3_irrelevant"      # purely descriptive; safe to drop
    UNCLASSIFIED = "unclassified"        # must not be compacted past


class WitnessBoundaryViolation(RuntimeError):
    """Raised when compaction would drop a witness the agent may later need to re-drive or verify."""
    pass


@dataclass
class TraceSegment:
    turn_range: tuple[int, int]
    side_effecting: bool
    witness: Optional[str] = None          # idempotency key, request id, hash, offset
    rehydrate_pointer: Optional[str] = None
    classification: WitnessClass = WitnessClass.UNCLASSIFIED


@dataclass
class CompactionPlan:
    segments: list[TraceSegment] = field(default_factory=list)
    token_budget: int = 0


def classify_and_compact(plan: CompactionPlan) -> list[TraceSegment]:
    """
    Enforce the witness boundary before allowing lossy summarization.
    Segments that are re-drivable must carry a witness (W1) or a re-hydration
    pointer (W2); otherwise compaction must refuse rather than silently drop.
    """
    compacted: list[TraceSegment] = []

    for seg in plan.segments:
        if seg.side_effecting:
            if seg.witness:
                seg.classification = WitnessClass.W1_RETAINED
                compacted.append(seg)  # witness kept verbatim; payload may be truncated
            elif seg.rehydrate_pointer:
                seg.classification = WitnessClass.W2_REHYDRATABLE
                compacted.append(seg)
            else:
                # Re-drivable segment with no witness and no pointer: refuse.
                raise WitnessBoundaryViolation(
                    f"Segment turns {seg.turn_range} is side-effecting but has no "
                    f"retained witness (W1) and no re-hydration pointer (W2). "
                    f"Compacting past this boundary would make re-execution "
                    f"indistinguishable from a fresh, un-deduplicated call. "
                    f"Refusing to compact; escalate to orchestrator or spill raw."
                )
        else:
            # Descriptive content: safe to summarize lossily.
            seg.classification = WitnessClass.W3_IRRELEVANT
            compacted.append(seg)

    return compacted


def assert_summary_is_authoritative(compacted: list[TraceSegment]) -> None:
    """
    Before treating a compacted trace as authoritative state for future
    reasoning or tool re-invocation, verify no segment carries UNCLASSIFIED
    provenance (absence of a witness tag is not evidence none was needed).
    """
    for seg in compacted:
        if seg.classification is WitnessClass.UNCLASSIFIED:
            raise WitnessBoundaryViolation(
                f"Segment turns {seg.turn_range} has unknown provenance. "
                f"A summary's silence about a witness does not license re-driving "
                f"side effects; re-hydrate or fail closed."
            )
