swarm-engine-core 0.1.6

Core types and orchestration for SwarmEngine
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
//! LLM-based OperatorProvider - LLM による探索戦略の動的決定
//!
//! AdaptiveOperatorProvider をベースに、LLM による戦略レビューを組み合わせた
//! AdaptiveLlmOperatorProvider を提供する。
//!
//! # 設計
//!
//! ```text
//! AdaptiveLlmOperatorProvider
//! ├── AdaptiveOperatorProvider (ベースのルールロジック)
//! └── StrategyAdvisor (LLM 戦略レビュー)
//!
//! 1. 通常: AdaptiveOperatorProvider のルールベース判断
//! 2. レビュー条件を満たした時: LLM に問い合わせ(同期ブロック)
//! 3. LLM が変更を推奨 + 信頼度が閾値以上: 戦略を切り替え
//! 4. LLM エラー時: AdaptiveOperatorProvider にフォールバック
//! ```
//!
//! # 使用例
//!
//! ```ignore
//! use swarm_engine_core::exploration::{AdaptiveLlmOperatorProvider, ReviewPolicy};
//! use swarm_engine_llm::LlmStrategyAdvisor;
//!
//! let advisor = LlmStrategyAdvisor::new(decider, runtime);
//! let provider = AdaptiveLlmOperatorProvider::new(Box::new(advisor))
//!     .with_policy(ReviewPolicy::default());
//!
//! let orchestrator = OrchestratorBuilder::new()
//!     .operator_provider(provider)
//!     .build(runtime);
//! ```

use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::RwLock;
use std::time::Instant;

use super::map::MapNodeState;
use super::mutation::ActionNodeData;
use super::node_rules::Rules;
use super::operator::{ConfigurableOperator, Operator, RulesBasedMutation};
use super::provider::{AdaptiveOperatorProvider, OperatorProvider, ProviderContext};
use super::selection::{AnySelection, SelectionKind};
use crate::events::{LearningEvent, LearningEventChannel};
use crate::online_stats::SwarmStats;

// ============================================================================
// StrategyContext - 戦略判断に必要なコンテキスト
// ============================================================================

/// 戦略判断に必要なコンテキスト
#[derive(Debug, Clone)]
pub struct StrategyContext {
    /// フロンティア数
    pub frontier_count: usize,
    /// 総訪問数
    pub total_visits: u32,
    /// 失敗率 (0.0-1.0)
    pub failure_rate: f64,
    /// 成功率 (0.0-1.0)
    pub success_rate: f64,
    /// 現在の戦略
    pub current_strategy: SelectionKind,
    /// 探索の深さ(平均)- オプション
    pub avg_depth: Option<f32>,
}

impl StrategyContext {
    /// 新しい StrategyContext を作成
    pub fn new(
        frontier_count: usize,
        total_visits: u32,
        failure_rate: f64,
        current_strategy: SelectionKind,
    ) -> Self {
        Self {
            frontier_count,
            total_visits,
            failure_rate,
            success_rate: 1.0 - failure_rate,
            current_strategy,
            avg_depth: None,
        }
    }

    /// SwarmStats と ProviderContext から構築
    pub fn from_provider_context(
        ctx: &ProviderContext<'_, ActionNodeData, String, MapNodeState>,
        current: SelectionKind,
    ) -> Self {
        Self {
            frontier_count: ctx.frontier_count(),
            total_visits: ctx.total_visits(),
            failure_rate: ctx.stats.failure_rate(),
            success_rate: ctx.stats.success_rate(),
            current_strategy: current,
            avg_depth: None,
        }
    }

    /// SwarmStats から構築
    pub fn from_stats(stats: &SwarmStats, frontier_count: usize, current: SelectionKind) -> Self {
        Self {
            frontier_count,
            total_visits: stats.total_visits(),
            failure_rate: stats.failure_rate(),
            success_rate: stats.success_rate(),
            current_strategy: current,
            avg_depth: None,
        }
    }

    /// 平均深度を設定
    pub fn with_avg_depth(mut self, depth: f32) -> Self {
        self.avg_depth = Some(depth);
        self
    }
}

// ============================================================================
// StrategyAdvice - 戦略アドバイスの結果
// ============================================================================

/// 戦略アドバイスの結果
#[derive(Debug, Clone)]
pub struct StrategyAdvice {
    /// 推奨する戦略
    pub recommended: SelectionKind,
    /// 変更すべきか(現状維持なら false)
    pub should_change: bool,
    /// 理由(デバッグ用)
    pub reason: String,
    /// 信頼度 (0.0-1.0)
    pub confidence: f64,
}

impl StrategyAdvice {
    /// 変更なしのアドバイスを作成
    pub fn no_change(current: SelectionKind, reason: impl Into<String>) -> Self {
        Self {
            recommended: current,
            should_change: false,
            reason: reason.into(),
            confidence: 1.0,
        }
    }

    /// 変更ありのアドバイスを作成
    pub fn change_to(new: SelectionKind, reason: impl Into<String>, confidence: f64) -> Self {
        Self {
            recommended: new,
            should_change: true,
            reason: reason.into(),
            confidence,
        }
    }
}

// ============================================================================
// StrategyAdviceError
// ============================================================================

/// 戦略アドバイスエラー
#[derive(Debug, Clone, thiserror::Error)]
pub enum StrategyAdviceError {
    /// LLM 呼び出しエラー
    #[error("LLM call failed: {0}")]
    LlmError(String),
    /// レスポンスパースエラー
    #[error("Failed to parse response: {0}")]
    ParseError(String),
    /// アドバイザー利用不可
    #[error("Advisor not available")]
    Unavailable,
}

// ============================================================================
// StrategyAdvisor trait
// ============================================================================

/// 戦略アドバイザー trait
///
/// 探索状態を受け取り、最適な戦略を推奨する。
/// 同期インターフェース(SLM ローカル前提、~100ms)。
pub trait StrategyAdvisor: Send + Sync {
    /// 戦略をレビューしてアドバイスを返す
    fn advise(&self, context: &StrategyContext) -> Result<StrategyAdvice, StrategyAdviceError>;

    /// アドバイザー名
    fn name(&self) -> &str;
}

// ============================================================================
// ReviewPolicy - レビュー条件の設定
// ============================================================================

/// レビュー条件の設定
#[derive(Debug, Clone)]
pub struct ReviewPolicy {
    /// レビュー間隔(visits 単位)
    pub interval: u32,
    /// 最小レビュー間隔(連続レビュー防止)
    pub min_interval: u32,
    /// 状態変化でトリガーする閾値(failure_rate の変化量)
    pub state_change_threshold: f64,
}

impl Default for ReviewPolicy {
    fn default() -> Self {
        Self {
            interval: 20,                 // 20 visits 毎
            min_interval: 5,              // 最低5回は間隔を空ける
            state_change_threshold: 0.15, // 15%以上の変化でトリガー
        }
    }
}

impl ReviewPolicy {
    /// 新しい ReviewPolicy を作成
    pub fn new(interval: u32, min_interval: u32, state_change_threshold: f64) -> Self {
        Self {
            interval,
            min_interval,
            state_change_threshold: state_change_threshold.clamp(0.0, 1.0),
        }
    }

    /// 頻繁にレビューする設定
    pub fn frequent() -> Self {
        Self {
            interval: 10,
            min_interval: 3,
            state_change_threshold: 0.1,
        }
    }

    /// 控えめにレビューする設定
    pub fn conservative() -> Self {
        Self {
            interval: 50,
            min_interval: 20,
            state_change_threshold: 0.25,
        }
    }
}

// ============================================================================
// AdaptiveLlmOperatorProvider - LLM と Adaptive のハイブリッド Provider
// ============================================================================

/// Adaptive LLM Operator Provider
///
/// AdaptiveOperatorProvider をベースに、LLM による戦略レビューを組み合わせる。
///
/// # 動作
///
/// 1. 通常: AdaptiveOperatorProvider のルールベース判断
/// 2. レビュー条件を満たした時: LLM に問い合わせ(同期ブロック、~100ms)
/// 3. LLM が変更を推奨 + 信頼度が閾値以上: 戦略を切り替え
/// 4. LLM エラー時: AdaptiveOperatorProvider にフォールバック
pub struct AdaptiveLlmOperatorProvider {
    /// ベースの Adaptive ロジック
    adaptive: AdaptiveOperatorProvider,
    /// 戦略アドバイザー
    advisor: Box<dyn StrategyAdvisor>,
    /// レビューポリシー
    policy: ReviewPolicy,
    /// UCB1 の探索係数
    ucb1_c: f64,
    /// 最後のレビュー時点の visits
    last_review_visits: AtomicU32,
    /// 最後のレビュー時点の failure_rate(f64 * 1000 で保存)
    last_failure_rate: AtomicU32,
    /// LLM によるオーバーライド(None = Adaptive に従う)
    llm_override: RwLock<Option<SelectionKind>>,
}

impl AdaptiveLlmOperatorProvider {
    /// 新しい AdaptiveLlmOperatorProvider を作成
    pub fn new(advisor: Box<dyn StrategyAdvisor>) -> Self {
        Self {
            adaptive: AdaptiveOperatorProvider::default(),
            advisor,
            policy: ReviewPolicy::default(),
            ucb1_c: std::f64::consts::SQRT_2,
            last_review_visits: AtomicU32::new(0),
            last_failure_rate: AtomicU32::new(0),
            llm_override: RwLock::new(None),
        }
    }

    /// レビューポリシーを設定
    pub fn with_policy(mut self, policy: ReviewPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// ベースの AdaptiveOperatorProvider を設定
    pub fn with_adaptive(mut self, adaptive: AdaptiveOperatorProvider) -> Self {
        self.adaptive = adaptive;
        self
    }

    /// UCB1 の探索係数を設定
    pub fn with_ucb1_c(mut self, c: f64) -> Self {
        self.ucb1_c = c;
        self
    }

    /// 現在の LLM override を取得
    pub fn llm_override(&self) -> Option<SelectionKind> {
        *self.llm_override.read().unwrap()
    }

    /// レビューが必要か判定
    fn should_review(&self, stats: &SwarmStats) -> bool {
        let current_visits = stats.total_visits();
        let last_visits = self.last_review_visits.load(Ordering::Relaxed);

        // 最小間隔チェック
        if current_visits < last_visits + self.policy.min_interval {
            return false;
        }

        // 定期レビュー
        if current_visits >= last_visits + self.policy.interval {
            return true;
        }

        // 状態変化チェック(failure_rate の急変)
        let current_rate = (stats.failure_rate() * 1000.0) as u32;
        let last_rate = self.last_failure_rate.load(Ordering::Relaxed);
        let rate_diff = (current_rate as i32 - last_rate as i32).unsigned_abs() as f64 / 1000.0;

        rate_diff >= self.policy.state_change_threshold
    }

    /// LLM レビューを実行
    fn do_review(
        &self,
        stats: &SwarmStats,
        frontier_count: usize,
        current: SelectionKind,
    ) -> Option<SelectionKind> {
        let context = StrategyContext::from_stats(stats, frontier_count, current);

        // タイミング計測開始
        let start_time = Instant::now();

        // 同期ブロッキング呼び出し(~100ms 想定)
        let result = self.advisor.advise(&context);

        // タイミング計測終了
        let elapsed = start_time.elapsed();

        match result {
            Ok(advice) => {
                let latency_ms = elapsed.as_millis() as u64;

                // 学習記録: LearningEventChannel に emit
                let tick = LearningEventChannel::global().current_tick();
                LearningEventChannel::global().emit(
                    LearningEvent::strategy_advice(tick, self.advisor.name())
                        .current_strategy(current.to_string())
                        .recommended(advice.recommended.to_string())
                        .should_change(advice.should_change)
                        .confidence(advice.confidence)
                        .reason(&advice.reason)
                        .frontier_count(frontier_count)
                        .total_visits(stats.total_visits())
                        .failure_rate(stats.failure_rate())
                        .latency_ms(latency_ms)
                        .success()
                        .build(),
                );

                // 構造化ログも出力(デバッグ/監視用)
                tracing::debug!(
                    target: "swarm_engine::learning",
                    advisor = %self.advisor.name(),
                    current_strategy = %current,
                    recommended = %advice.recommended,
                    should_change = advice.should_change,
                    confidence = advice.confidence,
                    reason = %advice.reason,
                    latency_ms = latency_ms,
                    "Strategy advice completed"
                );

                // レビュー状態を更新
                self.last_review_visits
                    .store(stats.total_visits(), Ordering::Relaxed);
                self.last_failure_rate
                    .store((stats.failure_rate() * 1000.0) as u32, Ordering::Relaxed);

                if advice.should_change {
                    Some(advice.recommended)
                } else {
                    None
                }
            }
            Err(e) => {
                let latency_ms = elapsed.as_millis() as u64;

                // 学習記録: LearningEventChannel に emit(エラー時)
                let tick = LearningEventChannel::global().current_tick();
                LearningEventChannel::global().emit(
                    LearningEvent::strategy_advice(tick, self.advisor.name())
                        .current_strategy(current.to_string())
                        .recommended(current.to_string()) // エラー時は変更なし
                        .frontier_count(frontier_count)
                        .total_visits(stats.total_visits())
                        .failure_rate(stats.failure_rate())
                        .latency_ms(latency_ms)
                        .failure(e.to_string())
                        .build(),
                );

                // 構造化ログ(エラー)
                tracing::warn!(
                    advisor = %self.advisor.name(),
                    error = %e,
                    latency_ms = latency_ms,
                    "Strategy advisor failed, falling back to Adaptive"
                );
                None
            }
        }
    }

    /// 現在有効な SelectionKind を取得
    fn effective_selection(&self, stats: &SwarmStats) -> SelectionKind {
        // LLM override があればそれを使用
        if let Some(kind) = *self.llm_override.read().unwrap() {
            return kind;
        }
        // なければ Adaptive のルール
        self.adaptive.current_selection(stats)
    }
}

impl<R> OperatorProvider<R> for AdaptiveLlmOperatorProvider
where
    R: Rules + 'static,
{
    fn provide(
        &self,
        rules: R,
        context: Option<&ProviderContext<'_, ActionNodeData, String, MapNodeState>>,
    ) -> ConfigurableOperator<R> {
        let selection_kind = match context {
            Some(ctx) => {
                let current = self.effective_selection(ctx.stats);

                // レビュー条件を満たしていれば LLM に問い合わせ
                if self.should_review(ctx.stats) {
                    if let Some(new_kind) = self.do_review(ctx.stats, ctx.frontier_count(), current)
                    {
                        *self.llm_override.write().unwrap() = Some(new_kind);
                        new_kind
                    } else {
                        current
                    }
                } else {
                    current
                }
            }
            None => SelectionKind::Ucb1, // 初回は UCB1
        };

        let selection = AnySelection::from_kind(selection_kind, self.ucb1_c);
        Operator::new(RulesBasedMutation::new(), selection, rules)
    }

    fn reevaluate(
        &self,
        operator: &mut ConfigurableOperator<R>,
        context: &ProviderContext<'_, ActionNodeData, String, MapNodeState>,
    ) {
        let current = operator.selection().kind();

        // レビュー条件を満たしていれば LLM に問い合わせ
        if self.should_review(context.stats) {
            if let Some(new_kind) = self.do_review(context.stats, context.frontier_count(), current)
            {
                if new_kind != current {
                    tracing::info!(
                        from = %current,
                        to = %new_kind,
                        "Strategy changed by LLM advisor"
                    );
                    operator.set_selection(AnySelection::from_kind(new_kind, self.ucb1_c));
                    *self.llm_override.write().unwrap() = Some(new_kind);
                }
                return;
            }
        }

        // LLM が変更しない場合は Adaptive のルールを適用
        // ただし llm_override がある場合はそれを維持
        if self.llm_override.read().unwrap().is_none() {
            self.adaptive.reevaluate(operator, context);
        }
    }

    fn name(&self) -> &str {
        "HybridLlm"
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::events::{ActionEventBuilder, ActionEventResult};
    use crate::exploration::{GraphMap, NodeRules};
    use crate::types::WorkerId;

    fn record_success(stats: &mut SwarmStats, action: &str) {
        let event = ActionEventBuilder::new(0, WorkerId(0), action)
            .result(ActionEventResult::success())
            .build();
        stats.record(&event);
    }

    fn record_failure(stats: &mut SwarmStats, action: &str) {
        let event = ActionEventBuilder::new(0, WorkerId(0), action)
            .result(ActionEventResult::failure("error"))
            .build();
        stats.record(&event);
    }

    // ========================================================================
    // Mock StrategyAdvisor for testing
    // ========================================================================

    struct MockAdvisor {
        advice: StrategyAdvice,
        call_count: std::sync::atomic::AtomicUsize,
    }

    impl MockAdvisor {
        fn new(advice: StrategyAdvice) -> Self {
            Self {
                advice,
                call_count: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        fn call_count(&self) -> usize {
            self.call_count.load(Ordering::Relaxed)
        }
    }

    impl StrategyAdvisor for MockAdvisor {
        fn advise(
            &self,
            _context: &StrategyContext,
        ) -> Result<StrategyAdvice, StrategyAdviceError> {
            self.call_count
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Ok(self.advice.clone())
        }

        fn name(&self) -> &str {
            "MockAdvisor"
        }
    }

    struct FailingAdvisor;

    impl StrategyAdvisor for FailingAdvisor {
        fn advise(
            &self,
            _context: &StrategyContext,
        ) -> Result<StrategyAdvice, StrategyAdviceError> {
            Err(StrategyAdviceError::LlmError("Mock error".into()))
        }

        fn name(&self) -> &str {
            "FailingAdvisor"
        }
    }

    // ========================================================================
    // StrategyContext Tests
    // ========================================================================

    #[test]
    fn test_strategy_context_new() {
        let ctx = StrategyContext::new(15, 47, 0.23, SelectionKind::Ucb1);
        assert_eq!(ctx.frontier_count, 15);
        assert_eq!(ctx.total_visits, 47);
        assert!((ctx.failure_rate - 0.23).abs() < 0.001);
        assert!((ctx.success_rate - 0.77).abs() < 0.001);
        assert_eq!(ctx.current_strategy, SelectionKind::Ucb1);
    }

    #[test]
    fn test_strategy_context_from_stats() {
        let mut stats = SwarmStats::new();
        for _ in 0..7 {
            record_success(&mut stats, "action");
        }
        for _ in 0..3 {
            record_failure(&mut stats, "action");
        }

        let ctx = StrategyContext::from_stats(&stats, 10, SelectionKind::Greedy);
        assert_eq!(ctx.frontier_count, 10);
        assert_eq!(ctx.total_visits, 10);
        assert!((ctx.failure_rate - 0.3).abs() < 0.01);
    }

    // ========================================================================
    // ReviewPolicy Tests
    // ========================================================================

    #[test]
    fn test_review_policy_default() {
        let policy = ReviewPolicy::default();
        assert_eq!(policy.interval, 20);
        assert_eq!(policy.min_interval, 5);
        assert!((policy.state_change_threshold - 0.15).abs() < 0.001);
    }

    #[test]
    fn test_review_policy_frequent() {
        let policy = ReviewPolicy::frequent();
        assert_eq!(policy.interval, 10);
        assert_eq!(policy.min_interval, 3);
    }

    #[test]
    fn test_review_policy_conservative() {
        let policy = ReviewPolicy::conservative();
        assert_eq!(policy.interval, 50);
        assert_eq!(policy.min_interval, 20);
    }

    // ========================================================================
    // AdaptiveLlmOperatorProvider Tests
    // ========================================================================

    #[test]
    fn test_hybrid_provider_initial_ucb1() {
        let advice = StrategyAdvice::no_change(SelectionKind::Ucb1, "test");
        let advisor = MockAdvisor::new(advice);
        let provider = AdaptiveLlmOperatorProvider::new(Box::new(advisor));
        let rules = NodeRules::for_testing();

        // Context なしで構築 → UCB1
        let operator = provider.provide(rules, None);
        assert_eq!(operator.name(), "RulesBased+UCB1");
    }

    #[test]
    fn test_hybrid_provider_review_at_interval() {
        let advice = StrategyAdvice::change_to(SelectionKind::Greedy, "test", 0.9);
        let advisor = MockAdvisor::new(advice);
        let provider =
            AdaptiveLlmOperatorProvider::new(Box::new(advisor)).with_policy(ReviewPolicy {
                interval: 10,
                min_interval: 5,
                state_change_threshold: 0.5,
            });
        let rules = NodeRules::for_testing();

        // stats を作成(20 visits)
        let mut stats = SwarmStats::new();
        for _ in 0..20 {
            record_success(&mut stats, "action");
        }

        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let ctx = ProviderContext::new(&map, &stats);

        // レビュー条件(interval=10)を満たしているので LLM に問い合わせ
        let operator = provider.provide(rules, Some(&ctx));
        assert_eq!(operator.name(), "RulesBased+Greedy");

        // advisor が呼ばれた
        let advisor_ref = provider.advisor.as_ref();
        let mock = unsafe { &*(advisor_ref as *const dyn StrategyAdvisor as *const MockAdvisor) };
        assert_eq!(mock.call_count(), 1);
    }

    #[test]
    fn test_hybrid_provider_no_review_before_min_interval() {
        let advice = StrategyAdvice::change_to(SelectionKind::Greedy, "test", 0.9);
        let advisor = MockAdvisor::new(advice);
        let provider =
            AdaptiveLlmOperatorProvider::new(Box::new(advisor)).with_policy(ReviewPolicy {
                interval: 10,
                min_interval: 5,
                state_change_threshold: 0.5,
            });
        let rules = NodeRules::for_testing();

        // stats を作成(3 visits = min_interval 未満)
        let mut stats = SwarmStats::new();
        for _ in 0..3 {
            record_success(&mut stats, "action");
        }

        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let ctx = ProviderContext::new(&map, &stats);

        // min_interval 未満なのでレビューしない → Adaptive のルール(UCB1)
        let operator = provider.provide(rules, Some(&ctx));
        assert_eq!(operator.name(), "RulesBased+UCB1");
    }

    #[test]
    fn test_hybrid_provider_fallback_on_error() {
        let provider =
            AdaptiveLlmOperatorProvider::new(Box::new(FailingAdvisor)).with_policy(ReviewPolicy {
                interval: 1,
                min_interval: 1,
                state_change_threshold: 0.0,
            });
        let rules = NodeRules::for_testing();

        let mut stats = SwarmStats::new();
        for _ in 0..10 {
            record_success(&mut stats, "action");
        }

        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let ctx = ProviderContext::new(&map, &stats);

        // advisor がエラーを返すが、フォールバックで動作
        let operator = provider.provide(rules, Some(&ctx));
        // Adaptive のルール(成熟 + 低エラー → Greedy)が適用される
        assert!(operator.name().contains("RulesBased"));
    }

    #[test]
    fn test_hybrid_provider_reevaluate() {
        let advice = StrategyAdvice::change_to(SelectionKind::Thompson, "high variance", 0.85);
        let advisor = MockAdvisor::new(advice);
        let provider =
            AdaptiveLlmOperatorProvider::new(Box::new(advisor)).with_policy(ReviewPolicy {
                interval: 5,
                min_interval: 1,
                state_change_threshold: 0.5,
            });
        let rules = NodeRules::for_testing();

        // 初期状態で構築
        let mut operator = provider.provide(rules, None);
        assert_eq!(operator.selection().kind(), SelectionKind::Ucb1);

        // stats を更新
        let mut stats = SwarmStats::new();
        for _ in 0..10 {
            record_success(&mut stats, "action");
        }
        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let ctx = ProviderContext::new(&map, &stats);

        // reevaluate で Thompson に切り替わる
        provider.reevaluate(&mut operator, &ctx);
        assert_eq!(operator.selection().kind(), SelectionKind::Thompson);
    }

    #[test]
    fn test_hybrid_provider_state_change_trigger() {
        let advice = StrategyAdvice::change_to(SelectionKind::Thompson, "high variance", 0.8);
        let advisor = MockAdvisor::new(advice);
        let provider =
            AdaptiveLlmOperatorProvider::new(Box::new(advisor)).with_policy(ReviewPolicy {
                interval: 100, // 高い interval
                min_interval: 1,
                state_change_threshold: 0.1, // 10% の変化でトリガー
            });
        let rules = NodeRules::for_testing();

        // 最初のレビュー(初期化)
        let mut stats = SwarmStats::new();
        for _ in 0..5 {
            record_success(&mut stats, "action");
        }
        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let ctx = ProviderContext::new(&map, &stats);
        let _ = provider.provide(rules.clone(), Some(&ctx));

        // failure_rate が急変(0% → 50%)
        for _ in 0..5 {
            record_failure(&mut stats, "action");
        }
        let ctx2 = ProviderContext::new(&map, &stats);

        // interval 未到達だが、state_change_threshold を超えているのでレビュー
        let operator = provider.provide(rules, Some(&ctx2));
        assert_eq!(operator.selection().kind(), SelectionKind::Thompson);
    }
}