# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconstruct-from-a-hierarchical-summary-checkpoint-after-lossy-compaction-and-how-is-the-lossy-to-los.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-reconstruct-from-a-hierarchical-summary-checkpoint-after-lossy-compaction-and-how-is-the-lossy-to-los.warrant.json
# Markdown SHA-256:   1f2e6834f4a9a3a009a48fad813ab9521401c4255d39abc7704c604b8e44ff31
# Code AST SHA-256:   6d5e572c8233851fcc825487786d346b69946a7f2faaa687f57e86f132461063
# Verified Classes:   LossyReconstructionRefused, Checkpoint, ContentAddressedStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class LossyReconstructionRefused(RuntimeError):
    """Raised when a checkpoint advertised lossless cannot be verified at read time."""
    pass


@dataclass
class Checkpoint:
    span_id: str
    generation: int          # 1 = direct from original; >=2 = re-summarized
    stored_hash: Optional[str]  # hash of original span; None if never captured
    lossless_flag: bool      # seal-time claim; treated as a HINT, not a warrant
    content: str             # the reconstruction payload


class ContentAddressedStore:
    """Store the producer does not mutate after seal. Slot reuse impossible."""
    def __init__(self) -> None:
        self._blobs: dict[str, str] = {}

    def put(self, content: str) -> str:
        h = hashlib.sha256(content.encode()).hexdigest()
        self._blobs[h] = content
        return h

    def get(self, h: str) -> Optional[str]:
        return self._blobs.get(h)


def reconstruct_for_action(
    cp: Checkpoint,
    store: ContentAddressedStore,
    original_span: Optional[str] = None,
) -> str:
    """
    Reconstruct a span the agent intends to ACT on (patch, numeric budget,
    user constraint, tool replay). Enforces the lossless boundary.
    """
    # Boundary test 1: generation. Re-summarized spans are never lossless.
    if cp.generation != 1:
        raise LossyReconstructionRefused(
            f"checkpoint {cp.span_id} is generation {cp.generation}; "
            f"re-summarization makes lossless claims invalid"
        )

    # Boundary test 2: the seal-time flag is not trusted on its own.
    if not cp.lossless_flag:
        raise LossyReconstructionRefused(
            f"checkpoint {cp.span_id} was sealed lossy; re-observe before acting"
        )

    # Boundary test 3: content-addressed verification at read time.
    if cp.stored_hash is None:
        raise LossyReconstructionRefused(
            f"checkpoint {cp.span_id} has no content hash; referent identity "
            f"unverifiable (slot-addressed pointer suspected)"
        )

    live = store.get(cp.stored_hash)
    if live is None:
        raise LossyReconstructionRefused(
            f"checkpoint {cp.span_id} referent evicted or hash mismatch; "
            f"reconstruction is lossy-only, re-observe"
        )

    if original_span is not None:
        got = hashlib.sha256(original_span.encode()).hexdigest()
        if got != cp.stored_hash:
            raise LossyReconstructionRefused(
                f"checkpoint {cp.span_id} reconstruction not byte-equivalent "
                f"to original span"
            )

    return live


def propagate_lossiness(children: list[Checkpoint]) -> int:
    """Mid node inherits generation >= 2 if any child is lossy-only."""
    if any(c.generation != 1 or not c.lossless_flag for c in children):
        return 2
    return 1
