# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-provenance-gap-between-hierarchical-summaries-and-lossy-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-compact-the-provenance-gap-between-hierarchical-summaries-and-lossy-checkpoints.warrant.json
# Markdown SHA-256:   73950d0eee6667c0360312b5507638f3f74046014c724a3bb8455e43c1ba204d
# Code AST SHA-256:   5416df6be01cb66d46ad3e70e59d8c0de83bceca93916d6405c46b299dedeba4
# Verified Classes:   ProvenanceGapError, SummaryNode
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class ProvenanceGapError(RuntimeError):
    """Raised when a checkpointed summary is used as ground truth without a valid re-derivation path."""
    pass

@dataclass
class SummaryNode:
    text: str
    compacted_at_turn: int
    source_span_ids: list[int]
    source_hash: Optional[str]          # hash of authoritative source, None if not re-derivable
    re_derivable: bool
    authoritative: bool = False         # true only if source is gone AND fully carried verbatim

    def is_safe_to_trust_post_resume(self, current_source_hash: Optional[str]) -> bool:
        if self.authoritative:
            return True
        if not self.re_derivable:
            # neither re-derivable nor authoritative: a paraphrase of a lost source
            return False
        if self.source_hash is None or current_source_hash is None:
            return False
        return self.source_hash == current_source_hash

def guard_write_against_summary(
    node: SummaryNode,
    current_source_hash: Optional[str],
    target_path: str,
) -> None:
    if not node.is_safe_to_trust_post_resume(current_source_hash):
        raise ProvenanceGapError(
            f"Refusing write to {target_path!r}: summary compacted at turn "
            f"{node.compacted_at_turn} has re_derivable={node.re_derivable}, "
            f"authoritative={node.authoritative}, and source hash does not match "
            f"current state. Re-derive the source before writing."
        )

def resume_from_checkpoint(nodes: list[SummaryNode], target_path: str,
                           hash_lookup: dict[str, Optional[str]]) -> None:
    for node in nodes:
        if target_path in node.text:
            guard_write_against_summary(node, hash_lookup.get(target_path), target_path)
