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
//! OperatorProvider - Operator を提供する戦略
//!
//! 状況に応じて最適な Operator を構築・選択する。
//!
//! # 設計
//!
//! ```text
//! OperatorProvider trait
//! ├── ConfigBasedOperatorProvider   (Config から静的に構築)
//! ├── AdaptiveOperatorProvider      (Stats を見て動的に切り替え)
//! └── AdaptiveLlmOperatorProvider   (llm_provider.rs, Adaptive + LLM レビュー)
//! ```
//!
//! # 使用例
//!
//! ```ignore
//! use swarm_engine_core::exploration::{
//!     ConfigBasedOperatorProvider, AdaptiveOperatorProvider, OperatorConfig,
//! };
//!
//! // Config ベース(静的)
//! let provider = ConfigBasedOperatorProvider::ucb1(1.41);
//! let operator = provider.provide(rules, None);
//!
//! // Adaptive(動的)
//! let provider = AdaptiveOperatorProvider::default();
//! let operator = provider.provide(rules, Some(&context));
//! provider.reevaluate(&mut operator, &context);
//! ```

use std::fmt::Debug;

use super::map::{ExplorationMap, GraphMap, MapNodeState, MapState};
use super::mutation::ActionNodeData;
use super::node_rules::Rules;
use super::operator::{ConfigurableOperator, Operator, RulesBasedMutation};
use super::selection::{AnySelection, SelectionKind};
use crate::online_stats::SwarmStats;

// ============================================================================
// OperatorConfig - Operator 設定
// ============================================================================

/// Operator の設定
#[derive(Debug, Clone)]
pub struct OperatorConfig {
    /// Selection アルゴリズム
    pub selection: SelectionKind,
    /// UCB1 の探索係数(UCB1 使用時のみ有効)
    pub ucb1_c: f64,
}

impl Default for OperatorConfig {
    fn default() -> Self {
        Self {
            selection: SelectionKind::Fifo,
            ucb1_c: std::f64::consts::SQRT_2,
        }
    }
}

impl OperatorConfig {
    /// UCB1 設定で生成
    pub fn ucb1(c: f64) -> Self {
        Self {
            selection: SelectionKind::Ucb1,
            ucb1_c: c,
        }
    }

    /// Greedy 設定で生成
    pub fn greedy() -> Self {
        Self {
            selection: SelectionKind::Greedy,
            ..Default::default()
        }
    }

    /// Thompson 設定で生成
    pub fn thompson() -> Self {
        Self {
            selection: SelectionKind::Thompson,
            ..Default::default()
        }
    }
}

// ============================================================================
// ProviderContext - Provider に渡すコンテキスト
// ============================================================================

/// OperatorProvider に渡すコンテキスト
///
/// Map の状態や Stats を参照し、最適な Operator を選択するための情報。
pub struct ProviderContext<'a, N, E, S>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState,
{
    /// 現在の Map
    pub map: &'a GraphMap<N, E, S>,
    /// 現在の統計(SwarmStats: Single Source of Truth)
    pub stats: &'a SwarmStats,
}

impl<'a, N, E, S> ProviderContext<'a, N, E, S>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState,
{
    pub fn new(map: &'a GraphMap<N, E, S>, stats: &'a SwarmStats) -> Self {
        Self { map, stats }
    }

    /// フロンティア数
    pub fn frontier_count(&self) -> usize {
        self.map.frontiers().len()
    }

    /// 総訪問数
    pub fn total_visits(&self) -> u32 {
        self.stats.total_visits()
    }

    /// 探索が進んでいるか(訪問数が閾値以上)
    pub fn is_exploration_mature(&self, threshold: u32) -> bool {
        self.stats.total_visits() >= threshold
    }
}

// ============================================================================
// OperatorProvider - Operator を提供する trait
// ============================================================================

/// Operator を提供する trait
///
/// 状況に応じて最適な Operator を選択・構築する。
pub trait OperatorProvider<R>: Send + Sync
where
    R: Rules,
{
    /// Operator を構築
    fn provide(
        &self,
        rules: R,
        context: Option<&ProviderContext<'_, ActionNodeData, String, MapNodeState>>,
    ) -> ConfigurableOperator<R>;

    /// Selection を再評価して切り替え
    fn reevaluate(
        &self,
        _operator: &mut ConfigurableOperator<R>,
        _context: &ProviderContext<'_, ActionNodeData, String, MapNodeState>,
    ) {
        // デフォルトは何もしない
    }

    /// Provider 名
    fn name(&self) -> &str;
}

// ============================================================================
// ConfigBasedOperatorProvider - Config から Operator を構築
// ============================================================================

/// Config から Operator を構築する Provider
#[derive(Debug, Clone)]
pub struct ConfigBasedOperatorProvider {
    config: OperatorConfig,
}

impl ConfigBasedOperatorProvider {
    pub fn new(config: OperatorConfig) -> Self {
        Self { config }
    }

    /// FIFO 設定で生成
    pub fn fifo() -> Self {
        Self::new(OperatorConfig::default())
    }

    /// UCB1 設定で生成
    pub fn ucb1(c: f64) -> Self {
        Self::new(OperatorConfig::ucb1(c))
    }

    /// Config を取得
    pub fn config(&self) -> &OperatorConfig {
        &self.config
    }
}

impl<R> OperatorProvider<R> for ConfigBasedOperatorProvider
where
    R: Rules + 'static,
{
    fn provide(
        &self,
        rules: R,
        _context: Option<&ProviderContext<'_, ActionNodeData, String, MapNodeState>>,
    ) -> ConfigurableOperator<R> {
        let selection = AnySelection::from_kind(self.config.selection, self.config.ucb1_c);
        Operator::new(RulesBasedMutation::new(), selection, rules)
    }

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

// ============================================================================
// AdaptiveOperatorProvider - 状況に応じて Selection を切り替え
// ============================================================================

/// 適応的に Selection を切り替える Provider
///
/// | 状態 | Selection | 理由 |
/// |------|-----------|------|
/// | 初期(visits < threshold) | UCB1 | 未探索優先で広く探る |
/// | 成熟 + エラー率低 | Greedy | 成功パスを活用 |
/// | 成熟 + エラー率高 | Thompson | バランス重視 |
#[derive(Debug, Clone)]
pub struct AdaptiveOperatorProvider {
    /// 成熟判定の閾値(これ以上の訪問で成熟)
    maturity_threshold: u32,
    /// エラー率の閾値(これ以上なら Thompson)
    error_rate_threshold: f64,
    /// UCB1 の探索係数
    ucb1_c: f64,
}

impl Default for AdaptiveOperatorProvider {
    fn default() -> Self {
        Self {
            maturity_threshold: 10,
            error_rate_threshold: 0.3,
            ucb1_c: std::f64::consts::SQRT_2,
        }
    }
}

impl AdaptiveOperatorProvider {
    /// 新しい AdaptiveOperatorProvider を作成
    pub fn new(maturity_threshold: u32, error_rate_threshold: f64, ucb1_c: f64) -> Self {
        Self {
            maturity_threshold,
            error_rate_threshold,
            ucb1_c,
        }
    }

    /// 成熟閾値を設定
    pub fn with_maturity_threshold(mut self, threshold: u32) -> Self {
        self.maturity_threshold = threshold;
        self
    }

    /// エラー率閾値を設定
    pub fn with_error_rate_threshold(mut self, threshold: f64) -> Self {
        self.error_rate_threshold = threshold.clamp(0.0, 1.0);
        self
    }

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

    /// 現在の状態から最適な Selection を決定
    fn select_strategy(&self, stats: &SwarmStats) -> SelectionKind {
        let visits = stats.total_visits();
        let error_rate = stats.failure_rate();

        if visits < self.maturity_threshold {
            SelectionKind::Ucb1
        } else if error_rate > self.error_rate_threshold {
            SelectionKind::Thompson
        } else {
            SelectionKind::Greedy
        }
    }

    /// 現在の Selection 種別を取得(デバッグ用)
    pub fn current_selection(&self, stats: &SwarmStats) -> SelectionKind {
        self.select_strategy(stats)
    }
}

impl<R> OperatorProvider<R> for AdaptiveOperatorProvider
where
    R: Rules + 'static,
{
    fn provide(
        &self,
        rules: R,
        context: Option<&ProviderContext<'_, ActionNodeData, String, MapNodeState>>,
    ) -> ConfigurableOperator<R> {
        let selection_kind = context
            .map(|ctx| self.select_strategy(ctx.stats))
            .unwrap_or(SelectionKind::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_kind = operator.selection.kind();
        let new_kind = self.select_strategy(context.stats);

        if current_kind != new_kind {
            operator.selection = AnySelection::from_kind(new_kind, self.ucb1_c);
        }
    }

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::events::{ActionEventBuilder, ActionEventResult};
    use crate::exploration::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);
    }

    // ========================================================================
    // OperatorConfig Tests
    // ========================================================================

    #[test]
    fn test_operator_config_default() {
        let config = OperatorConfig::default();
        assert_eq!(config.selection, SelectionKind::Fifo);
        assert!((config.ucb1_c - std::f64::consts::SQRT_2).abs() < 1e-10);
    }

    #[test]
    fn test_operator_config_ucb1() {
        let config = OperatorConfig::ucb1(2.0);
        assert_eq!(config.selection, SelectionKind::Ucb1);
        assert_eq!(config.ucb1_c, 2.0);
    }

    #[test]
    fn test_operator_config_greedy() {
        let config = OperatorConfig::greedy();
        assert_eq!(config.selection, SelectionKind::Greedy);
    }

    #[test]
    fn test_operator_config_thompson() {
        let config = OperatorConfig::thompson();
        assert_eq!(config.selection, SelectionKind::Thompson);
    }

    // ========================================================================
    // ConfigBasedOperatorProvider Tests
    // ========================================================================

    #[test]
    fn test_config_based_provider_fifo() {
        let provider = ConfigBasedOperatorProvider::fifo();
        let rules = NodeRules::for_testing();
        let operator = provider.provide(rules, None);

        assert_eq!(operator.name(), "RulesBased+FIFO");
    }

    #[test]
    fn test_config_based_provider_ucb1() {
        let provider = ConfigBasedOperatorProvider::ucb1(1.41);
        let rules = NodeRules::for_testing();
        let operator = provider.provide(rules, None);

        assert_eq!(operator.name(), "RulesBased+UCB1");
    }

    #[test]
    fn test_config_based_provider_with_context() {
        let provider = ConfigBasedOperatorProvider::new(OperatorConfig::greedy());
        let rules = NodeRules::for_testing();

        // Context なしで構築
        let operator1 = provider.provide(rules.clone(), None);
        assert_eq!(operator1.name(), "RulesBased+Greedy");

        // Context ありでも同じ結果(ConfigBased は Context を無視)
        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let stats = SwarmStats::new();
        let ctx = ProviderContext::new(&map, &stats);
        let operator2 = provider.provide(rules, Some(&ctx));
        assert_eq!(operator2.name(), "RulesBased+Greedy");
    }

    // ========================================================================
    // ProviderContext Tests
    // ========================================================================

    #[test]
    fn test_provider_context_queries() {
        let mut map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let _root = map.create_root(ActionNodeData::new("root"), MapNodeState::Open);

        let stats = SwarmStats::new();
        let ctx = ProviderContext::new(&map, &stats);

        assert_eq!(ctx.frontier_count(), 1);
        assert_eq!(ctx.total_visits(), 0);
        assert!(!ctx.is_exploration_mature(10));
    }

    // ========================================================================
    // AdaptiveOperatorProvider Tests
    // ========================================================================

    #[test]
    fn test_adaptive_provider_initial_ucb1() {
        let provider = AdaptiveOperatorProvider::default();
        let stats = SwarmStats::new();

        assert_eq!(provider.current_selection(&stats), SelectionKind::Ucb1);
    }

    #[test]
    fn test_adaptive_provider_mature_low_error_greedy() {
        let provider = AdaptiveOperatorProvider::default().with_maturity_threshold(5);
        let mut stats = SwarmStats::new();

        for _ in 0..10 {
            record_success(&mut stats, "grep");
        }

        assert_eq!(stats.failure_rate(), 0.0);
        assert_eq!(provider.current_selection(&stats), SelectionKind::Greedy);
    }

    #[test]
    fn test_adaptive_provider_mature_high_error_thompson() {
        let provider = AdaptiveOperatorProvider::default()
            .with_maturity_threshold(5)
            .with_error_rate_threshold(0.3);
        let mut stats = SwarmStats::new();

        for _ in 0..5 {
            record_success(&mut stats, "grep");
        }
        for _ in 0..5 {
            record_failure(&mut stats, "grep");
        }

        assert_eq!(stats.failure_rate(), 0.5);
        assert_eq!(provider.current_selection(&stats), SelectionKind::Thompson);
    }

    #[test]
    fn test_adaptive_provider_provide() {
        let provider = AdaptiveOperatorProvider::default();
        let rules = NodeRules::for_testing();

        let operator = provider.provide(rules.clone(), None);
        assert_eq!(operator.name(), "RulesBased+UCB1");

        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let mut stats = SwarmStats::new();
        for _ in 0..20 {
            record_success(&mut stats, "grep");
        }
        let ctx = ProviderContext::new(&map, &stats);

        let operator2 = provider.provide(rules, Some(&ctx));
        assert_eq!(operator2.name(), "RulesBased+Greedy");
    }

    #[test]
    fn test_adaptive_provider_reevaluate() {
        let provider = AdaptiveOperatorProvider::default().with_maturity_threshold(5);
        let rules = NodeRules::for_testing();

        let mut operator = provider.provide(rules, None);
        assert_eq!(operator.selection.kind(), SelectionKind::Ucb1);

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

        provider.reevaluate(&mut operator, &ctx);
        assert_eq!(operator.selection.kind(), SelectionKind::Greedy);
    }

    #[test]
    fn test_adaptive_provider_reevaluate_to_thompson() {
        let provider = AdaptiveOperatorProvider::default()
            .with_maturity_threshold(5)
            .with_error_rate_threshold(0.3);
        let rules = NodeRules::for_testing();

        let mut operator = provider.provide(rules, None);
        assert_eq!(operator.selection.kind(), SelectionKind::Ucb1);

        let map: GraphMap<ActionNodeData, String, MapNodeState> = GraphMap::new();
        let mut stats = SwarmStats::new();
        for _ in 0..3 {
            record_success(&mut stats, "grep");
        }
        for _ in 0..7 {
            record_failure(&mut stats, "grep");
        }
        let ctx = ProviderContext::new(&map, &stats);

        provider.reevaluate(&mut operator, &ctx);
        assert_eq!(operator.selection.kind(), SelectionKind::Thompson);
    }
}