# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-resume-from-a-lossy-summarization-checkpoint-and-how-is-that-refusal-detected-before-the-next-tool-ca.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-resume-from-a-lossy-summarization-checkpoint-and-how-is-that-refusal-detected-before-the-next-tool-ca.warrant.json
# Markdown SHA-256:   46fdd64347ee003e1fbb5ba3441b95c0f3085d4d9c1f8845bbb23a8bb49f0057
# Code AST SHA-256:   db500d7a071fb1849e373c87afc16558a537bce9efee850eefb1f08db8596b09
# Verified Classes:   CheckpointTrustError, Trust, ProvenancePointer, CompactionCheckpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CheckpointTrustError(RuntimeError):
    """Raised when a resumed instance attempts a state-mutating action
    against a compaction checkpoint that cannot be trusted as authoritative."""
    pass


class Trust(Enum):
    BOUNDED = "bounded"
    UNBOUNDED = "unbounded"
    DRIFTED = "drifted"


@dataclass
class ProvenancePointer:
    source_id: str
    reachable: bool


@dataclass
class CompactionCheckpoint:
    prose_summary: str
    constraint_manifest: list[str] = field(default_factory=list)
    pointers: list[ProvenancePointer] = field(default_factory=list)
    generation_depth: int = 0
    max_depth: int = 1
    manifest_contradicted_by_provenance: bool = False


MUTATING_ACTIONS = {"write", "delete", "deploy", "execute", "external_side_effect"}


def classify_checkpoint(cp: CompactionCheckpoint) -> Trust:
    if cp.manifest_contradicted_by_provenance:
        return Trust.DRIFTED
    if not cp.constraint_manifest:
        return Trust.UNBOUNDED
    if not cp.pointers or not all(p.reachable for p in cp.pointers):
        return Trust.UNBOUNDED
    if cp.generation_depth > cp.max_depth:
        return Trust.UNBOUNDED
    return Trust.BOUNDED


def gate_action(cp: CompactionCheckpoint, action: str, rehydrated: bool) -> None:
    """Enforce the read-only/write boundary at dispatch time.
    Must be called before every tool invocation on a resumed instance."""
    trust = classify_checkpoint(cp)

    if trust is Trust.DRIFTED:
        raise CheckpointTrustError(
            "checkpoint summary contradicts provenance; distrust entire checkpoint "
            "and re-hydrate from source before any action"
        )

    if trust is Trust.UNBOUNDED and action in MUTATING_ACTIONS and not rehydrated:
        raise CheckpointTrustError(
            f"refusing mutating action '{action}': checkpoint is unbounded "
            f"(manifest={bool(cp.constraint_manifest)}, "
            f"pointers_reachable={all(p.reachable for p in cp.pointers) if cp.pointers else False}, "
            f"depth={cp.generation_depth}/{cp.max_depth}); "
            "re-derive constraints from retrievable store or halt"
        )
    # BOUNDED, or UNBOUNDED with successful rehydration -> proceed.
