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
//! GraphMap 統合テスト
//!
//! 探索シナリオ全体をテストする。
//! Map の基本 API テストは map.rs 内の unit tests を参照。

use swarm_engine_core::exploration::map::{
    ExplorationMap, GraphMap, HierarchicalMap, MapNodeState,
};

// ============================================================================
// テスト用の型定義
// ============================================================================

/// テスト用ノード型
#[derive(Debug, Clone, PartialEq)]
enum NodeType {
    /// 検索クエリ(ルート)
    Search { query: String },
    /// ファイル(Read で内容確認 → Close)
    File { path: String },
    /// ディレクトリ(List で子を展開 → Close)
    Dir { path: String },
}

impl NodeType {
    fn key(&self) -> String {
        match self {
            NodeType::Search { query } => format!("search:{}", query),
            NodeType::File { path } => format!("file:{}", path),
            NodeType::Dir { path } => format!("dir:{}", path),
        }
    }
}

/// エッジ(アクション)の型
#[derive(Debug, Clone, PartialEq)]
enum EdgeType {
    Grep,
    List,
}

// ============================================================================
// 基本探索フローテスト
// ============================================================================

/// 基本的な探索フロー
///
/// シナリオ:
/// 1. Search("auth") をルートに
/// 2. Grep → File("src/auth.rs"), Dir("src/auth/")
/// 3. File → Read → Close
/// 4. Dir → List → File("src/auth/mod.rs"), File("src/auth/login.rs")
/// 5. 重複チェック: 同じパスは追加しない
/// 6. 全て Close
#[test]
fn test_exploration_basic_flow() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    // Step 1: Search ルートを作成
    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "auth".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    assert_eq!(map.frontiers().len(), 1);

    // Step 2: Grep 結果を追加
    let file1 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::File {
                path: "src/auth.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let dir1 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "src/auth/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    // root は子が生成されたので Close
    map.set_state(root, MapNodeState::Closed);
    assert_eq!(map.frontiers().len(), 2); // file1, dir1

    // Step 3: File を Read して Close
    map.set_state(file1, MapNodeState::Closed);
    assert_eq!(map.frontiers().len(), 1); // dir1 only

    // Step 4: Dir を List して子ファイルを発見
    let file2 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "src/auth/mod.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file3 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "src/auth/login.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    // dir1 は展開完了したので Close
    map.set_state(dir1, MapNodeState::Closed);
    assert_eq!(map.frontiers().len(), 2); // file2, file3

    // Step 5: 重複チェック
    let dup_result = map.add_child_if_absent(
        root,
        EdgeType::Grep,
        NodeType::File {
            path: "src/auth.rs".to_string(),
        },
        MapNodeState::Open,
        key_fn,
    );
    assert!(dup_result.unwrap().is_already_exists());
    assert_eq!(map.node_count(), 5); // root, file1, dir1, file2, file3

    // Step 6: 残りを Close
    map.set_state(file2, MapNodeState::Closed);
    map.set_state(file3, MapNodeState::Closed);

    // 全て Close されたか確認
    assert!(map.frontiers().is_empty());
    assert_eq!(map.closed_nodes().len(), 5);
}

/// 深い階層の探索
///
/// シナリオ: root → dir1 → dir2 → dir3 → file
#[test]
fn test_exploration_deep_hierarchy() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "deep".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    // 階層的にディレクトリを展開
    let dir1 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "a/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();
    map.set_state(root, MapNodeState::Closed);

    let dir2 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::Dir {
                path: "a/b/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();
    map.set_state(dir1, MapNodeState::Closed);

    let dir3 = map
        .add_child_if_absent(
            dir2,
            EdgeType::List,
            NodeType::Dir {
                path: "a/b/c/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();
    map.set_state(dir2, MapNodeState::Closed);

    let file = map
        .add_child_if_absent(
            dir3,
            EdgeType::List,
            NodeType::File {
                path: "a/b/c/target.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();
    map.set_state(dir3, MapNodeState::Closed);

    // depth 確認
    assert_eq!(map.depth(root), 0);
    assert_eq!(map.depth(dir1), 1);
    assert_eq!(map.depth(dir2), 2);
    assert_eq!(map.depth(dir3), 3);
    assert_eq!(map.depth(file), 4);

    // 親子関係確認
    assert_eq!(map.parent(file), Some(dir3));
    assert_eq!(map.parent(dir3), Some(dir2));
    assert_eq!(map.parent(dir2), Some(dir1));
    assert_eq!(map.parent(dir1), Some(root));
    assert_eq!(map.parent(root), None);

    // frontiers は file のみ
    assert_eq!(map.frontiers(), vec![file]);

    // file を Close
    map.set_state(file, MapNodeState::Closed);
    assert!(map.frontiers().is_empty());
}

/// 並列 Worker による重複防止
///
/// シナリオ: Worker A と Worker B が同時に同じファイルを発見
#[test]
fn test_exploration_parallel_workers() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "parallel".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    // Worker A: auth.rs を発見
    let result_a = map.add_child_if_absent(
        root,
        EdgeType::Grep,
        NodeType::File {
            path: "auth.rs".to_string(),
        },
        MapNodeState::Open,
        key_fn,
    );
    let file_a = result_a.unwrap();
    assert!(file_a.is_added());

    // Worker B: 同じ auth.rs を発見(並行実行をシミュレート)
    let result_b = map.add_child_if_absent(
        root,
        EdgeType::Grep,
        NodeType::File {
            path: "auth.rs".to_string(),
        },
        MapNodeState::Open,
        key_fn,
    );
    let file_b = result_b.unwrap();
    assert!(file_b.is_already_exists());

    // 同じ ID を返すことを確認
    assert_eq!(file_a.into_inner(), file_b.into_inner());

    // ノード数は 2 (root + auth.rs)
    assert_eq!(map.node_count(), 2);
}

/// サイクル防止
///
/// シナリオ: シンボリックリンク等でサイクルが発生するケース
/// dir_a/ → dir_b/ → dir_a/ (cycle!)
#[test]
fn test_exploration_cycle_prevention() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "cycle".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    let dir_a = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "dir_a/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();
    map.set_state(root, MapNodeState::Closed);

    let dir_b = map
        .add_child_if_absent(
            dir_a,
            EdgeType::List,
            NodeType::Dir {
                path: "dir_b/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();
    map.set_state(dir_a, MapNodeState::Closed);

    // dir_b から dir_a へのサイクル → 重複チェックで追加されない
    let cycle_result = map.add_child_if_absent(
        dir_b,
        EdgeType::List,
        NodeType::Dir {
            path: "dir_a/".to_string(),
        },
        MapNodeState::Open,
        key_fn,
    );
    assert!(cycle_result.unwrap().is_already_exists());

    // dir_b を Close
    map.set_state(dir_b, MapNodeState::Closed);

    // ノード数は 3 (root, dir_a, dir_b) - サイクルは追加されない
    assert_eq!(map.node_count(), 3);
    assert!(map.frontiers().is_empty());
}

// ============================================================================
// カスケードテスト
// ============================================================================

/// 下方向カスケード
///
/// 構造:
///       root
///      /    \
///   dir1    dir2
///   /  \
/// file1 file2
#[test]
fn test_cascade_down() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "test".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    let dir1 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "dir1/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let dir2 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "dir2/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file1 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "dir1/a.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file2 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "dir1/b.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    assert_eq!(map.frontiers().len(), 5);

    // dir1 から下方向カスケード → dir1, file1, file2 が Close
    let closed = map.cascade_down(dir1);

    assert_eq!(closed.len(), 3); // file1, file2, dir1
    assert!(map.get(dir1).unwrap().state.is_closed());
    assert!(map.get(file1).unwrap().state.is_closed());
    assert!(map.get(file2).unwrap().state.is_closed());

    // root と dir2 は Open のまま
    assert!(map.get(root).unwrap().state.is_open());
    assert!(map.get(dir2).unwrap().state.is_open());
    assert_eq!(map.frontiers().len(), 2); // root, dir2
}

/// 上方向カスケード
///
/// 構造:
///       root
///      /    \
///   dir1    dir2
///   /  \
/// file1 file2
#[test]
fn test_cascade_up() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "test".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    let dir1 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "dir1/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let dir2 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "dir2/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file1 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "dir1/a.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file2 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "dir1/b.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    // Step 1: file1 を Close + up cascade
    let closed1 = map.close_with_cascade_up(file1);
    // file1 のみ Close(file2 がまだ Open なので dir1 は Close されない)
    assert_eq!(closed1, vec![file1]);
    assert!(map.get(dir1).unwrap().state.is_open());

    // Step 2: file2 を Close + up cascade
    let closed2 = map.close_with_cascade_up(file2);
    // file2 と dir1 が Close(dir1 の子が全て Closed になった)
    assert_eq!(closed2.len(), 2);
    assert!(closed2.contains(&file2));
    assert!(closed2.contains(&dir1));
    assert!(map.get(dir1).unwrap().state.is_closed());
    assert!(map.get(root).unwrap().state.is_open()); // dir2 がまだ Open

    // Step 3: dir2 を Close + up cascade
    let closed3 = map.close_with_cascade_up(dir2);
    // dir2 と root が Close(root の子が全て Closed になった)
    assert_eq!(closed3.len(), 2);
    assert!(closed3.contains(&dir2));
    assert!(closed3.contains(&root));
    assert!(map.get(root).unwrap().state.is_closed());

    // 全て Close
    assert!(map.frontiers().is_empty());
}

/// 探索フローで上方向カスケードを使用
///
/// シナリオ:
/// 1. Search → Grep → dir1, dir2
/// 2. dir1 → List → file1, file2
/// 3. dir2 → List → file3
/// 4. 各ファイルを Close + up_cascade
/// 5. 自動的に全て Close される
#[test]
fn test_exploration_with_up_cascade() {
    let mut map: GraphMap<NodeType, EdgeType, MapNodeState> = GraphMap::new();
    let key_fn = |n: &NodeType| n.key();

    // 構築
    let root = map
        .create_root_if_absent(
            NodeType::Search {
                query: "auth".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .into_inner();

    let dir1 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "auth/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let dir2 = map
        .add_child_if_absent(
            root,
            EdgeType::Grep,
            NodeType::Dir {
                path: "user/".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file1 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "auth/mod.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file2 = map
        .add_child_if_absent(
            dir1,
            EdgeType::List,
            NodeType::File {
                path: "auth/login.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    let file3 = map
        .add_child_if_absent(
            dir2,
            EdgeType::List,
            NodeType::File {
                path: "user/mod.rs".to_string(),
            },
            MapNodeState::Open,
            key_fn,
        )
        .unwrap()
        .into_inner();

    assert_eq!(map.node_count(), 6);
    assert_eq!(map.frontiers().len(), 6);

    // ファイルを順に Close + up_cascade
    let c1 = map.close_with_cascade_up(file1);
    assert_eq!(c1, vec![file1]); // file2 がまだ Open

    let c2 = map.close_with_cascade_up(file2);
    assert!(c2.contains(&file2));
    assert!(c2.contains(&dir1)); // dir1 の子が全て Closed

    let c3 = map.close_with_cascade_up(file3);
    assert!(c3.contains(&file3));
    assert!(c3.contains(&dir2));
    assert!(c3.contains(&root)); // 全て Close

    // 最終確認
    assert!(map.frontiers().is_empty());
    assert_eq!(map.closed_nodes().len(), 6);
}