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
//! Node Rules - Exploration 内の純粋な遷移制約
//!
//! # 設計思想
//!
//! - **ドメイン非依存**: Action や Task を知らない
//! - **純粋な制約**: 「NodeType A → NodeType B が可能」というルールのみ
//! - **外部から注入**: DependencyGraph 等から変換して渡す
//!
//! # 研究室の探索グラフとの対比
//!
//! | 研究室(4セル) | SwarmEngine |
//! |----------------|-------------|
//! | 上下左右の4方向 | DependencyGraph から生成 |
//! | 静的ルール(固定) | 動的ルール(タスク依存) |
//!
//! 共通点: Exploration 内では **純粋な遷移制約** として扱う
//!
//! # 使用例
//!
//! ```ignore
//! // Domain 側で変換
//! let rules: NodeRules = dependency_graph.into();
//!
//! // Operator に渡す(型パラメータで強制)
//! let operator = FifoOperator::<NodeRules>::new(rules);
//!
//! // Rules trait を通じてノード生成
//! let successors = rules.successors("grep");
//! ```

use std::collections::{HashMap, HashSet};

use super::DependencyGraph;

// ============================================================================
// Rules trait - 遷移制約の抽象化
// ============================================================================

/// 遷移制約の抽象化
///
/// `MutationLogic` の R に対する trait bound。
/// これにより Operator は型パラメータでルールを強制される。
///
/// # 実装者
///
/// - `NodeRules`: 汎用的な遷移ルール
/// - `DependencyGraph`: ドメイン固有のグラフ(直接実装も可能)
pub trait Rules: Send + Sync {
    /// 指定 node_type の後に来れる node_type 一覧
    fn successors(&self, node_type: &str) -> Vec<&str>;

    /// ルート node_type 一覧
    fn roots(&self) -> Vec<&str>;

    /// 終端かどうか
    fn is_terminal(&self, node_type: &str) -> bool;

    /// ルールが空か
    fn is_empty(&self) -> bool;

    /// 指定 node_type のパラメータバリアント(キー, 値リスト)
    ///
    /// パラメータバリアントが定義されている場合、後続ノード展開時に
    /// 各バリアントごとにノードを生成する。
    ///
    /// # Returns
    ///
    /// - `Some((key, values))`: バリアントが定義されている場合
    /// - `None`: 定義されていない場合(デフォルト)
    fn param_variants(&self, _node_type: &str) -> Option<(&str, &[String])> {
        None
    }
}

// ============================================================================
// NodeRules - 純粋な遷移制約
// ============================================================================

/// Exploration 内の純粋な遷移制約
///
/// 「NodeType A の後に NodeType B が来れる」というルールを保持。
/// ドメイン知識(Action、Task)は知らない。
///
/// # 設計意図
///
/// - `DependencyGraph` 等のドメイン固有グラフから変換して使う
/// - Strategy はこれを参照してノード生成を行う
/// - アルゴリズム(DFS/BFS/UCB)がドメインに依存しない
#[derive(Debug, Clone, Default)]
pub struct NodeRules {
    /// node_type → 次に遷移可能な node_type 一覧
    successors: HashMap<String, HashSet<String>>,

    /// ルートから開始可能な node_type
    roots: HashSet<String>,

    /// 終端 node_type(これで探索完了の可能性)
    terminals: HashSet<String>,

    /// node_type → パラメータバリアント(key, values)
    ///
    /// 例: "Move" → ("target", ["north", "south", "east", "west"])
    param_variants: HashMap<String, (String, Vec<String>)>,

    /// (from, to) → confidence(0.0〜1.0)
    ///
    /// DependencyGraph の edge confidence を保持。
    /// SelectionLogic で使用。
    edge_confidence: HashMap<(String, String), f64>,
}

impl NodeRules {
    pub fn new() -> Self {
        Self::default()
    }

    // ========================================================================
    // Builder API
    // ========================================================================

    /// ルール追加: from → to が可能
    pub fn add_rule(mut self, from: &str, to: &str) -> Self {
        self.successors
            .entry(from.to_string())
            .or_default()
            .insert(to.to_string());
        self
    }

    /// 複数ルール追加: from → [to1, to2, ...]
    pub fn add_rules(mut self, from: &str, tos: &[&str]) -> Self {
        let entry = self.successors.entry(from.to_string()).or_default();
        for to in tos {
            entry.insert(to.to_string());
        }
        self
    }

    /// ルート node_type 追加
    pub fn add_root(mut self, node_type: &str) -> Self {
        self.roots.insert(node_type.to_string());
        self
    }

    /// 複数ルート node_type 追加
    pub fn add_roots(mut self, node_types: &[&str]) -> Self {
        for node_type in node_types {
            self.roots.insert(node_type.to_string());
        }
        self
    }

    /// 終端 node_type 追加
    pub fn add_terminal(mut self, node_type: &str) -> Self {
        self.terminals.insert(node_type.to_string());
        self
    }

    /// 複数終端 node_type 追加
    pub fn add_terminals(mut self, node_types: &[&str]) -> Self {
        for node_type in node_types {
            self.terminals.insert(node_type.to_string());
        }
        self
    }

    /// パラメータバリアントを追加
    ///
    /// 指定した node_type の後続ノード展開時に、各バリアントごとにノードを生成する。
    ///
    /// # Example
    ///
    /// ```ignore
    /// let rules = NodeRules::new()
    ///     .add_rule("Look", "Move")
    ///     .add_param_variants("Move", "target", &["north", "south", "east", "west"]);
    /// ```
    pub fn add_param_variants(mut self, node_type: &str, key: &str, values: &[&str]) -> Self {
        self.param_variants.insert(
            node_type.to_string(),
            (
                key.to_string(),
                values.iter().map(|s| s.to_string()).collect(),
            ),
        );
        self
    }

    /// ルール追加(confidence 付き): from → to が可能
    pub fn add_rule_with_confidence(mut self, from: &str, to: &str, confidence: f64) -> Self {
        self.successors
            .entry(from.to_string())
            .or_default()
            .insert(to.to_string());
        self.edge_confidence.insert(
            (from.to_string(), to.to_string()),
            confidence.clamp(0.0, 1.0),
        );
        self
    }

    // ========================================================================
    // Query API(純粋な参照)
    // ========================================================================

    /// 指定 node_type の後に来れる node_type 一覧
    pub fn successors(&self, node_type: &str) -> Vec<&str> {
        self.successors
            .get(node_type)
            .map(|set| set.iter().map(|s| s.as_str()).collect())
            .unwrap_or_default()
    }

    /// ルート node_type 一覧
    pub fn roots(&self) -> Vec<&str> {
        self.roots.iter().map(|s| s.as_str()).collect()
    }

    /// 終端 node_type 一覧
    pub fn terminals(&self) -> Vec<&str> {
        self.terminals.iter().map(|s| s.as_str()).collect()
    }

    /// 遷移が可能か
    pub fn can_transition(&self, from: &str, to: &str) -> bool {
        self.successors
            .get(from)
            .map(|set| set.contains(to))
            .unwrap_or(false)
    }

    /// node_type が定義されているか
    pub fn has_node_type(&self, node_type: &str) -> bool {
        self.successors.contains_key(node_type)
            || self.roots.contains(node_type)
            || self.terminals.contains(node_type)
    }

    /// 終端かどうか
    pub fn is_terminal(&self, node_type: &str) -> bool {
        self.terminals.contains(node_type)
    }

    /// ルートかどうか
    pub fn is_root(&self, node_type: &str) -> bool {
        self.roots.contains(node_type)
    }

    /// エッジの confidence を取得
    pub fn get_confidence(&self, from: &str, to: &str) -> Option<f64> {
        self.edge_confidence
            .get(&(from.to_string(), to.to_string()))
            .copied()
    }

    /// アクション名から confidence map を取得(SelectionLogic 用)
    ///
    /// 各 (from, to) → to の confidence として集約
    pub fn confidence_map(&self) -> HashMap<String, f64> {
        let mut result = HashMap::new();
        for ((_, to), conf) in &self.edge_confidence {
            // 同じ to に複数のエッジがある場合は最大値を採用
            let entry = result.entry(to.clone()).or_insert(0.0);
            if *conf > *entry {
                *entry = *conf;
            }
        }
        result
    }

    /// ルールが空か
    pub fn is_empty(&self) -> bool {
        self.successors.is_empty() && self.roots.is_empty()
    }

    // ========================================================================
    // Test Utilities
    // ========================================================================

    /// テスト用の標準ルールセットを生成
    ///
    /// grep/glob をルートに、read/summary を終端とするシンプルなルール。
    /// exploration モジュール全体のテストで共通利用される。
    #[cfg(test)]
    pub fn for_testing() -> Self {
        Self::new()
            .add_roots(&["grep", "glob"])
            .add_rules("grep", &["read", "summary"])
            .add_rule("glob", "grep")
            .add_terminals(&["read", "summary"])
    }
}

// ============================================================================
// Rules trait implementation for NodeRules
// ============================================================================

impl Rules for NodeRules {
    fn successors(&self, node_type: &str) -> Vec<&str> {
        self.successors(node_type)
    }

    fn roots(&self) -> Vec<&str> {
        self.roots()
    }

    fn is_terminal(&self, node_type: &str) -> bool {
        self.is_terminal(node_type)
    }

    fn is_empty(&self) -> bool {
        self.is_empty()
    }

    fn param_variants(&self, node_type: &str) -> Option<(&str, &[String])> {
        self.param_variants
            .get(node_type)
            .map(|(key, values)| (key.as_str(), values.as_slice()))
    }
}

// ============================================================================
// From<DependencyGraph> - ドメイン固有グラフからの変換
// ============================================================================

impl From<DependencyGraph> for NodeRules {
    /// DependencyGraph(ドメイン固有)から NodeRules(ドメイン非依存)へ変換
    ///
    /// - edges → successors + edge_confidence
    /// - start_nodes → roots
    /// - terminal_nodes → terminals
    /// - param_variants → param_variants
    fn from(graph: DependencyGraph) -> Self {
        let mut rules = NodeRules::new();

        // start_nodes → roots
        for start in graph.start_actions() {
            rules.roots.insert(start);
        }

        // terminal_nodes → terminals
        for terminal in graph.terminal_actions() {
            rules.terminals.insert(terminal);
        }

        // edges → successors + edge_confidence
        for edge in graph.edges() {
            rules
                .successors
                .entry(edge.from.clone())
                .or_default()
                .insert(edge.to.clone());
            rules
                .edge_confidence
                .insert((edge.from.clone(), edge.to.clone()), edge.confidence);
        }

        // param_variants を引き継ぐ
        for (action, (key, values)) in graph.all_param_variants() {
            rules
                .param_variants
                .insert(action.clone(), (key.clone(), values.clone()));
        }

        rules
    }
}

impl From<&DependencyGraph> for NodeRules {
    fn from(graph: &DependencyGraph) -> Self {
        let mut rules = NodeRules::new();

        for start in graph.start_actions() {
            rules.roots.insert(start);
        }

        for terminal in graph.terminal_actions() {
            rules.terminals.insert(terminal);
        }

        // edges → successors + edge_confidence
        for edge in graph.edges() {
            rules
                .successors
                .entry(edge.from.clone())
                .or_default()
                .insert(edge.to.clone());
            rules
                .edge_confidence
                .insert((edge.from.clone(), edge.to.clone()), edge.confidence);
        }

        // param_variants を引き継ぐ
        for (action, (key, values)) in graph.all_param_variants() {
            rules
                .param_variants
                .insert(action.clone(), (key.clone(), values.clone()));
        }

        rules
    }
}

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

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

    #[test]
    fn test_node_rules_basic() {
        let rules = NodeRules::new()
            .add_roots(&["grep", "glob"])
            .add_rules("grep", &["read", "summary", "grep"])
            .add_rules("read", &["analyze", "extract"])
            .add_rule("summary", "report")
            .add_terminals(&["report", "extract"]);

        // ルート確認
        let roots = rules.roots();
        assert!(roots.contains(&"grep"));
        assert!(roots.contains(&"glob"));

        // 遷移確認
        let grep_successors = rules.successors("grep");
        assert_eq!(grep_successors.len(), 3);
        assert!(grep_successors.contains(&"read"));
        assert!(grep_successors.contains(&"summary"));

        // 遷移可能性
        assert!(rules.can_transition("grep", "read"));
        assert!(!rules.can_transition("grep", "report"));
        assert!(rules.can_transition("summary", "report"));

        // 終端確認
        assert!(rules.is_terminal("report"));
        assert!(rules.is_terminal("extract"));
        assert!(!rules.is_terminal("grep"));
    }

    #[test]
    fn test_node_rules_empty() {
        let rules = NodeRules::new();
        assert!(rules.is_empty());
        assert!(rules.successors("anything").is_empty());
        assert!(rules.roots().is_empty());
    }

    #[test]
    fn test_node_rules_has_node_type() {
        let rules = NodeRules::new()
            .add_root("start")
            .add_rule("middle", "end")
            .add_terminal("end");

        assert!(rules.has_node_type("start"));
        assert!(rules.has_node_type("middle"));
        assert!(rules.has_node_type("end"));
        assert!(!rules.has_node_type("unknown"));
    }

    // ========================================================================
    // From<DependencyGraph> Tests
    // ========================================================================

    #[test]
    fn test_from_dependency_graph() {
        let graph = DependencyGraphBuilder::new()
            .task("Find auth function")
            .available_actions(["Grep", "List", "Read"])
            .edge("Grep", "Read", 0.95)
            .edge("List", "Grep", 0.60)
            .edge("List", "Read", 0.40)
            .start_nodes(["Grep", "List"])
            .terminal_node("Read")
            .build();

        // 変換
        let rules: NodeRules = graph.into();

        // ルート確認
        assert!(rules.is_root("Grep"));
        assert!(rules.is_root("List"));
        assert!(!rules.is_root("Read"));

        // 終端確認
        assert!(rules.is_terminal("Read"));
        assert!(!rules.is_terminal("Grep"));

        // 遷移確認(confidence は捨てられる)
        assert!(rules.can_transition("Grep", "Read"));
        assert!(rules.can_transition("List", "Grep"));
        assert!(rules.can_transition("List", "Read"));
        assert!(!rules.can_transition("Read", "Grep")); // 逆方向は不可
    }

    #[test]
    fn test_from_dependency_graph_ref() {
        let graph = DependencyGraphBuilder::new()
            .edge("A", "B", 0.9)
            .start_node("A")
            .terminal_node("B")
            .build();

        // 参照から変換
        let rules: NodeRules = (&graph).into();

        assert!(rules.is_root("A"));
        assert!(rules.is_terminal("B"));
        assert!(rules.can_transition("A", "B"));
    }
}