# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-fidelity-at-the-summarization-seam-when-hierarchical-compaction-re-derives-facts-from-intermediate-summaries-instead-of-the.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-fidelity-at-the-summarization-seam-when-hierarchical-compaction-re-derives-facts-from-intermediate-summaries-instead-of-the.warrant.json
# Markdown SHA-256:   d7f18b8950575923a26bc48ca1f76affd017353e702124b98225094774057578
# Code AST SHA-256:   b444c139da3b992de3c4d171b34250336275d90e51bef8570a3a4be87f2c2e48
# Verified Classes:   CompactionFidelityError, RawSpan, SummaryNode, SpanStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionFidelityError(RuntimeError):
    """Raised when a normative claim in a consumed summary node cannot be
    traced to a live raw span at the summarization seam."""
    pass


@dataclass
class RawSpan:
    span_id: str
    text: str
    evicted: bool = False


@dataclass
class SummaryNode:
    node_id: str
    depth: int
    text: str
    # span_ids for every normative sentence in `text`; empty means the
    # summarizer produced a normative claim with no provenance.
    normative_span_ids: list[str] = field(default_factory=list)


class SpanStore:
    def __init__(self) -> None:
        self._spans: dict[str, RawSpan] = {}

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

    def resolve(self, span_id: str) -> Optional[RawSpan]:
        span = self._spans.get(span_id)
        if span is None or span.evicted:
            return None
        return span


NORMATIVE_MARKERS = ("must", "may", "not", "at most", "at least",
                     "except", "only", "prohibit", "deferred", "pending")


def _is_normative(sentence: str) -> bool:
    low = sentence.lower()
    return any(m in low for m in NORMATIVE_MARKERS)


def seam_check(node: SummaryNode, store: SpanStore) -> list[str]:
    """Verify every normative sentence in `node` has a resolvable raw span.

    Returns the list of re-fetched span texts. Raises CompactionFidelityError
    if any normative sentence lacks provenance or points to an evicted span.
    """
    sentences = [s.strip() for s in node.text.split(".") if s.strip()]
    normative = [s for s in sentences if _is_normative(s)]

    if normative and not node.normative_span_ids:
        raise CompactionFidelityError(
            f"node {node.node_id} (depth {node.depth}) contains "
            f"{len(normative)} normative sentence(s) but carries no span "
            f"pointers; refusing to consume at seam"
        )

    refetched: list[str] = []
    for span_id in node.normative_span_ids:
        span = store.resolve(span_id)
        if span is None:
            raise CompactionFidelityError(
                f"node {node.node_id} points to span {span_id} which is "
                f"missing or evicted; normative claim is unverifiable"
            )
        refetched.append(span.text)
    return refetched


def consume_for_working_set(node: SummaryNode, store: SpanStore) -> dict:
    try:
        evidence = seam_check(node, store)
    except CompactionFidelityError:
        # fail closed: do not hand the summary to the reasoning loop
        raise
    return {"summary": node.text, "verified_evidence": evidence}
