# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-invalidated-a-tool-call-contract-it-still-intends-to-honor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-invalidated-a-tool-call-contract-it-still-intends-to-honor.warrant.json
# Markdown SHA-256:   e9af42b97b44ffcac010f0031cce883735a1691cf567ac764807a058b2939d71
# Code AST SHA-256:   bb454e9f7037f44b8e86f640795cc978c04ebaf430fe1ff25be3c58115197374
# Verified Classes:   RecordClass, CompactionContractError, ContextRecord, WriteIntent, CompactionGuard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RecordClass(Enum):
    RAW = "raw"
    SUMMARY = "summary"


class CompactionContractError(RuntimeError):
    """Raised when a write-class tool call depends on an argument that exists
    only inside a lossy summary, or cannot be re-fetched from a raw record."""


@dataclass
class ContextRecord:
    record_id: str
    record_class: RecordClass
    fields: dict  # exact tokens, e.g. {"order_id": "4471", "expected_version": 7}


@dataclass
class WriteIntent:
    tool: str
    args: dict
    safety_critical: set = field(
        default_factory=lambda: {"expected_version", "idempotency_key"}
    )


class CompactionGuard:
    def __init__(self, context: list[ContextRecord], fetcher):
        self.context = context
        self.fetcher = fetcher  # callable(record_id) -> ContextRecord | None

    def _raw_has(self, key: str, value) -> bool:
        return any(
            r.record_class is RecordClass.RAW and r.fields.get(key) == value
            for r in self.context
        )

    def _summary_has(self, key: str) -> bool:
        return any(
            r.record_class is RecordClass.SUMMARY and key in r.fields
            for r in self.context
        )

    def verify_before_write(self, intent: WriteIntent) -> dict:
        resolved = dict(intent.args)
        for key in intent.safety_critical:
            if key in resolved and self._raw_has(key, resolved[key]):
                continue
            if key in resolved and self._summary_has(key):
                # Present only in a summary: not trustworthy, attempt re-fetch.
                ref = self._find_ref_for(key)
                if ref is None:
                    raise CompactionContractError(
                        f"write '{intent.tool}' needs '{key}' but it exists only "
                        f"in a lossy summary and has no raw record id to re-fetch"
                    )
                fresh = self.fetcher(ref)
                if fresh is None or fresh.record_class is not RecordClass.RAW:
                    raise CompactionContractError(
                        f"re-fetch of '{key}' via {ref} returned no raw record; "
                        f"refusing to reconstruct safety-critical argument"
                    )
                resolved[key] = fresh.fields[key]
            elif key not in resolved:
                raise CompactionContractError(
                    f"write '{intent.tool}' is missing safety-critical '{key}' "
                    f"entirely after compaction; aborting rather than defaulting"
                )
        return resolved

    def _find_ref_for(self, key: str):
        for r in self.context:
            if r.record_class is RecordClass.SUMMARY and key in r.fields:
                return r.fields.get(f"_source_id_for_{key}")
        return None


if __name__ == "__main__":
    ctx = [
        ContextRecord("sum-18", RecordClass.SUMMARY,
                      {"order_id": "4471", "expected_version": 7,
                       "_source_id_for_expected_version": "raw-getorder-21"}),
        ContextRecord("raw-getorder-21", RecordClass.RAW,
                      {"order_id": "4471", "expected_version": 7,
                       "last_status": "PENDING"}),
    ]
    guard = CompactionGuard(ctx, fetcher=lambda rid: None)  # source evicted
    intent = WriteIntent(tool="issue_refund",
                         args={"order_id": "4471", "amount": 42.00})
    guard.verify_before_write(intent)  # raises: no raw record, no default
