# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-summaries-as-lossy-checkpoints-rather-than-lossless-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-summaries-as-lossy-checkpoints-rather-than-lossless-state.warrant.json
# Markdown SHA-256:   f46d098ed475864708d5fc99172047351417a1e37bbea2a12457f06b698b9891
# Code AST SHA-256:   aa04468f096c5b7025e595ca91916cfeabee9f5c39092ac41ccf9eaf66acd2cf
# Verified Classes:   CompactionReferentLoss
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionReferentLoss(RuntimeError):
    """Raised when destructive compaction would drop a referent the remaining plan needs."""
    pass


def compact_context(
    transcript_tokens: int,
    window_tokens: int,
    remaining_plan_referents: set[str],
    pinned_referents: set[str],
    generation: int,
) -> dict:
    # Trigger condition: utilization crosses the compaction threshold.
    utilization = transcript_tokens / window_tokens
    if utilization < 0.85:
        return {"action": "none", "generation": generation}

    # The invariant: every referent the remaining plan will consume must be
    # pinned verbatim BEFORE the transcript is destructively summarized.
    unpinned = remaining_plan_referents - pinned_referents
    if unpinned:
        raise CompactionReferentLoss(
            f"Refusing destructive compaction at generation {generation}: "
            f"{len(unpinned)} referent(s) required by remaining plan are not "
            f"pinned and would be lost by gist summarization: {sorted(unpinned)}"
        )

    # Safe path: prose summary is advisory; pinned block is authoritative.
    return {
        "action": "compact",
        "generation": generation + 1,
        "summary_is_lossy": True,
        "pinned_authoritative": sorted(pinned_referents),
    }
