# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-rewrite-divergence-when-model-driven-pruning-destroys-the-evidence-it-needs-to-validate-its-own-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-rewrite-divergence-when-model-driven-pruning-destroys-the-evidence-it-needs-to-validate-its-own-rewrite.warrant.json
# Markdown SHA-256:   1f34b54f6003ad1f926ebfffc5e49947fd5873fafeb54618b7c8bcb21452d835
# Code AST SHA-256:   56deddcea8054c8b9f1d0e9f72058985f9233087a65104eba1f6144953bce910
# Verified Classes:   RewriteFidelityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RewriteFidelityError(RuntimeError):
    """Raised when a model-driven context rewrite drops or abstracts a pinned obligation."""
    pass


def validate_rewrite(
    pre_rewrite_obligations: dict[str, str],
    rewritten_context: str,
    *,
    require_verbatim: bool = True,
) -> None:
    """
    Validate a model-driven compaction against the pinned obligation ledger.

    The ledger MUST be extracted from the ORIGINAL context before the rewrite runs
    and MUST be stored outside the compactable region. This function is the only
    check that is not conditioned on the rewrite itself.
    """
    if not pre_rewrite_obligations:
        # An empty ledger is itself a red flag: either the task genuinely had no
        # constraints, or extraction ran after the evidence was destroyed.
        raise RewriteFidelityError(
            "empty obligation ledger: extraction likely ran post-rewrite; "
            "fidelity cannot be certified"
        )

    missing = []
    for key, obligation in pre_rewrite_obligations.items():
        if require_verbatim:
            if obligation not in rewritten_context:
                missing.append((key, obligation, "dropped_or_paraphrased"))
        else:
            # Paraphrase-tolerant mode still requires the key to be referenced;
            # a key absent from the rewrite means the obligation was abstracted away.
            if key not in rewritten_context:
                missing.append((key, obligation, "key_absent"))

    if missing:
        detail = "; ".join(f"{k}: {reason} ({v[:60]!r})" for k, v, reason in missing)
        raise RewriteFidelityError(
            f"rewrite dropped {len(missing)} pinned obligation(s): {detail}. "
            f"Do not proceed on the rewritten context; re-expand from the "
            f"pre-rewrite transcript or halt for external audit."
        )


def compact_with_validation(
    original_context: str,
    obligation_ledger: dict[str, str],
    rewrite_fn,
) -> str:
    """
    Rewrite only after the ledger is pinned. The rewrite_fn is the model-driven
    summarizer; it is never trusted to validate itself.
    """
    if not obligation_ledger:
        raise RewriteFidelityError(
            "refusing to compact without a pinned obligation ledger"
        )

    rewritten = rewrite_fn(original_context)

    # Pin the ledger into the rewritten context verbatim, outside any summarizable
    # region, so subsequent validators can see it even after further compactions.
    pinned = "\n".join(f"[PINNED {k}] {v}" for k, v in obligation_ledger.items())
    rewritten_with_pins = rewritten + "\n\n" + pinned

    validate_rewrite(obligation_ledger, rewritten_with_pins, require_verbatim=True)
    return rewritten_with_pins
