rshogi-core 0.1.8

A high-performance shogi engine core library with NNUE evaluation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
//! 探索エンジンのエントリポイント
//!
//! USIプロトコルから呼び出すためのハイレベルインターフェース。

use crate::eval::EvalHash;
use crate::time::Instant;
// AtomicU64 is only needed for native multi-threaded builds.
// Wasm Rayon model doesn't use SearchProgress.
#[cfg(not(target_arch = "wasm32"))]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use super::time_manager::{
    calculate_falling_eval, calculate_time_reduction, normalize_nodes_effort,
    DEFAULT_MAX_MOVES_TO_DRAW,
};
use super::{LimitsType, RootMove, SearchWorker, Skill, SkillOptions, ThreadPool, TimeManagement};
use crate::position::Position;
use crate::tt::TranspositionTable;
use crate::types::{Depth, Move, Value, MAX_PLY};

// =============================================================================
// SearchInfo - 探索情報(USI info出力用)
// =============================================================================

/// 探索情報(USI info出力用)
#[derive(Debug, Clone)]
pub struct SearchInfo {
    /// 探索深さ
    pub depth: Depth,
    /// 選択的深さ
    pub sel_depth: i32,
    /// 最善手のスコア
    pub score: Value,
    /// 探索ノード数
    pub nodes: u64,
    /// 経過時間(ミリ秒)
    pub time_ms: u64,
    /// NPS (nodes per second)
    pub nps: u64,
    /// 置換表使用率(千分率)
    pub hashfull: u32,
    /// Principal Variation
    pub pv: Vec<Move>,
    /// MultiPV番号(1-indexed)
    pub multi_pv: usize,
}

impl SearchInfo {
    /// USI形式のinfo文字列を生成
    pub fn to_usi_string(&self) -> String {
        let score_str =
            if self.score.is_mate_score() && self.score.raw().abs() < Value::INFINITE.raw() {
                // USIでは手数(plies)で出力し、負値は自分が詰まされる側を示す
                let mate_ply = self.score.mate_ply();
                let signed_ply = if self.score.is_loss() {
                    -mate_ply
                } else {
                    mate_ply
                };
                format!("mate {signed_ply}")
            } else {
                format!("cp {}", self.score.raw())
            };

        let mut s = format!(
            "info depth {depth} seldepth {sel_depth} multipv {multi_pv} score {score} nodes {nodes} time {time_ms} nps {nps} hashfull {hashfull}",
            depth = self.depth,
            sel_depth = self.sel_depth,
            multi_pv = self.multi_pv,
            score = score_str,
            nodes = self.nodes,
            time_ms = self.time_ms,
            nps = self.nps,
            hashfull = self.hashfull
        );

        if !self.pv.is_empty() {
            s.push_str(" pv");
            for m in &self.pv {
                s.push(' ');
                s.push_str(&m.to_usi());
            }
        }

        s
    }
}

/// YaneuraOu準拠のaspiration windowを計算
pub(crate) fn compute_aspiration_window(rm: &RootMove, thread_id: usize) -> (Value, Value, Value) {
    // mean_squared_score がない場合は巨大なdeltaでフルウィンドウにする
    let fallback = {
        let inf = Value::INFINITE.raw() as i64;
        inf * inf
    };
    let mean_sq = rm.mean_squared_score.unwrap_or(fallback).abs();
    let mean_sq = mean_sq.min((Value::INFINITE.raw() as i64) * (Value::INFINITE.raw() as i64));

    let thread_offset = (thread_id % 8) as i32;
    let score_factor = rm.average_score.raw().abs() / 9000;
    let delta_raw =
        5 + thread_offset + score_factor + (mean_sq / 11131).min(i32::MAX as i64) as i32;
    let delta = Value::new(delta_raw);
    let alpha_raw = (rm.average_score.raw() - delta.raw()).max(-Value::INFINITE.raw());
    let beta_raw = (rm.average_score.raw() + delta.raw()).min(Value::INFINITE.raw());

    (Value::new(alpha_raw), Value::new(beta_raw), delta)
}

/// YaneuraOu準拠の詰みスコアに対する深さ打ち切り判定
#[inline]
fn proven_mate_depth_exceeded(best_value: Value, depth: Depth) -> bool {
    if best_value.is_win() || best_value.is_loss() {
        let mate_ply = best_value.mate_ply();
        return (mate_ply + 2) * 5 / 2 < depth;
    }

    false
}

/// `go mate` 指定時に、要求手数以内の詰みが見つかったか判定する
#[inline]
fn mate_within_limit(
    best_value: Value,
    score_lower_bound: bool,
    score_upper_bound: bool,
    mate_limit_moves: i32,
) -> bool {
    if mate_limit_moves <= 0
        || score_lower_bound
        || score_upper_bound
        || !best_value.is_mate_score()
    {
        return false;
    }

    let mate_ply = best_value.mate_ply() as i64;
    let limit_plies = (mate_limit_moves as i64).saturating_mul(2);

    mate_ply <= limit_plies
}

// =============================================================================
// SearchResult - 探索結果
// =============================================================================

/// 探索結果
#[derive(Debug, Clone)]
pub struct SearchResult {
    /// 最善手
    pub best_move: Move,
    /// Ponder手(相手の予想応手)
    pub ponder_move: Move,
    /// 最善手のスコア
    pub score: Value,
    /// 完了した探索深さ
    pub depth: Depth,
    /// 探索ノード数
    pub nodes: u64,
    /// Principal Variation(読み筋)
    pub pv: Vec<Move>,
    /// 探索統計レポート(search-stats feature有効時のみ内容あり)
    pub stats_report: String,
}

// =============================================================================
// Search - 探索エンジン
// =============================================================================

/// 探索エンジン
///
/// USIプロトコルから呼び出すための主要インターフェース。
/// デフォルトのEvalHashサイズ(MB)
pub const DEFAULT_EVAL_HASH_SIZE_MB: usize = 256;

pub struct Search {
    /// 置換表
    tt: Arc<TranspositionTable>,
    /// 評価ハッシュ(NNUE評価値キャッシュ)
    eval_hash: Arc<EvalHash>,
    /// 置換表のサイズ(MB)
    tt_size_mb: usize,
    /// EvalHashのサイズ(MB)
    eval_hash_size_mb: usize,
    /// 停止フラグ
    stop: Arc<AtomicBool>,
    /// ponderhit通知フラグ
    ponderhit_flag: Arc<AtomicBool>,
    /// 探索開始時刻
    start_time: Option<Instant>,
    /// 時間オプション
    time_options: super::TimeOptions,
    /// Skill Level オプション
    skill_options: SkillOptions,

    /// 探索スレッド数
    num_threads: usize,
    /// 探索スレッドプール(helper threads)
    thread_pool: ThreadPool,

    /// SearchWorker(YaneuraOu準拠: 長期保持して再利用)
    /// 履歴統計を含み、usinewgameでクリア、goでは保持
    worker: Option<Box<SearchWorker>>,

    /// 直前イテレーションのスコア(YaneuraOu準拠)
    best_previous_score: Option<Value>,
    /// 直前イテレーションの平均スコア(YaneuraOu準拠)
    best_previous_average_score: Option<Value>,
    /// 直近のイテレーション値(YaneuraOuは4要素リングバッファ)
    iter_value: [Value; 4],
    /// iter_valueの書き込み位置
    iter_idx: usize,
    /// 直前に安定したとみなした深さ
    last_best_move_depth: Depth,
    /// 直前の最善手(PV変化検出用)
    last_best_move: Move,
    /// totBestMoveChanges(世代減衰込み)
    tot_best_move_changes: f64,
    /// 直前の timeReduction(YO準拠で次手に持ち回る)
    previous_time_reduction: f64,
    /// 直前の手数(手番反転の検出用)
    last_game_ply: Option<i32>,
    /// 次のiterationで深さを伸ばすかどうか(YaneuraOu準拠)
    increase_depth: bool,
    /// 深さを伸ばせなかった回数(aspiration時の調整に使用)
    search_again_counter: i32,

    /// 引き分けまでの最大手数(YaneuraOu準拠のエンジンオプション)
    max_moves_to_draw: i32,
}

/// ワーカーから集約する軽量サマリ(並列探索を見据えて追加)
struct WorkerSummary {
    best_move_changes: f64,
}

impl From<&SearchWorker> for WorkerSummary {
    fn from(w: &SearchWorker) -> Self {
        Self {
            best_move_changes: w.state.best_move_changes,
        }
    }
}

/// best_move_changes を集約する(並列探索対応のためのヘルパー)
///
/// - `changes`: 各スレッドのbest_move_changes
/// - 戻り値: (合計, スレッド数)。スレッド数0の場合は(0.0, 1)を返しゼロ除算を避ける。
fn aggregate_best_move_changes(changes: &[f64]) -> (f64, usize) {
    if changes.is_empty() {
        return (0.0, 1);
    }
    let sum: f64 = changes.iter().copied().sum();
    (sum, changes.len())
}

// SearchProgress is only used in native multi-threaded builds.
// Wasm Rayon model doesn't use SearchProgress (passes None to search_helper).
#[cfg(not(target_arch = "wasm32"))]
/// SearchProgress はヘルパースレッドの進捗を追跡する。
/// False Sharing を防ぐため、各フィールドを別々のキャッシュラインに配置する。
#[repr(C, align(64))]
pub(crate) struct SearchProgress {
    nodes: AtomicU64,
    _pad1: [u8; 56], // 64バイト境界までパディング
    best_move_changes_bits: AtomicU64,
    _pad2: [u8; 56], // 64バイト境界までパディング
}

#[cfg(not(target_arch = "wasm32"))]
impl SearchProgress {
    pub(crate) fn new() -> Self {
        Self {
            nodes: AtomicU64::new(0),
            _pad1: [0; 56],
            best_move_changes_bits: AtomicU64::new(0.0f64.to_bits()),
            _pad2: [0; 56],
        }
    }

    pub(crate) fn reset(&self) {
        self.nodes.store(0, Ordering::Relaxed);
        self.best_move_changes_bits.store(0.0f64.to_bits(), Ordering::Relaxed);
    }

    pub(crate) fn update(&self, nodes: u64, best_move_changes: f64) {
        self.nodes.store(nodes, Ordering::Relaxed);
        self.best_move_changes_bits
            .store(best_move_changes.to_bits(), Ordering::Relaxed);
    }

    pub(crate) fn nodes(&self) -> u64 {
        self.nodes.load(Ordering::Relaxed)
    }

    pub(crate) fn best_move_changes(&self) -> f64 {
        f64::from_bits(self.best_move_changes_bits.load(Ordering::Relaxed))
    }
}

struct ThreadSummary {
    id: usize,
    score: Value,
    completed_depth: Depth,
}

impl ThreadSummary {
    fn from_worker(id: usize, worker: &SearchWorker) -> Option<Self> {
        worker.state.root_moves.get(0).map(|rm| Self {
            id,
            score: rm.score,
            completed_depth: worker.state.completed_depth,
        })
    }
}

fn get_best_thread_id(main_worker: &SearchWorker, thread_pool: &ThreadPool) -> usize {
    let mut summaries = Vec::new();
    if let Some(summary) = ThreadSummary::from_worker(0, main_worker) {
        summaries.push(summary);
    }

    // Native: Use helper_threads() to access Thread objects directly
    #[cfg(not(target_arch = "wasm32"))]
    for thread in thread_pool.helper_threads() {
        if let Some(summary) = thread.with_worker(|worker: &mut SearchWorker| {
            ThreadSummary::from_worker(thread.id(), worker)
        }) {
            summaries.push(summary);
        }
    }

    // Wasm with wasm-threads: Use helper_results() to get collected results
    #[cfg(all(target_arch = "wasm32", feature = "wasm-threads"))]
    for result in thread_pool.helper_results() {
        summaries.push(ThreadSummary {
            id: result.thread_id,
            score: result.best_score,
            completed_depth: result.completed_depth,
        });
    }

    // Wasm without wasm-threads: No helper threads, suppress unused warning
    #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
    let _ = thread_pool;

    if summaries.is_empty() {
        return 0;
    }

    if let Some(win) = summaries.iter().find(|s| s.score.is_win()) {
        return win.id;
    }

    let min_score = summaries.iter().map(|s| s.score.raw()).min().unwrap_or(0);

    let mut best_id = summaries[0].id;
    let mut best_value = i64::MIN;
    for summary in summaries {
        let vote_value =
            (summary.score.raw() - min_score + 14) as i64 * summary.completed_depth as i64;
        if vote_value > best_value {
            best_value = vote_value;
            best_id = summary.id;
        }
    }

    best_id
}

struct BestThreadResult {
    best_move: Move,
    ponder_move: Move,
    score: Value,
    completed_depth: Depth,
    nodes: u64,
    best_previous_score: Option<Value>,
    best_previous_average_score: Option<Value>,
    pv: Vec<Move>,
}

fn collect_best_thread_result(
    worker: &SearchWorker,
    limits: &LimitsType,
    skill_enabled: bool,
    skill: &mut Skill,
) -> BestThreadResult {
    let completed_depth = worker.state.completed_depth;
    let nodes = worker.state.nodes;
    let best_previous_score = worker.state.root_moves.get(0).map(|rm| rm.score);
    let best_previous_average_score = worker.state.root_moves.get(0).map(|rm| {
        if rm.average_score.raw() == -Value::INFINITE.raw() {
            rm.score
        } else {
            rm.average_score
        }
    });

    if worker.state.root_moves.is_empty() {
        return BestThreadResult {
            best_move: Move::NONE,
            ponder_move: Move::NONE,
            score: Value::ZERO,
            completed_depth,
            nodes,
            best_previous_score,
            best_previous_average_score,
            pv: Vec::new(),
        };
    }

    let mut effective_multi_pv = limits.multi_pv;
    if skill_enabled {
        effective_multi_pv = effective_multi_pv.max(4);
    }
    effective_multi_pv = effective_multi_pv.min(worker.state.root_moves.len());

    let mut best_move = worker.state.best_move;
    if skill_enabled && effective_multi_pv > 0 {
        let mut rng = rand::rng();
        let best = skill.pick_best(&worker.state.root_moves, effective_multi_pv, &mut rng);
        if best != Move::NONE {
            best_move = best;
        }
    }

    let best_rm = worker.state.root_moves.iter().find(|rm| rm.mv() == best_move);

    let ponder_move = best_rm
        .and_then(|rm| {
            if rm.pv.len() > 1 {
                Some(rm.pv[1])
            } else {
                None
            }
        })
        .unwrap_or(Move::NONE);

    let score = best_rm
        .map(|rm| rm.score)
        .unwrap_or(worker.state.root_moves.get(0).map(|rm| rm.score).unwrap_or(Value::ZERO));

    let pv = best_rm.map(|rm| rm.pv.clone()).unwrap_or_default();

    BestThreadResult {
        best_move,
        ponder_move,
        score,
        completed_depth,
        nodes,
        best_previous_score,
        best_previous_average_score,
        pv,
    }
}

impl Search {
    /// 時間計測用のメトリクスを準備(対局/Go開始時)
    fn prepare_time_metrics(&mut self, ply: i32) {
        // 手番が変わっている場合はスコア符号を反転
        if let Some(last_ply) = self.last_game_ply {
            if (last_ply - ply).abs() & 1 == 1 {
                if let Some(prev_score) = self.best_previous_score {
                    if prev_score != Value::INFINITE {
                        self.best_previous_score = Some(Value::new(-prev_score.raw()));
                    }
                }
                if let Some(prev_avg) = self.best_previous_average_score {
                    if prev_avg != Value::INFINITE {
                        self.best_previous_average_score = Some(Value::new(-prev_avg.raw()));
                    }
                }
            }
        }

        // best_previous_score が番兵(INFINITE)のときは 0 初期化(YO準拠)
        if self.best_previous_score == Some(Value::INFINITE) {
            self.iter_value = [Value::ZERO; 4];
        } else {
            let seed = self.best_previous_score.unwrap_or(Value::ZERO);
            self.iter_value = [seed; 4];
        }
        self.iter_idx = 0;
        self.last_best_move_depth = 0;
        self.last_best_move = Move::NONE;
        self.tot_best_move_changes = 0.0;
        self.last_game_ply = Some(ply);
        self.increase_depth = true;
        self.search_again_counter = 0;
    }

    /// fallingEval / timeReduction / totBestMoveChanges を計算
    ///
    /// YaneuraOu準拠の式を簡略化して single thread で適用する。
    fn compute_time_factors(
        &self,
        best_value: Value,
        completed_depth: Depth,
        tot_best_move_changes: f64,
        thread_count: usize,
    ) -> (f64, f64, f64, usize) {
        // fallingEval
        let prev_avg_raw = self.best_previous_average_score.unwrap_or(Value::INFINITE).raw();
        let iter_val = self.iter_value[self.iter_idx];
        let falling_eval = calculate_falling_eval(prev_avg_raw, iter_val.raw(), best_value.raw());

        // timeReduction
        let time_reduction = calculate_time_reduction(completed_depth, self.last_best_move_depth);

        (falling_eval, time_reduction, tot_best_move_changes, thread_count)
    }

    /// 時間要因計算後の状態更新
    fn update_time_factor_state(&mut self, best_value: Value, tot_best_move_changes: f64) {
        self.iter_value[self.iter_idx] = best_value;
        self.iter_idx = (self.iter_idx + 1) % self.iter_value.len();
        self.tot_best_move_changes = tot_best_move_changes;
    }

    /// 新しいSearchを作成
    ///
    /// # Arguments
    /// * `tt_size_mb` - 置換表のサイズ(MB)
    pub fn new(tt_size_mb: usize) -> Self {
        let tt = Arc::new(TranspositionTable::new(tt_size_mb));
        let eval_hash = Arc::new(EvalHash::new(DEFAULT_EVAL_HASH_SIZE_MB));
        let stop = Arc::new(AtomicBool::new(false));
        let ponderhit_flag = Arc::new(AtomicBool::new(false));
        let max_moves_to_draw = DEFAULT_MAX_MOVES_TO_DRAW;
        let thread_pool = ThreadPool::new(
            1,
            Arc::clone(&tt),
            Arc::clone(&eval_hash),
            Arc::clone(&stop),
            Arc::clone(&ponderhit_flag),
            max_moves_to_draw,
        );

        Self {
            tt,
            eval_hash,
            tt_size_mb,
            eval_hash_size_mb: DEFAULT_EVAL_HASH_SIZE_MB,
            stop,
            ponderhit_flag,
            start_time: None,
            time_options: super::TimeOptions::default(),
            skill_options: SkillOptions::default(),
            num_threads: 1,
            thread_pool,
            // YaneuraOu準拠: workerは遅延初期化(最初のgoで作成)
            worker: None,
            best_previous_score: Some(Value::INFINITE),
            best_previous_average_score: Some(Value::INFINITE),
            iter_value: [Value::ZERO; 4],
            iter_idx: 0,
            last_best_move_depth: 0,
            last_best_move: Move::NONE,
            tot_best_move_changes: 0.0,
            previous_time_reduction: 0.85,
            last_game_ply: None,
            increase_depth: true,
            search_again_counter: 0,
            max_moves_to_draw,
        }
    }

    /// 置換表のサイズを変更
    pub fn resize_tt(&mut self, size_mb: usize) {
        self.tt = Arc::new(TranspositionTable::new(size_mb));
        self.tt_size_mb = size_mb;
        // workerが存在する場合、TT参照を更新
        if let Some(worker) = &mut self.worker {
            worker.tt = Arc::clone(&self.tt);
        }
        self.thread_pool.update_tt(Arc::clone(&self.tt));
    }

    /// 置換表をクリア
    ///
    /// 新しい置換表を作成して置き換える。
    pub fn clear_tt(&mut self) {
        // Arc経由では&mutが取れないので、同じサイズの新しいTTを作成して置き換える
        self.tt = Arc::new(TranspositionTable::new(self.tt_size_mb));
        // workerが存在する場合、TT参照を更新
        if let Some(worker) = &mut self.worker {
            worker.tt = Arc::clone(&self.tt);
        }
        self.thread_pool.update_tt(Arc::clone(&self.tt));
    }

    /// Large Pagesで確保されているかを返す
    pub fn tt_uses_large_pages(&self) -> bool {
        self.tt.uses_large_pages()
    }

    /// EvalHashのサイズを変更
    ///
    /// # 注意
    /// このメソッドは**探索停止中にのみ**呼び出すこと。
    /// `&mut self` を取るため、探索中(`go` 実行中)には呼び出せない。
    /// USIプロトコルでは `setoption` は探索中に送られないため、
    /// 通常の使用では問題ない。
    pub fn resize_eval_hash(&mut self, size_mb: usize) {
        self.eval_hash = Arc::new(EvalHash::new(size_mb));
        self.eval_hash_size_mb = size_mb;
        // workerが存在する場合、EvalHash参照を更新
        if let Some(worker) = &mut self.worker {
            worker.eval_hash = Arc::clone(&self.eval_hash);
        }
        self.thread_pool.update_eval_hash(Arc::clone(&self.eval_hash));
    }

    /// EvalHashへの参照を取得
    pub fn eval_hash(&self) -> Arc<EvalHash> {
        Arc::clone(&self.eval_hash)
    }

    /// 履歴統計をクリア(usinewgame時に呼び出し)
    ///
    /// YaneuraOu準拠: Worker::clear()相当
    pub fn clear_histories(&mut self) {
        if let Some(worker) = &mut self.worker {
            worker.clear();
        }
        self.thread_pool.clear_histories();
    }

    /// 停止フラグを取得(探索スレッドに渡す用)
    pub fn stop_flag(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.stop)
    }

    /// ponderhitフラグを取得(探索スレッドへの通知に使用)
    pub fn ponderhit_flag(&self) -> Arc<AtomicBool> {
        Arc::clone(&self.ponderhit_flag)
    }

    /// ponderhitを要求(外部スレッドから)
    pub fn request_ponderhit(&self) {
        self.ponderhit_flag.store(true, Ordering::SeqCst);
    }

    /// 探索を停止
    pub fn stop(&self) {
        self.stop.store(true, Ordering::SeqCst);
    }

    /// 時間オプションを設定(USI setoptionから呼び出す想定)
    pub fn set_time_options(&mut self, opts: super::TimeOptions) {
        self.time_options = opts;
    }

    /// 時間オプションを取得
    pub fn time_options(&self) -> super::TimeOptions {
        self.time_options
    }

    /// Skillオプションを設定(USI setoptionから呼び出す想定)
    pub fn set_skill_options(&mut self, opts: SkillOptions) {
        self.skill_options = opts;
    }

    /// Skillオプションを取得
    pub fn skill_options(&self) -> SkillOptions {
        self.skill_options
    }

    /// 引き分けまでの最大手数を設定
    pub fn set_max_moves_to_draw(&mut self, v: i32) {
        self.max_moves_to_draw = if v > 0 { v } else { DEFAULT_MAX_MOVES_TO_DRAW };
    }

    /// 引き分けまでの最大手数を取得
    pub fn max_moves_to_draw(&self) -> i32 {
        self.max_moves_to_draw
    }

    /// 探索スレッド数を設定
    pub fn set_num_threads(&mut self, num: usize) {
        // WASM builds without wasm-threads feature use single-threaded search only.
        // With wasm-threads feature, multi-threading via wasm-bindgen-rayon is supported.
        #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
        let _ = num; // シングルスレッドモードでは引数を無視
        #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
        let num = 1;
        #[cfg(not(all(target_arch = "wasm32", not(feature = "wasm-threads"))))]
        let num = num.clamp(1, 512);
        self.num_threads = num;
        self.thread_pool.set_num_threads(
            num,
            Arc::clone(&self.tt),
            Arc::clone(&self.eval_hash),
            self.max_moves_to_draw,
        );
    }

    /// 探索スレッド数を取得
    pub fn num_threads(&self) -> usize {
        self.num_threads
    }

    /// 探索を実行
    ///
    /// # Arguments
    /// * `pos` - 探索対象の局面
    /// * `limits` - 探索制限
    /// * `on_info` - 探索情報のコールバック(Optional)
    ///
    /// # Returns
    /// 探索結果
    pub fn go<F>(
        &mut self,
        pos: &mut Position,
        limits: LimitsType,
        on_info: Option<F>,
    ) -> SearchResult
    where
        F: FnMut(&SearchInfo),
    {
        let ply = pos.game_ply();
        self.prepare_time_metrics(ply);
        // 停止フラグをリセット
        self.stop.store(false, Ordering::SeqCst);
        // ponderhitフラグをリセット
        self.ponderhit_flag.store(false, Ordering::SeqCst);
        self.start_time = Some(Instant::now());
        // 置換表の世代を進める(YaneuraOu準拠)
        self.tt.new_search();
        // ヘルパースレッドの結果をクリア
        // スレッド数が1の場合でも呼び出し、前回のマルチスレッド探索の結果が残らないようにする
        self.thread_pool.clear_helper_results();

        // 時間管理
        let mut time_manager =
            TimeManagement::new(Arc::clone(&self.stop), Arc::clone(&self.ponderhit_flag));
        time_manager.set_options(&self.time_options);
        time_manager.set_previous_time_reduction(self.previous_time_reduction);
        // ply(現在の手数)は局面から取得、max_moves_to_drawはYaneuraOu準拠のデフォルトを使う
        time_manager.init(&limits, pos.side_to_move(), ply, self.max_moves_to_draw);

        // YaneuraOu準拠: workerは遅延初期化、再利用する
        let tt_clone = Arc::clone(&self.tt);
        let eval_hash_clone = Arc::clone(&self.eval_hash);
        let max_moves = self.max_moves_to_draw;
        let worker = self
            .worker
            .get_or_insert_with(|| SearchWorker::new(tt_clone, eval_hash_clone, max_moves, 0));

        // setoptionで変更された可能性があるため、最新値を反映
        worker.max_moves_to_draw = self.max_moves_to_draw;

        // 探索状態のリセット(履歴はクリアしない、YaneuraOu準拠)
        worker.prepare_search();

        // 探索深さを決定
        let max_depth = if limits.depth > 0 {
            limits.depth
        } else {
            MAX_PLY // YaneuraOu準拠: 可能な限り深く探索
        };

        // SkillLevel設定を構築(手加減)
        let mut skill = Skill::from_options(&self.skill_options);
        let skill_enabled = skill.enabled();

        if self.num_threads > 1 {
            self.thread_pool.start_thinking(
                pos,
                limits.clone(),
                max_depth,
                self.time_options,
                self.max_moves_to_draw,
                skill_enabled,
            );
        }

        // 探索実行(コールバックなしの場合はダミーを渡す)
        let _effective_multi_pv = match on_info {
            Some(callback) => self.search_with_callback(
                pos,
                &limits,
                &mut time_manager,
                max_depth,
                callback,
                skill_enabled,
            ),
            None => {
                let mut noop = |_info: &SearchInfo| {};
                self.search_with_callback(
                    pos,
                    &limits,
                    &mut time_manager,
                    max_depth,
                    &mut noop,
                    skill_enabled,
                )
            }
        };

        if self.num_threads > 1 {
            self.stop.store(true, Ordering::SeqCst);
            self.thread_pool.wait_for_search_finished();
        }

        let best_thread_id = {
            let worker = self
                .worker
                .as_ref()
                .expect("worker should be initialized by search_with_callback");
            get_best_thread_id(worker, &self.thread_pool)
        };

        let best_result = if best_thread_id == 0 {
            let worker = self
                .worker
                .as_ref()
                .expect("worker should be initialized by search_with_callback");
            collect_best_thread_result(worker, &limits, skill_enabled, &mut skill)
        } else {
            // Native: Use helper_threads() to access Thread objects directly
            #[cfg(not(target_arch = "wasm32"))]
            let result = {
                let mut result = None;
                for thread in self.thread_pool.helper_threads() {
                    if thread.id() == best_thread_id {
                        result = Some(thread.with_worker(|worker: &mut SearchWorker| {
                            collect_best_thread_result(worker, &limits, skill_enabled, &mut skill)
                        }));
                        break;
                    }
                }
                result
            };

            // Wasm with wasm-threads: Use helper_results() to get collected results
            #[cfg(all(target_arch = "wasm32", feature = "wasm-threads"))]
            let result = {
                let helper_results = self.thread_pool.helper_results();
                helper_results.iter().find(|r| r.thread_id == best_thread_id).map(|r| {
                    // Apply skill-based move weakening if enabled
                    let (best_move, score) = if skill_enabled && !r.top_moves.is_empty() {
                        let mut rng = rand::rng();
                        let picked = skill.pick_best_from_pairs(&r.top_moves, &mut rng);
                        if picked != Move::NONE {
                            // Find the score of the picked move from top_moves
                            let picked_score = r
                                .top_moves
                                .iter()
                                .find(|(mv, _)| *mv == picked)
                                .map(|(_, score)| *score)
                                .unwrap_or(r.best_score);
                            (picked, picked_score)
                        } else {
                            (r.best_move, r.best_score)
                        }
                    } else {
                        (r.best_move, r.best_score)
                    };
                    BestThreadResult {
                        best_move,
                        ponder_move: Move::NONE, // Cannot get ponder from helper in Wasm
                        score,
                        completed_depth: r.completed_depth,
                        nodes: r.nodes,
                        // Use the actual best score (not skill-weakened) for time management
                        // and aspiration window initialization, matching native behavior.
                        best_previous_score: Some(r.best_score),
                        best_previous_average_score: Some(r.best_score),
                        pv: Vec::new(), // Cannot get PV from helper in Wasm
                    }
                })
            };

            // Wasm without wasm-threads: Always use main thread
            #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
            let result: Option<BestThreadResult> = None;

            result.unwrap_or_else(|| {
                let worker = self
                    .worker
                    .as_ref()
                    .expect("worker should be initialized by search_with_callback");
                collect_best_thread_result(worker, &limits, skill_enabled, &mut skill)
            })
        };

        let BestThreadResult {
            best_move,
            ponder_move,
            score,
            completed_depth,
            nodes: _best_nodes,
            best_previous_score,
            best_previous_average_score,
            pv,
        } = best_result;
        let total_nodes = {
            let main_nodes = self.worker.as_ref().map(|w| w.state.nodes).unwrap_or(0);

            // Native: Use helper_threads() to get node counts
            #[cfg(not(target_arch = "wasm32"))]
            let helper_nodes =
                self.thread_pool.helper_threads().iter().fold(0u64, |acc, thread| {
                    acc.saturating_add(thread.with_worker(|worker| worker.state.nodes))
                });

            // Wasm with wasm-threads: Use helper_nodes() to get node counts
            #[cfg(all(target_arch = "wasm32", feature = "wasm-threads"))]
            let helper_nodes = self.thread_pool.helper_nodes();

            // Wasm without wasm-threads: No helper threads
            #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
            let helper_nodes = 0u64;

            main_nodes.saturating_add(helper_nodes)
        };

        // 次の手番のために timeReduction を持ち回る
        self.previous_time_reduction = time_manager.previous_time_reduction();

        // 次回のfallingEval計算のために平均スコアを保存
        self.best_previous_score = best_previous_score;
        self.best_previous_average_score = best_previous_average_score;
        self.last_game_ply = Some(ply);

        // 探索統計レポートを取得(search-stats feature有効時のみ内容あり)
        let stats_report = self.worker.as_ref().map(|w| w.get_stats_report()).unwrap_or_default();

        SearchResult {
            best_move,
            ponder_move,
            score,
            depth: completed_depth,
            nodes: total_nodes,
            pv,
            stats_report,
        }
    }

    /// コールバック付きで探索を実行
    fn search_with_callback<F>(
        &mut self,
        pos: &mut Position,
        limits: &LimitsType,
        time_manager: &mut TimeManagement,
        max_depth: Depth,
        mut on_info: F,
        skill_enabled: bool,
    ) -> usize
    where
        F: FnMut(&SearchInfo),
    {
        // 深さペーシングの状態を初期化
        self.increase_depth = true;
        self.search_again_counter = 0;

        // workerを一時的に取り出す(借用チェッカー対策)
        let mut worker = self.worker.take().expect("worker should be available");

        // ルート手を初期化
        worker.state.root_moves = super::RootMoves::from_legal_moves(pos, &limits.search_moves);

        if worker.state.root_moves.is_empty() {
            worker.state.best_move = Move::NONE;
            #[cfg(debug_assertions)]
            eprintln!(
                "search_with_callback: root_moves is empty (search_moves_len={}, side_to_move={:?})",
                limits.search_moves.len(),
                pos.side_to_move()
            );
            self.worker = Some(worker);
            return 0;
        }

        #[cfg(debug_assertions)]
        eprintln!(
            "search_with_callback: root_moves_len={} first_move={}",
            worker.state.root_moves.len(),
            worker.state.root_moves.get(0).map(|rm| rm.mv().to_usi()).unwrap_or_default()
        );

        // 合法手が1つの場合は500ms上限を適用(YaneuraOu準拠)
        if worker.state.root_moves.len() == 1 {
            time_manager.apply_single_move_limit();
        }

        let start = self.start_time.unwrap();
        let mut effective_multi_pv = limits.multi_pv;
        if skill_enabled {
            effective_multi_pv = effective_multi_pv.max(4);
        }
        effective_multi_pv = effective_multi_pv.min(worker.state.root_moves.len());

        // 中断時にPVを巻き戻すための保持
        let mut last_best_pv = vec![Move::NONE];
        let mut last_best_score = Value::new(-Value::INFINITE.raw());
        let mut last_best_move_depth = 0;

        // 反復深化
        for depth in 1..=max_depth {
            #[cfg(debug_assertions)]
            if depth <= 2 {
                eprintln!(
                    "search_with_callback: depth={} nodes={} search_end={} max_time={} stop_requested={}",
                    depth,
                    worker.state.nodes,
                    time_manager.search_end(),
                    time_manager.maximum(),
                    time_manager.stop_requested()
                );
            }
            // 前回のiterationで深さを伸ばせなかった場合のカウンター(YO準拠)
            if depth > 1 && !self.increase_depth {
                self.search_again_counter += 1;
            }

            if worker.state.abort {
                break;
            }

            // ponderhitを検出した場合、時間再計算のみ行い探索は継続
            if self.ponderhit_flag.swap(false, Ordering::Relaxed) {
                time_manager.on_ponderhit();
            }

            // YaneuraOu準拠: depth 2以降は、次の深さを探索する時間があるかチェック
            // depth 1は必ず探索する(合法手が1つもない場合のresignを防ぐため)
            let is_pondering = time_manager.is_pondering();
            if depth > 1 && !is_pondering && time_manager.should_stop(depth) {
                break;
            }

            // YaneuraOu準拠: 詰みを読みきった場合の早期終了
            // 詰みまでの手数の2.5倍以上の深さを探索したら終了
            // MultiPV=1の時のみ適用(MultiPV>1では全候補を探索する必要がある)
            if effective_multi_pv == 1 && depth > 1 && !worker.state.root_moves.is_empty() {
                let best_value = worker.state.root_moves[0].score;

                if limits.mate == 0 {
                    if proven_mate_depth_exceeded(best_value, depth) {
                        break;
                    }
                } else if mate_within_limit(
                    best_value,
                    worker.state.root_moves[0].score_lower_bound,
                    worker.state.root_moves[0].score_upper_bound,
                    limits.mate,
                ) {
                    time_manager.request_stop();
                    break;
                }
            }

            let search_depth = depth;

            worker.state.root_depth = search_depth;
            worker.state.sel_depth = 0;

            // MultiPVループ(YaneuraOu準拠)
            let mut processed_pv = 0;
            for pv_idx in 0..effective_multi_pv {
                if worker.state.abort {
                    break;
                }

                // Aspiration Window(average/mean_squaredベース)
                let (mut alpha, mut beta, mut delta) =
                    compute_aspiration_window(&worker.state.root_moves[pv_idx], worker.thread_id);
                let mut failed_high_cnt = 0;

                // Aspiration Windowループ
                loop {
                    let adjusted_depth = (search_depth
                        - failed_high_cnt
                        - (3 * (self.search_again_counter + 1) / 4))
                        .max(1);
                    // pv_idx=0の場合は従来のsearch_rootを使用(後方互換性)
                    // pv_idx>0の場合のみsearch_root_for_pvを使用
                    let score = if pv_idx == 0 {
                        worker.search_root(pos, adjusted_depth, alpha, beta, limits, time_manager)
                    } else {
                        worker.search_root_for_pv(
                            pos,
                            search_depth,
                            alpha,
                            beta,
                            pv_idx,
                            limits,
                            time_manager,
                        )
                    };

                    if worker.state.abort {
                        break;
                    }

                    // Window調整
                    if score <= alpha {
                        beta = alpha;
                        alpha = Value::new(
                            score.raw().saturating_sub(delta.raw()).max(-Value::INFINITE.raw()),
                        );
                        failed_high_cnt = 0;
                        time_manager.reset_stop_on_ponderhit();
                    } else if score >= beta {
                        beta = Value::new(
                            score.raw().saturating_add(delta.raw()).min(Value::INFINITE.raw()),
                        );
                        failed_high_cnt += 1;
                    } else {
                        break;
                    }

                    delta = Value::new(delta.raw().saturating_add(delta.raw() / 3));
                }

                // 安定ソート [pv_idx..]
                worker.state.root_moves.stable_sort_range(pv_idx, worker.state.root_moves.len());
                // 📝 YaneuraOu行1477-1483: 探索済みのPVライン全体も安定ソートして順位を保つ
                worker.state.root_moves.stable_sort_range(0, pv_idx + 1);
                processed_pv = pv_idx + 1;
            }

            // 🆕 MultiPVループ完了後の最終ソート(YaneuraOu行1499)
            if !worker.state.abort && effective_multi_pv > 1 {
                worker.state.root_moves.stable_sort_range(0, effective_multi_pv);
            }

            // info出力は深さごとにまとめて行う(GUI詰まり防止のYO仕様)
            if processed_pv > 0 {
                let elapsed = start.elapsed();
                let time_ms = elapsed.as_millis() as u64;

                // Native: Use helper_threads() to get node counts
                #[cfg(not(target_arch = "wasm32"))]
                let helper_nodes = self
                    .thread_pool
                    .helper_threads()
                    .iter()
                    .fold(0u64, |acc, thread| acc.saturating_add(thread.nodes()));

                // Wasm with wasm-threads: Use helper_nodes() for realtime node counts
                #[cfg(all(target_arch = "wasm32", feature = "wasm-threads"))]
                let helper_nodes = self.thread_pool.helper_nodes();

                // Wasm without wasm-threads: No helper threads
                #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
                let helper_nodes = 0u64;

                let total_nodes = worker.state.nodes.saturating_add(helper_nodes);
                let nps = if time_ms > 0 {
                    total_nodes.saturating_mul(1000) / time_ms
                } else {
                    0
                };

                for pv_idx in 0..processed_pv {
                    let info = SearchInfo {
                        depth,
                        sel_depth: worker.state.root_moves[pv_idx].sel_depth,
                        score: worker.state.root_moves[pv_idx].score,
                        nodes: total_nodes,
                        time_ms,
                        nps,
                        hashfull: self.tt.hashfull(3) as u32,
                        pv: worker.state.root_moves[pv_idx].pv.clone(),
                        multi_pv: pv_idx + 1, // 1-indexed
                    };

                    on_info(&info);
                }
            }

            // Depth完了後の処理
            if !worker.state.abort {
                worker.state.completed_depth = search_depth;
                worker.state.best_move = worker.state.root_moves[0].mv();
                if worker.state.best_move != self.last_best_move {
                    self.last_best_move = worker.state.best_move;
                    self.last_best_move_depth = depth;
                }

                // 🆕 YaneuraOu準拠: previous_scoreを次のiterationのためにシード
                // (YaneuraOu行1267-1270: rm.previousScore = rm.score)
                for rm in worker.state.root_moves.iter_mut() {
                    rm.previous_score = rm.score;
                }

                // 評価変動・timeReduction・最善手不安定性をまとめて適用(YaneuraOu準拠)
                // 借用チェッカー対策: workerから必要な値をすべてローカルにコピー
                let summary = WorkerSummary::from(&*worker);
                let best_value = if worker.state.root_moves.is_empty() {
                    Value::ZERO
                } else {
                    worker.state.root_moves[0].score
                };
                let completed_depth = worker.state.completed_depth;
                let effort = if worker.state.root_moves.is_empty() {
                    0.0
                } else {
                    worker.state.root_moves[0].effort
                };
                let nodes = worker.state.nodes;
                let root_moves_len = worker.state.root_moves.len();
                let best_move_changes = summary.best_move_changes;
                worker.state.best_move_changes = 0.0; // 先にリセット

                // Native: Use helper_threads() to collect best_move_changes
                #[cfg(not(target_arch = "wasm32"))]
                let (changes_sum, thread_count) = {
                    let helper_threads = self.thread_pool.helper_threads();
                    let mut changes = Vec::with_capacity(helper_threads.len() + 1);
                    changes.push(best_move_changes);
                    for thread in helper_threads {
                        changes.push(thread.best_move_changes());
                    }
                    aggregate_best_move_changes(&changes)
                };

                // Wasm with wasm-threads: Use helper_best_move_changes() for realtime values
                #[cfg(all(target_arch = "wasm32", feature = "wasm-threads"))]
                let (changes_sum, thread_count) = {
                    let helper_changes = self.thread_pool.helper_best_move_changes();
                    let mut changes = Vec::with_capacity(helper_changes.len() + 1);
                    changes.push(best_move_changes);
                    changes.extend(helper_changes);
                    aggregate_best_move_changes(&changes)
                };

                // Wasm without wasm-threads: Only main thread
                #[cfg(all(target_arch = "wasm32", not(feature = "wasm-threads")))]
                let (changes_sum, thread_count) = (best_move_changes, 1);
                let tot_best_move_changes = self.tot_best_move_changes / 2.0 + changes_sum;
                if limits.use_time_management()
                    && !time_manager.stop_on_ponderhit()
                    && time_manager.search_end() == 0
                {
                    let (falling_eval, time_reduction, tot_changes, threads) = self
                        .compute_time_factors(
                            best_value,
                            completed_depth,
                            tot_best_move_changes,
                            thread_count,
                        );
                    let total_time = time_manager.total_time_for_iteration(
                        falling_eval,
                        time_reduction,
                        tot_changes,
                        threads,
                    );

                    // 実測 effort を正規化
                    let nodes_effort = normalize_nodes_effort(effort, nodes);

                    // 合法手が1つの場合は使う時間そのものを500msに丸める(YaneuraOu準拠)
                    let total_time = if root_moves_len == 1 {
                        total_time.min(500.0)
                    } else {
                        total_time
                    };
                    let elapsed_time = time_manager.elapsed_from_ponderhit() as f64;
                    time_manager.apply_iteration_timing(
                        time_manager.elapsed(),
                        total_time,
                        nodes_effort,
                        completed_depth,
                    );

                    // YaneuraOu準拠: 次iterationで深さを伸ばすかの判定
                    self.increase_depth =
                        time_manager.is_pondering() || elapsed_time <= total_time * 0.5138;

                    // 状態更新
                    self.update_time_factor_state(best_value, tot_best_move_changes);
                }
                // tot_best_move_changes は decay 後の値を保持(時間管理を使わない場合も持ち回る)
                self.tot_best_move_changes = tot_best_move_changes;

                // PVが変わったときのみ last_best_* を更新(YO準拠)
                if !worker.state.root_moves[0].pv.is_empty()
                    && worker.state.root_moves[0].pv[0] != last_best_pv[0]
                {
                    last_best_pv = worker.state.root_moves[0].pv.clone();
                    last_best_score = worker.state.root_moves[0].score;
                    last_best_move_depth = depth;
                }

                // YaneuraOu準拠: 詰みスコアが見つかっていたら早期終了
                // MultiPV=1の時のみ適用
                if effective_multi_pv == 1 && depth > 1 && !worker.state.root_moves.is_empty() {
                    let best_value = worker.state.root_moves[0].score;

                    if limits.mate == 0 {
                        if proven_mate_depth_exceeded(best_value, depth) {
                            break;
                        }
                    } else if mate_within_limit(
                        best_value,
                        worker.state.root_moves[0].score_lower_bound,
                        worker.state.root_moves[0].score_upper_bound,
                        limits.mate,
                    ) {
                        time_manager.request_stop();
                        break;
                    }
                }
            }
        }

        // 中断した探索で信頼できないPVになった場合のフォールバック(YO準拠)
        if worker.state.abort
            && !worker.state.root_moves.is_empty()
            && worker.state.root_moves[0].score.is_loss()
        {
            let head = last_best_pv.first().copied().unwrap_or(Move::NONE);
            if head != Move::NONE {
                if let Some(idx) = worker.state.root_moves.find(head) {
                    worker.state.root_moves.move_to_front(idx);
                    worker.state.root_moves[0].pv = last_best_pv;
                    worker.state.root_moves[0].score = last_best_score;
                    worker.state.completed_depth = last_best_move_depth;
                }
            }
        }

        // workerを戻す
        self.worker = Some(worker);

        effective_multi_pv
    }
}

// search_helper_impl is the core search logic used by helper threads.
// Progress callbacks are passed as closures to allow platform-specific progress tracking.
// Only compiled for Native and Wasm with wasm-threads (single-threaded Wasm doesn't use helper threads).
#[cfg(any(not(target_arch = "wasm32"), feature = "wasm-threads"))]
#[inline(always)]
fn search_helper_impl<F1, F2>(
    worker: &mut SearchWorker,
    pos: &mut Position,
    limits: &LimitsType,
    time_manager: &mut TimeManagement,
    max_depth: Depth,
    skill_enabled: bool,
    on_start: F1,
    mut on_depth_complete: F2,
) -> usize
where
    F1: FnOnce(),
    F2: FnMut(u64, f64),
{
    on_start();

    worker.state.root_moves = super::RootMoves::from_legal_moves(pos, &limits.search_moves);

    if worker.state.root_moves.is_empty() {
        worker.state.best_move = Move::NONE;
        return 0;
    }

    // 合法手が1つの場合は500ms上限を適用(YaneuraOu準拠)
    if worker.state.root_moves.len() == 1 {
        time_manager.apply_single_move_limit();
    }

    let mut effective_multi_pv = limits.multi_pv;
    if skill_enabled {
        effective_multi_pv = effective_multi_pv.max(4);
    }
    effective_multi_pv = effective_multi_pv.min(worker.state.root_moves.len());

    let mut last_best_pv = vec![Move::NONE];
    let mut last_best_score = Value::new(-Value::INFINITE.raw());
    let mut last_best_move_depth = 0;

    let search_again_counter = 0;

    for depth in 1..=max_depth {
        if worker.state.abort {
            break;
        }

        if effective_multi_pv == 1 && depth > 1 && !worker.state.root_moves.is_empty() {
            let best_value = worker.state.root_moves[0].score;

            if limits.mate == 0 {
                if proven_mate_depth_exceeded(best_value, depth) {
                    break;
                }
            } else if mate_within_limit(
                best_value,
                worker.state.root_moves[0].score_lower_bound,
                worker.state.root_moves[0].score_upper_bound,
                limits.mate,
            ) {
                break;
            }
        }

        let search_depth = depth;

        worker.state.root_depth = search_depth;
        worker.state.sel_depth = 0;

        for pv_idx in 0..effective_multi_pv {
            if worker.state.abort {
                break;
            }

            let (mut alpha, mut beta, mut delta) =
                compute_aspiration_window(&worker.state.root_moves[pv_idx], worker.thread_id);
            let mut failed_high_cnt = 0;

            loop {
                let adjusted_depth =
                    (search_depth - failed_high_cnt - (3 * (search_again_counter + 1) / 4)).max(1);
                let score = if pv_idx == 0 {
                    worker.search_root(pos, adjusted_depth, alpha, beta, limits, time_manager)
                } else {
                    worker.search_root_for_pv(
                        pos,
                        search_depth,
                        alpha,
                        beta,
                        pv_idx,
                        limits,
                        time_manager,
                    )
                };

                if worker.state.abort {
                    break;
                }

                if score <= alpha {
                    beta = alpha;
                    alpha = Value::new(
                        score.raw().saturating_sub(delta.raw()).max(-Value::INFINITE.raw()),
                    );
                    failed_high_cnt = 0;
                } else if score >= beta {
                    beta = Value::new(
                        score.raw().saturating_add(delta.raw()).min(Value::INFINITE.raw()),
                    );
                    failed_high_cnt += 1;
                } else {
                    break;
                }

                delta = Value::new(
                    delta.raw().saturating_add(delta.raw() / 3).min(Value::INFINITE.raw()),
                );
            }

            worker.state.root_moves.stable_sort_range(pv_idx, worker.state.root_moves.len());
            worker.state.root_moves.stable_sort_range(0, pv_idx + 1);
        }

        if !worker.state.abort && effective_multi_pv > 1 {
            worker.state.root_moves.stable_sort_range(0, effective_multi_pv);
        }

        if !worker.state.abort {
            worker.state.completed_depth = search_depth;
            worker.state.best_move = worker.state.root_moves[0].mv();

            for rm in worker.state.root_moves.iter_mut() {
                rm.previous_score = rm.score;
            }

            let best_move_changes = worker.state.best_move_changes;
            worker.state.best_move_changes = 0.0;
            on_depth_complete(worker.state.nodes, best_move_changes);

            if !worker.state.root_moves[0].pv.is_empty()
                && worker.state.root_moves[0].pv[0] != last_best_pv[0]
            {
                last_best_pv = worker.state.root_moves[0].pv.clone();
                last_best_score = worker.state.root_moves[0].score;
                last_best_move_depth = search_depth;
            }

            if effective_multi_pv == 1 && depth > 1 && !worker.state.root_moves.is_empty() {
                let best_value = worker.state.root_moves[0].score;

                if limits.mate == 0 {
                    if proven_mate_depth_exceeded(best_value, depth) {
                        break;
                    }
                } else if mate_within_limit(
                    best_value,
                    worker.state.root_moves[0].score_lower_bound,
                    worker.state.root_moves[0].score_upper_bound,
                    limits.mate,
                ) {
                    break;
                }
            }
        }
    }

    if worker.state.abort
        && !worker.state.root_moves.is_empty()
        && worker.state.root_moves[0].score.is_loss()
    {
        let head = last_best_pv.first().copied().unwrap_or(Move::NONE);
        if head != Move::NONE {
            if let Some(idx) = worker.state.root_moves.find(head) {
                worker.state.root_moves.move_to_front(idx);
                worker.state.root_moves[0].pv = last_best_pv;
                worker.state.root_moves[0].score = last_best_score;
                worker.state.completed_depth = last_best_move_depth;
            }
        }
    }

    effective_multi_pv
}

// Native version: takes progress parameter for tracking helper thread statistics.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn search_helper(
    worker: &mut SearchWorker,
    pos: &mut Position,
    limits: &LimitsType,
    time_manager: &mut TimeManagement,
    max_depth: Depth,
    skill_enabled: bool,
    progress: Option<&SearchProgress>,
) -> usize {
    search_helper_impl(
        worker,
        pos,
        limits,
        time_manager,
        max_depth,
        skill_enabled,
        || {
            if let Some(p) = progress {
                p.reset();
            }
        },
        |nodes, bmc| {
            if let Some(p) = progress {
                p.update(nodes, bmc);
            }
        },
    )
}

// Wasm with wasm-threads: takes progress parameter for tracking helper thread statistics.
#[cfg(all(target_arch = "wasm32", feature = "wasm-threads"))]
pub(crate) fn search_helper(
    worker: &mut SearchWorker,
    pos: &mut Position,
    limits: &LimitsType,
    time_manager: &mut TimeManagement,
    max_depth: Depth,
    skill_enabled: bool,
    progress: Option<&super::thread::HelperProgress>,
) -> usize {
    search_helper_impl(
        worker,
        pos,
        limits,
        time_manager,
        max_depth,
        skill_enabled,
        || {
            if let Some(p) = progress {
                p.reset();
            }
        },
        |nodes, bmc| {
            if let Some(p) = progress {
                p.update(nodes, bmc);
            }
        },
    )
}

// Wasm without wasm-threads: search_helper is not needed because there are no helper threads.
// Single-threaded Wasm only uses the main thread search in search_with_callback().

// =============================================================================
// テスト
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    /// SearchWorkerは大きなスタック領域を使うため、テストは別スレッドで実行
    const STACK_SIZE: usize = 64 * 1024 * 1024; // 64MB

    #[test]
    fn test_aggregate_best_move_changes_empty() {
        let (sum, threads) = aggregate_best_move_changes(&[]);
        assert_eq!(sum, 0.0);
        assert_eq!(threads, 1);
    }

    #[test]
    fn test_aggregate_best_move_changes_multi() {
        let (sum, threads) = aggregate_best_move_changes(&[1.0, 2.0, 3.0]);
        assert!((sum - 6.0).abs() < 1e-9, "sum should be 6.0, got {sum}");
        assert_eq!(threads, 3);
    }

    #[test]
    fn test_worker_summary_from_worker() {
        // SearchWorker はスタックを大きく消費するため、別スレッドで実行する。
        std::thread::Builder::new()
            .stack_size(STACK_SIZE)
            .spawn(|| {
                let tt = Arc::new(TranspositionTable::new(16));
                let eval_hash = Arc::new(EvalHash::new(1));
                let mut worker = SearchWorker::new(tt, eval_hash, DEFAULT_MAX_MOVES_TO_DRAW, 0);
                worker.state.best_move_changes = 3.5;

                let summary = WorkerSummary::from(&*worker);
                assert!(
                    (summary.best_move_changes - 3.5).abs() < 1e-9,
                    "best_move_changes should match"
                );
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_prepare_time_metrics_resets_iter_state() {
        std::thread::Builder::new()
            .stack_size(STACK_SIZE)
            .spawn(|| {
                let mut search = Search::new(16);
                search.best_previous_score = Some(Value::new(200));
                search.best_previous_average_score = Some(Value::new(123));
                search.last_game_ply = Some(5);
                search.iter_value = [Value::new(1), Value::new(2), Value::new(3), Value::new(4)];
                search.iter_idx = 2;
                search.last_best_move_depth = 5;
                search.tot_best_move_changes = 7.5;

                search.prepare_time_metrics(6);

                assert_eq!(search.best_previous_score, Some(Value::new(-200)));
                assert_eq!(search.best_previous_average_score, Some(Value::new(-123)));
                assert_eq!(search.iter_value, [Value::new(-200); 4]);
                assert_eq!(search.iter_idx, 0);
                assert_eq!(search.last_best_move_depth, 0);
                assert_eq!(search.tot_best_move_changes, 0.0);
                assert_eq!(search.last_game_ply, Some(6));
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_prepare_time_metrics_seeds_zero_for_infinite() {
        std::thread::Builder::new()
            .stack_size(STACK_SIZE)
            .spawn(|| {
                let mut search = Search::new(16);
                search.best_previous_score = Some(Value::INFINITE);
                search.best_previous_average_score = Some(Value::INFINITE);

                search.prepare_time_metrics(1);

                assert_eq!(search.iter_value, [Value::ZERO; 4]);
                assert_eq!(search.iter_idx, 0);
                assert_eq!(search.best_previous_score, Some(Value::INFINITE));
                assert_eq!(search.best_previous_average_score, Some(Value::INFINITE));
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_set_max_moves_to_draw_option() {
        std::thread::Builder::new()
            .stack_size(STACK_SIZE)
            .spawn(|| {
                let mut search = Search::new(16);
                search.set_max_moves_to_draw(512);
                assert_eq!(search.max_moves_to_draw(), 512);

                search.set_max_moves_to_draw(0);
                assert_eq!(search.max_moves_to_draw(), DEFAULT_MAX_MOVES_TO_DRAW);
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_mate_within_limit_converts_moves_to_plies() {
        // mate in 9 ply is within a 5-move limit (10 ply)
        assert!(mate_within_limit(Value::mate_in(9), false, false, 5));
        assert!(!mate_within_limit(Value::mate_in(11), false, false, 5));
    }

    #[test]
    fn test_mate_within_limit_handles_mated_scores() {
        // mated in 7 ply should still trigger when limit is 4 moves (8 ply)
        assert!(mate_within_limit(Value::mated_in(7), false, false, 4));
    }

    #[test]
    fn test_mate_within_limit_requires_exact_score() {
        assert!(!mate_within_limit(Value::mate_in(7), true, false, 4));
        assert!(!mate_within_limit(Value::mate_in(7), false, true, 4));
    }

    #[test]
    fn test_search_basic() {
        // スタックサイズを増やした別スレッドで実行
        std::thread::Builder::new()
            .stack_size(STACK_SIZE)
            .spawn(|| {
                let mut search = Search::new(16);
                let mut pos = Position::new();
                pos.set_hirate();

                let limits = LimitsType {
                    depth: 3,
                    ..Default::default()
                };

                let result = search.go(&mut pos, limits, None::<fn(&SearchInfo)>);

                assert_ne!(result.best_move, Move::NONE, "Should find a best move");
                assert!(result.depth >= 1, "Should complete at least depth 1");
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_search_with_callback() {
        // スタックサイズを増やした別スレッドで実行
        std::thread::Builder::new()
            .stack_size(STACK_SIZE)
            .spawn(|| {
                let mut search = Search::new(16);
                let mut pos = Position::new();
                pos.set_hirate();

                let limits = LimitsType {
                    depth: 2,
                    ..Default::default()
                };

                let mut info_count = 0;
                let result = search.go(
                    &mut pos,
                    limits,
                    Some(|_info: &SearchInfo| {
                        info_count += 1;
                    }),
                );

                assert_ne!(result.best_move, Move::NONE, "Should find a best move");
                assert!(info_count >= 1, "Should have called info callback at least once");
            })
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_search_info_to_usi() {
        let info = SearchInfo {
            depth: 5,
            sel_depth: 7,
            score: Value::new(123),
            nodes: 10000,
            time_ms: 500,
            nps: 20000,
            hashfull: 100,
            pv: vec![],
            multi_pv: 1,
        };

        let usi = info.to_usi_string();
        assert!(usi.contains("depth 5"));
        assert!(usi.contains("seldepth 7"));
        assert!(usi.contains("multipv 1"));
        assert!(usi.contains("score cp 123"));
        assert!(usi.contains("nodes 10000"));
    }

    #[test]
    fn test_search_info_to_usi_formats_mate_score() {
        let info = SearchInfo {
            depth: 9,
            sel_depth: 9,
            score: Value::mate_in(5),
            nodes: 42,
            time_ms: 10,
            nps: 4200,
            hashfull: 0,
            pv: vec![],
            multi_pv: 1,
        };

        let usi = info.to_usi_string();
        assert!(usi.contains("score mate 5"));
    }

    #[test]
    fn test_search_info_to_usi_formats_mated_score_with_negative_sign() {
        let info = SearchInfo {
            depth: 9,
            sel_depth: 9,
            score: Value::mated_in(4),
            nodes: 42,
            time_ms: 10,
            nps: 4200,
            hashfull: 0,
            pv: vec![],
            multi_pv: 1,
        };

        let usi = info.to_usi_string();
        assert!(usi.contains("score mate -4"));
    }
}