# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-model-driven-context-compaction-that-reports-success-while-the-surviving-state-no-longer-entails-the-original-task-cons.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-model-driven-context-compaction-that-reports-success-while-the-surviving-state-no-longer-entails-the-original-task-cons.warrant.json
# Markdown SHA-256:   33bce83748d38f6d3714f1072f43e423927936db4f854c95d160084eea0c6d61
# Code AST SHA-256:   7366eeaa19510ffc07a004825db87c954c7fe35f5463c71b0c964b27e4d76779
# Verified Classes:   CompactionEntailmentError, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field


class CompactionEntailmentError(RuntimeError):
    """Raised when a model-driven compaction reports success but the
    surviving state no longer entails a pre-compaction binding constraint."""
    pass


CONSTRAINT_PATTERNS = [
    re.compile(r"\bdo not\b", re.I),
    re.compile(r"\bmust not\b", re.I),
    re.compile(r"\bnever\b", re.I),
    re.compile(r"\bat most\b", re.I),
    re.compile(r"\bno more than\b", re.I),
    re.compile(r"\bdo not exceed\b", re.I),
]


@dataclass
class ConstraintLedger:
    # Append-only, pruner-immutable. The relevance scorer MUST NOT read this.
    constraints: list[str] = field(default_factory=list)

    def extract_and_seal(self, blocks: list[str]) -> None:
        for block in blocks:
            if any(p.search(block) for p in CONSTRAINT_PATTERNS):
                self.constraints.append(block.strip())

    def re_inject(self) -> str:
        if not self.constraints:
            return ""
        return "BINDING CONSTRAINTS (non-compressible):\n" + "\n".join(
            f"- {c}" for c in self.constraints
        )


def verify_compaction(
    ledger: ConstraintLedger,
    post_compaction_state: str,
    pruner_self_report: dict,
) -> None:
    """The pruner's own 'ok' is not evidence. Re-check entailment against the
    sealed ledger, which the pruner was forbidden to score or drop."""
    if pruner_self_report.get("compaction") != "ok":
        raise CompactionEntailmentError(
            f"compaction did not self-report ok: {pruner_self_report!r}"
        )

    # The self-report is only a claim; entailment is the actual gate.
    missing = [
        c for c in ledger.constraints
        if c not in post_compaction_state
    ]
    if missing:
        raise CompactionEntailmentError(
            "compaction self-reported ok but surviving state does not entail "
            f"{len(missing)} binding constraint(s); pruner was not qualified "
            f"to drop them. Missing: {missing!r}"
        )


def run_compaction_cycle(
    blocks: list[str],
    ledger: ConstraintLedger,
    pruner_output: str,
    pruner_self_report: dict,
) -> str:
    # 1. Seal constraints BEFORE any scoring happens.
    ledger.extract_and_seal(blocks)

    # 2. Pruner rewrites/scored/drops — it never saw the ledger.
    compacted = pruner_output

    # 3. Re-inject sealed constraints verbatim, then verify entailment.
    post_state = compacted + "\n" + ledger.re_inject()
    verify_compaction(ledger, post_state, pruner_self_report)
    return post_state
