# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-hallucinate-a-completed-tool-call-after-hierarchical-context-compaction-reconstructs-a-checkpoint-from-a-summary-of-summ.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-hallucinate-a-completed-tool-call-after-hierarchical-context-compaction-reconstructs-a-checkpoint-from-a-summary-of-summ.warrant.json
# Markdown SHA-256:   1c66d72cf2d12da9d1e759b81c0c359fd47401f12ac8d597a83572007c771e47
# Code AST SHA-256:   75a163d496a1ff1e33aef45a6c154e3a8a92950d75b740d59814d4579b84a218
# Verified Classes:   ProvenanceError, ClaimKind, Claim, ResumeDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from enum import Enum


class ProvenanceError(RuntimeError):
    """Raised when a resumed agent attempts to act on an unverified side-effect claim."""
    pass


class ClaimKind(Enum):
    OBSERVED = "observed"   # backed by a tool result handle in the raw log
    PLANNED = "planned"     # intention; never executed
    ASSERTED = "asserted"   # model belief, no tool backing
    UNTAGGED = "untagged"   # summarizer dropped provenance


@dataclass
class Claim:
    text: str
    kind: ClaimKind
    result_handle: str | None = None


@dataclass
class ResumeDecision:
    action: str            # "proceed" | "reground" | "halt"
    claim: Claim
    reason: str


SIDE_EFFECT_VERBS = re.compile(
    r"\b(commit|write|delete|send|transfer|deploy|reconcile|submit|post)\b",
    re.IGNORECASE,
)


def classify_resume_action(claim: Claim, is_idempotent: bool, is_observable: bool) -> ResumeDecision:
    """Decide whether a claim from a compacted summary may gate forward action."""
    gates_action = bool(SIDE_EFFECT_VERBS.search(claim.text))
    if not gates_action:
        return ResumeDecision("proceed", claim, "claim does not gate a side effect")

    if claim.kind is ClaimKind.OBSERVED and claim.result_handle:
        return ResumeDecision("proceed", claim, "observed with retrievable result handle")

    if claim.kind in (ClaimKind.PLANNED, ClaimKind.UNTAGGED):
        # The dangerous case: summary states it as done, but it was only ever an intent.
        if is_idempotent:
            return ResumeDecision("reground", claim, "re-execute: idempotent side effect")
        if is_observable:
            return ResumeDecision("reground", claim, "query ground truth before proceeding")
        raise ProvenanceError(
            f"Non-idempotent, unobservable side-effect claim cannot be verified: "
            f"kind={claim.kind.value!r} text={claim.text!r}. "
            f"Refusing to resume forward as if the side effect completed."
        )

    if claim.kind is ClaimKind.ASSERTED:
        if is_observable:
            return ResumeDecision("reground", claim, "asserted claim requires ground-truth check")
        raise ProvenanceError(
            f"Asserted claim gates irreversible action with no observable ground truth: "
            f"text={claim.text!r}. Halt and surface ambiguity."
        )

    raise ProvenanceError(f"Unrecognized claim kind: {claim.kind!r}")


def resume_from_checkpoint(root_summary_claims: list[Claim],
                           idempotency: dict[str, bool],
                           observability: dict[str, bool]) -> list[ResumeDecision]:
    decisions: list[ResumeDecision] = []
    for claim in root_summary_claims:
        key = claim.text[:32]
        decisions.append(classify_resume_action(
            claim,
            is_idempotent=idempotency.get(key, False),
            is_observable=observability.get(key, False),
        ))
    return decisions
