# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-summary-of-summary-anchor-loss-boundary-in-hierarchical-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-summary-of-summary-anchor-loss-boundary-in-hierarchical-context-compaction.warrant.json
# Markdown SHA-256:   2daa4f189ba9b3dee8f94653d658ea0296bf6295d7f6d98d1cdfd3ad7649343d
# Code AST SHA-256:   bfc8091cb9a88dec6b1d0e5641b6d4efd5cb4f2d267af061b63fc8069aef4d38
# Verified Classes:   CompactionRefused, SpanClass, Span, SummaryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class CompactionRefused(RuntimeError):
    """Raised when a constraint-bearing span would be folded into a summary."""
    pass


class SpanClass(Enum):
    CONSTRAINT = "constraint"
    CENTRAL = "central"
    CHATTER = "chatter"


DEONTIC = {"must", "must not", "do not", "frozen", "required", "forbidden", "only", "never"}
COMMITMENT = {"i will", "i won't", "agreed", "promised"}


@dataclass
class Span:
    span_id: int
    text: str
    raw_hash: str
    cls: SpanClass


@dataclass
class SummaryNode:
    node_id: int
    child_span_ids: list[int]
    text: str
    depth: int
    constraint_bearing: bool


def classify(span: Span) -> SpanClass:
    lowered = span.text.lower()
    if any(tok in lowered for tok in DEONTIC | COMMITMENT):
        return SpanClass.CONSTRAINT
    if len(span.text) > 400:
        return SpanClass.CENTRAL
    return SpanClass.CHATTER


def compact(spans: list[Span], depth: int, pinned: list[Span]) -> SummaryNode:
    if depth >= 2 and not pinned:
        raise CompactionRefused(
            f"recursive compaction at depth {depth} with empty pinned register; "
            "constraint-bearing spans would be irrecoverably folded"
        )
    for span in spans:
        if span.cls is SpanClass.CONSTRAINT:
            raise CompactionRefused(
                f"span {span.span_id} is constraint-bearing and must be promoted to "
                f"pinned register before folding; refusing to summarize"
            )
    return SummaryNode(
        node_id=max((s.span_id for s in spans), default=0),
        child_span_ids=[s.span_id for s in spans],
        text=" ".join(s.text[:80] for s in spans),
        depth=depth,
        constraint_bearing=False,
    )


def run_compaction_cycle(spans: list[Span], depth: int, pinned: list[Span]) -> SummaryNode:
    for span in spans:
        span.cls = classify(span)
    return compact(spans, depth, pinned)
