# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-post-compaction-summary-as-lossy-evidence-rather-than-ground-truth-and-gate-every-resumption-on-a-fidel.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-post-compaction-summary-as-lossy-evidence-rather-than-ground-truth-and-gate-every-resumption-on-a-fidel.warrant.json
# Markdown SHA-256:   32722a04b767cbc2334fec8cefb28dd109ed868cc6d25e649ec760871ffeed9e
# Code AST SHA-256:   f7a0b5e7cdffc8b2bf173ab740471635c942a2c0ea7a0ab50f065769d5448c9c
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a resumed instance attempts a fidelity-critical action
    using only summary-derived (paraphrased) evidence, with no verbatim anchor
    present in the current context."""


# Operands and constraints that MUST survive compaction verbatim.
VERBATIM_ANCHORS = {"cursor", "record_id", "path", "sha256", "date_bound", "negation"}
FIDELITY_CRITICAL_ACTIONS = {"tool_call", "irreversible_write", "gated_step"}


def assert_resumption_safe(action: dict, summary: dict, verbatim_index: set) -> None:
    """
    action:        {"kind": ..., "operands": {name: value}, "depends_on_verification": bool}
    summary:       the post-compaction projection the agent is about to trust
    verbatim_index: tokens currently present VERBATIM in context (not paraphrased)
    """
    kind = action.get("kind")

    # Fidelity-tolerant actions may resume from the summary freely.
    if kind not in FIDELITY_CRITICAL_ACTIONS:
        return

    # 1. Every operand the action will consume must exist verbatim in context.
    for name, value in action.get("operands", {}).items():
        if name in VERBATIM_ANCHORS and value not in verbatim_index:
            raise CompactionFidelityError(
                f"Operand '{name}'={value!r} is not present verbatim in context; "
                f"only a summary paraphrase exists. Re-ground against the raw "
                f"artifact before executing {kind}."
            )

    # 2. A verification obligation cannot be discharged by a summary claim.
    if action.get("depends_on_verification"):
        if not action.get("verification_anchor") in verbatim_index:
            raise CompactionFidelityError(
                "Action depends on a prior verification, but the verification "
                "is asserted only by the summary ('I already checked this'). "
                "Summary assertion is not evidence; re-run or re-read the check."
            )

    # 3. Absence of a constraint in the summary is NOT evidence of absence.
    if summary.get("constraint_ledger_complete") is not True:
        raise CompactionFidelityError(
            "Constraint ledger is incomplete after compaction; a dropped "
            "negation or threshold is indistinguishable from a task that "
            "never had one. Refuse gated actions until ledger is restored "
            "from the raw transcript."
        )


def measure_anchor_survival(pre_anchors: set, post_verbatim: set) -> float:
    """Anchor survival rate — the metric to gate on, distinct from prose quality."""
    if not pre_anchors:
        return 1.0
    return len(pre_anchors & post_verbatim) / len(pre_anchors)
