# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-working-set-and-the-summarizer-s-fidelity-guarantee-is-measured-against-a-token-budget-it-cannot-honor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-working-set-and-the-summarizer-s-fidelity-guarantee-is-measured-against-a-token-budget-it-cannot-honor.warrant.json
# Markdown SHA-256:   53740c16726dc751d6ac482762d65f00a7023f802967843476aa17df45253a37
# Code AST SHA-256:   950079e6a51fa0c14b1195d83434bdc78ceffd86ab73cee0c5990dca9b9ed50a
# Verified Classes:   CompactionFidelityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CompactionFidelityError(RuntimeError):
    """Raised when a compaction cannot honor its stated semantic-fidelity
    guarantee within the token budget, i.e. the pinned-obligation set does
    not fit. The caller MUST spill to durable storage or halt; it MUST NOT
    accept the summary, because a budget-faithful but semantically lossy
    summary is indistinguishable from a faithful one and defers the loss
    to a silent, later constraint violation."""


def compact(span_tokens: int, budget: int, pinned_obligations: list[str],
            tokenize) -> dict:
    # Pinned obligations (constraints, negations, open TODOs) are non-droppable.
    pinned_cost = sum(len(tokenize(o)) for o in pinned_obligations)
    if pinned_cost > budget:
        raise CompactionFidelityError(
            f"pinned obligations require {pinned_cost} tokens but budget is "
            f"{budget}; refusing to summarize below the fidelity floor. "
            f"Spill to durable store or halt for checkpoint."
        )
    # Only reclaimable span may be summarized, and only into the residual budget.
    residual = budget - pinned_cost
    summary = summarize(span_tokens, residual)  # lossy, but only over reclaimable
    return {"pinned": pinned_obligations, "summary": summary}
