# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-the-compaction-watermark-before-it-resumes-a-long-horizon-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-the-compaction-watermark-before-it-resumes-a-long-horizon-trajectory.warrant.json
# Markdown SHA-256:   02884540e4d30700dc9c289250f6c31800bfc4cc21e6adc8e41c9d89b4019ca8
# Code AST SHA-256:   2555c04294b7bc469c9b55233c550152c7c687b7a0a03f9efb79d66df9396eb9
# Verified Classes:   CompactionWatermarkError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionWatermarkError(RuntimeError):
    """Raised when a summary claims coverage of a step whose evidence
    was not captured at summary time (C > E for that step)."""


def reconcile_watermarks(summary, evidence_store, summary_created_at):
    """
    summary: dict with 'claimed_steps' -> list of (step_idx, evidence_handle|None)
    evidence_store: dict handle -> {'completed_at': ts, 'payload': ...}
    Returns highest contiguous verified step index.
    Raises CompactionWatermarkError if any phantom step is found and
    the caller has requested strict mode.
    """
    verified_upto = -1
    phantoms = []
    for step_idx, handle in sorted(summary["claimed_steps"]):
        if handle is None:
            phantoms.append((step_idx, "no_handle"))
            break
        ev = evidence_store.get(handle)
        if ev is None:
            phantoms.append((step_idx, "handle_missing"))
            break
        if ev["completed_at"] > summary_created_at:
            phantoms.append((step_idx, "evidence_after_summary"))
            break
        verified_upto = step_idx

    if phantoms:
        step_idx, reason = phantoms[0]
        raise CompactionWatermarkError(
            f"phantom step {step_idx} in summary ({reason}); "
            f"C advanced past E. Roll back C to {verified_upto} and rebuild "
            f"context from last verified checkpoint."
        )
    return verified_upto


def resume_after_compaction(summary, evidence_store, summary_created_at):
    try:
        return reconcile_watermarks(summary, evidence_store, summary_created_at)
    except CompactionWatermarkError:
        # Do not patch: a summary with any phantom is not locally repairable.
        raise
