# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-compaction-induced-instruction-loss-when-auto-compaction-rewrites-its-own-operating-contract-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-compaction-induced-instruction-loss-when-auto-compaction-rewrites-its-own-operating-contract-mid-run.warrant.json
# Markdown SHA-256:   63db30f1eb3f01973fcd654b648a80a75e8941a00e08f563f235d764062ee133
# Code AST SHA-256:   47bbf0beb2d857f5486ac699b13c6c7a305d047bd3b501e1e4078b1292c5d748
# Verified Classes:   ContractMutationError, ContractClause, Contract
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ContractMutationError(RuntimeError):
    """Raised when a compaction pass drops or mutates a pinned contract clause."""
    pass


@dataclass
class ContractClause:
    clause_id: str
    text: str
    pinned: bool = True

    def fingerprint(self) -> str:
        return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:16]


@dataclass
class Contract:
    clauses: dict = field(default_factory=dict)

    def add(self, clause_id: str, text: str) -> None:
        self.clauses[clause_id] = ContractClause(clause_id, text)

    def snapshot(self) -> dict:
        return {cid: c.fingerprint() for cid, c in self.clauses.items()}


def compact_with_contract_guard(
    transcript: list,
    contract: Contract,
    compactor,
    post_context: str,
    token_budget: int,
) -> str:
    """
    Run a compaction pass while enforcing the pinned-contract invariant.

    Invariant: for every pinned clause, the post-compaction context must
    contain the clause's exact text, and the clause set must be identical
    to the pre-compaction snapshot. A summarizer may never be the sole
    author of the operating contract.
    """
    pre = contract.snapshot()

    # Reserve pinned-clause budget; the compactor may not reclaim it.
    pinned_tokens = sum(len(c.text.split()) for c in contract.clauses.values())
    effective_budget = token_budget - pinned_tokens
    if effective_budget <= 0:
        raise ContractMutationError(
            f"pinned contract ({pinned_tokens} tokens) exceeds budget ({token_budget}); "
            "refusing to compact — contract cannot be evicted to make room"
        )

    # Compactor is given only the compactable stratum, never the pinned region.
    compacted = compactor(transcript, budget=effective_budget)

    # Reassemble: pinned clauses verbatim, then the lossy summary.
    reassembled = "\n".join(c.text for c in contract.clauses.values()) + "\n" + compacted

    # Post-compaction contract diff: detect drop or mutation.
    for clause_id, fp in pre.items():
        clause = contract.clauses[clause_id]
        if clause.text not in reassembled:
            raise ContractMutationError(
                f"clause {clause_id} (fp={fp}) missing from post-compaction context"
            )
        if clause.fingerprint() != fp:
            raise ContractMutationError(
                f"clause {clause_id} mutated across compaction: {fp} -> {clause.fingerprint()}"
            )

    # Guard against a summarizer that paraphrased a clause into the summary
    # while also dropping the canonical copy (double-representation drift).
    if compacted.count(contract.clauses[next(iter(contract.clauses))].text) > 0:
        raise ContractMutationError(
            "summarizer reproduced contract text inside the lossy stratum; "
            "canonical copy would be shadowed on next generation"
        )

    return reassembled
