# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-compaction-retention-metrics-as-invalid-proxies-for-downstream-task-success.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-compaction-retention-metrics-as-invalid-proxies-for-downstream-task-success.warrant.json
# Markdown SHA-256:   8d5533d09ea6853f8f8e72752287751339256dcd487fd571f47db81c8a7efb14
# Code AST SHA-256:   e85a570d73dcb5a5b1bd9df5f7d7ad96fb62551fbfa0240da636582ad2df95e6
# Verified Classes:   CompactionGateError, CompactionCandidate, PromotionPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class CompactionGateError(RuntimeError):
    """Raised when a compaction is authorized for resume on an invalid proxy."""


@dataclass
class CompactionCandidate:
    retention_score: float          # probe-based, salience-weighted
    token_reduction_ratio: float    # 1 - T/T0
    scaffolding_preserved: bool     # negative constraints, orderings, rejections keep FORCE
    probe_causally_closed: bool     # probes derived from action surface, not text salience
    next_action_diverged: bool      # behavioral replay diverged on a constraint-bearing action


@dataclass
class PromotionPolicy:
    min_token_reduction: float = 0.30   # floor constraint, NOT a reward
    resume_reduction_hard_cap: float = 0.66  # above ~3:1, content metrics sign-reverse
    require_behavioral_check_above: float = 0.50


def authorize_for_resume(
    cand: CompactionCandidate,
    policy: PromotionPolicy,
) -> bool:
    """
    Authorize a compacted context as a resuming agent's working context.
    Returns True only if the compaction is safe to promote. Raises on invalid
    proxy use so the caller cannot silently fall back to retention gating.
    """
    # Reduction is a constraint. Failing the floor is a hard no, not a quality question.
    if cand.token_reduction_ratio < policy.min_token_reduction:
        raise CompactionGateError(
            f"compaction under-reduces ({cand.token_reduction_ratio:.2f} < "
            f"{policy.min_token_reduction:.2f}); not a promotion candidate"
        )

    # Scaffolding loss is disqualifying regardless of retention score.
    if not cand.scaffolding_preserved:
        raise CompactionGateError(
            "scaffolding (constraints/orderings/rejections) lost force; "
            f"retention={cand.retention_score:.2f} is not a valid proxy"
        )

    # Retention cannot be trusted unless probes are causally closed over the action surface.
    if not cand.probe_causally_closed:
        raise CompactionGateError(
            "probe set not causally closed over action surface; "
            "retention score cannot authorize resume"
        )

    # Behavioral check is mandatory in the aggressive-reduction regime.
    if cand.token_reduction_ratio >= policy.require_behavioral_check_above:
        if cand.next_action_diverged:
            raise CompactionGateError(
                "behavioral replay diverged on constraint-bearing action; "
                "compaction invalid for resume despite retention="
                f"{cand.retention_score:.2f}"
            )

    # Above the hard cap, content metrics sign-reverse; refuse promotion outright.
    if cand.token_reduction_ratio > policy.resume_reduction_hard_cap:
        raise CompactionGateError(
            f"reduction {cand.token_reduction_ratio:.2f} exceeds resume hard cap "
            f"{policy.resume_reduction_hard_cap:.2f}; retention proxy is sign-reversed"
        )

    return True
