# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-then-grades-the-recall-of-the-summary-it-just-wrote.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-then-grades-the-recall-of-the-summary-it-just-wrote.warrant.json
# Markdown SHA-256:   32b1164e6bb12c00c28af0f071425288fe461dc4dcac3c4fc849c17f3f833a9f
# Code AST SHA-256:   4946b5ea216d7f4efeb14ecf3909787e142ad574d13aae867d95820124c1f714
# Verified Classes:   SelfGradedFidelityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SelfGradedFidelityError(RuntimeError):
    """Raised when a compaction-fidelity probe is answerable from outside the compacted context."""
    pass


def score_retention_probe(probe, compacted_context, gold, compactor_id, scorer_id,
                          prior_plausibility, recompaction_outcomes):
    # Invariant 1: instrument must not be the artifact's author.
    if scorer_id == compactor_id:
        raise SelfGradedFidelityError(
            f"scorer {scorer_id} is the compactor; fidelity number is advisory only"
        )

    # Invariant 2: gold must not be derived from the artifact under test.
    if gold.get("source") == "compacted_context":
        raise SelfGradedFidelityError(
            "gold extracted from the summary being graded; retention is self-referential"
        )

    # Invariant 3: forget probes must be prior-implausible, else they test the model.
    if probe.kind == "forget" and prior_plausibility > 0.1:
        raise SelfGradedFidelityError(
            f"forget probe {probe.id} is prior-plausible ({prior_plausibility:.2f}); "
            "cannot distinguish failed drop from parametric recall"
        )

    # Invariant 4: facts that flip across re-compactions are variance-band, not pass/fail.
    if len(set(recompaction_outcomes)) > 1:
        return {"probe": probe.id, "verdict": "variance_band",
                "outcomes": recompaction_outcomes}

    # Invariant 5: probe phrasing must be lexically decoupled from the summary.
    if probe.lexical_overlap_with(compacted_context) > 0.8:
        raise SelfGradedFidelityError(
            f"probe {probe.id} shares phrasing with summary; measuring string overlap, not retention"
        )

    recalled = scorer_id.answer(probe, compacted_context) is not None
    return {"probe": probe.id, "verdict": "retained" if recalled else "lost"}
