// Blackwood-style break-index backtracker for the 5-clue Eternity II record hunt.
//
// Copyright (C) 2026 Igor Pejic
//
// Port of Joshua Blackwood's public solver (github.com/jblackwood345/EternityII_Solver,
// the engine behind the 468/469/470 records), which is GPL-3.0. Modified in 2026,
// extended with:
//   * all 5 clue pieces forced (single-piece tables + neighbor-filtered tables)
//   * configurable break indices (default 19 breaks -> completed board = 461 = new clue record)
//   * per-thread restart campaign with node cap, heartbeat stats, atomic saves,
//     independent board re-validation before any save, signal-safe shutdown.
//
// Internal coordinates are "bu" (row 0 = bottom row of the physical board), matching
// Blackwood's fill order. Our project files (256pieces.txt, hints.txt, saved boards)
// are "td" (row 0 = top). bu_row = 15 - td_row. Piece rotations are physical
// (# of 90-degree CW turns) and identical in both frames.
//
// Verified 2026-07-04 (derive_mapping.py): our 256pieces.txt uses Blackwood's exact
// color labels, so heuristic_sides {13,16,10} and ring colors {1,5,9,13,17} apply as-is.
//
// Build:  g++ -O3 -march=native -std=c++17 -pthread bw.cpp -o bw
// Run:    ./bw ../256pieces.txt ../hints.txt --threads 32 --seconds 0 --seed 1

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cinttypes>
#include <csignal>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <climits>
#include <mutex>
#include <string>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <thread>
#include <unistd.h>
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <vector>

// On POSIX, binary and text descriptors are identical.  On the Windows CRT,
// however, a descriptor returned by open() stays in text mode even when it is
// later wrapped by fdopen(..., "wb").  Ticket logs contain arbitrary bytes, so
// opening without O_BINARY lets the CRT expand every 0x0A to 0x0D 0x0A and
// destroys the fixed 40-byte record framing.
#ifndef O_BINARY
#define O_BINARY 0
#endif

#ifdef BW_WASM_SINGLE_LANE
#include <emscripten/emscripten.h>
static inline void wasmPublishCheckpoint() {
    emscripten_run_script("if(globalThis.EternityCheckpoint)globalThis.EternityCheckpoint()");
}
#else
static inline void wasmPublishCheckpoint() {}
#endif

#ifdef BW_WASM_PGO_DUMP
// P1 (mission WASM-PGO) : dump EXPLICITE du profil LLVM pendant que le module est VIVANT,
// pour contourner l'atexit LLVM qui crashe (memory access OOB). Appelé depuis le worker JS
// après une phase d'entraînement bornée, AVANT terminate ; on lit ensuite le .profraw en MEMFS.
// Additif, ne compile que sous ce define (natif et WASM normal inchangés).
#include <cstdlib>
extern "C" {
    void __llvm_profile_reset_counters(void);
}
#ifdef BW_WASM_PGO_WRITEFILE
// Variante write_file (toolchains sans l'API buffer, ex. clang-20/emscripten 3.1.74).
// JS lit ensuite le fichier via FS.readFile.
extern "C" {
    int __llvm_profile_write_file(void);
    void __llvm_profile_set_filename(const char*);
}
extern "C" __attribute__((used, visibility("default"))) int bw_pgo_dump(const char* path) {
    __llvm_profile_set_filename((path && *path) ? path : "/prof.profraw");
    return __llvm_profile_write_file();   // 0 si OK
}
extern "C" __attribute__((used, visibility("default"))) unsigned bw_pgo_size(void) { return 0; }
extern "C" __attribute__((used, visibility("default"))) char* bw_pgo_ptr(void) { return nullptr; }
#else
extern "C" {
    uint64_t __llvm_profile_get_size_for_buffer(void);
    int __llvm_profile_write_buffer(char*);
}
static char* g_pgo_buf = nullptr;
static uint64_t g_pgo_size = 0;
// Écrit le profil dans un BUFFER mémoire (pas de fichier MEMFS) ; JS lit ptr/size via HEAPU8.
extern "C" __attribute__((used, visibility("default"))) int bw_pgo_dump(const char*) {
    g_pgo_size = __llvm_profile_get_size_for_buffer();
    if (g_pgo_buf) { free(g_pgo_buf); g_pgo_buf = nullptr; }
    g_pgo_buf = (char*)malloc(g_pgo_size ? (size_t)g_pgo_size : 1);
    return __llvm_profile_write_buffer(g_pgo_buf);   // 0 si OK
}
extern "C" __attribute__((used, visibility("default"))) unsigned bw_pgo_size(void) { return (unsigned)g_pgo_size; }
extern "C" __attribute__((used, visibility("default"))) char* bw_pgo_ptr(void) { return g_pgo_buf; }
#endif
extern "C" __attribute__((used, visibility("default"))) void bw_pgo_reset(void) {
    __llvm_profile_reset_counters();
}
#endif

// ---------------------------------------------------------------- basic types

struct Piece {          // physical sides, clockwise cycle from top
    uint8_t n, e, s, w; // north, east, south, west in canonical (file) orientation
};

struct RotatedPiece {   // one placement candidate, 8 bytes
    uint16_t pieceNumber;   // 1..256, 0 = empty
    uint8_t rot;            // CW quarter turns from canonical
    uint8_t top;            // color facing north after rotation
    uint8_t right;          // color facing east after rotation
    uint8_t breakCount;     // 0 or 1 mismatches vs the (west,south) key
    uint8_t hsc;            // heuristic side count of the piece (rotation-invariant)
    uint8_t pad;
};
static_assert(sizeof(RotatedPiece) == 8, "RotatedPiece must be 8 bytes");

// P1 (Codex) : pool chaud packé 8->4 octets. Encodage : piece-1 bits0-7, rot 8-9,
// top 10-14, right 15-19, break 20-21, HSC 22-24. Le board reste RotatedPiece.
#ifdef BW_PACKED_POOL32
typedef uint32_t PoolElem;
static inline uint32_t packRP(const RotatedPiece& r) {
    return (uint32_t)(r.pieceNumber - 1) | ((uint32_t)r.rot << 8) | ((uint32_t)r.top << 10)
         | ((uint32_t)r.right << 15) | ((uint32_t)r.breakCount << 20) | ((uint32_t)r.hsc << 22);
}
static inline RotatedPiece unpackRP(uint32_t w) {
    RotatedPiece r;
    r.pieceNumber = (uint16_t)((w & 0xFF) + 1);
    r.rot = (uint8_t)((w >> 8) & 3);
    r.top = (uint8_t)((w >> 10) & 0x1F);
    r.right = (uint8_t)((w >> 15) & 0x1F);
    r.breakCount = (uint8_t)((w >> 20) & 3);
    r.hsc = (uint8_t)((w >> 22) & 7);
    r.pad = 0;
    return r;
}
#else
typedef RotatedPiece PoolElem;
static inline RotatedPiece packRP(const RotatedPiece& r) { return r; }
#endif

struct SortEntry { RotatedPiece rp; int key; int32_t sortKey; };

// A candidate table: for key = west*23 + south, a slice of candidates.
struct Table {
    std::vector<PoolElem> pool;       // sorted per restart, slices contiguous per key (packé si BW_PACKED_POOL32)
    uint32_t off[530] = {0};          // off[k]..off[k+1] is the slice for key k
    std::vector<SortEntry> base;      // unsorted master copy (rebuilt slices from this)
#ifdef BW_EARLY_BREAKS
    uint16_t clsB1[530] = {0};        // offset RELATIF dans la slice où breakCount>=1 commence
    uint16_t clsB2[530] = {0};        // idem breakCount>=2 (scan par classe, prune HSC sûre par classe)
#endif
#ifdef BW_BLOCK_MASK
    // P14-B : masque 256-bit (4 uint64) par bloc GLOBAL de 64 entrées du pool = ensemble des pièces
    // présentes dans le bloc. Permet de sauter un bloc entier si aucune de ses pièces n'est restante.
    // Recalculé à chaque restart (pool re-trié). blockMask[g*4+w], g = position_pool/64.
    std::vector<uint64_t> blockMask;
    uint16_t bmClsB1[530] = {0};   // 1er offset RELATIF breakCount>=1 (indépendant de BW_EARLY_BREAKS)
    uint16_t bmClsB2[530] = {0};   // 1er offset RELATIF breakCount>=2
#endif
};

#ifdef BW_EARLY_BREAKS
struct Table;
static void computeClassBounds(struct Table& t);
#endif

static constexpr int NCOLORS = 23;
// Exhaustion-schedule colors. Blackwood's hand-tuned default {13,16,10};
// overridable with --heur-colors "13,16,10,11,12" (learned from pool telemetry).
// The ramp auto-scales by the chosen set's total edge count so the default
// reproduces the original array exactly.
static std::vector<int> HEUR_COLORS = {13, 16, 10};
static double HEUR_EDGE_TOTAL = 150.0;   // recomputed after pieces load
static constexpr bool IS_RING_COLOR[NCOLORS] = {
    false, true, false, false, false, true, false, false, false, true,
    false, false, false, true,  false, false, false, true, false, false,
    false, false, false}; // {1,5,9,13,17}

// LBflux se compose DERRIERE LBσ : il réutilise l'état de parité, le harness --tail-sigma-bench
// et les compteurs. Compiler avec -DBW_FLUX_LEDGER active AUSSI BW_SIGMA_LEDGER (binaire séparé).
#if defined(BW_FLUX_LEDGER) && !defined(BW_SIGMA_LEDGER)
#define BW_SIGMA_LEDGER
#endif

// Experimental checkerboard ledger is a second layer behind LB-sigma.
#if defined(BW_CHECKER_LEDGER) && !defined(BW_SIGMA_LEDGER)
#define BW_SIGMA_LEDGER
#endif

#ifdef BW_CHECKER_LEDGER
static constexpr int CHECKER_N = 5;
// Bits use the solver colour numbering directly (bit c == colour c).
static constexpr uint32_t CHECKER_MASK[CHECKER_N] = {
    0x040000u, // {18}
    0x005000u, // {12,14}
    0x000022u, // {1,5}
    0x000010u, // {4}
    0x000050u  // {4,6}
};
static uint8_t g_checkerWeight[257][CHECKER_N] = {};
static bool g_checkerWeightsBuilt = false;
static bool g_checkerTailOn = false;
static int g_checkerActive = CHECKER_N;
static int g_checkerGateRemain = 48;
static std::atomic<uint64_t> g_checkerCalls{0}, g_checkerStronger{0};
static std::atomic<uint64_t> g_checkerWouldCut{0}, g_checkerCut{0}, g_checkerLeafBug{0};
static std::atomic<int> g_checkerMaxGain{0};
#endif

#ifdef BW_FLUX_LEDGER
// ================= LBflux : conservation DIRECTIONNELLE ENTIÈRE du flux de couleurs ============
// LBσ (parité) oublie l'orientation ; LBflux la garde. Identité de conservation (prouvée sound) :
// pour toute couleur c != 0 (cadre) et toute direction, la somme sur TOUTES les cellules du flux
// signé se referme exactement sur les coutures CASSÉES :
//   Σ_cellules (E==c) - (W==c) = Σ_{coutures verticales cassées} ( (gauche.E==c) - (droite.W==c) )
//   Σ_cellules (N==c) - (S==c) = Σ_{coutures horizontales cassées} ( (bas.N==c) - (haut.S==c) )
// (les faces de bord sont couleur 0 et s'annulent ; les coutures APPARIÉES contribuent 0). Avec un
// potentiel entier λ (ici : INDICATEUR mono-couleur mono-direction, donc spread Q=1), chaque couture
// cassée contribue au plus Q en valeur absolue. En séparant coutures FERMÉES (déjà comptées) et
// FUTURES, on obtient un minorant SOUND du nombre de cassures futures :
//   B_future >= ceil( ( r_l + Σ_{pièces non posées} min_r F[p,r]·λ ) / Q )    (relaxe positions + all-diff)
// où r_l = (flux des cellules posées)·λ - (flux des coutures cassées déjà fermées)·λ. r_l == 0 à la
// feuille complète (analogue signé de oddMask==0). On itère un jeu déterministe de λ (indicateurs
// mono-couleur x et y) et on garde le MEILLEUR certificat. ENTIER STRICT (Q=1 -> pas de division).
// Coupe : spent + max(LBσ, LBflux) > B (JAMAIS sommer). Gate tardif obligatoire (remaining<=16 &&
// slack-LBσ<=2 && LBσ a survécu). Voir spec Codex / eternity2.dev raphael-anjou.
struct FluxLedger {
    // F par pièce/rotation, décomposé en indicateurs (spread Q=1) : on stocke pour chaque pièce p et
    // rotation r les 4 couleurs de face, d'où min_r/max_r par (couleur,direction) sur les 4 rotations.
    // minFx[p][c] = min_r ((E_r==c)-(W_r==c)) ∈ {-1,0,1} ; idem maxFx, minFy, maxFy.
    int8_t minFx[257][NCOLORS], maxFx[257][NCOLORS];
    int8_t minFy[257][NCOLORS], maxFy[257][NCOLORS];
    bool built = false;
} FLUX;
// Compteurs LBflux (portée tail-solver, distincts de LBσ). g_fluxCalls = nœuds où le gate a fait
// ÉVALUER LBflux (survivants LBσ satisfaisant remaining<=16 && slack<=2) = dénominateur du "% morts
// en plus". g_fluxWouldCut = ceux que LBflux couperait ; g_fluxCut = coupes réellement appliquées
// (ON) ; g_fluxLeafBug = feuilles complètes valides avec résidu de flux != 0 (bug du modèle).
static std::atomic<uint64_t> g_fluxCalls{0}, g_fluxWouldCut{0}, g_fluxCut{0}, g_fluxLeafBug{0};
// Diagnostic (indépendant du budget) : combien de nœuds gated où LBflux domine STRICTEMENT LBσ, et de
// combien au max. Répond « la borne directionnelle bat-elle jamais la parité ? » même sans coupe.
static std::atomic<uint64_t> g_fluxStronger{0};
static std::atomic<int> g_fluxMaxGain{0};
static bool g_fluxTailOn = false;      // copie runtime de --flux-ledger : APPLIQUE la coupe (bench la bascule)
static bool g_fluxEval = false;        // ÉVALUE LBflux au gate (shadow-count si !g_fluxTailOn). 0 = gate inerte.
static int  g_fluxGateRemain = 16;     // gate : cellules restantes <= ce seuil
static int  g_fluxGateSlack  = 2;      // gate : (bestCost-1) - running - LBσ <= ce seuil
static void buildFluxLedger();         // défini plus bas (après PIECES / sideAfterRot / logf)
#endif

// Two fill orders, selected at startup by clue mode (zero hot-loop cost: the DFS
// only ever reads the derived SEQ_ROW/SEQ_COL/FILL_IDX arrays).
//
// CLUED (5 hints): Blackwood's order with one change — the 3x3 corner containing
// clue 181 at bu(2,2) is filled FIRST (indices 0-8), then rows 0-2 sweep
// left-to-right. Raster order put the clue corner's dead-ends behind 13+ cells of
// row-0 tail that are independent of the corner, so DFS re-solved the same dead
// corner for millions of irrelevant tail configs (measured: never passed depth 20).
// Clue fill indices: 181@8, 249@45, 139@119, 208@188, 255@247.
//
// RASTER (center clue only): Blackwood's original, unmodified — the configuration
// behind every 468-470 record. No corner clues, so no corner-first fix needed.
static const int BOARD_ORDER_CLUED[16][16] = {
    {196, 197, 198, 199, 200, 205, 210, 215, 220, 225, 230, 235, 243, 249, 254, 255},
    {191, 192, 193, 194, 195, 204, 209, 214, 219, 224, 229, 234, 242, 248, 252, 253},
    {186, 187, 188, 189, 190, 203, 208, 213, 218, 223, 228, 233, 241, 247, 250, 251},
    {181, 182, 183, 184, 185, 202, 207, 212, 217, 222, 227, 232, 240, 244, 245, 246},
    {176, 177, 178, 179, 180, 201, 206, 211, 216, 221, 226, 231, 236, 237, 238, 239},
    {160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175},
    {144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159},
    {128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143},
    {112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127},
    { 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111},
    { 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95},
    { 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79},
    { 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63},
    {  6,   7,   8,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47},
    {  3,   4,   5,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31,  32,  33,  34},
    {  0,   1,   2,   9,  10,  11,  12,  13,  14,  15,  16,  17,  18,  19,  20,  21}};

static const int BOARD_ORDER_RASTER[16][16] = {
    {196, 197, 198, 199, 200, 205, 210, 215, 220, 225, 230, 235, 243, 249, 254, 255},
    {191, 192, 193, 194, 195, 204, 209, 214, 219, 224, 229, 234, 242, 248, 252, 253},
    {186, 187, 188, 189, 190, 203, 208, 213, 218, 223, 228, 233, 241, 247, 250, 251},
    {181, 182, 183, 184, 185, 202, 207, 212, 217, 222, 227, 232, 240, 244, 245, 246},
    {176, 177, 178, 179, 180, 201, 206, 211, 216, 221, 226, 231, 236, 237, 238, 239},
    {160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175},
    {144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159},
    {128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143},
    {112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127},
    { 96,  97,  98,  99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111},
    { 80,  81,  82,  83,  84,  85,  86,  87,  88,  89,  90,  91,  92,  93,  94,  95},
    { 64,  65,  66,  67,  68,  69,  70,  71,  72,  73,  74,  75,  76,  77,  78,  79},
    { 48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,  60,  61,  62,  63},
    { 32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47},
    { 16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,  30,  31},
    {  0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,  15}};

// Chosen at startup: CLUED when any non-center hint exists, else RASTER.
static const int (*BOARD_ORDER)[16] = BOARD_ORDER_CLUED;

// Default budget release schedules per mode (both overridable with --breaks).
// Clued: ours from the 461-463 hunt. Center-only: Blackwood's canonical 470-run
// set — for a realistic ladder start at 466/467, pass a 13-14 slot schedule.
static const char* DEFAULT_BREAKS =
    "177,182,187,192,197,201,206,211,216,221,225,229,233,237,239,241,244,250,253";
static const char* DEFAULT_BREAKS_CENTER_ONLY =
    "201,206,211,216,221,225,229,233,237,239";

// -------------------------------------------------------------------- globals

struct Config {
    std::string piecesFile, hintsFile;
    int threads = 32;
    long seconds = 0;              // 0 = run until signal
    uint64_t seed = 1;
    uint64_t nodeCap = 50000000000ULL;
    double heurScale = 1.0;
    int minSave = 458;             // save completed boards scoring >= this
    std::string saveDir = "campaign_bw";
    uint64_t pruneNodes = 0;       // 0 = prune-back off
    int pruneDepth = 0;
    bool bench = false;
    bool stats = false;            // per-depth node counters (debug)
    std::string breaks = DEFAULT_BREAKS;
    bool breaksSet = false;        // --breaks given (else mode default applies)
    bool heurSet = false;          // --heur-scale given (else mode default applies)
    std::string poolLog;           // telemetry: leftover-pool mask at depth 176 +
                                   // final attempt depth, one line per deep attempt
    std::string ticketLogDir;      // --ticket-log DIR : journal binaire par ticket termine (off par defaut).
                                   // buffer par-thread sans mutex (pattern pool-log), record 40o versionne.
    int ticketFlushSec = 60;       // --ticket-log-flush N : flush temporel par-thread (borne la perte sur crash)
    std::string heurColors;        // --heur-colors "13,16,10,11,12" (learned set)
    bool sdPrune = false;          // --sd-prune: color supply/demand necessary
                                   // condition (piece-theft early detection)
    bool sigmaTail = true;         // --sigma-tail : COUPE LBσ dans le TAIL-solver (615×, probes exact) ; DEFAULT ON.
    bool sigmaMain = false;        // --sigma-main : COUPE LBσ dans le DFS LARGE ; DEFAULT OFF (overhead hors petit-slack).
    bool sigmaMainShadow = false;  // --sigma-main-shadow : audit seul (compte wouldCut sans couper) ; DEFAULT OFF.
    bool fluxLedger = false;       // --flux-ledger : active LBflux (conservation directionnelle), gate tardif
    bool checkerLedger = false;    // --checker-ledger : joint sigma/checker tail bound (experimental)
    int checkerMasks = 5;          // --checker-masks 1..5 : active prefix of the learned portfolio
    int checkerRemain = 48;        // --checker-remain N : evaluate only with <=N tail cells left
    bool demSigmaJoint = false;     // --dem-sigma-joint : couple demand deficits with sigma parity
    int demSigmaGate = 0;           // --dem-sigma-gate T (A adaptatif) : n'évalue LBdemSigma que si lbDem >= T
    int fluxGateRemain = 16;       // --flux-gate-remain : cellules restantes <= seuil (gate)
    int fluxGateSlack = 2;         // --flux-gate-slack : slack après LBσ <= seuil (gate)
                                   // Compilé sous BW_SIGMA_LEDGER ; OFF (défaut) = oddMask
                                   // maintenu + shadow "wouldCut" mais AUCUNE coupe (baseline
                                   // A/B). ON = coupe sound spent + ceil(popcount(oddMask)/2) > B.
    bool isolatedBreaks = false;   // --isolated-breaks: Blackwood's discipline —
                                   // no two broken seams may share a cell
    int cellBreaks = 1;            // --double-breaks: allow 2 mismatches at one
                                   // placement (REPLAY class expansion)
    int frontierAudit = 0;         // --frontier-audit DEPTH : tallie multiplicité des frontières à cette profondeur d'anneau (P5a, shadow)
    bool lbOracle = false;         // --lb-oracle : échantillonne le LB cardinalité aux profondeurs cibles (P6a, shadow, sans prune)
    int budgetLB = 0;              // --budget-lb : P12. 0=off, 1=shadow (mesure, 0 coupe), 2=color (coupe sur LBcolor)
    int budgetLbMinDepth = 230;    // --budget-lb-min-depth : gate profondeur
    int budgetLbMaxSlack = 6;      // --budget-lb-max-slack : gate slack (B-spent)
    std::string boardOrderFile;    // --board-order FILE : ordre custom full-clue (P4c, shadow)
    bool dump3x3 = false;          // --dump-first3x3 FILE : harnais replay-9 (rétroactif, couverture racine 3x3), shadow
    std::string dump3x3Path;       // sortie par thread : FILE.t<tid>, une ligne "attempt p/r,...(9)" par attempt
    std::string enum3x3Path;       // --enum-3x3 FILE : énumère TOUTES les racines 3x3 légales (catalogue), one-shot
    std::string forceRootPath;     // --force-root FILE : canary racine forcée (une racine 3x3 par ligne)
    bool forceRoot = false;        // actif quand forceRootPath chargé
    uint64_t forceJitters = 64;    // --force-jitters N : nb de jitters (attempts) par racine forcée
    bool forceInterleave = false;  // --force-interleave : round-robin racines (tour j sur TOUTES avant tour j+1)
    int shardIndex = 0;            // P13 --shard-index I : ce worker traite les tickets globaux I + N*local
    int shardCount = 1;            // P13 --shard-count N : nb de workers (1 = pas de sharding, byte-identique)
    int forceJitterStart = 0;      // P13 --force-jitter-start J0 : 1er round exploré (évite de refaire ce que le local a déjà fait rounds 0..J0-1)
    std::string skipLedgerPath;    // P13 --skip-ledger FILE : tickets globaux déjà terminés (1/ligne) à ne JAMAIS recalculer (exclusion locale exacte)
    std::string rootAllowPath;     // --root-allow FILE : allowlist de cidx (index racine 0-based) autorisés ; nroots INCHANGÉ (globalTicket+seed préservés), les cidx hors-liste sont sautés
    std::string breakMaskPath;     // --break-mask FILE : masque SPATIAL par-seam (lignes "ci W"/"ci S") — break autorisé SEULEMENT sur ces seams, exact partout ailleurs (test rigidité-localisation vers 465)
    std::string campaignEpoch = "local";  // --epoch ID : provenance des résultats harvest (local/cloud/shard)
    std::string harvestFault;      // --harvest-fault STAGE:N : injection de panne synthétique (test exactly-once)
    std::string harvestSelftest;   // --harvest-selftest DIR:BOARDFILE : self-test durabilité harvest (one-shot)
    std::string harvestCheckFile;  // --harvest-check FILE : validateur autoritatif (verifyBoard+SHA256) one-shot
    std::string captureDir;        // --capture-dir DIR : phase-2, capture 1x/attempt au 1er depth 240 (signature bassin)
    std::string captureArm;        // --capture-arm A|B|C : tag du bras dans la capture
    bool shadowR224 = false;       // --shadow-r224 : phase-3, compte r224 éligibles + clés fortes uniques (0 enqueue)
    std::string tourneyPath;       // --tourney FILE : 1 ligne/attempt "rootID maxSi nodes nodes240 breaks240" (tournoi par racine)
    int tourneySyncLines = 0;      // --tourney-sync-lines N : fdatasync toutes les N lignes DONE (0=off ; borne la perte à N tickets sur crash noyau/VM)
    std::string capture3Dir;       // --capture-gap3 DIR : capture le board 244 de chaque événement bestTailGap<=3 (canary6)
    std::string harvest463Dir;     // --harvest463 DIR : sauve chaque board VÉRIFIÉ score>=463 (canary7), dédup DFP
    std::string probe240In;        // --probe240-in FILE : états depth-240 (hash breaks tok0..tok239) à optimiser en MRV
    std::string probe240Out;       // --probe240-out FILE : bestCost/nodes/capped par état (verrou budget vs ordre)
    long probe240Cap = 500000000;  // --probe240-cap : node-cap par état
    int probe240Gap = 6;           // --probe240-gap : budget = TOTAL_BUDGET + gap (marge de recherche du min)
    std::string fillOrder;         // --fill-order raster|colband|comb (center-only;
                                   // GAUNTLET: scan order unlocks disjoint
                                   // reachable-completion slices)
    int tailDepth = 0;             // --tail-mrv DEPTH:NODES: once per attempt,
    uint64_t tailNodes = 0;        // solve the remaining cells with exact MRV
    int tailTargetScore = -1;      // --tail-target-score SCORE: exact-tail target;
                                   // default inherits the generator's final budget
    uint64_t tailPeriod = 0;       // --tail-period N: sample another prefix
                                   // after N additional hot DFS nodes
    bool tailAdaptive = false;     // --tail-adaptive: progressively rewind a
                                   // wider suffix after depth 248/250/252/253
    int ringDepth = 0;             // --ring-breaks DEPTH: border cells filled at
                                   // or after DEPTH may mismatch a ring colour
                                   // (0 = Blackwood's ban, the historical default)
    int endgameDepth = 0;          // --exact-endgame DEPTH:NODES: at EVERY prefix
    uint64_t endgameNodes = 0;     // reaching DEPTH, replace the hot DFS's search
                                   // of the remaining cells with an exact
                                   // minimum-cost completion, and backtrack at
                                   // once when it exhausts. Affordable because
                                   // only ~22k prefixes per 80B nodes reach 244,
                                   // and it buys ring-colour mismatches, the full
                                   // remaining budget at any depth, and MRV order.
    uint64_t yieldBase = 0;        // --yield-budget BASE:PER — spend nodes on an
    uint64_t yieldPer = 0;         // attempt in proportion to what it produces:
                                   // the attempt starts with BASE nodes and earns
                                   // PER more for every exact-endgame arrival it
                                   // reaches. Measured: 40% of attempts reach the
                                   // cutoff zero times while the top few supply
                                   // ~40% of all arrivals, so a flat node cap
                                   // spends most of its time on dead bottoms.
    int escGap = 0;                // --endgame-escalate GAP:REWIND:NODES — when the
    int escRewind = 0;             // cheap 12-cell exact endgame lands within GAP of
    uint64_t escNodes = 0;         // the budget, re-solve a much wider suffix from
                                   // REWIND exactly. Near misses are rare, so the
                                   // wide search is nearly free, and it is applied
                                   // to a population already known to be good —
                                   // unlike simply lowering the cutoff, which
                                   // spends the wide search on everything and
                                   // measured strictly worse.
    // --endgame-ladder "G1:R1:N1,G2:R2:N2,..." — successive exact re-solves of an
    // ever wider suffix. A prefix enters rung k only when rung k-1 left its
    // cheapest completion within Gk of the budget, so each more expensive search
    // runs on a population the cheaper one already proved good, and the rungs stay
    // rare. Rewinds must strictly deepen. --endgame-escalate/2 append one rung
    // each and remain valid spellings.
    struct EscRung { int gap; int rewind; uint64_t nodes; };
    std::vector<EscRung> ladder;
    // --tail-slice S:N:REWIND — parallel tail. This process explores only MRV
    // candidate class S of N at the ladder rung whose rewind == tsRewind.
    int tsS = -1, tsN = 0, tsRewind = -1;
    // P7-A snapshot/replay of one exact-tail state (shadow tooling, doesn't touch prod).
    int captureRung = -1;          // --capture-rung REWIND:PATH — dump state before that rung's call
    std::string capturePath;
    std::string replayBoardPath;   // --replay-board PATH|DIR (BW_SIGMA_LEDGER) : trace LBσ le long d'une solution connue (soundness)
    // --tail-sigma-bench BOARD (BW_SIGMA_LEDGER) : porte LBσ dans le tail-solver et mesure soundness
    // (énumération exhaustive OFF vs ON) + gain nodes/wall par rung. LOCAL only, ne touche pas la prod.
    std::string tailSigmaBench;
#ifdef BW_CUT_SNAPSHOT
    // --cut-snapshot BOARD OUT : dumpe des VRAIS survivants LBσ (par rung) + taille de sous-arbre, pour
    // évaluer offline forcedSeamLB / τ (CUT_SNAPSHOT_CORPUS_V1). LOCAL only, jamais la prod.
    std::string cutSnapBoard, cutSnapOut;
    long cutStride = 500;          // --cut-stride N : échantillonne 1 survivant sur N
    long cutPerRung = 400;         // --cut-per-rung N : plafond de snapshots par rung
    uint64_t cutNodeCap = 400000000ULL; // --cut-nodecap N : node-cap par rung (sur q.nodes = survivants)
    std::string cutRungs;          // --cut-rungs "236,230" : rungs à échantillonner (défaut 6)
#endif
    std::string tsbRungs;          // --tsb-rungs "236:4,230:3,224:2,216:1" (rewind:gap) ; défaut si vide
    int tsbTarget = 465;           // --tsb-target : TOTAL_BUDGET = 480 - target (défaut 465 -> 15 breaks)
    uint64_t tsbCap = 2000000000ULL; // --tsb-cap N : node-cap par run
    int tsbEnumRewind = 250;       // --tsb-enum-rewind : petit tail exhaustif pour la soundness
    int tsbEnumBudget = 24;        // --tsb-enum-budget : borne de coût de l'énumération exhaustive
    int tsbInitBest = -1;          // --tsb-initbest : plafond incumbent (bestCost). -1 = boardBreaks (prod)
    std::string replayPath;        // --replay-tail PATH — restore & re-solve exactly, print verdict
    int cubeDepth = -1;            // --replay-cubes DEPTH:WORKERS (with --replay-tail PATH)
    int cubeWorkers = 1;
    long shardLo = -1, shardHi = -1;  // P8: --shard LO:HI (cube index range = one shard)
    bool countCubes = false;          // P8: --count-cubes (print CUBE_COUNT, no processing)
    std::string p8Journal;            // P8-B: --replay-p8b JOURNAL (per-cube cap + append journal)
    std::string terminalManifest;     // P8-B: --terminal-manifest DIR (file-per-key proofs)
    std::string terminalSelftest;     // --terminal-selftest SNAP : gate the key round-trip
    std::string deferSelftest;        // --defer-selftest SNAP : gate the admission logic
    std::string chainSelftest;        // --chain-selftest SNAP : gate l'admission chaîne (mode B) + spec corrompue
    std::string verifyBoardFile;      // --verify-board FILE : charge un board sauvé, imprime score + checksum (gate 465)
    bool deferInbox = false;          // --defer-inbox : main defers r224 to P8 (Codex B+garde)
    bool deferChain = false;          // --defer-chain : main defers the WHOLE r224->r216 chain (mode B)
    std::string p8Heartbeat;          // --p8-heartbeat FILE : main reads it to know P8 is alive
    std::string writeHeartbeat;       // --write-heartbeat FILE : one-shot, bw_p8 writes + exits
    int hbWorkers = 8;                // --write-heartbeat announces this worker count
    int hbMinRewind = 224;            // drain closes rewind >= this (r224)
    std::string attemptState;         // --attempt-state FILE : persist per-thread nextAttempt
    bool attemptSelftest = false;     // --attempt-selftest : gate the persistence logic
    std::string backfillProof;        // --backfill-proof SNAP : migrate an existing closed tail
    std::string backfillJournal;      // --backfill-journal JOURNAL : strict identity check
    std::string r216Gate;             // --r216-gate SNAP : inline-vs-chain r216 byte-identical (test only)
    std::string makeChainSnap;        // --make-chain SNAP : build a ChainSpec from an r224 snapshot
    std::string chainOut;             // --chain-out FILE : where to write the ChainSpec
    std::string replayChainPath;      // --replay-chain CHAIN : run the P8-owned r224->r216 chain
    std::string chainWorkdir;         // --chain-workdir DIR : chain state + sub-journals
    uint64_t chainCap216 = 10000000000ULL;  // --chain-cap216 N : total cap of the r216 probe
    uint64_t p8bTotalCapCli = 0;            // --p8b-total-cap N : total cap for a direct replayP8b (gate)
    std::string captureInbox;      // --capture-inbox DIR — refinery feed: dump every promising
                                   // rung224/216 arrival (deduped by state hash), generator continues
    int endgameSample = 0;         // --endgame-sample N: apply the wide probe to
                                   // every Nth call only, so the cost
                                   // distribution can be measured without paying
                                   // for it on every arrival (the probe changes
                                   // per-call cost by orders of magnitude at
                                   // shallow cutoffs, which distorts exactly the
                                   // comparison it is meant to inform).
    int endgameProbeExtra = 0;     // --endgame-probe EXTRA: widen the exact search
                                   // to budget+EXTRA so the telemetry shows how
                                   // far the endgame misses (measurement mode).
    int tailMinSlack = 0;          // --tail-min-slack S: only spend exact-endgame
                                   // work on states with >= S budget unspent.
                                   // Measured: the endgame of a banked depth-250
                                   // prefix needs 4-10 further mismatches, so
                                   // zero-slack states are hopeless by ~5.
};

static Config cfg;
static Piece PIECES[257];                 // 1-based
static uint8_t PIECE_HSC[257];
static int PIECE_CLASS[257];              // 0 middle, 1 side, 2 corner
static bool IS_CLUE[257];
struct Hint { int piece, tdRow, tdCol, rot; };
static std::vector<Hint> HINTS;

// Hot solver tables packed into one cache-aligned block so code/data layout
// changes elsewhere can't shift them across cache lines (a 1KB rodata addition
// once cost a measurable ~3% nodes/s purely from layout drift).
struct alignas(64) HotTables {
    uint8_t seqRow[256];   // bu row per solve index
    uint8_t seqCol[256];   // bu col per solve index
    uint8_t seqCell[256];  // P3: precomputed row*16+col (removes multiply + one lookup in hot scan)
    uint8_t breakArray[256];
    int heurArray[256];
};
static HotTables HOT;
#define SEQ_ROW HOT.seqRow
#define SEQ_COL HOT.seqCol
#define BREAK_ARRAY HOT.breakArray
#define HEUR_ARRAY HOT.heurArray
static int FILL_IDX[256];                  // bu cellIdx -> solve index
static int FIRST_BREAK_IDX = 256;
static constexpr int MAX_HEUR_IDX = 160;
// Cost-funnel depth thresholds, and the total mismatch budget of the schedule.
static constexpr int FUNNEL_TH[4] = {244, 248, 250, 252};
static int TOTAL_BUDGET = 0;               // BREAK_ARRAY[255], or the tail target

static std::atomic<bool> g_stop{false};
static std::atomic<bool> g_tailCaptured{false};   // P7-A: capture only the first matching rung
static std::atomic<uint64_t> g_hallChecks{0}, g_hallCuts{0};   // P7-C Hall telemetry
static std::atomic<int> g_bestScore{0};
static std::mutex g_saveMutex;
static FILE* g_log = nullptr;

struct alignas(64) ThreadStats {
    std::atomic<uint64_t> nodes{0}, placements{0}, restarts{0}, completions{0};
    std::atomic<uint64_t> tailCalls{0}, tailNodes{0};
    std::atomic<uint64_t> adaptiveCalls[4] = {};
    std::atomic<uint64_t> adaptiveNodes[4] = {};
    std::atomic<uint64_t> adaptiveCapped[4] = {};
    std::atomic<int> maxDepthEver{0};
    std::atomic<uint64_t> depthHist[257] = {}; // attempt-end max depth histogram
    std::atomic<uint64_t> placeHist[256] = {}; // pièces posées par case (fill index) — heatmap dashboard
    // Cost funnel: [threshold][slack] = attempts that reached depth >= FUNNEL_TH[k]
    // while still holding >= slack budget in reserve. Raw depth is a mirage —
    // every banked depth-250 prefix had spent its whole budget and still needed
    // 4-10 more mismatches. Reaching depth 248 with 3 unspent is the event that
    // actually precedes a completion; this is the A/B fitness signal.
    std::atomic<uint64_t> costFunnel[4][6] = {};
    // exact-endgame accounting. endgameGrid[slack][cost] counts calls that
    // arrived with `slack` budget unspent and whose cheapest exact filling of the
    // suffix cost `cost` further mismatches (cost 15 = none under the ceiling).
    // This joint distribution is what decides the schedule: a completion needs
    // cost <= slack, and P(cost <= s) rises steeply in s, so it prices "one more
    // unit of reserve" against the arrival rate that buying it costs.
    std::atomic<uint64_t> endgameCalls{0}, endgameCapped{0}, endgameNodes{0};
    std::atomic<uint64_t> endgameGrid[8][16] = {};
    // attemptYield[b] = attempts whose useful-arrival count fell in bucket b
    // (0, 1, 2-3, 4-7, ... 4096+). If yield is heavy-tailed then bottom halves
    // differ in kind, not luck, and re-exploring a good one beats resampling.
    std::atomic<uint64_t> attemptYield[14] = {};
    // ring-colour share of the cheapest completion each endgame call found
    std::atomic<uint64_t> endgameRing[16] = {};
    // escalated (wide-rewind) results: [gap] where gap = cost - budget, 15 = none
    static constexpr int MAX_RUNGS = 4;
    std::atomic<uint64_t> escCalls[MAX_RUNGS] = {}, escCapped[MAX_RUNGS] = {};
    std::atomic<uint64_t> escStarted[MAX_RUNGS] = {};  // incremented BEFORE the call (in-flight visibility)
    std::atomic<uint64_t> escInflightNodes[MAX_RUNGS] = {};  // live node count of the in-flight rung (for % / ETA)
    std::atomic<uint64_t> escNodes[MAX_RUNGS] = {};
    std::atomic<uint64_t> escGapHist[MAX_RUNGS][16] = {};
    uint64_t depthNodes[257] = {};             // nodes spent at each depth (--stats)
    uint64_t depthFits[257] = {};              // perfect placements per depth (--stats)
    uint64_t depthHalf[257] = {};              // break placements per depth (--stats)
};
static std::vector<ThreadStats> g_stats;

// --------------------------------------------------------------------- logging

static void logf(const char* fmt, ...) {
    char buf[2048];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof buf, fmt, ap);
    va_end(ap);
    time_t t = time(nullptr);
    struct tm tmv;
    localtime_r(&t, &tmv);
    char ts[32];
    strftime(ts, sizeof ts, "%Y-%m-%d %H:%M:%S", &tmv);
    std::lock_guard<std::mutex> lk(g_saveMutex);
    printf("[%s] %s\n", ts, buf);
    fflush(stdout);
    if (g_log) { fprintf(g_log, "[%s] %s\n", ts, buf); fflush(g_log); }
}

[[noreturn]] static void die(const char* fmt, ...) {
    char buf[2048];
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof buf, fmt, ap);
    va_end(ap);
    fprintf(stderr, "FATAL: %s\n", buf);
    exit(1);
}

// ------------------------------------------------------------------------ rng

struct Rng { // xoshiro256++, split-seeded
    uint64_t s[4];
    explicit Rng(uint64_t seed) {
        uint64_t x = seed;
        for (auto& v : s) { // splitmix64
            x += 0x9e3779b97f4a7c15ULL;
            uint64_t z = x;
            z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
            z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
            v = z ^ (z >> 31);
        }
    }
    static uint64_t rotl(uint64_t x, int k) { return (x << k) | (x >> (64 - k)); }
    uint64_t next() {
        uint64_t r = rotl(s[0] + s[3], 23) + s[0];
        uint64_t t = s[1] << 17;
        s[2] ^= s[0]; s[3] ^= s[1]; s[1] ^= s[2]; s[0] ^= s[3]; s[2] ^= t;
        s[3] = rotl(s[3], 45);
        return r;
    }
    uint32_t below(uint32_t n) { return (uint32_t)(next() % n); }
};

// ------------------------------------------------------------------- geometry

static inline uint8_t sideAfterRot(const Piece& p, int rot, int face) {
    // face: 0=N 1=E 2=S 3=W; rotated cycle: out[i] = canon[(i - rot) mod 4]
    const uint8_t c[4] = {p.n, p.e, p.s, p.w};
    return c[((face - rot) % 4 + 4) % 4];
}

#ifdef BW_FLUX_LEDGER
// Construit le ledger de flux (min_r/max_r de F·λ par couleur/direction sur les 4 rotations). Appelé
// une fois après loadPieces (PIECES prêt). Défini ici pour voir PIECES/sideAfterRot et le logf custom.
static void buildFluxLedger() {
    for (int p = 1; p <= 256; p++)
        for (int c = 0; c < NCOLORS; c++) {
            FLUX.minFx[p][c] = FLUX.minFy[p][c] = 127;
            FLUX.maxFx[p][c] = FLUX.maxFy[p][c] = -127;
        }
    for (int p = 1; p <= 256; p++) {
        for (int rot = 0; rot < 4; rot++) {
            int N = sideAfterRot(PIECES[p], rot, 0), E = sideAfterRot(PIECES[p], rot, 1);
            int S = sideAfterRot(PIECES[p], rot, 2), W = sideAfterRot(PIECES[p], rot, 3);
            for (int c = 1; c < NCOLORS; c++) {   // couleur 0 (cadre) : λ=0, ignorée
                int fx = (E == c) - (W == c);     // F·λ pour l'indicateur (c, x)
                int fy = (N == c) - (S == c);     // F·λ pour l'indicateur (c, y)
                if (fx < FLUX.minFx[p][c]) FLUX.minFx[p][c] = (int8_t)fx;
                if (fx > FLUX.maxFx[p][c]) FLUX.maxFx[p][c] = (int8_t)fx;
                if (fy < FLUX.minFy[p][c]) FLUX.minFy[p][c] = (int8_t)fy;
                if (fy > FLUX.maxFy[p][c]) FLUX.maxFy[p][c] = (int8_t)fy;
            }
        }
    }
    FLUX.built = true;
    logf("LBflux: ledger construit (%d couleurs, indicateurs x+y, Q=1, gate remaining<=%d slack<=%d)",
         NCOLORS - 1, g_fluxGateRemain, g_fluxGateSlack);
}
#endif

// ------------------------------------------------------------- input handling

static void loadPieces(const std::string& path) {
    FILE* f = fopen(path.c_str(), "r");
    if (!f) die("cannot open pieces file %s", path.c_str());
    int t, b, l, r, cnt = 0;
    while (fscanf(f, "%d %d %d %d", &t, &b, &l, &r) == 4) {
        if (cnt >= 256) die("more than 256 pieces");
        ++cnt;
        PIECES[cnt] = {(uint8_t)t, (uint8_t)r, (uint8_t)b, (uint8_t)l}; // file: T B L R
    }
    fclose(f);
    if (cnt != 256) die("expected 256 pieces, got %d", cnt);

    int nc = 0, ns = 0, nm = 0;
    for (int i = 1; i <= 256; i++) {
        const Piece& p = PIECES[i];
        int greys = (p.n == 0) + (p.e == 0) + (p.s == 0) + (p.w == 0);
        PIECE_CLASS[i] = greys == 2 ? 2 : (greys == 1 ? 1 : 0);
        (greys == 2 ? nc : greys == 1 ? ns : nm)++;
    }
    if (nc != 4 || ns != 56 || nm != 196)
        die("piece classes wrong: %d corners %d sides %d middles", nc, ns, nm);
}

// Compute per-piece heuristic side counts for the active color set (called after
// arg parsing so --heur-colors is honored). Also fixes the ramp scale base.
static void computeHsc() {
    // Blackwood's own set {13,16,10} totals 122 edges (13 is a ring color with
    // only 24) — the ramp scale is relative to THAT, so the default reproduces
    // his array exactly (scale 1.0).
    double blackwoodTotal = 0, total = 0;
    for (int i = 1; i <= 256; i++) {
        const Piece& p = PIECES[i];
        uint8_t h = 0;
        for (int hs : HEUR_COLORS)
            h += (p.n == hs) + (p.e == hs) + (p.s == hs) + (p.w == hs);
        PIECE_HSC[i] = h;
        total += h;
        for (int hs : {13, 16, 10})
            blackwoodTotal += (p.n == hs) + (p.e == hs) + (p.s == hs) + (p.w == hs);
    }
    HEUR_EDGE_TOTAL = 150.0 * total / blackwoodTotal;   // buildHeurArray divides by 150
    std::string cs;
    for (int c : HEUR_COLORS) cs += (cs.empty() ? "" : ",") + std::to_string(c);
    logf("heuristic colors: {%s}, total edges %.0f (ramp scale x%.3f)",
         cs.c_str(), total, total / blackwoodTotal);
}

static void loadHints(const std::string& path) {
    FILE* f = fopen(path.c_str(), "r");
    if (!f) die("cannot open hints file %s", path.c_str());
    char line[256];
    while (fgets(line, sizeof line, f)) {
        if (line[0] == '#' || line[0] == '\n') continue;
        Hint h;
        if (sscanf(line, "%d %d %d %d", &h.piece, &h.tdRow, &h.tdCol, &h.rot) == 4)
            HINTS.push_back(h);
    }
    fclose(f);
    if (HINTS.empty() || HINTS.size() > 5)
        die("expected 1-5 hints, got %zu", HINTS.size());
    bool haveCenter = false;
    for (const Hint& h : HINTS) {
        if (PIECE_CLASS[h.piece] != 0) die("clue piece %d is not interior", h.piece);
        if (IS_CLUE[h.piece]) die("duplicate hint for piece %d", h.piece);
        IS_CLUE[h.piece] = true;
        if (h.tdRow == 8 && h.tdCol == 7) haveCenter = true;
    }
    // The one-clue record-line mode is defined by the official centre clue.
    // Full-clue runs may rotate the entire instance to search the same puzzle
    // from another corner; on an even board that moves the centre clue among
    // the four central cells, while all five clues remain forced.
    if (HINTS.size() == 1 && !haveCenter)
        die("no hint at td(8,7): the mandatory center piece must always be fixed "
            "(all record-line configurations keep it)");
}

// Select fill order + config defaults by clue mode. Startup-only; the DFS reads
// the derived SEQ/FILL arrays, so this has zero effect on placements/sec.
static int ORDER_CUSTOM[16][16];

// Alternative center-only fill orders (GAUNTLET portfolio). Both keep the
// west-and-south-first invariant the DFS requires; the startup validator checks.
static void buildCustomOrder(const std::string& name) {
    auto set = [](int fi, int buRow, int col) { ORDER_CUSTOM[15 - buRow][col] = fi; };
    if (name == "colband") {          // columns left->right, each bottom->top
        for (int fi = 0; fi < 256; fi++) set(fi, fi & 15, fi >> 4);
    } else if (name == "comb") {      // bottom 8 rows raster, then 8-cell teeth
        for (int fi = 0; fi < 128; fi++) set(fi, fi >> 4, fi & 15);
        for (int fi = 128; fi < 256; fi++)
            set(fi, 8 + ((fi - 128) & 7), (fi - 128) >> 3);
    } else {
        die("unknown --fill-order %s (raster|colband|comb)", name.c_str());
    }
    BOARD_ORDER = ORDER_CUSTOM;
}

// P4c : charge un ordre de remplissage custom full-clue depuis un fichier (256 entiers,
// row-major td-frame : fichier[r*16+c] = fill index de la cellule td (r,c), r=0 en haut).
// bijection + precedences west/south verifiees par buildStaticArrays (die si mauvais).
// tailConfigHash() hashe seqRow/seqCol -> ce cfgHash DIVERGE du live -> ATTSTATE rejete.
static void loadBoardOrderFile(const std::string& path) {
    FILE* f = fopen(path.c_str(), "r");
    if (!f) die("cannot open --board-order file %s", path.c_str());
    int vals[256]; int n = 0, v;
    while (n < 256 && fscanf(f, "%d", &v) == 1) vals[n++] = v;
    fclose(f);
    if (n != 256) die("--board-order %s: expected 256 indices, got %d", path.c_str(), n);
    for (int i = 0; i < 256; i++) {
        if (vals[i] < 0 || vals[i] > 255) die("--board-order: index %d out of range at cell %d", vals[i], i);
        ORDER_CUSTOM[i / 16][i % 16] = vals[i];   // [td_row][col] = fill index
    }
    BOARD_ORDER = ORDER_CUSTOM;
    logf("board order: CUSTOM from %s (P4c shadow ; cfgHash inclut seqRow/seqCol -> ATTSTATE live rejete)",
         path.c_str());
}

static void applyClueMode() {
    bool centerOnly = HINTS.size() == 1;
    BOARD_ORDER = centerOnly ? BOARD_ORDER_RASTER : BOARD_ORDER_CLUED;
    if (!cfg.fillOrder.empty() && cfg.fillOrder != "raster") {
        if (!centerOnly) die("--fill-order variants are center-only for now");
        buildCustomOrder(cfg.fillOrder);
        logf("fill order: %s (GAUNTLET portfolio)", cfg.fillOrder.c_str());
    }
    if (!cfg.boardOrderFile.empty()) {          // P4c : override full-clue par fichier
        if (centerOnly) die("--board-order requires full-clue mode (5 hints)");
        loadBoardOrderFile(cfg.boardOrderFile);
    }
    if (!cfg.breaksSet && centerOnly) cfg.breaks = DEFAULT_BREAKS_CENTER_ONLY;
    if (!cfg.heurSet) cfg.heurScale = centerOnly ? 1.0 : 0.97;
    logf("clue mode: %s (%zu hints) -> %s fill order, heurScale %.3f%s",
         centerOnly ? "CENTER-ONLY" : "FULL-CLUES", HINTS.size(),
         centerOnly ? "raster" : "corner-first", cfg.heurScale,
         cfg.heurSet ? " (explicit)" : " (mode default)");
}

// ------------------------------------------------------- candidate enumeration

// Enumerate placement candidates of one piece into `base`.
//   rotFilter   : -1 any rotation, else exactly that rotation
//   maxBr       : max mismatches per placement (0 exact, 1 single, 2 double —
//                 REPLAY finding: community 460-class boards need double-break
//                 cells that single-break engines cannot represent)
//   allowRing   : also emit mismatches on a ring colour. Ring colours occur only
//                 on the lateral edges of border pieces, so Blackwood's ban keeps
//                 the 60-seam frame cycle perfect; measured on 300 banked
//                 depth-250 prefixes, 78% of them cannot be completed AT ALL
//                 under that ban, at any budget. Ring mismatches must come in
//                 pairs (each ring colour has exactly 24 edges, so a single
//                 mismatch leaves an odd count that cannot pair up), hence they
//                 cost at least 2 of the budget and belong in the reserve.
//   reqTop/reqRight : -1 none, else rotated piece must show this color N / E
static void enumeratePiece(std::vector<SortEntry>& base, int pieceNo,
                           int rotFilter, int maxBr, bool allowRing = false,
                           int reqTop = -1, int reqRight = -1) {
    const Piece& p = PIECES[pieceNo];
    for (int rot = 0; rot < 4; rot++) {
        if (rotFilter >= 0 && rot != rotFilter) continue;
        uint8_t nn = sideAfterRot(p, rot, 0), ee = sideAfterRot(p, rot, 1),
                ss = sideAfterRot(p, rot, 2), ww = sideAfterRot(p, rot, 3);
        if (reqTop >= 0 && nn != reqTop) continue;
        if (reqRight >= 0 && ee != reqRight) continue;
        for (int left = 0; left < NCOLORS; left++) {
            for (int bottom = 0; bottom < NCOLORS; bottom++) {
                int breaks = 0;
                bool ringBreak = false;
                if (ww != left) { breaks++; ringBreak |= IS_RING_COLOR[ww]; }
                if (ss != bottom) { breaks++; ringBreak |= IS_RING_COLOR[ss]; }
                if (breaks > maxBr || (ringBreak && !allowRing)) continue;
                SortEntry e;
                // pad = direction du break (bit0=ouest ww!=left, bit1=sud ss!=bottom), pour --break-mask (spatial per-seam)
                int breakDir = (ww != left ? 1 : 0) | (ss != bottom ? 2 : 0);
                e.rp = {(uint16_t)pieceNo, (uint8_t)rot, nn, ee,
                        (uint8_t)breaks, PIECE_HSC[pieceNo], (uint8_t)breakDir};
                e.key = left * NCOLORS + bottom;
                e.sortKey = 0;
                base.push_back(e);
            }
        }
    }
}

// Tables owned per thread (sorted with fresh jitter each restart).
struct Tables {
    Table corners, leftSides, bottomSides, topSides;
    Table rightNoBrk, rightBrk, midNoBrk, midBrk;
    // --ring-breaks variants: same piece classes, but a lateral (ring-colour)
    // seam may mismatch. Only cells whose fill index is >= cfg.ringDepth point
    // at these, so the hot loop pays nothing for the wider space — the cell ->
    // table map is fixed at startup exactly like the late/early break split.
    Table cornersRing, leftSidesRing, bottomSidesRing, topSidesRing, rightBrkRing;
    std::vector<Table> special;          // clue + neighbor-filtered tables
    const Table* lookup[256] = {nullptr}; // bu cellIdx -> table
};

static void finalizeTable(Table& t) {
    std::stable_sort(t.base.begin(), t.base.end(),
                     [](const SortEntry& a, const SortEntry& b) { return a.key < b.key; });
    uint32_t cnt[530] = {0};
    for (const auto& e : t.base) cnt[e.key + 1]++;
    for (int k = 1; k < 530; k++) cnt[k] += cnt[k - 1];
    memcpy(t.off, cnt, sizeof t.off);
    t.pool.resize(t.base.size());
}

#ifdef BW_EARLY_BREAKS
// bornes de classe breakCount (slices déjà triées breakCount-primaire) : clsB1=1er
// index breakCount>=1, clsB2=1er breakCount>=2, RELATIFS au début de slice.
static void computeClassBounds(Table& t) {
    for (int k = 0; k < 529; k++) {
        uint32_t a = t.off[k], b = t.off[k + 1];
        uint32_t r1 = b - a, r2 = b - a;
        for (uint32_t i = a; i < b; i++) {
            int bc = (int)t.base[i].rp.breakCount;
            if (bc >= 1 && r1 == b - a) r1 = i - a;
            if (bc >= 2 && r2 == b - a) { r2 = i - a; break; }
        }
        t.clsB1[k] = (uint16_t)(r1 > 65535 ? 65535 : r1);
        t.clsB2[k] = (uint16_t)(r2 > 65535 ? 65535 : r2);
    }
}
#endif

#ifdef BW_BLOCK_MASK
// Précalcule les masques de bloc (64 entrées) : blockMask[g] = OR des (1<<(piece-1)) du bloc g.
static void computeBlockMasks(Table& t) {
    size_t n = t.pool.size();
    size_t nb = (n + 63) / 64;
    t.blockMask.assign(nb * 4, 0);
    for (size_t i = 0; i < n; i++) {
        int p = t.pool[i].pieceNumber;           // PoolElem = RotatedPiece (build défaut)
        if (p >= 1 && p <= 256) {
            int bit = p - 1;
            t.blockMask[(i / 64) * 4 + (bit >> 6)] |= (1ULL << (bit & 63));
        }
    }
    // frontières de classe breakCount (slice triée breakCount-primaire) — RELATIVES
    for (int k = 0; k < 529; k++) {
        uint32_t a = t.off[k], b = t.off[k + 1];
        uint32_t r1 = b - a, r2 = b - a;
        for (uint32_t i = a; i < b; i++) {
            int bc = (int)t.pool[i].breakCount;
            if (bc >= 1 && r1 == b - a) r1 = i - a;
            if (bc >= 2) { r2 = i - a; break; }
        }
        t.bmClsB1[k] = (uint16_t)(r1 > 65535 ? 65535 : r1);
        t.bmClsB2[k] = (uint16_t)(r2 > 65535 ? 65535 : r2);
    }
}
#endif

static void sortTableForRestart(Table& t, Rng& rng) {
    for (auto& e : t.base)
        e.sortKey = -100000 * (int)e.rp.breakCount + 100 * (int)e.rp.hsc +
                    (int)rng.below(100);
    // (breakCount primaire -> classes contiguës)
    // per-key slices: stable partition by key already; sort each slice by sortKey desc
    size_t n = t.base.size();
    for (int k = 0; k < 529; k++) {
        uint32_t a = t.off[k], b = t.off[k + 1];
        if (b - a > 1)
            std::sort(t.base.begin() + a, t.base.begin() + b,
                      [](const SortEntry& x, const SortEntry& y) {
                          return x.sortKey > y.sortKey;
                      });
    }
    for (size_t i = 0; i < n; i++) t.pool[i] = packRP(t.base[i].rp);
#ifdef BW_BLOCK_MASK
    computeBlockMasks(t);
#endif
#ifdef BW_EARLY_BREAKS
    computeClassBounds(t);
#endif
}

// The bu row0 table gets Blackwood's special first-row ordering.
static void sortBottomRowForRestart(Table& t, Rng& rng) {
    for (auto& e : t.base)
#ifdef BW_EARLY_BREAKS
        // breakCount primaire pour garder les classes contiguës (scan par classe correct)
        e.sortKey = -100000 * (int)e.rp.breakCount + (e.rp.hsc > 0 ? 100 : 0) + (int)rng.below(100);
#else
        e.sortKey = (e.rp.hsc > 0 ? 100 : 0) + (int)rng.below(100);
#endif
    for (int k = 0; k < 529; k++) {
        uint32_t a = t.off[k], b = t.off[k + 1];
        if (b - a > 1)
            std::sort(t.base.begin() + a, t.base.begin() + b,
                      [](const SortEntry& x, const SortEntry& y) {
                          return x.sortKey > y.sortKey;
                      });
    }
    for (size_t i = 0; i < t.base.size(); i++) t.pool[i] = packRP(t.base[i].rp);
#ifdef BW_BLOCK_MASK
    computeBlockMasks(t);
#endif
#ifdef BW_EARLY_BREAKS
    computeClassBounds(t);
#endif
}

static void buildTables(Tables& T) {
    // generic pools ------------------------------------------------------
    for (int i = 1; i <= 256; i++) {
        switch (PIECE_CLASS[i]) {
            case 2: enumeratePiece(T.corners.base, i, -1, 0); break;
            case 1: {
                const Piece& p = PIECES[i];
                // canonical side piece has grey south; rot k puts grey at S,W,N,E
                for (int rot = 0; rot < 4; rot++) {
                    if (sideAfterRot(p, rot, 2) == 0)       // grey south -> bottom row
                        enumeratePiece(T.bottomSides.base, i, rot, 0);
                    if (sideAfterRot(p, rot, 3) == 0)       // grey west -> left col
                        enumeratePiece(T.leftSides.base, i, rot, 0);
                    if (sideAfterRot(p, rot, 0) == 0)       // grey north -> top row
                        enumeratePiece(T.topSides.base, i, rot, cfg.cellBreaks);
                    if (sideAfterRot(p, rot, 1) == 0) {     // grey east -> right col
                        enumeratePiece(T.rightNoBrk.base, i, rot, 0);
                        enumeratePiece(T.rightBrk.base, i, rot, cfg.cellBreaks);
                    }
                }
                break;
            }
            case 0:
                if (!IS_CLUE[i]) {
                    enumeratePiece(T.midNoBrk.base, i, -1, 0);
                    enumeratePiece(T.midBrk.base, i, -1, cfg.cellBreaks);
                }
                break;
        }
    }
    // ring-widened border pools (only built when the feature is on) ------
    // For a border cell the two seams closed at placement time are one frame
    // side (always grey, always matched) and one lateral ring seam, so under the
    // ban these tables hold no break candidates at all for their ring seam:
    // corners/leftSides/bottomSides are strictly exact today, and topSides /
    // rightBrk can only break on their single interior-facing seam.
    if (cfg.ringDepth) {
        for (int i = 1; i <= 256; i++) {
            const Piece& p = PIECES[i];
            switch (PIECE_CLASS[i]) {
                case 2: enumeratePiece(T.cornersRing.base, i, -1, cfg.cellBreaks, true); break;
                case 1:
                    for (int rot = 0; rot < 4; rot++) {
                        if (sideAfterRot(p, rot, 2) == 0)
                            enumeratePiece(T.bottomSidesRing.base, i, rot, cfg.cellBreaks, true);
                        if (sideAfterRot(p, rot, 3) == 0)
                            enumeratePiece(T.leftSidesRing.base, i, rot, cfg.cellBreaks, true);
                        if (sideAfterRot(p, rot, 0) == 0)
                            enumeratePiece(T.topSidesRing.base, i, rot, cfg.cellBreaks, true);
                        if (sideAfterRot(p, rot, 1) == 0)
                            enumeratePiece(T.rightBrkRing.base, i, rot, cfg.cellBreaks, true);
                    }
                    break;
                default: break;
            }
        }
        finalizeTable(T.cornersRing);
        finalizeTable(T.leftSidesRing);
        finalizeTable(T.bottomSidesRing);
        finalizeTable(T.topSidesRing);
        finalizeTable(T.rightBrkRing);
    }
    finalizeTable(T.corners);
    finalizeTable(T.leftSides);
    finalizeTable(T.bottomSides);
    finalizeTable(T.topSides);
    finalizeTable(T.rightNoBrk);
    finalizeTable(T.rightBrk);
    finalizeTable(T.midNoBrk);
    finalizeTable(T.midBrk);

    // default per-cell assignment ----------------------------------------
    for (int ci = 0; ci < 256; ci++) {
        int row = ci / 16, col = ci % 16, fi = FILL_IDX[ci];
        bool late = fi >= FIRST_BREAK_IDX;
        bool ring = cfg.ringDepth && fi >= cfg.ringDepth;
        if (row == 0)
            T.lookup[ci] = (col == 15) ? (ring ? &T.cornersRing : &T.corners)
                                       : (ring ? &T.bottomSidesRing : &T.bottomSides);
        else if (row == 15)
            T.lookup[ci] = (col == 0 || col == 15)
                               ? (ring ? &T.cornersRing : &T.corners)
                               : (ring ? &T.topSidesRing : &T.topSides);
        else if (col == 0)
            T.lookup[ci] = ring ? &T.leftSidesRing : &T.leftSides;
        else if (col == 15)
            T.lookup[ci] = ring ? &T.rightBrkRing
                                : (late ? &T.rightBrk : &T.rightNoBrk);
        else
            T.lookup[ci] = late ? &T.midBrk : &T.midNoBrk;
    }

    // clue cells + neighbor-filtered cells --------------------------------
    // reserve so pointers into T.special stay valid
    T.special.reserve(HINTS.size() * 3);
    for (const Hint& h : HINTS) {
        int bur = 15 - h.tdRow, buc = h.tdCol;
        int ci = bur * 16 + buc;
        const Piece& p = PIECES[h.piece];
        uint8_t clueW = sideAfterRot(p, h.rot, 3), clueS = sideAfterRot(p, h.rot, 2);
        uint8_t clueN = sideAfterRot(p, h.rot, 0), clueE = sideAfterRot(p, h.rot, 1);
        (void)clueN; (void)clueE;

        // the clue cell itself: single piece, fixed rotation, exact match only
        T.special.emplace_back();
        enumeratePiece(T.special.back().base, h.piece, h.rot, 0);
        finalizeTable(T.special.back());
        T.lookup[ci] = &T.special.back();

        // west neighbor: must show east == clue's west
        int wci = ci - 1;
        bool wLate = FILL_IDX[wci] >= FIRST_BREAK_IDX;
        T.special.emplace_back();
        for (int i = 1; i <= 256; i++)
            if (PIECE_CLASS[i] == 0 && !IS_CLUE[i])
                enumeratePiece(T.special.back().base, i, -1, wLate ? cfg.cellBreaks : 0,
                               false, -1, clueW);
        finalizeTable(T.special.back());
        T.lookup[wci] = &T.special.back();

        // south neighbor: must show north == clue's south
        int sci = ci - 16;
        bool sLate = FILL_IDX[sci] >= FIRST_BREAK_IDX;
        T.special.emplace_back();
        for (int i = 1; i <= 256; i++)
            if (PIECE_CLASS[i] == 0 && !IS_CLUE[i])
                enumeratePiece(T.special.back().base, i, -1, sLate ? cfg.cellBreaks : 0,
                               false, clueS, -1);
        finalizeTable(T.special.back());
        T.lookup[sci] = &T.special.back();
    }
    static std::atomic<bool> dumped{false};
    bool expect = false;
    if (dumped.compare_exchange_strong(expect, true)) {
        logf("table sizes: corners %zu leftSides %zu bottomSides %zu topSides %zu "
             "rightNoBrk %zu rightBrk %zu midNoBrk %zu midBrk %zu",
             T.corners.base.size(), T.leftSides.base.size(), T.bottomSides.base.size(),
             T.topSides.base.size(), T.rightNoBrk.base.size(), T.rightBrk.base.size(),
             T.midNoBrk.base.size(), T.midBrk.base.size());
        if (cfg.ringDepth) {
            int ringCells = 0;
            for (int ci = 0; ci < 256; ci++) {
                int row = ci / 16, col = ci % 16;
                if ((row == 0 || row == 15 || col == 0 || col == 15) &&
                    FILL_IDX[ci] >= cfg.ringDepth)
                    ringCells++;
            }
            logf("ring-break tables (from fill depth %d, %d border cells): corners %zu "
                 "leftSides %zu bottomSides %zu topSides %zu rightBrk %zu",
                 cfg.ringDepth, ringCells, T.cornersRing.base.size(),
                 T.leftSidesRing.base.size(), T.bottomSidesRing.base.size(),
                 T.topSidesRing.base.size(), T.rightBrkRing.base.size());
        }
        for (size_t i = 0; i < T.special.size(); i++)
            logf("special[%zu] (%s of clue %d): %zu entries",
                 i, i % 3 == 0 ? "cell" : (i % 3 == 1 ? "west-nb" : "south-nb"),
                 HINTS[i / 3].piece, T.special[i].base.size());
    }
}

// --------------------------------------------------------------- verification

// Independent rescoring of a completed board. Returns matched edges (of 480),
// or -1 if the board is structurally invalid (bad frame / piece reuse / clue moved).
static int verifyBoard(const RotatedPiece* board) {
    bool used[257] = {false};
    for (int ci = 0; ci < 256; ci++) {
        int pn = board[ci].pieceNumber;
        if (pn < 1 || pn > 256 || used[pn]) return -1;
        used[pn] = true;
    }
    for (const Hint& h : HINTS) {
        int ci = (15 - h.tdRow) * 16 + h.tdCol;
        if (board[ci].pieceNumber != h.piece || board[ci].rot != h.rot) return -1;
    }
    int matched = 0;
    for (int r = 0; r < 16; r++) {
        for (int c = 0; c < 16; c++) {
            int ci = r * 16 + c;
            const Piece& p = PIECES[board[ci].pieceNumber];
            int rot = board[ci].rot;
            uint8_t nn = sideAfterRot(p, rot, 0), ee = sideAfterRot(p, rot, 1),
                    ss = sideAfterRot(p, rot, 2), ww = sideAfterRot(p, rot, 3);
            if (r == 0 && ss != 0) return -1;   // frame must be grey
            if (r == 15 && nn != 0) return -1;
            if (c == 0 && ww != 0) return -1;
            if (c == 15 && ee != 0) return -1;
            if (c < 15) { // east seam
                const Piece& q = PIECES[board[ci + 1].pieceNumber];
                if (ee == sideAfterRot(q, board[ci + 1].rot, 3)) matched++;
            }
            if (r < 15) { // north seam (bu)
                const Piece& q = PIECES[board[ci + 16].pieceNumber];
                if (nn == sideAfterRot(q, board[ci + 16].rot, 2)) matched++;
            }
        }
    }
    return matched;
}

// internal color -> official `jef` motif letter (piecewise reflection, verified
// against the canonical Clues board_edges via the 5 forced clue pieces)
static inline char jefLetter(int c) {
    int i = c == 0 ? 0 : c <= 8 ? 9 - c : c <= 16 ? 25 - c : 39 - c;
    return (char)('a' + i);
}

static void saveBoard(const RotatedPiece* board, int score, int threadId,
                      uint64_t attemptSeed) {
    std::lock_guard<std::mutex> lk(g_saveMutex);
    char path[512], tmp[520];
    time_t t = time(nullptr);
    snprintf(path, sizeof path, "%s/board_%d_%ld_t%d.txt", cfg.saveDir.c_str(),
             score, (long)t, threadId);
    snprintf(tmp, sizeof tmp, "%s.tmp", path);
    FILE* f = fopen(tmp, "w");
    if (!f) { fprintf(stderr, "SAVE FAILED: %s\n", tmp); return; }
    // td row-major pieceID/rot — same format as the existing campaign boards
    for (int tdr = 0; tdr < 16; tdr++) {
        int bur = 15 - tdr;
        for (int c = 0; c < 16; c++) {
            const RotatedPiece& rp = board[bur * 16 + c];
            fprintf(f, "%d/%d%s", rp.pieceNumber, rp.rot, c == 15 ? "\n" : " ");
        }
    }
    fclose(f);
    rename(tmp, path);

    // sidecar metadata + bucas viewer URL (our colors == Blackwood's labels)
    snprintf(tmp, sizeof tmp, "%s.meta", path);
    f = fopen(tmp, "w");
    if (f) {
        fprintf(f, "score %d/480\nthread %d\nattempt_seed %" PRIu64 "\nbreaks %s\n",
                score, threadId, attemptSeed, cfg.breaks.c_str());
        // fill indices that actually consumed a break (for schedule tuning)
        fprintf(f, "breaks_used");
        for (int fi = 0; fi < 256; fi++) {
            int ci = SEQ_ROW[fi] * 16 + SEQ_COL[fi];
            if (board[ci].breakCount) fprintf(f, " %d", fi);
        }
        fprintf(f, "\n");
        fprintf(f, "https://e2.bucas.name/#puzzle=Joshua_Blackwood&board_w=16&board_h=16&board_edges=");
        for (int tdr = 0; tdr < 16; tdr++) {
            int bur = 15 - tdr;
            for (int c = 0; c < 16; c++) {
                const RotatedPiece& rp = board[bur * 16 + c];
                const Piece& p = PIECES[rp.pieceNumber];
                for (int face = 0; face < 4; face++)
                    fputc('a' + sideAfterRot(p, rp.rot, face), f);
            }
        }
        fprintf(f, "&motifs_order=jblackwood\n");
        // same board in the standard jef/Clues space (renders official motif art)
        fprintf(f, "https://e2.bucas.name/#puzzle=Clues&board_w=16&board_h=16&board_edges=");
        for (int tdr = 0; tdr < 16; tdr++) {
            int bur = 15 - tdr;
            for (int c = 0; c < 16; c++) {
                const RotatedPiece& rp = board[bur * 16 + c];
                const Piece& p = PIECES[rp.pieceNumber];
                for (int face = 0; face < 4; face++)
                    fputc(jefLetter(sideAfterRot(p, rp.rot, face)), f);
            }
        }
        fprintf(f, "&board_pieces=");
        for (int tdr = 0; tdr < 16; tdr++)
            for (int c = 0; c < 16; c++)
                fprintf(f, "%03d", board[(15 - tdr) * 16 + c].pieceNumber);
        fprintf(f, "&motifs_order=jef\n");
        fclose(f);
    }

    FILE* bs = fopen((cfg.saveDir + "/best_score.txt.tmp").c_str(), "w");
    if (bs) {
        fprintf(bs, "%d\n", g_bestScore.load());
        fclose(bs);
        rename((cfg.saveDir + "/best_score.txt.tmp").c_str(),
               (cfg.saveDir + "/best_score.txt").c_str());
    }
}

// Preserve exceptionally deep incomplete paths for stronger offline endgame
// work.  Depth 250 supplies the exact finishers, while the much rarer 252+
// records retain the precise paths that made those funnel hits valuable.  Zero
// placements are explicit as 0/0.
static void saveDeepPrefix(const RotatedPiece* board, int depth, int breaksUsed,
                           int threadId, uint64_t attemptSeed) {
    std::lock_guard<std::mutex> lk(g_saveMutex);
    char path[512], tmp[520];
    snprintf(path, sizeof path, "%s/prefix_%d_seed%" PRIu64 "_t%d.txt",
             cfg.saveDir.c_str(), depth, attemptSeed, threadId);
    snprintf(tmp, sizeof tmp, "%s.tmp", path);
    FILE* f = fopen(tmp, "w");
    if (!f) { fprintf(stderr, "PREFIX SAVE FAILED: %s\n", tmp); return; }
    for (int tdr = 0; tdr < 16; tdr++) {
        int bur = 15 - tdr;
        for (int c = 0; c < 16; c++) {
            const RotatedPiece& rp = board[bur * 16 + c];
            fprintf(f, "%d/%d%s", rp.pieceNumber, rp.rot,
                    c == 15 ? "\n" : " ");
        }
    }
    fclose(f);
    rename(tmp, path);
    snprintf(tmp, sizeof tmp, "%s.meta", path);
    f = fopen(tmp, "w");
    if (f) {
        fprintf(f, "depth %d/256\nbreaks_used %d\nthread %d\nattempt_seed %" PRIu64
                   "\nbreaks %s\ntail_target_score %d\n",
                depth, breaksUsed, threadId, attemptSeed, cfg.breaks.c_str(),
                cfg.tailTargetScore >= 0
                    ? cfg.tailTargetScore
                    : 480 - BREAK_ARRAY[255]);
        fclose(f);
    }
}

// Exact cold-path solver for the last few cells.  The main engine deliberately
// uses one extremely cheap topological order; once per restart, at --tail-mrv
// depth, this routine tries the same leftover pool with a most-constrained-cell
// order.  It scores every newly closed seam exactly, so unlike the fast tables
// it may also use a ring-colour mismatch when that still fits the target budget.
// Any result is independently checked by verifyBoard before it can be saved.

// P7-B: a disjoint sub-search unit. Snapshot of the board/occupancy after the first
// `depth` MRV placements plus the running cost; a worker restores it and continues.
struct TailCube {
    RotatedPiece board[256];
    bool used[257];
    int running;   // cost accumulated by the `depth` placements
    int depth;     // number of tail cells already placed (== generation cubeDepth)
};
// P8-B compact cube identity: the explicit placements of the occupied tail cells,
// so 1.12M cubes cost ~56 MB (paths) instead of 2.5 GB (boards). Reconstruct by
// applying these placements to the rewound board, then continue MRV from depth.
static constexpr int PATHCUBE_CAP = 48;   // >= largest tail (r216 = 40 cells); never truncate
struct PathCube {
    uint8_t depth;
    uint8_t cell[PATHCUBE_CAP];
    uint16_t piece[PATHCUBE_CAP];
    uint8_t rot[PATHCUBE_CAP];
    int running;
};
static std::atomic<bool> g_pathOverflow{false};   // fail-fast: a path exceeded PATHCUBE_CAP
static std::atomic<bool> g_hashCollision{false};  // fail-fast: two distinct paths, same 128-bit id

struct TailMrvState {
    RotatedPiece* board;
    bool* used;
    bool inTail[256] = {};
    bool placed[256] = {};
    int cells[256] = {};
    int nCells = 0;
#ifdef BW_TAIL_FREELIST
    int freeList[256] = {};   // pièces initialement libres (used==false à l'entrée), ordre ascendant. Construit au depth 0.
    int nFree = 0;
#endif
#ifdef BW_TAIL_PLACEMENT_MASK
    uint64_t availPlacement[16] = {};   // bit (p-1)*4+rot <=> pièce p libre. Init depth 0, maj O(1) pose/undo.
    bool availInit = false;
#endif
    int cluePiece[256] = {};
    int clueRot[256] = {};
    uint64_t nodes = 0, nodeCap = 0;
    int budget = 0;
    int solvedScore = -1;
    bool capped = false;
    // Branch and bound on total mismatches: bestCost is the cheapest complete
    // filling found so far (budget + 1 while none is known), and bestBoard keeps
    // it. Searching for the minimum rather than the first admissible filling
    // costs nothing extra — the incumbent replaces the fixed budget as the
    // pruning bound — and it means a call can return 466 where the old
    // first-solution search would have stopped at 465.
    int bestCost = 0;
    int sup[NCOLORS] = {0};         // colour supply of the still-unplaced pieces
#ifdef BW_MRV_DEM_INCREMENTAL
    int dem[NCOLORS] = {0};         // demande-offre MAINTENUE incrémentalement (état du nœud courant) ;
                                    // init full au depth 0, delta lazy O(voisins) par pose, RAII undo.
#endif
    int bestRing = -1;              // ring-colour mismatches in the incumbent
    RotatedPiece bestBoard[256] = {};
    // Parallel tail: partition the depth-0 MRV candidates into sliceN disjoint
    // classes; this worker explores only class sliceS. sliceN==0 disables.
    int sliceS = -1, sliceN = 0;
    // Live progress: published every ~1M nodes so the dashboard can show an in-flight
    // deep-rung's nodes-done / cap = % and an ETA. nullptr = don't publish.
    std::atomic<uint64_t>* progress = nullptr;
    // P7-B parallel cubes: at depth==cubeDepth, record the partial state as a cube
    // and stop (generation), instead of recursing. cubeDepth<0 = normal search.
    int cubeDepth = -1;
    void* cubeOut = nullptr;        // std::vector<TailCube>* (void to avoid fwd-decl churn)
    // P8 sharding: cubes are generated in a deterministic MRV order; cubeCount is
    // the stable cube_id. When [cubeLo,cubeHi) is set, only that index range is
    // kept (one shard). cubeCount always counts ALL cubes reached (for the manifest).
    long cubeCount = 0;
    long cubeLo = -1, cubeHi = -1;
    void* pathOut = nullptr;   // P8-B: std::vector<PathCube>* — record compact paths, not boards
    // Shared incumbent across cube workers: read as the pruning bound (tighter of
    // local/shared), CAS-updated on a better completion. nullptr = local only.
    std::atomic<int>* sharedBest = nullptr;
#ifdef BW_SIGMA_LEDGER
    // LBσ tail : parité initiale du préfixe (XOR des coutures cassées déjà fermées à
    // l'entrée du tail) — passée comme oddMask racine à tailMrvDfs. Voir solveTailMrv.
    uint32_t initOdd = 0;
    bool demSigmaOn = false;
    int demSigGateT = 0;   // A adaptatif (2026-08-19) : n'évalue LBdemSigma QUE si lbDem >= demSigGateT (0 = pas de porte)
    bool sigmaOn = false;           // copie locale de cfg.sigmaLedger (évite un accès global chaud)
#ifdef BW_TAIL_LEDGER_LOCAL
    // Compteurs télémétrie LOCAUX (évitent les atomiques par nœud) ; flush amorti (périodique + racine).
    uint64_t locSigCalls = 0, locWouldCut = 0, locCut = 0, locLeafBug = 0;
    // LBdemSigma (handoff 2026-08-18) : compteurs locaux (pas d'atomiques par nœud).
    uint64_t locDemSigCalls = 0, locDemSigStronger = 0, locDemSigWould = 0, locDemSigCut = 0;
    // A adaptatif (2026-08-19) : distribution des coupes marginales par classe lbDem (0,1,2,3,4,>=5).
    uint64_t locDemSigWClass[6] = {0,0,0,0,0,0};
#endif
#ifdef BW_FLUX_LEDGER
    bool fluxEval = false;          // LBflux : ÉVALUE la borne au gate (compte would-cut) — shadow si !fluxOn
    bool fluxOn = false;            // LBflux : APPLIQUE la coupe max(LBσ,LBflux) au gate tardif
#endif
    // Mode énumération exhaustive (soundness only) : ne resserre PAS bestCost ; recense TOUTES
    // les complétions valides de coût < enumBudget (compteur + hash XOR ordre-indépendant). Sert
    // à prouver que la coupe LBσ ne perd aucun témoin (set identique OFF vs ON).
#ifdef BW_CHECKER_LEDGER
    int16_t checkerA[5] = {};
    uint8_t checkerHist[5][3][5] = {};
    uint8_t checkerBlackLeft[3] = {};
    bool checkerOn = false;
#ifdef BW_TAIL_LEDGER_LOCAL
    uint64_t locCheckerCalls=0, locCheckerStronger=0, locCheckerWould=0, locCheckerCut=0, locCheckerBug=0;
    int locCheckerMaxGain=0;
#endif
#endif
    bool enumerate = false;
    int enumBudget = 0;
    uint64_t enumLeaves = 0, enumHash = 0;
#endif
};

struct AdaptiveTailTier {
    int triggerDepth;
    int rewindDepth;
    uint64_t nodeCap;
};

// A deeper main-DFS record earns a wider exact neighbourhood.  Each rewind
// depth is unique, so these calls do not deterministically repeat the ordinary
// depth-236 sampler or one another.
static constexpr AdaptiveTailTier ADAPTIVE_TAIL_TIERS[4] = {
    {248, 235,   2000000ULL},
    {250, 234,   5000000ULL},
    {252, 232,  50000000ULL},
    // Depth 253 is extremely rare (three hits in the previous 6.5T-node run)
    // and every 100M-node rewind capped.  A 1B cap costs negligible campaign
    // throughput at that frequency and gives the fertile 26-cell suffix a
    // meaningful exact pass.
    {253, 230, 1000000000ULL},
};

#ifdef BW_PRE_ROTATED
// PRE_ROTATED_SCALAR (Codex) : table immuable des 1024 (piece,rot) -> 4 faces après rotation.
// Remplace les sideAfterRot répétés (arithmétique modulaire) par un lookup dans tailFace/tailFrameOK.
static uint8_t g_face[257][4][4];   // [piece][rot][face] = couleur (face 0=N 1=E 2=S 3=W)
static bool g_preRotated = true;    // défaut ON (config promotion) ; l'A/B MICRO-COMBO le toggle explicitement
static void buildPreRotated() {
    for (int p = 1; p <= 256; p++) for (int rot = 0; rot < 4; rot++)
        for (int f = 0; f < 4; f++) g_face[p][rot][f] = sideAfterRot(PIECES[p], rot, f);
}
#endif

#ifdef BW_TAIL_PLACEMENT_MASK
// TAIL_PLACEMENT_MASK (Codex) : candidate-gen par bitmask des 1024 placements (p,rot). bit idx=(p-1)*4+rot.
// g_plFace[f][col] = placements dont la face f == col ; g_plFrame[sig] = placements passant tailFrameOK
// pour une signature de bordure sig (bit f=1 <=> côté f (0=N 1=E 2=S 3=W) est bordure).
static uint64_t g_plFace[4][NCOLORS][16];
static uint64_t g_plFrame[16][16];
static uint64_t g_plClue[16];    // placements des pièces-indices (IS_CLUE) : exclues des cellules non-indice
static bool g_plMasksBuilt = false;
static void buildPlacementMasks() {
    for (int f = 0; f < 4; f++) for (int col = 0; col < NCOLORS; col++) for (int w = 0; w < 16; w++) g_plFace[f][col][w] = 0;
    for (int sig = 0; sig < 16; sig++) for (int w = 0; w < 16; w++) g_plFrame[sig][w] = 0;
    for (int w = 0; w < 16; w++) g_plClue[w] = 0;
    for (int p = 1; p <= 256; p++) for (int rot = 0; rot < 4; rot++) {
        int b = (p - 1) * 4 + rot; int w = b >> 6; uint64_t bit = 1ull << (b & 63);
        int fc[4]; for (int f = 0; f < 4; f++) { fc[f] = sideAfterRot(PIECES[p], rot, f); g_plFace[f][fc[f]][w] |= bit; }
        if (IS_CLUE[p]) g_plClue[w] |= bit;
        for (int sig = 0; sig < 16; sig++) {
            bool ok = true;
            for (int f = 0; f < 4 && ok; f++) { bool border = (sig >> f) & 1; if ((fc[f] == 0) != border) ok = false; }
            if (ok) g_plFrame[sig][w] |= bit;
        }
    }
    g_plMasksBuilt = true;
}
static inline void plClear(uint64_t* av, int p) { int b = (p - 1) * 4; av[b >> 6] &= ~(0xFull << (b & 63)); }
static inline void plSet(uint64_t* av, int p)   { int b = (p - 1) * 4; av[b >> 6] |=  (0xFull << (b & 63)); }
#endif

static inline int tailFace(const RotatedPiece& rp, int face) {
#ifdef BW_PRE_ROTATED
    if (g_preRotated) return g_face[rp.pieceNumber][rp.rot][face];
#endif
    if (face == 0) return rp.top;
    if (face == 1) return rp.right;
    return sideAfterRot(PIECES[rp.pieceNumber], rp.rot, face);
}

#ifdef BW_CHECKER_LEDGER
static inline int checkerMember(int m, int color) {
    return color && ((CHECKER_MASK[m] >> color) & 1u);
}

static void buildCheckerWeights() {
    for (int p = 1; p <= 256; p++) {
        const int col[4] = {PIECES[p].n, PIECES[p].e, PIECES[p].s, PIECES[p].w};
        for (int m = 0; m < g_checkerActive; m++) {
            int w = 0;
            for (int f = 0; f < 4; f++) w += checkerMember(m, col[f]);
            g_checkerWeight[p][m] = (uint8_t)w;
        }
    }
    g_checkerWeightsBuilt = true;
}

static void initCheckerLedger(TailMrvState& q) {
    if (!g_checkerWeightsBuilt) buildCheckerWeights();
    memset(q.checkerA, 0, sizeof q.checkerA);
    memset(q.checkerHist, 0, sizeof q.checkerHist);
    memset(q.checkerBlackLeft, 0, sizeof q.checkerBlackLeft);

    for (int p = 1; p <= 256; p++) if (!q.used[p]) {
        const int cls = PIECE_CLASS[p];
        for (int m = 0; m < CHECKER_N; m++) {
            const int w = g_checkerWeight[p][m];
            q.checkerHist[m][cls][w]++;
            q.checkerA[m] -= w; // - total weight of unplaced pieces
        }
    }
    for (int k = 0; k < q.nCells; k++) {
        const int ci = q.cells[k];
        if ((((ci >> 4) + (ci & 15)) & 1) == 0)
            q.checkerBlackLeft[((ci >> 4) == 0 || (ci >> 4) == 15) +
                               ((ci & 15) == 0 || (ci & 15) == 15)]++;
    }
    for (int ci = 0; ci < 256; ci++) {
        const RotatedPiece& a = q.board[ci];
        if (!a.pieceNumber) continue;
        const int rr = ci >> 4, cc = ci & 15;
        const int sign = ((rr + cc) & 1) ? -1 : 1;
        for (int m = 0; m < g_checkerActive; m++)
            q.checkerA[m] += sign * (int)g_checkerWeight[a.pieceNumber][m];
        if (cc < 15) {
            const RotatedPiece& b = q.board[ci + 1];
            if (b.pieceNumber) {
                const int x = tailFace(a, 1), y = tailFace(b, 3);
                if (x != y) for (int m = 0; m < g_checkerActive; m++)
                    q.checkerA[m] -= sign * (checkerMember(m, x) - checkerMember(m, y));
            }
        }
        if (rr < 15) {
            const RotatedPiece& b = q.board[ci + 16];
            if (b.pieceNumber) {
                const int x = tailFace(a, 0), y = tailFace(b, 2);
                if (x != y) for (int m = 0; m < g_checkerActive; m++)
                    q.checkerA[m] -= sign * (checkerMember(m, x) - checkerMember(m, y));
            }
        }
    }
}

static inline int checkerGcd(int a, int b) {
    while (b) { int t = a % b; a = b; b = t; }
    return a;
}

// Sound joint lower bound.  For projection S, x future broken seams must cross
// (S,~S).  The checker residue lower-bounds x; sigma's odd vertices on each
// side additionally require internal seams not covered by those x crossings.
static inline int checkerLowerBound(const TailMrvState& q, uint32_t oddMask, int lbsig) {
    if (g_checkerActive == 1) {
        // Specialised hot case for S={18}: every piece weight is 0, 1 or 2.
        // Same modular relaxation as the generic code, with fixed-size integer
        // arithmetic only (no five-bin scans and no general GCD loop).
        int lo=0,hi=0,base=0,mod=0;
        for(int cls=0;cls<3;cls++){
            int n0=q.checkerHist[0][cls][0],n1=q.checkerHist[0][cls][1],n2=q.checkerHist[0][cls][2];
            int take=q.checkerBlackLeft[cls],k=take,z;
            z=k<n0?k:n0;k-=z; z=k<n1?k:n1;lo+=z;k-=z;lo+=2*k;
            k=take;z=k<n2?k:n2;hi+=2*z;k-=z;z=k<n1?k:n1;hi+=z;
            int first=n0?0:(n1?1:2);base+=take*first;
            int kinds=(n0!=0)+(n1!=0)+(n2!=0),gc=0;
            if(kinds>1) gc=n1?1:2;
            if(gc) mod=mod?checkerGcd(mod,gc):gc;
        }
        int crossing;
        if(!mod) crossing=abs((int)q.checkerA[0]+2*base);
        else {
            int qlo=(lo-base+mod-1)/mod,qhi=(hi-base)/mod;
            int q0=(-(int)q.checkerA[0]-2*base)/(2*mod);
            if(q0<qlo)q0=qlo;if(q0>qhi)q0=qhi;
            crossing=abs((int)q.checkerA[0]+2*(base+mod*q0));
            if(q0>qlo){int v=abs((int)q.checkerA[0]+2*(base+mod*(q0-1)));if(v<crossing)crossing=v;}
            if(q0<qhi){int v=abs((int)q.checkerA[0]+2*(base+mod*(q0+1)));if(v<crossing)crossing=v;}
        }
        int pc=__builtin_popcount(oddMask),os=__builtin_popcount(oddMask&CHECKER_MASK[0]),ot=pc-os;
        if((crossing-os)&1)crossing++;
        int joint=crossing+(os>crossing?(os-crossing)/2:0)+(ot>crossing?(ot-crossing)/2:0);
        return joint>lbsig?joint:lbsig;
    }
    int best = lbsig;
    const int pc = __builtin_popcount(oddMask);
    for (int m = 0; m < g_checkerActive; m++) {
        int lo = 0, hi = 0, base = 0, mod = 0;
        for (int cls = 0; cls < 3; cls++) {
            int take = q.checkerBlackLeft[cls], need = take;
            int first = -1, gc = 0;
            for (int w = 0; w <= 4; w++) if (q.checkerHist[m][cls][w]) {
                if (first < 0) first = w; else gc = checkerGcd(gc, w - first);
                int n = q.checkerHist[m][cls][w] < need ? q.checkerHist[m][cls][w] : need;
                lo += n * w; need -= n;
            }
            need = take;
            for (int w = 4; w >= 0; w--) {
                int n = q.checkerHist[m][cls][w] < need ? q.checkerHist[m][cls][w] : need;
                hi += n * w; need -= n;
            }
            if (first >= 0) base += take * first;
            if (gc) mod = mod ? checkerGcd(mod, gc) : gc;
        }

        int crossing = 0x3fff;
        if (!mod) {
            crossing = abs((int)q.checkerA[m] + 2 * base);
        } else {
            const int qlo = (lo - base + mod - 1) / mod;
            const int qhi = (hi - base) / mod;
            const int den = 2 * mod;
            const int q0 = (-(int)q.checkerA[m] - 2 * base) / den;
            const int cand[7] = {qlo, qhi, q0 - 2, q0 - 1, q0, q0 + 1, q0 + 2};
            for (int z : cand) if (z >= qlo && z <= qhi) {
                int v = abs((int)q.checkerA[m] + 2 * (base + mod * z));
                if (v < crossing) crossing = v;
            }
        }
        const int os = __builtin_popcount(oddMask & CHECKER_MASK[m]);
        const int ot = pc - os;
        if ((crossing - os) & 1) crossing++;
        const int joint = crossing + (os > crossing ? (os - crossing) / 2 : 0)
                                   + (ot > crossing ? (ot - crossing) / 2 : 0);
        if (joint > best) best = joint;
    }
    return best;
}
#endif

static inline bool tailFrameOK(int ci, int piece, int rot) {
    int r = ci >> 4, c = ci & 15;
#ifdef BW_PRE_ROTATED
    if (g_preRotated) {
        bool n = g_face[piece][rot][0] == 0, e = g_face[piece][rot][1] == 0;
        bool s = g_face[piece][rot][2] == 0, w = g_face[piece][rot][3] == 0;
        return n == (r == 15) && e == (c == 15) && s == (r == 0) && w == (c == 0);
    }
#endif
    bool n = sideAfterRot(PIECES[piece], rot, 0) == 0;
    bool e = sideAfterRot(PIECES[piece], rot, 1) == 0;
    bool s = sideAfterRot(PIECES[piece], rot, 2) == 0;
    bool w = sideAfterRot(PIECES[piece], rot, 3) == 0;
    return n == (r == 15) && e == (c == 15) &&
           s == (r == 0) && w == (c == 0);
}

// How many of a complete board's mismatched seams sit on a ring colour, i.e. on
// the 60-seam frame cycle. Tells us whether an endgame's cost is dominated by the
// frame (a border-piece pool problem) or by the interior (a middle-pool problem).
static int countRingMismatches(const RotatedPiece* board) {
    int ring = 0;
    for (int r = 0; r < 16; r++)
        for (int c = 0; c < 16; c++) {
            int ci = r * 16 + c;
            const Piece& p = PIECES[board[ci].pieceNumber];
            int rot = board[ci].rot;
            uint8_t ee = sideAfterRot(p, rot, 1), nn = sideAfterRot(p, rot, 0);
            if (c < 15) {
                const Piece& q = PIECES[board[ci + 1].pieceNumber];
                uint8_t ww = sideAfterRot(q, board[ci + 1].rot, 3);
                if (ee != ww && (IS_RING_COLOR[ee] || IS_RING_COLOR[ww])) ring++;
            }
            if (r < 15) {
                const Piece& q = PIECES[board[ci + 16].pieceNumber];
                uint8_t ss = sideAfterRot(q, board[ci + 16].rot, 2);
                if (nn != ss && (IS_RING_COLOR[nn] || IS_RING_COLOR[ss])) ring++;
            }
        }
    return ring;
}

#ifdef BW_TAIL_HALL
// P7-C: tight-slack Hall/matching prune. When at most `slack` more breaks are
// allowed, a completion requires an injective assignment of remaining cells to
// distinct remaining pieces where each piece can sit in the cell within slack.
// If no such system of distinct representatives exists, prune (sound).
static bool hallFeasible(TailMrvState& q, int running) {
    static constexpr int DR[4] = {1, 0, -1, 0}, DC[4] = {0, 1, 0, -1};
    int slack = q.bestCost - 1 - running;
    if (slack < 0 || slack > 2) return true;   // only fire tight
    int ucell[64], nu = 0;
    for (int k = 0; k < q.nCells; k++) if (!q.placed[q.cells[k]]) ucell[nu++] = q.cells[k];
    if (nu == 0 || nu > 64) return true;
    g_hallChecks.fetch_add(1, std::memory_order_relaxed);
    static thread_local uint64_t dom[64][4];
    for (int i = 0; i < nu; i++) {
        int x = ucell[i], r0 = x >> 4, c0 = x & 15;
        dom[i][0] = dom[i][1] = dom[i][2] = dom[i][3] = 0;
        bool any = false;
        for (int p = 1; p <= 256; p++) {
            if (q.used[p]) continue;
            if (q.cluePiece[x] && q.cluePiece[x] != p) continue;
            int minadd = 99;
            for (int rot = 0; rot < 4; rot++) {
                if (q.cluePiece[x] && q.clueRot[x] != rot) continue;
                if (!tailFrameOK(x, p, rot)) continue;
                RotatedPiece rp = {(uint16_t)p, (uint8_t)rot, sideAfterRot(PIECES[p], rot, 0),
                                   sideAfterRot(PIECES[p], rot, 1), 0, PIECE_HSC[p], 0};
                int add = 0;
                for (int f = 0; f < 4; f++) {
                    int rr = r0 + DR[f], cc = c0 + DC[f];
                    if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) continue;
                    int nb = rr * 16 + cc;
                    if (q.inTail[nb] && !q.placed[nb]) continue;
                    const RotatedPiece& o = q.board[nb];
                    if (!o.pieceNumber || tailFace(rp, f) != tailFace(o, (f + 2) & 3)) add++;
                }
                if (add < minadd) minadd = add;
            }
            if (minadd <= slack) { dom[i][(p - 1) >> 6] |= 1ULL << ((p - 1) & 63); any = true; }
        }
        if (!any) { g_hallCuts.fetch_add(1, std::memory_order_relaxed); return false; }   // empty domain
    }
    // Kuhn bipartite matching: cells -> pieces. Prune if not all cells can match.
    static thread_local int matchP[257];      // piece -> cell index (+1), 0 = free
    static thread_local int seen[257], stamp = 0;
    for (int p = 1; p <= 256; p++) matchP[p] = 0;
    // iterative augment via explicit recursion helper
    struct Aug {
        static bool go(int i, uint64_t (*dom)[4], int* matchP, int* seen, int st) {
            for (int w = 0; w < 4; w++) {
                uint64_t bits = dom[i][w];
                while (bits) {
                    int b = __builtin_ctzll(bits); bits &= bits - 1;
                    int p = w * 64 + b + 1;
                    if (seen[p] == st) continue;
                    seen[p] = st;
                    if (!matchP[p] || go(matchP[p] - 1, dom, matchP, seen, st)) { matchP[p] = i + 1; return true; }
                }
            }
            return false;
        }
    };
    for (int i = 0; i < nu; i++) {
        ++stamp;
        if (!Aug::go(i, dom, matchP, seen, stamp)) { g_hallCuts.fetch_add(1, std::memory_order_relaxed); return false; }
    }
    return true;
}
#endif

#ifdef BW_SIGMA_LEDGER
// LBσ TAIL (couche portée dans solveTailMrv / tailMrvDfs) : compteurs propres au tail-solver,
// distincts de la hot-loop. tailCalls = nœuds où la borne de parité est évaluée ; tailWouldCut =
// nœuds où running + ceil(popcount(oddMask)/2) >= bestCost (compté même en OFF, shadow) ; tailCut =
// coupes réellement appliquées (ON) ; tailLeafBug = feuilles complètes valides avec oddMask != 0.
static std::atomic<uint64_t> g_sigmaTailCalls{0}, g_sigmaTailWouldCut{0}, g_sigmaTailCut{0}, g_sigmaTailLeafBug{0};
// LBdemSigma (handoff 2026-08-18) : compteurs globaux, déclarés AVANT flushTailLedger qui les agrège.
static std::atomic<uint64_t> g_demSigmaCalls{0}, g_demSigmaStronger{0}, g_demSigmaWould{0}, g_demSigmaCuts{0};
static std::atomic<uint64_t> g_demSigWClass[6];   // A adaptatif : would-cut par classe lbDem
#ifdef BW_TAIL_LEDGER_LOCAL
// Agrégation amortie des compteurs télémétrie locaux -> atomiques globaux (périodique + sorties racine).
// Reset des locaux après flush -> totaux finaux EXACTEMENT identiques au mode atomique.
static inline void flushTailLedger(TailMrvState& q) {
    if (q.locSigCalls) { g_sigmaTailCalls.fetch_add(q.locSigCalls, std::memory_order_relaxed); q.locSigCalls = 0; }
    if (q.locWouldCut) { g_sigmaTailWouldCut.fetch_add(q.locWouldCut, std::memory_order_relaxed); q.locWouldCut = 0; }
    if (q.locCut)      { g_sigmaTailCut.fetch_add(q.locCut, std::memory_order_relaxed); q.locCut = 0; }
    if (q.locLeafBug)  { g_sigmaTailLeafBug.fetch_add(q.locLeafBug, std::memory_order_relaxed); q.locLeafBug = 0; }
    if (q.locDemSigCalls)    { g_demSigmaCalls.fetch_add(q.locDemSigCalls, std::memory_order_relaxed); q.locDemSigCalls = 0; }
    if (q.locDemSigStronger) { g_demSigmaStronger.fetch_add(q.locDemSigStronger, std::memory_order_relaxed); q.locDemSigStronger = 0; }
    if (q.locDemSigWould)    { g_demSigmaWould.fetch_add(q.locDemSigWould, std::memory_order_relaxed); q.locDemSigWould = 0; }
    if (q.locDemSigCut)      { g_demSigmaCuts.fetch_add(q.locDemSigCut, std::memory_order_relaxed); q.locDemSigCut = 0; }
    for (int k = 0; k < 6; ++k) if (q.locDemSigWClass[k]) { g_demSigWClass[k].fetch_add(q.locDemSigWClass[k], std::memory_order_relaxed); q.locDemSigWClass[k] = 0; }
#ifdef BW_CHECKER_LEDGER
    if(q.locCheckerCalls){g_checkerCalls.fetch_add(q.locCheckerCalls,std::memory_order_relaxed);q.locCheckerCalls=0;}
    if(q.locCheckerStronger){g_checkerStronger.fetch_add(q.locCheckerStronger,std::memory_order_relaxed);q.locCheckerStronger=0;}
    if(q.locCheckerWould){g_checkerWouldCut.fetch_add(q.locCheckerWould,std::memory_order_relaxed);q.locCheckerWould=0;}
    if(q.locCheckerCut){g_checkerCut.fetch_add(q.locCheckerCut,std::memory_order_relaxed);q.locCheckerCut=0;}
    if(q.locCheckerBug){g_checkerLeafBug.fetch_add(q.locCheckerBug,std::memory_order_relaxed);q.locCheckerBug=0;}
    if(q.locCheckerMaxGain){int gain=q.locCheckerMaxGain,old=g_checkerMaxGain.load(std::memory_order_relaxed);
        while(gain>old&&!g_checkerMaxGain.compare_exchange_weak(old,gain,std::memory_order_relaxed)){} q.locCheckerMaxGain=0;}
#endif
}
#endif
// Copie du flag runtime --sigma-ledger accessible depuis solveTailMrv (fonction libre sans cfg).
// Positionné une fois dans runSolver ; le bench le bascule directement pour ses runs OFF/ON.
static bool g_sigmaTailOn = false;
static bool g_demSigmaOn = false;   // --dem-sigma-joint : applique la coupe LBdemSigma (compteurs déclarés plus haut)
static int g_demSigmaGate = 0;      // A adaptatif (2026-08-19) : --dem-sigma-gate T (n'évalue que si lbDem >= T)
#endif

#ifdef BW_FLUX_LEDGER
// Résidu de flux courant, par couleur/direction (accX[c] = r pour l'indicateur (c,x)). Recompute
// FULL depuis le board : Σ_{cellules posées} F·λ  -  Σ_{coutures cassées fermées} contrib·λ. Chaque
// couture comptée UNE fois (voisin est + nord de chaque cellule). Ordre-indépendant, robuste. Coût
// payé UNIQUEMENT au gate (froid, rare), donc le chemin chaud du tail reste intact.
static inline void fluxResidual(const RotatedPiece* board, int accX[NCOLORS], int accY[NCOLORS]) {
    for (int c = 0; c < NCOLORS; c++) accX[c] = accY[c] = 0;
    for (int ci = 0; ci < 256; ci++) {
        const RotatedPiece& a = board[ci];
        if (!a.pieceNumber) continue;
        const int E = a.right, N = a.top;                 // faces après rotation (est, nord)
        const int W = sideAfterRot(PIECES[a.pieceNumber], a.rot, 3);
        const int S = sideAfterRot(PIECES[a.pieceNumber], a.rot, 2);
        // flux des cellules posées : +1 sur la couleur d'une face "positive", -1 "négative"
        if (E) accX[E]++;  if (W) accX[W]--;
        if (N) accY[N]++;  if (S) accY[S]--;
        const int cc = ci & 15, rr = ci >> 4;
        if (cc < 15) {                                    // couture verticale vers l'est (cellule a = gauche)
            const RotatedPiece& b = board[ci + 1];
            if (b.pieceNumber) {
                const int bw = sideAfterRot(PIECES[b.pieceNumber], b.rot, 3);
                if (E != bw) { if (E) accX[E]--; if (bw) accX[bw]++; }   // -= contrib (a.E==c) - (b.W==c)
            }
        }
        if (rr < 15) {                                    // couture horizontale vers le nord (cellule a = bas)
            const RotatedPiece& b = board[ci + 16];
            if (b.pieceNumber) {
                const int bs = sideAfterRot(PIECES[b.pieceNumber], b.rot, 2);
                if (N != bs) { if (N) accY[N]--; if (bs) accY[bs]++; }   // -= contrib (a.N==c) - (b.S==c)
            }
        }
    }
}
// LBflux au gate : minorant SOUND du nb de cassures futures. Q=1 (indicateurs) -> pur entier, pas de
// ceil(double). On teste chaque indicateur (c, dir) dans les DEUX sens (λ et -λ) et on garde le max.
static inline int computeLbFlux(const TailMrvState& q) {
    int accX[NCOLORS], accY[NCOLORS];
    fluxResidual(q.board, accX, accY);
    // Σ_{pièces non posées} min_r F·λ (et max_r pour le sens -λ). Positions/all-diff relâchés (sound).
    int sMinX[NCOLORS] = {0}, sMaxX[NCOLORS] = {0}, sMinY[NCOLORS] = {0}, sMaxY[NCOLORS] = {0};
    for (int p = 1; p <= 256; p++) {
        if (q.used[p]) continue;
        for (int c = 1; c < NCOLORS; c++) {
            sMinX[c] += FLUX.minFx[p][c]; sMaxX[c] += FLUX.maxFx[p][c];
            sMinY[c] += FLUX.minFy[p][c]; sMaxY[c] += FLUX.maxFy[p][c];
        }
    }
    int lb = 0;                                           // Q=1 : ceil(a/1)=a
    for (int c = 1; c < NCOLORS; c++) {
        int a = accX[c] + sMinX[c];  if (a > lb) lb = a;  // certificat +λ (x)
        int b = -accX[c] - sMaxX[c]; if (b > lb) lb = b;  // certificat -λ (x)
        int d = accY[c] + sMinY[c];  if (d > lb) lb = d;  // +λ (y)
        int e = -accY[c] - sMaxY[c]; if (e > lb) lb = e;  // -λ (y)
    }
    return lb;
}
// SELF-CHECK soundness : à une feuille COMPLÈTE valide, toutes les coutures sont fermées -> le résidu
// de flux DOIT être nul pour toute couleur/direction (analogue signé de oddMask==0). Non-nul = bug.
static inline bool fluxLeafResidualNonZero(const RotatedPiece* board) {
    int accX[NCOLORS], accY[NCOLORS];
    fluxResidual(board, accX, accY);
    for (int c = 1; c < NCOLORS; c++)
        if (accX[c] || accY[c]) return true;
    return false;
}
#endif

// Globals trace/dead0 (P1/P3) TOUJOURS déclarés : utilisés hors du shadow (DFS principal), inertes par défaut.
// Déplacés hors de #ifdef BW_LBASSIGN_SHADOW pour permettre le build sans ce flag (identique au runtime : défauts OFF).
static bool g_dead0Verify = false;
static int  g_dead0GateDet = 0;
static std::atomic<uint64_t> g_dead0Probed{0}, g_dead0Found{0};
static bool g_tsbDead0 = false;
static bool g_traceBackjump = false;      // --trace-backjump
static int  g_placeDepth[256];
static int  g_pieceUsedAtDepth[257];
static std::atomic<uint64_t> g_bjHist[6]{};
static std::atomic<uint64_t> g_bjUnexploit{0}, g_bjCells{0};

#ifdef BW_LBASSIGN_SHADOW
// ---- LEVIER 3 LBASSIGN_DUAL (shadow pur, guardé, jamais impliqué par BW_SIGMA/FLUX) ----
// Borne d'assignation min-coût : pièces restantes -> cellules ouvertes, coût = incompatibilités
// FORCÉES avec les voisins FIXES + bordure (meilleure rotation par placement). Admissible (les
// aretes ouvert-ouvert ne sont PAS comptées, >=0) -> ne coupe jamais un bon nœud. Compteurs seuls.
#ifndef BW_LBASSIGN_GATE_REMAIN
#define BW_LBASSIGN_GATE_REMAIN 16      // n'évalue qu'à l'endgame profond (Hungarian O(K^3), K<=gate)
#endif
static std::atomic<uint64_t> g_assignCalls{0}, g_assignStronger{0}, g_assignWouldCut{0}, g_assignNanos{0};
static std::atomic<uint64_t> g_assignCallClass[6], g_assignCutClass[6];   // gating-test (2026-08-19) : appels ET coupes assign par classe lbDem
static std::atomic<int> g_assignMaxGain{0};
static bool g_assignEval = true;    // évalue la borne (compteurs/ns) ; false = σ pur (0 overhead)
static bool g_assignApply = false;  // A/B : APPLIQUE la coupe (return false) quand running+LB>=bestCost. SOUND.
static int  g_assignMode = 0;       // 0=Hungarian(min-cost) ; 1=Deficiency(K-M0, max-matching 0-coût) ; 2=COMPARE ; 3=HALL_AUDIT ; 4=SINGLETON
static bool g_tsbSingletonOnly = false;   // --tsb-singleton-only : saute les sections lourdes (Hungarian/déficience/audit)
// (globals trace/dead0 déplacés avant #ifdef BW_LBASSIGN_SHADOW — voir plus haut)
// COMPARE (mode 2) : compteurs de rétention Déficience vs Hungarian sur les MÊMES nœuds.
static std::atomic<uint64_t> g_hungWould{0}, g_defWould{0}, g_defRetain{0}, g_defFalse{0}, g_hungNanos{0}, g_defNanos{0};
// HALL_AUDIT (mode 3) : histogramme de la taille MINIMALE du témoin de Hall qui explique chaque would-cut.
static std::atomic<uint64_t> g_hwitCuts{0}, g_hallS1{0}, g_hallS2{0}, g_hallS3{0}, g_hallS4{0}, g_hallS58{0}, g_hallSbig{0};
static std::atomic<uint64_t> g_hallDef1{0}, g_hallDef2{0}, g_hallDef3p{0}, g_hallNanos{0};
// Hungarian O(n^3) (potentiels + chemins augmentants, e-maxx). Coût min d'affectation parfaite.
static int lbAssignHungarian(const std::vector<std::vector<int>>& a, int n) {
    const int INF = 1000000000;
    std::vector<int> u(n + 1, 0), v(n + 1, 0), p(n + 1, 0), way(n + 1, 0);
    for (int i = 1; i <= n; i++) {
        p[0] = i; int j0 = 0;
        std::vector<int> minv(n + 1, INF); std::vector<char> used(n + 1, 0);
        do {
            used[j0] = 1; int i0 = p[j0], delta = INF, j1 = -1;
            for (int j = 1; j <= n; j++) if (!used[j]) {
                int cur = a[i0 - 1][j - 1] - u[i0] - v[j];
                if (cur < minv[j]) { minv[j] = cur; way[j] = j0; }
                if (minv[j] < delta) { delta = minv[j]; j1 = j; }
            }
            for (int j = 0; j <= n; j++) {
                if (used[j]) { u[p[j]] += delta; v[j] -= delta; }
                else minv[j] -= delta;
            }
            j0 = j1;
        } while (p[j0] != 0);
        do { int j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0);
    }
    int cost = 0;
    for (int j = 1; j <= n; j++) cost += a[p[j] - 1][j - 1];
    return cost;
}
// Renvoie la borne d'assignation, ou -1 si gaté (trop de cellules / incohérent).
static int computeLbAssign(const TailMrvState& q) {
    int oc[64], K = 0;
    for (int k = 0; k < q.nCells; k++) { int ci = q.cells[k]; if (!q.placed[ci]) { if (K < 64) oc[K] = ci; K++; } }
    if (K == 0 || K > BW_LBASSIGN_GATE_REMAIN) return -1;
    int pr[64], M = 0;
    for (int pp = 1; pp <= 256; pp++) if (!q.used[pp]) { if (M < 64) pr[M] = pp; M++; if (M > K) break; }
    if (M != K) return -1;
    std::vector<std::vector<int>> cost(K, std::vector<int>(K, 0));
    for (int i = 0; i < K; i++) {
        int ci = oc[i], rr = ci >> 4, cc = ci & 15;
        int req[4] = {-1, -1, -1, -1};   // -1 = voisin OUVERT (non contraint) ; sinon couleur requise (0=bordure)
        if (rr == 15) req[0] = 0; else { int nb = ci + 16; if (q.board[nb].pieceNumber) req[0] = tailFace(q.board[nb], 2); } // N <- voisin S
        if (cc == 15) req[1] = 0; else { int nb = ci + 1;  if (q.board[nb].pieceNumber) req[1] = tailFace(q.board[nb], 3); } // E <- voisin W
        if (rr == 0)  req[2] = 0; else { int nb = ci - 16; if (q.board[nb].pieceNumber) req[2] = tailFace(q.board[nb], 0); } // S <- voisin N
        if (cc == 0)  req[3] = 0; else { int nb = ci - 1;  if (q.board[nb].pieceNumber) req[3] = tailFace(q.board[nb], 1); } // W <- voisin E
        for (int j = 0; j < K; j++) {
            const Piece& pcp = PIECES[pr[j]]; int best = 99;
            for (int rot = 0; rot < 4; rot++) {
                int f0 = sideAfterRot(pcp, rot, 0), f1 = sideAfterRot(pcp, rot, 1);
                int f2 = sideAfterRot(pcp, rot, 2), f3 = sideAfterRot(pcp, rot, 3);
                int c = 0;
                if (req[0] >= 0 && f0 != req[0]) c++;
                if (req[1] >= 0 && f1 != req[1]) c++;
                if (req[2] >= 0 && f2 != req[2]) c++;
                if (req[3] >= 0 && f3 != req[3]) c++;
                if (c < best) best = c;
            }
            cost[i][j] = best;
        }
    }
    return lbAssignHungarian(cost, K);
}
// ---- LBASSIGN_DEFICIENCY (Codex) : K - M0, M0 = max matching du graphe 0-coût (cellule->pièces
// ayant >=1 rotation de coût frontière-fixe 0). SOUND : au plus M0 cellules peuvent prendre coût 0,
// donc >= K-M0 cellules paient >=1 break. Conserve Hall/supply, évite le min-cost Hungarian. Bitset uint64.
static bool lbDefTryKuhn(int i, const uint64_t* adj, int* matchPiece, uint64_t& seen) {
    uint64_t cand = adj[i] & ~seen;
    while (cand) {
        int j = __builtin_ctzll(cand); cand &= cand - 1;
        seen |= (1ull << j);
        if (matchPiece[j] < 0 || lbDefTryKuhn(matchPiece[j], adj, matchPiece, seen)) {
            matchPiece[j] = i; return true;
        }
    }
    return false;
}
static int computeLbDeficiency(const TailMrvState& q) {
    int oc[64], K = 0;
    for (int k = 0; k < q.nCells; k++) { int ci = q.cells[k]; if (!q.placed[ci]) { if (K < 64) oc[K] = ci; K++; } }
    if (K == 0 || K > BW_LBASSIGN_GATE_REMAIN) return -1;
    int pr[64], M = 0;
    for (int pp = 1; pp <= 256; pp++) if (!q.used[pp]) { if (M < 64) pr[M] = pp; M++; if (M > K) break; }
    if (M != K) return -1;
    uint64_t adj[64];
    for (int i = 0; i < K; i++) {
        int ci = oc[i], rr = ci >> 4, cc = ci & 15;
        int req[4] = {-1, -1, -1, -1};
        if (rr == 15) req[0] = 0; else { int nb = ci + 16; if (q.board[nb].pieceNumber) req[0] = tailFace(q.board[nb], 2); }
        if (cc == 15) req[1] = 0; else { int nb = ci + 1;  if (q.board[nb].pieceNumber) req[1] = tailFace(q.board[nb], 3); }
        if (rr == 0)  req[2] = 0; else { int nb = ci - 16; if (q.board[nb].pieceNumber) req[2] = tailFace(q.board[nb], 0); }
        if (cc == 0)  req[3] = 0; else { int nb = ci - 1;  if (q.board[nb].pieceNumber) req[3] = tailFace(q.board[nb], 1); }
        uint64_t bits = 0;
        for (int j = 0; j < K; j++) {
            const Piece& pcp = PIECES[pr[j]]; bool zero = false;
            for (int rot = 0; rot < 4 && !zero; rot++) {
                int f0 = sideAfterRot(pcp, rot, 0), f1 = sideAfterRot(pcp, rot, 1);
                int f2 = sideAfterRot(pcp, rot, 2), f3 = sideAfterRot(pcp, rot, 3);
                if ((req[0] < 0 || f0 == req[0]) && (req[1] < 0 || f1 == req[1]) &&
                    (req[2] < 0 || f2 == req[2]) && (req[3] < 0 || f3 == req[3])) zero = true;   // coût 0
            }
            if (zero) bits |= (1ull << j);
        }
        adj[i] = bits;
    }
    int matchPiece[64]; for (int j = 0; j < K; j++) matchPiece[j] = -1;
    int M0 = 0;
    for (int i = 0; i < K; i++) { uint64_t seen = 0; if (lbDefTryKuhn(i, adj, matchPiece, seen)) M0++; }
    return K - M0;
}
// HALL_AUDIT : sur un would-cut (running+(K-M0)>=bestCost), trouve la taille MINIMALE d'un témoin de Hall
// S (|N(S)|<|S|) parmi les <=12 cellules de plus faible degré (énum. bitmask), et met à jour l'histogramme.
static void hallAudit(const TailMrvState& q, int running, int bestCost) {
    int oc[64], K = 0;
    for (int k = 0; k < q.nCells; k++) { int ci = q.cells[k]; if (!q.placed[ci]) { if (K < 64) oc[K] = ci; K++; } }
    if (K == 0 || K > BW_LBASSIGN_GATE_REMAIN) return;
    int pr[64], M = 0;
    for (int pp = 1; pp <= 256; pp++) if (!q.used[pp]) { if (M < 64) pr[M] = pp; M++; if (M > K) break; }
    if (M != K) return;
    uint64_t adj[64];
    for (int i = 0; i < K; i++) {
        int ci = oc[i], rr = ci >> 4, cc = ci & 15;
        int req[4] = {-1, -1, -1, -1};
        if (rr == 15) req[0] = 0; else { int nb = ci + 16; if (q.board[nb].pieceNumber) req[0] = tailFace(q.board[nb], 2); }
        if (cc == 15) req[1] = 0; else { int nb = ci + 1;  if (q.board[nb].pieceNumber) req[1] = tailFace(q.board[nb], 3); }
        if (rr == 0)  req[2] = 0; else { int nb = ci - 16; if (q.board[nb].pieceNumber) req[2] = tailFace(q.board[nb], 0); }
        if (cc == 0)  req[3] = 0; else { int nb = ci - 1;  if (q.board[nb].pieceNumber) req[3] = tailFace(q.board[nb], 1); }
        uint64_t bits = 0;
        for (int j = 0; j < K; j++) {
            const Piece& pcp = PIECES[pr[j]]; bool zero = false;
            for (int rot = 0; rot < 4 && !zero; rot++) {
                int f0 = sideAfterRot(pcp, rot, 0), f1 = sideAfterRot(pcp, rot, 1);
                int f2 = sideAfterRot(pcp, rot, 2), f3 = sideAfterRot(pcp, rot, 3);
                if ((req[0] < 0 || f0 == req[0]) && (req[1] < 0 || f1 == req[1]) &&
                    (req[2] < 0 || f2 == req[2]) && (req[3] < 0 || f3 == req[3])) zero = true;
            }
            if (zero) bits |= (1ull << j);
        }
        adj[i] = bits;
    }
    int matchPiece[64]; for (int j = 0; j < K; j++) matchPiece[j] = -1;
    int M0 = 0;
    for (int i = 0; i < K; i++) { uint64_t seen = 0; if (lbDefTryKuhn(i, adj, matchPiece, seen)) M0++; }
    if (running + (K - M0) < bestCost) return;   // pas un would-cut
    g_hwitCuts.fetch_add(1, std::memory_order_relaxed);
    // <=12 cellules de plus faible degré (deg = popcount(adj))
    int idxByDeg[64]; for (int i = 0; i < K; i++) idxByDeg[i] = i;
    for (int a = 0; a < K; a++) for (int b = a + 1; b < K; b++)
        if (__builtin_popcountll(adj[idxByDeg[b]]) < __builtin_popcountll(adj[idxByDeg[a]]))
            { int t = idxByDeg[a]; idxByDeg[a] = idxByDeg[b]; idxByDeg[b] = t; }
    int L = K < 12 ? K : 12;
    uint64_t lowAdj[12]; for (int i = 0; i < L; i++) lowAdj[i] = adj[idxByDeg[i]];
    int bestSize = 99, bestDef = 0;
    for (uint32_t mask = 1; mask < (1u << L); mask++) {
        int sz = __builtin_popcount(mask); if (sz >= bestSize || sz > 8) continue;
        uint64_t un = 0; for (int b = 0; b < L; b++) if (mask & (1u << b)) un |= lowAdj[b];
        int nn = __builtin_popcountll(un);
        if (nn < sz) { bestSize = sz; bestDef = sz - nn; }
    }
    if (bestSize == 1) g_hallS1.fetch_add(1, std::memory_order_relaxed);
    else if (bestSize == 2) g_hallS2.fetch_add(1, std::memory_order_relaxed);
    else if (bestSize == 3) g_hallS3.fetch_add(1, std::memory_order_relaxed);
    else if (bestSize == 4) g_hallS4.fetch_add(1, std::memory_order_relaxed);
    else if (bestSize <= 8) g_hallS58.fetch_add(1, std::memory_order_relaxed);
    else g_hallSbig.fetch_add(1, std::memory_order_relaxed);   // témoin >8 (ou hors des 12 bas-degré)
    if (bestSize <= 8) { if (bestDef == 1) g_hallDef1.fetch_add(1, std::memory_order_relaxed);
        else if (bestDef == 2) g_hallDef2.fetch_add(1, std::memory_order_relaxed);
        else g_hallDef3p.fetch_add(1, std::memory_order_relaxed); }
}
// FILTRE DEAD-CELL (Codex, cheap forward-check, PAS de matching) : COMPTE les cellules libres sans AUCUNE
// pièce restante de coût-frontière 0. Chaque cellule dead force >=1 break (indépendant) -> #dead = LB SOUND
// des breaks futurs, <= K-M0 (déficience). Early-exit par cellule dès qu'une pièce de coût 0 est trouvée.
static int singletonDead(const TailMrvState& q) {
    int free = 0;
    for (int k = 0; k < q.nCells; k++) if (!q.placed[q.cells[k]]) free++;
    if (free == 0 || free > BW_LBASSIGN_GATE_REMAIN) return 0;
    int dead = 0;
    for (int k = 0; k < q.nCells; k++) {
        int ci = q.cells[k]; if (q.placed[ci]) continue;
        int rr = ci >> 4, cc = ci & 15; int req[4] = {-1, -1, -1, -1};
        if (rr == 15) req[0] = 0; else { int nb = ci + 16; if (q.board[nb].pieceNumber) req[0] = tailFace(q.board[nb], 2); }
        if (cc == 15) req[1] = 0; else { int nb = ci + 1;  if (q.board[nb].pieceNumber) req[1] = tailFace(q.board[nb], 3); }
        if (rr == 0)  req[2] = 0; else { int nb = ci - 16; if (q.board[nb].pieceNumber) req[2] = tailFace(q.board[nb], 0); }
        if (cc == 0)  req[3] = 0; else { int nb = ci - 1;  if (q.board[nb].pieceNumber) req[3] = tailFace(q.board[nb], 1); }
        if (req[0] < 0 && req[1] < 0 && req[2] < 0 && req[3] < 0) continue;  // 0 contrainte -> jamais dead
        bool fit = false;
        for (int pp = 1; pp <= 256 && !fit; pp++) {
            if (q.used[pp]) continue;
            const Piece& pcp = PIECES[pp];
            for (int rot = 0; rot < 4; rot++) {
                if ((req[0] < 0 || sideAfterRot(pcp, rot, 0) == req[0]) && (req[1] < 0 || sideAfterRot(pcp, rot, 1) == req[1]) &&
                    (req[2] < 0 || sideAfterRot(pcp, rot, 2) == req[2]) && (req[3] < 0 || sideAfterRot(pcp, rot, 3) == req[3])) { fit = true; break; }
            }
        }
        if (!fit) dead++;   // cellule dead -> +1 break forcé (sound)
    }
    return dead;
}
// DEAD0_PLACEMENT_BITSET (Codex) : même LB #dead que singletonDead mais en BITSETS. faceMask[s][col] =
// masque 1024-bit des placements (p,rot) ayant couleur col sur la face s. domaine coût-0 d'une cellule =
// avail INTERSECTÉ des faceMask[s][req_s] des voisins FIXES -> vide => dead. Remplace le scan 256x4 par
// ~5 AND/mots par cellule. avail reconstruit/nœud ici (prototype) ; en prod = availPlacement incrémental O(1).
static uint64_t g_faceMask[4][NCOLORS][16];
static bool g_dead0MasksBuilt = false;
static void buildDead0Masks() {
    for (int s = 0; s < 4; s++) for (int col = 0; col < NCOLORS; col++) for (int w = 0; w < 16; w++) g_faceMask[s][col][w] = 0;
    for (int p = 1; p <= 256; p++) for (int rot = 0; rot < 4; rot++) {
        int b = (p - 1) * 4 + rot; int w = b >> 6; uint64_t bit = 1ull << (b & 63);
        for (int s = 0; s < 4; s++) { int col = sideAfterRot(PIECES[p], rot, s); g_faceMask[s][col][w] |= bit; }
    }
    g_dead0MasksBuilt = true;
}
// P3 (2026-08-19) : trace read-only de profondeur de backjump sur les cellules mortes (size-1 witness).
// Dépendances SOUND pour chaque cellule vide morte (aucune pièce libre 0-coût, det>=g_dead0GateDet) :
//   (a) voisins tail posés (g_placeDepth>=0) imposant une face ; (b) TOUTE pièce consommée en tail
//   (g_pieceUsedAtDepth>=0) ayant >=1 rotation 0-coût pour cette cellule. Préfixe/clue/frame (=-1) = statique.
// jump = curDepth - max(depDepth). depMax<0 => aucune dépendance tail => saut = curDepth. Jamais de saut actif.
static void traceBackjump(const TailMrvState& q, int curDepth) {
    int free = 0; for (int k = 0; k < q.nCells; k++) if (!q.placed[q.cells[k]]) free++;
    if (free == 0 || free > 14) return;
    for (int k = 0; k < q.nCells; k++) {
        int ci = q.cells[k]; if (q.placed[ci] || q.cluePiece[ci]) continue;
        int rr = ci >> 4, cc = ci & 15;
        int req[4] = {-1,-1,-1,-1}; int nbc[4] = {-1,-1,-1,-1};
        if (rr == 15) req[0] = 0; else { int nb = ci+16; if (q.board[nb].pieceNumber) { req[0] = tailFace(q.board[nb],2); nbc[0]=nb; } }
        if (cc == 15) req[1] = 0; else { int nb = ci+1;  if (q.board[nb].pieceNumber) { req[1] = tailFace(q.board[nb],3); nbc[1]=nb; } }
        if (rr == 0)  req[2] = 0; else { int nb = ci-16; if (q.board[nb].pieceNumber) { req[2] = tailFace(q.board[nb],0); nbc[2]=nb; } }
        if (cc == 0)  req[3] = 0; else { int nb = ci-1;  if (q.board[nb].pieceNumber) { req[3] = tailFace(q.board[nb],1); nbc[3]=nb; } }
        int det = (req[0]>=0)+(req[1]>=0)+(req[2]>=0)+(req[3]>=0);
        if (det < g_dead0GateDet) continue;
        int depMax = -1; bool freeFits = false;
        for (int p = 1; p <= 256; p++) {
            bool fit = false;
            for (int rot = 0; rot < 4 && !fit; rot++) {
                bool ok = true;
                for (int s = 0; s < 4; s++) { if (req[s] >= 0 && sideAfterRot(PIECES[p], rot, s) != req[s]) { ok = false; break; } }
                if (ok) fit = true;
            }
            if (!fit) continue;
            if (!q.used[p]) { freeFits = true; break; }               // pièce libre 0-coût -> PAS morte
            int d = g_pieceUsedAtDepth[p]; if (d > depMax) depMax = d; // consommée : dépendance (préfixe d=-1 ignoré)
        }
        if (freeFits) continue;                                        // cellule vivante
        for (int s = 0; s < 4; s++) { if (nbc[s] < 0) continue; int d = g_placeDepth[nbc[s]]; if (d > depMax) depMax = d; }
        int jump = (depMax < 0) ? curDepth : (curDepth - depMax);
        int bin = jump <= 0 ? 0 : jump == 1 ? 1 : jump == 2 ? 2 : jump == 3 ? 3 : jump <= 7 ? 4 : 5;
        g_bjHist[bin].fetch_add(1, std::memory_order_relaxed);
        g_bjCells.fetch_add(1, std::memory_order_relaxed);
    }
}
static int dead0Bitset(const TailMrvState& q) {
    if (!g_dead0MasksBuilt) buildDead0Masks();
    int free = 0;
    for (int k = 0; k < q.nCells; k++) if (!q.placed[q.cells[k]]) free++;
    if (free == 0 || free > BW_LBASSIGN_GATE_REMAIN) return 0;
    uint64_t avail[16] = {0};
    for (int p = 1; p <= 256; p++) if (!q.used[p]) { int b = (p - 1) * 4; avail[b >> 6] |= (0xFull << (b & 63)); }
    int dead = 0; uint64_t _probed = 0;
    for (int k = 0; k < q.nCells; k++) {
        int ci = q.cells[k]; if (q.placed[ci] || q.cluePiece[ci]) continue;   // clue = réservée -> skip (sound)
        int rr = ci >> 4, cc = ci & 15;
        int req[4] = {-1, -1, -1, -1};
        if (rr == 15) req[0] = 0; else { int nb = ci + 16; if (q.board[nb].pieceNumber) req[0] = tailFace(q.board[nb], 2); }
        if (cc == 15) req[1] = 0; else { int nb = ci + 1;  if (q.board[nb].pieceNumber) req[1] = tailFace(q.board[nb], 3); }
        if (rr == 0)  req[2] = 0; else { int nb = ci - 16; if (q.board[nb].pieceNumber) req[2] = tailFace(q.board[nb], 0); }
        if (cc == 0)  req[3] = 0; else { int nb = ci - 1;  if (q.board[nb].pieceNumber) req[3] = tailFace(q.board[nb], 1); }
        if (req[0] < 0 && req[1] < 0 && req[2] < 0 && req[3] < 0) continue;   // 0 contrainte -> jamais dead
        // P1 (2026-08-19) : PORTE det -> ne sonde que les cellules à >= g_dead0GateDet côtés fixes.
        // Les DEAD0 se concentrent à det=2 (frontière 'coin') ; sonder ~20% des cellules garde ~97% des morts.
        int _det = (req[0] >= 0) + (req[1] >= 0) + (req[2] >= 0) + (req[3] >= 0);
        if (_det < g_dead0GateDet) continue;
        ++_probed;
        uint64_t dom[16]; for (int w = 0; w < 16; w++) dom[w] = avail[w];
        bool deadCell = false;
        for (int s = 0; s < 4 && !deadCell; s++) {
            if (req[s] < 0) continue;
            const uint64_t* fm = g_faceMask[s][req[s]];
            uint64_t any = 0; for (int w = 0; w < 16; w++) { dom[w] &= fm[w]; any |= dom[w]; }
            if (!any) deadCell = true;   // domaine vidé -> dead (early-exit)
        }
        if (deadCell) dead++;
    }
    g_dead0Probed.fetch_add(_probed, std::memory_order_relaxed);   // 1 add/nœud (pas par cellule)
    g_dead0Found.fetch_add((uint64_t)dead, std::memory_order_relaxed);
    return dead;
}
#endif // BW_LBASSIGN_SHADOW

#ifdef BW_TAIL_FREELIST
static bool g_tailFreeList = true;   // runtime toggle A/B : ON = free-list (pièces libres), OFF = 1..256
#endif

#ifdef BW_TAIL_PROFILE
// Profilage part gen+sort dans le tail : cycles(candidate-gen + insertion sort) / cycles(total tail).
static std::atomic<uint64_t> g_genCycles{0}, g_totalTailCycles{0};
// Ventilation fine par phase (self-cycles/nœud, hors récursion) : la somme ~ total tail.
static std::atomic<uint64_t> g_cLedger{0}, g_cMrv{0}, g_cMaskSetup{0}, g_cEnum{0}, g_cPlace{0}, g_cLeaf{0};
static std::atomic<uint64_t> g_tmCalls{0}, g_tmLeaves{0}, g_cDead{0};
static inline uint64_t _rd() { return __builtin_ia32_rdtsc(); }
#endif

#ifdef BW_TAIL_PLACEMENT_MASK
static bool g_useMask = true;   // toggle runtime A/B : ON = gen bitmap, OFF = scan+sort (baseline combo)
#endif
#ifdef BW_ENUM_NCON2_DIRECT
static bool g_ncon2Direct = true;   // toggle runtime A/B : ON = chemin direct nCon==2, OFF = subset (byte-identique)
#endif
#ifdef BW_MRV_DEM_INCREMENTAL
static bool g_mrvDemInc = true;     // toggle A/B : ON = sélection curseur + dem[] incrémental, OFF = scan baseline
#endif

#ifdef BW_CUT_SNAPSHOT
// CUT_SNAPSHOT_CORPUS_V1 (Codex GO 2026-08-11) : échantillonne des VRAIS survivants LBσ du tail-solver
// (nœuds ayant passé running+lbsig<bestCost, la population pertinente) et mesure la taille de leur
// SOUS-ARBRE (descendants réellement explorés = travail évitable si on coupait ici). Le calcul des
// bornes candidates (forcedSeamLB, τ) se fait OFFLINE en Python sur le board sérialisé. Jamais en prod.
#include <vector>
struct CutSnapshot {
    uint16_t piece[256]; uint8_t rot[256];
    int running, bestCost, depth, lbsig; uint32_t oddMask;
    int rung; uint64_t subtreeStart, subtree;
};
static std::vector<CutSnapshot> g_cutSnaps;
static uint64_t g_cutNodeCtr = 0;      // compteur GLOBAL monotone de nœuds entrés (subtree = delta)
static uint64_t g_cutSurvivors = 0;    // survivants LBσ vus (pour le stride sampling)
static long     g_cutStride = 1;       // échantillonne 1 survivant sur g_cutStride
static size_t   g_cutMax = 2000;       // plafond de snapshots
static int      g_cutRung = -1;        // rung courant (strate)
static bool     g_cutSampling = false; // actif uniquement dans le driver cut-snapshot
#endif
#ifdef BW_ENUM_CAPTURE
// ENUM_SDELTA_LEAN mesure (read-only) : histogramme nCon (nœuds mask-path + candidats générés) +
// capture de tuples (nCon, base[16], matchMask[nCon][16]) pour micro-bench offline old-vs-lean bucketing.
#include <vector>
struct EnumCap { int nCon; uint64_t base[16]; uint64_t mm[4][16]; int conSide[4]; int conReq[4]; int running; int bestCost; };
static uint64_t g_ecNodes[5] = {0}, g_ecCands[5] = {0};
static std::vector<EnumCap> g_ecCaps;
static long g_ecStride = 1; static size_t g_ecMax = 20000; static uint64_t g_ecSeen = 0;
static bool g_ecOn = false;
#endif
#ifdef BW_MRV_TELEMETRY
// SEQ_CURSOR_MRV_ELISION télémétrie (read-only) : la cellule MRV sélectionnée (max det, first-wins)
// est-elle TOUJOURS la première non-placée de q.cells (ou q.cells[depth]) ? Si 100%, le scan MRV
// complet (~32%) est élidable par un simple curseur. Mesure aussi det gap / cellules scannées / fingerprint.
static uint64_t g_mrvNodes=0, g_mrvSelEqFirst=0, g_mrvSelEqDepth=0;
static uint64_t g_mrvDetGapSum=0, g_mrvSelDetSum=0, g_mrvScannedSum=0;
static uint64_t g_mrvGapHist[10]={0};   // (selK-firstUnpK) clampé 9, seulement quand sélection != première
static uint64_t g_mrvDemandCut=0;   // nœuds où le LB demande-offre tirerait (running+lb>=bestCost)
static uint64_t g_mrvFp=1469598103934665603ull;
static bool g_mrvOn=false;
#endif

__attribute__((cold, noinline))
static bool tailMrvDfs(TailMrvState& q, int depth, int running
#ifdef BW_SIGMA_LEDGER
                       , uint32_t oddMask = 0
#endif
#ifdef BW_CHECKER_LEDGER
                       , int checkerPlacedCi = -1
#endif
                       ) {
    if (running >= q.bestCost || g_stop.load(std::memory_order_relaxed))
        return false;
#ifdef BW_CUT_SNAPSHOT
    if (g_cutSampling) g_cutNodeCtr++;   // chaque nœud entré (post-guard) compté globalement
#endif
#ifdef BW_TAIL_PROFILE
    g_tmCalls.fetch_add(1, std::memory_order_relaxed);
    uint64_t _tent = _rd();
#endif
#ifdef BW_SIGMA_LEDGER
    // LBσ (borne de parité des couleurs, portée dans le tail-solver). À la complétion, chaque
    // couleur a un degré PAIR dans le multigraphe des coutures cassées (les faces de cadre sont
    // grises/appariées, donc oddMask final == 0). Chaque break futur corrige AU PLUS 2 couleurs
    // impaires -> il faut au moins ceil(popcount(oddMask)/2) breaks supplémentaires. Donc le coût
    // total minimal de toute complétion de ce sous-arbre est >= running + ceil(popcount/2). Si ce
    // minorant atteint bestCost, le sous-arbre ne peut pas améliorer l'incumbent -> coupe SOUND.
    // Renforce le prune existant `running >= bestCost` (cas popcount == 0). Placé AVANT nodes++ :
    // un nœud coupé n'est pas compté (réduction de nœuds visible en A/B).
    const int pc = __builtin_popcount(oddMask);
    const int lbsig = (pc + 1) >> 1;               // borne LBσ (0 si oddMask==0)
    if (pc) {
#ifdef BW_TAIL_LEDGER_LOCAL
        ++q.locSigCalls;
#else
        g_sigmaTailCalls.fetch_add(1, std::memory_order_relaxed);
#endif
        if (running + lbsig >= q.bestCost) {
#ifdef BW_TAIL_LEDGER_LOCAL
            ++q.locWouldCut;
#else
            g_sigmaTailWouldCut.fetch_add(1, std::memory_order_relaxed);
#endif
            if (q.sigmaOn) {
#ifdef BW_TAIL_LEDGER_LOCAL
                ++q.locCut;
#else
                g_sigmaTailCut.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef BW_TAIL_PROFILE
                g_cDead.fetch_add(_rd() - _tent, std::memory_order_relaxed);   // cycles entrée->coupe LBσ (entrée morte)
#endif
                return false; }
        }
    }
#ifdef BW_CHECKER_LEDGER
    // Lazy ledger mutation: children killed by LB-sigma return above and pay
    // nothing.  Only a sigma survivor applies the just-placed piece, and RAII
    // restores the parent state on every later exit path.
    struct CheckerGuard {
        TailMrvState& q; int ci=-1, cls=0, sign=0; int delta[CHECKER_N]={}; bool on=false;
        explicit CheckerGuard(TailMrvState& qq) : q(qq) {}
        void engage(int x) {
            if (x < 0 || !q.checkerOn) return;
            ci=x; const RotatedPiece& rp=q.board[ci]; if (!rp.pieceNumber) return;
            cls=PIECE_CLASS[rp.pieceNumber]; int r=ci>>4,c=ci&15;
            sign=((r+c)&1)?-1:1; int closed[CHECKER_N]={};
            static constexpr int CDR[4]={1,0,-1,0}, CDC[4]={0,1,0,-1};
            for (int f=0;f<4;f++) { int rr=r+CDR[f],cc=c+CDC[f];
                if(rr<0||rr>=16||cc<0||cc>=16) continue; int nb=rr*16+cc;
                if(q.inTail[nb]&&!q.placed[nb]) continue; const RotatedPiece& o=q.board[nb];
                if(!o.pieceNumber) continue; int a=tailFace(rp,f),b=tailFace(o,(f+2)&3);
                if(a!=b) for(int m=0;m<g_checkerActive;m++)
                    closed[m]+=sign*(checkerMember(m,a)-checkerMember(m,b)); }
            if(sign>0) q.checkerBlackLeft[cls]--;
            for(int m=0;m<g_checkerActive;m++) { int w=g_checkerWeight[rp.pieceNumber][m];
                delta[m]=(sign+1)*w-closed[m]; q.checkerA[m]+=delta[m];
                q.checkerHist[m][cls][w]--; }
            on=true;
        }
        ~CheckerGuard(){ if(!on)return; const RotatedPiece& rp=q.board[ci];
            for(int m=0;m<g_checkerActive;m++){ int w=g_checkerWeight[rp.pieceNumber][m];
                q.checkerHist[m][cls][w]++; q.checkerA[m]-=delta[m]; }
            if(sign>0) q.checkerBlackLeft[cls]++; }
    } checkerGuard(q);
    checkerGuard.engage(checkerPlacedCi);
    // Only survivors within two breaks of the incumbent can benefit (observed
    // maximum gain is two).  OFF has one predictable branch and no ledger work.
    if (q.checkerOn && q.nCells - depth <= g_checkerGateRemain && q.bestCost - running - lbsig <= 2) {
#ifdef BW_TAIL_LEDGER_LOCAL
        ++q.locCheckerCalls;
#else
        g_checkerCalls.fetch_add(1, std::memory_order_relaxed);
#endif
        const int lbchecker = checkerLowerBound(q, oddMask, lbsig);
        if (lbchecker > lbsig) {
#ifdef BW_TAIL_LEDGER_LOCAL
            ++q.locCheckerStronger;
            int gain=lbchecker-lbsig;if(gain>q.locCheckerMaxGain)q.locCheckerMaxGain=gain;
#else
            g_checkerStronger.fetch_add(1, std::memory_order_relaxed);
            int gain = lbchecker - lbsig, old = g_checkerMaxGain.load(std::memory_order_relaxed);
            while (gain > old && !g_checkerMaxGain.compare_exchange_weak(old, gain, std::memory_order_relaxed)) {}
#endif
        }
        if (running + lbchecker >= q.bestCost) {
#ifdef BW_TAIL_LEDGER_LOCAL
            ++q.locCheckerWould;++q.locCheckerCut;
#else
            g_checkerWouldCut.fetch_add(1, std::memory_order_relaxed);
            g_checkerCut.fetch_add(1, std::memory_order_relaxed);
#endif
            return false;
        }
    }
#endif
#ifdef BW_CUT_SNAPSHOT
    // Ce nœud a passé le prune LBσ (running+lbsig < bestCost) -> VRAI survivant. RAII probe : enregistre
    // la taille de sous-arbre (descendants) à TOUT point de sortie de cette invocation.
    struct SubtreeProbe {
        int slot; SubtreeProbe() : slot(-1) {}
        ~SubtreeProbe() { if (slot >= 0) g_cutSnaps[(size_t)slot].subtree = g_cutNodeCtr - g_cutSnaps[(size_t)slot].subtreeStart; }
    } _cutProbe;
    if (g_cutSampling) {
        g_cutSurvivors++;
        if ((g_cutSurvivors % (uint64_t)g_cutStride) == 0 && g_cutSnaps.size() < g_cutMax) {
            CutSnapshot s{};
            for (int _ci = 0; _ci < 256; _ci++) { s.piece[_ci] = q.board[_ci].pieceNumber; s.rot[_ci] = q.board[_ci].rot; }
            s.running = running; s.bestCost = q.bestCost; s.depth = depth; s.lbsig = lbsig; s.oddMask = oddMask;
            s.rung = g_cutRung; s.subtreeStart = g_cutNodeCtr; s.subtree = 0;
            _cutProbe.slot = (int)g_cutSnaps.size();
            g_cutSnaps.push_back(s);
        }
    }
#endif
#ifdef BW_LBASSIGN_SHADOW
    // LEVIER 3 : sur les SURVIVANTS LBσ (running+lbsig < bestCost), évalue la borne d'assignation.
    // PUR SHADOW — compte seulement, ne coupe JAMAIS (aucun return false). Gaté à l'endgame profond.
    if (g_assignEval && running + lbsig < q.bestCost) {
        const int remaining = q.nCells - depth;
        if (remaining >= 1 && remaining <= BW_LBASSIGN_GATE_REMAIN) {
            if (g_assignMode == 2) {
                // COMPARE : Hungarian vs Déficience sur le MÊME nœud (rétention + coûts séparés).
                auto _t0 = std::chrono::steady_clock::now(); int lh = computeLbAssign(q);
                auto _t1 = std::chrono::steady_clock::now(); int ld = computeLbDeficiency(q);
                auto _t2 = std::chrono::steady_clock::now();
                g_hungNanos.fetch_add((uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(_t1 - _t0).count(), std::memory_order_relaxed);
                g_defNanos.fetch_add((uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(_t2 - _t1).count(), std::memory_order_relaxed);
                if (lh >= 0) {
                    g_assignCalls.fetch_add(1, std::memory_order_relaxed);
                    bool hc = running + lh >= q.bestCost;
                    bool dc = (ld >= 0) && (running + ld >= q.bestCost);
                    if (hc) g_hungWould.fetch_add(1, std::memory_order_relaxed);
                    if (dc) g_defWould.fetch_add(1, std::memory_order_relaxed);
                    if (hc && dc) g_defRetain.fetch_add(1, std::memory_order_relaxed);   // déficience retient une coupe Hungarian
                    if (dc && !hc) g_defFalse.fetch_add(1, std::memory_order_relaxed);    // doit rester 0 (LBdef<=LBhung)
                }
            } else if (g_assignMode == 3) {
                // HALL_AUDIT : distribution de la taille du témoin de Hall sur les would-cut (read-only).
                auto _ta = std::chrono::steady_clock::now();
                hallAudit(q, running, q.bestCost);
                auto _tb = std::chrono::steady_clock::now();
                g_hallNanos.fetch_add((uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(_tb - _ta).count(), std::memory_order_relaxed);
            } else if (g_assignMode == 4) {
                // FILTRE DEAD-CELL BITSET (DEAD0) : compte #cellules dead via bitsets (cheap), coupe si
                // running+#dead>=bestCost. g_dead0Verify -> cross-check vs scalaire (falsePrune).
                const int remaining = q.nCells - depth;
                if (remaining >= 1 && remaining <= BW_LBASSIGN_GATE_REMAIN) {
                    auto _ta = std::chrono::steady_clock::now();
                    int dead = dead0Bitset(q);
                    auto _tb = std::chrono::steady_clock::now();
                    g_assignNanos.fetch_add((uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(_tb - _ta).count(), std::memory_order_relaxed);
                    g_assignCalls.fetch_add(1, std::memory_order_relaxed);   // nœuds où le filtre s'évalue
                    if (g_dead0Verify && dead != singletonDead(q)) g_defFalse.fetch_add(1, std::memory_order_relaxed);
                    if (running + dead >= q.bestCost) {
                        g_assignWouldCut.fetch_add(1, std::memory_order_relaxed);
                        if (g_assignApply) return false;   // coupe SOUND (#dead breaks forcés)
                    }
                }
            } else {
                auto _ta = std::chrono::steady_clock::now();
                int lb = (g_assignMode == 1) ? computeLbDeficiency(q) : computeLbAssign(q);
                auto _tb = std::chrono::steady_clock::now();
                g_assignNanos.fetch_add((uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(_tb - _ta).count(),
                                        std::memory_order_relaxed);
                if (lb >= 0) {
                    g_assignCalls.fetch_add(1, std::memory_order_relaxed);
                    // gating-test (2026-08-19) : lbDem à ce nœud (frontière demande vs q.sup) pour binner
                    // appels/coupes par classe -> le gate lbDem>=T préserve-t-il les coupes marginales assign ?
                    int _dem[NCOLORS] = {0};
                    static constexpr int _GDR[4] = {-1, 0, 1, 0}, _GDC[4] = {0, 1, 0, -1};
                    for (int _ci = 0; _ci < 256; ++_ci) {
                        if (!q.placed[_ci]) continue;
                        const RotatedPiece& _rp = q.board[_ci]; int _r = _ci >> 4, _c = _ci & 15;
                        for (int _f = 0; _f < 4; ++_f) {
                            int _rr = _r + _GDR[_f], _cc = _c + _GDC[_f];
                            if (_rr < 0 || _rr >= 16 || _cc < 0 || _cc >= 16) continue;
                            int _nb = _rr * 16 + _cc;
                            if (q.inTail[_nb] && !q.placed[_nb]) { int _col = tailFace(_rp, _f); if (_col) _dem[_col]++; }
                        }
                    }
                    int _lbdem = 0;
                    for (int _cc = 1; _cc < NCOLORS; ++_cc) if (_dem[_cc] > q.sup[_cc]) _lbdem += _dem[_cc] - q.sup[_cc];
                    int _cls = _lbdem > 5 ? 5 : _lbdem;
                    g_assignCallClass[_cls].fetch_add(1, std::memory_order_relaxed);
                    if (lb > lbsig) {
                        g_assignStronger.fetch_add(1, std::memory_order_relaxed);
                        int g = lb - lbsig, prev = g_assignMaxGain.load(std::memory_order_relaxed);
                        while (g > prev && !g_assignMaxGain.compare_exchange_weak(prev, g, std::memory_order_relaxed)) {}
                    }
                    if (running + lb >= q.bestCost) {
                        g_assignWouldCut.fetch_add(1, std::memory_order_relaxed);   // coupe EN PLUS de LBσ
                        // coupe MARGINALE (au-delà de LBσ ET LBdem) binée par classe lbDem :
                        if (running + lbsig < q.bestCost && running + _lbdem < q.bestCost)
                            g_assignCutClass[_cls].fetch_add(1, std::memory_order_relaxed);
                        if (g_assignApply) return false;   // A/B APPLIQUÉ : coupe SOUND (LB admissible)
                    }
                }
            }
        }
    }
#endif
#ifdef BW_FLUX_LEDGER
    // LBflux EN CASCADE DERRIERE LBσ. Gate tardif OBLIGATOIRE (le signal directionnel n'apparaît qu'en
    // toute fin : +36.6% à r244, +3.3% à r240). On n'évalue LBflux que si (a) LBσ a SURVÉCU à ce nœud,
    // (b) cellules restantes <= seuil, (c) slack résiduel après LBσ <= seuil. Coupe SOUND :
    // running + max(LBσ, LBflux) >= bestCost — on ne SOMME JAMAIS les deux bornes.
    if (q.fluxEval && running + lbsig < q.bestCost) {
        const int remaining = q.nCells - depth;
        const int slack = (q.bestCost - 1) - running - lbsig;
        if (remaining <= g_fluxGateRemain && slack <= g_fluxGateSlack) {
            g_fluxCalls.fetch_add(1, std::memory_order_relaxed);
            const int lbflux = computeLbFlux(q);       // froid, recompute FULL depuis le board
            if (lbflux > lbsig) {                       // diagnostic : borne directionnelle strictement > parité
                g_fluxStronger.fetch_add(1, std::memory_order_relaxed);
                int g = lbflux - lbsig, prev = g_fluxMaxGain.load(std::memory_order_relaxed);
                while (g > prev && !g_fluxMaxGain.compare_exchange_weak(prev, g, std::memory_order_relaxed)) {}
            }
            if (running + lbflux >= q.bestCost) {      // == running + max(lbsig,lbflux) (lbflux>lbsig ici)
                g_fluxWouldCut.fetch_add(1, std::memory_order_relaxed);
                if (q.fluxOn) { g_fluxCut.fetch_add(1, std::memory_order_relaxed); return false; }
            }
        }
    }
#endif
#endif
    if (q.nodes >= q.nodeCap) {
        q.capped = true;
        return false;
    }
    q.nodes++;
#ifdef BW_TAIL_LEDGER_LOCAL
    if ((q.nodes & 0xFFFFF) == 0) flushTailLedger(q);   // flush amorti ~1M nœuds (fraîcheur lectures live)
#endif
    if (q.progress && (q.nodes & 0xFFFFF) == 0)   // ~every 1M nodes: publish live progress
        q.progress->store(q.nodes, std::memory_order_relaxed);
    // P7-B: refresh the pruning bound from the shared incumbent (~every 4K nodes)
    if (q.sharedBest && (q.nodes & 0xFFF) == 0) {
        int sb = q.sharedBest->load(std::memory_order_relaxed);
        if (sb < q.bestCost) q.bestCost = sb;
    }
    // P7-B: cube generation — snapshot the partial state at cubeDepth and stop
    if (q.cubeDepth >= 0 && depth == q.cubeDepth) {
        long idx = q.cubeCount++;   // stable deterministic cube_id
        bool keep = q.cubeLo < 0 || (idx >= q.cubeLo && idx < q.cubeHi);
        if (keep && q.pathOut) {   // P8-B: record compact path (occupied tail cells)
            auto* out = (std::vector<PathCube>*)q.pathOut;
            PathCube pc; pc.depth = 0; pc.running = running;
            for (int k = 0; k < q.nCells; k++) {
                int ci = q.cells[k];
                if (q.board[ci].pieceNumber) {
                    if (pc.depth >= PATHCUBE_CAP) {   // fail-fast: never silently truncate a path
                        g_pathOverflow.store(true, std::memory_order_relaxed);
                        g_stop.store(true, std::memory_order_relaxed);
                        return false;
                    }
                    pc.cell[pc.depth] = (uint8_t)ci; pc.piece[pc.depth] = q.board[ci].pieceNumber;
                    pc.rot[pc.depth] = q.board[ci].rot; pc.depth++;
                }
            }
            out->push_back(pc);
        } else if (keep && q.cubeOut) {
            auto* out = (std::vector<TailCube>*)q.cubeOut;
            TailCube c;
            memcpy(c.board, q.board, sizeof c.board);
            memcpy(c.used, q.used, sizeof c.used);
            c.running = running; c.depth = depth;
            out->push_back(c);
        }
        return false;
    }
    if (depth == q.nCells) {
#ifdef BW_TAIL_PROFILE
        g_tmLeaves.fetch_add(1, std::memory_order_relaxed);
        uint64_t _tlf = _rd(); int score = verifyBoard(q.board); g_cLeaf.fetch_add(_rd() - _tlf, std::memory_order_relaxed);
#else
        int score = verifyBoard(q.board);
#endif
#ifdef BW_SIGMA_LEDGER
        // SELF-CHECK soundness : toute feuille complète VALIDE doit avoir oddMask == 0 (parité paire
        // par couleur). Un non-zéro révélerait un bug du modèle de delta (init préfixe ou sDelta).
        if (score >= 0 && oddMask != 0)
#ifdef BW_TAIL_LEDGER_LOCAL
            ++q.locLeafBug;
#else
            g_sigmaTailLeafBug.fetch_add(1, std::memory_order_relaxed);
#endif
#ifdef BW_CHECKER_LEDGER
        if (q.checkerOn && score >= 0) {
            bool bad = false;
            for (int m = 0; m < g_checkerActive; m++) bad |= q.checkerA[m] != 0;
            if (bad)
#ifdef BW_TAIL_LEDGER_LOCAL
                ++q.locCheckerBug;
#else
                g_checkerLeafBug.fetch_add(1, std::memory_order_relaxed);
#endif
        }
#endif
#ifdef BW_FLUX_LEDGER
        // SELF-CHECK flux : sous énumération (soundness), toute feuille complète valide doit avoir un
        // résidu de flux NUL (toutes coutures fermées). Non-nul = bug du modèle de conservation.
        if (q.enumerate && score >= 0 && fluxLeafResidualNonZero(q.board))
            g_fluxLeafBug.fetch_add(1, std::memory_order_relaxed);
#endif
        if (q.enumerate) {   // recensement exhaustif (soundness) : pas de resserrement de bestCost
            if (score >= 0 && (480 - score) < q.enumBudget) {
                q.enumLeaves++;
                uint64_t hb = 1469598103934665603ULL;   // FNV-1a inline (fnv1a() défini plus bas)
                const uint8_t* bb = (const uint8_t*)q.board;
                for (size_t z = 0; z < 256 * sizeof(RotatedPiece); z++) { hb ^= bb[z]; hb *= 1099511628211ULL; }
                q.enumHash ^= hb;   // XOR sur les feuilles = accumulateur ordre-indépendant
            }
            return false;
        }
#endif
        if (score < 0 || 480 - score >= q.bestCost) return false;
        q.bestCost = 480 - score;          // new incumbent tightens the bound
        q.bestRing = countRingMismatches(q.board);
        q.solvedScore = score;
        memcpy(q.bestBoard, q.board, sizeof q.bestBoard);
        if (q.sharedBest) {                // publish the tighter bound to the pool
            int p = q.sharedBest->load(std::memory_order_relaxed);
            while (q.bestCost < p &&
                   !q.sharedBest->compare_exchange_weak(p, q.bestCost,
                                                        std::memory_order_relaxed)) {}
        }
        return false;                      // keep searching for a cheaper filling
    }

    static constexpr int DR[4] = {1, 0, -1, 0};
    static constexpr int DC[4] = {0, 1, 0, -1};
#ifdef BW_TAIL_TRUE_MRV
    // True MRV: choose the cell with the fewest currently legal
    // (piece,rotation) values.  The former topological proxy only maximized the
    // number of determined neighbours; it could therefore branch on a cell
    // with dozens of values while another live cell already had a singleton or
    // an empty domain.  This is a cold-path endgame solver, so spending a scan
    // here is cheap relative to the subtree it avoids.  Determined-neighbour
    // count remains the stable tie-break.
    int ci = -1, bestDomain = INT_MAX, bestDet = -1;
    for (int k = 0; k < q.nCells; k++) {
        int x = q.cells[k];
        if (q.placed[x]) continue;
        int r = x >> 4, c = x & 15, det = 0;
        for (int f = 0; f < 4; f++) {
            int rr = r + DR[f], cc = c + DC[f];
            if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) { det++; continue; }
            int nb = rr * 16 + cc;
            if (!q.inTail[nb] || q.placed[nb]) det++;
        }
        int domain = 0;
        for (int p = 1; p <= 256; p++) {
            if (q.used[p]) continue;
            if (IS_CLUE[p] && q.cluePiece[x] != p) continue;
            if (q.cluePiece[x] && q.cluePiece[x] != p) continue;
            for (int rot = 0; rot < 4; rot++) {
                if (q.cluePiece[x] && q.clueRot[x] != rot) continue;
                if (!tailFrameOK(x, p, rot)) continue;
                RotatedPiece rp = {(uint16_t)p, (uint8_t)rot,
                                   sideAfterRot(PIECES[p], rot, 0),
                                   sideAfterRot(PIECES[p], rot, 1), 0,
                                   PIECE_HSC[p], 0};
                int add = 0;
                for (int f = 0; f < 4; f++) {
                    int rr = r + DR[f], cc = c + DC[f];
                    if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) continue;
                    int nb = rr * 16 + cc;
                    if (q.inTail[nb] && !q.placed[nb]) continue;
                    const RotatedPiece& other = q.board[nb];
                    if (!other.pieceNumber ||
                        tailFace(rp, f) != tailFace(other, (f + 2) & 3))
                        add++;
                }
                domain += running + add < q.bestCost;
            }
        }
        if (domain == 0) return false;
        if (domain < bestDomain || (domain == bestDomain && det > bestDet)) {
            bestDomain = domain;
            bestDet = det;
            ci = x;
        }
    }
#else
    // Production baseline: a cheap MRV proxy that maximizes already determined
    // neighbours.  Frame sides count because they restrict the piece class.
    //
    // The same scan collects the colour demand of every open seam, giving an
    // admissible bound: a demand edge of colour c can only be matched by one of
    // the sup[c] colour-c edges still in hand, so at least
    // sum_c max(0, demand[c] - sup[c]) further seams must mismatch. Cheap here
    // (one pass over a handful of cells) and it is what makes a shallower
    // cutoff — a wider exact region — affordable.
#ifdef BW_TAIL_PROFILE
    uint64_t _tmrv = _rd();
#endif
    int ci = -1, bestDet = -1;
    int dem[NCOLORS] = {0};
#ifdef BW_MRV_TELEMETRY
    int _selK = -1, _firstUnpK = -1, _firstDet = -1;
#endif
    bool doneInc = false;
#ifdef BW_MRV_DEM_INCREMENTAL
    // MRV_DEM_INCREMENTAL : sélection curseur (ci=q.cells[depth], prouvé == argmax à 100%) + dem[] maintenu
    // incrémentalement. q.dem = état du nœud parent ; on applique LAZY (ici, après gates/cube/leaf) le delta
    // de q.cells[depth-1] posé par le parent, RAII restaure à toute sortie -> les ~96% enfants morts LBσ
    // (qui retournent AVANT ce point) ne paient rien.
    struct DemGuard {
        TailMrvState& q; int ci; bool on;
        DemGuard(TailMrvState& q_) : q(q_), ci(-1), on(false) {}
        void delta(int s) {
            static constexpr int GDR[4] = {1, 0, -1, 0}, GDC[4] = {0, 1, 0, -1};
            int r = ci >> 4, c = ci & 15;
            for (int f = 0; f < 4; f++) {
                int rr = r + GDR[f], cc = c + GDC[f];
                if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) continue;   // hors grille : aucun terme dem
                int nb = rr * 16 + cc;
                if (q.inTail[nb] && !q.placed[nb]) q.dem[tailFace(q.board[ci], f)] += s;         // ci devient déterminé pour nb ouvert
                else if (q.board[nb].pieceNumber) q.dem[tailFace(q.board[nb], (f + 2) & 3)] -= s; // retire la demande de ci-ouvert vers nb posé
            }
        }
        void engage(int c_) { ci = c_; on = true; delta(+1); }
        ~DemGuard() { if (on) delta(-1); }
    } _demg(q);
    if (g_mrvDemInc) {
        if (depth == 0) {   // racine : recompute full une fois
            for (int cc = 0; cc < NCOLORS; cc++) q.dem[cc] = 0;
            for (int k = 0; k < q.nCells; k++) { int x = q.cells[k]; if (q.placed[x]) continue; int r = x >> 4, c = x & 15;
                for (int f = 0; f < 4; f++) { int rr = r + DR[f], cc2 = c + DC[f]; if (rr < 0 || rr >= 16 || cc2 < 0 || cc2 >= 16) continue; int nb = rr * 16 + cc2;
                    if (!q.inTail[nb] || q.placed[nb]) { const RotatedPiece& o = q.board[nb]; if (o.pieceNumber) q.dem[tailFace(o, (f + 2) & 3)]++; } } }
        } else {
            _demg.engage(q.cells[depth - 1]);   // applique le delta de la pièce posée par le parent (RAII undo)
        }
        ci = q.cells[depth];
#ifdef BW_MRV_DEM_DEBUG
        {   int dbg[NCOLORS] = {0}; int dci = -1, dbest = -1;
            for (int k = 0; k < q.nCells; k++) { int x = q.cells[k]; if (q.placed[x]) continue; int r = x >> 4, c = x & 15, det = 0;
                for (int f = 0; f < 4; f++) { int rr = r + DR[f], cc2 = c + DC[f]; if (rr < 0 || rr >= 16 || cc2 < 0 || cc2 >= 16) { det++; continue; } int nb = rr * 16 + cc2;
                    if (!q.inTail[nb] || q.placed[nb]) { det++; const RotatedPiece& o = q.board[nb]; if (o.pieceNumber) dbg[tailFace(o, (f + 2) & 3)]++; } }
                if (det > dbest) { dbest = det; dci = x; } }
            for (int cc = 0; cc < NCOLORS; cc++) if (dbg[cc] != q.dem[cc]) { fprintf(stderr, "DEM_MISMATCH depth=%d col=%d inc=%d full=%d\n", depth, cc, q.dem[cc], dbg[cc]); abort(); }
            if (dci != ci) { fprintf(stderr, "MRV_CI_MISMATCH depth=%d inc=%d full=%d\n", depth, ci, dci); abort(); }
        }
#endif
        doneInc = true;
    }
    if (!doneInc)
#endif
    for (int k = 0; k < q.nCells; k++) {
        int x = q.cells[k];
        if (q.placed[x]) continue;
        int r = x >> 4, c = x & 15, det = 0;
        for (int f = 0; f < 4; f++) {
            int rr = r + DR[f], cc = c + DC[f];
            if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) { det++; continue; }
            int nb = rr * 16 + cc;
            if (!q.inTail[nb] || q.placed[nb]) {
                det++;
                const RotatedPiece& o = q.board[nb];
                if (o.pieceNumber) dem[tailFace(o, (f + 2) & 3)]++;
            }
        }
#ifdef BW_MRV_TELEMETRY
        if (_firstUnpK < 0) { _firstUnpK = k; _firstDet = det; }
#endif
        if (det > bestDet) { bestDet = det; ci = x;
#ifdef BW_MRV_TELEMETRY
            _selK = k;
#endif
        }
    }
#ifdef BW_MRV_TELEMETRY
    if (g_mrvOn && ci >= 0) {
        g_mrvNodes++;
        if (_selK == _firstUnpK) g_mrvSelEqFirst++;
        if (ci == q.cells[depth]) g_mrvSelEqDepth++;
        g_mrvDetGapSum += (uint64_t)(bestDet - _firstDet);
        g_mrvSelDetSum += (uint64_t)bestDet;
        int _scan = 0; for (int k = 0; k < q.nCells; k++) if (!q.placed[q.cells[k]]) _scan++;
        g_mrvScannedSum += (uint64_t)_scan;
        g_mrvFp = g_mrvFp * 1099511628211ull + (uint64_t)(ci + 1) * 131u + (uint64_t)depth;
        if (_selK != _firstUnpK) { int g = _selK - _firstUnpK; if (g > 9) g = 9; if (g < 0) g = 0; g_mrvGapHist[g]++; }
    }
#endif
#ifdef BW_TAIL_PROFILE
    g_cMrv.fetch_add(_rd() - _tmrv, std::memory_order_relaxed);
#endif
    const int* _demPtr = dem;
#ifdef BW_MRV_DEM_INCREMENTAL
    if (g_mrvDemInc) _demPtr = q.dem;
#endif
    int lb = 0;
    for (int c2 = 1; c2 < NCOLORS; c2++)
        if (_demPtr[c2] > q.sup[c2]) lb += _demPtr[c2] - q.sup[c2];
#ifdef BW_LBASSIGN_SHADOW
    if (g_traceBackjump) traceBackjump(q, depth);   // P3 : trace read-only (aucun saut/coupe, arbre identique) — appel guardé (fonction dans le bloc shadow)
#endif
#ifdef BW_SIGMA_LEDGER
    // ===== LBdemSigma (handoff 2026-08-18) : borne conjointe déficit-demande + parité LBσ =====
    // Chaque future erreur (couture cassée) = une arête du multigraphe des couleurs : +1 degré à 2
    // couleurs DISTINCTES (les 2 faces d'une erreur diffèrent). À la complétion tous les degrés sont
    // pairs (oddMask final == 0). Pour la couleur c : (a) déficit d_c = max(0,dem[c]-sup[c]) force
    // >= d_c erreurs incidentes à c ; (b) parité p_c = bit c de oddMask impose que le nb d'erreurs
    // incidentes à c ait la parité p_c. Donc erreurs incidentes à c >= r_c = d_c + ((d_c^p_c)&1).
    // Somme des degrés = 2*(#erreurs) => #erreurs >= ceil(Σ r_c / 2) = LBdegree. Avec d_c=0 partout,
    // LBdegree == LBσ (r_c=p_c => Σ r_c = popcount(oddMask)). LBdemSigma = max(LBdem, LBdegree) borne
    // SOUND le coût de complétion (jamais additionner LBdem+LBσ). Toujours >= max(LBdem, LBσ).
    // NB MESURE : bloc ENTIER derrière q.demSigmaOn -> le bras baseline (OFF) ne paie AUCUN coût de
    // calcul, donc l'A/B mesure le NET réel (bénéfice de coupe MOINS coût de la boucle 22-couleurs).
    // A ADAPTATIF (2026-08-19) : porte cheap `lb >= demSigGateT` (lb=LBdem déjà calculé gratuitement) ->
    // on ne paie la boucle 22-couleurs QUE sur les états à déficit riche (là où le gain se concentre).
    if (q.demSigmaOn && lb >= q.demSigGateT) {
        int degreeNeed = 0;
        for (int c = 1; c < NCOLORS; ++c) {
            const int d = (int)_demPtr[c] > (int)q.sup[c] ? (int)_demPtr[c] - (int)q.sup[c] : 0;
            const int p = (int)((oddMask >> c) & 1u);
            degreeNeed += d + ((d ^ p) & 1);
        }
        const int lbDegree = (degreeNeed + 1) >> 1;      // ceil(Σ r_c / 2)
        const int lbJoint  = lb > lbDegree ? lb : lbDegree;
#ifdef BW_TAIL_LEDGER_LOCAL
        ++q.locDemSigCalls;
        if (lbJoint > lbsig && lbJoint > lb) ++q.locDemSigStronger;   // strictement mieux que les 2 bornes existantes
#else
        g_demSigmaCalls.fetch_add(1, std::memory_order_relaxed);
        if (lbJoint > lbsig && lbJoint > lb) g_demSigmaStronger.fetch_add(1, std::memory_order_relaxed);
#endif
        // coupe MARGINALE : ce que ni LBσ (déjà passé plus haut) ni LBdem (cut juste en dessous)
        // n'auraient attrapé -> running+lb < bestCost mais running+lbJoint >= bestCost.
        if (running + lbJoint >= q.bestCost && running + lb < q.bestCost) {
            const int cls = lb > 5 ? 5 : lb;   // classe de déficit pour choisir la porte T
#ifdef BW_TAIL_LEDGER_LOCAL
            ++q.locDemSigWould; ++q.locDemSigCut; ++q.locDemSigWClass[cls];
#else
            g_demSigmaWould.fetch_add(1, std::memory_order_relaxed);
            g_demSigmaCuts.fetch_add(1, std::memory_order_relaxed);
            g_demSigWClass[cls].fetch_add(1, std::memory_order_relaxed);
#endif
            return false;
        }
    }
#endif
#ifdef BW_MRV_TELEMETRY
    // Le LB demande-offre est-il un VRAI prune (mord au-delà de ce que la suite coupe) ? Si oui, éliminer
    // le scan MRV change l'arbre. On compte les nœuds où running+lb>=bestCost (le prune demande tirerait).
    if (g_mrvOn && ci >= 0 && running + lb >= q.bestCost) g_mrvDemandCut++;
#endif
    if (running + lb >= q.bestCost) return false;
#endif
#ifdef BW_TAIL_HALL
    if (!hallFeasible(q, running)) return false;   // tight-slack matching prune
#endif

#ifdef BW_SIGMA_LEDGER
    struct Cand { RotatedPiece rp; uint8_t add; uint32_t sDelta; };
#else
    struct Cand { RotatedPiece rp; uint8_t add; };
#endif
    Cand cand[1024];
    int nc = 0, r = ci >> 4, c = ci & 15;
#ifdef BW_TAIL_PROFILE
    uint64_t _pg0 = __builtin_ia32_rdtsc();
#endif
#ifdef BW_TAIL_PLACEMENT_MASK
    if (g_useMask) {
    // ---- Génération de candidats par BITMAP (remplace scan + gen + tri) ----
    if (depth == 0 && !q.availInit) {
        for (int w = 0; w < 16; w++) q.availPlacement[w] = 0;
        for (int pp = 1; pp <= 256; pp++) if (!q.used[pp]) plSet(q.availPlacement, pp);
        q.availInit = true;
    }
#ifdef BW_TAIL_MASK_DEBUG
    // Invariant à CHAQUE nœud : availPlacement cohérent avec used[] (bit libre == !used). Détecte un
    // plClear/plSet manquant OU un availPlacement non restauré après undo/retour de récursion.
    for (int _p = 1; _p <= 256; _p++) {
        int _b = (_p - 1) * 4; bool _av = (q.availPlacement[_b >> 6] >> (_b & 63)) & 1;
        if (_av == q.used[_p]) { fprintf(stderr, "AVAIL_MISMATCH p=%d used=%d av=%d depth=%d\n", _p, (int)q.used[_p], (int)_av, depth); abort(); }
    }
#endif
    {
#ifdef BW_TAIL_PROFILE
        uint64_t _tms = _rd();
#endif
        const int sig = ((r == 15) ? 1 : 0) | ((c == 15) ? 2 : 0) | ((r == 0) ? 4 : 0) | ((c == 0) ? 8 : 0);
        uint64_t base[16];
        for (int w = 0; w < 16; w++) base[w] = g_plFrame[sig][w] & q.availPlacement[w];
        if (q.cluePiece[ci]) {                     // cellule-indice : force (piece,rot) exact
            int cb = (q.cluePiece[ci] - 1) * 4 + q.clueRot[ci], cw = cb >> 6; uint64_t cbit = 1ull << (cb & 63);
            for (int w = 0; w < 16; w++) base[w] &= (w == cw ? cbit : 0ull);
        } else {                                   // cellule non-indice : exclure les pièces-indices
            for (int w = 0; w < 16; w++) base[w] &= ~g_plClue[w];
        }
        // côtés contraints = voisins FIXES POSÉS (ni bordure ni ouvert) + couleur requise
        int nCon = 0, conSide[4], conReq[4];
        for (int f = 0; f < 4; f++) {
            int rr = r + DR[f], cc = c + DC[f];
            if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) continue;
            int nb = rr * 16 + cc;
            if (q.inTail[nb] && !q.placed[nb]) continue;
            const RotatedPiece& other = q.board[nb];
            if (!other.pieceNumber) continue;
            conSide[nCon] = f; conReq[nCon] = tailFace(other, (f + 2) & 3); nCon++;
        }
        uint64_t matchMask[4][16];
        for (int i = 0; i < nCon; i++) for (int w = 0; w < 16; w++) matchMask[i][w] = g_plFace[conSide[i]][conReq[i]][w];
#ifdef BW_ENUM_CAPTURE
        if (g_ecOn) {
            g_ecNodes[nCon]++;
            if ((++g_ecSeen % (uint64_t)g_ecStride) == 0 && g_ecCaps.size() < g_ecMax) {
                EnumCap e; e.nCon = nCon; e.running = running; e.bestCost = q.bestCost;
                for (int w = 0; w < 16; w++) e.base[w] = base[w];
                for (int i = 0; i < nCon; i++) { for (int w = 0; w < 16; w++) e.mm[i][w] = matchMask[i][w]; e.conSide[i] = conSide[i]; e.conReq[i] = conReq[i]; }
                g_ecCaps.push_back(e);
            }
        }
#endif
#ifdef BW_TAIL_PROFILE
        g_cMaskSetup.fetch_add(_rd() - _tms, std::memory_order_relaxed);
#endif
        // énumération par COÛT croissant (add = nb côtés cassés), ordre piece/rot dans chaque coût.
        bool doneDirect = false;
#ifdef BW_ENUM_NCON2_DIRECT
        // Chemin spécialisé nCon==2 (100% des nœuds mask-path mesurés) : bucketing direct + sDelta spécialisé.
        // Séquence (add, piece, rot) et sDelta STRICTEMENT identiques au chemin subset (prouvé bit-exact,
        // enum_ncon2_bench.cpp : 0 mismatch sur 20000 tuples réels). Fallback subset pour nCon != 2.
        if (nCon == 2 && g_ncon2Direct) {
            const uint64_t* A = matchMask[0]; const uint64_t* B = matchMask[1];
            const int s0 = conSide[0], rq0 = conReq[0], s1 = conSide[1], rq1 = conReq[1];
            for (int add = 0; add <= 2; add++) {
                if (running + add >= q.bestCost) break;
                uint64_t costMask[16];
                if (add == 0)      { for (int w = 0; w < 16; w++) costMask[w] = base[w] & A[w] & B[w]; }
                else if (add == 1) { for (int w = 0; w < 16; w++) costMask[w] = base[w] & (A[w] ^ B[w]); }
                else               { for (int w = 0; w < 16; w++) costMask[w] = base[w] & ~(A[w] | B[w]); }
                for (int w = 0; w < 16; w++) {
                    uint64_t bits = costMask[w];
                    while (bits) {
                        int bi = __builtin_ctzll(bits); bits &= bits - 1;
                        int idx = w * 64 + bi, p = idx / 4 + 1, rot = idx & 3;
                        RotatedPiece rp = {(uint16_t)p, (uint8_t)rot, g_face[p][rot][0], g_face[p][rot][1], 0, PIECE_HSC[p], 0};
#ifdef BW_SIGMA_LEDGER
                        uint32_t sDelta;
                        if (add == 0) sDelta = 0;
                        else if (add == 1) {
                            int s, oc; if ((A[w] >> bi) & 1) { s = s1; oc = rq1; } else { s = s0; oc = rq0; }
                            int mc = g_face[p][rot][s]; sDelta = (mc ? (1u << mc) : 0u) ^ (oc ? (1u << oc) : 0u);
                        } else {
                            int mc0 = g_face[p][rot][s0], mc1 = g_face[p][rot][s1];
                            sDelta = ((mc0 ? (1u << mc0) : 0u) ^ (rq0 ? (1u << rq0) : 0u))
                                   ^ ((mc1 ? (1u << mc1) : 0u) ^ (rq1 ? (1u << rq1) : 0u));
                        }
                        cand[nc++] = {rp, (uint8_t)add, sDelta};
#else
                        cand[nc++] = {rp, (uint8_t)add};
#endif
                    }
                }
            }
            doneDirect = true;
        }
#endif
        if (!doneDirect)
        for (int add = 0; add <= nCon; add++) {
            if (running + add >= q.bestCost) break;
            const int m = nCon - add;
            uint64_t costMask[16]; for (int w = 0; w < 16; w++) costMask[w] = 0;
            for (int T = 0; T < (1 << nCon); T++) {
                if (__builtin_popcount((unsigned)T) != m) continue;
                uint64_t sub[16]; for (int w = 0; w < 16; w++) sub[w] = base[w];
                for (int i = 0; i < nCon; i++)
                    if ((T >> i) & 1) { for (int w = 0; w < 16; w++) sub[w] &= matchMask[i][w]; }
                    else              { for (int w = 0; w < 16; w++) sub[w] &= ~matchMask[i][w]; }
                for (int w = 0; w < 16; w++) costMask[w] |= sub[w];
            }
            for (int w = 0; w < 16; w++) {
                uint64_t bits = costMask[w];
                while (bits) {
                    int bi = __builtin_ctzll(bits); bits &= bits - 1;
                    int idx = w * 64 + bi, p = idx / 4 + 1, rot = idx & 3;
                    RotatedPiece rp = {(uint16_t)p, (uint8_t)rot, g_face[p][rot][0], g_face[p][rot][1], 0, PIECE_HSC[p], 0};
#ifdef BW_SIGMA_LEDGER
                    uint32_t sDelta = 0;
                    for (int i = 0; i < nCon; i++) if (!((matchMask[i][w] >> bi) & 1)) {
                        int mc = g_face[p][rot][conSide[i]], oc = conReq[i];
                        sDelta ^= (mc ? (1u << mc) : 0u) ^ (oc ? (1u << oc) : 0u);
                    }
                    cand[nc++] = {rp, (uint8_t)add, sDelta};
#else
                    cand[nc++] = {rp, (uint8_t)add};
#endif
                }
            }
        }
#ifdef BW_ENUM_CAPTURE
        if (g_ecOn) g_ecCands[nCon] += nc;   // candidats générés par ce nœud mask-path (par nCon)
#endif
    }
    } else {
#endif
#ifdef BW_TAIL_FREELIST
    // Construit une fois (depth 0) la liste itérée, ordre ascendant. g_tailFreeList ON = seulement les
    // pièces initialement libres (~nCells) ; OFF = liste complète 1..256 (= baseline exact pour l'A/B).
    if (depth == 0) {
        q.nFree = 0;
        if (g_tailFreeList) { for (int p = 1; p <= 256; p++) if (!q.used[p]) q.freeList[q.nFree++] = p; }
        else                { for (int p = 1; p <= 256; p++) q.freeList[q.nFree++] = p; }
    }
    // Itère la liste (ordre ascendant identique à 1..256) : en ON, évite ~230 tests used[] inutiles/nœud
    // à l'endgame. Ne change ni les candidats ni leur ordre -> arbre/fingerprint identiques.
    for (int fi = 0; fi < q.nFree; fi++) {
        int p = q.freeList[fi];
        if (q.used[p]) continue;
        if (IS_CLUE[p] && q.cluePiece[ci] != p) continue;
#else
    for (int p = 1; p <= 256; p++) {
        if (q.used[p]) continue;
        if (IS_CLUE[p] && q.cluePiece[ci] != p) continue;
#endif
        if (q.cluePiece[ci] && q.cluePiece[ci] != p) continue;
        for (int rot = 0; rot < 4; rot++) {
            if (q.cluePiece[ci] && q.clueRot[ci] != rot) continue;
            if (!tailFrameOK(ci, p, rot)) continue;
            RotatedPiece rp = {(uint16_t)p, (uint8_t)rot,
                               sideAfterRot(PIECES[p], rot, 0),
                               sideAfterRot(PIECES[p], rot, 1), 0,
                               PIECE_HSC[p], 0};
            int add = 0;
#ifdef BW_SIGMA_LEDGER
            uint32_t sDelta = 0;   // parité XOR des coutures CASSÉES fermées par ce placement
#endif
            for (int f = 0; f < 4; f++) {
                int rr = r + DR[f], cc = c + DC[f];
                if (rr < 0 || rr >= 16 || cc < 0 || cc >= 16) continue;
                int nb = rr * 16 + cc;
                if (q.inTail[nb] && !q.placed[nb]) continue;
                const RotatedPiece& other = q.board[nb];
                if (!other.pieceNumber || tailFace(rp, f) != tailFace(other, (f + 2) & 3)) {
                    add++;
#ifdef BW_SIGMA_LEDGER
                    // Couture cassée vers un voisin DÉTERMINÉ (préfixe ou cellule tail déjà posée) :
                    // flippe la parité des deux couleurs de la couture. nz saute la couleur 0 (cadre).
                    if (other.pieceNumber) {
                        const int mc = tailFace(rp, f), oc = tailFace(other, (f + 2) & 3);
                        sDelta ^= (mc ? (1u << mc) : 0u) ^ (oc ? (1u << oc) : 0u);
                    }
#endif
                }
            }
            if (running + add < q.bestCost)
#ifdef BW_SIGMA_LEDGER
                cand[nc++] = {rp, (uint8_t)add, sDelta};
#else
                cand[nc++] = {rp, (uint8_t)add};
#endif
        }
    }
    // With <=8 cells, insertion sort is cheaper and simpler than allocating.
    for (int a = 1; a < nc; a++) {
        Cand v = cand[a]; int b = a - 1;
        while (b >= 0 && cand[b].add > v.add) { cand[b + 1] = cand[b]; b--; }
        cand[b + 1] = v;
    }
#ifdef BW_TAIL_PLACEMENT_MASK
    }   // fin du if(g_useMask) else (scan+sort)
#endif
#ifdef BW_TAIL_PROFILE
    g_genCycles.fetch_add(__builtin_ia32_rdtsc() - _pg0, std::memory_order_relaxed);
#endif

    q.placed[ci] = true;
    for (int i = 0; i < nc; i++) {
        // Parallel tail slicing: at the top MRV level, this worker owns only the
        // candidate classes i % sliceN == sliceS. Deeper levels run in full so
        // each class is a complete, disjoint sub-search (union == serial search).
        if (depth == 0 && q.sliceN > 0 && (i % q.sliceN) != q.sliceS) continue;
#ifdef BW_TAIL_PROFILE
        uint64_t _tpl = _rd();
#endif
        RotatedPiece rp = cand[i].rp;
        rp.breakCount = cand[i].add; // metadata only; verifier owns the score
        q.board[ci] = rp;
        q.used[rp.pieceNumber] = true;
        if (g_traceBackjump) { g_placeDepth[ci] = depth; g_pieceUsedAtDepth[rp.pieceNumber] = depth; }   // P3
#ifdef BW_TAIL_PLACEMENT_MASK
        plClear(q.availPlacement, rp.pieceNumber);
#endif
        const Piece& pl = PIECES[rp.pieceNumber];
        q.sup[pl.n]--; q.sup[pl.e]--; q.sup[pl.s]--; q.sup[pl.w]--;
#ifdef BW_TAIL_PROFILE
        g_cPlace.fetch_add(_rd() - _tpl, std::memory_order_relaxed);   // mutation pré-récursion (undo symétrique ~= x2)
#endif
        tailMrvDfs(q, depth + 1, running + cand[i].add
#ifdef BW_SIGMA_LEDGER
                   , oddMask ^ cand[i].sDelta
#endif
#ifdef BW_CHECKER_LEDGER
                   , ci
#endif
                   );
        q.sup[pl.n]++; q.sup[pl.e]++; q.sup[pl.s]++; q.sup[pl.w]++;
        if (q.nodes >= q.nodeCap || g_stop.load(std::memory_order_relaxed)) {
            if (q.nodes >= q.nodeCap) q.capped = true;   // reliable NODE_CAP vs EXHAUSTED verdict
            q.used[rp.pieceNumber] = false;
#ifdef BW_TAIL_PLACEMENT_MASK
            plSet(q.availPlacement, rp.pieceNumber);
#endif
            q.board[ci] = {};
            q.placed[ci] = false;
            return false;
        }   // supply already restored above
        q.used[rp.pieceNumber] = false;
        if (g_traceBackjump) g_pieceUsedAtDepth[rp.pieceNumber] = -1;   // P3 undo
#ifdef BW_TAIL_PLACEMENT_MASK
        plSet(q.availPlacement, rp.pieceNumber);
#endif
        q.board[ci] = {};
    }
    q.placed[ci] = false;
    if (g_traceBackjump) g_placeDepth[ci] = -1;   // P3 undo
    return false;
}

// Exactly complete the fill-order suffix from startDepth, minimizing total
// mismatches.  Returns the best score reachable within `budgetOverride` (or the
// schedule's total budget), or -1 when no filling that cheap exists.  On success
// `board` holds the winning arrangement.  `costOut` reports the cheapest cost
// seen even when it misses the budget, which is what the endgame telemetry
// needs: the interesting question is not "did it fit" but "by how much did it
// miss".
__attribute__((cold, noinline))
static int solveTailMrv(RotatedPiece* board, bool* used, int startDepth,
                        int breaksUsed, uint64_t nodeCap, uint64_t* nodesOut,
                        bool* cappedOut = nullptr, int* costOut = nullptr,
                        int budgetOverride = -1, int acceptCost = INT_MAX,
                        int* ringOut = nullptr, int sliceS = -1, int sliceN = 0,
                        int initialBestCost = -1,
                        std::atomic<uint64_t>* progress = nullptr,
                        RotatedPiece* incumbentOut = nullptr, int* incScoreOut = nullptr) {
    TailMrvState q;
    q.board = board;
    q.used = used;
    q.sliceS = sliceS;
    q.sliceN = sliceN;
    q.progress = progress;
    q.nodeCap = nodeCap;
    q.budget = budgetOverride >= 0 ? budgetOverride : TOTAL_BUDGET;
    // Carry the incumbent already proven by a shallower rung: start the B&B bound
    // at the known best cost so this rung only searches for a STRICTLY better
    // filling (Codex INCUMBENT_CARRY). Without it each rung re-discovers the same
    // 465 and burns billions of nodes. Clamp to the sentinel so it never loosens.
    q.bestCost = (initialBestCost > 0 && initialBestCost < q.budget + 1)
                     ? initialBestCost : q.budget + 1;
    for (const Hint& h : HINTS) {
        int ci = (15 - h.tdRow) * 16 + h.tdCol;
        q.cluePiece[ci] = h.piece;
        q.clueRot[ci] = h.rot;
    }
    for (int d = startDepth; d < 256; d++) {
        int ci = SEQ_ROW[d] * 16 + SEQ_COL[d];
        q.inTail[ci] = true;
        q.cells[q.nCells++] = ci;
    }
    for (int p = 1; p <= 256; p++) {
        if (used[p]) continue;
        const Piece& pc = PIECES[p];
        q.sup[pc.n]++; q.sup[pc.e]++; q.sup[pc.s]++; q.sup[pc.w]++;
    }
#ifdef BW_CHECKER_LEDGER
    q.checkerOn = g_checkerTailOn;
    if (q.checkerOn) initCheckerLedger(q);
#endif
#ifdef BW_SIGMA_LEDGER
    // LBσ tail : oddMask racine = parité XOR de TOUTES les coutures cassées déjà FERMÉES à l'entrée
    // du tail (les deux extrémités sont des cellules du préfixe, board[.].pieceNumber != 0). Chaque
    // couture est comptée une fois (voisins nord + est de chaque cellule posée). Init caller-agnostique
    // (ladder ou bench) : ne dépend pas de board[].breakCount, seulement des couleurs posées.
    q.sigmaOn = g_sigmaTailOn;
    q.demSigmaOn = g_demSigmaOn;   // LBdemSigma (handoff 2026-08-18) : applique la coupe conjointe si ON
    q.demSigGateT = g_demSigmaGate; // A adaptatif (2026-08-19) : porte lbDem >= T
    if (g_traceBackjump) {   // P3 : préfixe/clue = -1 (statique) ; seules les poses tail écrivent une profondeur
        for (int i = 0; i < 256; i++) g_placeDepth[i] = -1;
        for (int i = 0; i < 257; i++) g_pieceUsedAtDepth[i] = -1;
    }
#ifdef BW_FLUX_LEDGER
    q.fluxOn = g_fluxTailOn;
    q.fluxEval = g_fluxEval || g_fluxTailOn;   // appliquer implique évaluer
#endif
    {
        uint32_t io = 0;
        for (int ci = 0; ci < 256; ci++) {
            const RotatedPiece& a = board[ci];
            if (!a.pieceNumber) continue;
            const int rr = ci >> 4, cc = ci & 15;
            if (rr < 15) {                       // voisin nord (face 0 <-> sa face sud 2)
                const RotatedPiece& b = board[ci + 16];
                if (b.pieceNumber) {
                    const int m = tailFace(a, 0), o = tailFace(b, 2);
                    if (m != o) io ^= (m ? (1u << m) : 0u) ^ (o ? (1u << o) : 0u);
                }
            }
            if (cc < 15) {                       // voisin est (face 1 <-> sa face ouest 3)
                const RotatedPiece& b = board[ci + 1];
                if (b.pieceNumber) {
                    const int m = tailFace(a, 1), o = tailFace(b, 3);
                    if (m != o) io ^= (m ? (1u << m) : 0u) ^ (o ? (1u << o) : 0u);
                }
            }
        }
        q.initOdd = io;
    }
#ifdef BW_TAIL_PROFILE
    { uint64_t _pt0 = __builtin_ia32_rdtsc(); tailMrvDfs(q, 0, breaksUsed, q.initOdd);
      g_totalTailCycles.fetch_add(__builtin_ia32_rdtsc() - _pt0, std::memory_order_relaxed); }
#else
    tailMrvDfs(q, 0, breaksUsed, q.initOdd);
#endif
#else
#ifdef BW_TAIL_PROFILE
    { uint64_t _pt0 = __builtin_ia32_rdtsc(); tailMrvDfs(q, 0, breaksUsed);
      g_totalTailCycles.fetch_add(__builtin_ia32_rdtsc() - _pt0, std::memory_order_relaxed); }
#else
    tailMrvDfs(q, 0, breaksUsed);
#endif
#endif
#ifdef BW_TAIL_LEDGER_LOCAL
    flushTailLedger(q);   // flush final racine (toutes sorties : normal/capped/stop) -> totaux exacts
#endif
    if (nodesOut) *nodesOut = q.nodes;
    if (cappedOut) *cappedOut = q.capped;
    if (costOut) *costOut = q.bestCost;
    if (ringOut) *ringOut = q.bestRing;
    // canary7 : exporter l'incumbent vérifié MÊME s'il dépasse acceptCost (pour
    // harvester les 463), sans changer le retour ni l'arbre.
    if (incumbentOut && q.solvedScore >= 0) {
        memcpy(incumbentOut, q.bestBoard, sizeof q.bestBoard);
        if (incScoreOut) *incScoreOut = q.solvedScore;
    }
    // A filling that misses acceptCost is telemetry only: leave board/used
    // exactly as the caller had them so the live DFS can carry on.
    if (q.solvedScore < 0 || q.bestCost > acceptCost) return -1;
    memcpy(board, q.bestBoard, sizeof q.bestBoard);   // restore the incumbent
    return q.solvedScore;
}

// Temporarily unplace a suffix of the live Blackwood path, solve that larger
// constrained sub-puzzle, then restore the exact DFS state if it fails.  Full
// snapshots make restoration independent of how/where MRV stopped (exhausted,
// capped, or signal) and keep used[] consistent with board[].
__attribute__((cold, noinline))
// P17 option-2 (2026-08-19) : télémétrie READ-ONLY des entrées de bande r216 pour mesurer
// l'amortissement d'une table tropicale (clé = pool des 40 restantes + 8 couleurs sud de la bande).
// N'altère PAS la recherche ; producteurs de prod inchangés (binaire isolé, flag --r216-trace).
static bool g_r216trace = false;
static std::string g_r216traceOut;
static std::mutex g_r216mtx;
struct R216Row { uint64_t key, spent, nodes; uint32_t rewind; };
static std::vector<R216Row> g_r216rows;   // (key, spent, nodes, rewind)
static const size_t R216_CAP = 3000000;
static uint64_t r216key(const RotatedPiece* board, const bool* used) {
    uint64_t h = 1469598103934665603ULL;
    auto mix = [&](uint64_t x){ h ^= x; h *= 1099511628211ULL; };
    uint64_t pw[4] = {0,0,0,0};
    for (int p = 1; p <= 256; p++) if (!used[p]) pw[(p-1) >> 6] |= (1ull << ((p-1) & 63));
    for (int i = 0; i < 4; i++) mix(pw[i]);
    for (int c = 8; c < 16; c++) mix((uint64_t)board[5*16 + c].top);   // bordure sud de la bande (row5 nord)
    return h;
}
static void dumpR216Trace() {
    if (!g_r216trace || g_r216traceOut.empty()) return;
    std::lock_guard<std::mutex> lk(g_r216mtx);
    FILE* f = fopen(g_r216traceOut.c_str(), "w");
    if (!f) { logf("R216_TRACE_FAIL open %s", g_r216traceOut.c_str()); return; }
    fprintf(f, "# key spent nodes rewind  entries=%zu\n", g_r216rows.size());
    for (auto& r : g_r216rows) fprintf(f, "%llu %llu %llu %u\n",
        (unsigned long long)r.key, (unsigned long long)r.spent, (unsigned long long)r.nodes, r.rewind);
    fclose(f);
    logf("R216_TRACE wrote %zu band-entries -> %s", g_r216rows.size(), g_r216traceOut.c_str());
}
// P-ELITE opt-1 (2026-08-19) : télémétrie READ-ONLY des slices candidates aux profondeurs 9..31.
// Mesure la taille des slices par (cell,key) et le nombre de (cell,key) DISTINCTS pour trancher
// entre vues d'indices au restart / clones compacts / permutation par-nœud (demande Codex).
// N'altère PAS la recherche (compteurs seuls). Flag --elite-slice-trace <out>.
static bool g_eliteTrace = false;
static std::string g_eliteTraceOut;
static const int ELITE_IDXN = 256 * 23 * 23;   // 135424 : idx = ci*529 + left*23 + bottom
static std::atomic<uint32_t>* g_eliteVisits = nullptr;
static uint16_t* g_eliteNCand = nullptr;
static std::atomic<uint64_t> g_elite931Nodes{0}, g_elite931Accept{0};
static inline int eliteIdx(int ci, int left, int bottom) { return ci * 529 + left * 23 + bottom; }
static void dumpEliteTrace() {
    if (!g_eliteTrace || g_eliteTraceOut.empty() || !g_eliteVisits) return;
    FILE* f = fopen(g_eliteTraceOut.c_str(), "w");
    if (!f) { logf("ELITE_TRACE_FAIL open %s", g_eliteTraceOut.c_str()); return; }
    uint64_t distinct = 0;
    fprintf(f, "# ci left bottom nCand visits  (nodes931=%llu accepted931=%llu)\n",
            (unsigned long long)g_elite931Nodes.load(), (unsigned long long)g_elite931Accept.load());
    for (int idx = 0; idx < ELITE_IDXN; idx++) {
        uint32_t v = g_eliteVisits[idx].load();
        if (!v) continue;
        distinct++;
        int ci = idx / 529, rem = idx % 529, left = rem / 23, bottom = rem % 23;
        fprintf(f, "%d %d %d %d %u\n", ci, left, bottom, (int)g_eliteNCand[idx], v);
    }
    fclose(f);
    logf("ELITE_TRACE %llu (cell,key) distincts, %llu visites 9-31 -> %s",
         (unsigned long long)distinct, (unsigned long long)g_elite931Nodes.load(), g_eliteTraceOut.c_str());
}
// ============ P-ELITE V1 (2026-08-19) : move-ordering guidé profondeurs 9..31 ============
// Score statique appris des 1447 boards 463 (config prod), leave-current-root-out. Port EXACT de
// tools/elite_order_signal.py (validé .291). Frame TOP-DOWN (tci = td*16+col, row0=nord), faces via
// hot_main_tiles_531. Mapping vers le solveur (frame flippé) : tci = (15-(sci>>4))*16 + (sci&15),
// rotation INCHANGÉE (cf saveBoard). Ce bloc = loader + score + replay self-check (--elite-replay).
static int8_t g_hot531[257][4][4];       // [piece][rot][side N/E/S/W] -> couleur (top-down)
static bool   g_hot531Loaded = false;
struct EliteBoard { uint16_t piece[256]; uint8_t rot[256]; std::string root; };
static std::vector<EliteBoard> g_corpus;    // boards 463 config-prod
static int g_eliteOrder[256];               // depth -> cellule top-down (order[depth]=tci)
static int g_cell23[23];                    // les 23 cellules top-down aux depth 9..31
static int g_block23[23];                   // bloc 4x4 de chaque (=(tci_row/4)*4 + tci_col/4)
static thread_local float g_eliteScore[23][257][4];   // score par (k=si-9, piece, rot) — PAR-THREAD (leave-root-out)
static bool  g_eliteScoreReady = false;
static std::string g_eliteCurRoot;
static std::string g_eliteTilesPath, g_eliteCorpusList, g_eliteReplayList;
// ---- runtime (hot-loop) ----
static bool g_eliteOrderOn = false;   // --elite-order : APPLIQUE les vues elite (ON)
static bool g_eliteRefMode = false;   // --elite-ref   : calcule les vues mais itère l'ordre OFF (REF, bit-identique)
static uint64_t g_eliteAppliedT[256] = {0}, g_eliteViewMissT[256] = {0};   // compteurs PAR-THREAD (0 atomique hot-path)
static bool g_eliteCheck = false;   // --elite-check : vérifie multiset OFF==ON par nœud 9-31 (debug)
static std::atomic<uint64_t> g_eliteMsChecked{0}, g_eliteMsMismatch{0};
static const int ELITE_NKEY = NCOLORS * NCOLORS;   // 529
static const int ELITE_VMAX = 32;                  // slices >32 -> fallback OFF (observé max 12)
static thread_local uint16_t g_eview[23][ELITE_NKEY][ELITE_VMAX];   // permutation locale (PAR-THREAD)
static thread_local uint8_t  g_eviewN[23][ELITE_NKEY];             // taille (0xFF = miss construit cet epoch)
static thread_local uint32_t g_eviewEpoch[23][ELITE_NKEY];         // epoch de construction (lazy)
static thread_local uint32_t g_eliteEpoch = 1;                     // bumpé par attempt (par-thread)
static thread_local uint64_t g_eliteAttemptSeed = 0;               // seed du tie-break de vue (par attempt)
// construit la vue (k,key) : tri (breakCount asc, eliteScore desc, tie déterministe seedé). Renvoie n (0xFF=miss).
static uint8_t buildEview(int k, int key, const PoolElem* cand, int nCand, uint64_t seed) {
    if (nCand > ELITE_VMAX) return 0xFF;
    uint16_t idx[ELITE_VMAX]; uint8_t bc[ELITE_VMAX]; float sc[ELITE_VMAX]; uint32_t tie[ELITE_VMAX];
    for (int i = 0; i < nCand; i++) {
        const RotatedPiece c = cand[i];
        idx[i] = (uint16_t)i; bc[i] = c.breakCount; sc[i] = g_eliteScore[k][c.pieceNumber][c.rot];
        uint64_t h = seed ^ ((uint64_t)k << 40) ^ ((uint64_t)key << 24) ^ ((uint64_t)c.pieceNumber << 4) ^ (uint64_t)c.rot;
        h ^= h >> 33; h *= 0xff51afd7ed558ccdULL; h ^= h >> 33; tie[i] = (uint32_t)h;
    }
    for (int a = 1; a < nCand; a++) {   // insertion sort stable par clé (bc asc, sc desc, tie asc)
        uint16_t v = idx[a]; int b = a - 1;
        while (b >= 0) { uint16_t u = idx[b];
            bool uBeforeV = (bc[u] < bc[v]) || (bc[u]==bc[v] && (sc[u] > sc[v] || (sc[u]==sc[v] && tie[u] <= tie[v])));
            if (uBeforeV) break;
            idx[b+1] = idx[b]; b--; }
        idx[b+1] = v;
    }
    uint32_t px = 0; int ps = 0, es = 0;   // garde-fou 2 : assert permutation exacte de [0,nCand)
    for (int i = 0; i < nCand; i++) { px ^= idx[i]; ps += idx[i]; es += i; }
    uint32_t ex = 0; for (int i = 0; i < nCand; i++) ex ^= (uint32_t)i;
    if (px != ex || ps != es) { logf("ELITE_VIEW_NONPERM k=%d key=%d n=%d", k, key, nCand); return 0xFF; }
    for (int i = 0; i < nCand; i++) g_eview[k][key][i] = idx[i];
    return (uint8_t)nCand;
}
// clues fixes (top-down) : cells 34,45,119,210,221 = 181/0,208/0,139/3,249/1,255/0 (config prod)
static const int ELITE_CLUE_CELL[5] = {34, 45, 119, 210, 221};
static const int ELITE_CLUE_P[5]    = {181, 208, 139, 249, 255};
static const int ELITE_CLUE_R[5]    = {0, 0, 3, 1, 0};

static bool loadHot531(const char* path) {
    FILE* f = fopen(path, "r"); if (!f) { logf("ELITE hot531 open FAIL %s", path); return false; }
    int p, rot, n, e, s, w, lines = 0;
    while (fscanf(f, "%d %d %d %d %d %d", &p, &rot, &n, &e, &s, &w) == 6)
        if (p >= 1 && p <= 256 && rot >= 0 && rot < 4) {
            g_hot531[p][rot][0]=(int8_t)n; g_hot531[p][rot][1]=(int8_t)e;
            g_hot531[p][rot][2]=(int8_t)s; g_hot531[p][rot][3]=(int8_t)w; lines++;
        }
    fclose(f); g_hot531Loaded = (lines == 1024);
    if (!g_hot531Loaded) logf("ELITE hot531 lignes=%d (attendu 1024)", lines);
    return g_hot531Loaded;
}
// parse un board top-down "piece/rot" x16 par ligne + header ROOT (comme parse_board du reproducteur)
static bool parseEliteBoard(const char* path, EliteBoard& out) {
    FILE* f = fopen(path, "r"); if (!f) return false;
    char line[1024]; int cell = 0; out.root.clear();
    while (fgets(line, sizeof line, f)) {
        if (!strncmp(line, "ROOT ", 5)) {
            out.root = line + 5;
            while (!out.root.empty() && (out.root.back()=='\n'||out.root.back()=='\r'||out.root.back()==' '))
                out.root.pop_back();
        }
        char buf[1024]; strncpy(buf, line, sizeof buf); buf[sizeof buf - 1] = 0;
        int lp[16], lr[16], nt = 0; bool valid = true; char* save = nullptr;
        for (char* tok = strtok_r(buf, " \t\r\n", &save); tok; tok = strtok_r(nullptr, " \t\r\n", &save)) {
            int pn, rt; char ex;
            if (nt >= 16 || sscanf(tok, "%d/%d%c", &pn, &rt, &ex) != 2 || pn < 1 || pn > 256 || rt < 0 || rt > 3) { valid = false; break; }
            lp[nt] = pn; lr[nt] = rt; nt++;
        }
        if (valid && nt == 16 && cell < 256)
            for (int c = 0; c < 16; c++) { out.piece[cell] = (uint16_t)lp[c]; out.rot[cell] = (uint8_t)lr[c]; cell++; }
    }
    fclose(f);
    return cell == 256;
}
static void setupEliteCells() {   // order[depth]=tci depuis BOARD_ORDER_CLUED (= reproducteur load_order)
    for (int td = 0; td < 16; td++) for (int col = 0; col < 16; col++)
        g_eliteOrder[BOARD_ORDER_CLUED[td][col]] = td * 16 + col;
    for (int k = 0; k < 23; k++) {
        int tci = g_eliteOrder[9 + k]; g_cell23[k] = tci;
        g_block23[k] = (tci / 16 / 4) * 4 + (tci % 16 / 4);
    }
}
// charge le corpus 463 depuis un list-file (1 chemin/ligne), filtre config prod (5 clues)
static bool loadEliteCorpus(const char* listPath) {
    FILE* lf = fopen(listPath, "r"); if (!lf) { logf("ELITE corpus list open FAIL %s", listPath); return false; }
    char path[1024]; int total = 0, kept = 0;
    while (fgets(path, sizeof path, lf)) {
        char* nl = strpbrk(path, "\r\n"); if (nl) *nl = 0;
        if (!path[0]) continue;
        total++;
        EliteBoard b;
        if (!parseEliteBoard(path, b)) continue;
        bool prod = true;   // config prod : les 5 clues top-down doivent matcher
        for (int i = 0; i < 5; i++)
            if (b.piece[ELITE_CLUE_CELL[i]] != (uint16_t)ELITE_CLUE_P[i] || b.rot[ELITE_CLUE_CELL[i]] != (uint8_t)ELITE_CLUE_R[i]) { prod = false; break; }
        if (!prod) continue;
        g_corpus.push_back(std::move(b)); kept++;
    }
    fclose(lf);
    logf("ELITE corpus: %d fichiers, %d gardés (config prod)", total, kept);
    return kept > 0;
}
// recalcule g_eliteScore[k][p][rot] avec leave-root-out. Exclusion CORNER-BASED : exclut les boards
// dont les 9 cellules de coin (g_eliteOrder[0..8]) == (exP,exR) — équivaut au match ROOT-string mais
// indépendant du format. exP/exR = coin du ticket (fr) ou du board test. Retourne (train, excluded).
static int g_eliteTrainCount = 0, g_eliteExclCount = 0;
static void computeEliteScores(const uint16_t exP[9], const uint8_t exR[9]) {
    static thread_local int cp[23][257], cpr[23][257][4], cf[23][4][23], cbp[4][257];
    memset(cp,0,sizeof cp); memset(cpr,0,sizeof cpr); memset(cf,0,sizeof cf); memset(cbp,0,sizeof cbp);
    int usedB = 0, excl = 0;
    for (const auto& b : g_corpus) {
        bool same = true;
        for (int i = 0; i < 9; i++) { int oc = g_eliteOrder[i]; if (b.piece[oc] != exP[i] || b.rot[oc] != exR[i]) { same = false; break; } }
        if (same) { excl++; continue; }
        usedB++;
        for (int k = 0; k < 23; k++) { int tci = g_cell23[k]; int p = b.piece[tci], rot = b.rot[tci];
            cp[k][p]++; cpr[k][p][rot]++;
            for (int s = 0; s < 4; s++) cf[k][s][ g_hot531[p][rot][s] ]++;
        }
        for (int bl = 0; bl < 4; bl++) for (int r = 0; r < 4; r++) for (int cc = bl*4; cc < bl*4+4; cc++)
            cbp[bl][ b.piece[r*16+cc] ]++;
    }
    for (int k = 0; k < 23; k++) { int bl = g_block23[k];
        for (int p = 1; p <= 256; p++) for (int rot = 0; rot < 4; rot++) {
            double sp = log1p((double)cp[k][p]);
            double spr = log1p((double)cpr[k][p][rot]);
            double sb = log1p((double)cbp[bl][p]);
            double sf = 0; for (int s = 0; s < 4; s++) sf += log((double)cf[k][s][ g_hot531[p][rot][s] ] + 4.0);
            g_eliteScore[k][p][rot] = (float)(2.0*spr + sp + 0.25*sb + 0.65*sf);
        }
    }
    g_eliteScoreReady = true; g_eliteTrainCount = usedB; g_eliteExclCount = excl;
}
// self-check : reproduit le percentile 9-31 (attendu .291) sur une liste de boards 465 (top-down pur)
static int eliteReplay(const char* testListPath) {
    if (!g_hot531Loaded) { logf("ELITE replay: hot531 non chargé"); return 2; }
    setupEliteCells();
    FILE* tl = fopen(testListPath, "r"); if (!tl) { logf("ELITE replay list open FAIL %s", testListPath); return 2; }
    static const int DR[4] = {-1,0,1,0}, DC[4] = {0,1,0,-1};   // N,E,S,W top-down
    char path[1024]; int nBoards = 0; double sumPct[6] = {0}; int nPct[6] = {0};   // buckets 0-8,9-31,32-63,64-127,128-191,192+
    auto bucket = [](int d){ return d<9?0 : d<32?1 : d<64?2 : d<128?3 : d<192?4 : 5; };
    while (fgets(path, sizeof path, tl)) {
        char* nl = strpbrk(path, "\r\n"); if (nl) *nl = 0; if (!path[0]) continue;
        EliteBoard b; if (!parseEliteBoard(path, b)) { logf("ELITE replay parse FAIL %s", path); continue; }
        uint16_t exP[9]; uint8_t exR[9];
        for (int i = 0; i < 9; i++) { int oc = g_eliteOrder[i]; exP[i] = b.piece[oc]; exR[i] = b.rot[oc]; }
        computeEliteScores(exP, exR);
        nBoards++;
        int placedP[256]; uint8_t placedR[256]; bool placed[256] = {false}; bool used[257] = {false};
        for (int i = 0; i < 5; i++) { int ci = ELITE_CLUE_CELL[i]; placedP[ci]=ELITE_CLUE_P[i]; placedR[ci]=(uint8_t)ELITE_CLUE_R[i]; placed[ci]=true; used[ELITE_CLUE_P[i]]=true; }
        for (int depth = 0; depth < 256; depth++) {
            int ci = g_eliteOrder[depth];
            int ap = b.piece[ci], ar = b.rot[ci];
            bool isClue = false; for (int i=0;i<5;i++) if (ci==ELITE_CLUE_CELL[i]) isClue=true;
            if (isClue) { placedP[ci]=ap; placedR[ci]=(uint8_t)ar; placed[ci]=true; continue; }
            int r = ci/16, c = ci%16;
            // add_cost du vrai move
            auto addCost = [&](int p, int rot)->int { int t=0; const int8_t* fc=g_hot531[p][rot];
                for (int s=0;s<4;s++){ int nr=r+DR[s], nc=c+DC[s]; if(nr<0||nr>15||nc<0||nc>15) continue; int ni=nr*16+nc;
                    if (placed[ni]) t += (fc[s] != g_hot531[placedP[ni]][placedR[ni]][(s+2)&3]); } return t; };
            auto frameOk = [&](int p, int rot)->bool { const int8_t* fc=g_hot531[p][rot];
                bool outw[4]={r==0,c==15,r==15,c==0}; for(int s=0;s<4;s++) if((fc[s]==0)!=outw[s]) return false; return true; };
            int actualAdd = addCost(ap, ar);
            int k = (depth>=9 && depth<=31) ? depth-9 : -1;
            // énumère candidats même-add, calcule percentile si depth 9-31 (sinon skip scoring lourd hors fenêtre utile)
            if (depth>=9 && depth<=31) {
                double actualScore = 0; bool haveActual=false; int nCand=0, higher=0; double tied=0;
                // 1re passe : score du vrai move
                {
                    int p=ap, rot=ar; int bl=g_block23[k]; const int8_t* fc=g_hot531[p][rot];
                    double sp=g_eliteScore[k][p][rot]; actualScore=sp; haveActual=true; (void)bl; (void)fc;
                }
                for (int p=1;p<=256;p++){ if(used[p]) continue;
                    for(int rot=0;rot<4;rot++){ if(!frameOk(p,rot)) continue; if(addCost(p,rot)!=actualAdd) continue;
                        double sc=g_eliteScore[k][p][rot]; nCand++;
                        if (sc > actualScore + 1e-9) higher++; else if (sc >= actualScore - 1e-9) tied += 1.0;
                    }
                }
                if (nCand>0 && haveActual) { double pct=(higher + 0.5*tied)/nCand; int bk=bucket(depth); sumPct[bk]+=pct; nPct[bk]++; }
            }
            placedP[ci]=ap; placedR[ci]=(uint8_t)ar; placed[ci]=true; used[ap]=true;
        }
    }
    fclose(tl);
    logf("ELITE REPLAY boards=%d corpus=%zu", nBoards, g_corpus.size());
    const char* names[6]={"0-8","9-31","32-63","64-127","128-191","192+"};
    for (int i=0;i<6;i++) if (nPct[i]) logf("  bucket %-7s n=%d mean_percentile=%.3f", names[i], nPct[i], sumPct[i]/nPct[i]);
    return 0;
}
// ============ P-TEL option C (2026-08-19) : télémétrie PASSIVE crédit-assignment slack4 ============
// Lit seulement board[] + le compteur de nœuds, écrit thread_local. N'altère NI ordre NI rng NI arbre.
// Exposition mesurée à l'engagement du choix 9-31 (snapshot nœuds), soldée à l'undo (closed) ou au
// cap/restart (censored). Outcome (reach244/s4/s5) crédité aux 23 frames actives à si==244.
static bool g_telOn = false;                 // --tel
static std::string g_telOut;                 // --tel-out <fichier événements>
static uint64_t g_telCkptEvents = 2000;      // --tel-ckpt-events N : seuil checkpoint (défaut 2000)
static int g_telCkptSec = 30;                // --tel-ckpt-sec N : checkpoint temporel (borne la perte sur crash même si reach-endgame rare, défaut 30s)
static uint64_t g_telRunId = 0;              // identité du run (PID⊕temps) : fichiers par run, dédup agrégateur
struct TelFrame { uint64_t nodesEntry; uint32_t ci; uint16_t key; uint16_t piece; uint8_t rot; bool active; };
static thread_local TelFrame g_tframe[23];   // frame par cellule 9-31 (idx=depth-9)
struct TelExpo { uint64_t chosen=0, gnodes=0, closed=0, censored=0, r244=0, s4=0, s5=0; };
static thread_local TelExpo g_texpoArr[23][257][4];   // tableau plat [idx][piece][rot] : 0 hash, ~1.3MB/thread. Le `key` fin reste dans les événements.
static thread_local uint64_t g_tReach244=0, g_tS4=0, g_tS5=0, g_tEvents=0, g_tSettleClosed=0, g_tSettleCens=0;
static thread_local uint64_t g_tMaxSettledTicket=0, g_tSettledCount=0;   // crash-gate : identité/compte des tickets dont le télémétrie est dans g_texpoArr (invariant expo ⊆ ledger)
static thread_local std::string g_tEventBuf;                          // buffer événements (23 choix+slack), flush hors hot-loop
static std::mutex g_telMtx; static FILE* g_telEventF = nullptr;       // fichier partagé (flush sous mutex)
static uint64_t g_telReach244Tot=0, g_telS4Tot=0, g_telS5Tot=0, g_telEventsTot=0, g_telClosedTot=0, g_telCensTot=0;  // agrégat (sous g_telMtx)
// checkpoint ATOMIQUE périodique (write temp + rename) de la table expo par-thread. Reboot/crash-safe.
static thread_local uint64_t g_tLastCkptEvents = 0;
static thread_local std::chrono::steady_clock::time_point g_tLastCkptTime = std::chrono::steady_clock::now();  // checkpoint temporel
static void telCheckpointExpo(int tid) {
    if (g_telOut.empty()) return;
    char base[600]; snprintf(base, sizeof base, "%s.r%llu.t%d.expo", g_telOut.c_str(), (unsigned long long)g_telRunId, tid);
    std::string tmp = std::string(base) + ".tmp";
    FILE* f = fopen(tmp.c_str(), "w"); if (!f) return;
    uint64_t nlines = 0, ck = 1469598103934665603ULL;   // framing : checksum fnv1a des lignes E (END non inclus)
    auto put = [&](const char* s, int n){ fwrite(s,1,n,f); for(int i=0;i<n;i++){ ck ^= (uint8_t)s[i]; ck *= 1099511628211ULL; } };
    char hdr[320]; int hn = snprintf(hdr, sizeof hdr, "# TEL-EXPO v1 run=%llu tid=%d reach244=%llu s4=%llu s5=%llu closed=%llu cens=%llu maxSettled=%llu settledCount=%llu\n",
        (unsigned long long)g_telRunId, tid, (unsigned long long)g_tReach244,(unsigned long long)g_tS4,(unsigned long long)g_tS5,
        (unsigned long long)g_tSettleClosed,(unsigned long long)g_tSettleCens,
        (unsigned long long)g_tMaxSettledTicket,(unsigned long long)g_tSettledCount);
    put(hdr, hn);
    for (int idx=0; idx<23; idx++) for (int p=1; p<=256; p++) for (int r=0; r<4; r++) {
        TelExpo& e = g_texpoArr[idx][p][r]; if (!e.chosen && !e.r244) continue;
        char line[160]; int n = snprintf(line, sizeof line, "E %d %d %d %llu %llu %llu %llu %llu %llu %llu\n", idx,p,r,
            (unsigned long long)e.chosen,(unsigned long long)e.gnodes,(unsigned long long)e.closed,(unsigned long long)e.censored,
            (unsigned long long)e.r244,(unsigned long long)e.s4,(unsigned long long)e.s5);
        put(line, n); nlines++;
    }
    char end[80]; int en = snprintf(end, sizeof end, "END %llu %016llx\n", (unsigned long long)nlines, (unsigned long long)ck);
    fwrite(end, 1, en, f);   // marqueur de fin : le parser rejette tout fichier sans END valide (partiel)
    fflush(f); fsync(fileno(f)); fclose(f);
    rename(tmp.c_str(), base);   // atomique sur POSIX (ext4)
    std::string dir = g_telOut; size_t sl = dir.find_last_of('/'); dir = (sl==std::string::npos) ? std::string(".") : dir.substr(0, sl);
    int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY); if (dfd >= 0) { fsync(dfd); close(dfd); }   // durabilité du rename
}
// solde la frame idx (delta nœuds) en closed OU censored ; met active=false. nodesNow = compteur courant.
static inline void telSettle(int idx, uint64_t nodesNow, bool censored) {
    TelFrame& f = g_tframe[idx]; if (!f.active) return;
    TelExpo& e = g_texpoArr[idx][f.piece][f.rot];   // index direct, 0 hash
    e.chosen++; e.gnodes += (nodesNow - f.nodesEntry);
    if (censored) { e.censored++; g_tSettleCens++; } else { e.closed++; g_tSettleClosed++; }
    f.active = false;
}
static int solveTailMrvRewind(RotatedPiece* board, bool* used,
                              int currentDepth, int rewindDepth,
                              int breaksUsed, uint64_t nodeCap,
                              uint64_t* nodesOut, bool* cappedOut,
                              int* costOut = nullptr, int budgetOverride = -1,
                              int acceptCost = INT_MAX,
                              int sliceS = -1, int sliceN = 0,
                              int initialBestCost = -1,
                              std::atomic<uint64_t>* progress = nullptr,
                              RotatedPiece* incumbentOut = nullptr, int* incScoreOut = nullptr) {
    RotatedPiece savedBoard[256];
    bool savedUsed[257];
    memcpy(savedBoard, board, sizeof savedBoard);
    memcpy(savedUsed, used, sizeof savedUsed);

    for (int d = rewindDepth; d < currentDepth; d++) {
        int ci = SEQ_ROW[d] * 16 + SEQ_COL[d];
        if (board[ci].pieceNumber)
            used[board[ci].pieceNumber] = false;
        board[ci] = {};
    }

    // P17 option-2 : capture clé+spent APRÈS rewind (état préfixe exact), nodes APRÈS le solve.
    // Élargi à TOUS les rungs du ladder (216..240) pour mesurer la répartition endgame par profondeur.
    uint64_t _r216k = 0; int _r216sp = 0; const bool _r216hit = (g_r216trace && rewindDepth >= 216 && rewindDepth <= 240);
    if (_r216hit) { _r216k = r216key(board, used); _r216sp = breaksUsed; }

    int score = solveTailMrv(board, used, rewindDepth, breaksUsed,
                             nodeCap, nodesOut, cappedOut, costOut,
                             budgetOverride, acceptCost, nullptr, sliceS, sliceN,
                             initialBestCost, progress, incumbentOut, incScoreOut);
    if (_r216hit) {
        uint64_t nd = nodesOut ? *nodesOut : 0;
        std::lock_guard<std::mutex> lk(g_r216mtx);
        if (g_r216rows.size() < R216_CAP) g_r216rows.push_back({_r216k, (uint64_t)_r216sp, nd, (uint32_t)rewindDepth});
    }
    if (score < 0) {
        memcpy(board, savedBoard, sizeof savedBoard);
        memcpy(used, savedUsed, sizeof savedUsed);
    }
    return score;
}

// ------------------------------------------------------------------ the solver

// ---- P7-A: snapshot / replay of one exact-tail state (shadow tooling) --------
// Capture the exact inputs of a solveTailMrvRewind call once, then replay it
// directly (no Blackwood generator) so the deep tail becomes an isolated,
// reproducible benchmark for parallel cubes and tree-cutting A/Bs.
static uint64_t fnv1a(const void* p, size_t n, uint64_t h = 1469598103934665603ULL) {
    const uint8_t* b = (const uint8_t*)p;
    for (size_t i = 0; i < n; i++) { h ^= b[i]; h *= 1099511628211ULL; }
    return h;
}
// SHA-256 compact (domaine public, FIPS 180-4) : identité CANONIQUE persistante d'un board
// (Codex : content-addressing SHA256, pas FNV64). Retourne 64 chars hex minuscules.
static void sha256_hex(const void* data, size_t len, char out[65]) {
    static const uint32_t K[64] = {
        0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
        0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
        0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
        0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
        0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
        0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
        0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
        0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2};
    uint32_t H[8] = {0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19};
    auto rr = [](uint32_t x, int n){ return (x >> n) | (x << (32 - n)); };
    uint64_t bits = (uint64_t)len * 8;
    size_t padded = ((len + 8) / 64 + 1) * 64;
    std::vector<uint8_t> m(padded, 0);
    memcpy(m.data(), data, len);
    m[len] = 0x80;
    for (int i = 0; i < 8; i++) m[padded - 1 - i] = (uint8_t)(bits >> (8 * i));
    for (size_t off = 0; off < padded; off += 64) {
        uint32_t w[64];
        for (int i = 0; i < 16; i++)
            w[i] = (m[off+4*i]<<24)|(m[off+4*i+1]<<16)|(m[off+4*i+2]<<8)|m[off+4*i+3];
        for (int i = 16; i < 64; i++) {
            uint32_t s0 = rr(w[i-15],7)^rr(w[i-15],18)^(w[i-15]>>3);
            uint32_t s1 = rr(w[i-2],17)^rr(w[i-2],19)^(w[i-2]>>10);
            w[i] = w[i-16]+s0+w[i-7]+s1;
        }
        uint32_t a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7];
        for (int i = 0; i < 64; i++) {
            uint32_t S1 = rr(e,6)^rr(e,11)^rr(e,25);
            uint32_t ch = (e&f)^(~e&g);
            uint32_t t1 = h+S1+ch+K[i]+w[i];
            uint32_t S0 = rr(a,2)^rr(a,13)^rr(a,22);
            uint32_t maj = (a&b)^(a&c)^(b&c);
            uint32_t t2 = S0+maj;
            h=g;g=f;f=e;e=d+t1;d=c;c=b;b=a;a=t1+t2;
        }
        H[0]+=a;H[1]+=b;H[2]+=c;H[3]+=d;H[4]+=e;H[5]+=f;H[6]+=g;H[7]+=h;
    }
    static const char* hx = "0123456789abcdef";
    for (int i = 0; i < 8; i++)
        for (int j = 0; j < 4; j++) {
            uint8_t byte = (uint8_t)(H[i] >> (24 - 8*j));
            out[i*8 + j*2] = hx[byte >> 4];
            out[i*8 + j*2 + 1] = hx[byte & 15];
        }
    out[64] = 0;
}
static uint64_t tailConfigHash() {   // reject snapshots from a different puzzle/schedule
    uint64_t h = fnv1a(PIECES, sizeof(Piece) * 257);
    h = fnv1a(HOT.seqRow, 256, h); h = fnv1a(HOT.seqCol, 256, h);
    for (const Hint& hh : HINTS) h = fnv1a(&hh, sizeof hh, h);
    int tb = TOTAL_BUDGET; h = fnv1a(&tb, sizeof tb, h);
    return h;
}
struct TailSnapshot {
    uint32_t magic;        // 0x42575431 = "BWT1"
    uint32_t version;
    uint64_t cfgHash;
    int32_t si, rewindDepth, breaksUsed, initialBestCost, budgetOverride, acceptCost;
    RotatedPiece board[256];
    uint8_t used[260];     // 257 rounded up
    uint64_t crc;          // fnv1a over everything above (crc is last member)
};
static std::atomic<uint64_t> g_capSeq{0};   // unicité des .tmp (pas de collision concurrente)
// Capture DURABLE (shadow #2b) : renvoie succès/échec. tmp unique par appel, write
// vérifié, fsync du fichier, rename atomique vérifié, puis fsync du répertoire pour
// rendre le rename lui-même durable. Sur échec : nettoie le tmp et renvoie false
// (le caller peut choisir fallback_local, jamais abandonner le tail).
static bool captureTailState(const std::string& path, const RotatedPiece* board,
                             const bool* used, int si, int rewindDepth, int breaksUsed,
                             int initialBestCost, int budgetOverride, int acceptCost) {
    TailSnapshot s{};
    s.magic = 0x42575431; s.version = 1; s.cfgHash = tailConfigHash();
    s.si = si; s.rewindDepth = rewindDepth; s.breaksUsed = breaksUsed;
    s.initialBestCost = initialBestCost; s.budgetOverride = budgetOverride;
    s.acceptCost = acceptCost;
    memcpy(s.board, board, sizeof s.board);
    for (int p = 0; p <= 256; p++) s.used[p] = used[p] ? 1 : 0;
    s.crc = fnv1a(&s, sizeof s - sizeof s.crc);
    char tmp[600];
    snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(),
             (unsigned long long)g_capSeq.fetch_add(1, std::memory_order_relaxed));
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) { logf("CAPTURE_FAIL open tmp %s", tmp); return false; }
    const char* p = (const char*)&s; size_t left = sizeof s;
    while (left) {   // write vérifié (write partiel possible)
        ssize_t w = write(fd, p, left);
        if (w <= 0) { close(fd); unlink(tmp); logf("CAPTURE_FAIL write"); return false; }
        p += (size_t)w; left -= (size_t)w;
    }
    if (fsync(fd) != 0) { close(fd); unlink(tmp); logf("CAPTURE_FAIL fsync file"); return false; }
    close(fd);
    if (rename(tmp, path.c_str()) != 0) { unlink(tmp); logf("CAPTURE_FAIL rename"); return false; }
    // dir sync : rend le rename durable (sinon un crash peut perdre l'entrée de répertoire)
    size_t slash = path.find_last_of('/');
    std::string dir = (slash == std::string::npos) ? "." : path.substr(0, slash);
    int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY);
    if (dfd >= 0) { fsync(dfd); close(dfd); }
    logf("CAPTURE_PASS rewind %d -> %s (si %d breaks %d initBest %d budget %d cfgHash %016llx)",
         rewindDepth, path.c_str(), si, breaksUsed, initialBestCost, budgetOverride,
         (unsigned long long)s.cfgHash);
    return true;
}
static std::atomic<uint64_t> g_inboxWrites{0};
// Refinery feed: dedup by (board-state hash, rewind, initialBestCost); write once.
// Renvoie true SSI le tail est durablement présent dans l'inbox (déjà là = true).
static bool captureToInbox(const std::string& dir, const RotatedPiece* board,
                           const bool* used, int si, int rewindDepth, int breaksUsed,
                           int initialBestCost, int budgetOverride, int acceptCost) {
    uint64_t h = fnv1a(board, (size_t)si * sizeof(RotatedPiece));
    h = fnv1a(&rewindDepth, sizeof rewindDepth, h);
    h = fnv1a(&initialBestCost, sizeof initialBestCost, h);
    char name[300];
    snprintf(name, sizeof name, "%s/tail_%016llx_r%d_b%d.snap", dir.c_str(),
             (unsigned long long)h, rewindDepth, initialBestCost);
    FILE* ex = fopen(name, "rb");
    if (ex) { fclose(ex); return true; }   // dedup : déjà durablement enqueue
    bool ok = captureTailState(name, board, used, si, rewindDepth, breaksUsed,
                               initialBestCost, budgetOverride, acceptCost);
    if (ok) g_inboxWrites.fetch_add(1, std::memory_order_relaxed);   // compteur SEULEMENT si durable
    return ok;
}
static int replayTailState(const std::string& path, uint64_t nodeCap, int sliceS, int sliceN) {
    FILE* f = fopen(path.c_str(), "rb");
    if (!f) { logf("REPLAY_FAIL cannot open %s", path.c_str()); return 2; }
    TailSnapshot s{};
    bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
    if (!ok || s.magic != 0x42575431 || s.version != 1) { logf("REPLAY_FAIL bad snapshot"); return 2; }
    if (s.crc != fnv1a(&s, sizeof s - sizeof s.crc)) { logf("REPLAY_FAIL crc corrupt"); return 2; }
    if (s.cfgHash != tailConfigHash()) { logf("REPLAY_FAIL cfgHash mismatch (diff puzzle) — REFUSE"); return 2; }
    RotatedPiece board[256]; bool used[257];
    memcpy(board, s.board, sizeof board);
    for (int p = 0; p <= 256; p++) used[p] = s.used[p] != 0;
    uint64_t tnr = 0; bool cappedr = false; int costr = s.budgetOverride + 1;
    g_stop.store(false, std::memory_order_relaxed);
    int sr = solveTailMrvRewind(board, used, s.si, s.rewindDepth, s.breaksUsed,
                                nodeCap, &tnr, &cappedr, &costr, s.budgetOverride,
                                s.acceptCost, sliceS, sliceN, s.initialBestCost);
    const char* verdict = sr >= 0 ? "TARGET_FOUND" : cappedr ? "NODE_CAP" :
                          g_stop.load(std::memory_order_relaxed) ? "GLOBAL_STOP" : "EXHAUSTED";
    int v = sr >= 0 ? verifyBoard(board) : -1;
    logf("REPLAY_PASS verdict %s score %d cost %d nodes %llu verified %d (rewind %d initBest %d slice %d/%d)",
         verdict, sr, costr, (unsigned long long)tnr, v, s.rewindDepth, s.initialBestCost, sliceS, sliceN);
    return sr >= 0 ? 0 : 1;
}

// ---- P7-B: parallel cubes with a shared incumbent -----------------------------
static void setupTail(TailMrvState& q, RotatedPiece* board, bool* used,
                      int rewindDepth, int budgetOverride, int initialBestCost) {
    q.board = board; q.used = used;
    q.budget = budgetOverride >= 0 ? budgetOverride : TOTAL_BUDGET;
    q.bestCost = (initialBestCost > 0 && initialBestCost < q.budget + 1) ? initialBestCost : q.budget + 1;
    for (const Hint& h : HINTS) { int ci = (15 - h.tdRow) * 16 + h.tdCol; q.cluePiece[ci] = h.piece; q.clueRot[ci] = h.rot; }
    for (int d = rewindDepth; d < 256; d++) { int ci = SEQ_ROW[d] * 16 + SEQ_COL[d]; q.inTail[ci] = true; q.cells[q.nCells++] = ci; }
    for (int p = 1; p <= 256; p++) if (!used[p]) { const Piece& pc = PIECES[p]; q.sup[pc.n]++; q.sup[pc.e]++; q.sup[pc.s]++; q.sup[pc.w]++; }
}
static void applyRewind(RotatedPiece* board, bool* used, int currentDepth, int rewindDepth) {
    for (int d = rewindDepth; d < currentDepth; d++) {
        int ci = SEQ_ROW[d] * 16 + SEQ_COL[d];
        if (board[ci].pieceNumber) used[board[ci].pieceNumber] = false;
        board[ci] = {};
    }
}
struct CubeResult { uint64_t nodes = 0; bool capped = false; int bestCost = INT_MAX; int score = -1; RotatedPiece board[256]; };
static int replayCubes(const std::string& path, uint64_t nodeCap, int cubeDepth, int workers) {
    FILE* f = fopen(path.c_str(), "rb");
    if (!f) { logf("CUBES_FAIL cannot open %s", path.c_str()); return 2; }
    TailSnapshot s{};
    bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
    if (!ok || s.magic != 0x42575431 || s.crc != fnv1a(&s, sizeof s - sizeof s.crc)) { logf("CUBES_FAIL bad snapshot"); return 2; }
    if (s.cfgHash != tailConfigHash()) { logf("CUBES_FAIL cfgHash mismatch — REFUSE"); return 2; }
    // rewind to expose the tail region, then generate cubes at cubeDepth (single-thread)
    RotatedPiece gboard[256]; bool gused[257];
    memcpy(gboard, s.board, sizeof gboard);
    for (int p = 0; p <= 256; p++) gused[p] = s.used[p] != 0;
    applyRewind(gboard, gused, s.si, s.rewindDepth);
    std::vector<TailCube> cubes;
    { TailMrvState q; setupTail(q, gboard, gused, s.rewindDepth, s.budgetOverride, s.initialBestCost);
      q.nodeCap = UINT64_MAX; q.cubeDepth = cubeDepth; q.cubeOut = &cubes;
      g_stop.store(false, std::memory_order_relaxed);
      tailMrvDfs(q, 0, s.breaksUsed);
#ifdef BW_TAIL_LEDGER_LOCAL
      flushTailLedger(q);
#endif
    }
    logf("CUBES_GEN depth %d -> %zu cubes (workers %d)", cubeDepth, cubes.size(), workers);
    if (cubes.empty()) { logf("CUBES verdict EXHAUSTED score -1 cost %d nodes 0 (no cube)", s.initialBestCost); return 1; }
    // parallel drain with shared incumbent
    std::atomic<int> shared{s.initialBestCost};
    std::atomic<size_t> next{0};
    std::vector<CubeResult> res(workers);
    auto worker = [&](int wid) {
        static thread_local RotatedPiece board[256]; static thread_local bool used[257];
        CubeResult& r = res[wid];
        for (;;) {
            size_t idx = next.fetch_add(1, std::memory_order_relaxed);
            if (idx >= cubes.size() || g_stop.load(std::memory_order_relaxed)) break;
            const TailCube& c = cubes[idx];
            memcpy(board, c.board, sizeof board); memcpy(used, c.used, sizeof used);
            TailMrvState q; setupTail(q, board, used, s.rewindDepth, s.budgetOverride, s.initialBestCost);
            q.nodeCap = nodeCap; q.sharedBest = &shared;
            int placed = 0;
            for (int k = 0; k < q.nCells; k++) { int ci = q.cells[k]; if (board[ci].pieceNumber) { q.placed[ci] = true; placed++; } }
            tailMrvDfs(q, placed, c.running);
            r.nodes += q.nodes; r.capped |= q.capped;
            if (q.solvedScore >= 0 && q.bestCost < r.bestCost) {
                r.bestCost = q.bestCost; r.score = q.solvedScore; memcpy(r.board, q.bestBoard, sizeof r.board);
            }
        }
    };
    std::vector<std::thread> pool;
    for (int w = 0; w < workers; w++) pool.emplace_back(worker, w);
    for (auto& t : pool) t.join();
    // reduce
    uint64_t total = 0; bool capped = false; int bestCost = INT_MAX, score = -1, bestW = -1;
    for (int w = 0; w < workers; w++) { total += res[w].nodes; capped |= res[w].capped;
        if (res[w].score >= 0 && res[w].bestCost < bestCost) { bestCost = res[w].bestCost; score = res[w].score; bestW = w; } }
    bool found = score >= 0 && bestCost <= s.acceptCost;
    const char* verdict = found ? "TARGET_FOUND" :
                          g_stop.load(std::memory_order_relaxed) ? "GLOBAL_STOP" :
                          capped ? "NODE_CAP" : "EXHAUSTED";
    int v = (found && bestW >= 0) ? verifyBoard(res[bestW].board) : -1;
    if (found && bestW >= 0 && v == score) {   // persist the winning board for validation
        saveBoard(res[bestW].board, score, 900 + bestW, 0);
        logf("CUBES_HIT score %d saved (rewind %d) — validate officially", score, s.rewindDepth);
    }
    // imbalance p95-ish = max worker nodes / mean
    uint64_t mx = 0; for (int w = 0; w < workers; w++) mx = std::max(mx, res[w].nodes);
    double imb = total ? (double)mx / ((double)total / workers) : 1.0;
    logf("CUBES_PASS verdict %s bestCost %d score %d verified %d cubes %zu workers %d nodes %llu maxWorker %llu imbalance %.2fx hallChecks %llu hallCuts %llu",
         verdict, bestCost == INT_MAX ? s.initialBestCost : bestCost, score, v, cubes.size(), workers,
         (unsigned long long)total, (unsigned long long)mx, imb,
         (unsigned long long)g_hallChecks.load(), (unsigned long long)g_hallCuts.load());
    return found ? 0 : 1;
}

// ---- P8-A: one shard (deterministic cube index range) = one atomic work unit ----
static int replayShard(const std::string& path, uint64_t nodeCap, int cubeDepth,
                       long shardLo, long shardHi, bool countOnly) {
    FILE* f = fopen(path.c_str(), "rb");
    if (!f) { logf("SHARD_FAIL cannot open %s", path.c_str()); return 2; }
    TailSnapshot s{};
    bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
    if (!ok || s.magic != 0x42575431 || s.crc != fnv1a(&s, sizeof s - sizeof s.crc)) { logf("SHARD_FAIL bad snapshot"); return 2; }
    if (s.cfgHash != tailConfigHash()) { logf("SHARD_FAIL cfgHash mismatch — REFUSE"); return 2; }
    RotatedPiece gboard[256]; bool gused[257];
    memcpy(gboard, s.board, sizeof gboard);
    for (int p = 0; p <= 256; p++) gused[p] = s.used[p] != 0;
    applyRewind(gboard, gused, s.si, s.rewindDepth);
    std::vector<TailCube> cubes; long total;
    { TailMrvState q; setupTail(q, gboard, gused, s.rewindDepth, s.budgetOverride, s.initialBestCost);
      q.nodeCap = UINT64_MAX; q.cubeDepth = cubeDepth; q.cubeOut = &cubes;
      q.cubeLo = countOnly ? 0 : shardLo; q.cubeHi = countOnly ? 0 : shardHi;
      g_stop.store(false, std::memory_order_relaxed);
      tailMrvDfs(q, 0, s.breaksUsed);
#ifdef BW_TAIL_LEDGER_LOCAL
      flushTailLedger(q);
#endif
      total = q.cubeCount; }
    if (countOnly) { logf("CUBE_COUNT %ld depth %d", total, cubeDepth); return 0; }
    std::atomic<int> shared{s.initialBestCost};
    uint64_t nodes = 0; bool capped = false; int best = INT_MAX, score = -1;
    RotatedPiece bestBoard[256] = {};
    static thread_local RotatedPiece board[256]; static thread_local bool used[257];
    for (auto& c : cubes) {
        if (g_stop.load(std::memory_order_relaxed)) break;
        memcpy(board, c.board, sizeof board); memcpy(used, c.used, sizeof used);
        TailMrvState q; setupTail(q, board, used, s.rewindDepth, s.budgetOverride, s.initialBestCost);
        q.nodeCap = nodeCap; q.sharedBest = &shared;
        int placed = 0;
        for (int k = 0; k < q.nCells; k++) { int ci = q.cells[k]; if (board[ci].pieceNumber) { q.placed[ci] = true; placed++; } }
        tailMrvDfs(q, placed, c.running);
        nodes += q.nodes; capped |= q.capped;
        if (q.solvedScore >= 0 && q.bestCost < best) { best = q.bestCost; score = q.solvedScore; memcpy(bestBoard, q.bestBoard, sizeof bestBoard); }
    }
    bool found = score >= 0 && best <= s.acceptCost;
    const char* verdict = found ? "TARGET_FOUND" :
                          g_stop.load(std::memory_order_relaxed) ? "GLOBAL_STOP" :
                          capped ? "NODE_CAP" : "EXHAUSTED";
    if (found) { int v = verifyBoard(bestBoard); if (v == score) saveBoard(bestBoard, score, 800, 0); }
    logf("SHARD_RESULT shard %ld:%ld verdict %s nodes %llu bestCost %d cubes %zu total %ld",
         shardLo, shardHi, verdict, (unsigned long long)nodes,
         best == INT_MAX ? s.initialBestCost : best, cubes.size(), total);
    return found ? 0 : 1;
}

// ---- P8-B: fine per-cube persistence (cap 25M/cube + append journal) ----------
// Long-lived worker pool over compact path-cubes. Per-cube cap so no cube can
// monopolise a worker; every finished cube is journaled atomically so a crash
// replays at most the cubes still in flight. Resume skips journaled cubes.
static std::mutex g_p8Mutex;
static std::mutex g_termMutex;
#ifndef BW_BUILD_ID
#define BW_BUILD_ID (__DATE__ " " __TIME__)
#endif
// P8-B TERMINAL PROOF (Codex, file-per-key) : preuve robuste crash-safe qu'un tail est
// totalement clos. UN FICHIER PAR CLÉ = <cfg>_<crc>_r<rewind>_b<init>.term. Écrit via
// temp unique + fsync + rename atomique (sous verrou) + fsync du répertoire. Lookup =
// existence du fichier (direct, pas de reload, concurrence simple, corruption isolée).
// Seul EXHAUSTED est terminal réutilisable ; CANDIDATE_FOUND ne l'est PAS avant
// validation canonique. (Correction Codex : < PIPE_BUF n'est atomique que pour un pipe,
// pas un fichier régulier sur /mnt/c — d'où le rename atomique par clé.)
struct TermKey { uint64_t cfg, crc; int rewind, initBest;
    bool operator==(const TermKey& o) const {
        return cfg == o.cfg && crc == o.crc && rewind == o.rewind && initBest == o.initBest; } };
static std::string termFile(const std::string& dir, uint64_t cfg, uint64_t crc, int rewind, int initBest) {
    char n[600];
    snprintf(n, sizeof n, "%s/%016llx_%016llx_r%d_b%d.term", dir.c_str(),
             (unsigned long long)cfg, (unsigned long long)crc, rewind, initBest);
    return n;
}
// Hash du header journal P8-B v2 (identique à replayP8b) : lie une preuve à SON snapshot.
static uint64_t journalHeaderHash(const TailSnapshot& s) {
    uint64_t h = tailConfigHash();
    h = h * 1099511628211ULL + s.crc;
    h = h * 1099511628211ULL + (uint64_t)s.rewindDepth;
    h = h * 1099511628211ULL + (uint64_t)(uint32_t)s.initialBestCost;
    return h;
}
// Artefact RÉSULTAT durable (BLOQUEUR 2) : la sortie finale d'un P8-B, checksumée,
// écrite atomiquement à côté du journal. Le backfill l'exige (pas juste un snapshot).
static void writeResultArtifact(const std::string& path, const TailSnapshot& s,
                                const char* verdict, uint64_t unionNodes, int bestCost, uint64_t jHdr,
                                std::atomic<uint64_t>* seq) {
    if (path.empty()) return;
    char body[400];
    int bn = snprintf(body, sizeof body,
        "P8RESULT1 cfg=%llx crc=%llx rewind=%d initBest=%d verdict=%s bestCost=%d union=%llu jhdr=%llx",
        (unsigned long long)s.cfgHash, (unsigned long long)s.crc, s.rewindDepth,
        (int)s.initialBestCost, verdict, bestCost, (unsigned long long)unionNodes, (unsigned long long)jHdr);
    if (bn <= 0 || bn >= (int)sizeof body) return;
    char content[460];
    int n = snprintf(content, sizeof content, "%s chk=%llx\n", body, (unsigned long long)fnv1a(body, (size_t)bn));
    char tmp[560]; snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(),
                            (unsigned long long)(seq ? seq->fetch_add(1) : 0));
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) { logf("P8RESULT_FAIL open tmp"); return; }
    const char* p = content; size_t left = (size_t)n;   // write vérifié (partiel possible)
    while (left) { ssize_t w = write(fd, p, left); if (w <= 0) { close(fd); unlink(tmp); logf("P8RESULT_FAIL write"); return; } p += (size_t)w; left -= (size_t)w; }
    if (fsync(fd) != 0) { close(fd); unlink(tmp); logf("P8RESULT_FAIL fsync"); return; }
    close(fd);
    if (rename(tmp, path.c_str()) != 0) { unlink(tmp); logf("P8RESULT_FAIL rename"); return; }
    size_t sl = path.find_last_of('/'); std::string dir = sl == std::string::npos ? "." : path.substr(0, sl);
    int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY); if (dfd >= 0) { fsync(dfd); close(dfd); }   // dir-sync
}
// Lit + vérifie l'artefact résultat pour une clé donnée. Renvoie true + bestCost si
// EXHAUSTED complet, checksum OK, identité concordante avec le snapshot.
static bool readResultArtifact(const std::string& path, const TailSnapshot& s, int* outBestCost) {
    if (outBestCost) *outBestCost = -1;
    FILE* f = fopen(path.c_str(), "r"); if (!f) return false;
    char line[520]; char* g = fgets(line, sizeof line, f); fclose(f);
    if (!g) return false;
    char* c = strstr(line, " chk="); if (!c) return false;
    unsigned long long chk;
    if (sscanf(c + 5, "%llx", &chk) != 1 || fnv1a(line, (size_t)(c - line)) != chk) return false;
    unsigned long long pcfg, pcrc, un, jh; int prw, pib, pbc; char verd[40];
    if (sscanf(line, "P8RESULT1 cfg=%llx crc=%llx rewind=%d initBest=%d verdict=%39s bestCost=%d union=%llu jhdr=%llx",
               &pcfg, &pcrc, &prw, &pib, verd, &pbc, &un, &jh) != 8) return false;
    if (strcmp(verd, "EXHAUSTED") != 0) return false;                       // GLOBAL_STOP/PARTIAL/... refusés
    if (pcfg != s.cfgHash || pcrc != s.crc || prw != s.rewindDepth || pib != s.initialBestCost) return false;
    if (jh != journalHeaderHash(s)) return false;                           // identité journal concordante
    if (!(pbc > s.acceptCost && pbc <= s.initialBestCost)) return false;    // invariant bestCost
    if (outBestCost) *outBestCost = pbc;
    return true;
}
static void writeTerminalProof(const std::string& dir, const TailSnapshot& s,
                               const char* verdict, uint64_t unionNodes, uint64_t jHdr, int bestCost) {
    if (dir.empty()) return;
    mkdir(dir.c_str(), 0755);   // idempotent (EEXIST ignoré)
    if (strcmp(verdict, "EXHAUSTED") != 0) {   // CANDIDATE_FOUND -> jamais terminal ici
        logf("TERM_PROOF_CANDIDATE rewind=%d (non terminal avant validation)", s.rewindDepth);
        return;
    }
    // Invariant BLOQUEUR 3 : pour EXHAUSTED, acceptCost < bestCost <= initialBestCost
    // (le meilleur near-miss prouvé, ex. 15 pour un b16 ; jamais <= acceptCost = ce serait un hit).
    if (!(bestCost > s.acceptCost && bestCost <= s.initialBestCost)) {
        logf("TERM_PROOF_REFUSE bestCost %d hors (%d, %d] — pas de preuve", bestCost, s.acceptCost, s.initialBestCost);
        return;
    }
    std::string fin = termFile(dir, s.cfgHash, s.crc, s.rewindDepth, s.initialBestCost);
    char body[480];
    int bn = snprintf(body, sizeof body,
        "P8TERM2 cfg=%llx crc=%llx rewind=%d initBest=%d verdict=EXHAUSTED bestCost=%d "
        "closed_at=%lld union=%llu jver=P8BJ4 jhdr=%llx build=\"%s\"",
        (unsigned long long)s.cfgHash, (unsigned long long)s.crc, s.rewindDepth,
        (int)s.initialBestCost, bestCost, (long long)time(nullptr), (unsigned long long)unionNodes,
        (unsigned long long)jHdr, BW_BUILD_ID);
    if (bn <= 0 || bn >= (int)sizeof body) { logf("TERM_PROOF_FAIL content overflow"); return; }
    char content[560];   // checksum du record (fnv du corps) en dernier champ
    int n = snprintf(content, sizeof content, "%s chk=%llx\n", body,
                     (unsigned long long)fnv1a(body, (size_t)bn));
    if (n <= 0 || n >= (int)sizeof content) { logf("TERM_PROOF_FAIL content overflow"); return; }
    std::lock_guard<std::mutex> lk(g_termMutex);
    char tmp[680];
    snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", fin.c_str(), (int)getpid(),
             (unsigned long long)g_capSeq.fetch_add(1, std::memory_order_relaxed));
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) { logf("TERM_PROOF_FAIL open tmp"); return; }
    const char* p = content; size_t left = (size_t)n;
    while (left) { ssize_t w = write(fd, p, left); if (w <= 0) { close(fd); unlink(tmp); logf("TERM_PROOF_FAIL write"); return; } p += (size_t)w; left -= (size_t)w; }
    if (fsync(fd) != 0) { close(fd); unlink(tmp); logf("TERM_PROOF_FAIL fsync"); return; }
    close(fd);
    if (rename(tmp, fin.c_str()) != 0) { unlink(tmp); logf("TERM_PROOF_FAIL rename"); return; }
    int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY); if (dfd >= 0) { fsync(dfd); close(dfd); }
    logf("TERM_PROOF_WRITE rewind=%d initBest=%d union=%llu", s.rewindDepth, (int)s.initialBestCost, (unsigned long long)unionNodes);
}
static std::atomic<uint64_t> g_termRefused{0};
// Garde Codex #1 : un nom de fichier n'est PAS une preuve. Ouvrir, parser le record
// P8TERM2, vérifier version/verdict/cohérence nom↔contenu + checksum. Vide, tronqué,
// version inconnue, incohérent, chk faux = REFUS (term_refused), calcul normal.
static bool terminalProofValid(const std::string& dir, uint64_t cfg, uint64_t crc, int rewind, int initBest,
                               int* outBestCost = nullptr) {
    if (outBestCost) *outBestCost = -1;
    if (dir.empty()) return false;
    FILE* f = fopen(termFile(dir, cfg, crc, rewind, initBest).c_str(), "r");
    if (!f) return false;   // absent = MISS (pas un refus)
    char line[640]; char* got = fgets(line, sizeof line, f); fclose(f);
    if (!got) { g_termRefused.fetch_add(1, std::memory_order_relaxed); return false; }   // vide
    char* c = strstr(line, " chk=");
    if (!c) { g_termRefused.fetch_add(1, std::memory_order_relaxed); return false; }      // tronqué (pas de chk)
    unsigned long long chkStored;
    if (sscanf(c + 5, "%llx", &chkStored) != 1) { g_termRefused.fetch_add(1, std::memory_order_relaxed); return false; }
    if (fnv1a(line, (size_t)(c - line)) != chkStored) { g_termRefused.fetch_add(1, std::memory_order_relaxed); return false; }  // corrompu
    unsigned long long pcfg, pcrc; int prw, pib, pbc; char verd[40];
    if (sscanf(line, "P8TERM2 cfg=%llx crc=%llx rewind=%d initBest=%d verdict=%39s bestCost=%d",
               &pcfg, &pcrc, &prw, &pib, verd, &pbc) != 6) { g_termRefused.fetch_add(1, std::memory_order_relaxed); return false; }  // parse partiel/version
    if (strcmp(verd, "EXHAUSTED") != 0 || pcfg != cfg || pcrc != crc || prw != rewind || pib != initBest) {
        g_termRefused.fetch_add(1, std::memory_order_relaxed); return false;   // incohérent nom↔contenu ou pas EXHAUSTED
    }
    if (!(pbc > 0 && pbc <= pib)) { g_termRefused.fetch_add(1, std::memory_order_relaxed); return false; }  // bestCost aberrant
    if (outBestCost) *outBestCost = pbc;
    return true;   // preuve valide + bestCost prouvé
}
// --- Verdict cache (main-side, shadow #2a) : lookup file-per-key parsé+vérifié
// (pas de reload global). g_termProofDir vide = cache OFF (prod inchangée). ---
static std::string g_termProofDir;
static std::atomic<uint64_t> g_termHit{0}, g_termMiss{0};
// P5a : audit de transposition (hors hot loop : 1 insertion par arrivée d'anneau).
static std::mutex g_auditMtx;
static std::unordered_map<uint64_t, uint32_t> g_auditMult;   // crc-préfixe propre -> nb arrivées
static std::atomic<uint64_t> g_auditTotal{0};

// ============ P6a : oracle LB cardinalité admissible (shadow, échantillonné) ============
// LB = (cellules-frontière contraintes) - (max matching arcs coût-0).  Relaxation ADMISSIBLE :
// on ne compte que les demandes des voisins DÉJÀ posés (west/south), on ignore la contrainte de
// cadre -> matching >= vrai -> LB <= vrais breaks futurs forcés -> jamais de faux prune.
struct LBMatch {
    int nCon, nRem; const int* wDem; const int* sDem; const int* rem;
    std::vector<int> matchOf; std::vector<char> seen;
    bool arc(int k, int j) const {
        const Piece& p = PIECES[rem[j]];
        for (int r = 0; r < 4; r++) {
            if (wDem[k] >= 0 && sideAfterRot(p, r, 3) != wDem[k]) continue;
            if (sDem[k] >= 0 && sideAfterRot(p, r, 2) != sDem[k]) continue;
            return true;
        }
        return false;
    }
    bool tryK(int k) {
        for (int j = 0; j < nRem; j++) {
            if (seen[j] || !arc(k, j)) continue;
            seen[j] = 1;
            if (matchOf[j] < 0 || tryK(matchOf[j])) { matchOf[j] = k; return true; }
        }
        return false;
    }
};
static int cardinalityLB(const RotatedPiece* board, const bool* used) {
    int wDem[256], sDem[256], nCon = 0;
    for (int ci = 0; ci < 256; ci++) {
        if (board[ci].pieceNumber) continue;                       // cellule déjà posée
        int col = ci & 15, row = ci >> 4, wd = -1, sd = -1;
        if (col > 0 && board[ci - 1].pieceNumber)
            wd = sideAfterRot(PIECES[board[ci - 1].pieceNumber], board[ci - 1].rot, 1);   // est du voisin ouest
        if (row > 0 && board[ci - 16].pieceNumber)
            sd = sideAfterRot(PIECES[board[ci - 16].pieceNumber], board[ci - 16].rot, 0); // nord du voisin sud
        if (wd < 0 && sd < 0) continue;                            // non contrainte
        wDem[nCon] = wd; sDem[nCon] = sd; nCon++;
    }
    if (!nCon) return 0;
    int rem[256], nRem = 0;
    for (int p = 1; p <= 256; p++) if (!used[p]) rem[nRem++] = p;
    LBMatch m; m.nCon = nCon; m.nRem = nRem; m.wDem = wDem; m.sDem = sDem; m.rem = rem;
    m.matchOf.assign(nRem, -1); m.seen.assign(nRem, 0);
    int matched = 0;
    for (int k = 0; k < nCon; k++) { std::fill(m.seen.begin(), m.seen.end(), 0); if (m.tryK(k)) matched++; }
    return nCon - matched;
}
static constexpr int LB_NDEP = 8;
static const int LB_DEPTHS[LB_NDEP] = {216, 221, 225, 229, 233, 236, 240, 243};
static std::atomic<uint64_t> g_lbCalls[LB_NDEP], g_lbPrune[LB_NDEP], g_lbSumLB[LB_NDEP], g_lbNanos[LB_NDEP];
// P12 budget-LB : compteurs globaux (calls au gate, wouldCut = spent+LBcolor>B, cut réels)
static std::atomic<uint64_t> g_p12Calls{0}, g_p12WouldCut{0}, g_p12Cut{0};
#ifdef BW_SIGMA_LEDGER
// LBσ (ledger de parité des couleurs, couche 1). calls = candidats break évalués ;
// wouldCut = combien AURAIENT été coupés (shadow, compté même en OFF) ; cut = coupes
// RÉELLEMENT appliquées (ON seulement). g_sigmaLeafBug = feuilles complètes oddMask!=0.
static std::atomic<uint64_t> g_sigmaCalls{0}, g_sigmaWouldCut{0}, g_sigmaCut{0}, g_sigmaLeafBug{0};
#endif
static TermKey computeTailKey(const RotatedPiece* board, const bool* used, int si,
                             int rewindDepth, int breaksUsed, int initialBestCost,
                             int budgetOverride, int acceptCost) {
    TailSnapshot s{};   // MÊME construction que captureTailState -> CRC identique
    s.magic = 0x42575431; s.version = 1; s.cfgHash = tailConfigHash();
    s.si = si; s.rewindDepth = rewindDepth; s.breaksUsed = breaksUsed;
    s.initialBestCost = initialBestCost; s.budgetOverride = budgetOverride;
    s.acceptCost = acceptCost;
    memcpy(s.board, board, sizeof s.board);
    for (int p = 0; p <= 256; p++) s.used[p] = used[p] ? 1 : 0;
    s.crc = fnv1a(&s, sizeof s - sizeof s.crc);
    return {s.cfgHash, s.crc, s.rewindDepth, s.initialBestCost};
}
static bool termCacheHit(const TermKey& k, int* bestCost = nullptr) {
    return terminalProofValid(g_termProofDir, k.cfg, k.crc, k.rewind, k.initBest, bestCost);
}
// --- P8 heartbeat (Codex #2c) : le drain annonce vivant + compatible. Écrit
// atomiquement (temp+fsync+rename). Le main refuse de déférer si absent, stale
// (>45s), cfgHash différent, ou rewind non supporté. Checksum du record. ---
static void writeHeartbeatFile(const std::string& path, int minRewind, int workers) {
    if (path.empty()) return;
    char body[256];
    int bn = snprintf(body, sizeof body,
        "P8HB1 cfg=%llx minRewind=%d format=P8BJ4 workers=%d ts=%lld build=\"%s\"",
        (unsigned long long)tailConfigHash(), minRewind, workers,
        (long long)time(nullptr), BW_BUILD_ID);
    if (bn <= 0 || bn >= (int)sizeof body) return;
    char content[320];
    int n = snprintf(content, sizeof content, "%s chk=%llx\n", body,
                     (unsigned long long)fnv1a(body, (size_t)bn));
    char tmp[360];
    snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(),
             (unsigned long long)g_capSeq.fetch_add(1, std::memory_order_relaxed));
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return;
    if (write(fd, content, (size_t)n) == n) { fsync(fd); close(fd); rename(tmp, path.c_str()); }
    else { close(fd); unlink(tmp); }
}
// Statut heartbeat : 0=OK, 1=absent/stale/corrompu, 2=cfgHash incompatible, 3=rewind non supporté.
static int heartbeatStatus(const std::string& path, int wantRewind, long* ageOut) {
    if (ageOut) *ageOut = -1;
    if (path.empty()) return 1;
    FILE* f = fopen(path.c_str(), "r"); if (!f) return 1;
    char line[320]; char* g = fgets(line, sizeof line, f); fclose(f);
    if (!g) return 1;
    char* c = strstr(line, " chk="); if (!c) return 1;
    unsigned long long chk;
    if (sscanf(c + 5, "%llx", &chk) != 1 || fnv1a(line, (size_t)(c - line)) != chk) return 1;
    unsigned long long cfg; int minRewind, workers; long long ts;
    if (sscanf(line, "P8HB1 cfg=%llx minRewind=%d format=P8BJ4 workers=%d ts=%lld",
               &cfg, &minRewind, &workers, &ts) != 4) return 1;
    long age = (long)(time(nullptr) - (long long)ts);
    if (ageOut) *ageOut = age;
    if (age > 45 || age < -5) return 1;               // stale (ou horloge incohérente)
    if (cfg != tailConfigHash()) return 2;            // cfgHash incompatible
    if (wantRewind < minRewind) return 3;             // rewind non supporté par ce drain
    return 0;
}
// --- Admission defer (Codex garde #2) : décision RARE sérialisée (sous g_admitMtx)
// pour éviter la course des 24 threads. Enum de retour ; ALREADY_OWNED_P8 ne doit
// jamais entraîner un calcul local en double. Hystérésis backlog 4/2. ---
enum CaptureResult { CAP_CREATED, CAP_ALREADY_OWNED_P8, CAP_TERMINAL_HIT,
                     CAP_LOCAL_NOWORKER, CAP_LOCAL_CFG, CAP_LOCAL_BACKPRESSURE, CAP_FAILED };
static std::atomic<uint64_t> g_deferOk{0}, g_localNoWorker{0}, g_localCfgMismatch{0},
    g_localBackpressure{0}, g_localEnqueueFail{0}, g_alreadyOwned{0};
static std::atomic<long> g_pendingUnique{0}, g_hbAge{-1};
static std::mutex g_admitMtx;
static bool g_deferMode = true;   // état d'hystérésis (protégé par g_admitMtx)
// nom de fichier inbox : MÊME clé que captureToInbox (dédup cohérent).
static std::string inboxKeyName(const std::string& dir, const RotatedPiece* board,
                                int si, int rewind, int initBest) {
    uint64_t h = fnv1a(board, (size_t)si * sizeof(RotatedPiece));
    h = fnv1a(&rewind, sizeof rewind, h);
    h = fnv1a(&initBest, sizeof initBest, h);
    char name[300];
    snprintf(name, sizeof name, "%s/tail_%016llx_r%d_b%d.snap", dir.c_str(),
             (unsigned long long)h, rewind, initBest);
    return name;
}
static int countInboxPending(const std::string& dir) {   // backlog P8 : tails (.snap) ET chaînes (.spec)
    DIR* d = opendir(dir.c_str()); if (!d) return 0;
    int n = 0; struct dirent* e;
    while ((e = readdir(d))) { size_t L = strlen(e->d_name);
        // Compte snaps ET specs : la backpressure borne le backlog TOTAL (sinon les
        // .spec de la chaîne échapperaient à l'hystérésis -> admission illimitée).
        if (L > 5 && (strcmp(e->d_name + L - 5, ".snap") == 0 || strcmp(e->d_name + L - 5, ".spec") == 0)) n++; }
    closedir(d); return n;
}
static CaptureResult admitDefer(const std::string& inboxDir, const std::string& hbPath,
        const RotatedPiece* board, const bool* used, int si, int rewind, int breaks,
        int initBest, int budget, int accept, const TermKey& key) {
    std::lock_guard<std::mutex> lk(g_admitMtx);   // décision rare sérialisée
    if (termCacheHit(key)) return CAP_TERMINAL_HIT;                          // 1. déjà prouvé
    if (access(inboxKeyName(inboxDir, board, si, rewind, initBest).c_str(), F_OK) == 0) {
        g_alreadyOwned.fetch_add(1, std::memory_order_relaxed);
        return CAP_ALREADY_OWNED_P8;                                        // 2. déjà possédé P8 (defer, 0 slot)
    }
    long age; int hs = heartbeatStatus(hbPath, rewind, &age);
    g_hbAge.store(age, std::memory_order_relaxed);
    if (hs == 2) { g_localCfgMismatch.fetch_add(1, std::memory_order_relaxed); return CAP_LOCAL_CFG; }
    if (hs != 0) { g_localNoWorker.fetch_add(1, std::memory_order_relaxed); return CAP_LOCAL_NOWORKER; }  // absent/stale/rewind
    int pending = countInboxPending(inboxDir);
    g_pendingUnique.store(pending, std::memory_order_relaxed);
    if (pending >= 4) g_deferMode = false; else if (pending <= 2) g_deferMode = true;  // hystérésis 4/2
    if (!g_deferMode) { g_localBackpressure.fetch_add(1, std::memory_order_relaxed); return CAP_LOCAL_BACKPRESSURE; }
    // 4. enqueue durable -> ownership P8 (recheck terminal juste avant, réduit la course)
    if (termCacheHit(key)) return CAP_TERMINAL_HIT;
    bool ok = captureToInbox(inboxDir, board, used, si, rewind, breaks, initBest, budget, accept);
    if (!ok) { g_localEnqueueFail.fetch_add(1, std::memory_order_relaxed); return CAP_FAILED; }
    g_deferOk.fetch_add(1, std::memory_order_relaxed);
    return CAP_CREATED;
}
// --- Persistance des attempts (Codex #3) : nextAttempt[threadId] survit au restart.
// Header = cfgHash + seed (config SÉMANTIQUE, PAS le nb de threads). Migration N->M :
// tids communs reprennent, nouveaux à 0, tids désactivés préservés. Refuse autre config. ---
static constexpr int MAX_ATT_THREADS = 64;
static std::atomic<uint64_t> g_attemptDone[MAX_ATT_THREADS];
static uint64_t g_attemptResume[MAX_ATT_THREADS] = {0};
static std::mutex g_attMutex;

// --- Canary racine forcée : liste de racines 3x3 (piece/rot ×9), distribuées
// sans doublon entre workers via un dispenser atomique. Aucun contact prod. ---
struct ForceRoot { int p[9]; int r[9]; };
static std::vector<ForceRoot> g_forceRoots;
static uint64_t g_tkRunId = 0, g_tkCfgHash = 0;   // --ticket-log : run-id unique (segment immuable) + config-hash canonique
static bool g_tkArmed = false;                    // journal arme SEULEMENT si le manifeste a ete cree completement
static std::atomic<uint64_t> g_forceNext{0};
// P13 skip-ledger : ensemble EXACT des tickets globaux déjà terminés en local
// (exportés par export_completed_ledger.py depuis harv_out.t*). Un worker Cloud charge
// ce set et NE recalcule JAMAIS un ticket présent -> exclusion locale exacte, pas juste
// un offset de round (Codex : "aucun doublon ET aucun oubli"). Vide = comportement inchangé.
static std::unordered_set<uint64_t> g_skipLedger;
static std::atomic<uint64_t> g_skipLedgerHits{0};
// --root-allow FILE : allowlist de cidx (index racine dans --force-root) autorisés. Garde nroots
// INCHANGÉ -> globalTicket = jidx*nroots + cidx et attemptSeed(fcurRoot,fjleft) STRICTEMENT préservés ;
// seuls les cidx hors-liste sont sautés dans le dispenser (même mécanique que skip-ledger). Vide = tout autorisé.
static std::unordered_set<uint32_t> g_rootAllow;
static std::atomic<uint64_t> g_rootAllowSkips{0};
// --break-mask : masque SPATIAL par-seam. g_breakMaskW/S[ci] = un break est-il autorisé sur le seam
// ouest/sud de la cellule ci ? (sinon match exact imposé). g_breakMaskOn=false -> comportement normal.
static bool g_breakMaskOn = false;
static bool g_breakMaskW[256] = {false}, g_breakMaskS[256] = {false};
static std::atomic<uint64_t> g_tourWriteErrs{0};   // #3 : échecs fflush du journal DONE (tourney)
static std::atomic<uint64_t> g_tourSyncErrs{0};    // #3 : échecs fdatasync du journal DONE
#ifdef BW_CAND_INSTRUMENT
// P14-B falsification (shadow) : ratio de candidats rejetés car pièce déjà utilisée, par
// bucket de profondeur. thread-local dans la hot loop (0 atomic), fusionné en fin de thread.
static std::mutex g_candMtx;
static uint64_t g_candScanned[6] = {0}, g_rejectUsed[6] = {0};
static const char* CAND_BUCKETS[6] = {"<192", "192-207", "208-215", "216-223", "224-229", "230+"};
static inline int candBucket(int si) {
    return si < 192 ? 0 : si < 208 ? 1 : si < 216 ? 2 : si < 224 ? 3 : si < 230 ? 4 : 5;
}
#endif
#ifdef BW_CHOICE_FP
// P14-B gate soundness : fingerprint DÉTERMINISTE de la séquence exacte de choix committés
// (si,ci,piece,rot) + nb de nœuds. Deux bras order-identical DOIVENT donner la même fp.
// thread-local (mono-thread pour le gate) ; imprimée en fin de thread.
static std::mutex g_fpMtx;
static uint64_t g_choiceFP = 1469598103934665603ULL;
static uint64_t g_choiceCount = 0;
#endif

// --- Phase-3 shadow : mesure r224 éligibles + clés fortes DISTINCTES (le vrai
// intrant de l'exact-tail), sans admitChain/enqueue. DFS inchangé. ---
static std::atomic<uint64_t> g_shadowR224Elig{0};
static std::atomic<uint64_t> g_shadowRungEntry[260] = {};   // par rewind depth
static std::atomic<uint64_t> g_shadowCostHist[24] = {};     // curCost - TOTAL_BUDGET (0..23)
static std::mutex g_shadowMtx;
static std::unordered_set<uint64_t> g_shadowKeys;           // clés fortes r224 uniques
// Hash de TOUS les paramètres affectant la recherche (Codex #3) : cfgHash (pièces/
// hints/orientation/breaks-positions/budget) + seed + heur + prune + endgame + breaks
// + version d'algo. Le nb de threads est EXCLU (migration N<->M autorisée).
static uint64_t attemptParamHash(uint64_t seed) {
    uint64_t h = tailConfigHash();
    h = fnv1a(&seed, sizeof seed, h);
    double hs = cfg.heurScale; h = fnv1a(&hs, sizeof hs, h);
    long pr = cfg.pruneNodes; int pd = cfg.pruneDepth; h = fnv1a(&pr, sizeof pr, h); h = fnv1a(&pd, sizeof pd, h);
    int ed = cfg.endgameDepth; long en = (long)cfg.endgameNodes; int ep = cfg.endgameProbeExtra;
    h = fnv1a(&ed, sizeof ed, h); h = fnv1a(&en, sizeof en, h); h = fnv1a(&ep, sizeof ep, h);
    // Codex : hasher la TAILLE avant le contenu (pas d'ambiguïté de concaténation).
    size_t brs = cfg.breaks.size(); h = fnv1a(&brs, sizeof brs, h); h = fnv1a(cfg.breaks.data(), brs, h);
    int rd = cfg.ringDepth; h = fnv1a(&rd, sizeof rd, h);
    size_t lsz = cfg.ladder.size(); h = fnv1a(&lsz, sizeof lsz, h);
    for (const auto& r : cfg.ladder) {   // ladder gaps/rewinds/caps, champ par champ (pas de padding brut)
        int g = r.gap, rw = r.rewind; long nd = (long)r.nodes;
        h = fnv1a(&g, sizeof g, h); h = fnv1a(&rw, sizeof rw, h); h = fnv1a(&nd, sizeof nd, h);
    }
    // tous les paramètres qui changent l'issue d'un attempt, un par un.
    long nc = (long)cfg.nodeCap; h = fnv1a(&nc, sizeof nc, h);
    int cb = cfg.cellBreaks, sp = cfg.sdPrune, ib = cfg.isolatedBreaks, ta = cfg.tailAdaptive;
    h = fnv1a(&cb, sizeof cb, h); h = fnv1a(&sp, sizeof sp, h); h = fnv1a(&ib, sizeof ib, h); h = fnv1a(&ta, sizeof ta, h);
    int td = cfg.tailDepth, tms = cfg.tailMinSlack; long tn = (long)cfg.tailNodes, tp = (long)cfg.tailPeriod;
    h = fnv1a(&td, sizeof td, h); h = fnv1a(&tms, sizeof tms, h); h = fnv1a(&tn, sizeof tn, h); h = fnv1a(&tp, sizeof tp, h);
    long yb = (long)cfg.yieldBase, yp = (long)cfg.yieldPer; h = fnv1a(&yb, sizeof yb, h); h = fnv1a(&yp, sizeof yp, h);
    int es = cfg.endgameSample, tss = cfg.tsS, tsn = cfg.tsN, tsr = cfg.tsRewind;   // Codex 22:14
    h = fnv1a(&es, sizeof es, h); h = fnv1a(&tss, sizeof tss, h); h = fnv1a(&tsn, sizeof tsn, h); h = fnv1a(&tsr, sizeof tsr, h);
    size_t hcs = cfg.heurColors.size(); h = fnv1a(&hcs, sizeof hcs, h); h = fnv1a(cfg.heurColors.data(), hcs, h);
    const char* ver = "ATTSTATE1-ALGO4"; h = fnv1a(ver, strlen(ver), h);
    return h;
}
// Reconstruit merged[] depuis un fichier ATTSTATE1 valide (header param + checksum).
// Renvoie true si le fichier est valide et compatible ; sinon merged inchangé.
static bool readAttemptFile(const std::string& path, uint64_t param, uint64_t* merged) {
    FILE* f = fopen(path.c_str(), "rb"); if (!f) return false;
    std::string all; char buf[512]; size_t rd;
    while ((rd = fread(buf, 1, sizeof buf, f)) > 0) all.append(buf, rd);
    fclose(f);
    size_t ck = all.rfind("\nchk=");
    if (ck == std::string::npos) return false;
    unsigned long long stored;
    if (sscanf(all.c_str() + ck + 5, "%llx", &stored) != 1) return false;
    if (fnv1a(all.data(), ck + 1) != stored) return false;            // checksum du fichier
    unsigned long long p;
    if (sscanf(all.c_str(), "ATTSTATE1 param=%llx", &p) != 1 || p != param) return false;  // config
    size_t pos = all.find('\n'); if (pos == std::string::npos) return false;
    while (pos < ck) {
        size_t nl = all.find('\n', pos + 1); if (nl == std::string::npos || nl > ck) break;
        int tid; unsigned long long att;
        if (sscanf(all.c_str() + pos + 1, "%d %llu", &tid, &att) == 2 && tid >= 0 && tid < MAX_ATT_THREADS)
            merged[tid] = att;
        pos = nl;
    }
    return true;
}
static void loadAttemptState(const std::string& path, uint64_t seed) {
    for (int i = 0; i < MAX_ATT_THREADS; i++) g_attemptResume[i] = 0;
    if (path.empty()) return;
    uint64_t merged[MAX_ATT_THREADS]; for (int i = 0; i < MAX_ATT_THREADS; i++) merged[i] = 0;
    if (!readAttemptFile(path, attemptParamHash(seed), merged)) {
        logf("ATTEMPT_STATE_REFUSE absent/tronqué/checksum/config — départ frais"); return;
    }
    int loaded = 0;
    for (int i = 0; i < MAX_ATT_THREADS; i++) { g_attemptResume[i] = merged[i]; if (merged[i]) loaded++; }
    logf("ATTEMPT_STATE resumed %d tids", loaded);
}
static void writeAttemptState(const std::string& path, int threads, uint64_t seed) {
    if (path.empty()) return;
    std::lock_guard<std::mutex> lk(g_attMutex);
    uint64_t param = attemptParamHash(seed);
    uint64_t merged[MAX_ATT_THREADS]; for (int i = 0; i < MAX_ATT_THREADS; i++) merged[i] = 0;
    readAttemptFile(path, param, merged);   // préserve les tids désactivés (N->M->N)
    int hi = threads < MAX_ATT_THREADS ? threads : MAX_ATT_THREADS;
    for (int i = 0; i < hi; i++) merged[i] = g_attemptDone[i].load(std::memory_order_relaxed);
    std::string body = "ATTSTATE1 param=" ;
    { char hx[24]; snprintf(hx, sizeof hx, "%llx\n", (unsigned long long)param); body += hx; }
    for (int i = 0; i < MAX_ATT_THREADS; i++) if (merged[i]) {
        char l[48]; snprintf(l, sizeof l, "%d %llu\n", i, (unsigned long long)merged[i]); body += l; }
    char ckl[32]; snprintf(ckl, sizeof ckl, "chk=%llx\n", (unsigned long long)fnv1a(body.data(), body.size()));
    body += ckl;
    char tmp[600]; snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(),
                            (unsigned long long)g_capSeq.fetch_add(1, std::memory_order_relaxed));
    int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return;
    if (write(fd, body.data(), body.size()) == (ssize_t)body.size()) { fsync(fd); close(fd);
        if (rename(tmp, path.c_str()) == 0) {   // dir-sync : rend le rename durable
            size_t sl = path.find_last_of('/'); std::string dir = sl == std::string::npos ? "." : path.substr(0, sl);
            int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY); if (dfd >= 0) { fsync(dfd); close(dfd); }
        } else unlink(tmp);
    } else { close(fd); unlink(tmp); }
}
static long g_p8bSample = 0;            // >0: calibrate on first N cubes only
static size_t g_p8bQueueCap = 8000000;  // memory guard: stop splitting past this many queued cubes
static uint64_t g_p8bLowWater = 0;      // #4 : cap bas quand ready < 2*workers (0 = off)
// Outcome structuré d'un P8-B (mode B : chaîner r224 -> r216).
struct P8bOutcome { int verdict = -1; int bestCost = -1; bool targetFound = false; uint64_t spentNodes = 0; };
// verdict : 0=EXHAUSTED complet · 1=TARGET_FOUND · 2=CAPPED_TOTAL (sonde r216) · 3=autre (partiel/abort/stop)
static int replayP8b(const std::string& path, uint64_t perCubeCap, int cubeDepth,
                     int workers, const std::string& journalPath,
                     const std::string& manifestPath = "",
                     P8bOutcome* outcome = nullptr, uint64_t totalCap = 0) {
    FILE* f = fopen(path.c_str(), "rb");
    if (!f) { logf("P8B_FAIL cannot open %s", path.c_str()); return 2; }
    TailSnapshot s{};
    bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
    if (!ok || s.magic != 0x42575431 || s.crc != fnv1a(&s, sizeof s - sizeof s.crc)) { logf("P8B_FAIL bad snapshot"); return 2; }
    if (s.cfgHash != tailConfigHash()) { logf("P8B_FAIL cfgHash mismatch — REFUSE"); return 2; }
    RotatedPiece gboard[256]; bool gused[257];
    memcpy(gboard, s.board, sizeof gboard);
    for (int p = 0; p <= 256; p++) gused[p] = s.used[p] != 0;
    applyRewind(gboard, gused, s.si, s.rewindDepth);
    std::vector<PathCube> paths; long total;
    { TailMrvState q; setupTail(q, gboard, gused, s.rewindDepth, s.budgetOverride, s.initialBestCost);
      q.nodeCap = UINT64_MAX; q.cubeDepth = cubeDepth; q.pathOut = &paths;
      g_stop.store(false, std::memory_order_relaxed);
      tailMrvDfs(q, 0, s.breaksUsed);
#ifdef BW_TAIL_LEDGER_LOCAL
      flushTailLedger(q);
#endif
      total = q.cubeCount; }
    if (g_p8bSample > 0 && (long)paths.size() > g_p8bSample) paths.resize(g_p8bSample);
    logf("P8B_GEN paths %zu total %ld cap %lluM sample %ld", paths.size(), total, (unsigned long long)(perCubeCap / 1000000), g_p8bSample);
    auto reconstruct = [&](const PathCube& pc, RotatedPiece* b, bool* u) {
        memcpy(b, gboard, sizeof gboard); memcpy(u, gused, 257);
        for (int d = 0; d < pc.depth; d++) {
            int c = pc.cell[d], p = pc.piece[d], r = pc.rot[d];
            b[c] = {(uint16_t)p, (uint8_t)r, sideAfterRot(PIECES[p], r, 0), sideAfterRot(PIECES[p], r, 1), 0, PIECE_HSC[p], 0};
            u[p] = true;
        }
    };
    // Deterministic 128-bit path identity: two independent hashes over
    // (position, cell, piece, rot) — position folds in to defeat permutations.
    struct H128 { uint64_t a, b; };
    auto pathHash = [](const PathCube& pc) -> H128 {
        uint64_t h1 = 1469598103934665603ULL;   // FNV-1a
        uint64_t h2 = 0x9E3779B97F4A7C15ULL;     // independent mixer
        for (int d = 0; d < pc.depth; d++) {
            uint8_t buf[5] = { (uint8_t)d, pc.cell[d], (uint8_t)(pc.piece[d] & 0xff),
                               (uint8_t)(pc.piece[d] >> 8), pc.rot[d] };
            for (int b = 0; b < 5; b++) {
                h1 ^= buf[b]; h1 *= 1099511628211ULL;
                h2 = (h2 ^ buf[b]) * 0x100000001b3ULL; h2 ^= h2 >> 29;
            }
        }
        return {h1, h2};
    };
    // One deterministic MRV level from a cube -> children paths (no probe).
    auto expand = [&](const PathCube& pc, std::vector<PathCube>& out) {
        RotatedPiece eb[256]; bool eu[257]; reconstruct(pc, eb, eu);
        TailMrvState q2; setupTail(q2, eb, eu, s.rewindDepth, s.budgetOverride, s.initialBestCost);
        q2.nodeCap = UINT64_MAX; q2.cubeDepth = pc.depth + 1; q2.pathOut = &out;
        int pl2 = 0; for (int k = 0; k < q2.nCells; k++) { int c = q2.cells[k]; if (eb[c].pieceNumber) { q2.placed[c] = true; pl2++; } }
        tailMrvDfs(q2, pl2, pc.running);
    };

    // --- P8-B journal v2: versioned header, path-hash IDs, DAG recovery, bounded fsync ---
    // Header identity ties the journal to THIS tail (config + snapshot + rewind + initBest);
    // a foreign/stale journal is refused, never silently reused.
    uint64_t jHdr = tailConfigHash();
    jHdr = jHdr * 1099511628211ULL + s.crc;
    jHdr = jHdr * 1099511628211ULL + (uint64_t)s.rewindDepth;
    jHdr = jHdr * 1099511628211ULL + (uint64_t)(uint32_t)s.initialBestCost;
    std::unordered_map<uint64_t, std::pair<uint64_t,uint64_t>> jE;  // h1 -> (h2, nodes)
    std::unordered_map<uint64_t, std::pair<uint64_t,uint64_t>> jS;  // h1 -> (h2, probeNodes)
    int resumeBest = s.initialBestCost;   // BLOQUEUR 1 journal : meilleur coût DURABLE par record
    { FILE* jr = fopen(journalPath.c_str(), "r");
      if (jr) {
        char line[160]; bool hdrOk = false; unsigned long long hh;
        if (fgets(line, sizeof line, jr) && sscanf(line, "P8BJ4 %llx", &hh) == 1 && hh == jHdr) hdrOk = true;
        if (!hdrOk) { fclose(jr); logf("P8B_JOURNAL_REJECT header/version mismatch — refuse stale/foreign journal"); return 2; }
        char tag; unsigned long long h1, h2, nd; int bc;
        while (fgets(line, sizeof line, jr)) {
            int n = sscanf(line, "%c %llx %llx %llu %d", &tag, &h1, &h2, &nd, &bc);   // nd = nodes(E)|probeNodes(S)
            if (n != 5) continue;
            if (bc > 0 && bc < resumeBest) resumeBest = bc;
            if (tag == 'E') {   // Codex : une clé répétée doit être IDENTIQUE, sinon ABORT (jamais silencieux)
                auto it = jE.find(h1);
                if (it != jE.end() && (it->second.first != h2 || it->second.second != nd)) { fclose(jr); logf("P8B_JOURNAL_ABORT contradictory E key %llx", h1); return 2; }
                jE[h1] = { h2, nd };
            } else if (tag == 'S') {
                auto it = jS.find(h1);
                if (it != jS.end() && (it->second.first != h2 || it->second.second != nd)) { fclose(jr); logf("P8B_JOURNAL_ABORT contradictory S key %llx", h1); return 2; }
                jS[h1] = { h2, nd };
            }
        }
        fclose(jr);
      }
    }
    // Une même clé ne peut être E ET S (cube exhausted XOR split) : contradiction -> ABORT.
    for (auto& kv : jE) if (jS.count(kv.first)) { logf("P8B_JOURNAL_ABORT key %llx en E ET S", (unsigned long long)kv.first); return 2; }
    // Codex : resumeSpent APRÈS parsing, sur les entrées UNIQUES (pas de double compte de doublons).
    uint64_t resumeSpent = 0;
    for (auto& kv : jE) resumeSpent += kv.second.second;
    for (auto& kv : jS) resumeSpent += kv.second.second;
    logf("P8B_RESUME journal E=%zu S=%zu resumeBest=%d spent=%lluM", jE.size(), jS.size(), resumeBest, (unsigned long long)(resumeSpent/1000000));
    bool freshJournal = jE.empty() && jS.empty();
    FILE* jf = fopen(journalPath.c_str(), freshJournal ? "w" : "a");
    if (!jf) { logf("P8B_FAIL cannot open journal for write"); return 2; }
    if (freshJournal) { fprintf(jf, "P8BJ4 %llx\n", (unsigned long long)jHdr); fflush(jf); fsync(fileno(jf)); }

    // shared reprend le MIN durable (pas initialBestCost) : le best15 survit au kill.
    std::atomic<int> shared{resumeBest}, foundScore{-1};
    std::atomic<uint64_t> unionNodes{0}, wasted{0};
    std::atomic<uint64_t> spentNodes{resumeSpent};   // Codex : budget CPU cumulé DURABLE (E.nodes + S.probeNodes)
    std::atomic<long> exhausted{0}, splits{0}, skipE{0}, skipS{0}, jWrites{0}, interrupted{0};
    std::mutex nextMx;
    for (auto& kv : jE) unionNodes += kv.second.second;   // pre-credit already-closed leaves
    std::vector<PathCube> current = std::move(paths);
    int round = 0; size_t peak = current.size();
    const long FSYNC_EVERY = 256;   // bounded batch: a crash replays at most this many inflight cubes
    // Rounds: capped cube -> one MRV level -> children next round. Resume skips E leaves
    // (pre-credited) and re-expands S parents (deterministic children, no re-probe).
    while (!current.empty() && foundScore.load() < 0 && !g_stop.load(std::memory_order_relaxed)) {
        std::atomic<size_t> ci{0}; std::vector<PathCube> next;
        auto worker = [&]() {
            static thread_local RotatedPiece board[256]; static thread_local bool used[257];
            std::vector<PathCube> localNext;
            for (;;) {
                size_t i = ci.fetch_add(1, std::memory_order_relaxed);
                if (i >= current.size() || g_stop.load(std::memory_order_relaxed)) break;
                const PathCube& pc = current[i];
                H128 h = pathHash(pc);
                auto itE = jE.find(h.a);
                if (itE != jE.end()) {   // done leaf (nodes pre-credited) — verify 2nd hash
                    if (itE->second.first != h.b) { g_hashCollision.store(true); g_stop.store(true); break; }
                    skipE.fetch_add(1); continue;
                }
                auto itS = jS.find(h.a);
                if (itS != jS.end()) {   // done split — verify 2nd hash, regen children
                    if (itS->second.first != h.b) { g_hashCollision.store(true); g_stop.store(true); break; }
                    skipS.fetch_add(1); unionNodes += 1; expand(pc, localNext); continue;
                }
                reconstruct(pc, board, used);
                TailMrvState q; setupTail(q, board, used, s.rewindDepth, s.budgetOverride, s.initialBestCost);
                // #4 low-water : quand la fin du round approche (ready < 2*workers), cap bas
                // pour que les gros cubes restants SPLITTENT vite (nourrissent le round suivant)
                // au lieu qu'un seul monopolise et fasse traîner le round. union reste exacte.
                uint64_t capThis = perCubeCap;
                if (g_p8bLowWater > 0) {
                    size_t ready = (i < current.size()) ? current.size() - i : 0;
                    if (ready < (size_t)(2 * workers) && g_p8bLowWater < perCubeCap) capThis = g_p8bLowWater;
                }
                if (totalCap > 0) {   // Codex : borne l'overshoot par cube au budget CUMULÉ restant
                    uint64_t sp = spentNodes.load(std::memory_order_relaxed);
                    if (sp >= totalCap) { g_stop.store(true, std::memory_order_relaxed); break; }  // budget consommé
                    uint64_t rem = totalCap - sp; if (rem < capThis) capThis = rem;                 // overshoot <= workers*perCubeCap
                }
                q.nodeCap = capThis; q.sharedBest = &shared;
                int placed = 0; for (int k = 0; k < q.nCells; k++) { int c = q.cells[k]; if (board[c].pieceNumber) { q.placed[c] = true; placed++; } }
                tailMrvDfs(q, placed, pc.running);
                bool hit = q.solvedScore >= 0 && q.bestCost <= s.acceptCost;
                if (hit) { int v = verifyBoard(q.bestBoard); if (v == q.solvedScore) { foundScore.store(q.solvedScore); saveBoard(q.bestBoard, q.solvedScore, 800, 0); } }
                // BLOQUEUR Codex : tailMrvDfs sort tôt sur g_stop SANS poser q.capped. Un cube
                // interrompu (SIGTERM, ou budget atteint par un autre worker) ne doit JAMAIS être
                // journalé (faux E/S) ni compté : on le rejoue à la reprise (sûr, idempotent).
                if (!hit && g_stop.load(std::memory_order_relaxed)) { interrupted.fetch_add(1, std::memory_order_relaxed); break; }
                if (q.capped && !hit) {   // SPLIT réel : children déterministes + record S (probeNodes)
                    expand(pc, localNext);
                    splits.fetch_add(1); wasted += q.nodes; unionNodes += 1;
                    std::lock_guard<std::mutex> lk(g_p8Mutex);
                    fprintf(jf, "S %llx %llx %llu %d\n", (unsigned long long)h.a, (unsigned long long)h.b, (unsigned long long)q.nodes, q.bestCost);
                    spentNodes += q.nodes;   // Codex : compter SEULEMENT à l'écriture d'un record valide
                    if (jWrites.fetch_add(1) % FSYNC_EVERY == 0) { fflush(jf); fsync(fileno(jf)); }
                } else if (!hit) {   // EXHAUSTED réel (pas interrompu)
                    exhausted.fetch_add(1); unionNodes += q.nodes;
                    std::lock_guard<std::mutex> lk(g_p8Mutex);
                    fprintf(jf, "E %llx %llx %llu %d\n", (unsigned long long)h.a, (unsigned long long)h.b, (unsigned long long)q.nodes, q.bestCost);
                    spentNodes += q.nodes;
                    if (jWrites.fetch_add(1) % FSYNC_EVERY == 0) { fflush(jf); fsync(fileno(jf)); }
                }
            }
            std::lock_guard<std::mutex> lk(nextMx); for (auto& c : localNext) next.push_back(c);
        };
        std::vector<std::thread> pool;
        for (int w = 0; w < workers; w++) pool.emplace_back(worker);
        for (auto& t : pool) t.join();
        { std::lock_guard<std::mutex> lk(g_p8Mutex); fflush(jf); fsync(fileno(jf)); }   // round barrier: durable
        current = std::move(next); round++; if (current.size() > peak) peak = current.size();
        if (current.size() > g_p8bQueueCap) {   // memory guard: queue too big -> stop (raise cap / disk queue)
            logf("P8B_QUEUE_CAP hit queue %zu > %zu at round %d — verdict PARTIAL_MEM", current.size(), g_p8bQueueCap, round);
            g_stop.store(true, std::memory_order_relaxed);
        }
        // Cap TOTAL (mode B) : arrêt après spentNodes (budget CPU CUMULÉ durable) >= totalCap.
        if (totalCap > 0 && spentNodes.load() >= totalCap) g_stop.store(true, std::memory_order_relaxed);
    }
    bool capTotalHit = totalCap > 0 && spentNodes.load() >= totalCap;
    { std::lock_guard<std::mutex> lk(g_p8Mutex); fflush(jf); fsync(fileno(jf)); }
    fclose(jf);
    bool memStop = current.size() > g_p8bQueueCap;
    const char* tv = g_pathOverflow.load() ? "ABORT_PATH_OVERFLOW" :
                     g_hashCollision.load() ? "ABORT_HASH_COLLISION" :
                     foundScore.load() >= 0 ? "TARGET_FOUND" :
                     memStop ? "PARTIAL_MEM" :
                     capTotalHit ? "CAPPED_TOTAL" :
                     g_stop.load(std::memory_order_relaxed) ? "GLOBAL_STOP" : "EXHAUSTED";
    double wpct = unionNodes.load() ? 100.0 * wasted.load() / unionNodes.load() : 0.0;
    int provenBC = shared.load(std::memory_order_relaxed);   // BLOQUEUR 3 : meilleur coût prouvé
    logf("P8B_DONE exhausted %ld splits %ld skipE %ld skipS %ld interrupted %ld rounds %d peakQ %zu union_nodes %llu wasted %llu (%.1f%%) spent %llu bestCost %d verdict %s",
         exhausted.load(), splits.load(), skipE.load(), skipS.load(), interrupted.load(), round, peak, (unsigned long long)unionNodes.load(),
         (unsigned long long)wasted.load(), wpct, (unsigned long long)spentNodes.load(), provenBC, tv);
    // N'écrire QUE des preuves réutilisables. EXHAUSTED complet = preuve directe (avec
    // bestCost). TARGET_FOUND => CANDIDATE_FOUND (non terminal). Rien pour CAPPED/PARTIAL/STOP/ABORT.
    bool exhaustedComplete = !memStop && !capTotalHit && !g_pathOverflow.load() &&
                             !g_hashCollision.load() && !g_stop.load(std::memory_order_relaxed);
    if (g_p8bSample > 0) {
        if (!manifestPath.empty()) logf("TERM_MANIFEST_SKIP sampled run (not a complete proof)");
    } else if (foundScore.load() >= 0) {
        writeTerminalProof(manifestPath, s, "CANDIDATE_FOUND", unionNodes.load(), jHdr, 0);
    } else if (exhaustedComplete) {
        writeTerminalProof(manifestPath, s, "EXHAUSTED", unionNodes.load(), jHdr, provenBC);
        writeResultArtifact(journalPath + ".result", s, "EXHAUSTED", unionNodes.load(), provenBC, jHdr, &g_capSeq);
    }
    if (outcome) {   // mode B : remonter l'issue pour chaîner
        outcome->bestCost = provenBC;
        outcome->targetFound = foundScore.load() >= 0;
        outcome->verdict = foundScore.load() >= 0 ? 1 : exhaustedComplete ? 0 : capTotalHit ? 2 : 3;
        outcome->spentNodes = spentNodes.load();   // budget CPU cumulé (affiché avant/après kill)
    }
    return foundScore.load() >= 0 ? 0 : 1;
}

// ===== Mode B : chaîne P8-owned r224 -> r216 (Codex) =====
// Une chaîne = P8 possède tout le ladder d'un préfixe. R224 exhaustif ; si bestCost
// rend r216 éligible (condition INLINE exacte : curCost <= TOTAL_BUDGET+gap216, cf.
// ladder ligne "if (curCost > TOTAL_BUDGET+rung.gap) break"), P8 crée ATOMIQUEMENT la
// continuation r216 puis la sonde cappée. Crash-safe à chaque frontière (fichier d'état).
struct ChainSpec {
    uint32_t magic;        // 0x42574333 = "BWC3"
    uint32_t version;
    TailSnapshot r224;
    int32_t rewind216, gap216;
    int32_t breaksUsed216; // Invariant 2 Codex : breaksUsed à profondeur (rewind216-1), != r224
    uint64_t nodeCap216;   // cap TOTAL de la sonde r216 (r216 ne s'exhauste pas)
    uint64_t crc;
};
// cumBreaks[N-1] = somme des breakCount (0/1 par cellule) en ordre SEQ, depths 0..N-1.
static int breaksUpTo(const RotatedPiece* board, int N) {
    int b = 0;
    for (int d = 0; d < N; d++) { int ci = HOT.seqRow[d] * 16 + HOT.seqCol[d]; b += board[ci].breakCount; }
    return b;
}
static void writeChainState(const std::string& path, const char* stage, int b224) {
    char body[128]; int bn = snprintf(body, sizeof body, "P8CHAIN1 stage=%s b224=%d", stage, b224);
    char content[160]; int n = snprintf(content, sizeof content, "%s chk=%llx\n", body, (unsigned long long)fnv1a(body, (size_t)bn));
    char tmp[600]; snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(), (unsigned long long)g_capSeq.fetch_add(1));
    int fd = open(tmp, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (fd < 0) return;
    if (write(fd, content, (size_t)n) == n) { fsync(fd); close(fd);
        if (rename(tmp, path.c_str()) == 0) { size_t sl=path.find_last_of('/'); std::string d=sl==std::string::npos?".":path.substr(0,sl);
            int dfd=open(d.c_str(),O_RDONLY|O_DIRECTORY); if(dfd>=0){fsync(dfd);close(dfd);} } else unlink(tmp);
    } else { close(fd); unlink(tmp); }
}
static bool readChainState(const std::string& path, char* stageOut, int* b224Out) {
    FILE* f = fopen(path.c_str(), "r"); if (!f) return false;
    char line[160]; char* g = fgets(line, sizeof line, f); fclose(f); if (!g) return false;
    char* c = strstr(line, " chk="); if (!c) return false;
    unsigned long long chk; if (sscanf(c+5,"%llx",&chk)!=1 || fnv1a(line,(size_t)(c-line))!=chk) return false;
    int b; char st[32];
    if (sscanf(line, "P8CHAIN1 stage=%31s b224=%d", st, &b) != 2) return false;
    strncpy(stageOut, st, 31); stageOut[31]=0; if (b224Out) *b224Out = b;
    return true;
}
static bool writeSnapshotFile(const std::string& path, const TailSnapshot& s) {
    char tmp[600]; snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(), (unsigned long long)g_capSeq.fetch_add(1));
    int fd = open(tmp, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (fd<0) return false;
    const char* p=(const char*)&s; size_t left=sizeof s;
    while(left){ ssize_t w=write(fd,p,left); if(w<=0){close(fd);unlink(tmp);return false;} p+=(size_t)w; left-=(size_t)w; }
    if(fsync(fd)!=0){close(fd);unlink(tmp);return false;} close(fd);
    if(rename(tmp,path.c_str())!=0){unlink(tmp);return false;}
    size_t sl=path.find_last_of('/'); std::string d=sl==std::string::npos?".":path.substr(0,sl);
    int dfd=open(d.c_str(),O_RDONLY|O_DIRECTORY); if(dfd>=0){fsync(dfd);close(dfd);}
    return true;
}
// Admission-chaîne côté main (mode B) : nom par clé forte de chaîne.
static std::string chainKeyName(const std::string& dir, const ChainSpec& ch) {
    char n[320];
    snprintf(n, sizeof n, "%s/chain_%016llx_%016llx_r%d_b%d.spec", dir.c_str(),
             (unsigned long long)ch.r224.cfgHash, (unsigned long long)ch.r224.crc,
             ch.r224.rewindDepth, ch.r224.initialBestCost);
    return n;
}
static bool writeChainSpecFile(const std::string& path, const ChainSpec& ch) {
    char tmp[380]; snprintf(tmp, sizeof tmp, "%s.tmp.%d.%llu", path.c_str(), (int)getpid(), (unsigned long long)g_capSeq.fetch_add(1));
    int fd = open(tmp, O_WRONLY|O_CREAT|O_TRUNC, 0644); if (fd<0) return false;
    const char* p=(const char*)&ch; size_t left=sizeof ch;
    while(left){ ssize_t w=write(fd,p,left); if(w<=0){close(fd);unlink(tmp);return false;} p+=(size_t)w; left-=(size_t)w; }
    if(fsync(fd)!=0){close(fd);unlink(tmp);return false;} close(fd);
    if(rename(tmp,path.c_str())!=0){unlink(tmp);return false;}
    size_t sl=path.find_last_of('/'); std::string d=sl==std::string::npos?".":path.substr(0,sl);
    int dfd=open(d.c_str(),O_RDONLY|O_DIRECTORY); if(dfd>=0){fsync(dfd);close(dfd);}
    return true;
}
// Construit une ChainSpec depuis l'état ladder du main (board complet, breaks à 223 ET 215).
static ChainSpec buildChainSpec(const RotatedPiece* board, const bool* used, int si,
                                int breaks224, int breaks216, int curCost, int gap224, int gap216) {
    ChainSpec ch{}; ch.magic = 0x42574333; ch.version = 1;
    ch.r224.magic = 0x42575431; ch.r224.version = 1; ch.r224.cfgHash = tailConfigHash();
    ch.r224.si = si; ch.r224.rewindDepth = 224; ch.r224.breaksUsed = breaks224;
    ch.r224.initialBestCost = curCost; ch.r224.budgetOverride = TOTAL_BUDGET + gap224; ch.r224.acceptCost = TOTAL_BUDGET;
    memcpy(ch.r224.board, board, sizeof ch.r224.board);
    for (int p = 0; p <= 256; p++) ch.r224.used[p] = used[p] ? 1 : 0;
    ch.r224.crc = fnv1a(&ch.r224, sizeof ch.r224 - sizeof ch.r224.crc);
    ch.rewind216 = 216; ch.gap216 = gap216; ch.breaksUsed216 = breaks216; ch.nodeCap216 = 10000000000ULL;
    ch.crc = fnv1a(&ch, sizeof ch - sizeof ch.crc);
    return ch;
}
// Admission atomique d'une chaîne (mode B) : mêmes gardes que admitDefer (heartbeat,
// hystérésis backlog, ownership exclusif). Le main abandonne local seulement sur CREATED/ALREADY.
static CaptureResult admitChain(const std::string& inboxDir, const std::string& hbPath, const ChainSpec& ch) {
    std::lock_guard<std::mutex> lk(g_admitMtx);
    std::string kn = chainKeyName(inboxDir, ch);
    if (access(kn.c_str(), F_OK) == 0) { g_alreadyOwned.fetch_add(1, std::memory_order_relaxed); return CAP_ALREADY_OWNED_P8; }
    long age; int hs = heartbeatStatus(hbPath, 224, &age); g_hbAge.store(age, std::memory_order_relaxed);
    if (hs == 2) { g_localCfgMismatch.fetch_add(1, std::memory_order_relaxed); return CAP_LOCAL_CFG; }
    if (hs != 0) { g_localNoWorker.fetch_add(1, std::memory_order_relaxed); return CAP_LOCAL_NOWORKER; }
    int pending = countInboxPending(inboxDir); g_pendingUnique.store(pending, std::memory_order_relaxed);
    if (pending >= 4) g_deferMode = false; else if (pending <= 2) g_deferMode = true;
    if (!g_deferMode) { g_localBackpressure.fetch_add(1, std::memory_order_relaxed); return CAP_LOCAL_BACKPRESSURE; }
    if (!writeChainSpecFile(kn, ch)) { g_localEnqueueFail.fetch_add(1, std::memory_order_relaxed); return CAP_FAILED; }
    g_deferOk.fetch_add(1, std::memory_order_relaxed);
    return CAP_CREATED;
}
static int replayChain(const std::string& chainPath, int cubeDepth, int workers,
                       const std::string& workDir, const std::string& manifestPath) {
    FILE* f = fopen(chainPath.c_str(), "rb");
    if (!f) { logf("CHAIN_FAIL open %s", chainPath.c_str()); return 2; }
    ChainSpec ch{}; bool ok = fread(&ch, sizeof ch, 1, f) == 1; fclose(f);
    if (!ok || ch.magic != 0x42574333) { logf("CHAIN_FAIL bad spec"); return 2; }
    if (ch.crc != fnv1a(&ch, sizeof ch - sizeof ch.crc)) { logf("CHAIN_FAIL crc"); return 2; }
    if (ch.r224.cfgHash != tailConfigHash()) { logf("CHAIN_FAIL cfgHash mismatch"); return 2; }
    mkdir(workDir.c_str(), 0755);
    std::string statePath = workDir + "/chain.state";
    std::string r224snap = workDir + "/r224.snap", r224jrnl = workDir + "/r224.journal";
    std::string r216snap = workDir + "/r216.snap", r216jrnl = workDir + "/r216.journal";
    char stage[32] = "BEFORE_R224"; int b224 = -1;
    readChainState(statePath, stage, &b224);
    logf("CHAIN_START stage=%s b224=%d", stage, b224);
    // ---- Frontière R224 (exhaustif) ----
    if (strcmp(stage, "BEFORE_R224") == 0) {
        if (!writeSnapshotFile(r224snap, ch.r224)) { logf("CHAIN_FAIL write r224 snap"); return 2; }
        P8bOutcome o224;
        replayP8b(r224snap, 1000000000ULL, cubeDepth, workers, r224jrnl, manifestPath, &o224, 0);
        if (o224.targetFound) { logf("CHAIN_HIT r224 466-candidate — VALIDER"); writeChainState(statePath, "TERMINAL", o224.bestCost); return 0; }
        if (o224.verdict != 0) { logf("CHAIN_INCOMPLETE r224 verdict=%d — reprise", o224.verdict); return 1; }
        b224 = o224.bestCost; writeChainState(statePath, "R224_DONE", b224); strcpy(stage, "R224_DONE");
    }
    // ---- Éligibilité r216 = condition INLINE exacte ----
    int curCost = ch.r224.initialBestCost < b224 ? ch.r224.initialBestCost : b224;
    if (curCost > TOTAL_BUDGET + ch.gap216) {
        logf("CHAIN_TERMINAL_R224 b224=%d curCost=%d > %d — r216 NON éligible (comme l'inline)", b224, curCost, TOTAL_BUDGET+ch.gap216);
        writeChainState(statePath, "TERMINAL", b224); return 1;
    }
    // ---- Frontière création r216 (atomique, AVANT possession) ----
    if (strcmp(stage, "R224_DONE") == 0) {
        TailSnapshot r216 = ch.r224;
        r216.rewindDepth = ch.rewind216; r216.initialBestCost = curCost;
        r216.breaksUsed = ch.breaksUsed216;   // Invariant 2 : breaksUsed à 215, PAS celui de r224 (223)
        r216.budgetOverride = TOTAL_BUDGET + ch.gap216;
        r216.crc = fnv1a(&r216, sizeof r216 - sizeof r216.crc);
        if (!writeSnapshotFile(r216snap, r216)) { logf("CHAIN_FAIL write r216 snap"); return 2; }
        writeChainState(statePath, "R216_CREATED", b224); strcpy(stage, "R216_CREATED");  // pas de fenêtre crash
    }
    // ---- Frontière sonde r216 (budget cumulé, re-queue jusqu'à EXHAUSTED/BUDGET_DONE/466) ----
    if (strcmp(stage, "R216_CREATED") == 0 || strcmp(stage, "R216_RUNNING") == 0) {
        P8bOutcome o216;
        // perCubeCap r216 = 25M : overshoot du budget borné à <= workers*25M, +granularité de tranches.
        replayP8b(r216snap, 25000000ULL, cubeDepth, workers, r216jrnl, manifestPath, &o216, ch.nodeCap216);
        logf("CHAIN_R216_SPENT %llu (budget %llu, bestCost %d)", (unsigned long long)o216.spentNodes,
             (unsigned long long)ch.nodeCap216, o216.bestCost);
        if (o216.targetFound) { logf("CHAIN_HIT r216 466-candidate — VALIDER"); writeChainState(statePath, "TERMINAL", b224); return 0; }
        // Codex 23:31 — TROIS fins distinctes (budget r216 = CUMULÉ 10Md, préservé across
        // kills par le pré-crédit du journal ; PAS de chaîne éternelle) :
        //  - EXHAUSTED (verdict 0)   -> TERMINAL, preuve réutilisable ;
        //  - CAPPED_TOTAL (verdict 2) = budget cumulé consommé -> BUDGET_DONE : fin VALIDE
        //    du workflow, libère la chaîne, JAMAIS une preuve .term EXHAUSTED ;
        //  - interruption (verdict 3, kill) -> R216_RUNNING, reprise (cumul préservé).
        if (o216.verdict == 0) {
            writeChainState(statePath, "TERMINAL", b224);
            logf("CHAIN_TERMINAL_R216 EXHAUSTED (r216 épuisé, pas de 466)");
        } else if (o216.verdict == 2) {
            writeChainState(statePath, "BUDGET_DONE", b224);
            logf("CHAIN_BUDGET_DONE bestCost=%d (budget r216 cumulé consommé, pas de 466, PAS de preuve)", o216.bestCost);
        } else {
            writeChainState(statePath, "R216_RUNNING", b224);   // interrompu -> reprise, cumul préservé
            logf("CHAIN_R216_SLICE verdict=%d — reprise (cumul préservé par le journal)", o216.verdict);
            return 2;
        }
    }
    return 1;
}

// --enum-3x3 : énumère TOUTES les racines 3x3 légales (parfaites, breaks=0) dans
// l'ordre de remplissage C[0..8]. Lit tab->base (trié par key), indépendant du jitter.
// Le clue en C[8] est imposé par T.lookup (table spéciale) => catalogue exact.
static uint64_t g_enum3x3Count = 0;
static void enum3x3rec(const Tables& T, RotatedPiece* board, bool* used,
                       const int* C, int si, FILE* out) {
    if (si == 9) {
        char line[192]; int off = 0; int hsc = 0;
        for (int k = 0; k < 9; k++) {
            const RotatedPiece& rp = board[C[k]];
            hsc += (int)rp.hsc;
            off += snprintf(line + off, sizeof line - off, "%s%d/%d",
                            k ? "," : "", rp.pieceNumber, rp.rot);
        }
        off += snprintf(line + off, sizeof line - off, " hsc=%d\n", hsc);
        fwrite(line, 1, off, out); g_enum3x3Count++;
        return;
    }
    int ci = C[si];
    const Table* tab = (si == 0) ? &T.corners : T.lookup[ci];
    int left   = (ci & 15) ? board[ci - 1].right : 0;
    int bottom = (ci >> 4) ? board[ci - 16].top  : 0;
    int key = (si == 0) ? 0 : left * NCOLORS + bottom;
    for (uint32_t i = tab->off[key]; i < tab->off[key + 1]; i++) {
        const RotatedPiece& c = tab->base[i].rp;
        if (c.breakCount != 0) continue;          // racine parfaite uniquement
        if (used[c.pieceNumber]) continue;
        board[ci] = c; used[c.pieceNumber] = true;
        enum3x3rec(T, board, used, C, si + 1, out);
        used[c.pieceNumber] = false; board[ci].pieceNumber = 0;
    }
}

// Phase-2 : capture atomique 1x/attempt au 1er depth 240 (signature bassin/préfixe).
// board indexé bu-cell ; C[f] = cellule du fill index f. Coutures cassées = seams
// frustrées parmi les cellules posées (id = ci*2+0 nord, ci*2+1 est).
static void writeCanaryCapture(const std::string& dir, const std::string& arm,
        const RotatedPiece* board, int si, int breaksUsed,
        uint64_t attemptSeed, int threadId, uint64_t fcurRoot) {
    int C[256]; for (int f = 0; f < 256; f++) C[f] = SEQ_ROW[f] * 16 + SEQ_COL[f];
    auto prefHash = [&](int n) {
        uint32_t buf[256];
        for (int f = 0; f < n; f++) { const RotatedPiece& rp = board[C[f]];
            buf[f] = ((uint32_t)rp.pieceNumber << 8) | rp.rot; }
        return fnv1a(buf, (size_t)n * 4);
    };
    uint64_t h224 = prefHash(224), h240 = prefHash(240);
    char rootID[176]; { int off = 0; for (int k = 0; k < 9; k++) { const RotatedPiece& rp = board[C[k]];
        off += snprintf(rootID + off, sizeof rootID - off, "%s%d/%d", k ? "," : "", rp.pieceNumber, rp.rot); } }
    // coutures frustrées parmi les cellules posées (est + nord, chaque seam 1x)
    std::string broken; int nbrk = 0;
    for (int f = 0; f < si; f++) {
        int ci = C[f]; const RotatedPiece& rp = board[ci];
        if ((ci & 15) < 15 && board[ci + 1].pieceNumber) {   // seam est
            int nb = sideAfterRot(PIECES[board[ci + 1].pieceNumber], board[ci + 1].rot, 3);
            if (rp.right != nb) { broken += (nbrk++ ? "," : "") + std::to_string(ci * 2 + 1); }
        }
        if ((ci >> 4) < 15 && board[ci + 16].pieceNumber) {  // seam nord
            int nb = sideAfterRot(PIECES[board[ci + 16].pieceNumber], board[ci + 16].rot, 2);
            if (rp.top != nb) { broken += (nbrk++ ? "," : "") + std::to_string(ci * 2 + 0); }
        }
    }
    char tmp[600], path[600];
    snprintf(tmp, sizeof tmp, "%s/.tmp_%s_%llu_%d", dir.c_str(), arm.c_str(),
             (unsigned long long)attemptSeed, threadId);
    FILE* f = fopen(tmp, "w"); if (!f) return;
    fprintf(f, "CANARY_CAP v1\narm %s\nrootID %s\nfcurRoot %lld\nattemptSeed %llu\n"
               "depth %d\nbreaksUsed %d\nhash224 %llx\nhash240 %llx\nnbroken %d\n",
            arm.c_str(), rootID, (long long)(fcurRoot == UINT64_MAX ? -1 : (long long)fcurRoot),
            (unsigned long long)attemptSeed, si, breaksUsed,
            (unsigned long long)h224, (unsigned long long)h240, nbrk);
    fprintf(f, "board");
    for (int f2 = 0; f2 < si; f2++) { const RotatedPiece& rp = board[C[f2]];
        fprintf(f, " %d/%d", rp.pieceNumber, rp.rot); }
    fprintf(f, "\nbroken %s\n", broken.c_str());
    fclose(f);
    snprintf(path, sizeof path, "%s/cap_%s_%llu.txt", dir.c_str(), arm.c_str(),
             (unsigned long long)attemptSeed);
    rename(tmp, path);
}

// canary7 : harvest d'un board complet score>=463 (incumbent exporté). verifyBoard
// confirme le score, dédup par empreinte (DFP), sauve en td-row-major re-vérifiable.
static std::mutex g_harvestMtx;
// Identité CANONIQUE = SHA256(board) (Codex : content-addressing SHA256, pas FNV64).
// g_harvestSeen = ensemble des sha256 COMMITÉS DURABLEMENT (rempli seulement après fsync+link).
static std::unordered_set<std::string> g_harvestSeen;
static std::atomic<int> g_harvestCount{0};
static std::atomic<int> g_harvestAttempt{0};   // n° d'appel (pour l'injection de panne synthétique)

// Injection de panne (test only) : cfg.harvestFault = "STAGE:N" fait échouer l'appel n°N à
// l'étape STAGE (open|write|fsync|rename). Prouve exactly-once sans attendre un hit 463 réel.
static bool harvestFaultHit(const char* stage, int attemptNo);

// Relit un fichier harvest, reconstruit le board (les 256 DERNIERS tokens `pn/rot` = le board,
// l'entête étant avant), recalcule score + SHA256. Retourne true seulement si score>=463 ET
// (si wantSha fourni) sha == wantSha. Un fichier tronqué/corrompu -> false (Codex #1/#2).
static bool harvestVerifyFile(const std::string& path, const char* wantSha,
                              int* outScore, char shaOut[65]) {
    FILE* f = fopen(path.c_str(), "r"); if (!f) return false;
    std::vector<std::pair<int,int>> toks; char word[128];
    while (fscanf(f, "%127s", word) == 1) {
        int a, b; if (sscanf(word, "%d/%d", &a, &b) == 2) toks.push_back({a, b});
    }
    fclose(f);
    if (toks.size() < 256) return false;                     // tronqué
    size_t off = toks.size() - 256;
    RotatedPiece board[256]; memset(board, 0, sizeof board);
    for (int tdr = 0; tdr < 16; tdr++) { int bur = 15 - tdr;
        for (int c = 0; c < 16; c++) {
            auto& t = toks[off + tdr * 16 + c];
            if (t.first < 0 || t.first > 256 || t.second < 0 || t.second > 3) return false;
            RotatedPiece rp{}; rp.pieceNumber = (uint16_t)t.first; rp.rot = (uint8_t)t.second;
            const Piece& p = PIECES[t.first];
            rp.top = sideAfterRot(p, t.second, 0); rp.right = sideAfterRot(p, t.second, 1);
            board[bur * 16 + c] = rp;
        } }
    int v = verifyBoard(board);
    uint32_t buf[256]; for (int i = 0; i < 256; i++) buf[i] = ((uint32_t)board[i].pieceNumber << 8) | board[i].rot;
    char sha[65]; sha256_hex(buf, sizeof buf, sha);
    if (outScore) *outScore = v;
    if (shaOut) memcpy(shaOut, sha, 65);
    if (v < 463) return false;
    if (wantSha && strncmp(sha, wantSha, 64) != 0) return false;
    return true;
}

// Déplace un fichier corrompu en quarantaine (jamais supprimé silencieusement, jamais dans seen).
static void harvestQuarantine(const std::string& dir, const std::string& fname) {
    std::string q = dir + "/quarantine";
    mkdir(q.c_str(), 0755);
    std::string from = dir + "/" + fname, to = q + "/" + fname;
    if (rename(from.c_str(), to.c_str()) != 0) unlink(from.c_str());
    logf("HARVEST463 QUARANTAINE fichier corrompu/incohérent : %s", fname.c_str());
}

// Réconciliation au boot : pour chaque fichier final, RELIT + REVALIDE le contenu (score + SHA
// recalculé == SHA du nom) avant d'insérer dans seen ; corrompu -> quarantaine. Nettoie les
// .tmp_* orphelins. Protège la dédup inter-restart contre un fichier tronqué (Codex #1).
static void reconcileHarvestDir(const std::string& dir) {
    DIR* d = opendir(dir.c_str());
    if (!d) return;
    std::vector<std::string> finals, tmps;
    struct dirent* e;
    while ((e = readdir(d))) {
        const char* nm = e->d_name; size_t L = strlen(nm);
        if (L >= 5 && strncmp(nm, ".tmp_", 5) == 0) { tmps.push_back(nm); continue; }
        if (L < 69 || strcmp(nm + L - 4, ".txt") != 0 || nm[0] == '.') continue;
        const char* p = nm + L - 4 - 64;                     // sha = 64 hex juste avant .txt
        if (p <= nm || p[-1] != '_') continue;
        bool hex = true; for (int i = 0; i < 64; i++) if (!isxdigit((unsigned char)p[i])) { hex = false; break; }
        if (hex) finals.push_back(nm);
    }
    closedir(d);
    size_t loaded = 0, cleaned = 0, quar = 0;
    for (const std::string& nm : tmps) { if (unlink((dir + "/" + nm).c_str()) == 0) cleaned++; }
    for (const std::string& nm : finals) {
        char want[65]; memcpy(want, nm.c_str() + nm.size() - 68, 64); want[64] = 0;
        char sha[65]; int v;
        if (harvestVerifyFile(dir + "/" + nm, want, &v, sha)) {   // contenu revalidé + SHA recalculé
            std::lock_guard<std::mutex> lk(g_harvestMtx); g_harvestSeen.insert(std::string(want)); loaded++;
        } else { harvestQuarantine(dir, nm); quar++; }           // corrompu -> quarantaine, PAS dans seen
    }
    if (loaded || cleaned || quar)
        logf("HARVEST463 reconcile : %zu boards revalidés, %zu tmp orphelins nettoyés, %zu quarantaine",
             loaded, cleaned, quar);
}

static void saveHarvest463(const std::string& dir, const RotatedPiece* board, int claimedScore,
                           const char* rootID, uint64_t attemptSeed, uint64_t cidx, uint64_t jidx, int rewind) {
    int v = verifyBoard(board);
    if (v != claimedScore || v < 463) return;   // garde : score annoncé == verifyBoard, >=463
    std::vector<uint32_t> buf(256);
    for (int i = 0; i < 256; i++) buf[i] = ((uint32_t)board[i].pieceNumber << 8) | board[i].rot;
    char sha[65]; sha256_hex(buf.data(), 256 * sizeof(uint32_t), sha);
    std::string id(sha);
    // Déjà committé durablement (ce run OU réconcilié au boot) -> vrai doublon, skip.
    { std::lock_guard<std::mutex> lk(g_harvestMtx); if (g_harvestSeen.count(id)) return; }

    int attemptNo = g_harvestAttempt.fetch_add(1) + 1;
    uint64_t nroots = g_forceRoots.empty() ? 1 : g_forceRoots.size();
    uint64_t globalTicket = jidx * nroots + cidx;
    // Nom CANONIQUE indépendant du compteur (Codex #3) : s<score>_<sha>.txt. Deux process
    // produisant le même board -> MÊME chemin -> link()/EEXIST idempotent, jamais 2 fichiers.
    char path[720], tmp[780];
    snprintf(path, sizeof path, "%s/s%d_%s.txt", dir.c_str(), v, sha);
    snprintf(tmp, sizeof tmp, "%s/.tmp_%s.%d.%d", dir.c_str(), sha, (int)getpid(), attemptNo);

    // 1) open O_EXCL (temp unique). Panne "open" = rien écrit, rien réservé -> retry OK.
    if (harvestFaultHit("open", attemptNo)) return;
    int fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0644);
    if (fd < 0) return;
    FILE* f = fdopen(fd, "w"); if (!f) { close(fd); unlink(tmp); return; }

    // 2) write (retours vérifiés) — provenance complète epoch/shard/globalTicket/cidx/jidx.
    bool ok = fprintf(f, "SCORE %d\nSHA256 %s\nCHKFNV %016llx\nROOT %s\nSEED %llu\n"
                         "EPOCH %s\nSHARD %d/%d\nGLOBALTICKET %llu\nCIDX %llu\nJIDX %llu\nREWIND %d\n",
            v, sha, (unsigned long long)fnv1a(buf.data(), 256 * sizeof(uint32_t)), rootID,
            (unsigned long long)attemptSeed, cfg.campaignEpoch.c_str(), cfg.shardIndex, cfg.shardCount,
            (unsigned long long)globalTicket, (unsigned long long)cidx, (unsigned long long)jidx, rewind) > 0;
    for (int tdr = 0; ok && tdr < 16; tdr++) {   // td-row-major, re-lisible par --verify-board
        int bur = 15 - tdr;
        for (int c = 0; c < 16; c++) { const RotatedPiece& rp = board[bur * 16 + c];
            if (fprintf(f, "%s%d/%d", c ? " " : "", rp.pieceNumber, rp.rot) < 0) { ok = false; break; } }
        if (ok && fprintf(f, "\n") < 0) ok = false;
    }
    if (harvestFaultHit("write", attemptNo)) ok = false;
    // 3) flush + fsync + close, tous vérifiés (contenu complet sur disque avant publication).
    if (ok && fflush(f) != 0) ok = false;
    if (ok && harvestFaultHit("fsync", attemptNo)) ok = false;
    if (ok && fsync(fileno(f)) != 0) ok = false;
    if (fclose(f) != 0) ok = false;              // fclose TOUJOURS appelé
    if (!ok) { unlink(tmp); return; }            // rien de committé -> board NON marqué vu -> retry possible

    // 4) publication ATOMIQUE SANS écrasement : link() échoue EEXIST si dest existe.
    if (harvestFaultHit("rename", attemptNo)) { unlink(tmp); return; }
    if (link(tmp, path) != 0) {
        if (errno != EEXIST) { unlink(tmp); return; }
        // EEXIST : la dest existe déjà -> VALIDER qu'elle est un fichier complet du MÊME sha
        // (Codex #2). Si corrompue, la mettre en quarantaine et RÉPARER avec notre temp valide.
        std::string fname = std::string("s") + std::to_string(v) + "_" + sha + ".txt";
        if (harvestVerifyFile(path, sha, nullptr, nullptr)) {
            unlink(tmp);                         // dest valide identique -> idempotent
        } else {
            harvestQuarantine(dir, fname);       // dest corrompue -> quarantaine
            if (link(tmp, path) != 0) { unlink(tmp); return; }  // répare avec notre bon temp
            unlink(tmp);
        }
    } else {
        unlink(tmp);
    }
    // durabilité de l'entrée de répertoire (RC vérifié) ; échec -> NON annoncé committé.
    int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY);
    if (dfd < 0) return;
    if (fsync(dfd) != 0) { close(dfd); return; }
    close(dfd);

    // 5) SEULEMENT après commit durable prouvé : marque vu + incrémente idx cosmétique.
    { std::lock_guard<std::mutex> lk(g_harvestMtx); g_harvestSeen.insert(id); }
    g_harvestCount.fetch_add(1);
    logf("HARVEST463 score=%d sha=%.12s gticket=%llu epoch=%s (distincts %zu) root=%s", v, sha,
         (unsigned long long)globalTicket, cfg.campaignEpoch.c_str(), g_harvestSeen.size(), rootID);
    wasmPublishCheckpoint();
}

static bool harvestFaultHit(const char* stage, int attemptNo) {
    if (cfg.harvestFault.empty()) return false;
    size_t pos = cfg.harvestFault.find(':');
    if (pos == std::string::npos) return false;
    return cfg.harvestFault.compare(0, pos, stage) == 0
        && atoi(cfg.harvestFault.c_str() + pos + 1) == attemptNo;
}

#ifdef BW_HOTMAIN
// HOT_MAIN_CORPUS_V1 (Codex 2026-08-11) : capture de VRAIS états du DFS PRINCIPAL de bw.cpp aux profondeurs
// cibles + taille de sous-arbre réel (compteur `nodes` delta ; CENSORED si l'attempt se termine avant le
// retour naturel sous la profondeur). Échantillonnage déterministe par hash (board-prefix,si). Aucune I/O
// dans la hot loop (buffer mémoire). Build isolé compile-out ; producteurs (binaires déjà buildés) intacts.
#include <vector>
struct HotMainSnap {
    uint16_t piece[256]; uint8_t rot[256];
    int depth, spent; uint32_t sigmaOdd;
    uint64_t nodes_start, subtree; int censored;
};
static std::vector<HotMainSnap> g_hmSnaps;
static bool g_hmOn = false;
static int g_hmSlotAtDepth[257];              // slot du snapshot capturé à chaque profondeur (-1 = aucun)
static bool g_hmTarget[257] = {};
static long g_hmStride = 1; static size_t g_hmPerStratum = 25;
static uint64_t g_hmStratCount[257][40] = {}; // (depth, slack) reservoir counters
static std::string g_hmOut;
static inline uint64_t g_hmHash(const void* board, int si) {
    uint64_t h = 1469598103934665603ULL; const uint8_t* b = (const uint8_t*)board;
    for (int i = 0; i < si; i++) { h ^= b[i * sizeof(RotatedPiece)]; h *= 1099511628211ULL;
        h ^= b[i * sizeof(RotatedPiece) + 2]; h *= 1099511628211ULL; }   // pieceNumber(2o)+rot approx
    h ^= (uint64_t)si * 0x9e3779b97f4a7c15ULL; return h;
}
static void hotMainDumpCorpus() {
    // tileset g_face (convention solveur) pour l'oracle offline
    { std::string tp = g_hmOut + ".tiles"; FILE* tf = fopen(tp.c_str(), "w");
      if (tf) { for (int p = 1; p <= 256; p++) for (int rot = 0; rot < 4; rot++)
            fprintf(tf, "%d %d %d %d %d %d\n", p, rot, (int)g_face[p][rot][0], (int)g_face[p][rot][1], (int)g_face[p][rot][2], (int)g_face[p][rot][3]);
        fclose(tf); } }
    FILE* cf = fopen(g_hmOut.c_str(), "w");
    if (!cf) { logf("HOTMAIN_FAIL open %s", g_hmOut.c_str()); return; }
    fprintf(cf, "# HOT_MAIN_CORPUS_V1 snaps=%zu TOTAL_BUDGET=%d\n", g_hmSnaps.size(), TOTAL_BUDGET);
    for (const HotMainSnap& s : g_hmSnaps) {
        int slack = TOTAL_BUDGET - s.spent;
        int lbsig = (__builtin_popcount(s.sigmaOdd) + 1) / 2;   // LBσ = ceil(popcount(oddMask)/2)
        // bestCost=TOTAL_BUDGET+1 -> "running+LB >= bestCost" == "spent+LB > TOTAL_BUDGET" (sémantique main)
        fprintf(cf, "SNAP depth=%d running=%d bestCost=%d lbsig=%d slack=%d sigmaOdd=%u subtree=%llu censored=%d\n",
                s.depth, s.spent, TOTAL_BUDGET + 1, lbsig, slack, s.sigmaOdd, (unsigned long long)s.subtree, s.censored);
        fprintf(cf, "BOARD");
        for (int i = 0; i < 256; i++) { if (s.piece[i] == 0) fprintf(cf, " 0/0"); else fprintf(cf, " %d/%d", (int)s.piece[i], (int)s.rot[i]); }
        fprintf(cf, "\n");
    }
    fclose(cf);
    logf("HOTMAIN_DONE wrote %zu snapshots -> %s", g_hmSnaps.size(), g_hmOut.c_str());
    for (int d = 0; d <= 256; d++) { uint64_t tot = 0; for (int k = 0; k < 40; k++) tot += g_hmStratCount[d][k]; if (tot) logf("  depth %d: %llu snaps", d, (unsigned long long)tot); }
}
#endif

static void solverThread(int threadId) {
#ifdef BW_HOTMAIN
    for (int d = 0; d <= 256; d++) g_hmSlotAtDepth[d] = -1;
#endif
#ifdef BW_COMPILED_TAIL_DEPTH
    static constexpr int HOT_TAIL_DEPTH = BW_COMPILED_TAIL_DEPTH;
#else
    const int HOT_TAIL_DEPTH = cfg.tailDepth;
#endif
    Tables T;
    buildTables(T);
    FILE* poolF = nullptr;                 // pool telemetry sink (per thread)
    std::string poolBuf;
    FILE* tkF = nullptr;                    // --ticket-log : sink binaire par thread (sans mutex)
    std::string tkBuf;                      // buffer 40o/record, flush par blocs 16KB + temporel
    auto tkLastFlush = std::chrono::steady_clock::now();   // flush temporel (borne la perte sur crash)
    // arme SEULEMENT si le manifeste a ete cree completement (g_tkArmed)
    bool tkFail = (!cfg.ticketLogDir.empty() && !g_tkArmed);
    char tkPath[600] = {0};
    if (!cfg.ticketLogDir.empty())
        snprintf(tkPath, sizeof tkPath, "%s/seg_%016llx.t%d.bin",
                 cfg.ticketLogDir.c_str(), (unsigned long long)g_tkRunId, threadId);
    auto tkFlush = [&]() {                   // write_all + fflush verifie ; fail-stop sur toute erreur
        if (tkFail || tkBuf.empty()) return;
        if (!tkF) {                          // O_CREAT|O_EXCL : le .bin ne doit PAS exister (collision run-id -> fail-stop)
            int fd = open(tkPath, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0644);
            if (fd < 0) { tkFail = true; logf("TICKET_LOG open FAIL t%d (%s) -> journal off", threadId, tkPath); return; }
            tkF = fdopen(fd, "wb");
            if (!tkF) { close(fd); tkFail = true; logf("TICKET_LOG fdopen FAIL t%d -> journal off", threadId); return; }
        }
        size_t off = 0, N = tkBuf.size();
        while (off < N) {
            size_t w = fwrite(tkBuf.data() + off, 1, N - off, tkF);
            if (w == 0) {                    // ne PAS corrompre : ne garder que le non-confirme, fail-stop
                if (off) tkBuf.erase(0, off);
                tkFail = true; logf("TICKET_LOG write FAIL t%d (%zu confirmes) -> journal off", threadId, off);
                return;
            }
            off += w;
        }
        if (fflush(tkF) != 0 || ferror(tkF)) {   // ex. disque plein : buffer NON confirme -> fail-stop (segment incomplet)
            tkFail = true; logf("TICKET_LOG fflush FAIL t%d -> journal off (integrite non garantie)", threadId);
            return;
        }
        tkBuf.clear(); tkLastFlush = std::chrono::steady_clock::now();
    };
    FILE* dumpF = nullptr;                  // --dump-first3x3 : sink par thread
    std::string dumpBuf;
    FILE* tourF = nullptr;                   // --tourney : sink par thread
    int tourSyncCtr = 0;                      // compteur pour fdatasync batché (DONE-durable)
#ifdef BW_CAND_INSTRUMENT
    uint64_t tl_scan[6] = {0}, tl_rej[6] = {0};   // P14-B : scan/reject par bucket (thread-local)
#endif
#ifdef BW_CHOICE_FP
    uint64_t tl_choiceFP = 1469598103934665603ULL, tl_choiceCount = 0;   // P14-B gate fingerprint
#endif
    std::string tourBuf;
    ThreadStats& st = g_stats[threadId];
    auto tStart = std::chrono::steady_clock::now();

    // Reprise (shadow #3) : lastCompleted persisté ; currentAttempt = lastCompleted+1.
    // On ne publie lastCompleted qu'à la FIN SÉMANTIQUE de l'attempt (voir bas de boucle),
    // jamais avant : un checkpoint/SIGTERM au milieu ne doit PAS faire sauter l'attempt.
    // dump3x3 : rejoue les attempts DÉJÀ terminés [1..attMax] (au lieu de resume+1..∞).
    uint64_t attMax = (threadId >= 0 && threadId < MAX_ATT_THREADS) ? g_attemptResume[threadId] : 0;
    uint64_t attempt = cfg.dump3x3 ? 0 : attMax;
    int fr[9][2] = {};                            // canary : racine 3x3 forcée courante
    uint64_t fcurRoot = UINT64_MAX, fjleft = 0;   // dispenser + jitters restants
    uint64_t curGlobalTicket = UINT64_MAX;        // --ticket-log : ticket global du dispenser (mode interleave)
    uint64_t no3x3 = 0;                            // garde 1 : attempts sans 3x3 (tree_exhausted_before9)
    while (!g_stop.load(std::memory_order_relaxed)) {
        attempt++;   // currentAttempt = lastCompleted + 1
        if (cfg.dump3x3 && !cfg.forceRoot && attempt > attMax) break;   // plage historique épuisée (rétro pur)
        if (cfg.forceRoot) {   // pull une racine du dispenser
            if (cfg.forceInterleave) {
                // round-robin : ticket -> (cidx=racine, jidx=tour). TOUTES les racines
                // reçoivent le tour j avant qu'aucune ne reçoive j+1 -> couverture large
                // immédiate des 1047 racines (fix Codex : évite la monopolisation par thread).
                // P13 sharding : ticket LOCAL -> ticket GLOBAL = shardIndex + shardCount*local.
                // Chaque worker traite un sous-ensemble disjoint ; union = suite complète ;
                // seed dérivée du (cidx,jidx) GLOBAL -> résultat par ticket identique au non-shardé.
                uint64_t nroots = g_forceRoots.size();
                // ticket global = offset_round*nroots + shardIndex + shardCount*local.
                // L'offset saute les rounds 0..J0-1 déjà faits en local -> le Cloud ne les refait PAS.
                // + skip-ledger : saute EN PLUS tout ticket déjà terminé en local (exclusion exacte).
                uint64_t ticket, jidx;
                bool exhausted = false;
                for (;;) {
                    uint64_t localTicket = g_forceNext.fetch_add(1, std::memory_order_relaxed);
                    ticket = (uint64_t)cfg.forceJitterStart * nroots
                           + (uint64_t)cfg.shardIndex + (uint64_t)cfg.shardCount * localTicket;
                    jidx = ticket / nroots;
                    if (jidx >= cfg.forceJitters) { exhausted = true; break; }  // catalogue épuisé
                    // --root-allow : saute les cidx hors allowlist SANS toucher nroots/ticket/seed
                    // (le cidx = ticket%nroots reste l'index racine d'origine -> identité bijective).
                    if (!g_rootAllow.empty()
                        && g_rootAllow.find((uint32_t)(ticket % nroots)) == g_rootAllow.end()) {
                        g_rootAllowSkips.fetch_add(1, std::memory_order_relaxed);
                        continue;                              // racine non autorisée -> ticket suivant
                    }
                    if (g_skipLedger.empty() || g_skipLedger.find(ticket) == g_skipLedger.end())
                        break;                                 // ticket neuf -> on le traite
                    g_skipLedgerHits.fetch_add(1, std::memory_order_relaxed);   // déjà fait -> skip
                }
                if (exhausted) break;
                fcurRoot = ticket % nroots;
                fjleft = jidx;                                 // ici fjleft porte le n° de tour (seed/log)
                curGlobalTicket = ticket;                      // --ticket-log : ticket global exact
                const ForceRoot& R = g_forceRoots[fcurRoot];
                for (int k = 0; k < 9; k++) { fr[k][0] = R.p[k]; fr[k][1] = R.r[k]; }
            } else {           // mode batch historique : forceJitters attempts d'affilée par racine
                if (fjleft == 0) {
                    bool got = false;                          // --root-allow : saute les racines hors-liste
                    while (true) {
                        fcurRoot = g_forceNext.fetch_add(1, std::memory_order_relaxed);
                        if (fcurRoot >= g_forceRoots.size()) break;   // catalogue forcé épuisé
                        if (g_rootAllow.empty()
                            || g_rootAllow.find((uint32_t)fcurRoot) != g_rootAllow.end()) { got = true; break; }
                        g_rootAllowSkips.fetch_add(1, std::memory_order_relaxed);
                    }
                    if (!got) break;                           // épuisé -> sort de la boucle principale
                    const ForceRoot& R = g_forceRoots[fcurRoot];
                    for (int k = 0; k < 9; k++) { fr[k][0] = R.p[k]; fr[k][1] = R.r[k]; }
                    fjleft = cfg.forceJitters;
                }
                fjleft--;
            }
        }
        // force : seed INDÉPENDANT du thread (fcurRoot=index dispenser unique, fjleft) →
        // attribution stable + reproductibilité 1/24 threads (Codex).
        uint64_t attemptSeed = cfg.forceRoot
            ? (0x9E3779B97F4A7C15ULL * (fcurRoot + 1) + 0xD1B54A32D192ED03ULL * (fjleft + 1))
            : cfg.seed * 1000000007ULL + (uint64_t)threadId * 1000003ULL + attempt;
        Rng rng(attemptSeed);
        for (auto* t : {&T.corners, &T.leftSides, &T.topSides, &T.rightNoBrk,
                        &T.rightBrk, &T.midNoBrk, &T.midBrk})
            sortTableForRestart(*t, rng);
        sortBottomRowForRestart(T.bottomSides, rng);
        if (cfg.ringDepth) {
            for (auto* t : {&T.cornersRing, &T.leftSidesRing, &T.topSidesRing,
                            &T.rightBrkRing})
                sortTableForRestart(*t, rng);
            sortBottomRowForRestart(T.bottomSidesRing, rng);
        }
        for (auto& sp : T.special) sortTableForRestart(sp, rng);

        if (g_eliteOrderOn || g_eliteRefMode) {   // P-ELITE : scores leave-root-out (par ROOT) + invalidation vues (par attempt)
            uint16_t exP[9]; uint8_t exR[9]; uint64_t cornerH = 1469598103934665603ULL;
            for (int i = 0; i < 9; i++) { exP[i] = (uint16_t)fr[i][0]; exR[i] = (uint8_t)fr[i][1];
                cornerH = (cornerH ^ (((uint64_t)fr[i][0] << 3) ^ (uint64_t)fr[i][1])) * 1099511628211ULL; }
            static thread_local uint64_t lastCornerH = 0; static thread_local bool haveScores = false;
            if (!haveScores || cornerH != lastCornerH) { computeEliteScores(exP, exR); lastCornerH = cornerH; haveScores = true; }
            g_eliteEpoch++;                // nouvelle attempt -> vues reconstruites lazy avec ce attemptSeed
            g_eliteAttemptSeed = attemptSeed;
        }

        // ---- one restart attempt -----------------------------------------
        RotatedPiece board[256] = {};
        bool used[257] = {false};
        uint8_t cumBreaks[256] = {0};
        uint8_t cumHeur[256] = {0};
        uint16_t tryNext[256] = {0};
#ifdef BW_SIGMA_LEDGER
        // LBσ : multigraphe des couleurs des breaks fermés. oddMask bit c = couleur c a un
        // degré IMPAIR. Chaque break INTERNE (a,b) fait oddMask ^= (1<<a)^(1<<b) (a,b non-nuls).
        // sigmaDelta[si] = delta XOR appliqué à la profondeur si (annulé au backtrack).
        uint32_t sigmaOdd = 0;
        uint32_t sigmaDelta[256] = {0};
        // sigma-MAIN : ne calcule/maintient la parité dans le DFS large QUE si main-cut ou shadow demandé.
        // Sinon sDelta reste 0 -> maintien sigmaOdd = no-op -> coût sigma NUL dans le climb (tail inchangé).
        const bool sigMainAct = (cfg.sigmaMain || cfg.sigmaMainShadow);
#endif

        // supply/demand state (--sd-prune): S[c] = edges of color c on unplaced
        // pieces; D[c] = edges of color c exposed by placed cells toward empty
        // in-board neighbors. Necessary condition for completability: S >= D.
        int16_t S[NCOLORS] = {0}, D[NCOLORS] = {0};
        // side color of a placed cell facing a given direction (0=N 1=E 2=S 3=W)
        auto faceColor = [&](const RotatedPiece& rp, int face) -> int {
            if (face == 0) return rp.top;
            if (face == 1) return rp.right;
            return sideAfterRot(PIECES[rp.pieceNumber], rp.rot, face);
        };
        // apply placement/removal effects on S/D. dir: +1 place, -1 remove.
        auto sdApply = [&](int ci, const RotatedPiece& rp, int dir) {
            const Piece& p = PIECES[rp.pieceNumber];
            S[p.n] -= dir; S[p.e] -= dir; S[p.s] -= dir; S[p.w] -= dir;
            const int r = ci >> 4, c = ci & 15;
            const int nb[4] = { r < 15 ? ci + 16 : -1, c < 15 ? ci + 1 : -1,
                                r > 0 ? ci - 16 : -1, c > 0 ? ci - 1 : -1 };
            for (int f = 0; f < 4; f++) {   // f: my face N,E,S,W toward nb[f]
                if (nb[f] < 0) continue;    // frame side: no demand
                const RotatedPiece& o = board[nb[f]];
                if (o.pieceNumber) D[faceColor(o, (f + 2) & 3)] -= dir; // seam closed/reopened
                else D[faceColor(rp, f)] += dir;                       // exposed/unexposed
            }
        };
        auto sdViolated = [&]() {
            for (int c2 = 1; c2 < NCOLORS; c2++)
                if (D[c2] > S[c2]) return true;
            return false;
        };

        // seed cell 0 = bu(0,0): random corner showing grey west+south
        {
            uint32_t a = T.corners.off[0], b = T.corners.off[0 + 1];
            if (b <= a) die("no corner candidates for cell 0");
            uint32_t pick = a + rng.below(b - a);   // consomme le rng comme baseline (comparabilité A/B)
            if (cfg.forceRoot) {                     // impose le coin fr[0]
                for (uint32_t z = a; z < b; z++) {
#ifdef BW_PACKED_POOL32
                    RotatedPiece cz = unpackRP(T.corners.pool[z]);
#else
                    const RotatedPiece& cz = T.corners.pool[z];
#endif
                    if (cz.pieceNumber == fr[0][0] && cz.rot == fr[0][1]) { pick = z; break; }
                }
            }
#ifdef BW_PACKED_POOL32
            RotatedPiece c0 = unpackRP(T.corners.pool[pick]);
#else
            const RotatedPiece& c0 = T.corners.pool[pick];
#endif
            board[0] = c0;
            used[c0.pieceNumber] = true;
            cumBreaks[0] = 0;
            cumHeur[0] = c0.hsc;
            if (cfg.sdPrune || cfg.budgetLB) {   // P12 : S/D maintenu aussi pour budget-LB
                for (int p = 1; p <= 256; p++) {
                    if (p == c0.pieceNumber) continue;
                    S[PIECES[p].n]++; S[PIECES[p].e]++; S[PIECES[p].s]++; S[PIECES[p].w]++;
                }
                D[faceColor(c0, 0)]++;      // exposes north toward bu(1,0)
                D[faceColor(c0, 1)]++;      // exposes east toward bu(0,1)
            }
        }

        int si = 1, maxSi = 1;
        bool rec3x3 = false;    // dump3x3 : ce attempt a-t-il émis une racine ?
        uint64_t nodesAt240 = 0;  // tournoi : nœuds au 1er franchissement depth 240
        int breaks240 = -1;       // breaksUsed à depth 240 (slack)
        // canary5 : qualité EXACTE du tail par attempt (endgame244 + rungs). La vraie
        // variable discriminante (maxSi=243 est un artefact ; 244 EST atteint).
        int bestTailCost = 9999, bestTailRewind = -1, bestTailProven = 0;
        int spentAtBest = -1, ringMisAtBest = -1, endgame244Calls = 0;
        uint64_t exactTailNodes = 0;
        int countGap[6] = {0, 0, 0, 0, 0, 0};
        int rungCalls[8] = {0};   // canary5b : appels par rung (Codex : prouve l'entrée r230/r224 indép. du coût)
        int deepestRewind = 999;  // plus petit rewind réellement entré
        bool gap3cap = false;     // canary6 : board 244 déjà capturé pour un événement gap<=3 ?
        RotatedPiece incBuf[256]; int incScore = -1;   // canary7 : incumbent 463 exporté
        uint64_t deepCrc = 0;   // P5a : crc de la frontière la plus profonde de cette tentative
        auto tkAttStart = std::chrono::steady_clock::now();   // --ticket-log : duree par attempt
        uint64_t nodes = 0;
        uint64_t placements = 0, lastFlushedPlacements = 0;
        uint64_t placeHist[256] = {}, lastFlushedPlaceHist[256] = {};  // pièces posées par case (heatmap)
        uint64_t nodesAtDepthCheck = 0;
        bool snapped = false;              // pool telemetry: mask at depth 176
        uint8_t snapMask[32];
        uint8_t brokenAt[256] = {0};       // --isolated-breaks: incident broken seams
        int16_t brokeNbAt[256];            // per-depth: other cell of the broken seam
        if (cfg.isolatedBreaks) memset(brokeNbAt, 0xFF, sizeof brokeNbAt); // -1
        bool tailCalled = false;
        uint64_t nextTailAt = 0;
        // deepest cell index reached while holding each cumulative spend
        uint16_t depthAtSpend[32] = {0};
        uint64_t attemptArrivals = 0;   // exact-endgame calls this attempt made
        uint64_t endgameSeq = 0;        // call counter driving --endgame-sample
        uint64_t attemptCap = cfg.yieldBase ? cfg.yieldBase : cfg.nodeCap;
#ifdef BW_BLOCK_MASK
        // P14-B : remainingMask = ~used[] (bit p-1 = pièce p disponible). Init depuis used[] ici
        // (après placements initiaux), puis maintenu à chaque commit/uncommit de la hot loop.
        uint64_t remainingMask[4] = {0, 0, 0, 0};
        for (int p = 1; p <= 256; p++)
            if (!used[p]) remainingMask[(p - 1) >> 6] |= (1ULL << ((p - 1) & 63));
#endif

        while (true) {
            nodes++;
            if (__builtin_expect(cfg.dump3x3, false) && si == 9) {
                // premier 3x3 complet (fill 0..8 = bu {0,1,2,16,17,18,32,33,34}).
                // Invariant live placehist[d8]==restarts : jamais de remontée au-dessus -> 1er == LE 3x3.
                static const int C9[9] = {0, 1, 2, 16, 17, 18, 32, 33, 34};
                char line[160];
                int off = snprintf(line, sizeof line, "%" PRIu64 " ", attempt);
                for (int k = 0; k < 9; k++) {
                    const RotatedPiece& rp = board[C9[k]];
                    off += snprintf(line + off, sizeof line - off, "%s%d/%d",
                                    k ? "," : "", rp.pieceNumber, rp.rot);
                }
                line[off++] = '\n';
                dumpBuf.append(line, off);
                if (dumpBuf.size() > 65536) {
                    if (!dumpF) dumpF = fopen((cfg.dump3x3Path + ".t" +
                                               std::to_string(threadId)).c_str(), "w");
                    if (dumpF) { fwrite(dumpBuf.data(), 1, dumpBuf.size(), dumpF); dumpBuf.clear(); }
                }
                rec3x3 = true;
                break;   // pas de DFS profond : on ne veut que la racine
            }
            if (cfg.stats) st.depthNodes[si]++;
            if ((nodes & 0xFFFFF) == 0) { // every ~1M nodes: time/stop checks
                if (g_stop.load(std::memory_order_relaxed)) break;
                if (cfg.seconds > 0) {
                    auto el = std::chrono::duration_cast<std::chrono::seconds>(
                                  std::chrono::steady_clock::now() - tStart).count();
                    if (el >= cfg.seconds) { g_stop = true; break; }
                }
                st.nodes.fetch_add(0x100000, std::memory_order_relaxed);
                st.placements.fetch_add(placements - lastFlushedPlacements,
                                        std::memory_order_relaxed);
                lastFlushedPlacements = placements;
                for (int d = 0; d < 256; d++)   // flush delta heatmap (peu fréquent : /~1M nœuds)
                    if (placeHist[d] != lastFlushedPlaceHist[d]) {
                        st.placeHist[d].fetch_add(placeHist[d] - lastFlushedPlaceHist[d], std::memory_order_relaxed);
                        lastFlushedPlaceHist[d] = placeHist[d];
                    }
            }
            if (si > maxSi) {
                maxSi = si;
                nodesAtDepthCheck = nodes;
                if (si == 240) {   // 1er franchissement depth 240 : marqueurs tournoi + capture phase-2
                    nodesAt240 = nodes; breaks240 = (int)cumBreaks[si - 1];
                    if (!cfg.captureDir.empty())
                        writeCanaryCapture(cfg.captureDir, cfg.captureArm, board, si,
                                           (int)cumBreaks[si - 1], attemptSeed, threadId, fcurRoot);
                }
                if (cfg.frontierAudit && si >= cfg.frontierAudit)   // P5a : snapshot frontière la plus profonde
                    deepCrc = fnv1a(board, (size_t)si * sizeof(RotatedPiece));
                if (cfg.lbOracle) {   // P6a : échantillonne le LB aux profondeurs cibles (1x/prof/tentative)
                    int di = -1;
                    for (int q = 0; q < LB_NDEP; q++) if (LB_DEPTHS[q] == si) { di = q; break; }
                    if (di >= 0) {
                        auto t0 = std::chrono::steady_clock::now();
                        int lb = cardinalityLB(board, used);
                        auto t1 = std::chrono::steady_clock::now();
                        uint64_t ns = (uint64_t)std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
                        g_lbCalls[di].fetch_add(1, std::memory_order_relaxed);
                        g_lbSumLB[di].fetch_add((uint64_t)lb, std::memory_order_relaxed);
                        g_lbNanos[di].fetch_add(ns, std::memory_order_relaxed);
                        if ((int)cumBreaks[si - 1] + lb > TOTAL_BUDGET)
                            g_lbPrune[di].fetch_add(1, std::memory_order_relaxed);
                    }
                }
                if ((si == 250 || si >= 252) &&
                    TOTAL_BUDGET - (int)cumBreaks[si - 1] >= cfg.tailMinSlack)
                    saveDeepPrefix(board, si, cumBreaks[si - 1],
                                   threadId, attemptSeed);
                if (!snapped && si >= 176 && !cfg.poolLog.empty()) {
                    snapped = true;        // cold path: first crossing only
                    memset(snapMask, 0, sizeof snapMask);
                    for (int p = 1; p <= 256; p++)
                        if (used[p]) snapMask[(p - 1) >> 3] |= (uint8_t)(1u << ((p - 1) & 7));
                }
                // A newly established near-miss is disproportionately valuable.
                // Retry the exact official-score finisher at every deeper record
                // so depth-252/254 prefixes cannot miss MRV merely because the
                // periodic depth-236 sampler was not due on their ancestor.
                if (cfg.tailDepth && si > cfg.tailDepth && si < 256 &&
                    TOTAL_BUDGET - (int)cumBreaks[si - 1] >= cfg.tailMinSlack) {
                    uint64_t tn = 0;
                    int score = solveTailMrv(board, used, si, cumBreaks[si - 1],
                                             cfg.tailNodes, &tn);
                    st.tailCalls.fetch_add(1, std::memory_order_relaxed);
                    st.tailNodes.fetch_add(tn, std::memory_order_relaxed);
                    if (score >= 0) {
                        st.completions.fetch_add(1, std::memory_order_relaxed);
                        int prev = g_bestScore.load();
                        while (score > prev &&
                               !g_bestScore.compare_exchange_weak(prev, score)) {}
                        logf("TAIL-MRV COMPLETION: %d/480 thread %d seed %" PRIu64
                             " depth %d nodes %" PRIu64 "%s",
                             score, threadId, attemptSeed, si, tn,
                             score > prev ? "  *** NEW BEST ***" : "");
                        if (score >= cfg.minSave)
                            saveBoard(board, score, threadId, attemptSeed);
                        break;
                    }
                }
                // A record at 248+ is evidence that this attempt's earlier
                // prefix is unusually fertile.  Spend progressively more exact
                // work by unplacing a wider, previously untested suffix.  The
                // cheap exact-current-suffix call above still refutes the exact
                // 8/6/4/2-cell dead end first.
                if (cfg.tailAdaptive && si < 256 &&
                    TOTAL_BUDGET - (int)cumBreaks[si - 1] >= cfg.tailMinSlack) {
                    int tier = -1;
                    for (int k = 0; k < 4; k++)
                        if (si == ADAPTIVE_TAIL_TIERS[k].triggerDepth) tier = k;
                    if (tier >= 0) {
                        const AdaptiveTailTier& at = ADAPTIVE_TAIL_TIERS[tier];
                        uint64_t tn = 0;
                        bool capped = false;
                        int score = solveTailMrvRewind(
                            board, used, si, at.rewindDepth,
                            cumBreaks[at.rewindDepth - 1], at.nodeCap,
                            &tn, &capped);
                        st.tailCalls.fetch_add(1, std::memory_order_relaxed);
                        st.tailNodes.fetch_add(tn, std::memory_order_relaxed);
                        st.adaptiveCalls[tier].fetch_add(1, std::memory_order_relaxed);
                        st.adaptiveNodes[tier].fetch_add(tn, std::memory_order_relaxed);
                        if (capped)
                            st.adaptiveCapped[tier].fetch_add(1, std::memory_order_relaxed);
                        if (score >= 0) {
                            st.completions.fetch_add(1, std::memory_order_relaxed);
                            int prev = g_bestScore.load();
                            while (score > prev &&
                                   !g_bestScore.compare_exchange_weak(prev, score)) {}
                            logf("ADAPTIVE-MRV COMPLETION: %d/480 thread %d seed %" PRIu64
                                 " record %d rewind %d nodes %" PRIu64 "%s",
                                 score, threadId, attemptSeed, si, at.rewindDepth, tn,
                                 score > prev ? "  *** NEW BEST ***" : "");
                            if (score >= cfg.minSave)
                                saveBoard(board, score, threadId, attemptSeed);
                            break;
                        }
                    }
                }
                if (si == 256) { // completed board
                    int breaks = cumBreaks[255];
                    int score = 480 - breaks;
#ifdef BW_SIGMA_LEDGER
                    // SOUNDNESS self-check : à toute feuille complète VALIDE, chaque couleur a un
                    // degré pair dans le multigraphe des breaks => oddMask DOIT être 0. Un non-zéro
                    // révélerait une incohérence du modèle de delta (à investiguer, jamais en prod).
                    if (sigmaOdd != 0) {
                        g_sigmaLeafBug.fetch_add(1, std::memory_order_relaxed);
                        logf("SIGMA-LEDGER SOUNDNESS ALERT: complete board oddMask=0x%x (breaks=%d) "
                             "— delta model inconsistent", sigmaOdd, breaks);
                    }
#endif
                    st.completions.fetch_add(1, std::memory_order_relaxed);
                    int v = verifyBoard(board);
                    if (v != score) {
                        logf("CRITICAL BUG: engine score %d != verified %d — not saving",
                             score, v);
                    } else {
                        int prev = g_bestScore.load();
                        while (score > prev && !g_bestScore.compare_exchange_weak(prev, score)) {}
                        logf("COMPLETION: %d/480 (%d breaks) thread %d seed %" PRIu64 "%s%s",
                             score, breaks, threadId, attemptSeed,
                             score > prev ? "  *** NEW BEST ***" : "",
                             score == 480 ? "  ***** FULL SOLUTION — ETERNITY II SOLVED *****" : "");
                        if (score >= cfg.minSave) saveBoard(board, score, threadId, attemptSeed);
                    }
                    break; // restart with fresh ordering
                }
            }
            if (nodes > attemptCap) break;
            if (cfg.pruneNodes && nodes - nodesAtDepthCheck > cfg.pruneNodes &&
                maxSi < cfg.pruneDepth)
                break; // prune-back: stalled shallow, restart early

            int ci = HOT.seqCell[si];   // P3: one lookup, no multiply

            if (board[ci].pieceNumber) {
#ifdef BW_HOTMAIN
                // retour naturel sous la profondeur si : le sous-arbre du placement capturé à si est complet.
                if (g_hmOn && g_hmSlotAtDepth[si] >= 0) {
                    HotMainSnap& s = g_hmSnaps[(size_t)g_hmSlotAtDepth[si]];
                    s.subtree = nodes - s.nodes_start; s.censored = 0; g_hmSlotAtDepth[si] = -1;
                }
#endif
#ifdef BW_SIGMA_LEDGER
                sigmaOdd ^= sigmaDelta[si];   // LBσ : annule la parité de la pièce retirée
#endif
#ifndef BW_DEEP_LEAN
                if (cfg.sdPrune || cfg.budgetLB) sdApply(ci, board[ci], -1);   // P12 : backtrack S/D
                if (cfg.isolatedBreaks && brokeNbAt[si] >= 0) {
                    brokenAt[ci]--;
                    brokenAt[brokeNbAt[si]]--;
                    brokeNbAt[si] = -1;
                }
#endif
                used[board[ci].pieceNumber] = false;
                if (g_telOn && si >= 9 && si <= 31) telSettle(si - 9, nodes, false);   // P-TEL : undo normal = closed
#ifdef BW_BLOCK_MASK
                { int _p = board[ci].pieceNumber - 1; remainingMask[_p >> 6] |= (1ULL << (_p & 63)); }
#endif
                board[ci].pieceNumber = 0;
            }

            const Table* tab = T.lookup[ci];
            int left = (ci & 15) ? board[ci - 1].right : 0;   // P3: col = ci&15
            int bottom = (ci >> 4) ? board[ci - 16].top : 0;  // P3: row = ci>>4
            int key = left * NCOLORS + bottom;
            const PoolElem* cand = tab->pool.data() + tab->off[key];
            int nCand = (int)(tab->off[key + 1] - tab->off[key]);
            if (g_eliteTrace && si >= 9 && si <= 31) {   // P-ELITE opt-1 : télémétrie slice (read-only)
                int _ei = eliteIdx(ci, left, bottom);
                g_eliteVisits[_ei].fetch_add(1, std::memory_order_relaxed);
                g_eliteNCand[_ei] = (uint16_t)nCand;
                g_elite931Nodes.fetch_add(1, std::memory_order_relaxed);
            }

            int allowedBreaks = g_breakMaskOn
                ? ((g_breakMaskW[ci] ? 1 : 0) + (g_breakMaskS[ci] ? 1 : 0))   // masque spatial : max breaks à cette cellule
                : (BREAK_ARRAY[si] - cumBreaks[si - 1]);
            bool found = false;
            // P-ELITE : sélection de la vue elite (ON) ou identité (OFF & REF). eview = permutation
            // de [0,nCand) (breakCount primaire), construite lazy par attempt. useView seulement en ON.
            const uint16_t* eview = nullptr; bool useView = false;
            if ((g_eliteOrderOn || g_eliteRefMode) && si >= 9 && si <= 31) {
                int ek = si - 9;
                if (g_eviewEpoch[ek][key] != g_eliteEpoch) {
                    g_eviewN[ek][key] = buildEview(ek, key, cand, nCand, g_eliteAttemptSeed);
                    g_eviewEpoch[ek][key] = g_eliteEpoch;
                }
                if (g_eviewN[ek][key] != 0xFF && (int)g_eviewN[ek][key] == nCand) {
                    eview = g_eview[ek][key];
                    if (g_eliteOrderOn) { useView = true; g_eliteAppliedT[threadId]++; }
                    if (g_eliteCheck && !g_breakMaskOn) {   // gate #2 : multiset OFF==ON (ensemble accepté identique)
                        uint32_t offS[ELITE_VMAX], onS[ELITE_VMAX]; int no = 0, non = 0;
                        for (int pass = 0; pass < 2; pass++) {
                            uint32_t* out = pass ? onS : offS; int& nn = pass ? non : no; bool vo = (pass == 1);
                            for (int vj2 = 0; vj2 < nCand; vj2++) { int ii = vo ? eview[vj2] : vj2; const RotatedPiece cc = cand[ii];
                                if ((int)cc.breakCount > allowedBreaks) break;
                                if (used[cc.pieceNumber]) continue;
                                if (si <= MAX_HEUR_IDX && (int)cumHeur[si - 1] + (int)cc.hsc < HEUR_ARRAY[si]) { if (vo) continue; else break; }
                                out[nn++] = ((uint32_t)cc.pieceNumber << 2) | cc.rot;
                            }
                        }
                        std::sort(offS, offS + no); std::sort(onS, onS + non);
                        g_eliteMsChecked.fetch_add(1, std::memory_order_relaxed);
                        bool same = (no == non); for (int z = 0; same && z < no; z++) if (offS[z] != onS[z]) same = false;
                        if (!same && g_eliteMsMismatch.fetch_add(1, std::memory_order_relaxed) < 5)
                            logf("ELITE_MS_MISMATCH si=%d key=%d nCand=%d offN=%d onN=%d", si, key, nCand, no, non);
                    }
                } else if (g_eliteOrderOn) g_eliteViewMissT[threadId]++;
            }
#ifdef BW_BLOCK_MASK
            // plage sans-break [0, breakLimitRel) : au-delà, le loop DOIT break sur breakCount.
            const int breakLimitRel = (allowedBreaks >= 2) ? nCand
                                    : (allowedBreaks == 1) ? (int)tab->bmClsB2[key]
                                    : (allowedBreaks == 0) ? (int)tab->bmClsB1[key] : 0;
            const uint32_t bmBase = tab->off[key];
#endif
            for (int vj = tryNext[si]; vj < nCand; vj++) {
                int i = useView ? eview[vj] : vj;   // P-ELITE : ordre vue (ON) ou identité (OFF/REF => i==vj)
#ifdef BW_BLOCK_MASK
                {   // saut de bloc GLOBAL (64) order-identical : bloc entièrement dans la plage
                    // sans-break ET aucune pièce restante -> équivaut à used[] continue sur tout le bloc.
                    uint32_t absi = bmBase + (uint32_t)i;
                    if ((absi & 63) == 0 && (i + 64) <= breakLimitRel) {
                        const uint64_t* bm = &tab->blockMask[(size_t)(absi >> 6) << 2];
                        if (((remainingMask[0] & bm[0]) | (remainingMask[1] & bm[1])
                           | (remainingMask[2] & bm[2]) | (remainingMask[3] & bm[3])) == 0) {
                            i += 63;   // i++ du for -> saut de 64
                            continue;
                        }
                    }
                }
#endif
#ifdef BW_PACKED_POOL32
                // décode break+piece+hsc d'abord (rejets), le reste seulement si on pose
                uint32_t w = cand[i];
                if ((int)((w >> 20) & 3) > allowedBreaks) break;   // sorted: breaks last
                int c_pn = (int)(w & 0xFF) + 1;
                if (used[c_pn]) continue;
                if (si <= MAX_HEUR_IDX &&
                    (int)cumHeur[si - 1] + (int)((w >> 22) & 7) < HEUR_ARRAY[si]) {
#ifdef BW_EARLY_BREAKS
                    int r1 = tab->clsB1[key], r2 = tab->clsB2[key];
                    i = ((i < r1) ? r1 : (i < r2) ? r2 : nCand) - 1;
                    continue;
#else
                    break;
#endif
                }
                const RotatedPiece c = unpackRP(w);
#else
                const RotatedPiece c = cand[i];
                if ((int)c.breakCount > allowedBreaks) break; // sorted: breaks last
                if (g_breakMaskOn) {   // masque spatial per-seam : rejette un break sur un seam NON autorisé (c.pad=dir)
                    if ((c.pad & 1) && !g_breakMaskW[ci]) continue;   // break ouest interdit ici
                    if ((c.pad & 2) && !g_breakMaskS[ci]) continue;   // break sud interdit ici
                }
#ifdef BW_CAND_INSTRUMENT
                { int _db = candBucket(si); tl_scan[_db]++; if (used[c.pieceNumber]) { tl_rej[_db]++; continue; } }
#else
                if (used[c.pieceNumber]) continue;
#endif
                if (cfg.forceRoot && si < 9) {
                    // racine forcée : n'accepte que fr[si], ignore le plancher HSC
                    if (c.pieceNumber != fr[si][0] || c.rot != fr[si][1]) continue;
                } else if (si <= MAX_HEUR_IDX &&
                    (int)cumHeur[si - 1] + (int)c.hsc < HEUR_ARRAY[si]) {
#ifdef BW_EARLY_BREAKS
                    // HSC monotone DANS la classe : saut direct à la fin de classe (i++ -> début classe suivante)
                    int r1 = tab->clsB1[key], r2 = tab->clsB2[key];
                    i = ((i < r1) ? r1 : (i < r2) ? r2 : nCand) - 1;
                    continue;
#else
                    if (useView) continue;   // P-ELITE ON : HSC = filtre par-candidat (bc0 monotone à 9-31 => même ensemble)
                    else break;              // OFF/REF : break bit-identique (hsc desc dans la classe)
#endif
                }
#endif
                board[ci] = c;
#ifdef BW_SIGMA_LEDGER
                // LBσ (couche 1) : borne de parité des couleurs. Coût O(1), UNIQUEMENT sur les
                // candidats break (breakCount>0) ; les placements exacts ne coûtent RIEN et ne
                // peuvent jamais déclencher la coupe (oddMask/spent inchangés). left = est du
                // voisin ouest, bottom = nord du voisin sud (déjà posés). pw/ps = ouest/sud de la
                // pièce posée. Un break interne (pw!=left ou ps!=bottom) flippe la parité des DEUX
                // couleurs de la couture (toutes deux non-nulles : les seams de cadre sont toujours
                // gris-matchés). nz(x) saute la couleur 0 (cadre) => borne toujours sound.
                uint32_t sDelta = 0;
                if (sigMainAct && c.breakCount) {
                    const Piece& pcs = PIECES[c.pieceNumber];
                    const int pw = sideAfterRot(pcs, c.rot, 3);   // ouest de la pièce
                    const int ps = sideAfterRot(pcs, c.rot, 2);   // sud de la pièce
                    if (pw != left)   sDelta ^= (left   ? (1u << left)   : 0u) ^ (pw ? (1u << pw) : 0u);
                    if (ps != bottom) sDelta ^= (bottom ? (1u << bottom) : 0u) ^ (ps ? (1u << ps) : 0u);
                    if (sDelta) {
                        const uint32_t nodd = sigmaOdd ^ sDelta;
                        // Chaque break restant corrige AU PLUS 2 couleurs impaires => il faut au moins
                        // ceil(popcount/2) breaks futurs. popcount toujours pair ici (2 flips/break),
                        // ceil = garde-fou si un flip simple (cadre) rendait popcount impair.
                        const int lbsig = (__builtin_popcount(nodd) + 1) >> 1;
                        const int spent = (int)cumBreaks[si - 1] + (int)c.breakCount;
                        g_sigmaCalls.fetch_add(1, std::memory_order_relaxed);
                        if (spent + lbsig > TOTAL_BUDGET) {            // spent + LBσ > B  <=>  LBσ > r
                            g_sigmaWouldCut.fetch_add(1, std::memory_order_relaxed);
                            if (cfg.sigmaMain) {                       // ON : coupe sound (DFS large)
                                g_sigmaCut.fetch_add(1, std::memory_order_relaxed);
                                board[ci].pieceNumber = 0;
                                continue;                             // aucun autre état modifié encore
                            }
                        }
                    }
                }
#endif
#ifndef BW_DEEP_LEAN
                // P15-A : options OFF en prod (isolatedBreaks/sdPrune/budgetLB/stats). BW_DEEP_LEAN les RETIRE
                // ENTIÈREMENT du binaire (pas juste des if prédits) pour un kernel plus dense (i-cache).
                // Behavior-identique quand ces options sont off (garanti par le gate fingerprint).
                int isoNb = -1;                // --isolated-breaks bookkeeping
                if (cfg.isolatedBreaks && c.breakCount) {
                    int westC = sideAfterRot(PIECES[c.pieceNumber], c.rot, 3);
                    isoNb = (westC != left) ? ci - 1 : ci - 16;
                    if (brokenAt[ci] || brokenAt[isoNb]) {  // would touch a break
                        board[ci].pieceNumber = 0;
                        continue;
                    }
                }
                if (cfg.sdPrune || cfg.budgetLB) {
                    sdApply(ci, c, +1);
                    bool p12cut = false;
                    if (cfg.sdPrune && sdViolated()) p12cut = true;   // --sd-prune : comportement inchangé
                    if (cfg.budgetLB && !p12cut) {                    // P12 : prune SOUND sur budget restant
                        const int spent = (int)cumBreaks[si - 1] + (int)c.breakCount;
                        const int slack = TOTAL_BUDGET - spent;
                        if (si >= cfg.budgetLbMinDepth && slack <= cfg.budgetLbMaxSlack) {
                            int lbcolor = 0;   // Σ_c max(0, D[c]-S[c]) : borne admissible des cassures futures
                            for (int c2 = 1; c2 < NCOLORS; c2++) { const int df = (int)D[c2] - (int)S[c2]; if (df > 0) lbcolor += df; }
                            g_p12Calls.fetch_add(1, std::memory_order_relaxed);
                            if (spent + lbcolor > TOTAL_BUDGET) {     // spent + LBcolor > B -> coupe sound
                                g_p12WouldCut.fetch_add(1, std::memory_order_relaxed);
                                if (cfg.budgetLB == 2) { p12cut = true; g_p12Cut.fetch_add(1, std::memory_order_relaxed); }
                            }
                        }
                    }
                    if (p12cut) {
                        sdApply(ci, c, -1);
                        board[ci].pieceNumber = 0;
                        continue;
                    }
                }
                if (isoNb >= 0) {
                    brokenAt[ci]++;
                    brokenAt[isoNb]++;
                    brokeNbAt[si] = (int16_t)isoNb;
                }
                if (cfg.stats) (c.breakCount ? st.depthHalf : st.depthFits)[si]++;
#endif
#ifdef BW_SIGMA_LEDGER
                // Placement COMMIS (tous les cuts passés) : applique le delta de parité.
                sigmaDelta[si] = sDelta;
                sigmaOdd ^= sDelta;
#endif
                used[c.pieceNumber] = true;
#ifdef BW_BLOCK_MASK
                { int _p = c.pieceNumber - 1; remainingMask[_p >> 6] &= ~(1ULL << (_p & 63)); }
#endif
#ifdef BW_CHOICE_FP
                tl_choiceFP = tl_choiceFP * 1099511628211ULL
                    ^ (((uint64_t)si << 40) | ((uint64_t)ci << 24)
                       | ((uint64_t)c.pieceNumber << 4) | (uint64_t)c.rot);
                tl_choiceCount++;
#endif
                cumBreaks[si] = (uint8_t)(cumBreaks[si - 1] + c.breakCount);
#ifdef BW_LEAN
                // P14-A : cumHeur[si] n'est lu qu'au check HSC de si+1 (gated si<=MAX_HEUR_IDX) -> inutile au-delà
                if (si <= MAX_HEUR_IDX) cumHeur[si] = (uint8_t)(cumHeur[si - 1] + c.hsc);
#else
                cumHeur[si] = (uint8_t)(cumHeur[si - 1] + c.hsc);
#endif
                tryNext[si] = (uint16_t)(vj + 1);   // P-ELITE : curseur = position dans la vue (OFF/REF: vj==i)
                if (g_telOn && si >= 9 && si <= 31) {   // P-TEL : engagement du choix -> snapshot nœuds
                    int _ti = si - 9; g_tframe[_ti] = {nodes, (uint32_t)ci, (uint16_t)key, (uint16_t)c.pieceNumber, (uint8_t)c.rot, true};
                }
#ifdef BW_HOTMAIN
                // Placement COMMIS à la profondeur si (après tous les gates, board/used/cumBreaks/sigmaOdd à jour).
                if (g_hmOn && g_hmTarget[si]) {
                    int slk = TOTAL_BUDGET - cumBreaks[si]; if (slk < 0) slk = 0; if (slk > 39) slk = 39;
                    if (g_hmStratCount[si][slk] < g_hmPerStratum && (g_hmHash(board, si) % (uint64_t)g_hmStride) == 0) {
                        HotMainSnap s{}; for (int k = 0; k < 256; k++) { s.piece[k] = board[k].pieceNumber; s.rot[k] = board[k].rot; }
                        s.depth = si; s.spent = cumBreaks[si];
#ifdef BW_SIGMA_LEDGER
                        s.sigmaOdd = sigmaOdd;
#else
                        s.sigmaOdd = 0;
#endif
                        s.nodes_start = nodes; s.subtree = 0; s.censored = 0;
                        g_hmSlotAtDepth[si] = (int)g_hmSnaps.size();
                        g_hmStratCount[si][slk]++;
                        g_hmSnaps.push_back(s);
                    }
                }
#endif
                if (g_eliteTrace && si >= 9 && si <= 31) g_elite931Accept.fetch_add(1, std::memory_order_relaxed);   // P-ELITE opt-1
                si++;
                found = true;
                break;
            }
            if (found) {
                placements++;
#ifndef BW_LEAN
                placeHist[si - 1]++;   // pièce posée à la profondeur si-1 (heatmap par case) — P14-A: OFF en lean
#endif
                // cost funnel: only the deep region can satisfy any threshold,
                // so the tracking cost stays off the shallow hot path
                if (__builtin_expect(si >= FUNNEL_TH[0], false)) {
                    uint8_t sp = cumBreaks[si - 1];
                    if (sp < 32 && si > depthAtSpend[sp]) depthAtSpend[sp] = (uint16_t)si;
                }
                // exact minimum-cost endgame, once per distinct prefix of this depth
                if (__builtin_expect(cfg.endgameDepth && si == cfg.endgameDepth, false)) {
                    int spent = (int)cumBreaks[si - 1];
                    if (g_telOn) {   // P-TEL : crédit outcome aux 23 frames actives à si==244 (slack466 = 14 - spent)
                        int slack = 14 - spent;
                        g_tReach244++; if (slack >= 4) g_tS4++; if (slack >= 5) g_tS5++;
                        for (int _ti = 0; _ti < 23; _ti++) if (g_tframe[_ti].active) {
                            TelExpo& e = g_texpoArr[_ti][g_tframe[_ti].piece][g_tframe[_ti].rot];
                            e.r244++; if (slack >= 4) e.s4++; if (slack >= 5) e.s5++;
                        }
                        // événement (rare, hors hot-loop) : slack root TICKET puis 23× key:piece.rot (features fins pour le modèle)
                        // crash-gate : le ticket permet à l'agrégateur de dédupliquer les V-events au crash-boundary (un ticket = un run).
                        char ev[512]; int eo = snprintf(ev, sizeof ev, "V %d %llu %llu", slack, (unsigned long long)fcurRoot, (unsigned long long)curGlobalTicket);
                        for (int _ti = 0; _ti < 23; _ti++)
                            eo += snprintf(ev+eo, sizeof ev-eo, " %u:%u.%u", (unsigned)g_tframe[_ti].key,
                                g_tframe[_ti].active?(unsigned)g_tframe[_ti].piece:0u, g_tframe[_ti].active?(unsigned)g_tframe[_ti].rot:0u);
                        g_tEventBuf.append(ev, eo); g_tEventBuf += '\n'; g_tEvents++;
                        if (g_tEventBuf.size() > 65536 && g_telEventF) { std::lock_guard<std::mutex> lk(g_telMtx); fwrite(g_tEventBuf.data(),1,g_tEventBuf.size(),g_telEventF); fflush(g_telEventF); g_tEventBuf.clear(); }
                    }
                    if (TOTAL_BUDGET - spent >= cfg.tailMinSlack) {
                        uint64_t tn = 0;
                        bool capped = false;
                        endgameSeq++;
                        bool probeThis = cfg.endgameProbeExtra &&
                            (!cfg.endgameSample || endgameSeq % cfg.endgameSample == 0);
                        int ceiling = TOTAL_BUDGET + (probeThis ? cfg.endgameProbeExtra : 0);
                        int cost = ceiling + 1;
                        int ringMis = -1;
                        incScore = -1;
                        int score = solveTailMrv(
                            board, used, si, spent, cfg.endgameNodes, &tn, &capped,
                            &cost, ceiling, TOTAL_BUDGET, &ringMis, -1, 0, -1, nullptr,
                            cfg.harvest463Dir.empty() ? nullptr : incBuf, &incScore);
                        if (!cfg.harvest463Dir.empty() && incScore >= 463) {   // canary7 : board 463 concret
                            char rid[176]; int ro = 0;
                            static const int C9[9] = {0,1,2,16,17,18,32,33,34};
                            for (int k = 0; k < 9; k++) { const RotatedPiece& rp = board[C9[k]];
                                ro += snprintf(rid + ro, sizeof rid - ro, "%s%d/%d", k?",":"", rp.pieceNumber, rp.rot); }
                            saveHarvest463(cfg.harvest463Dir, incBuf, incScore, rid, attemptSeed, fcurRoot, fjleft, 244);
                        }
                        if (ringMis >= 0)
                            st.endgameRing[ringMis < 15 ? ringMis : 15].fetch_add(
                                1, std::memory_order_relaxed);
                        st.endgameCalls.fetch_add(1, std::memory_order_relaxed);
                        st.endgameNodes.fetch_add(tn, std::memory_order_relaxed);
                        if (capped) st.endgameCapped.fetch_add(1, std::memory_order_relaxed);
                        if (!cfg.tourneyPath.empty()) {   // canary5 : qualité tail (endgame244 = preuve depth-244 atteint)
                            endgame244Calls++; exactTailNodes += tn;
                            int g = cost - TOTAL_BUDGET;
                            if (g >= 0 && g < 6) countGap[g]++;
                            if (cost < bestTailCost) {
                                bestTailCost = cost; bestTailRewind = 244;
                                bestTailProven = capped ? 0 : 1; spentAtBest = spent; ringMisAtBest = ringMis;
                            }
                            if (!cfg.capture3Dir.empty() && !gap3cap && cost <= TOTAL_BUDGET + 3) {
                                writeCanaryCapture(cfg.capture3Dir, "g3e244", board, si, spent,
                                                   attemptSeed, threadId, fcurRoot);
                                gap3cap = true;   // board 244 de l'événement gap<=3
                            }
                        }
                        if (cfg.endgameSample && !probeThis) {
                            // unsampled call: counted, but kept out of the
                            // distribution it would bias
                            if (score < 0 && !capped) { si--; continue; }
                        }
                        int slackIdx = TOTAL_BUDGET - spent;
                        slackIdx = slackIdx < 0 ? 0 : (slackIdx > 7 ? 7 : slackIdx);
                        int egCost = cost - spent;   // sentinel cost stays > probe
                        egCost = egCost < 0 ? 0 : (egCost > 15 ? 15 : egCost);
                        st.endgameGrid[slackIdx][egCost].fetch_add(
                            1, std::memory_order_relaxed);
                        attemptArrivals++;
                        attemptCap += cfg.yieldPer;   // productive attempts earn more nodes
                        if (score >= 0) {
                            st.completions.fetch_add(1, std::memory_order_relaxed);
                            int v = verifyBoard(board);
                            if (v != score) {
                                logf("CRITICAL BUG: endgame score %d != verified %d "
                                     "— not saving", score, v);
                            } else {
                                int prev = g_bestScore.load();
                                while (score > prev &&
                                       !g_bestScore.compare_exchange_weak(prev, score)) {}
                                logf("ENDGAME COMPLETION: %d/480 thread %d seed %" PRIu64
                                     " depth %d spent %d nodes %" PRIu64 "%s",
                                     score, threadId, attemptSeed, si, spent, tn,
                                     score > prev ? "  *** NEW BEST ***" : "");
                                if (score >= cfg.minSave)
                                    saveBoard(board, score, threadId, attemptSeed);
                            }
                            break;
                        }
                        // Ladder: each rung re-solves an ever wider suffix
                        // exactly, entered only when the previous pass left this
                        // prefix within that rung's gap of the budget.
                        bool laddered = false;
                        if (score < 0 && !capped && !cfg.ladder.empty()) {
                            int curCost = cost;
                            int gap216 = 1; for (const auto& lr : cfg.ladder) if (lr.rewind == 216) gap216 = lr.gap;
                            for (size_t rk = 0; rk < cfg.ladder.size(); rk++) {
                                const Config::EscRung& rung = cfg.ladder[rk];
                                if (curCost > TOTAL_BUDGET + rung.gap) break;
                                if (rung.rewind >= si) break;
                                if (cfg.shadowR224) {   // phase-3 : observe au rung, aucun enqueue, DFS inchangé
                                    if (rung.rewind < 260)
                                        g_shadowRungEntry[rung.rewind].fetch_add(1, std::memory_order_relaxed);
                                    if (rung.rewind == 224) {
                                        g_shadowR224Elig.fetch_add(1, std::memory_order_relaxed);
                                        TermKey tk = computeTailKey(board, used, si, 224, (int)cumBreaks[223],
                                            curCost, TOTAL_BUDGET + rung.gap, TOTAL_BUDGET);
                                        uint64_t k = tk.crc ^ (0x9E3779B97F4A7C15ULL * (uint64_t)(uint32_t)tk.initBest);
                                        { std::lock_guard<std::mutex> lk(g_shadowMtx); g_shadowKeys.insert(k); }
                                        int over = curCost - TOTAL_BUDGET;
                                        if (over < 0) over = 0; if (over > 23) over = 23;
                                        g_shadowCostHist[over].fetch_add(1, std::memory_order_relaxed);
                                    }
                                }
                                if (!cfg.tourneyPath.empty()) {   // canary5b : rung ENTRÉ (Codex : indép. du coût)
                                    if (rk < 8) rungCalls[rk]++;
                                    if (rung.rewind < deepestRewind) deepestRewind = rung.rewind;
                                }
                                // Mode B : au rung r224, déférer la CHAÎNE COMPLÈTE (r224+r216) à P8.
                                // Sur CREATED/ALREADY -> P8 possède r224+r216, main abandonne le ladder.
                                if (cfg.deferChain && rung.rewind == 224 && !cfg.captureInbox.empty()) {
                                    TermKey tk224 = computeTailKey(board, used, si, 224, (int)cumBreaks[223],
                                        curCost, TOTAL_BUDGET + rung.gap, TOTAL_BUDGET);
                                    int pbc = -1;
                                    if (!g_termProofDir.empty() && termCacheHit(tk224, &pbc)) {
                                        g_termHit.fetch_add(1, std::memory_order_relaxed);   // r224 prouvé -> r216 inline
                                        if (pbc > 0 && pbc < curCost) curCost = pbc;
                                        continue;
                                    }
                                    ChainSpec ch = buildChainSpec(board, used, si, (int)cumBreaks[223],
                                        (int)cumBreaks[215], curCost, rung.gap, gap216);
                                    CaptureResult cr = admitChain(cfg.captureInbox, cfg.p8Heartbeat, ch);
                                    if (cr == CAP_CREATED || cr == CAP_ALREADY_OWNED_P8) { laddered = true; break; }
                                    // sinon LOCAL_*/FAILED : fallback inline (le code ci-dessous tourne)
                                }
                                uint64_t tnr = 0;
                                bool cappedr = false;
                                int costr = TOTAL_BUDGET + rung.gap + 1;
                                st.escStarted[rk].fetch_add(1, std::memory_order_relaxed);
                                st.escInflightNodes[rk].store(0, std::memory_order_relaxed);
                                // P7-A: snapshot this exact-tail state once, if requested
                                if (cfg.captureRung == rung.rewind &&
                                    !g_tailCaptured.exchange(true, std::memory_order_relaxed))
                                    captureTailState(cfg.capturePath, board, used, si, rung.rewind,
                                                     (int)cumBreaks[rung.rewind - 1], curCost,
                                                     TOTAL_BUDGET + rung.gap, TOTAL_BUDGET);
                                bool sliceHere = cfg.tsN > 0 && rung.rewind == cfg.tsRewind;
                                // Décision r224/r216 (shadow #2) : cache de verdict -> defer -> local.
                                //  1. tail déjà prouvé EXHAUSTED -> skip (0 nœud).
                                //  2. sinon, si --defer-inbox et r224 : admission atomique -> déféré à
                                //     P8 (CREATED/ALREADY_OWNED/TERMINAL_HIT) sinon ownership LOCAL.
                                //  3. sinon (mode actuel) : feed refinery + résout inline.
                                int sr;
                                bool termSkip = false;
                                int termBestCost = -1;   // BLOQUEUR 3 : bestCost prouvé si cache hit
                                if (rung.rewind == 224 || rung.rewind == 216) {
                                    TermKey tk = computeTailKey(board, used, si, rung.rewind,
                                        (int)cumBreaks[rung.rewind - 1], curCost,
                                        TOTAL_BUDGET + rung.gap, TOTAL_BUDGET);
                                    if (!g_termProofDir.empty() && termCacheHit(tk, &termBestCost)) {
                                        g_termHit.fetch_add(1, std::memory_order_relaxed);
                                        termSkip = true;   // preuve réutilisée : provenBestCost connu -> propagé
                                    } else {
                                        g_termMiss.fetch_add(1, std::memory_order_relaxed);
                                        if (cfg.deferInbox && rung.rewind == 224 && !cfg.captureInbox.empty()) {
                                            CaptureResult r = admitDefer(cfg.captureInbox, cfg.p8Heartbeat,
                                                board, used, si, rung.rewind, (int)cumBreaks[rung.rewind - 1],
                                                curCost, TOTAL_BUDGET + rung.gap, TOTAL_BUDGET, tk);
                                            if (r == CAP_CREATED || r == CAP_ALREADY_OWNED_P8 || r == CAP_TERMINAL_HIT)
                                                termSkip = true;   // déféré/prouvé/possédé -> main ne résout pas
                                            // sinon LOCAL_*/FAILED : ownership local, résout inline ci-dessous
                                        } else if (!cfg.captureInbox.empty() && curCost <= TOTAL_BUDGET + 2) {
                                            captureToInbox(cfg.captureInbox, board, used, si, rung.rewind,
                                                           (int)cumBreaks[rung.rewind - 1], curCost,
                                                           TOTAL_BUDGET + rung.gap, TOTAL_BUDGET);  // feed refinery (mode actuel)
                                        }
                                    }
                                }
                                // Carry the best cost proven so far (curCost, e.g.
                                // 15 after rung2) so this wider rewind only hunts a
                                // STRICTLY better filling instead of re-finding 465.
                                if (termSkip) {   // 0 nœud, pas de complétion
                                    sr = -1; tnr = 0; cappedr = false;
                                    // BLOQUEUR 3 : cache hit -> propager le bestCost prouvé EXACTEMENT
                                    // comme le run inline (ligne curCost=min(curCost,costr)). Ex. f0 b16
                                    // prouve bestCost15 -> curCost passe à 15 -> le rung r216 se déclenche.
                                    // Defer (termBestCost<0) : pas de bestCost -> curCost inchangé (cas
                                    // r216-continuation, defer OFF par défaut, à traiter avant mode B).
                                    costr = (termBestCost > 0) ? termBestCost : (TOTAL_BUDGET + rung.gap + 1);
                                } else { incScore = -1; sr = solveTailMrvRewind(
                                    board, used, si, rung.rewind,
                                    (int)cumBreaks[rung.rewind - 1], rung.nodes,
                                    &tnr, &cappedr, &costr,
                                    TOTAL_BUDGET + rung.gap, TOTAL_BUDGET,
                                    sliceHere ? cfg.tsS : -1, sliceHere ? cfg.tsN : 0,
                                    curCost, &st.escInflightNodes[rk],
                                    cfg.harvest463Dir.empty() ? nullptr : incBuf, &incScore);
                                if (!cfg.harvest463Dir.empty() && incScore >= 463) {   // canary7 : board 463 via rung
                                    char rid[176]; int ro = 0;
                                    static const int C9[9] = {0,1,2,16,17,18,32,33,34};
                                    for (int k = 0; k < 9; k++) { const RotatedPiece& rp = board[C9[k]];
                                        ro += snprintf(rid + ro, sizeof rid - ro, "%s%d/%d", k?",":"", rp.pieceNumber, rp.rot); }
                                    saveHarvest463(cfg.harvest463Dir, incBuf, incScore, rid, attemptSeed, fcurRoot, fjleft, rung.rewind);
                                } }
                                st.escCalls[rk].fetch_add(1, std::memory_order_relaxed);
                                st.escInflightNodes[rk].store(0, std::memory_order_relaxed);  // clear on finish (no lingering count)
                                st.escNodes[rk].fetch_add(tnr, std::memory_order_relaxed);
                                if (cappedr)
                                    st.escCapped[rk].fetch_add(1, std::memory_order_relaxed);
                                int gr = costr - TOTAL_BUDGET;
                                st.escGapHist[rk][gr < 0 ? 0 : (gr > 15 ? 15 : gr)]
                                    .fetch_add(1, std::memory_order_relaxed);
                                if (!cfg.tourneyPath.empty()) {   // canary5 : qualité tail par rung
                                    exactTailNodes += tnr;
                                    if (gr >= 0 && gr < 6) countGap[gr]++;
                                    if (costr < bestTailCost) {
                                        bestTailCost = costr; bestTailRewind = rung.rewind;
                                        bestTailProven = cappedr ? 0 : 1;
                                        spentAtBest = (int)cumBreaks[rung.rewind - 1]; ringMisAtBest = -1;
                                    }
                                    if (!cfg.capture3Dir.empty() && !gap3cap && costr <= TOTAL_BUDGET + 3) {
                                        writeCanaryCapture(cfg.capture3Dir, "g3r", board, si,
                                                           (int)cumBreaks[si - 1], attemptSeed, threadId, fcurRoot);
                                        gap3cap = true;
                                    }
                                }
                                if (sr >= 0) {
                                    st.completions.fetch_add(1, std::memory_order_relaxed);
                                    int vr = verifyBoard(board);
                                    if (vr != sr) {
                                        logf("CRITICAL BUG: ladder score %d != verified"
                                             " %d — not saving", sr, vr);
                                    } else {
                                        int prevr = g_bestScore.load();
                                        while (sr > prevr &&
                                               !g_bestScore.compare_exchange_weak(prevr, sr)) {}
                                        logf("ESCALATED COMPLETION: %d/480 thread %d seed %"
                                             PRIu64 " rung %zu rewind %d spent %d nodes %"
                                             PRIu64 "%s", sr, threadId, attemptSeed,
                                             rk + 1, rung.rewind, spent, tnr,
                                             sr > prevr ? "  *** NEW BEST ***" : "");
                                        if (sr >= cfg.minSave)
                                            saveBoard(board, sr, threadId, attemptSeed);
                                    }
                                    laddered = true;
                                    break;
                                }
                                if (costr < curCost) curCost = costr;
                            }
                        }
                        if (laddered) break;
                        // Exhausted with nothing cheap enough: the whole subtree
                        // under this prefix is refuted, including the fillings the
                        // hot tables cannot even represent. Retry this cell.
                        if (!capped) { si--; continue; }
                    }
                }
                // We only arrive at a new prefix after a successful placement,
                // so keep the cold hybrid check off the backtracking half of
                // the hot loop.  The first depth crossing is always tested;
                // --tail-period sparsely samples later distinct prefixes.
                if (__builtin_expect(HOT_TAIL_DEPTH && si == HOT_TAIL_DEPTH &&
                        (!tailCalled || (cfg.tailPeriod && nodes >= nextTailAt)), false)) {
                    uint64_t tn = 0;
                    int score = solveTailMrv(board, used, si, cumBreaks[si - 1],
                                             cfg.tailNodes, &tn);
                    tailCalled = true;
                    nextTailAt = nodes + cfg.tailPeriod;
                    st.tailCalls.fetch_add(1, std::memory_order_relaxed);
                    st.tailNodes.fetch_add(tn, std::memory_order_relaxed);
                    if (score >= 0) {
                        st.completions.fetch_add(1, std::memory_order_relaxed);
                        int prev = g_bestScore.load();
                        while (score > prev &&
                               !g_bestScore.compare_exchange_weak(prev, score)) {}
                        logf("TAIL-MRV COMPLETION: %d/480 thread %d seed %" PRIu64
                             " nodes %" PRIu64 "%s",
                             score, threadId, attemptSeed, tn,
                             score > prev ? "  *** NEW BEST ***" : "");
                        if (score >= cfg.minSave)
                            saveBoard(board, score, threadId, attemptSeed);
                        break;
                    }
                }
                continue;
            }
            tryNext[si] = 0;
            si--;
            if (si <= 0) break; // exhausted the whole tree under cell 0's corner
        }
#ifdef BW_HOTMAIN
        // Fin d'attempt (restart/cap/stop/timeout/exhausted) : les slots encore actifs = CENSORED>=delta.
        if (g_hmOn) for (int d = 0; d <= 256; d++) if (g_hmSlotAtDepth[d] >= 0) {
            HotMainSnap& s = g_hmSnaps[(size_t)g_hmSlotAtDepth[d]];
            s.subtree = nodes - s.nodes_start; s.censored = 1; g_hmSlotAtDepth[d] = -1;
        }
#endif
        if (cfg.dump3x3 && !rec3x3) no3x3++;   // garde 1 : tree_exhausted_before9
        if (!cfg.tourneyPath.empty() && cfg.forceRoot) {   // tournoi : 1 ligne/attempt, flush immédiat (UI live)
            if (!tourF) tourF = fopen((cfg.tourneyPath + ".t" + std::to_string(threadId)).c_str(), "w");
            if (tourF) {
                char rid[176]; int ro = 0;
                for (int k = 0; k < 9; k++) ro += snprintf(rid + ro, sizeof rid - ro, "%s%d/%d", k ? "," : "", fr[k][0], fr[k][1]);
                int btg = (bestTailCost < 9999) ? bestTailCost - TOTAL_BUDGET : -1;
                fprintf(tourF, "%s %d %llu %llu %d btc=%d btg=%d btp=%d btr=%d eg=%d "
                        "g0=%d g1=%d g2=%d g3=%d g4=%d spb=%d rm=%d en=%llu "
                        "r236=%d r230=%d r224=%d r216=%d drw=%d "
                        "seed=%llu cidx=%llu jidx=%llu\n",
                        rid, maxSi, (unsigned long long)nodes, (unsigned long long)nodesAt240, breaks240,
                        bestTailCost < 9999 ? bestTailCost : -1, btg, bestTailProven, bestTailRewind,
                        endgame244Calls, countGap[0], countGap[1], countGap[2], countGap[3], countGap[4],
                        spentAtBest, ringMisAtBest, (unsigned long long)exactTailNodes,
                        rungCalls[0], rungCalls[1], rungCalls[2], rungCalls[3],
                        deepestRewind < 999 ? deepestRewind : -1,
                        (unsigned long long)attemptSeed, (unsigned long long)fcurRoot,
                        (unsigned long long)(cfg.forceInterleave ? fjleft : (cfg.forceJitters - 1 - fjleft)));
                // RC vérifiés (Codex #3) : un échec I/O DONE est compté, pas silencieux.
                if (fflush(tourF) != 0) g_tourWriteErrs.fetch_add(1, std::memory_order_relaxed);
                // DONE-durable borné : fdatasync périodique -> survit crash NOYAU/VM (perte <= N tickets).
                if (cfg.tourneySyncLines > 0 && ++tourSyncCtr >= cfg.tourneySyncLines) {
                    if (fdatasync(fileno(tourF)) != 0) g_tourSyncErrs.fetch_add(1, std::memory_order_relaxed);
                    tourSyncCtr = 0;
                }
            }
        }

        if (g_telOn) for (int _ti = 0; _ti < 23; _ti++) if (g_tframe[_ti].active) telSettle(_ti, nodes, true);   // P-TEL : frames actives fin d'attempt = censored (sous-arbre coupé)
        // crash-gate : le télémétrie de CE ticket est désormais entièrement dans g_texpoArr (settles undo + fin d'attempt).
        if (g_telOn && curGlobalTicket != UINT64_MAX) { if (curGlobalTicket > g_tMaxSettledTicket) g_tMaxSettledTicket = curGlobalTicket; g_tSettledCount++; }
        // P-TEL crash-gate : le CHECKPOINT télémétrie est DÉPLACÉ APRÈS le record ticket-log (voir plus bas),
        // pour garantir l'invariant expo ⊆ ledger-durable (aucun double-comptage au restart via skip-ledger).
#ifdef BW_TEL_BROKEN_ORDER
        // CONTRÔLE DISCRIMINANT (test uniquement) : ancien ordering BUGGÉ = checkpoint AVANT le flush ticket-log,
        // sans tkFlush forcé -> des expositions peuvent être persistées pour des tickets pas encore au ledger ->
        // rejoués au restart -> DOUBLE-COMPTAGE. Doit faire ÉCHOUER le gate (preuve que le gate a des dents).
        // (même trigger événements-OU-temps que le fixed, pour produire des checkpoints, mais SANS l'ordering.)
        {
            bool ckptDue = (g_tEvents - g_tLastCkptEvents >= g_telCkptEvents);
            if (g_telOn && !ckptDue && g_telCkptSec > 0)
                ckptDue = std::chrono::duration_cast<std::chrono::seconds>(
                              std::chrono::steady_clock::now() - g_tLastCkptTime).count() >= g_telCkptSec;
            if (g_telOn && ckptDue) {
                if (g_telEventF && !g_tEventBuf.empty()) { std::lock_guard<std::mutex> lk(g_telMtx); fwrite(g_tEventBuf.data(),1,g_tEventBuf.size(),g_telEventF); fflush(g_telEventF); g_tEventBuf.clear(); }
                telCheckpointExpo(threadId); g_tLastCkptEvents = g_tEvents; g_tLastCkptTime = std::chrono::steady_clock::now();
            }
        }
#endif
        st.nodes.fetch_add(nodes & 0xFFFFF, std::memory_order_relaxed);
        st.placements.fetch_add(placements - lastFlushedPlacements,
                                std::memory_order_relaxed);
        for (int d = 0; d < 256; d++)   // flush final heatmap de la tentative
            if (placeHist[d] != lastFlushedPlaceHist[d])
                st.placeHist[d].fetch_add(placeHist[d] - lastFlushedPlaceHist[d], std::memory_order_relaxed);
        st.restarts.fetch_add(1, std::memory_order_relaxed);
        if (!cfg.ticketLogDir.empty()) {   // --ticket-log : record binaire 40o (v1, little-endian), buffer par-thread
            uint8_t status = (maxSi >= 255) ? 2 : (nodes >= attemptCap ? 1
                             : (g_stop.load(std::memory_order_relaxed) ? 3 : 0));  // 0=exhausted 1=cap 2=hit 3=interrupt
            uint32_t durMs = (uint32_t)std::chrono::duration_cast<std::chrono::milliseconds>(
                             std::chrono::steady_clock::now() - tkAttStart).count();
            uint32_t ci = (uint32_t)fcurRoot, ji = (uint32_t)fjleft; uint16_t md = (uint16_t)maxSi;
            uint8_t tid = (uint8_t)threadId; char rec[40] = {0};
            // canary5 : bestTailCost (breaks a la frontiere la plus profonde) dans le reserved -> desature
            // la metrique (maxSi=243 est un artefact) -> vraie proximite de 465 (continu). 0xFFFF = aucun tail profond.
            uint16_t btc = (uint16_t)((bestTailCost >= 0 && bestTailCost < 9999) ? bestTailCost : 0xFFFF);
            memcpy(rec + 0, &curGlobalTicket, 8); memcpy(rec + 8, &ci, 4); memcpy(rec + 12, &ji, 4);
            memcpy(rec + 16, &nodes, 8); memcpy(rec + 24, &durMs, 4); memcpy(rec + 28, &md, 2);
            rec[30] = (char)status; rec[31] = (char)tid;
            memcpy(rec + 32, &btc, 2);   // octets 32-33 du reserved = bestTailCost
            if (!tkFail) {
                tkBuf.append(rec, 40);
                bool tkDue = tkBuf.size() >= 16384 ||
                    (!tkBuf.empty() && std::chrono::duration_cast<std::chrono::seconds>(
                         std::chrono::steady_clock::now() - tkLastFlush).count() >= cfg.ticketFlushSec);
                if (tkDue) {
                    tkFlush();
                    wasmPublishCheckpoint();
                }
            }
        }
        // P-TEL crash-gate : checkpoint télémétrie APRÈS le record ticket-log de CET attempt.
        // Invariant no-double-count : avant de persister g_texpoArr (expositions cumulées incl. ce ticket),
        // on FORCE tkFlush() -> le record de ce ticket (+ tous les précédents) est durable dans le journal.
        // Donc toute exposition présente dans un .expo appartient à un ticket durablement au ledger ->
        // exporté au skip-ledger -> sauté au restart -> jamais rejoué -> jamais recompté.
#ifndef BW_TEL_BROKEN_ORDER
        // Déclenche sur événements (reach-endgame) OU temps écoulé. Le trigger temporel borne la perte sur crash
        // MÊME quand reach-endgame est rare (cas réel : la plupart des attempts meurent shallow -> events~0).
        {
            bool ckptDue = (g_tEvents - g_tLastCkptEvents >= g_telCkptEvents);
            if (g_telOn && !ckptDue && g_telCkptSec > 0)
                ckptDue = std::chrono::duration_cast<std::chrono::seconds>(
                              std::chrono::steady_clock::now() - g_tLastCkptTime).count() >= g_telCkptSec;
            if (g_telOn && ckptDue) {   // P-TEL : checkpoint atomique périodique + flush événements (24h reboot/crash-safe)
                if (!cfg.ticketLogDir.empty() && !tkFail) tkFlush();   // ORDERING : ledger durable AVANT télémétrie
                if (g_telEventF && !g_tEventBuf.empty()) { std::lock_guard<std::mutex> lk(g_telMtx); fwrite(g_tEventBuf.data(),1,g_tEventBuf.size(),g_telEventF); fflush(g_telEventF); g_tEventBuf.clear(); }
                telCheckpointExpo(threadId); g_tLastCkptEvents = g_tEvents; g_tLastCkptTime = std::chrono::steady_clock::now();
            }
        }
#endif
        st.depthHist[maxSi].fetch_add(1, std::memory_order_relaxed);
        if (cfg.frontierAudit && deepCrc) {   // P5a : tally la frontière-de-mort de cette tentative
            g_auditTotal.fetch_add(1, std::memory_order_relaxed);
            std::lock_guard<std::mutex> lk(g_auditMtx);
            g_auditMult[deepCrc]++;
        }
        if (cfg.endgameDepth) {
            int b = 0;
            while (b < 13 && attemptArrivals >= (uint64_t)(1u << b)) b++;
            st.attemptYield[b].fetch_add(1, std::memory_order_relaxed);
        }
        {   // cost funnel: deepest cell reached per remaining budget
            uint16_t fr = 0;
            for (int sp = 0; sp <= TOTAL_BUDGET && sp < 32; sp++) {
                if (depthAtSpend[sp] > fr) fr = depthAtSpend[sp];
                int slack = TOTAL_BUDGET - sp;
                if (slack > 5) continue;
                for (int k = 0; k < 4; k++)
                    if (fr >= FUNNEL_TH[k])
                        st.costFunnel[k][slack].fetch_add(1, std::memory_order_relaxed);
            }
        }
        int prev = st.maxDepthEver.load();
        while (maxSi > prev && !st.maxDepthEver.compare_exchange_weak(prev, maxSi)) {}
        if (snapped) {                     // pool telemetry: "depth hex64(mask@176)"
            char head[16];
            poolBuf.append(head, (size_t)snprintf(head, sizeof head, "%d ", maxSi));
            for (int b = 0; b < 32; b++) {
                char h[3];
                snprintf(h, sizeof h, "%02x", snapMask[b]);
                poolBuf.append(h, 2);
            }
            poolBuf += '\n';
            if (poolBuf.size() > 16384) {
                if (!poolF)
                    poolF = fopen((cfg.poolLog + ".t" + std::to_string(threadId)).c_str(), "a");
                if (poolF) { fwrite(poolBuf.data(), 1, poolBuf.size(), poolF); fflush(poolF); }
                poolBuf.clear();
            }
        }
        // FIN SÉMANTIQUE de l'attempt : publier lastCompleted SEULEMENT si non interrompu.
        // Un checkpoint 30s / SIGTERM au milieu -> non publié -> l'attempt est REPRIS au restart.
        // (Les tails déférés à P8 dans cet attempt sont déjà durablement possédés : admitDefer
        // enqueue avec fsync AVANT de rendre CREATED.)
        if (!g_stop.load(std::memory_order_relaxed) && threadId >= 0 && threadId < MAX_ATT_THREADS)
            g_attemptDone[threadId].store(attempt, std::memory_order_relaxed);
    }
    if (!poolBuf.empty()) {
        if (!poolF)
            poolF = fopen((cfg.poolLog + ".t" + std::to_string(threadId)).c_str(), "a");
        if (poolF) fwrite(poolBuf.data(), 1, poolBuf.size(), poolF);
    }
    if (!cfg.ticketLogDir.empty()) {   // --ticket-log : flush final (write_all, record complet)
        tkFlush();
        if (tkF) fclose(tkF);
    }
    // P-TEL crash-gate : checkpoint télémétrie FINAL (capture la tranche <ckpt-events restante à l'arrêt propre).
    // APRÈS le flush ticket-log final ci-dessus -> ordering préservé (expo ⊆ ledger durable) même en fin de run.
    if (g_telOn) {
        if (g_telEventF && !g_tEventBuf.empty()) { std::lock_guard<std::mutex> lk(g_telMtx); fwrite(g_tEventBuf.data(),1,g_tEventBuf.size(),g_telEventF); fflush(g_telEventF); g_tEventBuf.clear(); }
        telCheckpointExpo(threadId);
    }
    if (poolF) fclose(poolF);
    if (cfg.dump3x3) {
        if (!dumpBuf.empty()) {
            if (!dumpF) dumpF = fopen((cfg.dump3x3Path + ".t" +
                                       std::to_string(threadId)).c_str(), "w");
            if (dumpF) fwrite(dumpBuf.data(), 1, dumpBuf.size(), dumpF);
        }
        if (dumpF) fclose(dumpF);
        logf("DUMP3X3 tid=%d attMax=%llu no3x3=%llu (tree_exhausted_before9)",
             threadId, (unsigned long long)attMax, (unsigned long long)no3x3);
    }
    if (tourF) {   // #3 : sync final DONE + RC vérifiés avant fermeture (aucune perte silencieuse)
        if (fflush(tourF) != 0) g_tourWriteErrs.fetch_add(1, std::memory_order_relaxed);
        if (fdatasync(fileno(tourF)) != 0) g_tourSyncErrs.fetch_add(1, std::memory_order_relaxed);
        if (fclose(tourF) != 0) g_tourWriteErrs.fetch_add(1, std::memory_order_relaxed);
    }
#ifdef BW_CAND_INSTRUMENT
    { std::lock_guard<std::mutex> lk(g_candMtx);
      for (int b = 0; b < 6; b++) { g_candScanned[b] += tl_scan[b]; g_rejectUsed[b] += tl_rej[b]; } }
#endif
#ifdef BW_CHOICE_FP
    { std::lock_guard<std::mutex> lk(g_fpMtx);   // combine ordre-indépendant (XOR) ; gate = mono-thread
      g_choiceFP ^= tl_choiceFP; g_choiceCount += tl_choiceCount; }
#endif
#ifdef BW_HOTMAIN
    if (g_hmOn && !g_hmOut.empty() && threadId == 0) hotMainDumpCorpus();
#endif
    if (g_telOn && g_telEventF) {   // P-TEL : dump per-thread (événements V + table expo E) sous mutex, à la sortie du thread
        std::lock_guard<std::mutex> lk(g_telMtx);
        if (!g_tEventBuf.empty()) { fwrite(g_tEventBuf.data(), 1, g_tEventBuf.size(), g_telEventF); g_tEventBuf.clear(); }
        for (int idx=0; idx<23; idx++) for (int piece=1; piece<=256; piece++) for (int rot=0; rot<4; rot++) {
            TelExpo& e = g_texpoArr[idx][piece][rot];
            if (!e.chosen && !e.r244) continue;
            fprintf(g_telEventF, "E %d %d %d %llu %llu %llu %llu %llu %llu %llu\n", idx, piece, rot,
                (unsigned long long)e.chosen,(unsigned long long)e.gnodes,(unsigned long long)e.closed,(unsigned long long)e.censored,
                (unsigned long long)e.r244,(unsigned long long)e.s4,(unsigned long long)e.s5);
        }
        fflush(g_telEventF);
        g_telReach244Tot+=g_tReach244; g_telS4Tot+=g_tS4; g_telS5Tot+=g_tS5; g_telEventsTot+=g_tEvents;
        g_telClosedTot+=g_tSettleClosed; g_telCensTot+=g_tSettleCens;
    }
}

// ------------------------------------------------------------------ heartbeat

static void heartbeat() {
    uint64_t lastNodes = 0, lastPlace = 0;
    auto last = std::chrono::steady_clock::now();
    while (!g_stop.load()) {
        for (int i = 0; i < 30 && !g_stop.load(); i++)
            std::this_thread::sleep_for(std::chrono::seconds(1));
        writeAttemptState(cfg.attemptState, cfg.threads, cfg.seed);   // shadow #3 : batch borné ~30s
        uint64_t n = 0, p = 0, r = 0, c = 0;
        int md = 0;
        // near-miss funnel: attempts whose max depth reached these thresholds
        static const int TH[6] = {240, 244, 248, 250, 252, 254};
        uint64_t fun[6] = {0, 0, 0, 0, 0, 0};
        uint64_t ac[4] = {}, ax[4] = {}, an[4] = {};
        uint64_t cf[4][6] = {};
        uint64_t eg[8][16] = {}, egCalls = 0, egCapped = 0, egNodes = 0;
        uint64_t histAll[257] = {};   // histogramme profondeur agrégé (heatmap puzzle dashboard)
        uint64_t placeAll[256] = {};  // pièces posées par case, agrégé (heatmap "pièces testées ici")
        for (auto& s : g_stats) {
            for (int k = 0; k < 4; k++)
                for (int sl = 0; sl < 6; sl++) cf[k][sl] += s.costFunnel[k][sl].load();
            if (cfg.endgameDepth) {
                egCalls += s.endgameCalls.load();
                egCapped += s.endgameCapped.load();
                egNodes += s.endgameNodes.load();
                for (int sl = 0; sl < 8; sl++)
                    for (int c2 = 0; c2 < 16; c2++)
                        eg[sl][c2] += s.endgameGrid[sl][c2].load();
            }
            n += s.nodes.load();
            p += s.placements.load();
            r += s.restarts.load();
            c += s.completions.load();
            md = std::max(md, s.maxDepthEver.load());
            if (cfg.tailAdaptive) {
                for (int k = 0; k < 4; k++) {
                    ac[k] += s.adaptiveCalls[k].load();
                    ax[k] += s.adaptiveCapped[k].load();
                    an[k] += s.adaptiveNodes[k].load();
                }
            }
            for (int d = 0; d <= 256; d++) {
                uint64_t v = s.depthHist[d].load();
                histAll[d] += v;   // heatmap : profondeur max atteinte par tentative, par case
                if (!v) continue;
                for (int k = 0; k < 6; k++)
                    if (d >= TH[k]) fun[k] += v;
            }
            for (int d = 0; d < 256; d++) placeAll[d] += s.placeHist[d].load();
        }
        if (!cfg.saveDir.empty()) {   // dump histogrammes -> le dashboard en fait une heatmap du puzzle
            char hp[600], tmpp[640];
            auto dump = [&](const char* fname, const char* tag, const uint64_t* arr, int n2) {
                snprintf(hp, sizeof hp, "%s/%s", cfg.saveDir.c_str(), fname);
                snprintf(tmpp, sizeof tmpp, "%s.tmp", hp);
                FILE* hf = fopen(tmpp, "w");
                if (hf) {
                    fprintf(hf, "%s", tag);
                    for (int d = 0; d < n2; d++) fprintf(hf, " %llu", (unsigned long long)arr[d]);
                    fprintf(hf, "\n"); fclose(hf); rename(tmpp, hp);
                }
            };
            dump("depthhist.txt", "DEPTHHIST1", histAll, 257);
            dump("placehist.txt", "PLACEHIST1", placeAll, 256);   // pièces posées par case
        }
        auto now = std::chrono::steady_clock::now();
        double dt = std::chrono::duration<double>(now - last).count();
        logf("nodes %.1fB (%.1fM/s) placements %.1fB (%.1fM/s) restarts %" PRIu64
             " completions %" PRIu64 " maxDepth %d best %d funnel"
             " %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
             " (≥240/244/248/250/252/254)",
             n / 1e9, (n - lastNodes) / dt / 1e6, p / 1e9,
             (p - lastPlace) / dt / 1e6, r, c, md, g_bestScore.load(),
             fun[0], fun[1], fun[2], fun[3], fun[4], fun[5]);
        // The event that precedes a completion under budget: arriving deep with
        // budget still in hand. Each group is slack 0/1/2/3/4/5+.
        logf("cost funnel d244 %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
             " d248 %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
             " d250 %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
             " d252 %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
             " (slack 0/1/2/3/4/5)",
             cf[0][0], cf[0][1], cf[0][2], cf[0][3], cf[0][4], cf[0][5],
             cf[1][0], cf[1][1], cf[1][2], cf[1][3], cf[1][4], cf[1][5],
             cf[2][0], cf[2][1], cf[2][2], cf[2][3], cf[2][4], cf[2][5],
             cf[3][0], cf[3][1], cf[3][2], cf[3][3], cf[3][4], cf[3][5]);
        if (cfg.endgameDepth) {
            uint64_t ay[14] = {}, ar[16] = {};
            for (auto& s : g_stats) {
                for (int b = 0; b < 14; b++) ay[b] += s.attemptYield[b].load();
                for (int b = 0; b < 16; b++) ar[b] += s.endgameRing[b].load();
            }
            std::string rh;
            for (int b = 0; b < 16; b++)
                if (ar[b]) rh += " " + std::to_string(b) + ":" + std::to_string(ar[b]);
            if (!rh.empty()) logf("  cheapest-completion ring mismatches:%s", rh.c_str());
            for (size_t rk = 0; rk < cfg.ladder.size(); rk++) {
                uint64_t rc = 0, rx = 0, rn = 0, rst = 0, rif = 0, rg[16] = {};
                for (auto& s3 : g_stats) {
                    rc += s3.escCalls[rk].load();
                    rx += s3.escCapped[rk].load();
                    rn += s3.escNodes[rk].load();
                    rst += s3.escStarted[rk].load();
                    rif = std::max(rif, s3.escInflightNodes[rk].load());  // furthest-along in-flight call (not sum)
                    for (int b = 0; b < 16; b++) rg[b] += s3.escGapHist[rk][b].load();
                }
                if (!rst && !rc) continue;  // print if entered (started) even when none finished yet
                std::string gh;
                for (int b = 0; b < 16; b++)
                    if (rg[b]) gh += " +" + std::to_string(b) + ":" + std::to_string(rg[b]);
                // live progress of the in-flight rung: nodes-done / cap = % (for dashboard ETA)
                std::string prog;
                if (rst > rc && rif > 0) {
                    double cap = (double)cfg.ladder[rk].nodes;
                    char buf[96];
                    snprintf(buf, sizeof buf, " progress %.0fM/%.0fM (%.1f%%)",
                             rif / 1e6, cap / 1e6, cap > 0 ? 100.0 * rif / cap : 0.0);
                    prog = buf;
                }
                logf("  ladder rung %zu (rewind %d): started %" PRIu64 " finished %" PRIu64
                     " inflight %" PRIu64 " capped %" PRIu64
                     " nodes %.1fM (%.0f/call) gap-to-budget%s%s", rk + 1,
                     cfg.ladder[rk].rewind, rst, rc, rst - rc, rx, rn / 1e6,
                     rc ? (double)rn / rc : 0.0, gh.c_str(), prog.c_str());
            }
        }
        {   // P5a : télémétrie transposition (compteurs atomiques existants, hors hot loop)
            uint64_t th = g_termHit.load(), tm = g_termMiss.load();
            uint64_t dOk = g_deferOk.load(), dOwn = g_alreadyOwned.load();
            double hitPct = (th + tm) ? 100.0 * th / (th + tm) : 0.0;
            double dupPct = (dOk + dOwn) ? 100.0 * dOwn / (dOk + dOwn) : 0.0;
            logf("  frontier-dedup: termCache hit %" PRIu64 " miss %" PRIu64 " (hit%% %.2f) |"
                 " chain-enqueue new %" PRIu64 " dup %" PRIu64 " (dup%% %.2f)",
                 th, tm, hitPct, dOk, dOwn, dupPct);
        }
        if (cfg.lbOracle) {   // P6a : signal de l'oracle LB par profondeur (poses/s tiré de placeAll)
            for (int q = 0; q < LB_NDEP; q++) {
                uint64_t ca = g_lbCalls[q].load();
                if (!ca) continue;
                uint64_t pr = g_lbPrune[q].load(), slb = g_lbSumLB[q].load(), ns = g_lbNanos[q].load();
                int d = LB_DEPTHS[q];
                uint64_t poses = (d < 256) ? placeAll[d] : 0;   // poses cumulées à cette profondeur
                logf("  lb-oracle d%d: calls %" PRIu64 " wouldPrune %" PRIu64 " (%.1f%%) meanLB %.2f"
                     " us/call %.2f poses@d %" PRIu64,
                     d, ca, pr, 100.0 * pr / ca, (double)slb / ca, (double)ns / ca / 1000.0, poses);
            }
        }
        if (cfg.budgetLB) {   // P12 : stats budget-LB (color) — mode 1=shadow, 2=coupe
            uint64_t ca = g_p12Calls.load(), wc = g_p12WouldCut.load(), ct = g_p12Cut.load();
            logf("  budget-lb(mode=%d minDepth=%d maxSlack=%d): calls %" PRIu64 " wouldCut %" PRIu64
                 " (%.2f%%) cut %" PRIu64, cfg.budgetLB, cfg.budgetLbMinDepth, cfg.budgetLbMaxSlack,
                 ca, wc, ca ? 100.0 * wc / ca : 0.0, ct);
        }
#ifdef BW_SIGMA_LEDGER
        {   // LBσ (couche 1) : stats de coupe parité. wouldCut compté même en OFF (shadow).
            uint64_t sca = g_sigmaCalls.load(), swc = g_sigmaWouldCut.load(),
                     sct = g_sigmaCut.load(), slb = g_sigmaLeafBug.load();
            logf("  sigma-MAIN(%s): breakCands %" PRIu64 " wouldCut %" PRIu64 " (%.3f%%) cut %"
                 PRIu64 " leafBugs %" PRIu64, cfg.sigmaMain ? "ON" : (cfg.sigmaMainShadow ? "SHADOW" : "OFF"),
                 sca, swc, sca ? 100.0 * swc / sca : 0.0, sct, slb);
            uint64_t tca = g_sigmaTailCalls.load(), twc = g_sigmaTailWouldCut.load(),
                     tct = g_sigmaTailCut.load(), tlb = g_sigmaTailLeafBug.load();
            logf("  sigma-TAIL(%s): nodes %" PRIu64 " wouldCut %" PRIu64 " (%.3f%%) cut %"
                 PRIu64 " leafBugs %" PRIu64, cfg.sigmaTail ? "ON" : "OFF/shadow",
                 tca, twc, tca ? 100.0 * twc / tca : 0.0, tct, tlb);
        }
#endif
        if (!g_skipLedger.empty())   // P13 : nb de tickets sautés car déjà terminés en local
            logf("  P13 skip-ledger : %" PRIu64 " tickets sautés (déjà terminés local) sur %zu chargés",
                 g_skipLedgerHits.load(), g_skipLedger.size());
        if (cfg.tourneySyncLines > 0 || g_tourWriteErrs.load() || g_tourSyncErrs.load())
            logf("  DONE-durable(tourney) : sync-lines=%d  fflush_err=%" PRIu64 "  fdatasync_err=%" PRIu64,
                 cfg.tourneySyncLines, g_tourWriteErrs.load(), g_tourSyncErrs.load());
#ifdef BW_TAIL_HALL
        {   // télémétrie prototype Hall P7-C (A/B) : appels + coupes prouvées (matching impossible)
            uint64_t hc = g_hallChecks.load(), hk = g_hallCuts.load();
            logf("  HALL-P7C : checks %" PRIu64 " cuts %" PRIu64 " (cut%% %.2f)",
                 hc, hk, hc ? 100.0 * hk / (double)hc : 0.0);
        }
#endif
#ifdef BW_CHOICE_FP
        logf("  P14B-CHOICE-FP %016llx count %" PRIu64,
             (unsigned long long)g_choiceFP, g_choiceCount);
#endif
#ifdef BW_CAND_INSTRUMENT
        {   // P14-B : ratio reject_used/cand_scanned par profondeur -> gisement d'ACTIVE-RANK
            uint64_t ts = 0, tr = 0;
            for (int b = 0; b < 6; b++) { ts += g_candScanned[b]; tr += g_rejectUsed[b]; }
            logf("  P14B-CAND total scanned %" PRIu64 " reject_used %" PRIu64 " (%.1f%%)",
                 ts, tr, ts ? 100.0 * tr / (double)ts : 0.0);
            for (int b = 0; b < 6; b++)
                logf("    depth %-8s scanned %" PRIu64 " reject_used %" PRIu64 " (%.1f%%)",
                     CAND_BUCKETS[b], g_candScanned[b], g_rejectUsed[b],
                     g_candScanned[b] ? 100.0 * g_rejectUsed[b] / (double)g_candScanned[b] : 0.0);
        }
#endif
        if (cfg.frontierAudit) {   // P5a : uniques vs transpositions à la profondeur auditée
            std::lock_guard<std::mutex> lk(g_auditMtx);
            uint64_t tot = g_auditTotal.load(); size_t uniq = g_auditMult.size();
            uint32_t mx = 0; uint64_t rep = 0, m2 = 0, m5 = 0;
            for (auto& kv : g_auditMult) {
                if (kv.second > mx) mx = kv.second;
                if (kv.second > 1) rep += kv.second - 1;   // Σ(mult-1) = économie contrefactuelle (arrivées)
                if (kv.second >= 2) m2++;
                if (kv.second >= 5) m5++;
            }
            logf("  frontier-audit d%d: arrivals %" PRIu64 " distinct %zu (uniq%% %.2f)"
                 " transpositions %" PRIu64 " maxMult %u frontiers>=2 %" PRIu64 " >=5 %" PRIu64,
                 cfg.frontierAudit, tot, uniq, tot ? 100.0 * uniq / (double)tot : 0.0,
                 rep, mx, m2, m5);
        }
        if (cfg.tailAdaptive)
            logf("adaptive calls %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
                 " capped %" PRIu64 "/%" PRIu64 "/%" PRIu64 "/%" PRIu64
                 " nodes %.1fM/%.1fM/%.1fM/%.1fM (248/250/252/253)",
                 ac[0], ac[1], ac[2], ac[3], ax[0], ax[1], ax[2], ax[3],
                 an[0] / 1e6, an[1] / 1e6, an[2] / 1e6, an[3] / 1e6);
        lastNodes = n;
        lastPlace = p;
        last = now;
    }
}

// ----------------------------------------------------------------------- main

// heuristic ramp (Blackwood's 470-run array, scaled)
static void buildHeurArray() {
    for (int i = 0; i < 256; i++) {
        double v = 0;
        if (i <= 16) v = 0;
        else if (i <= 26) v = (i - 16) * 2.8;
        else if (i <= 56) v = (i - 26) * 1.43333 + 28;
        else if (i <= 76) v = (i - 56) * 0.9 + 71;
        else if (i <= 102) v = (i - 76) * 0.6538 + 89;
        else if (i <= MAX_HEUR_IDX) v = (i - 102) / 4.4615 + 106;
        HEUR_ARRAY[i] = (int)(v * cfg.heurScale * (HEUR_EDGE_TOTAL / 150.0));
    }
}

static void buildStaticArrays() {
    // fill order
    bool seen[256] = {false};
    for (int pr = 0; pr < 16; pr++) {
        for (int c = 0; c < 16; c++) {
            int fi = BOARD_ORDER[pr][c];
            int bur = 15 - pr;
            if (fi < 0 || fi > 255 || seen[fi]) die("bad BOARD_ORDER");
            seen[fi] = true;
            SEQ_ROW[fi] = (uint8_t)bur;
            SEQ_COL[fi] = (uint8_t)c;
            HOT.seqCell[fi] = (uint8_t)(bur * 16 + c);   // P3
            FILL_IDX[bur * 16 + c] = fi;
        }
    }
    // west & south neighbors must be filled before each cell
    for (int fi = 0; fi < 256; fi++) {
        int r = SEQ_ROW[fi], c = SEQ_COL[fi];
        if (c > 0 && FILL_IDX[r * 16 + c - 1] >= fi) die("fill order: west not before %d", fi);
        if (r > 0 && FILL_IDX[(r - 1) * 16 + c] >= fi) die("fill order: south not before %d", fi);
    }

    // break indices
    std::vector<int> breaks;
    {
        std::string s = cfg.breaks;
        for (char& ch : s) if (ch == ',') ch = ' ';
        char* end = nullptr;
        const char* q = s.c_str();
        while (*q) {
            long v = strtol(q, &end, 10);
            if (end == q) break;
            breaks.push_back((int)v);
            q = end;
        }
    }
    if (breaks.empty()) {
        // ZERO-BREAK exact mode: no budget ever releases — perfect placements
        // only, every prefix exhaustively refuted or completed. Target: 480.
        FIRST_BREAK_IDX = 256;
        memset(BREAK_ARRAY, 0, sizeof(BREAK_ARRAY));
        TOTAL_BUDGET = 0;
        logf("ZERO-BREAK exact mode: perfect placements only, target 480");
        buildHeurArray();
        return;
    }
    std::sort(breaks.begin(), breaks.end());
    FIRST_BREAK_IDX = breaks.front();
#ifndef BW_EARLY_BREAKS
    if (FIRST_BREAK_IDX <= MAX_HEUR_IDX)
        die("first break index %d must exceed heuristic range %d", FIRST_BREAK_IDX, MAX_HEUR_IDX);
#endif
    int cum = 0, bi = 0;
    for (int i = 0; i < 256; i++) {
        while (bi < (int)breaks.size() && breaks[bi] == i) { cum++; bi++; }
        BREAK_ARRAY[i] = (uint8_t)cum;
        // reject duplicates / out-of-range
    }
    if (bi != (int)breaks.size()) die("break index out of range 0..255");
    // eligibility: not row0/col0/corners/clue cells. Those cells close one frame
    // side plus one lateral ring seam, so a release landing there is unspendable
    // — unless --ring-breaks has opened that cell's ring seam.
    for (int fi2 : breaks) {
        int r = SEQ_ROW[fi2], c = SEQ_COL[fi2];
        bool ringOpen = cfg.ringDepth && fi2 >= cfg.ringDepth;
        if (!ringOpen && (r == 0 || c == 0 || (r == 15 && (c == 0 || c == 15))))
            die("break index %d targets a no-break cell (bu r%d c%d)", fi2, r, c);
        for (const Hint& h : HINTS)
            if (15 - h.tdRow == r && h.tdCol == c)
                die("break index %d targets clue cell", fi2);
    }
    TOTAL_BUDGET = cfg.tailTargetScore >= 0 ? 480 - cfg.tailTargetScore
                                            : (int)BREAK_ARRAY[255];
    logf("breaks (%zu total, target completion score %d): %s",
         breaks.size(), 480 - (int)breaks.size(), cfg.breaks.c_str());
    buildHeurArray();
}

#ifdef BW_SIGMA_LEDGER
// --replay-board : rejoue une (ou tout un répertoire de) solution(s) CONNUE(s) le long de
// l'ordre de remplissage et trace la borne LBσ. TEST DE SOUNDNESS DÉCISIF : pour toute
// solution à b = 480 - verifyBoard breaks, la théorie garantit qu'à CHAQUE profondeur
// spent_si + ceil(popcount(oddMask_si)/2) <= b  (la vraie complétion fournit exactement
// b - spent_si breaks restants, or ce nombre >= borne de parité). Donc maxNeed == b et la
// feuille a oddMask == 0. Tout écart (maxNeed > b) prouverait que la coupe élaguerait la
// VRAIE solution => UNSOUND. Indépendant du budget configuré.
static int sigmaReplayOneBoard(const char* path) {
    FILE* f = fopen(path, "r");
    if (!f) return -1;
    RotatedPiece bd[256] = {};
    int pn, rt, cells = 0;
    for (int tdr = 0; tdr < 16; tdr++) {          // td row-major : ligne tdr = bur (15-tdr)
        int bur = 15 - tdr;
        for (int c = 0; c < 16; c++) {
            if (fscanf(f, " %d/%d", &pn, &rt) != 2) { fclose(f); return -1; }
            if (pn < 1 || pn > 256 || rt < 0 || rt > 3) { fclose(f); return -1; }
            int ci = bur * 16 + c;
            const Piece& p = PIECES[pn];
            bd[ci].pieceNumber = (uint16_t)pn;
            bd[ci].rot = (uint8_t)rt;
            bd[ci].top = sideAfterRot(p, rt, 0);
            bd[ci].right = sideAfterRot(p, rt, 1);
            cells++;
        }
    }
    fclose(f);
    if (cells != 256) return -1;
    int vb = verifyBoard(bd);
    if (vb < 0) { logf("replay-board %s: INVALID (verifyBoard=-1, mauvais frame/hints?)", path); return -1; }
    int bTrue = 480 - vb;
    uint32_t odd = 0;
    int spent = 0, maxNeed = 0, argMaxSi = -1, wouldCutAtB = 0;
    const int B = TOTAL_BUDGET;
    for (int si = 0; si < 256; si++) {            // ordre de remplissage EXACT du solveur
        int ci = HOT.seqCell[si];
        int r = ci >> 4, c = ci & 15;
        int left   = c ? bd[ci - 1].right : 0;    // est du voisin ouest (déjà posé)
        int bottom = r ? bd[ci - 16].top  : 0;    // nord du voisin sud (déjà posé)
        const Piece& p = PIECES[bd[ci].pieceNumber];
        int pw = sideAfterRot(p, bd[ci].rot, 3);
        int ps = sideAfterRot(p, bd[ci].rot, 2);
        uint32_t d = 0; int bc = 0;
        if (pw != left)   { d ^= (left ? (1u << left) : 0u) ^ (pw ? (1u << pw) : 0u); bc++; }
        if (ps != bottom) { d ^= (bottom ? (1u << bottom) : 0u) ^ (ps ? (1u << ps) : 0u); bc++; }
        odd ^= d; spent += bc;
        int need = spent + ((__builtin_popcount(odd) + 1) >> 1);
        if (need > maxNeed) { maxNeed = need; argMaxSi = si; }
        if (need > B) wouldCutAtB++;
    }
    bool pass = (maxNeed == bTrue) && (odd == 0) && (spent == bTrue);
    logf("replay-board %s: verify=%d/480 breaks=%d leafOdd=0x%x maxNeed=%d(@si%d) B=%d "
         "wouldCut@B=%d -> %s", path, vb, bTrue, odd, maxNeed, argMaxSi, B, wouldCutAtB,
         pass ? "SOUND (maxNeed==breaks, leaf odd=0)" : "*** UNSOUND ***");
    return pass ? 0 : 1;
}
static int sigmaReplayBoards(const std::string& spec) {
    int fails = 0, n = 0, skipped = 0;
    struct stat stt;
    if (stat(spec.c_str(), &stt) == 0 && S_ISDIR(stt.st_mode)) {
        std::vector<std::string> names;
        DIR* dp = opendir(spec.c_str());
        struct dirent* de;
        while (dp && (de = readdir(dp))) {
            std::string nm = de->d_name;
            if (nm.size() >= 5 && nm.substr(nm.size() - 4) == ".txt") names.push_back(nm);
            else if (nm.size() >= 5 && nm.substr(nm.size() - 4) == ".et2") names.push_back(nm);
        }
        if (dp) closedir(dp);
        std::sort(names.begin(), names.end());
        for (const auto& nm : names) {
            int r = sigmaReplayOneBoard((spec + "/" + nm).c_str());
            if (r < 0) skipped++; else { n++; if (r == 1) fails++; }
        }
    } else {
        int r = sigmaReplayOneBoard(spec.c_str());
        if (r < 0) skipped++; else { n++; if (r == 1) fails++; }
    }
    logf("replay-board SUMMARY: %d boards valides, %d UNSOUND, %d ignorés(parse/frame)",
         n, fails, skipped);
    return fails ? 1 : 0;
}

// ---------------------------------------------------------------------------
#ifdef BW_CUT_SNAPSHOT
// CUT_SNAPSHOT_CORPUS_V1 driver : charge un board complet, et pour chaque rung (rewind) rejoue le
// tail-solver en mode impasse (bestCost=boardBreaks, cherche strictement mieux -> exhauste), LBσ ON.
// Échantillonne les survivants LBσ (stride) + mesure leur sous-arbre, puis dumpe board+méta en texte.
static int cutSnapshotDump(const Config& cfg) {
    TOTAL_BUDGET = 480 - cfg.tsbTarget;
#ifdef BW_PRE_ROTATED
    buildPreRotated();
#endif
#ifdef BW_TAIL_PLACEMENT_MASK
    buildPlacementMasks();
#endif
    RotatedPiece full[256] = {};
    {   FILE* f = fopen(cfg.cutSnapBoard.c_str(), "r");
        if (!f) { logf("CUT_FAIL open %s", cfg.cutSnapBoard.c_str()); return 2; }
        int cells=0,rows=0;char line[4096];
        while(rows<16&&fgets(line,sizeof line,f)){int lp[16],lr[16],nt=0;bool valid=true;char* save=nullptr;
            for(char* tok=strtok_r(line," \t\r\n",&save);tok;tok=strtok_r(nullptr," \t\r\n",&save)){
                int pn,rt;char extra;if(nt>=16||sscanf(tok,"%d/%d%c",&pn,&rt,&extra)!=2||pn<1||pn>256||rt<0||rt>3){valid=false;break;}
                lp[nt]=pn;lr[nt]=rt;nt++;}
            if(!valid||nt!=16)continue;int bur=15-rows;
            for(int c=0;c<16;c++){int pn=lp[c],rt=lr[c],ci=bur*16+c;const Piece& p=PIECES[pn];
                full[ci].pieceNumber=(uint16_t)pn;full[ci].rot=(uint8_t)rt;
                full[ci].top=sideAfterRot(p,rt,0);full[ci].right=sideAfterRot(p,rt,1);cells++;}rows++;}
        fclose(f); if (cells != 256) { logf("CUT_FAIL cells=%d", cells); return 2; } }
    int vb = verifyBoard(full);
    if (vb < 0) { logf("CUT_FAIL board INVALID"); return 2; }
    int boardBreaks = 480 - vb;
    logf("CUT board=%s breaks=%d stride=%ld perRung=%ld nodecap=%llu", cfg.cutSnapBoard.c_str(),
         boardBreaks, cfg.cutStride, cfg.cutPerRung, (unsigned long long)cfg.cutNodeCap);
    auto prefixBreaks = [&](int rewind) -> int {
        int b = 0;
        for (int si = 0; si < rewind; si++) {
            int ci = SEQ_ROW[si] * 16 + SEQ_COL[si]; int r = ci >> 4, c = ci & 15;
            const Piece& p = PIECES[full[ci].pieceNumber];
            int pw = sideAfterRot(p, full[ci].rot, 3), ps = sideAfterRot(p, full[ci].rot, 2);
            if (c && pw != full[ci - 1].right) b++;
            if (r && ps != full[ci - 16].top) b++;
        }
        return b; };
    auto makeRewound = [&](int rewind, RotatedPiece* board, bool* used) {
        memcpy(board, full, 256 * sizeof(RotatedPiece));
        for (int p = 0; p <= 256; p++) used[p] = false;
        for (int ci = 0; ci < 256; ci++) if (board[ci].pieceNumber) used[board[ci].pieceNumber] = true;
        for (int d = rewind; d < 256; d++) { int ci = SEQ_ROW[d] * 16 + SEQ_COL[d];
            if (board[ci].pieceNumber) used[board[ci].pieceNumber] = false; board[ci] = {}; } };
    auto computeInitOdd = [&](const RotatedPiece* board) -> uint32_t {
        uint32_t io = 0;
        for (int ci = 0; ci < 256; ci++) { const RotatedPiece& a = board[ci]; if (!a.pieceNumber) continue;
            int rr = ci >> 4, cc = ci & 15;
            if (rr < 15) { const RotatedPiece& b = board[ci + 16]; if (b.pieceNumber) {
                int m = tailFace(a, 0), o = tailFace(b, 2); if (m != o) io ^= (m ? (1u << m) : 0u) ^ (o ? (1u << o) : 0u); } }
            if (cc < 15) { const RotatedPiece& b = board[ci + 1]; if (b.pieceNumber) {
                int m = tailFace(a, 1), o = tailFace(b, 3); if (m != o) io ^= (m ? (1u << m) : 0u) ^ (o ? (1u << o) : 0u); } } }
        return io; };

    std::vector<int> rungs;
    if (!cfg.cutRungs.empty()) {
        const char* p = cfg.cutRungs.c_str();
        while (*p) { int v = atoi(p); if (v > 0) rungs.push_back(v); while (*p && *p != ',') p++; if (*p == ',') p++; }
    } else { rungs = {236, 230, 228, 226, 224, 216}; }
    g_cutSnaps.clear();
    for (int ri = 0; ri < (int)rungs.size(); ri++) {
        int rung = rungs[ri];
        RotatedPiece board[256]; bool used[257];
        makeRewound(rung, board, used);
        int pb = prefixBreaks(rung);
        TailMrvState q; q.board = board; q.used = used; q.nodeCap = cfg.cutNodeCap;
        q.budget = boardBreaks; q.bestCost = boardBreaks;   // impasse : cherche strictement < boardBreaks
        q.sigmaOn = true;
        for (const Hint& h : HINTS) { int ci = (15 - h.tdRow) * 16 + h.tdCol; q.cluePiece[ci] = h.piece; q.clueRot[ci] = h.rot; }
        for (int d = rung; d < 256; d++) { int ci = SEQ_ROW[d] * 16 + SEQ_COL[d]; q.inTail[ci] = true; q.cells[q.nCells++] = ci; }
        for (int p = 1; p <= 256; p++) if (!used[p]) { const Piece& pc = PIECES[p]; q.sup[pc.n]++; q.sup[pc.e]++; q.sup[pc.s]++; q.sup[pc.w]++; }
        uint32_t io = computeInitOdd(board); q.initOdd = io;
        g_cutRung = rung; g_cutSampling = true; g_cutNodeCtr = 0; g_cutSurvivors = 0;
        g_cutStride = cfg.cutStride > 0 ? cfg.cutStride : 1;
        g_cutMax = g_cutSnaps.size() + (size_t)cfg.cutPerRung;
        g_stop.store(false, std::memory_order_relaxed);
#ifdef BW_ENUM_CAPTURE
        for (int z = 0; z < 5; z++) { g_ecNodes[z] = 0; g_ecCands[z] = 0; }   // histogramme PAR RUNG
        g_ecOn = true; g_ecStride = 997;   // capture éparse pour le micro-bench (rung-agnostique via nCon)
#endif
#ifdef BW_MRV_TELEMETRY
        g_mrvNodes=0; g_mrvSelEqFirst=0; g_mrvSelEqDepth=0; g_mrvDetGapSum=0; g_mrvSelDetSum=0; g_mrvScannedSum=0; g_mrvDemandCut=0;
        for (int z=0;z<10;z++) g_mrvGapHist[z]=0; g_mrvFp=1469598103934665603ull; g_mrvOn=true;
#endif
#ifdef BW_ENUM_CAPTURE
        struct timespec _cpu0, _cpu1; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &_cpu0);
        uint64_t _tcy0 = __builtin_ia32_rdtsc();
#endif
        tailMrvDfs(q, 0, pb, io);
#ifdef BW_ENUM_CAPTURE
        uint64_t _tcy = __builtin_ia32_rdtsc() - _tcy0;
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &_cpu1);
        double _cpums = (_cpu1.tv_sec - _cpu0.tv_sec) * 1e3 + (_cpu1.tv_nsec - _cpu0.tv_nsec) / 1e6;
        int _dir = -1;
#ifdef BW_ENUM_NCON2_DIRECT
        _dir = (int)g_ncon2Direct;
#endif
        logf("TOTCY rung=%d direct=%d totalCycles=%llu cpu_ms=%.3f maskNodes=%llu q.nodes=%llu", rung,
             _dir, (unsigned long long)_tcy, _cpums, (unsigned long long)g_ecNodes[2],
             (unsigned long long)q.nodes);
#endif
        g_cutSampling = false;
#ifdef BW_MRV_TELEMETRY
        g_mrvOn = false;
        {   uint64_t n = g_mrvNodes ? g_mrvNodes : 1;
            logf("MRVTEL rung=%d nodes=%llu selEqFirst=%llu(%.4f%%) selEqDepth=%llu(%.4f%%) avgDetGap=%.4f avgSelDet=%.3f avgScanned=%.2f demandCut=%llu fp=%llx gapHist[1..9]=%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu,%llu",
                 rung,(unsigned long long)g_mrvNodes,(unsigned long long)g_mrvSelEqFirst,100.0*g_mrvSelEqFirst/n,
                 (unsigned long long)g_mrvSelEqDepth,100.0*g_mrvSelEqDepth/n,(double)g_mrvDetGapSum/n,(double)g_mrvSelDetSum/n,
                 (double)g_mrvScannedSum/n,(unsigned long long)g_mrvDemandCut,(unsigned long long)g_mrvFp,
                 (unsigned long long)g_mrvGapHist[1],(unsigned long long)g_mrvGapHist[2],(unsigned long long)g_mrvGapHist[3],
                 (unsigned long long)g_mrvGapHist[4],(unsigned long long)g_mrvGapHist[5],(unsigned long long)g_mrvGapHist[6],
                 (unsigned long long)g_mrvGapHist[7],(unsigned long long)g_mrvGapHist[8],(unsigned long long)g_mrvGapHist[9]);
        }
#endif
        logf("CUT rung=%d nodes=%llu survivors=%llu snaps_total=%zu capped=%d", rung,
             (unsigned long long)g_cutNodeCtr, (unsigned long long)g_cutSurvivors, g_cutSnaps.size(), (int)q.capped);
#ifdef BW_TAIL_PROFILE
        {   uint64_t ms=g_cMaskSetup.load(), gen=g_genCycles.load(), mrv=g_cMrv.load(), pl=g_cPlace.load(),
                     lf=g_cLeaf.load(), tot=g_totalTailCycles.load(), calls=g_tmCalls.load();
            uint64_t enumc = gen>ms? gen-ms : 0;   // bucketing+decode+sDelta = gen - maskSetup
            uint64_t self = ms+gen+mrv+pl+lf;      // (gen inclut ms ; on retire ms du dénominateur)
            self = mrv + gen + pl + lf;            // self-cost node = MRV + gen(=ms+enum) + place + leaf
            logf("PROFILE rung=%d calls=%llu self=%llu ms=%llu enum=%llu(=gen-ms) mrv=%llu place=%llu leaf=%llu | enum/self=%.1f%%",
                 rung,(unsigned long long)calls,(unsigned long long)self,(unsigned long long)ms,(unsigned long long)enumc,
                 (unsigned long long)mrv,(unsigned long long)pl,(unsigned long long)lf, 100.0*enumc/(self?self:1));
            g_cMaskSetup=0; g_genCycles=0; g_cMrv=0; g_cPlace=0; g_cLeaf=0; g_totalTailCycles=0; g_tmCalls=0; g_tmLeaves=0; g_cDead=0;
        }
#endif
#ifdef BW_ENUM_CAPTURE
        g_ecOn = false;
        logf("NCON rung=%d nodes[0..4]=%llu,%llu,%llu,%llu,%llu cands[0..4]=%llu,%llu,%llu,%llu,%llu", rung,
             (unsigned long long)g_ecNodes[0],(unsigned long long)g_ecNodes[1],(unsigned long long)g_ecNodes[2],
             (unsigned long long)g_ecNodes[3],(unsigned long long)g_ecNodes[4],
             (unsigned long long)g_ecCands[0],(unsigned long long)g_ecCands[1],(unsigned long long)g_ecCands[2],
             (unsigned long long)g_ecCands[3],(unsigned long long)g_ecCands[4]);
#endif
    }
#ifdef BW_ENUM_CAPTURE
    {   // dump des tuples capturés (nCon, base[16], matchMask[nCon][16]) pour micro-bench old-vs-lean
        std::string cp = cfg.cutSnapOut + ".enumcaps";
        FILE* cf = fopen(cp.c_str(), "w");
        if (cf) {
            fprintf(cf, "# ENUMCAPS n=%zu format: nCon running bestCost base16(hex) mm[nCon]16(hex) conSide[nCon] conReq[nCon]\n", g_ecCaps.size());
            for (const EnumCap& e : g_ecCaps) {
                fprintf(cf, "%d %d %d", e.nCon, e.running, e.bestCost);
                for (int w = 0; w < 16; w++) fprintf(cf, " %llx", (unsigned long long)e.base[w]);
                for (int i = 0; i < e.nCon; i++) for (int w = 0; w < 16; w++) fprintf(cf, " %llx", (unsigned long long)e.mm[i][w]);
                for (int i = 0; i < e.nCon; i++) fprintf(cf, " %d", e.conSide[i]);
                for (int i = 0; i < e.nCon; i++) fprintf(cf, " %d", e.conReq[i]);
                fprintf(cf, "\n");
            }
            fclose(cf);
            logf("CUT wrote %zu enum-capture tuples -> %s", g_ecCaps.size(), cp.c_str());
        }
    }
#endif
    {   // sidecar : table de faces du solveur g_face[p][rot][side] (side 0..3, convention interne),
        // pour que l'analyse Python lise le board avec EXACTEMENT la convention du solveur (adjacence
        // f -> (r+DR[f],c+DC[f]) DR={1,0,-1,0} DC={0,1,0,-1}, opp=(f+2)&3 ; frame r0->f2,r15->f0,c0->f3,c15->f1).
        std::string fp = cfg.cutSnapOut + ".faces";
        FILE* ff = fopen(fp.c_str(), "w");
        if (ff) {
            for (int p = 1; p <= 256; p++) for (int rot = 0; rot < 4; rot++) {
                fprintf(ff, "%d %d", p, rot);
                for (int s = 0; s < 4; s++) fprintf(ff, " %d", (int)g_face[p][rot][s]);
                fprintf(ff, "\n");
            }
            fclose(ff);
            logf("CUT wrote face table -> %s", fp.c_str());
        }
    }
    FILE* out = fopen(cfg.cutSnapOut.c_str(), "w");
    if (!out) { logf("CUT_FAIL open out %s", cfg.cutSnapOut.c_str()); return 2; }
    fprintf(out, "# CUT_SNAPSHOT_CORPUS_V1 board=%s boardBreaks=%d snaps=%zu\n", cfg.cutSnapBoard.c_str(), boardBreaks, g_cutSnaps.size());
    for (const CutSnapshot& s : g_cutSnaps) {
        fprintf(out, "SNAP rung=%d depth=%d running=%d bestCost=%d lbsig=%d oddMask=%u subtree=%llu\n",
                s.rung, s.depth, s.running, s.bestCost, s.lbsig, s.oddMask, (unsigned long long)s.subtree);
        fprintf(out, "BOARD");
        for (int ci = 0; ci < 256; ci++) fprintf(out, " %d/%d", (int)s.piece[ci], (int)s.rot[ci]);
        fprintf(out, "\n");
    }
    fclose(out);
    logf("CUT_DONE wrote %zu snapshots -> %s", g_cutSnaps.size(), cfg.cutSnapOut.c_str());
    return 0;
}
#endif

// --tail-sigma-bench : porte la borne LBσ dans le TAIL-SOLVER (solveTailMrv /
// tailMrvDfs) et la valide + mesure LOCALEMENT, sans jamais toucher la prod.
//   1) SOUNDNESS exhaustive : sur un petit tail (rewind ~250), énumère TOUT le
//      sous-arbre OFF vs ON ; le multiset de complétions (compte + hash XOR) doit
//      être IDENTIQUE (toute divergence = coupe unsound). + self-check oddMask==0
//      à chaque feuille complète.
//   2) BENCHMARK par rung (236/230/224/216) : mode « exhaust/no-improve »
//      (initialBestCost = boardBreaks -> cherche strictement mieux, prouve l'impasse),
//      OFF vs ON, nodes ET wall. C'est le régime petit-budget-suffixe-profond où la
//      repro publique montre 19-45×.
//   3) REACHABILITY : initialBestCost = boardBreaks+1 -> le board (le 465) doit rester
//      atteignable avec LBσ ON (même score que OFF).
static int tailSigmaBench(const Config& cfg) {
    TOTAL_BUDGET = 480 - cfg.tsbTarget;    // budget de breaks cible (défaut 465 -> 15)
#ifdef BW_PRE_ROTATED
    buildPreRotated();
#endif
#ifdef BW_TAIL_PLACEMENT_MASK
    buildPlacementMasks();
#endif
    RotatedPiece full[256] = {};
    {   // charge un board complet, format td-row-major "piece/rot" (cf sigmaReplayOneBoard)
        FILE* f = fopen(cfg.tailSigmaBench.c_str(), "r");
        if (!f) { logf("TSB_FAIL open %s", cfg.tailSigmaBench.c_str()); return 2; }
        int cells = 0, rows = 0; char line[4096];
        while (rows < 16 && fgets(line, sizeof line, f)) {
            int lp[16], lr[16], nt = 0; bool valid = true; char* save = nullptr;
            for (char* tok = strtok_r(line, " \t\r\n", &save); tok; tok = strtok_r(nullptr, " \t\r\n", &save)) {
                int pn, rt; char extra;
                if (nt >= 16 || sscanf(tok, "%d/%d%c", &pn, &rt, &extra) != 2 ||
                    pn < 1 || pn > 256 || rt < 0 || rt > 3) { valid = false; break; }
                lp[nt] = pn; lr[nt] = rt; nt++;
            }
            if (!valid || nt != 16) continue; // skip SCORE/ROOT/provenance headers
            int bur = 15 - rows;
            for (int c = 0; c < 16; c++) { int pn=lp[c],rt=lr[c],ci=bur*16+c; const Piece& p=PIECES[pn];
                full[ci].pieceNumber=(uint16_t)pn; full[ci].rot=(uint8_t)rt;
                full[ci].top=sideAfterRot(p,rt,0); full[ci].right=sideAfterRot(p,rt,1); cells++; }
            rows++;
        }
        fclose(f); if (cells != 256) { logf("TSB_FAIL cells=%d", cells); return 2; }
    }
    int vb = verifyBoard(full);
    if (vb < 0) { logf("TSB_FAIL board INVALID (verifyBoard=-1, mauvais frame/hints ?)"); return 2; }
    int boardBreaks = 480 - vb;
    logf("TSB board=%s verify=%d/480 breaks=%d TOTAL_BUDGET=%d", cfg.tailSigmaBench.c_str(),
         vb, boardBreaks, TOTAL_BUDGET);

    // breaks accumulés dans le préfixe [0,rewind) selon l'ordre de remplissage (west + south).
    auto prefixBreaks = [&](int rewind) -> int {
        int b = 0;
        for (int si = 0; si < rewind; si++) {
            int ci = SEQ_ROW[si] * 16 + SEQ_COL[si]; int r = ci >> 4, c = ci & 15;
            const Piece& p = PIECES[full[ci].pieceNumber];
            int pw = sideAfterRot(p, full[ci].rot, 3), ps = sideAfterRot(p, full[ci].rot, 2);
            if (c && pw != full[ci - 1].right) b++;
            if (r && ps != full[ci - 16].top) b++;
        }
        return b;
    };
    // board + used avec le tail [rewind,256) vidé (rewind exact du tail-solver).
    auto makeRewound = [&](int rewind, RotatedPiece* board, bool* used) {
        memcpy(board, full, 256 * sizeof(RotatedPiece));
        for (int p = 0; p <= 256; p++) used[p] = false;
        for (int ci = 0; ci < 256; ci++) if (board[ci].pieceNumber) used[board[ci].pieceNumber] = true;
        for (int d = rewind; d < 256; d++) { int ci = SEQ_ROW[d] * 16 + SEQ_COL[d];
            if (board[ci].pieceNumber) used[board[ci].pieceNumber] = false; board[ci] = {}; }
    };
    auto resetCtrs = [&]() { g_sigmaTailCalls = 0; g_sigmaTailWouldCut = 0; g_sigmaTailCut = 0; g_sigmaTailLeafBug = 0;
        g_demSigmaCalls = 0; g_demSigmaStronger = 0; g_demSigmaWould = 0; g_demSigmaCuts = 0;
        for (int k = 0; k < 6; ++k) g_demSigWClass[k] = 0;
#ifdef BW_CHECKER_LEDGER
        g_checkerCalls = 0; g_checkerStronger = 0; g_checkerWouldCut = 0; g_checkerCut = 0;
        g_checkerLeafBug = 0; g_checkerMaxGain = 0;
#endif
#ifdef BW_FLUX_LEDGER
        g_fluxCalls = 0; g_fluxWouldCut = 0; g_fluxCut = 0; g_fluxLeafBug = 0; g_fluxStronger = 0; g_fluxMaxGain = 0;
#endif
#ifdef BW_LBASSIGN_SHADOW
        g_assignCalls = 0; g_assignStronger = 0; g_assignWouldCut = 0; g_assignNanos = 0; g_assignMaxGain = 0;
        for (int _k = 0; _k < 6; ++_k) { g_assignCallClass[_k] = 0; g_assignCutClass[_k] = 0; }
        g_hungWould = 0; g_defWould = 0; g_defRetain = 0; g_defFalse = 0; g_hungNanos = 0; g_defNanos = 0;
        g_hwitCuts = 0; g_hallS1 = 0; g_hallS2 = 0; g_hallS3 = 0; g_hallS4 = 0; g_hallS58 = 0; g_hallSbig = 0;
        g_hallDef1 = 0; g_hallDef2 = 0; g_hallDef3p = 0; g_hallNanos = 0;
#endif
    };
    // initOdd (parité XOR des coutures cassées déjà fermées) — même calcul que solveTailMrv.
    auto computeInitOdd = [&](const RotatedPiece* board) -> uint32_t {
        uint32_t io = 0;
        for (int ci = 0; ci < 256; ci++) { const RotatedPiece& a = board[ci]; if (!a.pieceNumber) continue;
            int rr = ci >> 4, cc = ci & 15;
            if (rr < 15) { const RotatedPiece& b = board[ci + 16]; if (b.pieceNumber) {
                int m = tailFace(a, 0), o = tailFace(b, 2); if (m != o) io ^= (m ? (1u << m) : 0u) ^ (o ? (1u << o) : 0u); } }
            if (cc < 15) { const RotatedPiece& b = board[ci + 1]; if (b.pieceNumber) {
                int m = tailFace(a, 1), o = tailFace(b, 3); if (m != o) io ^= (m ? (1u << m) : 0u) ^ (o ? (1u << o) : 0u); } } }
        return io;
    };

    // -------- 1) SOUNDNESS EXHAUSTIVE : énumère TOUT le sous-arbre OFF vs ON --------
    {
        int er = cfg.tsbEnumRewind, eb = cfg.tsbEnumBudget;
        RotatedPiece board[256]; bool used[257];
        auto enumRun = [&](bool sigmaOn, bool demSigmaOn, bool fluxOn, bool checkerOn, uint64_t* leaves, uint64_t* hash, bool* capped, uint64_t* nodes) {
            makeRewound(er, board, used);
            int pb = prefixBreaks(er);
            TailMrvState q; q.board = board; q.used = used; q.nodeCap = cfg.tsbCap;
            q.budget = eb; q.bestCost = eb;    // FIXE : mode énumération, jamais resserré
            q.enumerate = true; q.enumBudget = eb; q.sigmaOn = sigmaOn;
            q.demSigmaOn = demSigmaOn;   // LBdemSigma (handoff 2026-08-18)
            q.demSigGateT = g_demSigmaGate;   // A adaptatif (2026-08-19)
#ifdef BW_CHECKER_LEDGER
            q.checkerOn = checkerOn;
#else
            (void)checkerOn;
#endif
#ifdef BW_FLUX_LEDGER
            q.fluxOn = fluxOn; q.fluxEval = fluxOn;
#else
            (void)fluxOn;
#endif
            for (const Hint& h : HINTS) { int ci = (15 - h.tdRow) * 16 + h.tdCol; q.cluePiece[ci] = h.piece; q.clueRot[ci] = h.rot; }
            for (int d = er; d < 256; d++) { int ci = SEQ_ROW[d] * 16 + SEQ_COL[d]; q.inTail[ci] = true; q.cells[q.nCells++] = ci; }
            for (int p = 1; p <= 256; p++) if (!used[p]) { const Piece& pc = PIECES[p]; q.sup[pc.n]++; q.sup[pc.e]++; q.sup[pc.s]++; q.sup[pc.w]++; }
#ifdef BW_CHECKER_LEDGER
            if (q.checkerOn) initCheckerLedger(q);
#endif
            uint32_t io = computeInitOdd(board); q.initOdd = io;
            g_stop.store(false, std::memory_order_relaxed);
            tailMrvDfs(q, 0, pb, io);
#ifdef BW_TAIL_LEDGER_LOCAL
            flushTailLedger(q);
#endif
            *leaves = q.enumLeaves; *hash = q.enumHash; *capped = q.capped; *nodes = q.nodes;
        };
        resetCtrs();
        uint64_t offL, offH, offN, onL, onH, onN; bool offCap, onCap;
        enumRun(false, false, false, false, &offL, &offH, &offCap, &offN);   // OFF : aucune coupe
        enumRun(true,  false, false, false, &onL,  &onH,  &onCap,  &onN);    // SIGMA : LBσ seul
        uint64_t sigLeafBug = g_sigmaTailLeafBug.load();
        bool ok = (offL == onL) && (offH == onH) && !offCap && !onCap && sigLeafBug == 0;
        // ---- LBdemSigma SOUNDNESS : SIGMA+demSigma doit énumérer EXACTEMENT les mêmes feuilles qu'OFF ----
        uint64_t dsL, dsH, dsN; bool dsCap;
        resetCtrs();
        enumRun(true, true, false, false, &dsL, &dsH, &dsCap, &dsN);   // SIGMA + LBdemSigma
        uint64_t dsCalls = g_demSigmaCalls.load(), dsStronger = g_demSigmaStronger.load(),
                 dsWould = g_demSigmaWould.load(), dsCut = g_demSigmaCuts.load(), dsBug = g_sigmaTailLeafBug.load();
        bool dsok = (offL == dsL) && (offH == dsH) && !dsCap && dsBug == 0;
        ok = ok && dsok;
        logf("TSB DEMSIGMA-SOUNDNESS: leaves=%llu hash=%016llx nodes=%llu calls=%llu stronger=%llu would=%llu cut=%llu leafBug=%llu -> %s",
             (unsigned long long)dsL, (unsigned long long)dsH, (unsigned long long)dsN,
             (unsigned long long)dsCalls, (unsigned long long)dsStronger, (unsigned long long)dsWould,
             (unsigned long long)dsCut, (unsigned long long)dsBug,
             dsok ? "PASS (witness set identical OFF==SIGMA+DEMSIGMA)" : "*** FAIL (UNSOUND) ***");
        // A adaptatif : distribution des coupes marginales par classe lbDem (choisir la porte T).
        logf("TSB DEMSIGMA-CLASS (would-cut par lbDem) : c0=%llu c1=%llu c2=%llu c3=%llu c4=%llu c5+=%llu (gate=%d)",
             (unsigned long long)g_demSigWClass[0].load(), (unsigned long long)g_demSigWClass[1].load(),
             (unsigned long long)g_demSigWClass[2].load(), (unsigned long long)g_demSigWClass[3].load(),
             (unsigned long long)g_demSigWClass[4].load(), (unsigned long long)g_demSigWClass[5].load(), g_demSigmaGate);
#ifdef BW_CHECKER_LEDGER
        uint64_t ckL, ckH, ckN; bool ckCap;
        enumRun(true, false, false, true, &ckL, &ckH, &ckCap, &ckN);
        uint64_t ckBug = g_checkerLeafBug.load(), ckCut = g_checkerCut.load();
        bool ckok = (offL == ckL) && (offH == ckH) && !ckCap && ckBug == 0;
        ok = ok && ckok;
        logf("TSB CHECKER-SOUNDNESS: leaves=%llu hash=%016llx nodes=%llu cut=%llu leafBug=%llu -> %s",
             (unsigned long long)ckL, (unsigned long long)ckH, (unsigned long long)ckN,
             (unsigned long long)ckCut, (unsigned long long)ckBug,
             ckok ? "PASS (witness set identical OFF==CHECKER)" : "*** FAIL (UNSOUND) ***");
#endif
#ifdef BW_FLUX_LEDGER
        // FLUX : LBσ + LBflux. Le multiset de complétions valides (leaves + hash XOR) doit rester
        // IDENTIQUE à OFF. Toute divergence = LBflux a raté un témoin => UNSOUND, on FERME la couche.
        uint64_t flL, flH, flN; bool flCap;
        g_fluxLeafBug.store(0);
        enumRun(true, false, true, false, &flL, &flH, &flCap, &flN);
        uint64_t fluxLeafBug = g_fluxLeafBug.load(), fluxCut = g_fluxCut.load();
        bool fok = (offL == flL) && (offH == flH) && !flCap && fluxLeafBug == 0;
        ok = ok && fok;
        logf("TSB SOUNDNESS enum rewind=%d cells=%d budget=%d : OFF leaves=%llu hash=%016llx nodes=%llu | "
             "SIGMA leaves=%llu hash=%016llx nodes=%llu | FLUX leaves=%llu hash=%016llx nodes=%llu cut=%llu | "
             "sigLeafBug=%llu fluxLeafBug=%llu -> %s",
             er, 256 - er, eb, (unsigned long long)offL, (unsigned long long)offH, (unsigned long long)offN,
             (unsigned long long)onL, (unsigned long long)onH, (unsigned long long)onN,
             (unsigned long long)flL, (unsigned long long)flH, (unsigned long long)flN, (unsigned long long)fluxCut,
             (unsigned long long)sigLeafBug, (unsigned long long)fluxLeafBug,
             ok ? "PASS (witness set identical OFF==SIGMA==FLUX)" : "*** FAIL (UNSOUND) ***");
#else
        logf("TSB SOUNDNESS enum rewind=%d cells=%d budget=%d : OFF leaves=%llu hash=%016llx nodes=%llu cap=%d | "
             "ON leaves=%llu hash=%016llx nodes=%llu cap=%d | leafBug=%llu -> %s",
             er, 256 - er, eb, (unsigned long long)offL, (unsigned long long)offH, (unsigned long long)offN, offCap,
             (unsigned long long)onL, (unsigned long long)onH, (unsigned long long)onN, onCap,
             (unsigned long long)sigLeafBug, ok ? "PASS (witness set identical)" : "*** FAIL (UNSOUND) ***");
#endif
        if (!ok) return 1;
    }

    // parse rungs "rewind:gap,..." (défaut = ladder prod).
    int rungs[8], gaps[8], nr = 0;
    { std::string spec = cfg.tsbRungs.empty() ? std::string("236:4,230:3,224:2,216:1") : cfg.tsbRungs;
      size_t i = 0; while (i < spec.size() && nr < 8) { int rw = 0, gp = 1;
          if (sscanf(spec.c_str() + i, "%d:%d", &rw, &gp) >= 1) { rungs[nr] = rw; gaps[nr] = gp; nr++; }
          size_t k = spec.find(',', i); if (k == std::string::npos) break; i = k + 1; } }

    // -------- 2) BENCHMARK par rung : mode exhaust/no-improve (production) --------
    int initBest = cfg.tsbInitBest >= 0 ? cfg.tsbInitBest : boardBreaks;
#ifdef BW_LBASSIGN_SHADOW
    if (g_tsbSingletonOnly) g_assignEval = false;   // coupe l'overhead shadow dans BENCH/REACH (runs σ purs)
#endif
    logf("TSB BENCH exhaust (initBest=%d -> seek cost<%d) cap=%lluM/run",
         initBest, initBest, (unsigned long long)(cfg.tsbCap / 1000000));
    RotatedPiece board[256]; bool used[257];
    // *nodesCut renvoie les coupes LBσ (nœuds coupés AVANT nodes++, donc HORS *nodes). Le vrai
    // « node reduction » (au sens du doc) se lit sur les ENTRÉES = nodes compté + coupé.
    bool benchDemSig = false;   // LBdemSigma (handoff 2026-08-18) : piloté par le bloc DEMSIGMA-AB (OFF pour tous les autres benchs)
    auto runTail = [&](int rewind, int gap, int ib, bool sigmaOn, bool fluxEval, bool fluxOn,
                       uint64_t* nodes, uint64_t* nodesCut, double* wall, int* score, int* cost, bool* capped) {
        makeRewound(rewind, board, used);
        g_sigmaTailOn = sigmaOn; g_demSigmaOn = benchDemSig; resetCtrs();
#ifdef BW_FLUX_LEDGER
        g_fluxEval = fluxEval; g_fluxTailOn = fluxOn;
#else
        (void)fluxEval; (void)fluxOn;
#endif
        int pb = prefixBreaks(rewind);
        uint64_t tn = 0; bool cap = false; int co = TOTAL_BUDGET + gap + 1;
        g_stop.store(false, std::memory_order_relaxed);
        auto t0 = std::chrono::steady_clock::now();
        int sr = solveTailMrv(board, used, rewind, pb, cfg.tsbCap, &tn, &cap, &co,
                              TOTAL_BUDGET + gap, TOTAL_BUDGET, nullptr, -1, 0, ib);
        auto t1 = std::chrono::steady_clock::now();
        *nodes = tn; *nodesCut = g_sigmaTailCut.load();
        *wall = std::chrono::duration<double>(t1 - t0).count();
        *score = sr; *cost = co; *capped = cap;
    };
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t offN, offCut, onN, onCut; double offW, onW; int offS, onS, offC, onC; bool offCap, onCap;
        runTail(rw, gp, initBest, false, false, false, &offN, &offCut, &offW, &offS, &offC, &offCap);
        uint64_t wouldCut = g_sigmaTailWouldCut.load();
        runTail(rw, gp, initBest, true,  false, false, &onN,  &onCut,  &onW,  &onS,  &onC,  &onCap);
        uint64_t offEntries = offN + offCut, onEntries = onN + onCut;   // OFF: offCut==0
        double nodeX  = onN ? (double)offN / (double)onN : 0.0;               // nœuds COMPTÉS (MRV chers)
        double entryX = onEntries ? (double)offEntries / (double)onEntries : 0.0; // ENTRÉES (metric doc)
        double wallX  = onW > 1e-9 ? offW / onW : 0.0;
        // Verdict SOUNDNESS (cap-aware) : unsound seulement si (a) leafBug, (b) les DEUX épuisent avec
        // scores différents, ou (c) OFF a trouvé un témoin (offS>=0) que ON n'égale pas (onS<offS).
        // OFF cape / ON épuise = LE GAIN (ON prouve l'impasse), PAS de l'unsoundness.
        uint64_t lb = g_sigmaTailLeafBug.load();
        bool unsound = lb || (!offCap && !onCap && offS != onS) || (offS >= 0 && onS < offS);
        const char* verdict = unsound ? "*** UNSOUND ***"
                            : (!onCap && offCap) ? "ON EXHAUSTS / OFF CAPPED (ON proves dead-end)"
                            : (!offCap && !onCap) ? "consistent (both exhausted)"
                            : "both capped";
        logf("TSB RUNG r%d gap%d budget%d cells%d prefBreaks%d slack%d : "
             "OFF nodes=%llu(+cut0) wall=%.3fs score=%d cap=%d | ON nodes=%llu(+cut%llu=%llu entries) wall=%.3fs score=%d cap=%d | "
             "nodeX(counted)=%.1f entryX=%.1f wallX=%.1f wouldCut=%llu leafBug=%llu -> %s",
             rw, gp, TOTAL_BUDGET + gp, 256 - rw, prefixBreaks(rw), TOTAL_BUDGET - prefixBreaks(rw),
             (unsigned long long)offN, offW, offS, offCap,
             (unsigned long long)onN, (unsigned long long)onCut, (unsigned long long)onEntries, onW, onS, onCap,
             nodeX, entryX, wallX, (unsigned long long)wouldCut, (unsigned long long)lb, verdict);
#ifdef BW_CHECKER_LEDGER
        if (g_checkerTailOn) logf("TSB CHECKER r%d: calls=%llu stronger=%llu wouldCut=%llu cut=%llu maxGain=%d leafBug=%llu",
             rw, (unsigned long long)g_checkerCalls.load(), (unsigned long long)g_checkerStronger.load(),
             (unsigned long long)g_checkerWouldCut.load(), (unsigned long long)g_checkerCut.load(),
             g_checkerMaxGain.load(), (unsigned long long)g_checkerLeafBug.load());
#endif
    }

    // -------- 3) DEMSIGMA-AB (handoff 2026-08-18) : ABBA baseline sigma vs sigma+LBdemSigma --------
    if (cfg.demSigmaJoint) {
        logf("TSB DEMSIGMA-AB: baseline sigma vs sigma+LBdemSigma (ABBA OFF,ON,ON,OFF, gain marginal)");
        for (int ri = 0; ri < nr; ri++) {
            int rw = rungs[ri], gp = gaps[ri], pairs = rw >= 230 ? 10 : 1, reps = 2 * pairs;
            uint64_t sN = 0, sCut = 0, dN = 0, dCut = 0; double sW = 0, dW = 0;
            uint64_t dCalls = 0, dStronger = 0, dWould = 0, dCuts = 0, lb = 0;
            int sS = -1, dS = -1, sC = 0, dC = 0; bool sCap = false, dCap = false;
            auto arm = [&](bool dem) { uint64_t n, k; double w; int sc, co; bool cap;
                benchDemSig = dem;   // pilote g_demSigmaOn dans runTail
                runTail(rw, gp, initBest, true, false, false, &n, &k, &w, &sc, &co, &cap);
                benchDemSig = false;
                if (dem) { dN = n; dCut = k; dW += w; dS = sc; dC = co; dCap = cap;
                    dCalls = g_demSigmaCalls.load(); dStronger = g_demSigmaStronger.load();
                    dWould = g_demSigmaWould.load(); dCuts = g_demSigmaCuts.load(); }
                else { sN = n; sCut = k; sW += w; sS = sc; sC = co; sCap = cap; }
                if (g_sigmaTailLeafBug.load()) lb = g_sigmaTailLeafBug.load(); };
            for (int z = 0; z < pairs; z++) { arm(false); arm(true); arm(true); arm(false); }
            sW /= reps; dW /= reps;
            double nodeRed = sN ? 100.0 * (1.0 - (double)dN / (double)sN) : 0.0;
            double wallX = dW > 1e-12 ? sW / dW : 0.0;
            bool same = (sS == dS && sC == dC && sCap == dCap && lb == 0);
            logf("TSB DEMSIGMA-AB r%d reps%d: sigma nodes=%llu wall=%.6fs | +demSigma nodes=%llu wall=%.6fs nodeRed=%.2f%% wallX=%.3f calls=%llu stronger=%llu would=%llu cut=%llu -> %s",
                 rw, reps, (unsigned long long)sN, sW, (unsigned long long)dN, dW, nodeRed, wallX,
                 (unsigned long long)dCalls, (unsigned long long)dStronger, (unsigned long long)dWould, (unsigned long long)dCuts,
                 same ? "consistent" : "*** MISMATCH (score/cost divergent) ***");
        }
    }

    // -------- P3 : BACKJUMP DEPTH TRACE (2026-08-19, read-only, aucun saut/coupe, arbre identique) --------
    // Pour chaque cellule morte size-1 rencontrée, saut sound = curDepth - max(profondeurs dépendances).
    // Gate Codex PASS : médiane >=2 ET jump>=2 sur >=10% du travail. Sinon STOP P3 = fin recherches de coupe.
    if (g_traceBackjump) {
        logf("TSB BACKJUMP-TRACE: profondeur de saut SOUND sur cellules mortes (det>=%d), read-only", g_dead0GateDet);
        for (int ri = 0; ri < nr; ri++) {
            int rw = rungs[ri], gp = gaps[ri];
            for (int b = 0; b < 6; b++) g_bjHist[b].store(0);
            g_bjCells.store(0); g_bjUnexploit.store(0);
            uint64_t n, k; double w; int sc, co; bool cap;
            benchDemSig = false;
            runTail(rw, gp, initBest, true, false, false, &n, &k, &w, &sc, &co, &cap);
            uint64_t h[6]; uint64_t tot = 0;
            for (int b = 0; b < 6; b++) { h[b] = g_bjHist[b].load(); tot += h[b]; }
            uint64_t ge2 = h[2] + h[3] + h[4] + h[5];
            auto pctBin = [&](double qq){ uint64_t acc = 0, thr = (uint64_t)(qq * (double)tot); for (int b = 0; b < 6; b++) { acc += h[b]; if (acc >= thr && tot) return b; } return 5; };
            double fge2 = tot ? 100.0 * (double)ge2 / (double)tot : 0.0;
            int medBin = pctBin(0.5), p90Bin = pctBin(0.9);
            bool pass = tot && medBin >= 2 && fge2 >= 10.0;
            logf("TSB BACKJUMP r%d nodes=%llu deadCells=%llu : jump0=%llu jump1=%llu jump2=%llu jump3=%llu jump4-7=%llu jump8+=%llu | medianBin=%d P90Bin=%d jump>=2=%.1f%% -> %s",
                 rw, (unsigned long long)n, (unsigned long long)tot,
                 (unsigned long long)h[0], (unsigned long long)h[1], (unsigned long long)h[2],
                 (unsigned long long)h[3], (unsigned long long)h[4], (unsigned long long)h[5],
                 medBin, p90Bin, fge2, pass ? "PASS (saut exploitable)" : "STOP (saut shallow)");
        }
    }

#ifdef BW_CHECKER_LEDGER
    if (cfg.checkerLedger) {
        logf("TSB CHECKER-AB: clean sigma vs sigma+checker (%d mask(s))", g_checkerActive);
        for (int ri = 0; ri < nr; ri++) {
            int rw = rungs[ri], gp = gaps[ri], pairs = rw >= 230 ? 10 : 1, reps = 2*pairs;
            uint64_t sN=0, sCut=0, cN=0, cCut=0; double sW=0, cW=0;
            uint64_t checkerCuts=0, checkerCalls=0;
            int sS=-1,cS=-1,sC=0,cC=0; bool sCap=false,cCap=false;
            auto arm = [&](bool checker) { uint64_t n,k; double w; int sc,co; bool cap;
                g_checkerTailOn=checker;
                runTail(rw,gp,initBest,true,false,false,&n,&k,&w,&sc,&co,&cap);
                if(checker){ cN=n;cCut=k;cW+=w;cS=sc;cC=co;cCap=cap;
                    checkerCuts=g_checkerCut.load();checkerCalls=g_checkerCalls.load(); }
                else { sN=n;sCut=k;sW+=w;sS=sc;sC=co;sCap=cap; } };
            for(int z=0;z<pairs;z++){ arm(false);arm(true);arm(true);arm(false); }
            sW/=reps; cW/=reps;
            double nodeRed=sN ? 100.0*(1.0-(double)cN/(double)sN):0.0;
            double wallX=cW>0 ? sW/cW:0.0;
            bool same=(sS==cS && sC==cC && sCap==cCap);
            logf("TSB CHECKER-AB r%d reps%d: sigma nodes=%llu wall=%.6fs | checker nodes=%llu wall=%.6fs red=%.2f%% wallX=%.3f cuts=%llu calls=%llu -> %s",
                 rw,reps,(unsigned long long)sN,sW,(unsigned long long)cN,cW,nodeRed,wallX,
                 (unsigned long long)checkerCuts,(unsigned long long)checkerCalls,
                 same ? "consistent" : "*** DIVERGENCE ***");
        }
        g_checkerTailOn = cfg.checkerLedger;
    }
#endif
    // -------- 3) REACHABILITY : le board (465) reste-t-il atteignable avec LBσ ON ? --------
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t offN, offCut, onN, onCut; double offW, onW; int offS, onS, offC, onC; bool offCap, onCap;
        runTail(rw, gp, boardBreaks + 1, false, false, false, &offN, &offCut, &offW, &offS, &offC, &offCap);
        // ON = LBσ + LBflux APPLIQUÉS : le board cible (465) doit rester atteignable (même score).
        runTail(rw, gp, boardBreaks + 1, true,  true,  true,  &onN,  &onCut,  &onW,  &onS,  &onC,  &onCap);
        const char* verdict = (offS == onS) ? (onS >= 0 ? "PASS (target reachable ON==OFF)"
                                                        : (offCap || onCap ? "inconclusive (capped)" : "both none"))
                                            : "*** LOST (ON != OFF) ***";
        logf("TSB REACH r%d gap%d : OFF score=%d nodes=%llu cap=%d | ON(sig+flux) score=%d nodes=%llu cap=%d -> %s",
             rw, gp, offS, (unsigned long long)offN, offCap, onS, (unsigned long long)onN, onCap, verdict);
    }
#ifdef BW_FLUX_LEDGER
    // -------- 2b) ORACLE LBflux : coupes EN PLUS des survivants LBσ (Gate A) --------
    // 3 runs/rung : (i) SIGMA propre (baseline nodes+wall, flux inerte) ; (ii) SHADOW (LBσ appliqué,
    // LBflux ÉVALUÉ mais non appliqué -> compte would-cut/calls sur l'ARBRE LBσ + coût ns/check) ;
    // (iii) FLUX (LBσ+LBflux appliqués -> réduction nodes/wall réelle). Gate A PASS si >=10% de morts
    // en plus parmi les survivants LBσ gated ET wall net positif (flux plus rapide que sigma seul).
    logf("TSB FLUX-ORACLE gate(remaining<=%d slack<=%d) : morts LBflux EN PLUS des survivants LBσ",
         g_fluxGateRemain, g_fluxGateSlack);
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t sN, sCut, shN, shCut, fN, fCut; double sW, shW, fW; int sS, shS, fS, sC, shC, fC; bool sCap, shCap, fCap;
        // (i) SIGMA propre
        runTail(rw, gp, initBest, true, false, false, &sN, &sCut, &sW, &sS, &sC, &sCap);
        // (ii) SHADOW : LBσ appliqué + LBflux évalué non appliqué
        runTail(rw, gp, initBest, true, true, false, &shN, &shCut, &shW, &shS, &shC, &shCap);
        uint64_t sigCalls = g_sigmaTailCalls.load(), fCalls = g_fluxCalls.load(), fWould = g_fluxWouldCut.load();
        uint64_t fStronger = g_fluxStronger.load(); int fMaxGain = g_fluxMaxGain.load();
        // (iii) FLUX : LBσ + LBflux appliqués
        runTail(rw, gp, initBest, true, true, true, &fN, &fCut, &fW, &fS, &fC, &fCap);
        uint64_t fCutApplied = g_fluxCut.load(), fLeafBug = g_fluxLeafBug.load();
        double pctExtra = fCalls ? 100.0 * (double)fWould / (double)fCalls : 0.0;   // % survivants LBσ gated tués
        double nodeRed  = sN ? 100.0 * (1.0 - (double)fN / (double)sN) : 0.0;        // réduction nodes σ->σ+flux
        double nsCheck  = fCalls ? 1e9 * (shW - sW) / (double)fCalls : 0.0;          // coût moyen d'un check LBflux
        double wallNet  = sW - fW;                                                   // >0 = flux plus rapide (gain)
        // soundness locale : flux ne doit jamais perdre un témoin que σ garde (fS >= sS quand σ trouve)
        bool unsound = fLeafBug || (sS >= 0 && fS < sS);
        bool gateA = !unsound && (pctExtra >= 10.0) && (wallNet > 0.0);
        const char* verdict = unsound ? "*** UNSOUND ***" : (gateA ? "GATE A PASS" : "GATE A FAIL (LBσ suffit)");
        logf("TSB FLUX-ORACLE r%d gap%d cells%d : fluxCalls=%llu stronger(LBflux>LBσ)=%llu maxGain=%d "
             "fluxWould=%llu (%.1f%% extra) fluxCut=%llu | nodes sig=%llu flux=%llu (red %.1f%%) | "
             "wall sig=%.3fs flux=%.3fs net=%+.3fs ns/check=%.0f leafBug=%llu -> %s",
             rw, gp, 256 - rw, (unsigned long long)fCalls, (unsigned long long)fStronger, fMaxGain,
             (unsigned long long)fWould, pctExtra, (unsigned long long)fCutApplied,
             (unsigned long long)sN, (unsigned long long)fN, nodeRed, sW, fW, wallNet, nsCheck,
             (unsigned long long)fLeafBug, verdict);
        (void)sigCalls;
    }
#endif
#ifdef BW_LBASSIGN_SHADOW
    // -------- 2c) ORACLE LBassign : coupes EN PLUS des survivants LBσ (LEVIER 3, PUR SHADOW) --------
    // Un run/rung, LBσ ON ; le shadow assign est évalué en interne sur chaque survivant LBσ à l'endgame
    // profond (remaining<=gate). On rapporte : #survivants évalués, #où LBa>LBσ, #would-cut-EN-PLUS,
    // maxGain, wall, ns/check. Aucune coupe appliquée (mêmes leaves/hash que sans le flag = soundness).
    logf("TSB ASSIGN-ORACLE gate(remaining<=%d) mode=%s dead0GateDet=%d : σ-clean / shadow / APPLIQUÉ (node-reduction + wall net)",
         BW_LBASSIGN_GATE_REMAIN, g_tsbDead0 ? "DEAD0" : "Hungarian", g_dead0GateDet);
    if (g_tsbDead0) g_assignMode = 4;   // P1 : tester DEAD0 (déficience 0-witness bitset) gaté par det
    for (int ri = 0; ri < (g_tsbSingletonOnly ? 0 : nr); ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t nSig, cSig, nSh, cSh, nAp, cAp; double wSig, wSh, wAp; int sSig, sSh, sAp, xSig, xSh, xAp; bool capSig, capSh, capAp;
        // (A) σ CLEAN : assign non évalué (0 overhead)
        g_assignEval = false; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &nSig, &cSig, &wSig, &sSig, &xSig, &capSig);
        // (B) SHADOW : évalué, non appliqué -> compteurs would-cut + ns/check
        g_assignEval = true; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &nSh, &cSh, &wSh, &sSh, &xSh, &capSh);
        uint64_t aCalls = g_assignCalls.load(), aStrong = g_assignStronger.load();
        uint64_t aWould = g_assignWouldCut.load(), aNs = g_assignNanos.load(); int aMax = g_assignMaxGain.load();
        // (C) APPLIQUÉ : σ + LBassign coupent -> réduction de nœuds + wall
        g_assignEval = true; g_assignApply = true; resetCtrs();
        g_dead0Probed = 0; g_dead0Found = 0;   // P1 : mesure cellules sondées / mortes sur la passe appliquée
        runTail(rw, gp, initBest, true, false, false, &nAp, &cAp, &wAp, &sAp, &xAp, &capAp);
        uint64_t d0probed = g_dead0Probed.load(), d0found = g_dead0Found.load();
        g_assignEval = true; g_assignApply = false;   // reset mode
        double pctExtra = aCalls ? 100.0 * (double)aWould / (double)aCalls : 0.0;
        double nsCheck  = aCalls ? (double)aNs / (double)aCalls : 0.0;
        double nodeRed  = nSig ? 100.0 * (1.0 - (double)nAp / (double)nSig) : 0.0;   // réduction σ -> σ+assign
        double wallNet  = wSig - wAp;                                                // >0 = assign PLUS RAPIDE
        // soundness locale : l'applied ne doit pas perdre un témoin que σ garde (sAp >= sSig quand σ trouve),
        // ni diverger si les deux épuisent.
        bool unsound = (sSig >= 0 && sAp < sSig) || (!capSig && !capAp && sSig != sAp);
        const char* verdict = unsound ? "*** UNSOUND ***"
                            : (pctExtra >= 5.0 && wallNet > 0.0) ? "NET PASS (extra>=5% & assign plus rapide)"
                            : (pctExtra >= 5.0) ? "SIGNAL>=5% mais wall net<=0 (coût mange le gain)"
                            : "signal<5%";
        logf("TSB ASSIGN-ORACLE r%d gap%d cells%d : survEval=%llu would-cut-extra=%llu (%.1f%%) maxGain=%d ns/check=%.0f | "
             "nodes σ=%llu applied=%llu (red %.1f%%) | wall σ=%.3fs applied=%.3fs net=%+.3fs | σcap=%d apCap=%d sc(σ=%d,ap=%d) -> %s",
             rw, gp, 256 - rw, (unsigned long long)aCalls, (unsigned long long)aWould, pctExtra, aMax, nsCheck,
             (unsigned long long)nSig, (unsigned long long)nAp, nodeRed, wSig, wAp, wallNet,
             capSig, capAp, sSig, sAp, verdict);
        (void)aStrong; (void)nSh; (void)cSig; (void)cSh; (void)cAp; (void)wSh; (void)sSh; (void)xSig; (void)xSh; (void)xAp;
        if (g_tsbDead0)
            logf("TSB DEAD0-GATE r%d det>=%d : cellules-sondées=%llu mortes=%llu deadCuts=%llu | nodes σ=%llu applied=%llu (red %.2f%%) | wallX=%.3f ns/check=%.0f",
                 rw, g_dead0GateDet, (unsigned long long)d0probed, (unsigned long long)d0found, (unsigned long long)aWould,
                 (unsigned long long)nSig, (unsigned long long)nAp, nodeRed, wAp > 1e-9 ? wSig / wAp : 0.0, nsCheck);
        // gating-test (2026-08-19) : distribution appels/coupes-marginales assign par classe lbDem.
        logf("TSB ASSIGN-GATE r%d : appels[c0..c5]=%llu/%llu/%llu/%llu/%llu/%llu | coupes-marg[c0..c5]=%llu/%llu/%llu/%llu/%llu/%llu",
             rw,
             (unsigned long long)g_assignCallClass[0].load(), (unsigned long long)g_assignCallClass[1].load(),
             (unsigned long long)g_assignCallClass[2].load(), (unsigned long long)g_assignCallClass[3].load(),
             (unsigned long long)g_assignCallClass[4].load(), (unsigned long long)g_assignCallClass[5].load(),
             (unsigned long long)g_assignCutClass[0].load(), (unsigned long long)g_assignCutClass[1].load(),
             (unsigned long long)g_assignCutClass[2].load(), (unsigned long long)g_assignCutClass[3].load(),
             (unsigned long long)g_assignCutClass[4].load(), (unsigned long long)g_assignCutClass[5].load());
    }
    // -------- 2d) LBASSIGN_DEFICIENCY (Codex) : rétention vs Hungarian + coût, puis A/B appliqué --------
    logf("TSB DEFICIENCY (K-M0, max-matching 0-coût) : rétention du signal Hungarian + ns/check, puis A/B");
    for (int ri = 0; ri < (g_tsbSingletonOnly ? 0 : nr); ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t n, cut; double w; int s, c; bool cap;
        // (1) COMPARE (mode 2) : Hungarian vs Déficience sur les MÊMES nœuds
        g_assignMode = 2; g_assignEval = true; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &n, &cut, &w, &s, &c, &cap);
        uint64_t calls = g_assignCalls.load(), hW = g_hungWould.load(), dW = g_defWould.load();
        uint64_t dR = g_defRetain.load(), dF = g_defFalse.load(), hNs = g_hungNanos.load(), dNs = g_defNanos.load();
        double retain = hW ? 100.0 * (double)dR / (double)hW : 0.0;
        double defNs = calls ? (double)dNs / (double)calls : 0.0, hungNs = calls ? (double)hNs / (double)calls : 0.0;
        logf("TSB DEF-COMPARE r%d gap%d cells%d : calls=%llu hungWould=%llu defWould=%llu retain=%llu (%.1f%% signal Hungarian) "
             "falsePrune=%llu | def=%.0fns/check hung=%.0fns/check",
             rw, gp, 256 - rw, (unsigned long long)calls, (unsigned long long)hW, (unsigned long long)dW,
             (unsigned long long)dR, retain, (unsigned long long)dF, defNs, hungNs);
        // (2) A/B DÉFICIENCE appliqué (mode 1) : node reduction + wall σ vs σ+déficience
        uint64_t nSg, cSg, nAp, cAp2; double wSg, wAp2; int sSg, sAp2, xSg, xAp2; bool capSg, capAp2;
        g_assignMode = 1;
        g_assignEval = false; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &nSg, &cSg, &wSg, &sSg, &xSg, &capSg);
        g_assignEval = true; g_assignApply = true; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &nAp, &cAp2, &wAp2, &sAp2, &xAp2, &capAp2);
        g_assignMode = 0; g_assignEval = true; g_assignApply = false;   // reset état
        double nodeRed = nSg ? 100.0 * (1.0 - (double)nAp / (double)nSg) : 0.0;
        double wallX = wAp2 > 1e-9 ? wSg / wAp2 : 0.0;
        bool unsound = (sSg >= 0 && sAp2 < sSg) || (!capSg && !capAp2 && sSg != sAp2);
        const char* verdict = unsound ? "*** UNSOUND ***" : (wallX >= 1.10) ? "WALL_PASS (>=1.10x)" : "wall<1.10x -> fermer L3";
        logf("TSB DEF-APPLY r%d gap%d cells%d : nodes σ=%llu def=%llu (red %.1f%%) | wall σ=%.3fs def=%.3fs wallX=%.2f | sc(σ=%d,def=%d) -> %s",
             rw, gp, 256 - rw, (unsigned long long)nSg, (unsigned long long)nAp, nodeRed, wSg, wAp2, wallX, sSg, sAp2, verdict);
        (void)n; (void)cut; (void)w; (void)s; (void)c; (void)cap; (void)xSg; (void)xAp2; (void)cSg; (void)cAp2;
    }
    // -------- 2e) HALL_WITNESS_SIZE (Codex) : le signal 30%% a-t-il un certificat local O(1) ? --------
    logf("TSB HALL-AUDIT : taille MIN du témoin de Hall par would-cut déficience (parmi <=12 cellules bas-degré, read-only)");
    for (int ri = 0; ri < (g_tsbSingletonOnly ? 0 : nr); ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t n, cut; double w; int s, c; bool cap;
        g_assignMode = 3; g_assignEval = true; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &n, &cut, &w, &s, &c, &cap);
        g_assignMode = 0;
        uint64_t H = g_hwitCuts.load();
        uint64_t s1 = g_hallS1.load(), s2 = g_hallS2.load(), s3 = g_hallS3.load(), s4 = g_hallS4.load();
        uint64_t s58 = g_hallS58.load(), sb = g_hallSbig.load();
        uint64_t d1 = g_hallDef1.load(), d2 = g_hallDef2.load(), d3 = g_hallDef3p.load(), hns = g_hallNanos.load();
        double le4 = H ? 100.0 * (double)(s1 + s2 + s3 + s4) / (double)H : 0.0;
        double le8 = H ? 100.0 * (double)(s1 + s2 + s3 + s4 + s58) / (double)H : 0.0;
        double auditNs = H ? (double)hns / (double)H : 0.0;
        const char* gate = (le4 >= 50.0 || le8 >= 80.0) ? "GATE PASS -> filtre O(1) <500ns envisageable" : "GATE FAIL -> HALL_FAMILY_NET_NULL";
        logf("TSB HALL-AUDIT r%d gap%d cells%d : cuts=%llu | |S| 1:%llu 2:%llu 3:%llu 4:%llu 5-8:%llu >8:%llu | <=4=%.1f%% <=8=%.1f%% | "
             "deficit 1:%llu 2:%llu 3+:%llu | %.0fns/audit -> %s",
             rw, gp, 256 - rw, (unsigned long long)H, (unsigned long long)s1, (unsigned long long)s2, (unsigned long long)s3,
             (unsigned long long)s4, (unsigned long long)s58, (unsigned long long)sb, le4, le8,
             (unsigned long long)d1, (unsigned long long)d2, (unsigned long long)d3, auditNs, gate);
        (void)n; (void)cut; (void)w; (void)s; (void)c; (void)cap;
    }
    // -------- 2f) FILTRE SINGLETON cheap (Codex) : A/B node-reduction + wall, cible <500ns/check --------
    logf("TSB DEAD0-BITSET : vérif équivalence vs scalaire (falsePrune) puis A/B ABBA (wall médian)");
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t n, cut; double w; int s, cc0; bool cap;
        // (0) VÉRIF : bitset == scalaire ? + ns/check + node-reduction
        g_assignMode = 4; g_assignEval = true; g_assignApply = false; g_dead0Verify = true; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &n, &cut, &w, &s, &cc0, &cap);
        uint64_t calls = g_assignCalls.load(), cuts = g_assignWouldCut.load(), ns = g_assignNanos.load(), fp = g_defFalse.load();
        g_dead0Verify = false;
        double nsCheck = calls ? (double)ns / (double)calls : 0.0;
        // (A/B ABBA) : σ, filt, filt, σ -> wall médian robuste
        double wS1, wF1, wF2, wS2; uint64_t nSg, nAp, dum; int sSg, sAp, xd; bool cS, cA;
        g_assignEval = false; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &nSg, &dum, &wS1, &sSg, &xd, &cS);
        g_assignEval = true;  g_assignApply = true;  resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &nAp, &dum, &wF1, &sAp, &xd, &cA);
        g_assignEval = true;  g_assignApply = true;  resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &dum, &dum, &wF2, &sAp, &xd, &cA);
        g_assignEval = false; g_assignApply = false; resetCtrs();
        runTail(rw, gp, initBest, true, false, false, &dum, &dum, &wS2, &sSg, &xd, &cS);
        g_assignMode = 0; g_assignEval = true; g_assignApply = false;
        double wSig = (wS1 + wS2) / 2.0, wFil = (wF1 + wF2) / 2.0;
        double nodeRed = nSg ? 100.0 * (1.0 - (double)nAp / (double)nSg) : 0.0;
        double wallX = wFil > 1e-9 ? wSig / wFil : 0.0;
        bool unsound = (sSg >= 0 && sAp < sSg) || (!cS && !cA && sSg != sAp) || fp > 0;
        const char* verdict = unsound ? "*** UNSOUND/falsePrune ***" : (wallX >= 1.10) ? "NET PASS (>=1.10x DÉPLOYABLE)"
                            : (nodeRed >= 10.0) ? "node-red ok mais wall<1.10x" : "signal faible";
        logf("TSB DEAD0-BITSET r%d gap%d cells%d : evalNodes=%llu cuts=%llu falsePrune=%llu ns/check=%.0f | nodes σ=%llu filt=%llu (red %.1f%%) | "
             "wall σ=%.3fs filt=%.3fs wallX=%.2f (ABBA) | sc(σ=%d,filt=%d) -> %s",
             rw, gp, 256 - rw, (unsigned long long)calls, (unsigned long long)cuts, (unsigned long long)fp, nsCheck,
             (unsigned long long)nSg, (unsigned long long)nAp, nodeRed, wSig, wFil, wallX, sSg, sAp, verdict);
        (void)n; (void)cut; (void)w; (void)s; (void)cc0; (void)cap;
    }
#endif
#ifdef BW_TAIL_FREELIST
    logf("TSB FREELIST : A/B ABBA node-cost (OFF=scan 1..256 vs ON=free-list), même arbre/nodes attendu");
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t nA, nB, nC, nD, cx; double wA, wB, wC, wD; int sx, xx; bool capx;
        g_tailFreeList = false; runTail(rw, gp, initBest, true, false, false, &nA, &cx, &wA, &sx, &xx, &capx);
        g_tailFreeList = true;  runTail(rw, gp, initBest, true, false, false, &nB, &cx, &wB, &sx, &xx, &capx);
        g_tailFreeList = true;  runTail(rw, gp, initBest, true, false, false, &nC, &cx, &wC, &sx, &xx, &capx);
        g_tailFreeList = false; runTail(rw, gp, initBest, true, false, false, &nD, &cx, &wD, &sx, &xx, &capx);
        g_tailFreeList = true;
        double wOff = (wA + wD) / 2.0, wOn = (wB + wC) / 2.0;
        double wallX = wOn > 1e-9 ? wOff / wOn : 0.0;
        bool sameTree = (nA == nB && nB == nC && nC == nD);
        logf("TSB FREELIST r%d gap%d cells%d : nodes OFF=%llu ON=%llu sameTree=%d | wall OFF=%.3fs ON=%.3fs wallX=%.2f -> %s",
             rw, gp, 256 - rw, (unsigned long long)nA, (unsigned long long)nB, sameTree ? 1 : 0, wOff, wOn, wallX,
             !sameTree ? "*** TREE CHANGED (bug) ***" : (wallX >= 1.05 ? "PASS (>=1.05x)" : "pas de gain net"));
    }
#endif
#if defined(BW_TAIL_FREELIST) && defined(BW_PRE_ROTATED)
    logf("TSB MICRO-COMBO : baseline vs free-list vs pre-rotated vs COMBO (même arbre, wallX, ABBA)");
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t nRef = 0;
        auto meas = [&](bool fl, bool pr) -> double {
            g_tailFreeList = fl; g_preRotated = pr;
            uint64_t n, c2; double w; int s2, x2; bool cap2;
            runTail(rw, gp, initBest, true, false, false, &n, &c2, &w, &s2, &x2, &cap2);
            if (!nRef) nRef = n; else if (n != nRef) nRef = 0xFFFFFFFFFFFFFFFFULL;   // détecte tout changement d'arbre
            return w;
        };
        double b1 = meas(0,0), f1 = meas(1,0), p1 = meas(0,1), c1 = meas(1,1);
        double c2 = meas(1,1), p2 = meas(0,1), f2 = meas(1,0), b2 = meas(0,0);
        g_tailFreeList = true; g_preRotated = true;
        double B = (b1+b2)/2, F = (f1+f2)/2, P = (p1+p2)/2, C = (c1+c2)/2;
        double xF = F>1e-9?B/F:0, xP = P>1e-9?B/P:0, xC = C>1e-9?B/C:0;
        bool sameTree = (nRef != 0xFFFFFFFFFFFFFFFFULL);
        logf("TSB MICRO-COMBO r%d gap%d cells%d : sameTree=%d | wall B=%.3f F=%.3f P=%.3f C=%.3f | wallX free=%.2f prerot=%.2f COMBO=%.2f | RAW b=[%.3f,%.3f] f=[%.3f,%.3f] p=[%.3f,%.3f] c=[%.3f,%.3f] -> %s",
             rw, gp, 256 - rw, sameTree?1:0, B, F, P, C, xF, xP, xC,
             b1, b2, f1, f2, p1, p2, c1, c2,
             !sameTree ? "*** TREE CHANGED ***" : (xC >= 1.05 ? "COMBO PASS (>=1.05x)" : "combo<1.05x"));
    }
#endif
#ifdef BW_TAIL_PROFILE
    logf("TSB PROFILE : ventilation cycles par phase du tail (masqué), par rung");
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t n, cut; double w; int s, c; bool cap;
        g_genCycles = 0; g_totalTailCycles = 0; g_cMrv = 0; g_cMaskSetup = 0; g_cPlace = 0; g_cLeaf = 0; g_tmCalls = 0; g_tmLeaves = 0; g_cDead = 0;
        runTail(rw, gp, initBest, true, false, false, &n, &cut, &w, &s, &c, &cap);
        double T = (double)g_totalTailCycles.load(); if (T < 1) T = 1;
        double mrv = (double)g_cMrv.load(), setup = (double)g_cMaskSetup.load(), gen = (double)g_genCycles.load();
        double en = gen - setup; if (en < 0) en = 0;
        double place = 2.0 * (double)g_cPlace.load();
        double leaf = (double)g_cLeaf.load();
        double rest = T - (mrv + setup + en + place + leaf); if (rest < 0) rest = 0;
        uint64_t calls = g_tmCalls.load(), leaves = g_tmLeaves.load(); uint64_t cd = calls ? calls : 1;
        uint64_t lbcut = g_sigmaTailCut.load();   // entryLbCuts : entrées coupées par LBσ (sigmaOn)
        uint64_t deadEntries = calls - n;         // entrées qui n'ont pas développé (calls - expandedNodes)
        double deadCyc = (double)g_cDead.load();  // cycles TOTAUX dans les entrées mortes (entrée->coupe)
        logf("TSB PROFILE-HOIST r%d : deadEntries cycles=%.0fMc = %.1f%% du total | dont ~popcount ledger RESTE (déplacé), "
             "seul call+guard ~éliminable (~40%% de deadCyc) -> plafond Amdahl hoist ~%.1f%%",
             rw, deadCyc / 1e6, 100 * deadCyc / T, 0.40 * 100 * deadCyc / T);
        logf("TSB PROFILE r%d gap%d cells%d : total=%.0fMc | MRV %.1f%% | maskSetup %.1f%% | enum+sDelta %.1f%% | place(x2) %.1f%% | "
             "leaf/verify %.1f%% | rest %.1f%% || recEntries=%llu expandedNodes=%llu entryLbCuts=%llu deadEntries=%llu (%.1f%% des entrées) leaves=%llu cyc/call=%.0f",
             rw, gp, 256 - rw, T / 1e6, 100 * mrv / T, 100 * setup / T, 100 * en / T, 100 * place / T, 100 * leaf / T, 100 * rest / T,
             (unsigned long long)calls, (unsigned long long)n, (unsigned long long)lbcut, (unsigned long long)deadEntries, 100.0 * (double)deadEntries / (double)cd, (unsigned long long)leaves, T / (double)cd);
    }
#endif
#ifdef BW_TAIL_PLACEMENT_MASK
    logf("TSB MASK-AB : A/B ABBA gen bitmap (mask) vs scan+sort (combo), >=0.2s/échantillon (répété)");
    auto measRep = [&](int rw, int gp, bool useMask, uint64_t* nout) -> double {
        g_useMask = useMask;
        double acc = 0; int it = 0; uint64_t n = 0, cut; double w; int s, x; bool cap;
        while (acc < 0.2 && it < 5000) { runTail(rw, gp, initBest, true, false, false, &n, &cut, &w, &s, &x, &cap); acc += w; it++; }
        *nout = n; return acc / (it > 0 ? it : 1);   // wall par itération
    };
    for (int ri = 0; ri < nr; ri++) {
        int rw = rungs[ri], gp = gaps[ri];
        uint64_t nA, nB, nC, nD;
        double sA = measRep(rw, gp, false, &nA);   // scan
        double mB = measRep(rw, gp, true,  &nB);   // mask
        double mC = measRep(rw, gp, true,  &nC);   // mask
        double sD = measRep(rw, gp, false, &nD);   // scan
        g_useMask = true;
        double wScan = (sA + sD) / 2.0, wMask = (mB + mC) / 2.0;
        double wallX = wMask > 1e-12 ? wScan / wMask : 0.0;
        bool sameTree = (nA == nB && nB == nC && nC == nD);
        logf("TSB MASK-AB r%d gap%d cells%d : nodes scan=%llu mask=%llu sameTree=%d | wall/iter scan=%.6fs mask=%.6fs wallX=%.2f | "
             "RAW scan=[%.6f,%.6f] mask=[%.6f,%.6f] -> %s",
             rw, gp, 256 - rw, (unsigned long long)nA, (unsigned long long)nB, sameTree ? 1 : 0, wScan, wMask, wallX,
             sA, sD, mB, mC, !sameTree ? "*** TREE CHANGED ***" : (wallX >= 1.10 ? "MASK PASS (>=1.10x)" : (wallX >= 1.05 ? "faible" : "pas de gain")));
    }
#endif
    return 0;
}
#endif

int main(int argc, char** argv) {
    if (argc < 3) {
        fprintf(stderr,
                "usage: %s <pieces.txt> <hints.txt> [--threads N] [--seconds S] "
                "[--seed X] [--breaks \"i,j,...\"] [--node-cap N] [--heur-scale F] "
                "[--min-save S] [--save-dir D] [--prune NODES:DEPTH] "
                "[--tail-mrv DEPTH:NODES] [--tail-target-score SCORE] "
                "[--tail-period N] [--tail-adaptive] [--ring-breaks DEPTH] "
                "[--tail-min-slack S] [--exact-endgame DEPTH:NODES] [--endgame-probe E] "
                "[--bench]\n",
                argv[0]);
        return 1;
    }
    cfg.piecesFile = argv[1];
    cfg.hintsFile = argv[2];
    for (int i = 3; i < argc; i++) {
        std::string a = argv[i];
        auto next = [&]() -> const char* {
            if (++i >= argc) die("missing value for %s", a.c_str());
            return argv[i];
        };
        if (a == "--threads") cfg.threads = atoi(next());
        else if (a == "--seconds") cfg.seconds = atol(next());
#ifdef BW_HOTMAIN
        else if (a == "--hot-main-capture") { g_hmOut = next(); g_hmOn = true;
            for (int d : {208, 216, 221, 225, 229, 233}) g_hmTarget[d] = true; }
        else if (a == "--hot-stride") g_hmStride = atol(next());
        else if (a == "--hot-per-stratum") g_hmPerStratum = (size_t)atol(next());
#endif
        else if (a == "--seed") cfg.seed = strtoull(next(), nullptr, 10);
        else if (a == "--breaks") { cfg.breaks = next(); cfg.breaksSet = true; }
        else if (a == "--node-cap") cfg.nodeCap = (uint64_t)atof(next());
        else if (a == "--heur-scale") { cfg.heurScale = atof(next()); cfg.heurSet = true; }
        else if (a == "--min-save") cfg.minSave = atoi(next());
        else if (a == "--save-dir") cfg.saveDir = next();
        else if (a == "--prune") {
            const char* v = next();
            cfg.pruneNodes = (uint64_t)atof(v);
            const char* colon = strchr(v, ':');
            if (!colon) die("--prune wants NODES:DEPTH");
            cfg.pruneDepth = atoi(colon + 1);
        } else if (a == "--bench") { cfg.bench = true; }
        else if (a == "--stats") { cfg.stats = true; }
        else if (a == "--pool-log") cfg.poolLog = next();
        else if (a == "--ticket-log") cfg.ticketLogDir = next();
        else if (a == "--ticket-log-flush") cfg.ticketFlushSec = atoi(next());
        else if (a == "--heur-colors") cfg.heurColors = next();
        else if (a == "--sd-prune") cfg.sdPrune = true;
        else if (a == "--sigma-tail") cfg.sigmaTail = true;        // LBσ tail-solver (default ON)
        else if (a == "--no-sigma-tail") cfg.sigmaTail = false;
        else if (a == "--sigma-main") cfg.sigmaMain = true;        // LBσ DFS large (default OFF)
        else if (a == "--no-sigma-main") cfg.sigmaMain = false;
        else if (a == "--sigma-main-shadow") cfg.sigmaMainShadow = true;   // audit seul
        else if (a == "--sigma-ledger") { cfg.sigmaTail = true; cfg.sigmaMain = true; }   // alias legacy = tail+main (ambigu, éviter en prod/cloud)
        else if (a == "--dem-sigma-joint") cfg.demSigmaJoint = true;   // LBdemSigma (handoff 2026-08-18) : coupe conjointe déficit+parité (défaut OFF)
        else if (a == "--dem-sigma-gate") cfg.demSigmaGate = atoi(next());   // A adaptatif (2026-08-19) : porte lbDem >= T
        else if (a == "--flux-ledger") cfg.fluxLedger = true;     // LBflux : active la coupe directionnelle (binaire BW_FLUX_LEDGER)
        else if (a == "--checker-ledger") cfg.checkerLedger = true;
        else if (a == "--checker-masks") cfg.checkerMasks = atoi(next());
        else if (a == "--checker-remain") cfg.checkerRemain = atoi(next());
        else if (a == "--flux-gate-remain") cfg.fluxGateRemain = atoi(next());
        else if (a == "--flux-gate-slack") cfg.fluxGateSlack = atoi(next());
        else if (a == "--isolated-breaks") cfg.isolatedBreaks = true;
        else if (a == "--double-breaks") cfg.cellBreaks = 2;
        else if (a == "--fill-order") cfg.fillOrder = next();
        else if (a == "--board-order") cfg.boardOrderFile = next();
        else if (a == "--frontier-audit") cfg.frontierAudit = atoi(next());
        else if (a == "--lb-oracle") cfg.lbOracle = true;
        else if (a == "--budget-lb") { std::string m = next(); cfg.budgetLB = (m == "color" ? 2 : m == "shadow" ? 1 : 0); }
        else if (a == "--budget-lb-min-depth") cfg.budgetLbMinDepth = atoi(next());
        else if (a == "--budget-lb-max-slack") cfg.budgetLbMaxSlack = atoi(next());
        else if (a == "--dump-first3x3") { cfg.dump3x3 = true; cfg.dump3x3Path = next(); }
        else if (a == "--enum-3x3") { cfg.enum3x3Path = next(); }
        else if (a == "--force-root") { cfg.forceRoot = true; cfg.forceRootPath = next(); }
        else if (a == "--force-jitters") { cfg.forceJitters = strtoull(next(), nullptr, 10); }
        else if (a == "--force-interleave") { cfg.forceInterleave = true; }
        else if (a == "--shard-index") cfg.shardIndex = atoi(next());
        else if (a == "--shard-count") cfg.shardCount = atoi(next());
        else if (a == "--force-jitter-start") cfg.forceJitterStart = atoi(next());
        else if (a == "--skip-ledger") cfg.skipLedgerPath = next();
        else if (a == "--root-allow") cfg.rootAllowPath = next();
        else if (a == "--break-mask") cfg.breakMaskPath = next();
        else if (a == "--epoch") cfg.campaignEpoch = next();
        else if (a == "--harvest-fault") cfg.harvestFault = next();
        else if (a == "--harvest-selftest") cfg.harvestSelftest = next();
        else if (a == "--harvest-check") cfg.harvestCheckFile = next();
        else if (a == "--capture-dir") { cfg.captureDir = next(); }
        else if (a == "--capture-arm") { cfg.captureArm = next(); }
        else if (a == "--shadow-r224") { cfg.shadowR224 = true; }
        else if (a == "--tourney") { cfg.tourneyPath = next(); }
        else if (a == "--tourney-sync-lines") { cfg.tourneySyncLines = atoi(next()); }
        else if (a == "--capture-gap3") { cfg.capture3Dir = next(); }
        else if (a == "--harvest463") { cfg.harvest463Dir = next(); }
        else if (a == "--probe240-in") { cfg.probe240In = next(); }
        else if (a == "--probe240-out") { cfg.probe240Out = next(); }
        else if (a == "--probe240-cap") { cfg.probe240Cap = atol(next()); }
        else if (a == "--probe240-gap") { cfg.probe240Gap = atoi(next()); }
        else if (a == "--tail-mrv") {
            const char* v = next();
            const char* colon = strchr(v, ':');
            if (!colon) die("--tail-mrv wants DEPTH:NODES");
            cfg.tailDepth = atoi(v);
            cfg.tailNodes = (uint64_t)atof(colon + 1);
        }
        else if (a == "--tail-target-score") cfg.tailTargetScore = atoi(next());
        else if (a == "--tail-period") cfg.tailPeriod = (uint64_t)atof(next());
        else if (a == "--tail-adaptive") cfg.tailAdaptive = true;
        else if (a == "--ring-breaks") cfg.ringDepth = atoi(next());
        else if (a == "--tail-min-slack") cfg.tailMinSlack = atoi(next());
        else if (a == "--exact-endgame") {
            const char* v = next();
            const char* colon = strchr(v, ':');
            if (!colon) die("--exact-endgame wants DEPTH:NODES");
            cfg.endgameDepth = atoi(v);
            cfg.endgameNodes = (uint64_t)atof(colon + 1);
        }
        else if (a == "--endgame-probe") cfg.endgameProbeExtra = atoi(next());
        else if (a == "--endgame-sample") cfg.endgameSample = atoi(next());
        else if (a == "--endgame-ladder") {
            std::string spec = next();
            for (char& ch : spec) if (ch == ',') ch = ' ';
            const char* q = spec.c_str();
            while (*q) {
                while (*q == ' ') q++;
                if (!*q) break;
                int g = 0, rw = 0; double nd = 0;
                if (sscanf(q, "%d:%d:%lf", &g, &rw, &nd) != 3)
                    die("--endgame-ladder wants GAP:REWIND:NODES[,GAP:REWIND:NODES...]");
                cfg.ladder.push_back({g, rw, (uint64_t)nd});
                while (*q && *q != ' ') q++;
            }
        }
        else if (a == "--tail-slice") {
            if (sscanf(next(), "%d:%d:%d", &cfg.tsS, &cfg.tsN, &cfg.tsRewind) != 3)
                die("--tail-slice wants S:N:REWIND (candidate class S of N at rung rewind==REWIND)");
        }
        else if (a == "--capture-rung") {   // P7-A: REWIND:PATH
            std::string v = next();
            size_t c = v.find(':');
            if (c == std::string::npos) die("--capture-rung wants REWIND:PATH");
            cfg.captureRung = atoi(v.substr(0, c).c_str());
            cfg.capturePath = v.substr(c + 1);
        }
        else if (a == "--replay-tail") { cfg.replayPath = next(); }
        else if (a == "--replay-board") { cfg.replayBoardPath = next(); }
        else if (a == "--tail-sigma-bench") { cfg.tailSigmaBench = next(); }
#ifdef BW_CUT_SNAPSHOT
        else if (a == "--cut-snapshot") { cfg.cutSnapBoard = next(); cfg.cutSnapOut = next(); }
        else if (a == "--cut-stride") { cfg.cutStride = atol(next()); }
        else if (a == "--cut-per-rung") { cfg.cutPerRung = atol(next()); }
        else if (a == "--cut-nodecap") { cfg.cutNodeCap = strtoull(next(), nullptr, 10); }
        else if (a == "--cut-rungs") { cfg.cutRungs = next(); }
#endif
#ifdef BW_ENUM_NCON2_DIRECT
        else if (a == "--ncon2-direct") { g_ncon2Direct = atoi(next()) != 0; }
#endif
#ifdef BW_MRV_DEM_INCREMENTAL
        else if (a == "--mrv-dem-inc") { g_mrvDemInc = atoi(next()) != 0; }
#endif
        else if (a == "--tsb-rungs") { cfg.tsbRungs = next(); }
        else if (a == "--tsb-target") { cfg.tsbTarget = atoi(next()); }
        else if (a == "--tsb-cap") { cfg.tsbCap = strtoull(next(), nullptr, 10); }
        else if (a == "--tsb-enum-rewind") { cfg.tsbEnumRewind = atoi(next()); }
        else if (a == "--tsb-enum-budget") { cfg.tsbEnumBudget = atoi(next()); }
        else if (a == "--tsb-initbest") { cfg.tsbInitBest = atoi(next()); }
#ifdef BW_LBASSIGN_SHADOW
        else if (a == "--tsb-singleton-only") { g_tsbSingletonOnly = true; }
        else if (a == "--dead0-gate-det") { g_dead0GateDet = atoi(next()); }   // P1 (2026-08-19) : porte det pour DEAD0
        else if (a == "--tsb-dead0") { g_tsbDead0 = true; }                    // P1 : bench ASSIGN-ORACLE en mode DEAD0 (4)
        else if (a == "--trace-backjump") { g_traceBackjump = true; }          // P3 (2026-08-19) : trace read-only de profondeur de saut
        else if (a == "--r216-trace") { g_r216trace = true; g_r216traceOut = next(); }  // P17 opt-2 : télémétrie entrées bande r216
        else if (a == "--elite-slice-trace") { g_eliteTrace = true; g_eliteTraceOut = next();   // P-ELITE opt-1
            g_eliteVisits = new std::atomic<uint32_t>[ELITE_IDXN](); g_eliteNCand = new uint16_t[ELITE_IDXN](); }
        else if (a == "--elite-tiles") { g_eliteTilesPath = next(); }             // P-ELITE : hot_main_tiles_531
        else if (a == "--elite-corpus-list") { g_eliteCorpusList = next(); }       // P-ELITE : list-file boards 463
        else if (a == "--elite-replay") { g_eliteReplayList = next(); }            // P-ELITE : self-check .291 sur boards 465
        else if (a == "--elite-order") { g_eliteOrderOn = true; }                  // P-ELITE : APPLIQUE les vues (ON)
        else if (a == "--elite-ref") { g_eliteRefMode = true; }                    // P-ELITE : REF (calcule vues, itère OFF, bit-identique)
        else if (a == "--elite-check") { g_eliteCheck = true; }                    // P-ELITE : vérif multiset OFF==ON par nœud 9-31
        else if (a == "--tel") { g_telOn = true; }                                 // P-TEL option C : télémétrie passive slack4
        else if (a == "--tel-out") { g_telOut = next(); }                          // P-TEL : fichier événements+expo
        else if (a == "--tel-ckpt-events") { g_telCkptEvents = (uint64_t)atoll(next()); }   // P-TEL : seuil checkpoint (défaut 2000)
        else if (a == "--tel-ckpt-sec") { g_telCkptSec = atoi(next()); }   // P-TEL : checkpoint temporel (défaut 30s ; 0=off)
#endif
        else if (a == "--replay-cubes") {   // DEPTH:WORKERS (needs --replay-tail PATH)
            if (sscanf(next(), "%d:%d", &cfg.cubeDepth, &cfg.cubeWorkers) != 2)
                die("--replay-cubes wants DEPTH:WORKERS");
        }
        else if (a == "--capture-inbox") { cfg.captureInbox = next(); }
        else if (a == "--shard") {   // LO:HI cube index range (with --replay-tail + --replay-cubes DEPTH:_)
            if (sscanf(next(), "%ld:%ld", &cfg.shardLo, &cfg.shardHi) != 2)
                die("--shard wants LO:HI (cube index range)");
        }
        else if (a == "--count-cubes") { cfg.countCubes = true; }
        else if (a == "--replay-p8b") { cfg.p8Journal = next(); }
        else if (a == "--terminal-manifest") { cfg.terminalManifest = next(); }
        else if (a == "--terminal-selftest") { cfg.terminalSelftest = next(); }
        else if (a == "--defer-selftest") { cfg.deferSelftest = next(); }
        else if (a == "--chain-selftest") { cfg.chainSelftest = next(); }
        else if (a == "--verify-board") { cfg.verifyBoardFile = next(); }
        else if (a == "--defer-inbox") { cfg.deferInbox = true; }
        else if (a == "--defer-chain") { cfg.deferChain = true; }
        else if (a == "--p8-heartbeat") { cfg.p8Heartbeat = next(); }
        else if (a == "--write-heartbeat") { cfg.writeHeartbeat = next(); }
        else if (a == "--hb-workers") { cfg.hbWorkers = atoi(next()); }
        else if (a == "--attempt-state") { cfg.attemptState = next(); }
        else if (a == "--attempt-selftest") { cfg.attemptSelftest = true; }
        else if (a == "--backfill-proof") { cfg.backfillProof = next(); }
        else if (a == "--backfill-journal") { cfg.backfillJournal = next(); }
        else if (a == "--r216-gate") { cfg.r216Gate = next(); }
        else if (a == "--make-chain") { cfg.makeChainSnap = next(); }
        else if (a == "--chain-out") { cfg.chainOut = next(); }
        else if (a == "--replay-chain") { cfg.replayChainPath = next(); }
        else if (a == "--chain-workdir") { cfg.chainWorkdir = next(); }
        else if (a == "--chain-cap216") { cfg.chainCap216 = (uint64_t)atoll(next()); }
        else if (a == "--p8b-sample") { g_p8bSample = atol(next()); }
        else if (a == "--p8b-queue-cap") { g_p8bQueueCap = (size_t)atol(next()); }
        else if (a == "--p8b-lowwater") { g_p8bLowWater = (uint64_t)atoll(next()); }
        else if (a == "--p8b-total-cap") { cfg.p8bTotalCapCli = (uint64_t)atoll(next()); }
        else if (a == "--endgame-escalate" || a == "--endgame-escalate2") {
            const char* v = next();
            int g = 0, rw = 0; double nd = 0;
            if (sscanf(v, "%d:%d:%lf", &g, &rw, &nd) != 3)
                die("%s wants GAP:REWIND:NODES", a.c_str());
            cfg.ladder.push_back({g, rw, (uint64_t)nd});
        }
        else if (a == "--yield-budget") {
            const char* v = next();
            const char* colon = strchr(v, ':');
            if (!colon) die("--yield-budget wants BASE:PER");
            cfg.yieldBase = (uint64_t)atof(v);
            cfg.yieldPer = (uint64_t)atof(colon + 1);
        }
        else die("unknown arg %s", a.c_str());
    }
    if (cfg.bench) { cfg.threads = 1; if (!cfg.seconds) cfg.seconds = 20; }

    if (cfg.isolatedBreaks && cfg.cellBreaks > 1)
        die("--isolated-breaks and --double-breaks are mutually exclusive");
    if (cfg.tailDepth && (cfg.tailDepth < 1 || cfg.tailDepth > 255 || !cfg.tailNodes))
        die("--tail-mrv depth must be 1..255 and nodes must be positive");
    if (cfg.tailTargetScore < -1 || cfg.tailTargetScore > 480)
        die("--tail-target-score must be 0..480");
    if (cfg.tailTargetScore >= 0 && !cfg.tailDepth)
        die("--tail-target-score requires --tail-mrv");
    if (cfg.tailAdaptive && !cfg.tailDepth)
        die("--tail-adaptive requires --tail-mrv");
    if (cfg.ringDepth && (cfg.ringDepth <= MAX_HEUR_IDX || cfg.ringDepth > 255))
        die("--ring-breaks depth must be %d..255 (the exhaustion ramp owns the "
            "earlier cells)", MAX_HEUR_IDX + 1);
    if (cfg.tailMinSlack < 0 || cfg.tailMinSlack > 20)
        die("--tail-min-slack must be 0..20");
    if (cfg.endgameDepth &&
        (cfg.endgameDepth < 200 || cfg.endgameDepth > 255 || !cfg.endgameNodes))
        die("--exact-endgame depth must be 200..255 with a positive node cap");
    if (cfg.endgameProbeExtra < 0 || cfg.endgameProbeExtra > 20)
        die("--endgame-probe must be 0..20");
    if (cfg.endgameProbeExtra && !cfg.endgameDepth)
        die("--endgame-probe requires --exact-endgame");
    if (cfg.endgameSample < 0) die("--endgame-sample must be >= 0");
    if (cfg.endgameSample && !cfg.endgameProbeExtra)
        die("--endgame-sample requires --endgame-probe");
    if (!cfg.ladder.empty()) {
        if (!cfg.endgameDepth) die("--endgame-ladder requires --exact-endgame");
        if ((int)cfg.ladder.size() > ThreadStats::MAX_RUNGS)
            die("--endgame-ladder supports at most %d rungs", ThreadStats::MAX_RUNGS);
        if (cfg.endgameSample)
            die("--endgame-ladder and --endgame-sample are mutually exclusive");
        int prevRewind = cfg.endgameDepth;
        for (const Config::EscRung& r : cfg.ladder) {
            if (cfg.endgameProbeExtra < r.gap)
                die("ladder rung gap %d needs --endgame-probe >= %d so the cheaper "
                    "pass can see how close it came", r.gap, r.gap);
            if (r.rewind < 180 || r.rewind >= prevRewind || !r.nodes)
                die("ladder rewinds must strictly deepen (180..%d) with a positive "
                    "node cap", prevRewind - 1);
            prevRewind = r.rewind;
        }
    }
    mkdir(cfg.saveDir.c_str(), 0755);
    g_log = fopen((cfg.saveDir + "/bw.log").c_str(), "a");

    loadPieces(cfg.piecesFile);
#ifdef BW_PRE_ROTATED
    buildPreRotated();   // OBLIGATOIRE avant tout tail-solver : sinon g_face non-init -> tailFace renvoie 0 (BUG canary)
#endif
#ifdef BW_TAIL_PLACEMENT_MASK
    buildPlacementMasks();   // OBLIGATOIRE (leçon g_face) : tables placements init dans le VRAI solveur aussi
#endif
    if (!cfg.heurColors.empty()) {
        HEUR_COLORS.clear();
        std::string s = cfg.heurColors;
        for (char& ch : s) if (ch == ',') ch = ' ';
        const char* q = s.c_str();
        char* end = nullptr;
        while (*q) {
            long v = strtol(q, &end, 10);
            if (end == q) break;
            if (v < 1 || v >= NCOLORS) die("bad heuristic color %ld", v);
            HEUR_COLORS.push_back((int)v);
            q = end;
        }
        if (HEUR_COLORS.empty()) die("no heuristic colors parsed");
    }
    computeHsc();
    loadHints(cfg.hintsFile);
    applyClueMode();
    buildStaticArrays();
    if (g_eliteOrderOn || g_eliteRefMode) {   // P-ELITE boot : charge faces + corpus (shared read-only), calcule les 23 cells
        setupEliteCells();
        if (!loadHot531(g_eliteTilesPath.c_str())) { logf("ELITE boot hot531 FAIL -> DÉSACTIVÉ"); g_eliteOrderOn = g_eliteRefMode = false; }
        else if (!loadEliteCorpus(g_eliteCorpusList.c_str())) { logf("ELITE boot corpus FAIL -> DÉSACTIVÉ"); g_eliteOrderOn = g_eliteRefMode = false; }
        else logf("ELITE boot OK: order=%d ref=%d corpus=%zu VMAX=%d", g_eliteOrderOn, g_eliteRefMode, g_corpus.size(), ELITE_VMAX);
    }
    if (g_telOn && !g_telOut.empty()) {   // P-TEL : ouvre le fichier (header schéma + provenance)
        g_telRunId = (((uint64_t)getpid()) << 20) ^ (uint64_t)time(nullptr);   // identité du run (fichiers par run -> dédup)
        // crash-gate : fichier V-events PER-RUN (run_id dans le nom) -> un restart n'écrase PAS les events du run précédent.
        // Framing : chaque event est une ligne '\n'-terminée ; l'agrégateur ignore une dernière ligne incomplète (crash).
        char evpath[700]; snprintf(evpath, sizeof evpath, "%s.r%llu.events", g_telOut.c_str(), (unsigned long long)g_telRunId);
        g_telEventF = fopen(evpath, "w");
        if (g_telEventF) fprintf(g_telEventF, "# TEL v1 schema=slack4-creditC run=%llu seed=%llu roots=%s epoch=%s threads=%d\n"
            "# V slack root ticket key:p.r(x23) | E idx piece rot chosen gnodes closed censored r244 s4 s5\n",
            (unsigned long long)g_telRunId, (unsigned long long)cfg.seed, cfg.forceRootPath.c_str(), cfg.campaignEpoch.c_str(), cfg.threads);
        else { logf("TEL open FAIL %s -> désactivé", evpath); g_telOn = false; }
    }
#ifdef BW_SIGMA_LEDGER
    g_sigmaTailOn = cfg.sigmaTail;   // le ladder prod (solveTailMrv) honore --sigma-tail (default ON)
    g_demSigmaOn = cfg.demSigmaJoint;   // LBdemSigma (handoff 2026-08-18) : OFF par défaut, le bench le bascule
    g_demSigmaGate = cfg.demSigmaGate;  // A adaptatif (2026-08-19) : porte lbDem >= T (0 = pas de porte)
#ifdef BW_CHECKER_LEDGER
    buildCheckerWeights();
    if (cfg.checkerMasks < 1 || cfg.checkerMasks > CHECKER_N) die("--checker-masks wants 1..5");
    g_checkerActive = cfg.checkerMasks;
    if (cfg.checkerRemain < 1 || cfg.checkerRemain > 64) die("--checker-remain wants 1..64");
    g_checkerGateRemain = cfg.checkerRemain;
    g_checkerTailOn = cfg.checkerLedger;
    if (g_checkerTailOn) logf("LBchecker: ON tail, %d projection(s), gate remaining<=%d slack-after-sigma<=2", g_checkerActive, g_checkerGateRemain);
#endif
#ifdef BW_FLUX_LEDGER
    g_fluxTailOn = cfg.fluxLedger;
    g_fluxGateRemain = cfg.fluxGateRemain;
    g_fluxGateSlack = cfg.fluxGateSlack;
    buildFluxLedger();
#endif
    if (!cfg.replayBoardPath.empty()) return sigmaReplayBoards(cfg.replayBoardPath);
#ifdef BW_CUT_SNAPSHOT
    if (!cfg.cutSnapBoard.empty()) return cutSnapshotDump(cfg);
#endif
    if (!g_eliteReplayList.empty()) {   // P-ELITE self-check : reproduit .291 en C++ (valide frame+score)
        if (!loadHot531(g_eliteTilesPath.c_str())) return 2;
        if (!loadEliteCorpus(g_eliteCorpusList.c_str())) return 2;
        return eliteReplay(g_eliteReplayList.c_str());
    }
    if (!cfg.tailSigmaBench.empty()) return tailSigmaBench(cfg);
#endif
    if (cfg.sdPrune) logf("supply/demand prune: ON");
    if (cfg.tailDepth) {
        if (cfg.tailTargetScore >= 0)
            logf("tail MRV: depth %d (%d cells), node cap %.1fM, period %.1fM hot "
                 "nodes, target %d, official-score seams", cfg.tailDepth,
                 256 - cfg.tailDepth, cfg.tailNodes / 1e6,
                 cfg.tailPeriod / 1e6, cfg.tailTargetScore);
        else
            logf("tail MRV: depth %d (%d cells), node cap %.1fM, period %.1fM hot "
                 "nodes, target generator-budget, official-score seams", cfg.tailDepth,
                 256 - cfg.tailDepth, cfg.tailNodes / 1e6,
                 cfg.tailPeriod / 1e6);
    }
    if (cfg.tailAdaptive)
        logf("adaptive MRV: %d->%d@%.0fM, %d->%d@%.0fM, "
             "%d->%d@%.0fM, %d->%d@%.0fM",
             ADAPTIVE_TAIL_TIERS[0].triggerDepth, ADAPTIVE_TAIL_TIERS[0].rewindDepth,
             ADAPTIVE_TAIL_TIERS[0].nodeCap / 1e6,
             ADAPTIVE_TAIL_TIERS[1].triggerDepth, ADAPTIVE_TAIL_TIERS[1].rewindDepth,
             ADAPTIVE_TAIL_TIERS[1].nodeCap / 1e6,
             ADAPTIVE_TAIL_TIERS[2].triggerDepth, ADAPTIVE_TAIL_TIERS[2].rewindDepth,
             ADAPTIVE_TAIL_TIERS[2].nodeCap / 1e6,
             ADAPTIVE_TAIL_TIERS[3].triggerDepth, ADAPTIVE_TAIL_TIERS[3].rewindDepth,
             ADAPTIVE_TAIL_TIERS[3].nodeCap / 1e6);

    // resume best score
    {
        FILE* f = fopen((cfg.saveDir + "/best_score.txt").c_str(), "r");
        if (f) {
            int b = 0;
            if (fscanf(f, "%d", &b) == 1) g_bestScore = b;
            fclose(f);
        }
    }

    // P13 sharding : validation STRICTE (0 <= I < N). Codex bloqueur #1 : JAMAIS corriger
    // silencieusement une config de flotte (un clamp -1->0 = deux workers sur shard 0 = doublon).
    // Toute valeur invalide => die() non-zéro pour arrêter la VM avant tout calcul.
    if (cfg.shardCount < 1)
        die("--shard-count doit etre >= 1 (recu %d)", cfg.shardCount);
    if (cfg.shardIndex < 0)
        die("--shard-index doit etre >= 0 (recu %d)", cfg.shardIndex);
    if (cfg.shardIndex >= cfg.shardCount)
        die("--shard-index (%d) doit etre < --shard-count (%d)", cfg.shardIndex, cfg.shardCount);
    // Codex #4 : le sharding n'est implémenté QUE pour force-root+force-interleave.
    // Sans ces deux flags, N>1 ne partitionne rien => refuser plutôt que laisser croire protégé.
    if (cfg.shardCount > 1 && !(cfg.forceRoot && cfg.forceInterleave))
        die("--shard-count > 1 exige --force-root ET --force-interleave (sharding non implémenté hors force-interleave)");
    if (cfg.forceJitterStart < 0)
        die("--force-jitter-start doit etre >= 0 (recu %d)", cfg.forceJitterStart);
    if (cfg.shardCount > 1 || cfg.forceJitterStart > 0)
        logf("P13 SHARD %d/%d jitterStart=%d : ce worker traite les tickets globaux J0*nroots + %d + %d*local (sous-ensemble disjoint)",
             cfg.shardIndex, cfg.shardCount, cfg.forceJitterStart, cfg.shardIndex, cfg.shardCount);
    // P13 skip-ledger : charge l'ensemble exact des tickets globaux déjà terminés en local.
    if (!cfg.skipLedgerPath.empty()) {
        if (!(cfg.forceRoot && cfg.forceInterleave))
            die("--skip-ledger exige --force-root ET --force-interleave");
        FILE* f = fopen(cfg.skipLedgerPath.c_str(), "r");
        if (!f) die("--skip-ledger : impossible d'ouvrir %s", cfg.skipLedgerPath.c_str());
        char line[64]; uint64_t v, mx = 0; size_t n = 0;
        while (fgets(line, sizeof(line), f)) {
            if (line[0] < '0' || line[0] > '9') continue;   // skip entête/commentaire
            v = strtoull(line, nullptr, 10);
            g_skipLedger.insert(v); if (v > mx) mx = v; n++;
        }
        fclose(f);
        logf("P13 skip-ledger : %zu tickets terminés chargés (uniques=%zu, max=%" PRIu64 ") -> jamais recalculés",
             n, g_skipLedger.size(), mx);
    }
    // --break-mask : charge le masque spatial par-seam (lignes "ci W" / "ci S").
    if (!cfg.breakMaskPath.empty()) {
        FILE* fm = fopen(cfg.breakMaskPath.c_str(), "r");
        if (!fm) die("--break-mask : impossible d'ouvrir %s", cfg.breakMaskPath.c_str());
        int ci; char dir; int nw = 0, ns = 0;
        char lm[64];
        while (fgets(lm, sizeof lm, fm)) {
            if (sscanf(lm, "%d %c", &ci, &dir) != 2) continue;
            if (ci < 0 || ci > 255) continue;
            if (dir == 'W' || dir == 'w') { g_breakMaskW[ci] = true; nw++; }
            else if (dir == 'S' || dir == 's') { g_breakMaskS[ci] = true; ns++; }
        }
        fclose(fm);
        g_breakMaskOn = true;
        logf("BREAK-MASK ON : %d seams ouest + %d seams sud autorisés (break interdit partout ailleurs, match exact)", nw, ns);
    }
    logf("bw starting: %d threads, seed %" PRIu64 ", nodeCap %.1fB, heurScale %.3f, "
         "minSave %d, resume best %d, seconds %ld%s",
         cfg.threads, cfg.seed, cfg.nodeCap / 1e9, cfg.heurScale, cfg.minSave,
         g_bestScore.load(), cfg.seconds, cfg.bench ? " [BENCH]" : "");
    for (const Hint& h : HINTS)
        logf("clue: piece %d td(%d,%d) rot %d -> bu cell (%d,%d) fill idx %d",
             h.piece, h.tdRow, h.tdCol, h.rot, 15 - h.tdRow, h.tdCol,
             FILL_IDX[(15 - h.tdRow) * 16 + h.tdCol]);

    signal(SIGINT, [](int) { g_stop = true; });
    signal(SIGTERM, [](int) { g_stop = true; });

    g_stats = std::vector<ThreadStats>(cfg.threads);
    // Mode one-shot : le drain écrit son heartbeat (cfgHash + rewinds + workers + ts).
    if (!cfg.writeHeartbeat.empty()) {
        writeHeartbeatFile(cfg.writeHeartbeat, cfg.hbMinRewind, cfg.hbWorkers);
        return 0;
    }
    // Gate shadow #2a : round-trip de clé snapshot -> board -> manifeste -> cache hit.
    if (!cfg.terminalSelftest.empty()) {
        FILE* f = fopen(cfg.terminalSelftest.c_str(), "rb");
        if (!f) { logf("SELFTEST_FAIL open %s", cfg.terminalSelftest.c_str()); return 2; }
        TailSnapshot s{};
        bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
        if (!ok || s.magic != 0x42575431) { logf("SELFTEST_FAIL bad snapshot"); return 2; }
        RotatedPiece board[256]; bool used[257];
        memcpy(board, s.board, sizeof board);
        for (int p = 0; p <= 256; p++) used[p] = s.used[p] != 0;
        // 1) la clé recalculée depuis le BOARD (comme le main en live) doit == clé stockée
        TermKey live = computeTailKey(board, used, s.si, s.rewindDepth, s.breaksUsed,
                                      s.initialBestCost, s.budgetOverride, s.acceptCost);
        TermKey stored{ s.cfgHash, s.crc, s.rewindDepth, s.initialBestCost };
        bool keyMatch = (live == stored);
        logf("SELFTEST key live(cfg=%llx crc=%llx) stored(cfg=%llx crc=%llx) rewind=%d initBest=%d match=%d",
             (unsigned long long)live.cfg, (unsigned long long)live.crc,
             (unsigned long long)stored.cfg, (unsigned long long)stored.crc,
             s.rewindDepth, s.initialBestCost, keyMatch);
        // 2) écrire EXHAUSTED au manifeste, recharger le cache, vérifier le hit
        mkdir(cfg.terminalManifest.c_str(), 0755);
        writeTerminalProof(cfg.terminalManifest, s, "EXHAUSTED", 123456789, 0, s.acceptCost + 1);  // bestCost valide
        g_termProofDir = cfg.terminalManifest;
        int hbc = -1; bool hit = termCacheHit(live, &hbc);
        logf("SELFTEST proof_write -> cache_hit=%d bestCost=%d (file-per-key)", hit, hbc);
        // Garde Codex #1 : chaque FAUX .term (même nom, contenu invalide) doit être REFUSÉ.
        std::string tf = termFile(cfg.terminalManifest, live.cfg, live.crc, live.rewind, live.initBest);
        auto put = [&](const char* txt) { FILE* w = fopen(tf.c_str(), "w"); if (w) { fputs(txt, w); fclose(w); } };
        int refused = 0;
        put("");                                                                  // vide
        if (!termCacheHit(live)) refused++;
        put("P8TERM2 cfg=1 crc=2 rewind=224 initBest=16 verdict=EXHAUSTED\n");     // tronqué (pas de chk)
        if (!termCacheHit(live)) refused++;
        put("total garbage not a proof\n");                                        // version inconnue
        if (!termCacheHit(live)) refused++;
        put("P8TERM2 cfg=0 crc=0 rewind=1 initBest=1 verdict=EXHAUSTED closed_at=1 union=1 jver=P8BJ4 jhdr=0 build=\"x\" chk=deadbeef\n"); // chk faux + incohérent
        if (!termCacheHit(live)) refused++;
        bool guardPass = (refused == 4);
        logf("SELFTEST guard1 fake_term_refused=%d/4 (term_refused counter=%llu) %s",
             refused, (unsigned long long)g_termRefused.load(), guardPass ? "PASS" : "FAIL");
        bool pass = keyMatch && hit && guardPass;
        logf("SELFTEST %s", pass ? "PASS" : "FAIL");
        return pass ? 0 : 1;
    }
    // Gate shadow #3 : persistance des attempts (migration N->M->N + refus config).
    if (cfg.attemptSelftest) {
        std::string sf = cfg.attemptState.empty() ? (cfg.saveDir + "/att_selftest.state") : cfg.attemptState;
        uint64_t seed = cfg.seed; unlink(sf.c_str());
        int pass = 0, tot = 0;
        auto chk = [&](const char* nm, bool ok) { tot++; if (ok) pass++; logf("ATT_SELFTEST %s %s", nm, ok ? "ok" : "FAIL"); };
        g_attemptDone[0] = 100; g_attemptDone[1] = 200; writeAttemptState(sf, 2, seed);   // 2 threads
        loadAttemptState(sf, seed);                                                        // reprise en 4 threads
        chk("resume_common", g_attemptResume[0] == 100 && g_attemptResume[1] == 200);
        chk("new_tids_fresh", g_attemptResume[2] == 0 && g_attemptResume[3] == 0);
        g_attemptDone[0] = 111; g_attemptDone[1] = 222; g_attemptDone[2] = 333; g_attemptDone[3] = 444;
        writeAttemptState(sf, 4, seed);                                                    // 4 threads écrivent
        g_attemptDone[0] = 500; g_attemptDone[1] = 600; writeAttemptState(sf, 2, seed);    // retour 2 threads
        loadAttemptState(sf, seed);
        chk("shrink_preserves", g_attemptResume[0] == 500 && g_attemptResume[1] == 600
                             && g_attemptResume[2] == 333 && g_attemptResume[3] == 444);   // tids désactivés préservés
        loadAttemptState(sf, seed + 1);                                                    // autre config
        chk("wrong_config_refused", g_attemptResume[0] == 0 && g_attemptResume[1] == 0);
        unlink(sf.c_str());
        logf("ATT_SELFTEST %s (%d/%d)", pass == tot ? "PASS" : "FAIL", pass, tot);
        return pass == tot ? 0 : 1;
    }
    // Backfill STRICT (Codex BLOQUEUR 2) : migre un tail clos en preuve .term SEULEMENT si
    // les TROIS artefacts sont présents et concordants : snapshot valide + journal v2 header
    // concordant + artefact RÉSULTAT EXHAUSTED (checksumé, identité concordante, bestCost dans
    // l'invariant). PAS de voie snapshot-seul. Chaque artefact absent/tronqué/faux -> REFUSE.
    if (!cfg.backfillProof.empty()) {
        FILE* f = fopen(cfg.backfillProof.c_str(), "rb");
        if (!f) { logf("BACKFILL_REFUSE open %s", cfg.backfillProof.c_str()); return 2; }
        TailSnapshot s{}; bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
        if (!ok || s.magic != 0x42575431) { logf("BACKFILL_REFUSE bad magic"); return 1; }
        if (s.crc != fnv1a(&s, sizeof s - sizeof s.crc)) { logf("BACKFILL_REFUSE crc corrupt"); return 1; }
        if (s.cfgHash != tailConfigHash()) { logf("BACKFILL_REFUSE cfgHash mismatch (autre puzzle)"); return 1; }
        if (cfg.backfillJournal.empty()) { logf("BACKFILL_REFUSE journal v2 OBLIGATOIRE"); return 1; }
        { FILE* jf = fopen(cfg.backfillJournal.c_str(), "r");   // journal v2 header concordant
          char line[128]; unsigned long long jh;
          bool jok = jf && fgets(line, sizeof line, jf) &&
                     sscanf(line, "P8BJ4 %llx", &jh) == 1 && jh == journalHeaderHash(s);
          if (jf) fclose(jf);
          if (!jok) { logf("BACKFILL_REFUSE journal v2 absent/incohérent"); return 1; } }
        int bc = -1;   // artefact RÉSULTAT EXHAUSTED concordant OBLIGATOIRE (fournit bestCost)
        if (!readResultArtifact(cfg.backfillJournal + ".result", s, &bc)) {
            logf("BACKFILL_REFUSE résultat EXHAUSTED absent/tronqué/incohérent (pas GLOBAL_STOP/PARTIAL/etc.)"); return 1; }
        mkdir(cfg.terminalManifest.c_str(), 0755);
        g_termProofDir = cfg.terminalManifest;
        writeTerminalProof(cfg.terminalManifest, s, "EXHAUSTED", 0, journalHeaderHash(s), bc);
        int vbc = -1;
        bool verified = terminalProofValid(cfg.terminalManifest, s.cfgHash, s.crc, s.rewindDepth, s.initialBestCost, &vbc);
        logf("BACKFILL_%s rewind=%d initBest=%d bestCost=%d provenance=%s",
             verified ? "OK" : "FAIL", s.rewindDepth, s.initialBestCost, vbc, cfg.backfillProof.c_str());
        return verified ? 0 : 1;
    }
    // Gate r216 déterministe (Codex) : construction inline vs chaîne, byte-identique.
    // curCost=15 forcé en MODE TEST — ne crée ni near-miss réel, ni .term, ni résultat prod.
    if (!cfg.r216Gate.empty()) {
        FILE* f = fopen(cfg.r216Gate.c_str(), "rb");
        if (!f) { logf("R216_GATE_FAIL open"); return 2; }
        TailSnapshot r224{}; bool ok = fread(&r224, sizeof r224, 1, f) == 1; fclose(f);
        if (!ok || r224.magic != 0x42575431) { logf("R216_GATE_FAIL bad snapshot"); return 2; }
        int gap216 = 1; for (const auto& lr : cfg.ladder) if (lr.rewind == 216) gap216 = lr.gap;
        int curCost = 15;   // forcé, test only
        bool used[257]; for (int p = 0; p <= 256; p++) used[p] = r224.used[p] != 0;
        // INLINE : ce que le ladder passerait à solveTailMrvRewind pour r216 (état exact).
        TailSnapshot inl = r224;
        inl.rewindDepth = 216; inl.initialBestCost = curCost;
        inl.breaksUsed = breaksUpTo(r224.board, 216);
        inl.budgetOverride = TOTAL_BUDGET + gap216; inl.acceptCost = TOTAL_BUDGET;
        inl.crc = fnv1a(&inl, sizeof inl - sizeof inl.crc);
        // CHAÎNE : via buildChainSpec (breaksUsed216) + la construction exacte de replayChain.
        ChainSpec ch = buildChainSpec(r224.board, used, r224.si, r224.breaksUsed,
                                      (int)breaksUpTo(r224.board, 216), curCost, 2, gap216);
        TailSnapshot chn = ch.r224;
        chn.rewindDepth = ch.rewind216; chn.initialBestCost = curCost;
        chn.breaksUsed = ch.breaksUsed216; chn.budgetOverride = TOTAL_BUDGET + ch.gap216;
        chn.crc = fnv1a(&chn, sizeof chn - sizeof chn.crc);
        bool same = memcmp(&inl, &chn, sizeof inl) == 0;
        logf("R216_GATE cfg %d si %d rewind %d/%d breaks %d/%d initBest %d/%d budget %d/%d accept %d/%d board %d crc %d",
             inl.cfgHash == chn.cfgHash, inl.si == chn.si, inl.rewindDepth, chn.rewindDepth,
             inl.breaksUsed, chn.breaksUsed, inl.initialBestCost, chn.initialBestCost,
             inl.budgetOverride, chn.budgetOverride, inl.acceptCost, chn.acceptCost,
             memcmp(inl.board, chn.board, sizeof inl.board) == 0, inl.crc == chn.crc);
        logf("R216_GATE %s (byte-identique inline vs chaîne)", same ? "PASS" : "FAIL");
        return same ? 0 : 1;
    }
    // Mode B : construire une ChainSpec de test depuis un snapshot r224.
    if (!cfg.makeChainSnap.empty()) {
        FILE* f = fopen(cfg.makeChainSnap.c_str(), "rb");
        if (!f) { logf("MAKECHAIN_FAIL open"); return 2; }
        TailSnapshot s{}; bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
        if (!ok || s.magic != 0x42575431) { logf("MAKECHAIN_FAIL bad snapshot"); return 2; }
        ChainSpec ch{}; ch.magic = 0x42574333; ch.version = 1; ch.r224 = s;
        ch.rewind216 = 216; ch.gap216 = 1; ch.nodeCap216 = cfg.chainCap216;
        ch.breaksUsed216 = breaksUpTo(s.board, ch.rewind216);   // Invariant 2 : recalcul depuis le board
        // Vérif : le recalcul reproduit-il le breaksUsed du r224 (à rewind 224) ?
        int chk224 = breaksUpTo(s.board, s.rewindDepth);
        logf("MAKECHAIN breaks216=%d (recalcul), verif224 recalc=%d vs snapshot=%d %s",
             ch.breaksUsed216, chk224, s.breaksUsed, chk224 == s.breaksUsed ? "OK" : "MISMATCH");
        ch.crc = fnv1a(&ch, sizeof ch - sizeof ch.crc);
        std::string out = cfg.chainOut.empty() ? (cfg.makeChainSnap + ".chain") : cfg.chainOut;
        FILE* w = fopen(out.c_str(), "wb");
        if (!w || fwrite(&ch, sizeof ch, 1, w) != 1) { if (w) fclose(w); logf("MAKECHAIN_FAIL write"); return 2; }
        fclose(w);
        logf("MAKECHAIN_OK -> %s (rewind216=%d gap216=%d cap216=%lluM)", out.c_str(), ch.rewind216, ch.gap216, (unsigned long long)(ch.nodeCap216/1000000));
        return 0;
    }
    if (!cfg.replayChainPath.empty()) {   // Mode B : exécuter la chaîne P8-owned r224->r216
        std::string wd = cfg.chainWorkdir.empty() ? (cfg.saveDir + "/chainwork") : cfg.chainWorkdir;
        return replayChain(cfg.replayChainPath, cfg.cubeDepth < 0 ? 3 : cfg.cubeDepth,
                           cfg.cubeWorkers < 1 ? 1 : cfg.cubeWorkers, wd, cfg.terminalManifest);
    }
    // Gate shadow #2c : logique d'admission defer (heartbeat + hystérésis + enum).
    if (!cfg.deferSelftest.empty()) {
        FILE* f = fopen(cfg.deferSelftest.c_str(), "rb");
        if (!f) { logf("DEFER_SELFTEST_FAIL open"); return 2; }
        TailSnapshot s{}; bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
        if (!ok || s.magic != 0x42575431) { logf("DEFER_SELFTEST_FAIL bad snapshot"); return 2; }
        RotatedPiece bd[256]; bool ud[257];
        memcpy(bd, s.board, sizeof bd);
        for (int p = 0; p <= 256; p++) ud[p] = s.used[p] != 0;
        int rw = s.rewindDepth, br = s.breaksUsed, ib = s.initialBestCost;
        int bg = s.budgetOverride, ac = s.acceptCost;
        TermKey key = computeTailKey(bd, ud, s.si, rw, br, ib, bg, ac);
        std::string inbox = cfg.captureInbox, hb = cfg.p8Heartbeat;
        g_termProofDir = "";   // pas de preuve terminale -> pas de TERMINAL_HIT
        mkdir(inbox.c_str(), 0755);
        auto cleanInbox = [&]() { DIR* d = opendir(inbox.c_str()); if (!d) return; struct dirent* e;
            while ((e = readdir(d))) { size_t L = strlen(e->d_name);
                if (L > 5 && strcmp(e->d_name + L - 5, ".snap") == 0) unlink((inbox + "/" + e->d_name).c_str()); }
            closedir(d); };
        int pass = 0, tot = 0;
        auto chk = [&](const char* nm, CaptureResult got, CaptureResult want) {
            tot++; bool o = got == want; if (o) pass++;
            logf("DEFER_SELFTEST %s got=%d want=%d %s", nm, got, want, o ? "ok" : "FAIL"); };
        cleanInbox(); unlink(hb.c_str());
        // S1 : pas de heartbeat -> LOCAL_NOWORKER
        chk("no_heartbeat", admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib, bg, ac, key), CAP_LOCAL_NOWORKER);
        // S2 : heartbeat frais + backlog 0 -> CREATED (+ fichier enqueue)
        g_deferMode = true; writeHeartbeatFile(hb, 224, 8);
        chk("fresh_backlog0", admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib, bg, ac, key), CAP_CREATED);
        // S3 : même clé désormais possédée -> ALREADY_OWNED_P8 (jamais de double calcul)
        chk("already_owned", admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib, bg, ac, key), CAP_ALREADY_OWNED_P8);
        // S4 : backpressure : clé non possédée + 4 dummies -> LOCAL_BACKPRESSURE
        cleanInbox();
        for (int i = 0; i < 4; i++) { std::string dn = inbox + "/dummy" + std::to_string(i) + ".snap";
            FILE* w = fopen(dn.c_str(), "w"); if (w) { fputs("x", w); fclose(w); } }
        g_deferMode = true;
        chk("backpressure_4", admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib, bg, ac, key), CAP_LOCAL_BACKPRESSURE);
        // S5 : cfgHash incompatible -> LOCAL_CFG
        cleanInbox(); g_deferMode = true;
        { char body[256]; int bn = snprintf(body, sizeof body,
            "P8HB1 cfg=deadbeef minRewind=224 format=P8BJ4 workers=8 ts=%lld build=\"x\"", (long long)time(nullptr));
          FILE* w = fopen(hb.c_str(), "w"); if (w) { fprintf(w, "%s chk=%llx\n", body, (unsigned long long)fnv1a(body, (size_t)bn)); fclose(w); } }
        chk("cfg_mismatch", admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib, bg, ac, key), CAP_LOCAL_CFG);
        // S6 : barrière 24 threads même clé, backlog 3 -> 1 seul CREATED, 23 ALREADY_OWNED,
        // AUCUN double-enqueue (atomicité de l'admission sous g_admitMtx).
        cleanInbox(); g_deferMode = true; writeHeartbeatFile(hb, 224, 8);
        for (int i = 0; i < 3; i++) { std::string dn = inbox + "/dummy" + std::to_string(i) + ".snap";
            FILE* w = fopen(dn.c_str(), "w"); if (w) { fputs("x", w); fclose(w); } }
        std::atomic<int> created{0}, owned{0}, other{0};
        std::vector<std::thread> pool;
        for (int t = 0; t < 24; t++) pool.emplace_back([&]() {
            CaptureResult r = admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib, bg, ac, key);
            if (r == CAP_CREATED) created.fetch_add(1);
            else if (r == CAP_ALREADY_OWNED_P8) owned.fetch_add(1);
            else other.fetch_add(1);
        });
        for (auto& t : pool) t.join();
        std::string fk = inboxKeyName(inbox, bd, s.si, rw, ib);
        int fkCount = access(fk.c_str(), F_OK) == 0 ? 1 : 0;   // la clé f0 : 0 ou 1 fichier, jamais dupliqué
        tot++;
        bool s6 = (created.load() == 1 && owned.load() == 23 && other.load() == 0 && fkCount == 1);
        if (s6) pass++;
        logf("DEFER_SELFTEST barrier24 created=%d owned=%d other=%d f0files=%d %s",
             created.load(), owned.load(), other.load(), fkCount, s6 ? "ok" : "FAIL");
        // S7 (Codex) : 24 CLÉS DIFFÉRENTES, backlog 3 -> exactement 1 CREATED, <=4 pending
        // uniques, 23 LOCAL_BACKPRESSURE (borne d'admission réellement prouvée).
        cleanInbox(); g_deferMode = true; writeHeartbeatFile(hb, 224, 8);
        for (int i = 0; i < 3; i++) { std::string dn = inbox + "/dummy" + std::to_string(i) + ".snap";
            FILE* w = fopen(dn.c_str(), "w"); if (w) { fputs("x", w); fclose(w); } }
        std::atomic<int> u7c{0}, u7bp{0}, u7o{0};
        std::vector<std::thread> pool7;
        for (int t = 0; t < 24; t++) pool7.emplace_back([&, t]() {
            int ib2 = 10 + t;   // clé différente par thread (initBest varié)
            TermKey k2 = computeTailKey(bd, ud, s.si, rw, br, ib2, bg, ac);
            CaptureResult r = admitDefer(inbox, hb, bd, ud, s.si, rw, br, ib2, bg, ac, k2);
            if (r == CAP_CREATED) u7c.fetch_add(1);
            else if (r == CAP_LOCAL_BACKPRESSURE) u7bp.fetch_add(1);
            else u7o.fetch_add(1);
        });
        for (auto& t : pool7) t.join();
        int pend7 = countInboxPending(inbox);
        tot++;
        bool s7 = (u7c.load() == 1 && pend7 <= 4 && u7bp.load() == 23 && u7o.load() == 0);
        if (s7) pass++;
        logf("DEFER_SELFTEST unique24 created=%d bp=%d other=%d pending=%d %s",
             u7c.load(), u7bp.load(), u7o.load(), pend7, s7 ? "ok" : "FAIL");
        cleanInbox(); unlink(hb.c_str());
        logf("DEFER_SELFTEST %s (%d/%d)", pass == tot ? "PASS" : "FAIL", pass, tot);
        return pass == tot ? 0 : 1;
    }
    // Gate concurrence CHAÎNE (mode B) : admitChain sous course + spec corrompue.
    // Prouve : (C1) 24 threads même clé -> 1 seul CREATED, 23 ALREADY_OWNED, 1 seule .spec ;
    //          (C2) 24 clés diff, backlog 3 -> 1 CREATED, 23 BACKPRESSURE (borne) ;
    //          (C3) pas de heartbeat -> LOCAL_NOWORKER (le main NE défère PAS -> reste local) ;
    //          (C4) round-trip : la .spec écrite se relit (magic+crc ok) ;
    //          (C5) spec corrompue (garbage / crc flippé) -> REJET parse (jamais faux terminal).
    if (!cfg.chainSelftest.empty()) {
        FILE* f = fopen(cfg.chainSelftest.c_str(), "rb");
        if (!f) { logf("CHAIN_SELFTEST_FAIL open %s", cfg.chainSelftest.c_str()); return 2; }
        TailSnapshot s{}; bool ok = fread(&s, sizeof s, 1, f) == 1; fclose(f);
        if (!ok || s.magic != 0x42575431) { logf("CHAIN_SELFTEST_FAIL bad snapshot"); return 2; }
        RotatedPiece bd[256]; bool ud[257];
        memcpy(bd, s.board, sizeof bd);
        for (int p = 0; p <= 256; p++) ud[p] = s.used[p] != 0;
        int rw = 224, br = s.breaksUsed, ib = s.initialBestCost;
        std::string inbox = cfg.captureInbox, hb = cfg.p8Heartbeat;
        mkdir(inbox.c_str(), 0755);
        auto cleanSpecs = [&]() { DIR* d = opendir(inbox.c_str()); if (!d) return; struct dirent* e;
            while ((e = readdir(d))) { size_t L = strlen(e->d_name);
                if (L > 5 && strcmp(e->d_name + L - 5, ".spec") == 0) unlink((inbox + "/" + e->d_name).c_str());
                else if (L > 5 && strcmp(e->d_name + L - 5, ".snap") == 0) unlink((inbox + "/" + e->d_name).c_str()); }
            closedir(d); };
        ChainSpec ch = buildChainSpec(bd, ud, s.si, br, br, ib, 2, 1);   // gap224=2, gap216=1
        int pass = 0, tot = 0;
        auto want = [&](const char* nm, bool cond) { tot++; if (cond) pass++;
            logf("CHAIN_SELFTEST %s %s", nm, cond ? "ok" : "FAIL"); };
        // C1 : barrière 24 threads, même clé -> 1 CREATED, 23 ALREADY_OWNED, 1 seule .spec.
        cleanSpecs(); unlink(hb.c_str()); g_deferMode = true; writeHeartbeatFile(hb, 224, 8);
        std::atomic<int> c1c{0}, c1o{0}, c1x{0};
        { std::vector<std::thread> pool;
          for (int t = 0; t < 24; t++) pool.emplace_back([&]() {
              CaptureResult r = admitChain(inbox, hb, ch);
              if (r == CAP_CREATED) c1c.fetch_add(1);
              else if (r == CAP_ALREADY_OWNED_P8) c1o.fetch_add(1);
              else c1x.fetch_add(1); });
          for (auto& t : pool) t.join(); }
        std::string kn = chainKeyName(inbox, ch);
        int specCount = access(kn.c_str(), F_OK) == 0 ? 1 : 0;
        want("barrier24_samekey", c1c.load() == 1 && c1o.load() == 23 && c1x.load() == 0 && specCount == 1);
        logf("CHAIN_SELFTEST c1 created=%d owned=%d other=%d specs=%d", c1c.load(), c1o.load(), c1x.load(), specCount);
        // C2 : 24 clés différentes, backlog 3 -> 1 CREATED, 23 BACKPRESSURE.
        cleanSpecs(); g_deferMode = true; writeHeartbeatFile(hb, 224, 8);
        for (int i = 0; i < 3; i++) { std::string dn = inbox + "/dummy" + std::to_string(i) + ".spec";
            FILE* w = fopen(dn.c_str(), "w"); if (w) { fputs("x", w); fclose(w); } }
        std::atomic<int> c2c{0}, c2bp{0}, c2x{0};
        { std::vector<std::thread> pool;
          for (int t = 0; t < 24; t++) pool.emplace_back([&, t]() {
              ChainSpec ch2 = buildChainSpec(bd, ud, s.si, br, br, 10 + t, 2, 1);  // clé diff par initBest
              CaptureResult r = admitChain(inbox, hb, ch2);
              if (r == CAP_CREATED) c2c.fetch_add(1);
              else if (r == CAP_LOCAL_BACKPRESSURE) c2bp.fetch_add(1);
              else c2x.fetch_add(1); });
          for (auto& t : pool) t.join(); }
        want("unique24_backpressure", c2c.load() == 1 && c2bp.load() == 23 && c2x.load() == 0);
        logf("CHAIN_SELFTEST c2 created=%d bp=%d other=%d", c2c.load(), c2bp.load(), c2x.load());
        // C3 : pas de heartbeat -> LOCAL_NOWORKER (main reste local, JAMAIS d'abandon silencieux).
        cleanSpecs(); unlink(hb.c_str());
        want("no_heartbeat_stays_local", admitChain(inbox, hb, ch) == CAP_LOCAL_NOWORKER);
        // C4 : round-trip d'une .spec écrite -> se relit (magic + crc + cfgHash).
        cleanSpecs(); g_deferMode = true; writeHeartbeatFile(hb, 224, 8);
        bool rtOk = false;
        if (admitChain(inbox, hb, ch) == CAP_CREATED) {
            FILE* rf = fopen(chainKeyName(inbox, ch).c_str(), "rb");
            if (rf) { ChainSpec rd{}; bool rok = fread(&rd, sizeof rd, 1, rf) == 1; fclose(rf);
                rtOk = rok && rd.magic == 0x42574333 && rd.crc == fnv1a(&rd, sizeof rd - sizeof rd.crc)
                       && rd.r224.cfgHash == tailConfigHash(); } }
        want("roundtrip_readable", rtOk);
        // C5 : spec corrompue -> le parse de replayChain REJETTE (magic OU crc), jamais un faux terminal.
        std::string cf = inbox + "/corrupt.spec";
        { FILE* w = fopen(cf.c_str(), "wb"); if (w) { for (int i = 0; i < (int)sizeof(ChainSpec); i++) fputc(0xA5, w); fclose(w); } }
        FILE* cff = fopen(cf.c_str(), "rb"); ChainSpec cbad{}; bool cread = cff && fread(&cbad, sizeof cbad, 1, cff) == 1; if (cff) fclose(cff);
        bool rejectGarbage = !cread || cbad.magic != 0x42574333 || cbad.crc != fnv1a(&cbad, sizeof cbad - sizeof cbad.crc);
        ChainSpec cflip = ch; cflip.gap216 ^= 0x1;   // crc désormais faux (champ modifié, crc pas recalculé)
        bool rejectFlip = cflip.crc != fnv1a(&cflip, sizeof cflip - sizeof cflip.crc);
        want("corrupt_spec_rejected", rejectGarbage && rejectFlip);
        cleanSpecs(); unlink(cf.c_str()); unlink(hb.c_str());
        logf("CHAIN_SELFTEST %s (%d/%d)", pass == tot ? "PASS" : "FAIL", pass, tot);
        return pass == tot ? 0 : 1;
    }
    // Validateur AUTORITATIF d'un fichier harvest (avec ou sans entête) : verifyBoard + SHA256.
    // Imprime "HARVEST_CHECK valid=0/1 score=N sha=<64hex>" ; exit 0 si valide (>=463) sinon 1.
    // Utilisé par l'ingestion Cloud pour valider un objet reçu avec le MÊME code que le solveur.
    if (!cfg.harvestCheckFile.empty()) {
        char sha[65]; int v = -1;
        bool okv = harvestVerifyFile(cfg.harvestCheckFile, nullptr, &v, sha);
        logf("HARVEST_CHECK valid=%d score=%d sha=%s", okv ? 1 : 0, v, okv ? sha : "-");
        return okv ? 0 : 1;
    }
    // Self-test durabilité harvest (Codex : prouver exactly-once SANS attendre un hit 463 réel).
    // --harvest-selftest DIR:BOARDFILE  charge un board >=463 (256 tokens pn/rot) et appelle
    // saveHarvest463 DEUX fois. Combiné à --harvest-fault STAGE:1, prouve : panne à l'étape 1 ->
    // rien de committé ET retry (appel 2) commit -> EXACTEMENT 1 fichier final. Imprime le compte.
    if (!cfg.harvestSelftest.empty()) {
        size_t pos = cfg.harvestSelftest.find(':', 3);   // ':' après un éventuel "C:" Windows
        if (pos == std::string::npos) { logf("SELFTEST_FAIL format DIR:BOARDFILE"); return 2; }
        std::string dir = cfg.harvestSelftest.substr(0, pos);
        std::string bf  = cfg.harvestSelftest.substr(pos + 1);
        mkdir(dir.c_str(), 0755);
        reconcileHarvestDir(dir);
        FILE* f = fopen(bf.c_str(), "r");
        if (!f) { logf("SELFTEST_FAIL open %s", bf.c_str()); return 2; }
        RotatedPiece board[256]; memset(board, 0, sizeof board);
        for (int tdr = 0; tdr < 16; tdr++) {
            int bur = 15 - tdr;
            for (int c = 0; c < 16; c++) {
                int pn = -1, rot = -1;
                if (fscanf(f, " %d/%d", &pn, &rot) != 2) { logf("SELFTEST_FAIL parse"); fclose(f); return 2; }
                RotatedPiece rp{}; rp.pieceNumber = (uint16_t)pn; rp.rot = (uint8_t)rot;
                const Piece& p = PIECES[pn];
                rp.top = sideAfterRot(p, rot, 0); rp.right = sideAfterRot(p, rot, 1);
                board[bur * 16 + c] = rp;
            }
        }
        fclose(f);
        int v = verifyBoard(board);
        if (v < 463) { logf("SELFTEST_FAIL board score=%d < 463", v); return 2; }
        // 2 appels : le 1er peut être fauté (STAGE:1), le 2e (attemptNo=2) commit toujours.
        saveHarvest463(dir, board, v, "selftest", 0, 0, 0, 0);
        saveHarvest463(dir, board, v, "selftest", 0, 0, 0, 0);
        // compte les fichiers FINAUX (pas .tmp) présents pour ce board
        char sha[65]; uint32_t buf[256];
        for (int i = 0; i < 256; i++) buf[i] = ((uint32_t)board[i].pieceNumber << 8) | board[i].rot;
        sha256_hex(buf, sizeof buf, sha);
        int finals = 0, tmps = 0;
        DIR* dd = opendir(dir.c_str()); struct dirent* e;
        while (dd && (e = readdir(dd))) {
            if (strncmp(e->d_name, ".tmp_", 5) == 0) { tmps++; continue; }
            if (strstr(e->d_name, sha) && strstr(e->d_name, ".txt")) finals++;
        }
        if (dd) closedir(dd);
        logf("HARVEST_SELFTEST score=%d fault='%s' finals=%d tmp_leftover=%d sha=%.12s",
             v, cfg.harvestFault.c_str(), finals, tmps, sha);
        return (finals == 1 && tmps == 0) ? 0 : 1;   // exactly-once + aucun tmp orphelin
    }
    // Gate 465 : charge un board sauvé (format saveBoard : 16 lignes top-down de
    // 16 tokens `pieceNumber/rot`), le vérifie avec le MÊME verifyBoard() que le
    // candidat utilise en course, imprime score + checksum du board (byte-identité).
    if (!cfg.verifyBoardFile.empty()) {
        FILE* f = fopen(cfg.verifyBoardFile.c_str(), "r");
        if (!f) { logf("VERIFY_BOARD_FAIL open %s", cfg.verifyBoardFile.c_str()); return 2; }
        RotatedPiece board[256]; memset(board, 0, sizeof board);
        int cells = 0;
        for (int tdr = 0; tdr < 16; tdr++) {
            int bur = 15 - tdr;
            for (int c = 0; c < 16; c++) {
                int pn = -1, rot = -1;
                if (fscanf(f, " %d/%d", &pn, &rot) != 2) { logf("VERIFY_BOARD_FAIL parse tdr=%d c=%d", tdr, c); fclose(f); return 2; }
                RotatedPiece rp{}; rp.pieceNumber = (uint16_t)pn; rp.rot = (uint8_t)rot;
                const Piece& p = PIECES[pn];
                rp.top = sideAfterRot(p, rot, 0); rp.right = sideAfterRot(p, rot, 1);
                board[bur * 16 + c] = rp; cells++;
            }
        }
        fclose(f);
        int score = verifyBoard(board);
        // checksum stable du board (pieceNumber<<8 | rot en ordre canonique bu-row-major)
        uint32_t buf[256]; for (int i = 0; i < 256; i++) buf[i] = ((uint32_t)board[i].pieceNumber << 8) | board[i].rot;
        unsigned long long chk = fnv1a(buf, sizeof buf);
        logf("VERIFY_BOARD file=%s cells=%d score=%d/480 checksum=%llx", cfg.verifyBoardFile.c_str(), cells, score, chk);
        return score >= 0 ? 0 : 1;
    }
    // --enum-3x3 : catalogue exact des racines 3x3 légales (one-shot, mono-thread).
    if (!cfg.enum3x3Path.empty()) {
        Tables T; buildTables(T);
        FILE* out = fopen(cfg.enum3x3Path.c_str(), "w");
        if (!out) { logf("ENUM3X3_FAIL open %s", cfg.enum3x3Path.c_str()); return 2; }
        RotatedPiece board[256]; memset(board, 0, sizeof board);
        bool used[257] = {false};
        int C[9]; for (int s = 0; s < 9; s++) C[s] = SEQ_ROW[s] * 16 + SEQ_COL[s];
        g_enum3x3Count = 0;
        enum3x3rec(T, board, used, C, 0, out);
        fclose(out);
        logf("ENUM3X3 done: %llu racines legales -> %s",
             (unsigned long long)g_enum3x3Count, cfg.enum3x3Path.c_str());
        return 0;
    }
    // --probe240 : optimise chaque état depth-240 en MRV réordonné (bypass le gate
    // dormant depth244). Révèle si le verrou du mur +4 est le budget résiduel ou l'ordre.
    if (!cfg.probe240In.empty()) {
        FILE* in = fopen(cfg.probe240In.c_str(), "r");
        if (!in) { logf("PROBE240_FAIL open %s", cfg.probe240In.c_str()); return 2; }
        FILE* out = cfg.probe240Out.empty() ? stdout : fopen(cfg.probe240Out.c_str(), "w");
        if (!out) { logf("PROBE240_FAIL open out"); return 2; }
        std::string buf; buf.resize(8192);
        int done = 0, better = 0, solved466 = 0;
        while (fgets(&buf[0], (int)buf.size(), in)) {
            char* s = &buf[0];
            char hash[80]; int breaks240, consumed = 0;
            if (sscanf(s, "%79s %d%n", hash, &breaks240, &consumed) != 2) continue;
            s += consumed;
            RotatedPiece board[256]; memset(board, 0, sizeof board);
            bool used[257] = {false};
            int cnt = 0;
            for (int f = 0; f < 240; f++) {
                int pn = -1, rot = -1, c2 = 0;
                if (sscanf(s, " %d/%d%n", &pn, &rot, &c2) != 2) break;
                s += c2;
                int ci = SEQ_ROW[f] * 16 + SEQ_COL[f];
                RotatedPiece rp{}; rp.pieceNumber = (uint16_t)pn; rp.rot = (uint8_t)rot;
                const Piece& p = PIECES[pn];
                rp.top = sideAfterRot(p, rot, 0); rp.right = sideAfterRot(p, rot, 1);
                board[ci] = rp; used[pn] = true; cnt++;
            }
            if (cnt != 240) { fprintf(out, "%s PARSE_FAIL cnt=%d\n", hash, cnt); continue; }
            uint64_t nodes = 0; bool capped = false;
            int cost = TOTAL_BUDGET + cfg.probe240Gap + 1;
            solveTailMrv(board, used, 240, breaks240, (uint64_t)cfg.probe240Cap,
                         &nodes, &capped, &cost, TOTAL_BUDGET + cfg.probe240Gap, INT_MAX);
            int add = cost - breaks240, score = 480 - cost;
            fprintf(out, "%s breaks240=%d bestCost=%d add=%d score=%d nodes=%llu capped=%d\n",
                    hash, breaks240, cost, add, score, (unsigned long long)nodes, capped ? 1 : 0);
            fflush(out);
            done++;
            if (cost <= TOTAL_BUDGET + 3) better++;   // mieux que le +4 du DFS
            if (cost <= TOTAL_BUDGET) solved466++;     // score >= 466 !
        }
        fclose(in); if (out != stdout) fclose(out);
        logf("PROBE240 done=%d better_than_+4=%d solved_466=%d (TOTAL_BUDGET=%d)",
             done, better, solved466, TOTAL_BUDGET);
        return 0;
    }
    // P7-A/B: replay mode re-solves one captured tail directly, no Blackwood generator.
    if (!cfg.replayPath.empty()) {
        if (!cfg.p8Journal.empty())   // P8-B: per-cube cap + journal + terminal manifest (+ total cap gate)
            return replayP8b(cfg.replayPath, cfg.nodeCap, cfg.cubeDepth < 0 ? 3 : cfg.cubeDepth,
                             cfg.cubeWorkers < 1 ? 1 : cfg.cubeWorkers, cfg.p8Journal,
                             cfg.terminalManifest, nullptr, cfg.p8bTotalCapCli);
        if (cfg.countCubes || cfg.shardLo >= 0)   // P8-A: count or one shard
            return replayShard(cfg.replayPath, cfg.nodeCap, cfg.cubeDepth < 0 ? 3 : cfg.cubeDepth,
                               cfg.shardLo, cfg.shardHi, cfg.countCubes);
        if (cfg.cubeDepth >= 0)
            return replayCubes(cfg.replayPath, cfg.nodeCap, cfg.cubeDepth, cfg.cubeWorkers);
        return replayTailState(cfg.replayPath, cfg.nodeCap, cfg.tsS, cfg.tsN);
    }
    // Verdict cache (shadow #2a) : le main lit le manifeste terminal écrit par P8.
    // Vide => cache OFF (comportement prod strictement inchangé).
    g_termProofDir = cfg.terminalManifest;
    if (!g_termProofDir.empty()) {
        mkdir(g_termProofDir.c_str(), 0755);
        logf("TERM_CACHE armed proof-dir=%s (file-per-key lookup)", g_termProofDir.c_str());
    }
    loadAttemptState(cfg.attemptState, cfg.seed);   // shadow #3 : reprise par-thread
    if (cfg.forceRoot) {   // canary : charge la liste de racines 3x3 forcées (une par ligne : p/r,...×9 [hsc=..])
        FILE* f = fopen(cfg.forceRootPath.c_str(), "r");
        if (!f) { logf("FORCE_ROOT_FAIL open %s", cfg.forceRootPath.c_str()); return 2; }
        char lb[256];
        while (fgets(lb, sizeof lb, f)) {
            ForceRoot R; int ok = 1;
            char* p = lb;
            for (int k = 0; k < 9; k++) {
                int pn = -1, rt = -1;
                if (sscanf(p, " %d/%d", &pn, &rt) != 2) { ok = 0; break; }
                R.p[k] = pn; R.r[k] = rt;
                p = strchr(p, '/'); p = strchr(p + 1, ',');   // avance au champ suivant
                if (!p && k < 8) { ok = 0; break; }
                if (p) p++;
            }
            if (ok) g_forceRoots.push_back(R);
        }
        fclose(f);
        if (g_forceRoots.empty()) { logf("FORCE_ROOT_FAIL 0 racines lues %s", cfg.forceRootPath.c_str()); return 2; }
        logf("FORCE_ROOT chargé: %zu racines, %llu jitters/racine, %d threads",
             g_forceRoots.size(), (unsigned long long)cfg.forceJitters, cfg.threads);
        // --root-allow : allowlist de cidx (index racine 0-based dans le catalogue ci-dessus).
        // Chargé APRÈS les racines pour valider cidx < nroots. nroots reste inchangé -> les tickets
        // et les seeds sont identiques au run non-filtré ; seuls les cidx hors-liste sont sautés.
        if (!cfg.rootAllowPath.empty()) {
            if (!cfg.forceInterleave)
                logf("ROOT_ALLOW note : sans --force-interleave (mode batch), le skip s'applique quand même par index racine");
            FILE* fa = fopen(cfg.rootAllowPath.c_str(), "r");
            if (!fa) { logf("ROOT_ALLOW_FAIL open %s", cfg.rootAllowPath.c_str()); return 2; }
            char lb2[64]; size_t nlines = 0, noob = 0;
            while (fgets(lb2, sizeof lb2, fa)) {
                if (lb2[0] < '0' || lb2[0] > '9') continue;    // saute entête/commentaire
                uint64_t c = strtoull(lb2, nullptr, 10);
                nlines++;
                if (c >= g_forceRoots.size()) { noob++; continue; }   // hors bornes -> ignoré
                g_rootAllow.insert((uint32_t)c);
            }
            fclose(fa);
            if (g_rootAllow.empty()) { logf("ROOT_ALLOW_FAIL 0 cidx valides dans %s", cfg.rootAllowPath.c_str()); return 2; }
            logf("ROOT_ALLOW : %zu cidx autorisés / %zu racines (%zu lignes lues, %zu hors-bornes ignorées) -> les autres cidx sont sautés (ticket/seed d'origine préservés)",
                 g_rootAllow.size(), g_forceRoots.size(), nlines, noob);
        }
    }
    if (!cfg.captureDir.empty()) {   // phase-2 : dir de capture séparé
        mkdir(cfg.captureDir.c_str(), 0755);
        logf("CAPTURE arm=%s dir=%s (1x/attempt au 1er depth 240)", cfg.captureArm.c_str(), cfg.captureDir.c_str());
    }
    if (!cfg.ticketLogDir.empty()) {   // --ticket-log : SEGMENT IMMUABLE par invocation ; arme seulement si manifeste complet
        mkdir(cfg.ticketLogDir.c_str(), 0755);
        // cfg-hash CANONIQUE : base semantique attemptParamHash (prune/endgame/ladder/breaks/tail/heur...) + espace tickets + build
        uint64_t h = attemptParamHash(cfg.seed);
        h = fnv1a(cfg.campaignEpoch.data(), cfg.campaignEpoch.size(), h);
        h = fnv1a(&cfg.shardIndex, sizeof cfg.shardIndex, h);
        h = fnv1a(&cfg.shardCount, sizeof cfg.shardCount, h);
        h = fnv1a(&cfg.forceJitters, sizeof cfg.forceJitters, h);
        { int fi = cfg.forceInterleave ? 1 : 0; h = fnv1a(&fi, sizeof fi, h); }
        h = fnv1a(&cfg.minSave, sizeof cfg.minSave, h);
        { size_t nr = g_forceRoots.size(); h = fnv1a(&nr, sizeof nr, h);
          for (auto& R : g_forceRoots) { h = fnv1a(R.p, sizeof R.p, h); h = fnv1a(R.r, sizeof R.r, h); } }
        // --root-allow : politique de couverture -> nouveau cfg-hash (ne PAS confondre couverture
        // full-1047 et filtrée). Hash ordre-indépendant des cidx autorisés (XOR mixé) + leur nombre.
        if (!g_rootAllow.empty()) {
            uint64_t nra = g_rootAllow.size(), acc = 0;
            for (uint32_t c : g_rootAllow) acc ^= (0x9E3779B97F4A7C15ULL * ((uint64_t)c + 1));
            h = fnv1a(&nra, sizeof nra, h);
            h = fnv1a(&acc, sizeof acc, h);
        }
        h = fnv1a(BW_BUILD_ID, strlen(BW_BUILD_ID), h);
        g_tkCfgHash = h;
        // run-id ROBUSTE (random_device + pid + nanos) ; O_EXCL sur temp -> retry si collision ; rename atomique
        std::random_device rdv;
        for (int at = 0; at < 16 && !g_tkArmed; at++) {
            g_tkRunId = (((uint64_t)rdv() << 32) ^ (uint64_t)rdv())
                      ^ ((uint64_t)getpid() << 40)
                      ^ (uint64_t)std::chrono::steady_clock::now().time_since_epoch().count();
            char fin[600], tmp[640];
            snprintf(fin, sizeof fin, "%s/seg_%016llx.manifest.json", cfg.ticketLogDir.c_str(), (unsigned long long)g_tkRunId);
            snprintf(tmp, sizeof tmp, "%s.tmp", fin);
            int fd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644);   // EEXIST -> collision run-id -> retry
            if (fd < 0) continue;
            char body[2048];
            int nb = snprintf(body, sizeof body,
                "{\n \"format_version\":2,\n \"record_size\":40,\n \"endianness\":\"little\",\n"
                " \"run_id\":\"%016llx\",\n \"cfg_hash\":\"%016llx\",\n \"build_id\":\"%s\",\n"
                " \"epoch\":\"%s\",\n \"shard_index\":%d,\n \"shard_count\":%d,\n"
                " \"nroots\":%zu,\n \"force_jitters\":%llu,\n \"force_interleave\":%d,\n"
                " \"node_cap\":%llu,\n \"seed\":%llu,\n \"min_save\":%d,\n"
                " \"record_layout\":\"off0 u64 globalticket; 8 u32 cidx; 12 u32 jidx; 16 u64 nodes; 24 u32 dur_ms; 28 u16 max_depth; 30 u8 status(0=exhausted,1=cap,2=hit,3=interrupt); 31 u8 thread_id; 32 u64 reserved\",\n"
                " \"files\":\"seg_%016llx.t<thread>.bin\",\n \"dedup_key\":\"(epoch,cfg_hash,shard_index,globalticket)\"\n}\n",
                (unsigned long long)g_tkRunId, (unsigned long long)g_tkCfgHash, BW_BUILD_ID,
                cfg.campaignEpoch.c_str(), cfg.shardIndex, cfg.shardCount,
                g_forceRoots.size(), (unsigned long long)cfg.forceJitters, cfg.forceInterleave ? 1 : 0,
                (unsigned long long)cfg.nodeCap, (unsigned long long)cfg.seed, cfg.minSave,
                (unsigned long long)g_tkRunId);
            bool ok = nb > 0 && nb < (int)sizeof body;
            for (int off = 0; ok && off < nb; ) { ssize_t w = write(fd, body + off, nb - off); if (w <= 0) { ok = false; break; } off += (int)w; }
            if (ok) ok = (fsync(fd) == 0);
            close(fd);
            if (ok && rename(tmp, fin) == 0) g_tkArmed = true;   // manifeste COMPLET visible atomiquement
            else unlink(tmp);                                    // incomplet -> ne JAMAIS armer les .bin
        }
        if (g_tkArmed)
            logf("TICKET_LOG ARME run_id=%016llx cfg_hash=%016llx dir=%s (segment immuable v2)",
                 (unsigned long long)g_tkRunId, (unsigned long long)g_tkCfgHash, cfg.ticketLogDir.c_str());
        else {
            logf("TICKET_LOG_FAIL manifeste non cree dir=%s -> journal DESARME (aucun .bin)", cfg.ticketLogDir.c_str());
            return 2;
        }
    }
    if (!cfg.capture3Dir.empty()) {   // canary6 : capture des états gap<=3
        mkdir(cfg.capture3Dir.c_str(), 0755);
        logf("CAPTURE_GAP3 dir=%s (board 244 des événements bestTailGap<=3)", cfg.capture3Dir.c_str());
    }
    if (!cfg.harvest463Dir.empty()) {   // canary7 : harvest des boards 463 vérifiés
        mkdir(cfg.harvest463Dir.c_str(), 0755);
        reconcileHarvestDir(cfg.harvest463Dir);   // recharge sha des boards déjà présents (anti-doublon inter-restart)
        logf("HARVEST463 dir=%s (board vérifié score>=463, identité SHA256)", cfg.harvest463Dir.c_str());
    }
 #ifdef BW_WASM_SINGLE_LANE
    // Browser portfolio mode: one solver per dedicated Web Worker. Avoiding
    // pthread/shared-memory atomics is substantially faster in WebAssembly.
    solverThread(0);
    g_stop = true;
 #else
    std::vector<std::thread> threads;
    for (int i = 0; i < cfg.threads; i++) threads.emplace_back(solverThread, i);
    std::thread hb(heartbeat);
    for (auto& t : threads) t.join();
    g_stop = true;
    hb.join();
 #endif
    writeAttemptState(cfg.attemptState, cfg.threads, cfg.seed);   // flush exact à l'arrêt coopératif
    dumpR216Trace();   // P17 opt-2 : écrit la télémétrie des entrées de bande r216 (si --r216-trace)
    dumpEliteTrace();  // P-ELITE opt-1 : écrit la télémétrie des slices 9-31 (si --elite-slice-trace)
    if (g_telOn) {     // P-TEL option C : ferme le fichier + report (threads déjà join -> dumps faits)
        if (g_telEventF) { std::lock_guard<std::mutex> lk(g_telMtx); fflush(g_telEventF); fclose(g_telEventF); g_telEventF = nullptr; }
        logf("TEL FINAL: reach244=%llu s4=%llu s5=%llu events=%llu settleClosed=%llu settleCens=%llu -> %s",
            (unsigned long long)g_telReach244Tot,(unsigned long long)g_telS4Tot,(unsigned long long)g_telS5Tot,
            (unsigned long long)g_telEventsTot,(unsigned long long)g_telClosedTot,(unsigned long long)g_telCensTot, g_telOut.c_str());
    }
    if (g_eliteOrderOn || g_eliteRefMode) {
        uint64_t app = 0, miss = 0; for (int i = 0; i < 256; i++) { app += g_eliteAppliedT[i]; miss += g_eliteViewMissT[i]; }
        logf("ELITE FINAL: applied=%llu viewMiss=%llu msChecked=%llu msMismatch=%llu",
             (unsigned long long)app, (unsigned long long)miss,
             (unsigned long long)g_eliteMsChecked.load(), (unsigned long long)g_eliteMsMismatch.load());
    }

    // final report
    uint64_t n = 0, p = 0, r = 0, c = 0, tc = 0, tn = 0;
    uint64_t ac[4] = {}, an[4] = {}, ax[4] = {};
    for (auto& s : g_stats) {
        n += s.nodes.load();
        p += s.placements.load();
        r += s.restarts.load();
        c += s.completions.load();
        tc += s.tailCalls.load();
        tn += s.tailNodes.load();
        for (int k = 0; k < 4; k++) {
            ac[k] += s.adaptiveCalls[k].load();
            an[k] += s.adaptiveNodes[k].load();
            ax[k] += s.adaptiveCapped[k].load();
        }
    }
    uint64_t hist[257] = {0};
    for (auto& s : g_stats)
        for (int d = 0; d < 257; d++) hist[d] += s.depthHist[d].load();
    logf("FINAL: nodes %.2fB placements %.2fB restarts %" PRIu64 " completions %" PRIu64
         " best %d", n / 1e9, p / 1e9, r, c, g_bestScore.load());
    if (cfg.shadowR224) {
        uint64_t elig = g_shadowR224Elig.load(); size_t uniq; { std::lock_guard<std::mutex> lk(g_shadowMtx); uniq = g_shadowKeys.size(); }
        logf("SHADOW_R224 arm=%s eligible=%llu unique_keys=%zu rung236=%llu rung230=%llu rung224=%llu termHit=%llu",
             cfg.captureArm.c_str(), (unsigned long long)elig, uniq,
             (unsigned long long)g_shadowRungEntry[236].load(),
             (unsigned long long)g_shadowRungEntry[230].load(),
             (unsigned long long)g_shadowRungEntry[224].load(),
             (unsigned long long)g_termHit.load());
        char hb[128]; int off = 0;
        for (int i = 0; i < 12; i++) off += snprintf(hb + off, sizeof hb - off, "%s%llu", i ? "," : "",
                                                      (unsigned long long)g_shadowCostHist[i].load());
        logf("SHADOW_R224 curCost-budget hist[0..11]=%s (0 = pile budget, +k = k trop cher)", hb);
    }
    if (cfg.tailDepth)
        logf("tail MRV FINAL: calls %" PRIu64 " nodes %.2fM (%.0f/call)",
             tc, tn / 1e6, tc ? (double)tn / tc : 0.0);
    if (cfg.tailAdaptive) {
        for (int k = 0; k < 4; k++) {
            const AdaptiveTailTier& at = ADAPTIVE_TAIL_TIERS[k];
            logf("adaptive MRV %d->%d FINAL: calls %" PRIu64
                 " capped %" PRIu64 " nodes %.2fM (%.0f/call)",
                 at.triggerDepth, at.rewindDepth, ac[k], ax[k], an[k] / 1e6,
                 ac[k] ? (double)an[k] / ac[k] : 0.0);
        }
    }
    // depth distribution of attempts (only non-zero buckets)
    std::string dist = "attempt max-depth histogram:";
    for (int d = 0; d < 257; d++)
        if (hist[d]) dist += " " + std::to_string(d) + ":" + std::to_string(hist[d]);
    logf("%s", dist.c_str());
    if (cfg.stats) {
        std::string dn = "nodes per depth (nonzero):";
        std::string df = "fits per depth:";
        std::string dh = "halffits per depth:";
        for (int d = 0; d < 257; d++) {
            uint64_t v = 0, f = 0, h2 = 0;
            for (auto& s : g_stats) {
                v += s.depthNodes[d];
                f += s.depthFits[d];
                h2 += s.depthHalf[d];
            }
            if (v) dn += " " + std::to_string(d) + ":" + std::to_string(v);
            if (f) df += " " + std::to_string(d) + ":" + std::to_string(f);
            if (h2) dh += " " + std::to_string(d) + ":" + std::to_string(h2);
        }
        // logf truncates at 2KB — write the full arrays directly
        for (const std::string* s2 : {&dn, &df, &dh}) {
            printf("%s\n", s2->c_str());
            if (g_log) fprintf(g_log, "%s\n", s2->c_str());
        }
        fflush(stdout);
        if (g_log) fflush(g_log);
    }
    if (g_log) fclose(g_log);
    return 0;
}
