# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summary-compaction-as-a-lossy-projection-requiring-recall-triggered-rehydration.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-summary-compaction-as-a-lossy-projection-requiring-recall-triggered-rehydration.warrant.json
# Markdown SHA-256:   4f337317392fa74b134c389599fab505b778136f4b8ba2f42b49bed9a6368c9e
# Code AST SHA-256:   21858709233a9984f6f25b572c45ec674bfb727459be35f98b00714528785e8a
# Verified Classes:   Fidelity, SummaryNode, CompactionLossError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Fidelity(Enum):
    LITERAL = "literal"
    PARAPHRASE = "paraphrase"
    CATEGORY = "category"


class SummaryNode:
    def __init__(self, node_id: str, text: str, source_span_id: Optional[str],
                 fidelity: Fidelity, decision_tags: set[str]):
        self.node_id = node_id
        self.text = text
        self.source_span_id = source_span_id  # pointer into external store
        self.fidelity = fidelity
        self.decision_tags = decision_tags


class CompactionLossError(RuntimeError):
    """Raised when a commitment would be made on a summary node whose
    fidelity/tags indicate the source span must be rehydrated first."""


# Tags that make a node decision-relevant regardless of salience.
MANDATORY_RECALL_TAGS = {"constraint", "negation", "identifier", "threshold"}


def commitment_gate(node: SummaryNode, action_is_side_effecting: bool,
                    cites_summary: bool) -> None:
    """Enforce the rehydrate-before-commit invariant.

    Raises CompactionLossError if the pending action depends on a summary
    node whose loss profile cannot be trusted for commitment.
    """
    if not action_is_side_effecting and not cites_summary:
        return  # planning may consume summaries freely

    # C1: pointer integrity
    if node.source_span_id is None:
        raise CompactionLossError(
            f"node {node.node_id}: no rehydration pointer; summary is orphaned"
        )

    # C3 + commitment gating: category rendering of a decision-relevant tag
    if node.fidelity is Fidelity.CATEGORY and (node.decision_tags & MANDATORY_RECALL_TAGS):
        raise CompactionLossError(
            f"node {node.node_id}: {node.fidelity.value} rendering of "
            f"{node.decision_tags & MANDATORY_RECALL_TAGS}; rehydrate "
            f"source span {node.source_span_id} before committing"
        )

    # Hedged numeric near a threshold
    if "threshold" in node.decision_tags and node.fidelity is not Fidelity.LITERAL:
        raise CompactionLossError(
            f"node {node.node_id}: non-literal threshold value; "
            f"rehydrate {node.source_span_id} to recover exact numeric"
        )


def plan_and_commit(node: SummaryNode, action: str, side_effecting: bool) -> str:
    commitment_gate(node, action_is_side_effecting=side_effecting,
                    cites_summary=True)
    return f"committed: {action}"


# Reproduction of the observed failure as a caught exception.
if __name__ == "__main__":
    spine = SummaryNode(
        node_id="spine-1",
        text="Respect read-only paths.",
        source_span_id="leaf-L2",          # pointer survives: C1 holds
        fidelity=Fidelity.CATEGORY,        # path was dropped: C3 violated
        decision_tags={"constraint"},
    )
    try:
        plan_and_commit(spine, "write /etc/app/legacy/config.yaml",
                        side_effecting=True)
    except CompactionLossError as e:
        print(f"BLOCKED before side effect: {e}")
        # -> rehydrate leaf-L2, recover literal "/etc/app/legacy/", reject plan
