# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-own-transcript-across-a-tool-call-boundary-and-the-summary-severs-the-causal-link-between-a-claimed-ef.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-own-transcript-across-a-tool-call-boundary-and-the-summary-severs-the-causal-link-between-a-claimed-ef.warrant.json
# Markdown SHA-256:   e2e40070439668b51d29926dfa867f2531bb554482c1414838dc6bfd2ec446c7
# Code AST SHA-256:   514b47e68c7c57e40057ab54564ca7c326fffec0e6090c42b0378e08985dc818
# Verified Classes:   CompactionEvidenceError, EffectClass, Frame, SummaryClaim, AnchorStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionEvidenceError(RuntimeError):
    """Raised when a compaction summary asserts an effect whose observation
    frame is not retrievable verbatim. This is a hard stop: acting on the
    summary alone would let the agent treat an ambiguous outcome as verified."""


class EffectClass(Enum):
    PURE_REASONING = "pure_reasoning"
    EFFECT_VERIFIED = "effect_verified"      # unambiguous mutation + confirmation
    EFFECT_AMBIGUOUS = "effect_ambiguous"    # no-op / already-exists / partial / retry
    EFFECT_FAILED = "effect_failed"          # attempted, no side effect


@dataclass
class Frame:
    tool_call_id: str
    effect: EffectClass
    observation: dict
    verbatim: bool = True

    def observation_hash(self) -> str:
        # content-address the observation so a summary claim can be checked
        blob = repr(sorted(self.observation.items())).encode()
        return hashlib.sha256(blob).hexdigest()


@dataclass
class SummaryClaim:
    text: str
    asserted_effect: bool
    anchor_tool_call_id: Optional[str]
    anchor_observation_hash: Optional[str]


@dataclass
class AnchorStore:
    frames: dict = field(default_factory=dict)  # tool_call_id -> Frame

    def resolve_observation(self, tool_call_id: str) -> Optional[Frame]:
        f = self.frames.get(tool_call_id)
        if f is None or not f.verbatim:
            return None
        return f


def validate_compaction(claims: list[SummaryClaim], anchors: AnchorStore) -> None:
    """Enforce the effect-boundary invariant before committing a compaction pass.

    Rules:
      1. Any claim asserting an effect MUST carry an anchor to a verbatim
         observation frame (not merely an invocation id).
      2. The anchored frame's observation hash MUST match the claim's recorded
         hash, or the claim is unverifiable.
      3. EFFECT_AMBIGUOUS frames MUST NOT be summarized into a clean effect
         claim; they must be retained verbatim and re-expanded on read.
    """
    for c in claims:
        if not c.asserted_effect:
            continue

        if c.anchor_tool_call_id is None:
            raise CompactionEvidenceError(
                f"effect claim without observation anchor: {c.text!r}"
            )

        frame = anchors.resolve_observation(c.anchor_tool_call_id)
        if frame is None:
            raise CompactionEvidenceError(
                f"anchor {c.anchor_tool_call_id} does not resolve to a verbatim "
                f"observation frame; claim {c.text!r} is unsupported"
            )

        if frame.effect is EffectClass.EFFECT_AMBIGUOUS:
            raise CompactionEvidenceError(
                f"ambiguous effect (no-op/already-applied/partial) at "
                f"{frame.tool_call_id} cannot be summarized as a clean effect; "
                f"retain verbatim and re-expand on dependent read"
            )

        if c.anchor_observation_hash != frame.observation_hash():
            raise CompactionEvidenceError(
                f"observation hash mismatch for {frame.tool_call_id}: summary "
                f"claims {c.anchor_observation_hash}, store has "
                f"{frame.observation_hash()}"
            )


# --- Trace of the observed failure, now gated -------------------------------

store = AnchorStore()
turn41 = Frame(
    tool_call_id="call_0041",
    effect=EffectClass.EFFECT_AMBIGUOUS,
    observation={"exit": 0, "rows": 0, "note": "no-op; migration already applied"},
)
store.frames[turn41.tool_call_id] = turn41

bad_summary = [
    SummaryClaim(
        text="Applied migration to db/schema.sql (turn 41); schema confirmed.",
        asserted_effect=True,
        anchor_tool_call_id="call_0041",
        anchor_observation_hash=turn41.observation_hash(),
    )
]

try:
    validate_compaction(bad_summary, store)
except CompactionEvidenceError as e:
    # Correct outcome: compaction is rejected; turn 41 stays verbatim so the
    # turn-92 destructive step can see it does not own the schema state.
    print(f"COMPACTION REJECTED: {e}")
