# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-self-rewrite-of-working-memory-when-the-compaction-budget-forces-eviction-of-the-sole-witness-to-a-prior-too.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-self-rewrite-of-working-memory-when-the-compaction-budget-forces-eviction-of-the-sole-witness-to-a-prior-too.warrant.json
# Markdown SHA-256:   6de8f19c22e9502c39c003a02be73ef8c48ff7da078f43b17ec5ba73ee12dc61
# Code AST SHA-256:   638f52c41b781795cec20f22cf12174fd9091e15cbb02b7045d0c10119b8407e
# Verified Classes:   LedgerWitnessEvictionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class LedgerWitnessEvictionError(RuntimeError):
    """Raised when a self-editing context policy attempts to evict or
    summarize the sole in-context witness to a non-idempotent side effect."""


# Tools whose side effects are irreversible and not deduped on re-invocation.
NON_IDEMPOTENT_TOOLS = {"charge_payment", "send_email", "delete_record"}


def compact_span(span: dict, ledger: dict, budget_remaining: int) -> dict:
    """Attempt to compact a single working-memory span under budget pressure.

    Refuses if the span is the sole witness to a non-idempotent side effect
    and the compaction would drop the correlation handle or terminal modality.
    """
    if span.get("kind") == "tool_result" and span.get("tool") in NON_IDEMPOTENT_TOOLS:
        key = span.get("correlation_id")
        entry = ledger.get(key)
        if entry is None or entry.get("status") not in {"succeeded", "failed"}:
            raise LedgerWitnessEvictionError(
                f"refusing to compact span for tool={span.get('tool')!r}: "
                f"no terminal ledger entry (key={key!r}); compaction would "
                f"destroy the only witness to an irreversible side effect"
            )
        # Compaction may proceed ONLY if it preserves the ledger handle verbatim.
        summary = f"{span['tool']} -> {entry['status']} (id={key})"
        if key not in summary or entry["status"] not in summary:
            raise LedgerWitnessEvictionError(
                "compaction summary dropped terminal modality or correlation id"
            )
        if len(summary) > budget_remaining:
            raise LedgerWitnessEvictionError(
                "budget cannot hold ledger witness verbatim; refusing to "
                "summarize further — halt and surface shortfall instead"
            )
        return {"summary": summary, "ledger_preserved": True}

    # Reconstructible span: safe to summarize.
    return {"summary": span.get("text", "")[: budget_remaining // 2], "ledger_preserved": False}
