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
//! Exploration Space V2 - 探索空間の統合レイヤー
//!
//! # 設計思想
//!
//! ## 責務の分離
//!
//! | レイヤー | 責務 |
//! |----------|------|
//! | `ExplorationSpaceV2` | 統合レイヤー。Map + Operator を繋ぐだけ |
//! | `GraphMap` | 純粋なデータ構造(Plain Board) |
//! | `Operator` | Mutation + Selection の連携、統計管理 |
//! | `DependencyGraph` | アクション依存関係(Optional) |
//!
//! ## Operator パターン
//!
//! Mutation と Selection はアルゴリズム的にセットである:
//! - Discover フェーズで発見した結果を Selection の統計に反映
//! - その統計が次の Selection に影響
//!
//! Operator がこの連携を担保する。Space は Operator を通じて
//! Mutation と Selection にアクセスする。
//!
//! # 使用例
//!
//! ```ignore
//! use exploration::{Operator, RulesBasedMutation, FifoSelection, NodeRules};
//!
//! // Operator を構築
//! let rules: NodeRules = dependency_graph.into();
//! let operator = Operator::new(RulesBasedMutation::new(), FifoSelection::new(), rules);
//!
//! // Space に渡す
//! let mut space = ExplorationSpaceV2::new(operator);
//!
//! // ルート作成と初期展開
//! let root = space.create_root(ActionNodeData::new("task"));
//! space.initialize(&["auth", "login"]);
//!
//! // 結果を適用(Operator 内で stats 更新 → Mutation 実行)
//! space.apply(&input);
//!
//! // ノード選択(Operator 内で stats 参照 → Selection 実行)
//! let next_nodes = space.select(worker_count);
//! ```

use std::fmt::Debug;

use super::map::{ExplorationMap, GraphExplorationMap, GraphMap, MapNodeId, MapState};
use super::mutation::{MapUpdateResult, MutationInput};
use super::node_rules::Rules;
use super::operator::{MutationLogic, Operator};
use super::selection::SelectionLogic;
use crate::actions::ActionsConfig;
use crate::online_stats::SwarmStats;

// Re-export MutationInput for convenience
pub use super::mutation::MutationInput as SpaceMutationInput;

// ============================================================================
// ExplorationSpaceV2 - 統合レイヤー
// ============================================================================

/// 探索空間 V2 - 統合レイヤー
///
/// GraphMap と Operator を統合する。
/// ロジックは持たず、コンポーネントを繋ぐだけ。
///
/// # 型パラメータ
///
/// - `N`: ノードデータの型
/// - `E`: エッジデータの型
/// - `S`: 状態の型
/// - `R`: 遷移ルールの型(`Rules` を実装)
/// - `M`: Mutation ロジック
/// - `Sel`: Selection ロジック
pub struct ExplorationSpaceV2<N, E, S, R, M, Sel>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState,
    R: Rules,
    M: MutationLogic<N, E, S, R>,
    Sel: SelectionLogic<N, E, S>,
{
    /// グラフデータ
    map: GraphMap<N, E, S>,

    /// Operator(Mutation + Selection の連携)
    operator: Operator<M, Sel, N, E, S, R>,

    /// アクション依存グラフ(Optional)
    dependency_graph: Option<super::DependencyGraph>,

    /// 完了フラグ
    completed: bool,

    /// アクション設定(category 判定用)
    actions_config: ActionsConfig,
}

impl<N, E, S, R, M, Sel> ExplorationSpaceV2<N, E, S, R, M, Sel>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState + Default,
    R: Rules + 'static,
    M: MutationLogic<N, E, S, R>,
    Sel: SelectionLogic<N, E, S>,
{
    /// 新しい ExplorationSpaceV2 を作成
    pub fn new(operator: Operator<M, Sel, N, E, S, R>) -> Self {
        Self {
            map: GraphMap::new(),
            operator,
            dependency_graph: None,
            completed: false,
            actions_config: ActionsConfig::new(),
        }
    }

    /// DependencyGraph を設定
    pub fn with_dependency_graph(mut self, graph: super::DependencyGraph) -> Self {
        self.dependency_graph = Some(graph);
        self
    }

    /// ActionsConfig を設定
    pub fn with_actions_config(mut self, config: ActionsConfig) -> Self {
        self.actions_config = config;
        self
    }

    // ========================================================================
    // Core API
    // ========================================================================

    /// ルートノードを作成
    pub fn create_root(&mut self, data: N) -> MapNodeId {
        self.map.create_root(data, S::default())
    }

    /// 入力を適用(Operator に委譲)
    ///
    /// Note: 統計は ActionEventPublisher 経由で別途記録されるため、
    /// この関数では統計を更新しない。SwarmStats は Mutation に渡される。
    pub fn apply(&mut self, input: &dyn MutationInput, stats: &SwarmStats) -> Vec<MapUpdateResult> {
        let updates = self
            .operator
            .interpret(input, &self.map, &self.actions_config, stats);
        self.map.apply_updates(updates, |k| k.to_string())
    }

    /// 次のノードを選択(Operator に委譲)
    pub fn select(&self, count: usize, stats: &SwarmStats) -> Vec<MapNodeId> {
        self.operator.select(&self.map, count, stats)
    }

    /// 次のノードを1つ選択(Operator に委譲)
    pub fn next(&self, stats: &SwarmStats) -> Option<MapNodeId> {
        self.operator.next(&self.map, stats)
    }

    /// ノードの優先度スコアを取得(Operator に委譲)
    pub fn score(&self, action: &str, target: Option<&str>, stats: &SwarmStats) -> f64 {
        self.operator.score(action, target, stats)
    }

    /// 次のノードを選択し、MapNode ごと返す
    pub fn select_nodes(
        &self,
        count: usize,
        stats: &SwarmStats,
    ) -> Vec<&super::map::MapNode<N, S>> {
        let ids = self.select(count, stats);
        self.map.get_nodes(&ids)
    }

    /// 初期ノードを展開(Operator に委譲)
    pub fn initialize(&mut self, initial_contexts: &[&str]) -> Vec<MapUpdateResult> {
        let root_id = match self.map.root() {
            Some(id) => id,
            None => return vec![],
        };

        if initial_contexts.is_empty() {
            return vec![];
        }

        let updates = self.operator.initialize(root_id, initial_contexts);
        self.map.apply_updates(updates, |k| k.to_string())
    }

    // ========================================================================
    // Query API
    // ========================================================================

    /// 複数ノードを一括取得
    pub fn get_nodes(&self, ids: &[MapNodeId]) -> Vec<&super::map::MapNode<N, S>> {
        self.map.get_nodes(ids)
    }

    /// 複数ノードのデータを一括取得
    pub fn get_node_data(&self, ids: &[MapNodeId]) -> Vec<&N> {
        self.map.get_node_data(ids)
    }

    /// フロンティア(探索可能ノード)を取得
    pub fn frontiers(&self) -> Vec<MapNodeId> {
        self.map.frontiers()
    }

    /// ルートノード ID
    pub fn root(&self) -> Option<MapNodeId> {
        self.map.root()
    }

    /// ノード数
    pub fn node_count(&self) -> usize {
        self.map.node_count()
    }

    /// 探索が完了したか(Operator に委譲)
    pub fn is_complete(&self) -> bool {
        self.completed || self.operator.is_complete(&self.map)
    }

    /// 成功で完了したか(外部からマーク済みの場合)
    pub fn has_completed(&self) -> bool {
        self.completed
    }

    /// 成功として完了をマーク
    pub fn mark_completed(&mut self) {
        self.completed = true;
    }

    /// フロンティアが枯渇したか
    pub fn is_exhausted(&self) -> bool {
        self.map.frontiers().is_empty()
    }

    /// GraphMap への参照
    pub fn map(&self) -> &GraphMap<N, E, S> {
        &self.map
    }

    /// GraphMap への可変参照
    pub fn map_mut(&mut self) -> &mut GraphMap<N, E, S> {
        &mut self.map
    }

    /// Operator への参照
    pub fn operator(&self) -> &Operator<M, Sel, N, E, S, R> {
        &self.operator
    }

    /// Operator への可変参照
    pub fn operator_mut(&mut self) -> &mut Operator<M, Sel, N, E, S, R> {
        &mut self.operator
    }

    /// DependencyGraph への参照
    pub fn dependency_graph(&self) -> Option<&super::DependencyGraph> {
        self.dependency_graph.as_ref()
    }

    /// Operator 名
    pub fn operator_name(&self) -> String {
        self.operator.name()
    }

    /// Rules への参照
    pub fn rules(&self) -> &R {
        self.operator.rules()
    }
}

// ============================================================================
// Type Alias for common usage
// ============================================================================

use super::map::MapNodeState;
use super::mutation::ActionNodeData;
use super::operator::RulesBasedMutation;
use super::selection::{AnySelection, Fifo as FifoSelection};

/// ActionNodeData + FIFO Operator の Space
pub type ActionSpace<R> =
    ExplorationSpaceV2<ActionNodeData, String, MapNodeState, R, RulesBasedMutation, FifoSelection>;

/// ActionNodeData + Configurable Selection の Space
///
/// AdaptiveProvider / ConfigBasedProvider で Selection を動的に切り替え可能。
pub type ConfigurableSpace<R> =
    ExplorationSpaceV2<ActionNodeData, String, MapNodeState, R, RulesBasedMutation, AnySelection>;

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

#[cfg(test)]
mod tests {
    use super::super::mutation::ExplorationResult;
    use super::super::operator::Operator;
    use super::super::NodeRules;
    use super::*;

    // テスト用の MutationInput 実装
    struct TestInput {
        node_id: MapNodeId,
        action_name: String,
        target: Option<String>,
        result: ExplorationResult,
    }

    impl MutationInput for TestInput {
        fn node_id(&self) -> MapNodeId {
            self.node_id
        }

        fn action_name(&self) -> &str {
            &self.action_name
        }

        fn target(&self) -> Option<&str> {
            self.target.as_deref()
        }

        fn result(&self) -> &ExplorationResult {
            &self.result
        }
    }

    fn make_test_space() -> ActionSpace<NodeRules> {
        let rules = NodeRules::for_testing();
        let operator = Operator::new(RulesBasedMutation::new(), FifoSelection::new(), rules);
        ExplorationSpaceV2::new(operator)
    }

    #[test]
    fn test_exploration_space_v2_basic() {
        let mut space = make_test_space();

        // ルート作成
        let root = space.create_root(ActionNodeData::new("root"));
        assert_eq!(space.node_count(), 1);
        assert_eq!(space.root(), Some(root));

        // フロンティア確認
        assert_eq!(space.frontiers().len(), 1);
        assert!(!space.is_exhausted());
    }

    #[test]
    fn test_exploration_space_v2_apply() {
        let mut space = make_test_space();
        let stats = SwarmStats::new();

        let root = space.create_root(ActionNodeData::new("root"));

        // 成功入力を適用(grep → read, summary への子ノード生成 + root を Close)
        let input = TestInput {
            node_id: root,
            action_name: "grep".to_string(),
            target: Some("auth.rs".to_string()),
            result: ExplorationResult::Success,
        };

        let results = space.apply(&input, &stats);
        // 3 results: read, summary, Close(root)
        assert_eq!(results.len(), 3);
        assert!(matches!(results[0], MapUpdateResult::NodeCreated(_)));
        assert!(matches!(results[1], MapUpdateResult::NodeCreated(_)));
        assert!(matches!(results[2], MapUpdateResult::NodeClosed(_)));

        // ノード数が増えた (root + read + summary)
        assert_eq!(space.node_count(), 3);

        // root は Closed されたのでフロンティアは read, summary のみ
        assert_eq!(space.frontiers().len(), 2);
    }

    #[test]
    fn test_exploration_space_v2_select() {
        let mut space = make_test_space();
        let stats = SwarmStats::new();

        let root = space.create_root(ActionNodeData::new("root"));

        // 子ノードを追加(grep → read, summary)
        let input1 = TestInput {
            node_id: root,
            action_name: "grep".to_string(),
            target: Some("a.rs".to_string()),
            result: ExplorationResult::Success,
        };
        space.apply(&input1, &stats);

        // select で複数ノードを取得
        let selected = space.select(2, &stats);
        assert_eq!(selected.len(), 2);
    }

    #[test]
    fn test_exploration_space_v2_completion() {
        let mut space = make_test_space();

        // 初期状態: フロンティアなし → Operator は完了と判断
        assert!(!space.has_completed()); // 明示的マークはまだ
        assert!(space.is_complete()); // Operator: frontiers 空 → 完了
        assert!(space.is_exhausted());

        // ルート追加 → フロンティアあり → 完了でない
        space.create_root(ActionNodeData::new("task"));
        assert!(!space.is_complete());
        assert!(!space.is_exhausted());

        // 明示的に完了マーク
        space.mark_completed();
        assert!(space.has_completed());
        assert!(space.is_complete()); // マーク済みなので完了
    }

    #[test]
    fn test_exploration_space_v2_is_complete_operator() {
        let mut space = make_test_space();

        let root = space.create_root(ActionNodeData::new("task"));
        assert!(!space.is_complete()); // フロンティアあり

        // ノードを Close → フロンティア枯渇 → Operator が完了と判断
        space.map_mut().set_state(root, MapNodeState::Closed);
        assert!(space.is_complete());
        assert!(space.is_exhausted());
        assert!(!space.has_completed()); // 明示的マークはしてない
    }

    #[test]
    fn test_exploration_space_v2_initialize() {
        let mut space = make_test_space();

        // ルート作成
        let _root = space.create_root(ActionNodeData::new("task"));
        assert_eq!(space.node_count(), 1);

        // 初期展開: ["auth", "login"] × roots["grep", "glob"] = 4 ノード
        let results = space.initialize(&["auth", "login"]);
        assert_eq!(results.len(), 4); // 2 contexts × 2 root actions

        // ノード数: root + 4 初期ノード = 5
        assert_eq!(space.node_count(), 5);

        // フロンティア: root(Open) + 4 初期ノード = 5
        let frontiers = space.frontiers();
        assert_eq!(frontiers.len(), 5);
    }

    #[test]
    fn test_exploration_space_v2_initialize_empty_rules() {
        // 空のルールで初期化した場合
        let rules = NodeRules::new(); //        let operator = Operator::new(RulesBasedMutation::new(), FifoSelection::new(), rules);
        let mut space: ActionSpace<NodeRules> = ExplorationSpaceV2::new(operator);

        let _root = space.create_root(ActionNodeData::new("task"));

        // ルートアクションがない場合は初期ノードなし
        let results = space.initialize(&["auth"]);
        assert!(results.is_empty());
        assert_eq!(space.node_count(), 1);
    }

    #[test]
    fn test_exploration_space_v2_initialize_no_root() {
        let mut space = make_test_space();

        // ルートがない場合は何もしない
        let results = space.initialize(&["auth"]);
        assert!(results.is_empty());
    }

    #[test]
    fn test_exploration_space_v2_get_nodes() {
        use crate::actions::Action;

        let mut space = make_test_space();
        let stats = SwarmStats::new();

        // ルートとサブノードを作成
        let root = space.create_root(ActionNodeData::new("root"));
        let input = TestInput {
            node_id: root,
            action_name: "grep".to_string(),
            target: Some("auth.rs".to_string()),
            result: ExplorationResult::Success,
        };
        space.apply(&input, &stats);

        // select で取得
        let selected = space.select(3, &stats);
        assert!(!selected.is_empty());

        // get_nodes で Node を取得
        let nodes = space.get_nodes(&selected);
        assert_eq!(nodes.len(), selected.len());

        // get_node_data でデータのみ取得
        let data = space.get_node_data(&selected);
        assert_eq!(data.len(), selected.len());

        // ActionNodeData から Action に変換可能
        let actions: Vec<Action> = data.iter().map(|d| Action::from(*d)).collect();
        assert_eq!(actions.len(), selected.len());
    }

    #[test]
    fn test_exploration_space_v2_operator_name() {
        let space = make_test_space();
        assert_eq!(space.operator_name(), "RulesBased+FIFO");
    }
}