# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-silent-semantic-loss-when-lossy-context-compaction-rewrites-the-agent-s-own-prior-commitments.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-silent-semantic-loss-when-lossy-context-compaction-rewrites-the-agent-s-own-prior-commitments.warrant.json
# Markdown SHA-256:   55adb6e7c83547b816edec451b6249f2c47466a4cd4cb1736605cfe73fd0cf8f
# Code AST SHA-256:   b348ce0f041e407773d16d4b282e7fcd23a12161f1300a267b078ad371921788
# Verified Classes:   CompactionFidelityError, SpanClass, Span, ConstraintLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction pass would violate a pinned constraint."""
    pass


class SpanClass(Enum):
    CONSTRAINT = "constraint"
    COMMITMENT = "commitment"
    FACT = "fact"
    NARRATIVE = "narrative"


@dataclass
class Span:
    text: str
    cls: SpanClass
    origin_turn: int
    generation: int = 0
    pinned: bool = False


@dataclass
class ConstraintLedger:
    pinned: list[Span] = field(default_factory=list)

    def add(self, span: Span) -> None:
        if span.cls in (SpanClass.CONSTRAINT, SpanClass.COMMITMENT):
            span.pinned = True
            self.pinned.append(span)

    def contains_verbatim(self, text: str) -> bool:
        return any(s.text == text for s in self.pinned)


def compact(
    spans: list[Span],
    summary_budget: int,
    verbatim_budget: int,
    ledger: ConstraintLedger,
) -> tuple[str, ConstraintLedger]:
    """
    Lossy compaction with a pinned carve-out. Constraints and commitments are
    retained verbatim and excluded from the summary budget. If pinned spans
    exceed verbatim_budget, compaction HALTS rather than truncating them.
    """
    pinned_cost = sum(len(s.text) for s in ledger.pinned)
    if pinned_cost > verbatim_budget:
        raise CompactionFidelityError(
            f"pinned constraint budget exceeded: {pinned_cost} > {verbatim_budget}; "
            f"refusing to truncate constraints (would risk silent semantic inversion)"
        )

    summary_parts: list[str] = []
    spent = 0
    for span in spans:
        if span.pinned:
            continue  # already in ledger; never re-summarized
        if span.cls in (SpanClass.CONSTRAINT, SpanClass.COMMITMENT):
            # Promoted mid-pass: must be pinned, not compressed.
            ledger.add(span)
            continue
        if span.cls == SpanClass.FACT:
            # Lossy-eligible but keep back-pointer.
            candidate = f"[fact@{span.origin_turn}] {span.text[:120]}"
        else:
            candidate = span.text[:80]
        if spent + len(candidate) > summary_budget:
            break
        summary_parts.append(candidate)
        spent += len(candidate)

    # Second-generation guard: verify no pinned span was paraphrased away.
    summary = "\n".join(summary_parts)
    for pinned in ledger.pinned:
        if pinned.text not in summary and not ledger.contains_verbatim(pinned.text):
            raise CompactionFidelityError(
                f"pinned span lost during compaction: {pinned.text!r}"
            )

    return summary, ledger


def resume_from_cold_start(
    summary: str, ledger: ConstraintLedger, proposed_action: str
) -> None:
    """
    On resume, the summary is untrusted for constraints. Any action that
    touches a pinned target must be checked against the ledger verbatim.
    """
    for pinned in ledger.pinned:
        target = _extract_target(pinned.text)
        if target and target in proposed_action:
            if not _action_respects(pinned.text, proposed_action):
                raise CompactionFidelityError(
                    f"proposed action {proposed_action!r} violates pinned "
                    f"constraint {pinned.text!r} (origin turn {pinned.origin_turn}); "
                    f"summary is UNTRUSTED_FOR_CONSTRAINTS"
                )


def _extract_target(constraint_text: str) -> Optional[str]:
    # Minimal path extraction; real impl uses a typed constraint grammar.
    for token in constraint_text.split():
        if "/" in token or token.endswith(".py"):
            return token.strip("`.,;")
    return None


def _action_respects(constraint_text: str, action: str) -> bool:
    # A constraint containing "do not modify X" is violated by any write to X.
    if "do not" in constraint_text.lower() or "never" in constraint_text.lower():
        return False
    return True
