# 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-lossy-rewrite-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-its-own-context-the-lossy-rewrite-invariant.warrant.json
# Markdown SHA-256:   ae2e0feddc79317e181d4e95fb4f8c703c9b853d0003cad4af8af18cd5cc8842
# Code AST SHA-256:   0fd86090a78f75aca41a9180cf40958059de40c4cee63f145b467b32c68b7c32
# Verified Classes:   UnsafeCompactionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnsafeCompactionError(RuntimeError):
    """Raised when an agent attempts to compact a live, unique, unverifiable region."""
    pass


def compact_region(region, *, is_inert, is_redundant, has_oracle, relocatable):
    """
    Decide whether a context region may be compacted.
    Returns a plan dict on success; raises UnsafeCompactionError on refusal.
    """
    if is_inert:
        # Subgoal closed and verified; the fact will not be acted on again.
        return {"action": "compact", "reason": "inert"}

    if is_redundant:
        # Re-fetchable; prefer eviction with a retained pointer over summarizing.
        return {"action": "evict", "reason": "redundant", "pointer": region.get("source")}

    # Live and unique from here down.
    if relocatable:
        # Promote the fact to a durable store FIRST; compaction is licensed only after.
        return {
            "action": "promote_then_compact",
            "reason": "live_unique_relocatable",
            "promote_to": region["target_store"],
        }

    if has_oracle:
        # No relocation possible, but a scheduled external check will contradict a
        # wrong summary before it is acted on. Permitted only with the check scheduled.
        return {
            "action": "compact_with_oracle",
            "reason": "live_unique_verifiable_after",
            "schedule_check": region["oracle"],
        }

    # Live, unique, unrelocatable, unverifiable: refusal is the correct output.
    raise UnsafeCompactionError(
        "Refusing to compact region {id!r}: it is the sole authority for a live fact, "
        "cannot be relocated, and no oracle is scheduled to detect a corrupted summary. "
        "Grow the context or split the task so the region becomes inert.".format(
            id=region.get("id")
        )
    )
