# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-non-idempotent-operator-rather-than-a-memory-management-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-auto-compaction-as-a-lossy-non-idempotent-operator-rather-than-a-memory-management-optimization.warrant.json
# Markdown SHA-256:   dea62e5eb5d6d807afb96f1a8f3a1ccd7deea1af91dd230dbb6239fcfbea38f1
# Code AST SHA-256:   db1872ecc84fffa66b967be8af080bd21420446de6c5930cbf01b9d3e90ecb1a
# Verified Classes:   CompactionDepthExceeded, FaithfulnessTag, Claim
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum


class CompactionDepthExceeded(RuntimeError):
    """Raised when a decision-bearing claim is asserted at a compaction depth
    that does not permit factual assertion without dereference."""
    pass


class FaithfulnessTag(IntEnum):
    RAW = 0          # observed directly; assertable as fact
    SEGMENT = 1      # single summarization; assertable with hedge + pointer
    ROLLUP = 2       # >=2 summarizations; NOT assertable as fact or quote


@dataclass
class Claim:
    text: str
    depth: FaithfulnessTag
    source_turn: int | None
    decision_bearing: bool
    is_negative: bool = False


DECISION_BEARING_MAX_DEPTH = {
    # decision-bearing claims may only be asserted as fact at RAW/SEGMENT
    "assert_as_fact": 1,
    "quote_verbatim": 0,
}


def assert_claim(claim: Claim, mode: str) -> str:
    """Gate assertion strength on compaction depth. mode in {'assert_as_fact','quote_verbatim'}."""
    limit = DECISION_BEARING_MAX_DEPTH[mode]
    if claim.decision_bearing and claim.depth > limit:
        raise CompactionDepthExceeded(
            f"claim at depth {claim.depth.name} cannot be used to '{mode}' "
            f"(limit depth {FaithfulnessTag(limit).name}); dereference source_turn="
            f"{claim.source_turn} first. text={claim.text!r}"
        )
    if claim.is_negative and claim.depth >= FaithfulnessTag.ROLLUP:
        raise CompactionDepthExceeded(
            f"negative finding survived to rollup depth and may have inverted polarity; "
            f"re-derive from source_turn={claim.source_turn}. text={claim.text!r}"
        )
    return claim.text


def guard_recompaction(buffer_state_hash: str, last_compacted_hash: str | None) -> None:
    """Disallow re-compaction of an unchanged buffer (idempotence guard)."""
    if last_compacted_hash is not None and buffer_state_hash == last_compacted_hash:
        raise CompactionDepthExceeded(
            "duplicate compaction trigger on identical buffer state; "
            "re-summarization is non-idempotent and may drop open questions."
        )
