# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-compaction-to-preserve-a-replayable-checkpoint-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-compaction-to-preserve-a-replayable-checkpoint-invariant.warrant.json
# Markdown SHA-256:   80ab00634083f8f64b5048f1437fa87ec7855148d5f4be5e61bc2090f8fbf1b5
# Code AST SHA-256:   fca458e2804e4a9e665ab5f674436fd43403f69b7e7eeca90bab1cb46bef2811
# Verified Classes:   CompactionInvariantViolation, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CompactionInvariantViolation(RuntimeError):
    """Raised when a compaction would destroy the sole record of a truth-bearing token."""
    pass


TRUTH_BEARING_MARKERS = (
    "delete", "drop", "revoke", "not ", "never", "must not", "forbidden",
    "grant", "allow", "permit", "password", "token", "commit", "spend",
)


@dataclass
class Span:
    start_turn: int
    end_turn: int
    text: str
    raw_retained: bool
    content_hash: str = field(init=False)

    def __post_init__(self):
        self.content_hash = hashlib.sha256(self.text.encode()).hexdigest()[:16]

    def is_truth_bearing(self) -> bool:
        low = self.text.lower()
        return any(m in low for m in TRUTH_BEARING_MARKERS)


def plan_compaction(spans: list[Span], summarizer_id: str, seed: int) -> dict:
    plan = {"generative": [], "extractive": [], "refused": [], "provenance": {}}
    for s in spans:
        if not s.is_truth_bearing():
            plan["generative"].append(s)
            plan["provenance"][s.content_hash] = (summarizer_id, seed, s.start_turn, s.end_turn)
        elif s.raw_retained:
            plan["extractive"].append(s)
        else:
            plan["refused"].append(s)
            raise CompactionInvariantViolation(
                f"Span turns {s.start_turn}-{s.end_turn} (hash {s.content_hash}) is "
                f"truth-bearing and its raw source would be pruned. Refusing generative "
                f"compaction; escalate to extractive pass or fresh-instance handoff."
            )
    return plan


def checkpoint_digest(plan: dict, tier_state: dict) -> str:
    # Checkpoint identity MUST include summarizer provenance, not just state.
    h = hashlib.sha256()
    for key in sorted(tier_state):
        h.update(f"{key}:{tier_state[key]}".encode())
    for cid, prov in sorted(plan["provenance"].items()):
        h.update(f"{cid}:{prov}".encode())
    return h.hexdigest()


if __name__ == "__main__":
    spans = [
        Span(70, 76, "collection deleted, 1203 vectors removed", raw_retained=False),
    ]
    plan_compaction(spans, summarizer_id="summarizer-v3", seed=42)
