# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-state-mutating-operation-requiring-regression-detection-rather-than-a-lossless-conte.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-state-mutating-operation-requiring-regression-detection-rather-than-a-lossless-conte.warrant.json
# Markdown SHA-256:   63597c7571a38ed5fec1b54403a69f1fdeb896ac7359f0e0fbd966b8ced08064
# Code AST SHA-256:   be3f7d6c6671d0f475e6cd397bd4ac59385e84ac7857ecbca29e58593e644cac
# Verified Classes:   CompactionRegressionError, CompactionRefusedError, PinnedConstraint, CompactionRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionRegressionError(RuntimeError):
    """Raised when a post-compaction action violates a pre-compaction invariant."""
    pass


class CompactionRefusedError(RuntimeError):
    """Raised when the pinned constraint set cannot fit the reserved budget."""
    pass


@dataclass
class PinnedConstraint:
    text: str
    kind: str  # "hard_constraint" | "commitment" | "side_effect"
    source_offset: int


@dataclass
class CompactionRecord:
    transcript_hash: str
    summary_token_count: int
    pinned: list[PinnedConstraint] = field(default_factory=list)
    commitment_log: list[str] = field(default_factory=list)


def compact(
    transcript: str,
    summary_budget: int,
    pinned_budget: int,
    extract_pinned,          # (transcript) -> list[PinnedConstraint], irreversibility-aware
    summarize,               # (transcript, budget) -> str, similarity-scored
) -> CompactionRecord:
    pinned = extract_pinned(transcript)
    pinned_tokens = sum(len(p.text.split()) for p in pinned)

    # The pinned set is non-budgeted. If it overflows, refuse to compact.
    if pinned_tokens > pinned_budget:
        raise CompactionRefusedError(
            f"pinned set requires {pinned_tokens} tokens, reserved budget is "
            f"{pinned_budget}; compaction would drop a constraint. Refusing."
        )

    summary = summarize(transcript, summary_budget)
    return CompactionRecord(
        transcript_hash=hash(transcript),
        summary_token_count=len(summary.split()),
        pinned=pinned,
        commitment_log=[p.text for p in pinned if p.kind == "side_effect"],
    )


def execute_post_compaction(
    action: dict,
    record: CompactionRecord,
) -> None:
    """Gate every post-compaction action against the pinned invariant set."""
    target = action.get("target", "")

    for constraint in record.pinned:
        if constraint.kind == "hard_constraint" and constraint.text.split()[-1] in target:
            raise CompactionRegressionError(
                f"action targets {target!r}, which violates pinned constraint "
                f"{constraint.text!r} from offset {constraint.source_offset} "
                f"(transcript {record.transcript_hash}). "
                f"Constraint was dropped by salience scoring; action blocked."
            )

    if action.get("kind") in ("create", "delete", "send", "spend"):
        if action.get("idempotency_key") in record.commitment_log:
            raise CompactionRegressionError(
                f"action {action.get('idempotency_key')!r} was already committed "
                f"pre-compaction; re-issuing would duplicate an irreversible effect."
            )
