# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-lossy-auto-compaction-boundary-has-been-crossed-in-long-horizon-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-lossy-auto-compaction-boundary-has-been-crossed-in-long-horizon-agent-traces.warrant.json
# Markdown SHA-256:   63433a2fc8003419c464f777a30b818f5e4f61b33d70d8c04e0ec65858589843
# Code AST SHA-256:   d9be9a0cbd0b7f46d427a19024b80d27125a7cad9d80c767a11e2fa700f9d339
# Verified Classes:   CompactionFidelityError, Event, CandidateSummary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class CompactionFidelityError(RuntimeError):
    """Raised when a candidate summary would cross the lossy-compaction boundary."""


@dataclass
class Event:
    step: int
    kind: str                 # "tool_call" | "tool_output" | "decision" | "narrative"
    payload: str
    verbatim_class: bool = False   # classified at WRITE time, not compaction time
    identifiers: tuple[str, ...] = ()


@dataclass
class CandidateSummary:
    text: str
    preserved_verbatim: set[str] = field(default_factory=set)
    refetch_pointers: dict[str, str] = field(default_factory=dict)


def check_compaction_boundary(
    compacted_out: Iterable[Event],
    live_plan_references: set[str],
    candidate: CandidateSummary,
    archive_queryable: bool,
) -> None:
    """
    Enforce the fidelity invariant before installing a summary as the live trace.

    Raises CompactionFidelityError if any of the three structural signals fires.
    """
    events = list(compacted_out)

    # Signal 1: orphaned dereference tokens.
    defined = {ident for e in events for ident in e.identifiers}
    orphaned = live_plan_references - defined - set(candidate.refetch_pointers)
    if orphaned:
        raise CompactionFidelityError(
            f"orphaned dereference tokens after compaction: {sorted(orphaned)}"
        )

    # Signal 2: verbatim-class facts demoted to paraphrase.
    verbatim_required = {e.payload for e in events if e.verbatim_class}
    demoted = verbatim_required - candidate.preserved_verbatim
    if demoted:
        raise CompactionFidelityError(
            f"verbatim-class facts not preserved byte-identical: {sorted(demoted)}"
        )

    # Signal 3 preconditions: replay entailment requires a queryable archive.
    if not archive_queryable:
        raise CompactionFidelityError(
            "archive not queryable during live continuation; re-fetch pointers unresolvable"
        )


def install_summary(
    compacted_out: list[Event],
    live_plan_references: set[str],
    candidate: CandidateSummary,
    archive_queryable: bool,
) -> CandidateSummary:
    check_compaction_boundary(
        compacted_out, live_plan_references, candidate, archive_queryable
    )
    # Only reached if the boundary was not crossed.
    return candidate
