# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-compaction-aware-evaluation-harness-is-measuring-the-wrong-agent-the-post-compaction-summary-as-context-substitut.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-compaction-aware-evaluation-harness-is-measuring-the-wrong-agent-the-post-compaction-summary-as-context-substitut.warrant.json
# Markdown SHA-256:   50576730e3d29ae6ecc5b350c46f76533dbd1a3ff0c75bf9f2afde9fd4a32d8f
# Code AST SHA-256:   8f0485a38bd21c4783ce4e2779ba064f02e58185368738849b2dc71f13c123a4
# Verified Classes:   CompactionAttributionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionAttributionError(RuntimeError):
    """Raised when a post-compaction score cannot be soundly attributed to the agent."""
    pass


def attribute_post_compaction_score(
    facts_pre: set[str],
    summary_content: str,
    agent_score_pre: float,
    agent_score_post: float,
    replay_scores: list[float],
    replay_variance_threshold: float = 0.15,
) -> dict:
    """
    Decide whether a post-compaction score drop is attributable to the agent
    or to the compaction function. Refuses to emit a retention scalar when
    attribution is not identifiable.
    """
    missing = {f for f in facts_pre if f not in summary_content}

    # Invariant 1: fact-set conservation. If any load-bearing fact was evicted,
    # the score is a compaction measurement, not an agent-retention measurement.
    if missing:
        raise CompactionAttributionError(
            f"Compaction evicted {len(missing)} load-bearing fact(s) "
            f"{sorted(missing)}; post-compaction score is not attributable to the agent."
        )

    # Invariant 3: reconstruction determinism bound.
    if len(replay_scores) < 5:
        raise CompactionAttributionError(
            "Fewer than 5 replays on a deterministic summary; "
            "reconstruction variance is unmeasurable, retention undefined."
        )
    mean = sum(replay_scores) / len(replay_scores)
    variance = sum((s - mean) ** 2 for s in replay_scores) / len(replay_scores)
    if variance > replay_variance_threshold:
        raise CompactionAttributionError(
            f"Replay variance {variance:.3f} exceeds {replay_variance_threshold}: "
            "summary is under-specified and licenses divergent reconstructions; "
            "attribute to compaction quality, not agent."
        )

    # Invariant 2: summarizer uplift confound.
    if agent_score_post > agent_score_pre and agent_score_pre < 0.5:
        return {
            "attribution": "summarizer_uplift",
            "retention": None,
            "note": "post > pre on a failed pre-run: composite agent beat solo agent; "
                    "exclude from retention statistics.",
        }

    # All invariants hold: a genuine agent-conditional retention estimate.
    return {
        "attribution": "agent",
        "retention": agent_score_post / agent_score_pre if agent_score_pre > 0 else None,
        "conditional_competence": agent_score_post,
        "reconstruction_variance": variance,
    }
