# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-context-compaction-as-a-lossy-non-monotonic-transform-rather-than-a-monotone-compression-of-its.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-context-compaction-as-a-lossy-non-monotonic-transform-rather-than-a-monotone-compression-of-its.warrant.json
# Markdown SHA-256:   a93ab5bd205ab302e198f72ae8fcbab4c357a9faafd06b55450e03cd877bb14c
# Code AST SHA-256:   4418c9ed261abbc2711b94940af09c29bd3406989cd0f710915302f5afb6fb57
# Verified Classes:   CompactionProvenanceError, SummaryNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionProvenanceError(RuntimeError):
    """Raised when an irreversible action depends on a claim whose only
    surviving support is a generative summary with no addressable raw span."""


class SummaryNode:
    def __init__(self, node_id, text, depth, child_span_ids, pinned=False):
        self.node_id = node_id
        self.text = text
        self.depth = depth                      # 0 = raw span, n = n generative folds
        self.child_span_ids = list(child_span_ids)
        self.pinned = pinned                    # pinned by an open commitment


def assert_action_grounded(action_param_claim: SummaryNode,
                           span_store: dict,
                           max_depth_for_irreversible: int = 1) -> str:
    """
    Gate an irreversible action on provenance depth and live child spans.
    Returns the raw span text that grounds the claim, or raises.
    """
    if action_param_claim.depth > max_depth_for_irreversible:
        raise CompactionProvenanceError(
            f"claim '{action_param_claim.node_id}' has depth "
            f"{action_param_claim.depth} > {max_depth_for_irreversible}; "
            f"too many generative folds to act irreversibly"
        )

    live_children = [sid for sid in action_param_claim.child_span_ids
                     if sid in span_store]
    if not live_children:
        raise CompactionProvenanceError(
            f"claim '{action_param_claim.node_id}' has no surviving raw span; "
            f"evicted children cannot re-ground the action"
        )

    # Re-expand one level and confirm the claim is entailed by a raw span.
    for sid in live_children:
        raw = span_store[sid]
        if _raw_span_supports(raw, action_param_claim.text):
            return raw

    raise CompactionProvenanceError(
        f"no surviving raw span entails claim '{action_param_claim.node_id}'; "
        f"summary may have inverted a hypothetical into a fact"
    )


def _raw_span_supports(raw_span: str, claim_text: str) -> bool:
    # Non-generative check: structured slot match, not an LLM judgment.
    # Placeholder for the real extractor.
    return claim_text.split()[0] in raw_span
