# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-automatic-context-compaction-as-a-lossy-state-transfer-rather-than-a-summarization-convenience.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-automatic-context-compaction-as-a-lossy-state-transfer-rather-than-a-summarization-convenience.warrant.json
# Markdown SHA-256:   25016f27cb88d2d20680b0f707e0934304d88a03f227de46a0487e36102e69f8
# Code AST SHA-256:   5dc2ba8b299c74a76c23694c6adf388f94067f534b4e6daaa092e09c61847652
# Verified Classes:   CompactionFrameViolation, OperationalFrame
# Defensive Guards:   5 fail-closed invariants (zero external deps)

"""Post-compaction integrity check: the operational frame must survive verbatim.

Compaction is a lossy state transfer. The narrative may be summarized; the
frame may only be *moved*. This guard enforces that invariant at fold time.
"""

from dataclasses import dataclass, field
from typing import Any


class CompactionFrameViolation(RuntimeError):
    """Raised when a compaction cycle fails to preserve the operational frame."""


@dataclass
class OperationalFrame:
    """Fields the planner reads directly. Never summarized, only copied."""
    target_entities: dict[str, str] = field(default_factory=dict)
    negative_constraints: list[str] = field(default_factory=list)
    machine_invariants: dict[str, Any] = field(default_factory=dict)
    retry_ledger: dict[str, str] = field(default_factory=dict)  # id -> outcome


def verify_compaction(
    pre: OperationalFrame,
    post: OperationalFrame,
    *,
    compaction_depth: int,
    max_depth: int = 2,
) -> None:
    """Assert the frame survived the fold. Abort the fold on any violation."""

    if compaction_depth > max_depth:
        # Beyond depth 2, re-derive from external spill, never from prior digest.
        raise CompactionFrameViolation(
            f"compaction depth {compaction_depth} exceeds {max_depth}; "
            "re-derive frame from external spill instead of folding again"
        )

    for name, expected in pre.target_entities.items():
        actual = post.target_entities.get(name)
        if actual != expected:
            raise CompactionFrameViolation(
                f"entity {name!r} mutated across fold: {expected!r} -> {actual!r} "
                "(summarizer likely collapsed similarly-named entities)"
            )

    missing_constraints = set(pre.negative_constraints) - set(post.negative_constraints)
    if missing_constraints:
        raise CompactionFrameViolation(
            f"negative constraints dropped at fold: {sorted(missing_constraints)}"
        )

    for key, expected in pre.machine_invariants.items():
        actual = post.machine_invariants.get(key)
        if actual != expected:
            raise CompactionFrameViolation(
                f"machine invariant {key!r} lost or paraphrased: "
                f"{expected!r} -> {actual!r}"
            )

    for step_id, outcome in pre.retry_ledger.items():
        if post.retry_ledger.get(step_id) != outcome:
            raise CompactionFrameViolation(
                f"retry ledger entry {step_id!r} altered at fold "
                f"({outcome!r} -> {post.retry_ledger.get(step_id)!r}); "
                "permanent failures may be retried as transient"
            )


def safe_fold(pre: OperationalFrame, digest_frame: OperationalFrame, depth: int) -> OperationalFrame:
    """Fold, then verify. If verification fails, the fold is rejected."""
    verify_compaction(pre, digest_frame, compaction_depth=depth)
    return digest_frame
