# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-hierarchical-compaction-rewrites-its-own-fidelity-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-provenance-when-hierarchical-compaction-rewrites-its-own-fidelity-budget.warrant.json
# Markdown SHA-256:   afbb23b9c11ffc304c72b827c95cb1a4809b5eda7e804a6de523638c571f7801
# Code AST SHA-256:   c6f7559cceb41b8cf5260536ed02b464e73114922d5167367f1e55aa1dc9b272
# Verified Classes:   FidelityBudgetViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class FidelityBudgetViolation(RuntimeError):
    """Raised when a compacted node fails to carry a required fidelity field."""
    pass


REQUIRED_FIELDS = ("tool_name", "call_id", "arguments_hash", "result_status")


def validate_compacted_node(node: dict, depth: int) -> None:
    """Enforce the fidelity contract structurally, not via prompt text.

    The contract is held here, in code. It is never delegated to the
    summarizer's prose, so paraphrase at depth >= 2 cannot dissolve it.
    """
    if depth < 1:
        return  # leaf nodes are produced under direct instruction; trusted
    missing = [f for f in REQUIRED_FIELDS if f not in node.get("records", {})]
    if missing:
        raise FidelityBudgetViolation(
            f"compacted node at depth {depth} dropped required fields {missing}; "
            f"refusing to promote — widen budget or emit tombstone"
        )


def compact(nodes: list[dict], depth: int, summarizer) -> dict:
    """Summarize children into a parent, then validate before promotion."""
    parent = summarizer(nodes)  # model call; may paraphrase freely
    try:
        validate_compacted_node(parent, depth)
    except FidelityBudgetViolation:
        # Deterministic fallback: pin the fields ourselves, bypassing the model.
        parent["records"] = {
            f: [n["records"][f] for n in nodes if f in n.get("records", {})]
            for f in REQUIRED_FIELDS
        }
        validate_compacted_node(parent, depth)
    return parent
