# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-discarding-the-active-constraint-during-automatic-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-discarding-the-active-constraint-during-automatic-context-compaction.warrant.json
# Markdown SHA-256:   11892d51ecc6a2b00bf91114a325a032a1664a5df7edc6dfb7b740826d77a78d
# Code AST SHA-256:   af3453964af38a3c237b30daf2e6cf3b9e3cea48175b2893a56c1cb2ff05247f
# Verified Classes:   ConstraintLedgerViolation, Constraint, SummaryNode
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ConstraintLedgerViolation(RuntimeError):
    """Raised when a compaction merge drops or modal-degrades an active constraint."""


@dataclass(frozen=True)
class Constraint:
    cid: str
    text: str            # must be emitted verbatim-or-stronger
    modality: str        # "prohibition" | "precondition" | "unapproved" | "commitment"


@dataclass
class SummaryNode:
    level: int
    text: str
    constraints: set[str] = field(default_factory=set)  # cids carried through this node


def merge_summaries(
    children: Iterable[SummaryNode],
    ledger: dict[str, Constraint],
    proposed_text: str,
) -> SummaryNode:
    """
    Merge child summaries into a parent at level+1.

    Invariant: the parent's carried constraint set must be a superset of the
    union of children's carried sets. Fluency is irrelevant; set inclusion is
    the only acceptance criterion.
    """
    children = list(children)
    required: set[str] = set()
    for child in children:
        required |= child.constraints

    # The proposed merged text must literally carry each required constraint
    # in its live form. We check by cid marker presence, not similarity.
    missing = {cid for cid in required if f"[{cid}]" not in proposed_text}
    if missing:
        details = "; ".join(f"{cid}={ledger[cid].text!r} ({ledger[cid].modality})" for cid in sorted(missing))
        raise ConstraintLedgerViolation(
            f"merge at level {children[0].level + 1} dropped active constraints: {details}. "
            f"Refuse merge and hoist these constraints instead of paraphrasing them."
        )

    # Also guard against modal degradation: a prohibition re-emitted as a
    # past-tense report is a violation even though the cid marker is present.
    for cid in required:
        c = ledger[cid]
        if c.modality == "prohibition" and "MUST NOT" not in proposed_text and "must not" not in proposed_text.lower():
            raise ConstraintLedgerViolation(
                f"constraint {cid} ({c.text!r}) was re-emitted without its binding modality "
                f"(expected an explicit 'MUST NOT'); narrative paraphrase is not a valid carry."
            )

    return SummaryNode(
        level=children[0].level + 1,
        text=proposed_text,
        constraints=required,
    )


def compact(transcript_constraints: dict[str, Constraint], proposed_root: str) -> SummaryNode:
    """Top-level entry: root summary must carry the full live ledger."""
    leaf = SummaryNode(level=0, text="", constraints=set(transcript_constraints))
    return merge_summaries([leaf], transcript_constraints, proposed_root)
