# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-rewriting-the-agent-s-commitments-during-auto-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-rewriting-the-agent-s-commitments-during-auto-compaction.warrant.json
# Markdown SHA-256:   ebb05aae6e5687d23f9887f76f92496f26c6c2889be5861e7d0e19cf7502f825
# Code AST SHA-256:   9ba0baf5e2e50ae01ff860a707b055b5863a796d4cd7dc7d2700b7141bfbf071
# Verified Classes:   CommitmentFidelityError, Commitment, SummaryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

class CommitmentFidelityError(RuntimeError):
    """Raised when a summary node mutates, drops, or fabricates a critical commitment."""
    pass

@dataclass(frozen=True)
class Commitment:
    key: str
    value: str            # canonical string, e.g. "EUR", "250", "SUP-4471"
    modal: Literal["obligation", "constraint", "permission", "description"]
    critical: bool = True

@dataclass
class SummaryNode:
    level: int
    text: str
    covered_keys: set[str] = field(default_factory=set)

def verify_promotion(parent: SummaryNode, children: list[SummaryNode],
                     ledger: dict[str, Commitment]) -> None:
    """
    Enforce the invariant: every critical commitment whose key is covered by
    any child must appear in the parent with identical value and modal force,
    and the parent must not introduce critical commitments absent from the ledger.
    """
    required = {k for c in children for k in c.covered_keys if ledger.get(k, Commitment("", "", "description", False)).critical}

    for key in required:
        commitment = ledger[key]
        if not _contains_exact(parent.text, commitment):
            raise CommitmentFidelityError(
                f"Promotion to level {parent.level} violated fidelity for "
                f"commitment '{key}': expected value={commitment.value!r} "
                f"modal={commitment.modal!r}; parent text={parent.text!r}"
            )

    # Fabrication check: parent must not assert critical commitments not in ledger.
    for key in _extract_commitment_keys(parent.text):
        if key not in ledger and _looks_critical(parent.text, key):
            raise CommitmentFidelityError(
                f"Parent level {parent.level} introduced unbacked critical "
                f"commitment '{key}' not present in ledger."
            )

def _contains_exact(text: str, c: Commitment) -> bool:
    # Conservative: require value substring AND modal force marker present.
    modal_markers = {
        "obligation": ("will", "must", "shall", "commit"),
        "constraint": ("max", "min", "cap", "limit", "=", "<=", ">="),
        "permission": ("may", "can", "allowed"),
        "description": (),  # descriptions are not fidelity-checked for modal
    }
    if c.value not in text:
        return False
    markers = modal_markers[c.modal]
    return not markers or any(m in text.lower() for m in markers)

def _extract_commitment_keys(text: str) -> set[str]:
    # Placeholder: real impl uses the ledger's key schema / NER + regex.
    return set()

def _looks_critical(text: str, key: str) -> bool:
    return any(t in text for t in ("will", "must", "cap", "max", "before"))
