//
//  probe_restore_policy.c
//  W0lfSword
//
//  BUG.1 (2026-09-11 SE panic). The two decisions of the staged write probe's
//  restore contract, in a file that compiles for the host as well as for the
//  engine (no Mach, no Foundation, no globals). See probe_restore_policy.h for
//  why each branch exists.
//
//  Host verification: tests/krw_zone_write_host_test.c (same object the engine
//  builds) + bash scripts/run_krw_zone_write_host_test.sh.
//
#include "probe_restore_policy.h"

probe_exit_action probe_exit_action_for(int probeRc)
{
    if (probeRc == PROBE_EXIT_PROMOTED) {
        // The one exit that deliberately keeps the corrupted socket: it IS the
        // krw primitive from here on, and run_write_test() / the staged
        // stage-2 failure path own the restore.
        return PROBE_ACTION_HAND_OFF;
    }
    // Everything else - including a return code this policy has never seen -
    // restores. Fail-safe direction: a restore that was not needed costs two
    // writes of the values that are already there, a restore that was skipped
    // leaves a corrupted live inpcb behind.
    return PROBE_ACTION_RESTORE;
}

probe_fd_source probe_restore_fd_source(bool trackingArrayHoldsPair,
                                        bool promotionPairLive)
{
    // Prefer the tracking array: it is the record of the spray this attempt
    // owns, and re-opening from it is what the pre-release exits have always
    // done.
    if (trackingArrayHoldsPair) return PROBE_FD_SOURCE_FILEPORTS;
    // The array is gone (pe_v1's release funnel emptied it) but the promotion's
    // fds are still open and belong to exactly this corruption: this is the
    // staged -5 case, where the old code wrote NOTHING back and reported a
    // failure while the corrupted inpcb stayed live.
    if (promotionPairLive) return PROBE_FD_SOURCE_PROMOTION_FDS;
    // Neither source exists. There is no safe write to issue, so the engine
    // must say so loudly rather than report a restore it did not perform.
    return PROBE_FD_SOURCE_UNREACHABLE;
}
