# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-fact-loss-during-automatic-context-compaction-in-long-horizon-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-fact-loss-during-automatic-context-compaction-in-long-horizon-agents.warrant.json
# Markdown SHA-256:   9db5af57f411315210da297b43ec343027bd60c282f10c4ccce6b89dee39efca
# Code AST SHA-256:   b5093e12a859b17d70985fa2730dcd2f3904188db58577ff16ebf193a9d61369
# Verified Classes:   CompactionInvariantViolation, Span, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction would evict a load-bearing span."""
    pass


@dataclass(frozen=True)
class Span:
    text: str
    provenance: str          # e.g. "tool:write_file@t=00:14:02"
    pinned: bool = False


@dataclass
class Context:
    pinned: list[Span] = field(default_factory=list)      # never compacted
    eligible: list[Span] = field(default_factory=list)    # compaction-eligible


# Tokens that mark a span as load-bearing. Conservative on purpose:
# false positives pin harmless text; false negatives lose constraints.
LOAD_BEARING_MARKERS = (
    "read-only", "readonly", "forbidden", "must not", "do not",
    "permissionerror", "erofs", "quota", "rate limit", "max size",
    "deadline", "expires",
)


def is_load_bearing(span: Span) -> bool:
    lowered = span.text.lower()
    return any(marker in lowered for marker in LOAD_BEARING_MARKERS)


def ingest(ctx: Context, span: Span) -> None:
    """Classify at ingestion, not at compaction. Pin immediately."""
    if is_load_bearing(span):
        ctx.pinned.append(Span(span.text, span.provenance, pinned=True))
    else:
        ctx.eligible.append(span)


def summarize(spans: list[Span]) -> str:
    # Lossy by design. Only ever called on the eligible region.
    return " ".join(s.text for s in spans)[:200] + " ..."


def compact(ctx: Context) -> str:
    """Compact the eligible region; re-inject pinned region verbatim."""
    for span in ctx.eligible:
        if is_load_bearing(span):
            # A load-bearing span reached the eligible region: ingestion
            # misclassified it, or it was inserted out-of-band. Refuse.
            raise CompactionInvariantViolation(
                f"load-bearing span in eligible region: {span.text!r} "
                f"(provenance={span.provenance}); pin before compacting"
            )
    summary = summarize(ctx.eligible)
    pinned_block = "\n".join(
        f"[PINNED {s.provenance}] {s.text}" for s in ctx.pinned
    )
    ctx.eligible = []  # evicted; summary replaces them
    return pinned_block + "\n\n" + summary


def run_compaction_cycle(ctx: Context) -> str:
    try:
        return compact(ctx)
    except CompactionInvariantViolation:
        # Fail loud and halt the horizon; do not proceed on a lossy summary.
        raise
