# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-its-own-context-the-self-edit-commit-paradox-at-the-token-pressure-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-its-own-context-the-self-edit-commit-paradox-at-the-token-pressure-boundary.warrant.json
# Markdown SHA-256:   bd9593d30640333538108e323231b8e6bdbfb5ceb6df712ef211f404be03b0e4
# Code AST SHA-256:   606daceded4637c46fa85b2e7c82a99ae6388d4009aeaf86ec2d210aae5f72dd
# Verified Classes:   UnsafeSelfCompactionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnsafeSelfCompactionError(RuntimeError):
    """Raised when a self-compaction would evict the sole copy of an
    obligation or derivation, or would paraphrase a polarity-bearing
    constraint into a digest without a verbatim protected copy."""
    pass


# Spans whose content is re-derivable or externally re-fetchable.
RECOMPUTABLE_KINDS = {"tool_output", "redundant_restatement", "chatter"}

# Spans that must never be paraphrased away without a verbatim copy.
PROTECTED_KINDS = {"user_constraint", "committed_decision", "derivation", "verified_intermediate"}


def compact_span(span: dict, digest: str, protected_ledger: list[str]) -> dict:
    """Decide whether a self-edit may commit. Returns the post-edit context
    fragment, or raises if the edit would destroy an unrecoverable invariant."""
    kind = span["kind"]
    text = span["text"]

    if kind in RECOMPUTABLE_KINDS:
        # Safe: ground truth lives outside the window.
        return {"kind": "digest", "text": digest}

    if kind in PROTECTED_KINDS:
        # The span holds an obligation or derivation. A paraphrase is not
        # authoritative. Require a verbatim copy in the protected ledger
        # BEFORE the source span may be evicted.
        if text not in protected_ledger:
            raise UnsafeSelfCompactionError(
                f"Refusing to compact {kind!r} span: no verbatim copy in "
                f"protected ledger. Paraphrase would become sole authority "
                f"and polarity (negations, 'do not', 'only if') may invert. "
                f"Copy verbatim into ledger first, then evict."
            )
        # Verbatim copy exists; the digest is now a convenience, not authority.
        return {"kind": "digest", "text": digest, "authoritative_ledger_ref": True}

    # Unknown kind under token pressure: default to safe (refuse).
    raise UnsafeSelfCompactionError(
        f"Unknown span kind {kind!r} at compaction boundary; cannot verify "
        f"recomputability. Refuse self-edit and defer to external orchestrator."
    )
