# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-hierarchical-compaction-as-a-lossy-transform-requiring-a-re-derivation-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-hierarchical-compaction-as-a-lossy-transform-requiring-a-re-derivation-barrier.warrant.json
# Markdown SHA-256:   8b7f1979bc913063c6bf40482b22da8a4542b8ac196e21180dd7f1aab1bfe634
# Code AST SHA-256:   fb0b3b8d1ba97d67bcdb745fc9191f8bdaefe138db3aa5b2f1038016c0121b0a
# Verified Classes:   CompactionInvariantError, SummaryNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionInvariantError(RuntimeError):
    """Raised when a summary node is asked to stand in for operational facts it did not preserve."""
    pass


@dataclass
class SummaryNode:
    narrative: str
    pinned_literals: dict[str, str] = field(default_factory=dict)
    pinned_constraints: list[str] = field(default_factory=list)
    source_turns: tuple[int, ...] = ()


# Literals/constraints that must never be reconstructed from a summary.
OPERATIONAL_KEYS = {"resource_id", "retry_ceiling", "timeout_ms", "namespace_scope"}


def validate_compaction(children: Iterable[SummaryNode], parent: SummaryNode) -> None:
    """
    Enforce the re-derivation barrier: every operational literal and negative
    constraint present in the children must survive verbatim into the parent's
    pinned block. Narrative may be lossy; operational facts may not.
    """
    required_literals: dict[str, str] = {}
    required_constraints: list[str] = []

    for child in children:
        for key, val in child.pinned_literals.items():
            if key in OPERATIONAL_KEYS:
                required_literals[key] = val
        required_constraints.extend(child.pinned_constraints)

    missing = {
        k: v for k, v in required_literals.items()
        if parent.pinned_literals.get(k) != v
    }
    if missing:
        raise CompactionInvariantError(
            f"Summary node dropped or altered operational literals {missing!r}; "
            f"refusing to evict source turns {parent.source_turns!r}. "
            f"Pin these verbatim or retain the raw children."
        )

    lost_constraints = [c for c in required_constraints if c not in parent.pinned_constraints]
    if lost_constraints:
        raise CompactionInvariantError(
            f"Negative constraints were paraphrased away: {lost_constraints!r}. "
            f"A softened prohibition is a probabilistic hint, not a guardrail."
        )


def compact(children: list[SummaryNode], candidate: SummaryNode) -> SummaryNode:
    validate_compaction(children, candidate)
    return candidate


def resolve_tool_argument(node: SummaryNode, key: str, authoritative_fetch) -> str:
    """
    Post-compaction, never reconstruct an operational literal from summary text.
    Re-derive from the authoritative source; fall back to pinned block only if
    the fetch is unavailable, and refuse outright if neither holds the value.
    """
    if key in OPERATIONAL_KEYS:
        fetched = authoritative_fetch(key)
        if fetched is not None:
            return fetched
        if key in node.pinned_literals:
            return node.pinned_literals[key]
        raise CompactionInvariantError(
            f"Cannot resolve operational argument {key!r}: absent from authoritative "
            f"source and not pinned in summary node. Re-derivation barrier violated."
        )
    return node.pinned_literals.get(key, "")
