# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-compaction-summary-headers-as-unverified-cache-not-ground-truth-when-hierarchical-summarization-promotes-lossy-child-summ.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-compaction-summary-headers-as-unverified-cache-not-ground-truth-when-hierarchical-summarization-promotes-lossy-child-summ.warrant.json
# Markdown SHA-256:   587d5f1c061a5ca477431c7a76972a049e86020c3a7ca7437c57c808e15f391c
# Code AST SHA-256:   97b45b34216c3d0895cca54a0cd5425779fb7d1be54e6a9de028864827894f12
# Verified Classes:   CompactionFault, ClaimKind, RawSpan, SummaryNode, SummaryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CompactionFault(RuntimeError):
    """Raised when a summary node cannot be safely promoted or acted upon."""
    pass


class ClaimKind(Enum):
    DESCRIPTIVE = "descriptive"
    POLARITY_BEARING = "polarity_bearing"  # verified / failed / matches / NOT ...


@dataclass
class RawSpan:
    span_id: str
    text: str
    tool_exit_code: int | None = None


@dataclass
class SummaryNode:
    depth: int
    text: str
    pointer_ids: frozenset[str] = field(default_factory=frozenset)
    paraphrased_depths: int = 0
    unresolved_claims: list[str] = field(default_factory=list)

    def is_cache_hit_unverified(self) -> bool:
        return bool(self.unresolved_claims) or self.paraphrased_depths >= 2


class SummaryStore:
    def __init__(self) -> None:
        self.raw: dict[str, RawSpan] = {}
        self.nodes: list[SummaryNode] = []

    def add_raw(self, span: RawSpan) -> None:
        self.raw[span.span_id] = span

    def merge(self, children: list[SummaryNode], merged_text: str) -> SummaryNode:
        # Provenance is monotonic: union of child pointers, never dropped.
        pointers: set[str] = set()
        for c in children:
            pointers |= c.pointer_ids
        if not pointers:
            raise CompactionFault(
                "merge produced a node with empty provenance; summary would "
                "become unverified cache with no path back to raw spans"
            )
        max_depth = max(c.depth for c in children)
        unresolved = [u for c in children for u in c.unresolved_claims]
        return SummaryNode(
            depth=max_depth + 1,
            text=merged_text,
            pointer_ids=frozenset(pointers),
            paraphrased_depths=max(c.paraphrased_depths for c in children) + 1,
            unresolved_claims=unresolved,
        )

    def assert_actionable(
        self, node: SummaryNode, kind: ClaimKind, irreversible: bool
    ) -> RawSpan:
        """Resolve a summary claim to its raw span before an action is taken."""
        if kind is ClaimKind.POLARITY_BEARING or irreversible:
            if node.is_cache_hit_unverified():
                # Force resolution to raw span; never act on the summary itself.
                for pid in node.pointer_ids:
                    span = self.raw.get(pid)
                    if span is not None and span.tool_exit_code not in (0, None):
                        return span  # raw evidence contradicts the summary
                if not node.pointer_ids:
                    raise CompactionFault(
                        f"claim {node.text!r} has no live provenance and raw "
                        "span was evicted; halt rather than act on unverified cache"
                    )
                raise CompactionFault(
                    f"polarity-bearing claim {node.text!r} unresolved after "
                    f"{node.paraphrased_depths} paraphrase depths; "
                    "raw re-read required but no contradicting span found"
                )
        for pid in node.pointer_ids:
            if pid in self.raw:
                return self.raw[pid]
        raise CompactionFault(
            f"summary node at depth {node.depth} cannot be resolved to any "
            "surviving raw span; compaction has made the fact unrecoverable"
        )


def run_turn(store: SummaryStore, node: SummaryNode) -> RawSpan:
    # Agent is about to deploy based on a summary's "migration verified" claim.
    return store.assert_actionable(node, ClaimKind.POLARITY_BEARING, irreversible=True)


if __name__ == "__main__":
    store = SummaryStore()
    store.add_raw(RawSpan("s1", "schema diff: 3 mismatches", tool_exit_code=1))
    leaf = SummaryNode(0, "schema diff shows 3 mismatches, migration NOT verified",
                       frozenset({"s1"}), 0)
    d1 = store.merge([leaf], "migration status: schema diff run")
    d2 = store.merge([d1], "migration verified")
    try:
        run_turn(store, d2)
    except CompactionFault as e:
        print(f"halted: {e}")
