# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-context-folding-as-a-recall-bounded-operation-rather-than-a-lossless-one.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hierarchical-context-folding-as-a-recall-bounded-operation-rather-than-a-lossless-one.warrant.json
# Markdown SHA-256:   ffdf07c7f102cb2ea4e7d5d526bfd5648a1bc05aedc859f0f12b6d23d4170560
# Code AST SHA-256:   5466e781496b73e6b5bf2fd3ac60cd3cc0cf0d311c2c5acaaca95def0d13a84a
# Verified Classes:   FidelityClass, FoldNode, RecallContractViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class FidelityClass(IntEnum):
    APPROXIMATE = 0     # generalization only; no token guarantee
    TRAJECTORY = 1      # decisions and open threads preserved
    EXACT_TOKEN = 2     # verbatim tokens preserved and addressable


@dataclass
class FoldNode:
    node_id: str
    fidelity: FidelityClass
    provenance: dict[str, str]   # fact -> raw span key in external store
    raw_recoverable: bool


class RecallContractViolation(RuntimeError):
    pass


def recall(node: FoldNode, query: str, required: FidelityClass, store_has: callable) -> str:
    """
    Answer a recall query against a folded node, enforcing the fidelity contract.
    Raises RecallContractViolation when the node cannot honor the required fidelity
    and the raw is not recoverable — the exact condition that produced the
    checksum divergence.
    """
    if required <= node.fidelity and node.raw_recoverable:
        # fold is sufficient AND raw exists as backstop
        return f"fold:{node.node_id}"

    if required > node.fidelity:
        # fold is too lossy for this query; must escalate to raw
        if not node.raw_recoverable:
            raise RecallContractViolation(
                f"query requires {required.name} but node {node.node_id} is "
                f"{node.fidelity.name} and raw is unrecoverable; refusing to "
                f"answer from generalization (would substitute, not evict)"
            )
        span = node.provenance.get(query)
        if span is None or not store_has(span):
            raise RecallContractViolation(
                f"no provenance for '{query}' at node {node.node_id}; "
                f"cannot escalate to raw span"
            )
        return f"raw:{span}"

    # required <= fidelity but raw not recoverable: answer is UNVERIFIED
    return f"fold:{node.node_id}:UNVERIFIED"


def compact(parent: FoldNode, children: list[FoldNode], preserved: set[str]) -> FoldNode:
    """
    Fold children into a parent. Parent fidelity is the min of children,
    downgraded to APPROXIMATE for any preserved fact lacking provenance.
    """
    min_fidelity = min((c.fidelity for c in children), default=FidelityClass.APPROXIMATE)
    provenance: dict[str, str] = {}
    for c in children:
        for fact, span in c.provenance.items():
            if fact in preserved:
                provenance[fact] = span

    missing = preserved - provenance.keys()
    if missing:
        # cannot guarantee token fidelity for facts we failed to trace
        min_fidelity = min(min_fidelity, FidelityClass.TRAJECTORY)
        if min_fidelity < FidelityClass.TRAJECTORY:
            raise RecallContractViolation(
                f"fold would drop provenance for {missing} below TRAJECTORY; "
                f"refusing to emit a node that presents substitution as eviction"
            )

    return FoldNode(
        node_id=f"fold:{'-'.join(c.node_id for c in children)}",
        fidelity=min_fidelity,
        provenance=provenance,
        raw_recoverable=all(c.raw_recoverable for c in children),
    )
