# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-preserve-a-compaction-floor-before-auto-compaction-rewrites-its-own-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-preserve-a-compaction-floor-before-auto-compaction-rewrites-its-own-trajectory.warrant.json
# Markdown SHA-256:   7d608e39000ab3a923f7536fae129f6c90232f2e3ea05a634793fd6058ea9c6e
# Code AST SHA-256:   30b48e0ef2824751ac78e9003a9c896a7329f825d66865acf9a1dadbee383839
# Verified Classes:   CompactionFloorViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CompactionFloorViolation(RuntimeError):
    """Raised when auto-compaction would evict the causal support of an active goal."""
    pass


def check_compaction_floor(
    post_context_goals: list[dict],
    compaction_depth: int,
    support_keys: tuple[str, ...] = ("origin", "ruled_out", "decision"),
) -> None:
    """
    Verify that every active goal retains its three-element causal support set.
    At depth >= 2, any missing element is a hard failure: the source of truth
    is already a lossy projection, so retrying cannot recover it.
    """
    if compaction_depth < 0:
        raise CompactionFloorViolation(f"invalid compaction_depth={compaction_depth}")

    for goal in post_context_goals:
        if not goal.get("active", False):
            continue
        missing = [k for k in support_keys if not goal.get(k)]
        if not missing:
            continue

        if compaction_depth >= 2:
            # Unsafe zone: refuse. Do not re-summarize a summary.
            raise CompactionFloorViolation(
                f"goal={goal.get('id')!r} lost support {missing} at depth "
                f"{compaction_depth}; must evict completed goals or escalate, "
                f"not compact again"
            )
        # Safe zone: source is intact; caller may re-summarize with stricter prompt.
        goal["_requires_resummarize"] = True


def compact_or_escalate(
    goals: list[dict],
    compaction_depth: int,
    budget_pressure: bool,
) -> str:
    if not budget_pressure:
        return "no_action"

    check_compaction_floor(goals, compaction_depth)

    completed = [g for g in goals if not g.get("active", False)]
    if completed:
        return "evict_completed"
    if compaction_depth >= 2:
        raise CompactionFloorViolation(
            "no completed goals to evict and depth>=2; escalate to orchestrator "
            "rather than compacting active causal structure"
        )
    return "compact_safe_zone"
