# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-diff-based-context-rewrite-that-passes-every-invariant-check-but-shrinks-the-protected-span-below-the-recovery-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-diff-based-context-rewrite-that-passes-every-invariant-check-but-shrinks-the-protected-span-below-the-recovery-horizon.warrant.json
# Markdown SHA-256:   fa64afdb59c6f412a4129d0b0ca23ff0bb500fddcd70fd93afb0096e334c7559
# Code AST SHA-256:   28acb2cb5f51812cb36631e27f95be2cbbf4115a2258db71f282df0a6cc7ee92
# Verified Classes:   RecoverySpanCollapseError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RecoverySpanCollapseError(RuntimeError):
    """Raised when a diff passes all invariants but reduces the recoverable span
    below the recovery horizon, with no externalized witness."""
    pass


def authorize_diff(diff, invariants, recovery_horizon, witness_store):
    # Step 1: invariant gate (necessary, not sufficient).
    if not invariants.all_hold(diff.post_state):
        return "reject: invariant_violation"

    # Step 2: recovery-span predicate, evaluated independently.
    pre_span = diff.pre_state.reversible_steps()
    post_span = diff.post_state.reversible_steps()

    if post_span >= pre_span:
        return "commit"  # recovery-neutral or recovery-positive

    # Recovery-reducing edit: requires an externalized witness.
    if post_span < recovery_horizon:
        if witness_store.has_witness_for(diff.removed_trajectory()):
            return "commit-with-witness"
        raise RecoverySpanCollapseError(
            f"diff {diff.id} passed {invariants.count()} invariants but reduced "
            f"reversible steps {pre_span}->{post_span}, below horizon "
            f"{recovery_horizon}, with no witness. Refusing: a green invariant "
            f"gate does not authorize a recovery-reducing edit."
        )
    return "commit-with-witness-required"
