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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
//! Exploration Map - 探索マップの抽象層
//!
//! 課題空間を「マップ走査」として解くための抽象インターフェース。
//!
//! # 設計思想
//!
//! - **Tick ベース更新**: `apply(update) -> Result` で状態を確定的に更新
//! - **Node の抽象化**: 何を Node とするかは実装が決める
//! - **内部表現の自由**: Graph / Grid / Tree など実装詳細は隠蔽
//!
//! # 使用例
//!
//! ```ignore
//! // 課題を Node とするマップ
//! let mut map = TaskMap::new();
//!
//! // Tick ごとに更新を適用
//! let result = map.apply(update);
//!
//! // フロンティアから次の探索対象を取得
//! for node_id in map.frontiers() {
//!     let node = map.get(node_id);
//!     // ...
//! }
//! ```
//!
//! # 旧 ExplorationSpace からの移行
//!
//! 旧 `ExplorationSpace` には以下の機能があったが、クリーンな探索マップ設計では
//! 多くが不要になる(または別レイヤーの責務となる)。
//!
//! ## 新設計で解決済み
//!
//! | 旧機能 | 問題点 | 新設計での解決 |
//! |--------|--------|----------------|
//! | `NodeKind` (Exploration/ActionNode) | 分岐がコード全体に散らばる | Node 型パラメータ `<N>` で柔軟に |
//! | 2つの apply API | `apply_update` と `apply_results` 混在 | `apply()` に統一 |
//! | `ExplorationNode` 固定 | 拡張性がない | `MapNode<T>` で任意データを格納 |
//!
//! ## 別レイヤーの責務(マップ外で処理)
//!
//! | 旧機能 | 新設計での扱い |
//! |--------|----------------|
//! | `DependencyGraph` 統合 | Orchestrator/Strategy 層で注入 |
//! | `SubRoot` 管理 | 上位レイヤーで課題分解を担当 |
//! | `NodeSelectionStrategy` | Strategy 層で `frontiers()` を使って実装 |
//! | `has_successful_action_globally` | 上位レイヤーで履歴管理 |
//!
//! ## シンプル化により不要
//!
//! | 旧機能 | 理由 |
//! |--------|------|
//! | `NodeState` (5状態) | `Open`/`Closed` の2状態で十分。詳細は Node データ `T` で管理 |
//! | `TrialPolicy` (OneShot/Retriable/Probabilistic) | Node データ `T` でリトライ回数を管理 |
//! | `ActionCategory` (NodeExpand/NodeStateChange) | Update バリアントで明示 |
//! | `ExplorationTarget` / `ExplorationUpdate` | `GraphMapUpdate` で統一 |
//! | `NodeAssignment` (複雑なメタデータ) | シンプルな `MapNodeId` で足りる |
//!
//! ## 設計原則
//!
//! 1. **マップは純粋なデータ構造**: 戦略やポリシーは外から注入
//! 2. **Tick ベースの確定的更新**: `apply()` で全ての状態遷移を表現
//! 3. **Node の抽象化**: 課題/Action/状態など、用途に応じて型で表現
//! 4. **複雑さは上位レイヤーへ**: DependencyGraph、SubRoot 等は Orchestrator の責務

use std::collections::hash_map::DefaultHasher;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};

use serde::{Deserialize, Serialize};

// ============================================================================
// Core ID Types
// ============================================================================

/// ノード ID(マップ内で一意)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MapNodeId(pub u64);

impl MapNodeId {
    pub fn new(id: u64) -> Self {
        Self(id)
    }
}

/// エッジ ID(マップ内で一意)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MapEdgeId(pub u64);

impl MapEdgeId {
    pub fn new(id: u64) -> Self {
        Self(id)
    }
}

// ============================================================================
// Error Types
// ============================================================================

/// マップ操作のエラー
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum MapError {
    /// ノードが見つからない
    #[error("Node not found: {0:?}")]
    NodeNotFound(MapNodeId),

    /// エッジが見つからない
    #[error("Edge not found: {0:?}")]
    EdgeNotFound(MapEdgeId),

    /// ノード ID の衝突
    #[error("Node ID conflict: {0:?}")]
    NodeConflict(MapNodeId),

    /// エッジ ID の衝突
    #[error("Edge ID conflict: {0:?}")]
    EdgeConflict(MapEdgeId),

    /// 無効な状態遷移
    #[error("Invalid state transition: {from:?} -> {to:?}")]
    InvalidStateTransition {
        node_id: MapNodeId,
        from: MapNodeState,
        to: MapNodeState,
    },

    /// ルートノードが既に存在
    #[error("Root node already exists: {0:?}")]
    RootAlreadyExists(MapNodeId),

    /// 親ノードが見つからない
    #[error("Parent node not found: {0:?}")]
    ParentNotFound(MapNodeId),

    /// ノードが既に Closed
    #[error("Node already closed: {0:?}")]
    AlreadyClosed(MapNodeId),
}

/// マップ操作の結果型
pub type MapResult<T> = Result<T, MapError>;

/// 追加操作の結果
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AddResult<T> {
    /// 新規追加された
    Added(T),
    /// 既に存在していた(既存の値を返す)
    AlreadyExists(T),
}

impl<T> AddResult<T> {
    /// 追加されたかどうか
    pub fn is_added(&self) -> bool {
        matches!(self, Self::Added(_))
    }

    /// 既に存在していたかどうか
    pub fn is_already_exists(&self) -> bool {
        matches!(self, Self::AlreadyExists(_))
    }

    /// 内部の値を取得
    pub fn into_inner(self) -> T {
        match self {
            Self::Added(v) | Self::AlreadyExists(v) => v,
        }
    }

    /// 内部の値への参照を取得
    pub fn as_inner(&self) -> &T {
        match self {
            Self::Added(v) | Self::AlreadyExists(v) => v,
        }
    }
}

// ============================================================================
// Core Trait: ExplorationMap
// ============================================================================

/// 探索マップの抽象インターフェース
///
/// Tick ベースでマップを更新し、探索状態を管理する。
///
/// # 型パラメータ
///
/// - `Node`: ノードに持たせるデータ(課題 / Action / 状態 など)
/// - `Edge`: エッジに持たせるデータ(遷移情報など)
/// - `Update`: Tick 更新の入力型
/// - `Result`: apply の結果型
///
/// # 実装例
///
/// - `GraphMap`: グラフ構造のマップ(現在の ExplorationSpace に相当)
/// - `GridMap`: グリッド構造のマップ
/// - `TreeMap`: 木構造のマップ
pub trait ExplorationMap {
    /// ノードに持たせるデータ型
    type Node: Debug + Clone;

    /// エッジに持たせるデータ型
    type Edge: Debug + Clone;

    /// Tick 更新の入力型
    type Update;

    /// apply の結果型
    type Result;

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

    /// 更新を適用する(Tick の中心 API)
    ///
    /// 毎 Tick でこのメソッドを呼び、マップ状態を更新する。
    /// 更新は確定的に処理され、結果が返される。
    fn apply(&mut self, update: Self::Update) -> Self::Result;

    /// 複数の更新をバッチ適用
    fn apply_batch(&mut self, updates: Vec<Self::Update>) -> Vec<Self::Result> {
        updates.into_iter().map(|u| self.apply(u)).collect()
    }

    // ========================================================================
    // Node API
    // ========================================================================

    /// ノードを取得
    fn get(&self, id: MapNodeId) -> Option<&Self::Node>;

    /// ノードを変更可能で取得
    fn get_mut(&mut self, id: MapNodeId) -> Option<&mut Self::Node>;

    /// ノード数
    fn node_count(&self) -> usize;

    // ========================================================================
    // Frontier API
    // ========================================================================

    /// 現在のフロンティア(Expandable なノード群)を取得
    ///
    /// Closed になったノードは含まれない。
    /// これを「枯渇」「完了」と解釈するかは利用者の責務。
    fn frontiers(&self) -> Vec<MapNodeId>;
}

// ============================================================================
// Extended Traits
// ============================================================================

/// グラフ構造を持つマップ
///
/// ノード間のエッジ関係をクエリ可能。
pub trait GraphExplorationMap: ExplorationMap {
    /// エッジを取得
    fn get_edge(&self, id: MapEdgeId) -> Option<&Self::Edge>;

    /// ノードからの出ていくエッジを取得
    fn outgoing_edges(&self, node: MapNodeId) -> Vec<MapEdgeId>;

    /// ノードに入ってくるエッジを取得(親エッジ)
    fn incoming_edge(&self, node: MapNodeId) -> Option<MapEdgeId>;

    /// エッジ数
    fn edge_count(&self) -> usize;

    /// ルートノードを取得
    fn root(&self) -> Option<MapNodeId>;
}

/// 階層構造を持つマップ
///
/// 親子関係をクエリ可能。
pub trait HierarchicalMap: ExplorationMap {
    /// 親ノードを取得
    fn parent(&self, node: MapNodeId) -> Option<MapNodeId>;

    /// 子ノード群を取得
    fn children(&self, node: MapNodeId) -> Vec<MapNodeId>;

    /// ノードの深さを取得
    fn depth(&self, node: MapNodeId) -> u32;
}

// ============================================================================
// Common Update Types
// ============================================================================

/// 汎用的な更新結果
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MapApplyResult<N> {
    /// 新しいノードが作成された
    NodeCreated { node_id: MapNodeId, data: N },
    /// ノードの状態が更新された
    NodeUpdated { node_id: MapNodeId },
    /// ノードが完了としてマークされた
    NodeCompleted { node_id: MapNodeId },
    /// ノードが行き止まりとしてマークされた
    NodeDeadEnd { node_id: MapNodeId },
    /// 失敗(リトライ可能かどうかを含む)
    Failed {
        node_id: MapNodeId,
        can_retry: bool,
        reason: String,
    },
    /// 無視された(重複や Pending など)
    Ignored,
}

// ============================================================================
// MapState Trait - 状態型の最小制約
// ============================================================================

/// Map が状態型 S に要求する制約
///
/// Map は状態の「意味」を知らない。Map が興味を持つのは2点のみ:
///
/// - **Expandable**: 子ノード追加可能(フロンティアとして管理)
/// - **Closed**: 終了(フロンティアから除外)
///
/// 具体的な状態の詳細(Unexplored/Exploring/Explored/DeadEnd/Completed/Processing 等)は
/// この trait を実装する型で自由に定義できる。Map はそれらを
/// `is_expandable()` / `is_closed()` で抽象化して扱う。
///
/// # 例: カスタム状態型
///
/// ```ignore
/// #[derive(Clone, Debug)]
/// enum MyState {
///     Pending,      // → Expandable
///     Processing,   // → neither (Map は関与しない)
///     Completed,    // → Closed
///     Failed,       // → Closed
/// }
///
/// impl MapState for MyState {
///     fn is_expandable(&self) -> bool {
///         matches!(self, Self::Pending)
///     }
///     fn is_closed(&self) -> bool {
///         matches!(self, Self::Completed | Self::Failed)
///     }
///     fn closed() -> Self {
///         Self::Completed
///     }
/// }
/// ```
pub trait MapState: Clone + std::fmt::Debug {
    /// フロンティアとして展開可能か
    fn is_expandable(&self) -> bool;

    /// 終了状態か(フロンティアから除外される)
    fn is_closed(&self) -> bool;

    /// デフォルトの Closed 状態を返す(カスケード操作等で使用)
    fn closed() -> Self;
}

// ============================================================================
// MapNodeState - デフォルトの2状態実装
// ============================================================================

/// ノードの基本状態
///
/// シンプルに Open(探索可能)と Closed(終了)の2状態のみ。
/// 詳細な状態(成功/失敗/リトライ回数など)は Node のデータ `T` で管理する。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum MapNodeState {
    /// 探索可能(フロンティア)
    #[default]
    Open,
    /// 終了(フロンティアから除外)
    Closed,
}

impl MapState for MapNodeState {
    fn is_expandable(&self) -> bool {
        matches!(self, Self::Open)
    }

    fn is_closed(&self) -> bool {
        matches!(self, Self::Closed)
    }

    fn closed() -> Self {
        Self::Closed
    }
}

impl MapNodeState {
    /// フロンティアになりうる状態か
    pub fn is_open(&self) -> bool {
        matches!(self, Self::Open)
    }

    /// 終了状態か
    pub fn is_closed(&self) -> bool {
        matches!(self, Self::Closed)
    }
}

// ============================================================================
// Node Wrapper
// ============================================================================

/// 汎用ノードラッパー
///
/// ユーザー定義のデータ `N` と状態 `S` に共通のメタデータを付与する。
///
/// # 型パラメータ
///
/// - `N`: ノードデータの型
/// - `S`: 状態の型(MapState を実装)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MapNode<N, S: MapState> {
    /// ノード ID
    pub id: MapNodeId,
    /// ユーザー定義データ
    pub data: N,
    /// 状態
    pub state: S,
    /// 深さ
    pub depth: u32,
    /// 親エッジ(ルートは None)
    pub parent_edge: Option<MapEdgeId>,
}

impl<N, S: MapState> MapNode<N, S> {
    pub fn new(id: MapNodeId, data: N, state: S) -> Self {
        Self {
            id,
            data,
            state,
            depth: 0,
            parent_edge: None,
        }
    }

    pub fn with_state(mut self, state: S) -> Self {
        self.state = state;
        self
    }

    pub fn with_depth(mut self, depth: u32) -> Self {
        self.depth = depth;
        self
    }

    pub fn with_parent(mut self, edge: MapEdgeId) -> Self {
        self.parent_edge = Some(edge);
        self
    }
}

// ============================================================================
// Edge Wrapper
// ============================================================================

/// 汎用エッジラッパー
///
/// ユーザー定義のデータ `T` に共通のメタデータを付与する。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MapEdge<T> {
    /// エッジ ID
    pub id: MapEdgeId,
    /// 元ノード
    pub from: MapNodeId,
    /// 先ノード(成功時のみ設定)
    pub to: Option<MapNodeId>,
    /// ユーザー定義データ
    pub data: T,
    /// 試行回数
    pub attempts: u32,
    /// 成功したか
    pub succeeded: bool,
}

impl<T> MapEdge<T> {
    pub fn new(id: MapEdgeId, from: MapNodeId, data: T) -> Self {
        Self {
            id,
            from,
            to: None,
            data,
            attempts: 0,
            succeeded: false,
        }
    }

    pub fn mark_success(&mut self, to: MapNodeId) {
        self.succeeded = true;
        self.to = Some(to);
        self.attempts += 1;
    }

    pub fn mark_failure(&mut self) {
        self.succeeded = false;
        self.attempts += 1;
    }
}

// ============================================================================
// GraphMap - グラフ構造のマップ実装
// ============================================================================

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

/// グラフベースの探索マップ
///
/// ノードとエッジでグラフ構造を表現する。
/// `ExplorationMap` と `GraphExplorationMap` を実装。
///
/// # 型パラメータ
///
/// - `N`: ノードデータの型(課題 / Action / 状態 など)
/// - `E`: エッジデータの型(アクション / 遷移情報 など)
/// - `S`: 状態の型(MapState を実装)
///
/// # 使用例
///
/// ```ignore
/// // 文字列をノードデータとするマップ
/// let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
///
/// // ルートノードを作成
/// let root = map.create_root("start".to_string(), MapNodeState::Open);
///
/// // 子ノードを追加
/// let update = GraphMapUpdate::AddChild {
///     parent: root,
///     edge_data: "action-1".to_string(),
///     node_data: "state-1".to_string(),
///     node_state: MapNodeState::Open,
///     dedup_key: "state-1".to_string(),
/// };
/// let result = map.apply(update);
/// ```
#[derive(Debug, Clone)]
pub struct GraphMap<N, E, S: MapState> {
    /// ノード群
    nodes: HashMap<MapNodeId, MapNode<N, S>>,
    /// エッジ群
    edges: HashMap<MapEdgeId, MapEdge<E>>,
    /// フロンティア(展開可能なノード群)- O(1) 操作のため HashSet
    expandables: HashSet<MapNodeId>,
    /// ルートノード
    root: Option<MapNodeId>,
    /// 次のノード ID
    next_node_id: u64,
    /// 次のエッジ ID
    next_edge_id: u64,
    /// ノードインデックス(キーハッシュ → ノードID)
    /// 重複チェック用。キー抽出関数のハッシュ値でノードを検索可能にする。
    index: HashMap<u64, MapNodeId>,
}

impl<N, E, S: MapState> Default for GraphMap<N, E, S> {
    fn default() -> Self {
        Self::new()
    }
}

impl<N, E, S: MapState> GraphMap<N, E, S> {
    /// 空のマップを作成
    pub fn new() -> Self {
        Self {
            nodes: HashMap::new(),
            edges: HashMap::new(),
            expandables: HashSet::new(),
            root: None,
            next_node_id: 0,
            next_edge_id: 0,
            index: HashMap::new(),
        }
    }

    // ========================================================================
    // Index API (D)
    // ========================================================================

    /// キーのハッシュ値を計算
    fn compute_hash<K: Hash>(key: &K) -> u64 {
        let mut hasher = DefaultHasher::new();
        key.hash(&mut hasher);
        hasher.finish()
    }

    /// ノードをインデックスに登録
    ///
    /// キー抽出関数でキーを取得し、ハッシュ値でインデックスに登録する。
    pub fn index_node<K, F>(&mut self, node_id: MapNodeId, key_fn: F)
    where
        K: Hash,
        F: FnOnce(&N) -> K,
    {
        if let Some(node) = self.nodes.get(&node_id) {
            let key = key_fn(&node.data);
            let hash = Self::compute_hash(&key);
            self.index.insert(hash, node_id);
        }
    }

    /// キーでノードを検索
    ///
    /// インデックスを使って O(1) で検索。
    pub fn get_by_key<K: Hash>(&self, key: &K) -> Option<MapNodeId> {
        let hash = Self::compute_hash(key);
        self.index.get(&hash).copied()
    }

    /// キーが存在するか確認
    pub fn contains_key<K: Hash>(&self, key: &K) -> bool {
        self.get_by_key(key).is_some()
    }

    /// インデックスをクリア
    pub fn clear_index(&mut self) {
        self.index.clear();
    }

    /// インデックスを再構築
    ///
    /// 全ノードに対してキー抽出関数を適用し、インデックスを再構築する。
    pub fn rebuild_index<K, F>(&mut self, key_fn: F)
    where
        K: Hash,
        F: Fn(&N) -> K,
    {
        self.index.clear();
        for (&node_id, node) in &self.nodes {
            let key = key_fn(&node.data);
            let hash = Self::compute_hash(&key);
            self.index.insert(hash, node_id);
        }
    }

    // ========================================================================
    // Search API (B)
    // ========================================================================

    /// 条件に一致する最初のノードを検索
    ///
    /// O(n) の線形検索。頻繁に呼ぶ場合はインデックスを使う。
    pub fn find_node<F>(&self, predicate: F) -> Option<MapNodeId>
    where
        F: Fn(&MapNode<N, S>) -> bool,
    {
        self.nodes.values().find(|n| predicate(n)).map(|n| n.id)
    }

    /// 条件に一致する全ノードを検索
    pub fn find_nodes<F>(&self, predicate: F) -> Vec<MapNodeId>
    where
        F: Fn(&MapNode<N, S>) -> bool,
    {
        self.nodes
            .values()
            .filter(|n| predicate(n))
            .map(|n| n.id)
            .collect()
    }

    /// データで検索(N: PartialEq の場合)
    pub fn find_by_data(&self, data: &N) -> Option<MapNodeId>
    where
        N: PartialEq,
    {
        self.nodes.values().find(|n| &n.data == data).map(|n| n.id)
    }

    /// 状態で検索(S: PartialEq の場合)
    ///
    /// 指定した状態のノードを全て返す。
    /// 利用者が「Completed 状態のノード」「Failed 状態のノード」等を
    /// 取得するのに使う。
    pub fn find_by_state(&self, state: &S) -> Vec<MapNodeId>
    where
        S: PartialEq,
    {
        self.nodes
            .values()
            .filter(|n| &n.state == state)
            .map(|n| n.id)
            .collect()
    }

    /// 状態の条件で検索
    ///
    /// 状態に対する任意の条件でノードを検索する。
    pub fn find_nodes_by_state<F>(&self, predicate: F) -> Vec<MapNodeId>
    where
        F: Fn(&S) -> bool,
    {
        self.nodes
            .values()
            .filter(|n| predicate(&n.state))
            .map(|n| n.id)
            .collect()
    }

    // ========================================================================
    // Add with Dedup API
    // ========================================================================

    /// 重複チェック付きルートノード作成
    ///
    /// キーが既に存在する場合は既存ノードを返す。
    pub fn create_root_if_absent<K, F>(
        &mut self,
        data: N,
        state: S,
        key_fn: F,
    ) -> AddResult<MapNodeId>
    where
        K: Hash,
        F: FnOnce(&N) -> K,
    {
        let key = key_fn(&data);
        let hash = Self::compute_hash(&key);

        if let Some(&existing) = self.index.get(&hash) {
            return AddResult::AlreadyExists(existing);
        }

        let id = self.create_root(data, state);
        self.index.insert(hash, id);
        AddResult::Added(id)
    }

    /// 重複チェック付きノード追加(親ノード指定)
    ///
    /// キーが既に存在する場合は既存ノードを返す。
    /// 親ノードが見つからない場合はエラー。
    pub fn add_child_if_absent<K, F>(
        &mut self,
        parent: MapNodeId,
        edge_data: E,
        node_data: N,
        node_state: S,
        key_fn: F,
    ) -> MapResult<AddResult<MapNodeId>>
    where
        K: Hash,
        F: FnOnce(&N) -> K,
    {
        let key = key_fn(&node_data);
        let hash = Self::compute_hash(&key);

        if let Some(&existing) = self.index.get(&hash) {
            return Ok(AddResult::AlreadyExists(existing));
        }

        // 親ノードの深さを取得
        let parent_depth = self
            .nodes
            .get(&parent)
            .map(|n| n.depth)
            .ok_or(MapError::ParentNotFound(parent))?;

        // エッジとノードを作成
        let edge_id = self.add_edge(parent, edge_data);
        let id = self.add_node(node_data, node_state, edge_id, parent_depth + 1);

        // エッジの to を設定(親子関係を確立)
        if let Some(edge) = self.edges.get_mut(&edge_id) {
            edge.to = Some(id);
        }

        // インデックスに登録
        self.index.insert(hash, id);

        Ok(AddResult::Added(id))
    }

    /// ルートノードを作成
    pub fn create_root(&mut self, data: N, state: S) -> MapNodeId {
        let id = self.allocate_node_id();
        let node = MapNode::new(id, data, state.clone());
        self.nodes.insert(id, node);
        if state.is_expandable() {
            self.expandables.insert(id);
        }
        self.root = Some(id);
        id
    }

    /// ノードを追加(内部用)
    fn add_node(&mut self, data: N, state: S, parent_edge: MapEdgeId, depth: u32) -> MapNodeId {
        let id = self.allocate_node_id();
        let node = MapNode::new(id, data, state.clone())
            .with_parent(parent_edge)
            .with_depth(depth);
        self.nodes.insert(id, node);
        if state.is_expandable() {
            self.expandables.insert(id);
        }
        id
    }

    /// エッジを追加(内部用)
    fn add_edge(&mut self, from: MapNodeId, data: E) -> MapEdgeId {
        let id = self.allocate_edge_id();
        let edge = MapEdge::new(id, from, data);
        self.edges.insert(id, edge);

        id
    }

    /// ノード ID を割り当て
    fn allocate_node_id(&mut self) -> MapNodeId {
        let id = MapNodeId(self.next_node_id);
        self.next_node_id += 1;
        id
    }

    /// エッジ ID を割り当て
    fn allocate_edge_id(&mut self) -> MapEdgeId {
        let id = MapEdgeId(self.next_edge_id);
        self.next_edge_id += 1;
        id
    }

    /// ノードの状態を更新
    ///
    /// 状態変更時に expandables インデックスを自動更新する。
    pub fn set_state(&mut self, id: MapNodeId, state: S) {
        if let Some(node) = self.nodes.get_mut(&id) {
            let was_expandable = node.state.is_expandable();
            node.state = state;
            let is_expandable = node.state.is_expandable();

            // expandables インデックス更新(O(1))
            if was_expandable && !is_expandable {
                self.expandables.remove(&id);
            } else if !was_expandable && is_expandable {
                self.expandables.insert(id);
            }
        }
    }

    // ========================================================================
    // Batch Operations
    // ========================================================================

    /// 複数ノードを一括追加
    ///
    /// 各 (data, state) ペアからノードを作成。
    /// 最初のノードがルートになり、以降は独立したノードとして追加。
    pub fn add_nodes(&mut self, nodes: Vec<(N, S)>) -> Vec<MapNodeId> {
        nodes
            .into_iter()
            .map(|(data, state)| {
                if self.root.is_none() {
                    self.create_root(data, state)
                } else {
                    // ルートが既にある場合は独立ノードとして追加
                    let id = self.allocate_node_id();
                    let is_expandable = state.is_expandable();
                    let node = MapNode::new(id, data, state);
                    self.nodes.insert(id, node);
                    if is_expandable {
                        self.expandables.insert(id);
                    }
                    id
                }
            })
            .collect()
    }

    /// 複数ノードの状態を一括変更
    pub fn set_states(&mut self, ids: &[MapNodeId], state: S) -> Vec<MapNodeId> {
        let mut changed = Vec::new();
        for &id in ids {
            if self.nodes.contains_key(&id) {
                self.set_state(id, state.clone());
                changed.push(id);
            }
        }
        changed
    }

    /// 複数ノードを一括 Close(S::closed() を使用)
    ///
    /// 存在しないノード ID はスキップされる。
    /// 戻り値は実際に Close されたノード ID のリスト。
    pub fn close_nodes(&mut self, ids: &[MapNodeId]) -> Vec<MapNodeId> {
        self.set_states(ids, S::closed())
    }

    // ========================================================================
    // Cascade Operations
    // ========================================================================

    /// 下方向カスケード: 自身と全子孫を Close
    ///
    /// 戻り値は Close されたノード ID のリスト(指定ノード含む)。
    pub fn cascade_down(&mut self, id: MapNodeId) -> Vec<MapNodeId> {
        let mut closed = Vec::new();
        self.cascade_down_recursive(id, &mut closed);
        closed
    }

    fn cascade_down_recursive(&mut self, id: MapNodeId, closed: &mut Vec<MapNodeId>) {
        if !self.nodes.contains_key(&id) {
            return;
        }

        // 子ノードを先に処理(深さ優先)
        let children: Vec<MapNodeId> = self.children_internal(id);
        for child in children {
            self.cascade_down_recursive(child, closed);
        }

        // 自身を Close
        self.set_state(id, S::closed());
        closed.push(id);
    }

    /// 子ノード一覧を取得
    pub fn children(&self, node: MapNodeId) -> Vec<MapNodeId> {
        self.children_internal(node)
    }

    /// 子ノード一覧を取得(内部用)
    fn children_internal(&self, node: MapNodeId) -> Vec<MapNodeId> {
        self.edges
            .values()
            .filter(|e| e.from == node && e.to.is_some())
            .filter_map(|e| e.to)
            .collect()
    }

    /// 上方向カスケード: 全子が is_closed() なら親を Close(再帰)
    ///
    /// 戻り値は Close されたノード ID のリスト。
    pub fn cascade_up_if_all_closed(&mut self, id: MapNodeId) -> Vec<MapNodeId> {
        let mut closed = Vec::new();
        self.cascade_up_recursive(id, &mut closed);
        closed
    }

    fn cascade_up_recursive(&mut self, id: MapNodeId, closed: &mut Vec<MapNodeId>) {
        let parent = self.parent_internal(id);
        if let Some(parent_id) = parent {
            let all_children_closed = self.children_internal(parent_id).iter().all(|&child| {
                self.nodes
                    .get(&child)
                    .map(|n| n.state.is_closed())
                    .unwrap_or(true)
            });

            if all_children_closed {
                self.set_state(parent_id, S::closed());
                closed.push(parent_id);
                self.cascade_up_recursive(parent_id, closed);
            }
        }
    }

    /// 親ノードを取得
    pub fn parent(&self, node: MapNodeId) -> Option<MapNodeId> {
        self.parent_internal(node)
    }

    /// 親ノードを取得(内部用)
    fn parent_internal(&self, node: MapNodeId) -> Option<MapNodeId> {
        self.nodes
            .get(&node)
            .and_then(|n| n.parent_edge)
            .and_then(|edge_id| self.edges.get(&edge_id))
            .map(|e| e.from)
    }

    /// 状態変更 + 上方向カスケード
    ///
    /// ノードを Close した後、親が Close 可能ならカスケード。
    /// 戻り値は Close されたノード ID のリスト(自身含む)。
    pub fn close_with_cascade_up(&mut self, id: MapNodeId) -> Vec<MapNodeId> {
        let mut closed = Vec::new();

        if self.nodes.contains_key(&id) {
            self.set_state(id, S::closed());
            closed.push(id);
            closed.extend(self.cascade_up_if_all_closed(id));
        }

        closed
    }

    // ========================================================================
    // Query Operations
    // ========================================================================

    /// 複数ノードを一括取得
    ///
    /// 存在しない ID はスキップされる。
    /// 順序は入力の順序を保持。
    pub fn get_nodes(&self, ids: &[MapNodeId]) -> Vec<&MapNode<N, S>> {
        ids.iter().filter_map(|id| self.nodes.get(id)).collect()
    }

    /// 複数ノードのデータを一括取得
    ///
    /// 存在しない ID はスキップされる。
    /// ノード全体ではなくデータ部分のみが必要な場合に使用。
    pub fn get_node_data(&self, ids: &[MapNodeId]) -> Vec<&N> {
        ids.iter()
            .filter_map(|id| self.nodes.get(id).map(|n| &n.data))
            .collect()
    }

    /// 展開可能なノード一覧(= expandables)
    pub fn expandables(&self) -> impl Iterator<Item = MapNodeId> + '_ {
        self.expandables.iter().copied()
    }

    /// 展開可能なノード数
    pub fn expandables_count(&self) -> usize {
        self.expandables.len()
    }

    /// Closed なノード一覧
    pub fn closed_nodes(&self) -> Vec<MapNodeId> {
        self.nodes
            .values()
            .filter(|n| n.state.is_closed())
            .map(|n| n.id)
            .collect()
    }

    /// 作業中のノード一覧(!is_expandable && !is_closed)
    ///
    /// フロンティアでも終了でもない中間状態のノード。
    /// 例: Processing, Pending など。
    pub fn working_nodes(&self) -> Vec<MapNodeId> {
        self.nodes
            .values()
            .filter(|n| !n.state.is_expandable() && !n.state.is_closed())
            .map(|n| n.id)
            .collect()
    }
}

// ============================================================================
// GraphMap Update Types
// ============================================================================

/// GraphMap の更新入力
#[derive(Debug, Clone)]
pub enum GraphMapUpdate<N, E, S: MapState> {
    /// 子ノードを追加
    AddChild {
        /// 親ノード
        parent: MapNodeId,
        /// エッジデータ
        edge_data: E,
        /// 新しいノードのデータ
        node_data: N,
        /// 新しいノードの状態
        node_state: S,
        /// 重複チェック用キー
        dedup_key: String,
    },
    /// 状態変更
    SetState {
        /// 対象ノード
        node_id: MapNodeId,
        /// 新しい状態
        state: S,
    },
    /// 何もしない
    Noop,
}

// ============================================================================
// ExplorationMap impl for GraphMap
// ============================================================================

impl<N, E, S> ExplorationMap for GraphMap<N, E, S>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState,
{
    type Node = MapNode<N, S>;
    type Edge = MapEdge<E>;
    type Update = GraphMapUpdate<N, E, S>;
    type Result = MapApplyResult<N>;

    fn apply(&mut self, update: Self::Update) -> Self::Result {
        match update {
            GraphMapUpdate::AddChild {
                parent,
                edge_data,
                node_data,
                node_state,
                dedup_key,
            } => {
                // 重複チェック
                if self.contains_key(&dedup_key) {
                    return MapApplyResult::Ignored;
                }

                // 親ノードが存在するか確認
                let parent_depth = match self.nodes.get(&parent) {
                    Some(node) => node.depth,
                    None => {
                        return MapApplyResult::Failed {
                            node_id: parent,
                            can_retry: false,
                            reason: "Parent node not found".to_string(),
                        }
                    }
                };

                // エッジを作成
                let edge_id = self.add_edge(parent, edge_data);

                // 新しいノードを作成
                let new_node_id =
                    self.add_node(node_data.clone(), node_state, edge_id, parent_depth + 1);

                // エッジを成功としてマーク
                if let Some(edge) = self.edges.get_mut(&edge_id) {
                    edge.mark_success(new_node_id);
                }

                // インデックスに登録
                self.index_node(new_node_id, |_| dedup_key);

                MapApplyResult::NodeCreated {
                    node_id: new_node_id,
                    data: node_data,
                }
            }

            GraphMapUpdate::SetState { node_id, state } => {
                self.set_state(node_id, state);
                MapApplyResult::NodeUpdated { node_id }
            }

            GraphMapUpdate::Noop => MapApplyResult::Ignored,
        }
    }

    fn get(&self, id: MapNodeId) -> Option<&Self::Node> {
        self.nodes.get(&id)
    }

    fn get_mut(&mut self, id: MapNodeId) -> Option<&mut Self::Node> {
        self.nodes.get_mut(&id)
    }

    fn node_count(&self) -> usize {
        self.nodes.len()
    }

    fn frontiers(&self) -> Vec<MapNodeId> {
        self.expandables.iter().copied().collect()
    }
}

// ============================================================================
// GraphExplorationMap impl for GraphMap
// ============================================================================

impl<N, E, S> GraphExplorationMap for GraphMap<N, E, S>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState,
{
    fn get_edge(&self, id: MapEdgeId) -> Option<&Self::Edge> {
        self.edges.get(&id)
    }

    fn outgoing_edges(&self, node: MapNodeId) -> Vec<MapEdgeId> {
        self.edges
            .values()
            .filter(|e| e.from == node)
            .map(|e| e.id)
            .collect()
    }

    fn incoming_edge(&self, node: MapNodeId) -> Option<MapEdgeId> {
        self.nodes.get(&node).and_then(|n| n.parent_edge)
    }

    fn edge_count(&self) -> usize {
        self.edges.len()
    }

    fn root(&self) -> Option<MapNodeId> {
        self.root
    }
}

// ============================================================================
// HierarchicalMap impl for GraphMap
// ============================================================================

impl<N, E, S> HierarchicalMap for GraphMap<N, E, S>
where
    N: Debug + Clone,
    E: Debug + Clone,
    S: MapState,
{
    fn parent(&self, node: MapNodeId) -> Option<MapNodeId> {
        self.nodes
            .get(&node)
            .and_then(|n| n.parent_edge)
            .and_then(|edge_id| self.edges.get(&edge_id))
            .map(|e| e.from)
    }

    fn children(&self, node: MapNodeId) -> Vec<MapNodeId> {
        self.edges
            .values()
            .filter(|e| e.from == node && e.to.is_some())
            .filter_map(|e| e.to)
            .collect()
    }

    fn depth(&self, node: MapNodeId) -> u32 {
        self.nodes.get(&node).map(|n| n.depth).unwrap_or(0)
    }
}

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

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

    #[test]
    fn test_map_node_state() {
        assert!(MapNodeState::Open.is_open());
        assert!(!MapNodeState::Open.is_closed());
        assert!(!MapNodeState::Closed.is_open());
        assert!(MapNodeState::Closed.is_closed());
    }

    #[test]
    fn test_map_node_builder() {
        // MapNode::new は (id, data, state) の3引数
        let node = MapNode::new(MapNodeId(1), "task-1", MapNodeState::Open).with_depth(2);

        assert_eq!(node.id, MapNodeId(1));
        assert_eq!(node.data, "task-1");
        assert_eq!(node.state, MapNodeState::Open);
        assert_eq!(node.depth, 2);
        assert!(node.parent_edge.is_none()); // ルートなので親エッジなし
    }

    #[test]
    fn test_map_node_with_parent() {
        // 親エッジ付きノード
        let node = MapNode::new(MapNodeId(2), "child", MapNodeState::Open)
            .with_parent(MapEdgeId(0))
            .with_depth(1);

        assert_eq!(node.depth, 1);
        assert_eq!(node.parent_edge, Some(MapEdgeId(0)));
    }

    #[test]
    fn test_map_edge() {
        let mut edge = MapEdge::new(MapEdgeId(1), MapNodeId(0), "action-1");
        assert!(!edge.succeeded);
        assert_eq!(edge.attempts, 0);

        edge.mark_success(MapNodeId(1));
        assert!(edge.succeeded);
        assert_eq!(edge.attempts, 1);
        assert_eq!(edge.to, Some(MapNodeId(1)));
    }

    // ========================================================================
    // GraphMap Tests
    // ========================================================================

    #[test]
    fn test_graph_map_create_root() {
        // GraphMap<N, E, S> - 3つのジェネリック引数が必要
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Open);

        assert_eq!(map.node_count(), 1);
        assert_eq!(map.frontiers().len(), 1);
        assert_eq!(map.root(), Some(root));

        let node = map.get(root).unwrap();
        assert_eq!(node.data, "root");
        assert_eq!(node.state, MapNodeState::Open);
        assert_eq!(node.depth, 0);
        assert!(node.parent_edge.is_none()); // ルートは親エッジなし
    }

    #[test]
    fn test_graph_map_create_root_closed() {
        // Closed 状態でルートを作成した場合、frontiers には含まれない
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Closed);

        assert_eq!(map.node_count(), 1);
        assert!(map.frontiers().is_empty()); // Closed なのでフロンティアに含まれない
        assert_eq!(map.root(), Some(root));
    }

    /// AddChild で子ノードが追加されることを検証
    ///
    /// マップの責務:
    /// - 子ノードが作成される
    /// - エッジが作成される
    /// - 深さが親+1 になる
    /// - 親エッジが設定される
    /// - 状態に応じて frontiers に含まれる
    #[test]
    fn test_graph_map_apply_add_child() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Open);

        // AddChild で子ノードを追加
        let update = GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "action-1".to_string(),
            node_data: "child-1".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "child-1".to_string(),
        };
        let result = map.apply(update);

        // 結果を確認
        match result {
            MapApplyResult::NodeCreated { node_id, data } => {
                assert_eq!(data, "child-1");

                let node = map.get(node_id).unwrap();
                assert_eq!(node.depth, 1); // 親の深さ + 1
                assert!(node.parent_edge.is_some()); // 親エッジあり
                assert_eq!(node.state, MapNodeState::Open);
            }
            _ => panic!("Expected NodeCreated, got {:?}", result),
        }

        // マップ状態を確認
        assert_eq!(map.node_count(), 2); // root + child
        assert_eq!(map.edge_count(), 1); // 1本のエッジ

        // 両方 Open なので frontiers に含まれる
        assert_eq!(map.frontiers().len(), 2);

        // 注意: マップは親を自動的に Close しない
        // それは上位レイヤーの責務
        let root_node = map.get(root).unwrap();
        assert_eq!(root_node.state, MapNodeState::Open);
    }

    /// 存在しない親に AddChild した場合、Failed が返る
    #[test]
    fn test_graph_map_add_child_parent_not_found() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        // ルートを作らずに、存在しない親を指定

        let update = GraphMapUpdate::AddChild {
            parent: MapNodeId(999), // 存在しない
            edge_data: "action".to_string(),
            node_data: "child".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "child".to_string(),
        };
        let result = map.apply(update);

        match result {
            MapApplyResult::Failed {
                node_id, reason, ..
            } => {
                assert_eq!(node_id, MapNodeId(999));
                assert!(reason.contains("not found"));
            }
            _ => panic!("Expected Failed, got {:?}", result),
        }

        // ノードもエッジも作成されない
        assert_eq!(map.node_count(), 0);
        assert_eq!(map.edge_count(), 0);
    }

    /// 重複キーで AddChild した場合、Ignored が返る
    #[test]
    fn test_graph_map_add_child_duplicate_key() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Open);

        // 1回目: 成功
        let update1 = GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "action-1".to_string(),
            node_data: "child".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "unique-key".to_string(),
        };
        let result1 = map.apply(update1);
        assert!(matches!(result1, MapApplyResult::NodeCreated { .. }));

        // 2回目: 同じキーで追加 → Ignored
        let update2 = GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "action-2".to_string(),
            node_data: "child-different-data".to_string(), // データは違う
            node_state: MapNodeState::Open,
            dedup_key: "unique-key".to_string(), // キーが同じ
        };
        let result2 = map.apply(update2);
        assert!(matches!(result2, MapApplyResult::Ignored));

        // ノードは2つのまま(root + child)
        assert_eq!(map.node_count(), 2);
        // エッジも1つのまま
        assert_eq!(map.edge_count(), 1);
    }

    /// SetState で状態が変わり、frontiers が更新されることを検証
    ///
    /// マップの責務:
    /// - 状態が変わる
    /// - Open → Closed で frontiers から除外される
    /// - Closed → Open で frontiers に追加される
    #[test]
    fn test_graph_map_apply_set_state() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Open);

        // 子ノードを追加
        let update = GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "action-1".to_string(),
            node_data: "child".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "child".to_string(),
        };
        let child = match map.apply(update) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            _ => panic!("Expected NodeCreated"),
        };

        // 初期状態: 両方 Open → frontiers に2つ
        assert_eq!(map.frontiers().len(), 2);

        // child を Closed に変更
        let update = GraphMapUpdate::SetState {
            node_id: child,
            state: MapNodeState::Closed,
        };
        let result = map.apply(update);

        // 結果確認
        assert!(matches!(result, MapApplyResult::NodeUpdated { .. }));

        // child は Closed になった
        let child_node = map.get(child).unwrap();
        assert_eq!(child_node.state, MapNodeState::Closed);

        // frontiers から除外された
        assert_eq!(map.frontiers().len(), 1);
        assert!(map.frontiers().contains(&root));
        assert!(!map.frontiers().contains(&child));
    }

    /// SetState で Closed → Open に戻せることを検証
    #[test]
    fn test_graph_map_set_state_reopen() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Closed);

        // 初期状態: Closed → frontiers は空
        assert!(map.frontiers().is_empty());

        // Open に変更
        let update = GraphMapUpdate::SetState {
            node_id: root,
            state: MapNodeState::Open,
        };
        map.apply(update);

        // frontiers に追加された
        assert_eq!(map.frontiers().len(), 1);
        assert!(map.frontiers().contains(&root));
    }

    /// 階層構造(親子関係、深さ)が正しく維持されることを検証
    #[test]
    fn test_graph_map_hierarchical() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("root".to_string(), MapNodeState::Open);

        // 2段階のノードを作成: root → node1 → node2
        let node1 = match map.apply(GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "edge-1".to_string(),
            node_data: "node-1".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "node-1".to_string(),
        }) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            r => panic!("Expected NodeCreated, got {:?}", r),
        };

        let node2 = match map.apply(GraphMapUpdate::AddChild {
            parent: node1,
            edge_data: "edge-2".to_string(),
            node_data: "node-2".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "node-2".to_string(),
        }) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            r => panic!("Expected NodeCreated, got {:?}", r),
        };

        // 親子関係を確認
        assert_eq!(map.parent(node1), Some(root));
        assert_eq!(map.parent(node2), Some(node1));
        assert_eq!(map.parent(root), None); // ルートは親なし

        // 子ノードを確認
        assert_eq!(map.children(root), vec![node1]);
        assert_eq!(map.children(node1), vec![node2]);
        assert!(map.children(node2).is_empty()); // 葉ノード

        // 深さを確認
        assert_eq!(map.depth(root), 0);
        assert_eq!(map.depth(node1), 1);
        assert_eq!(map.depth(node2), 2);
    }

    // ========================================================================
    // Search API Tests (B)
    // ========================================================================

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

        // 子ノードを作成
        let target_id = match map.apply(GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "edge".to_string(),
            node_data: "target".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "target".to_string(),
        }) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            r => panic!("Expected NodeCreated, got {:?}", r),
        };

        // 条件で検索
        let found = map.find_node(|n| n.data == "target");
        assert_eq!(found, Some(target_id));

        // 存在しないものは None
        let not_found = map.find_node(|n| n.data == "nonexistent");
        assert!(not_found.is_none());
    }

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

        // 複数ノードを作成
        let id1 = match map.apply(GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "edge-1".to_string(),
            node_data: "match-1".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "match-1".to_string(),
        }) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            r => panic!("Expected NodeCreated, got {:?}", r),
        };

        let id2 = match map.apply(GraphMapUpdate::AddChild {
            parent: id1,
            edge_data: "edge-2".to_string(),
            node_data: "match-2".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "match-2".to_string(),
        }) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            r => panic!("Expected NodeCreated, got {:?}", r),
        };

        // "match" で始まるものを検索
        let found = map.find_nodes(|n| n.data.starts_with("match"));
        assert_eq!(found.len(), 2);
        assert!(found.contains(&id1));
        assert!(found.contains(&id2));
    }

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

        let found = map.find_by_data(&"root".to_string());
        assert_eq!(found, Some(root));

        let not_found = map.find_by_data(&"nonexistent".to_string());
        assert!(not_found.is_none());
    }

    // ========================================================================
    // Index API Tests (D)
    // ========================================================================

    #[test]
    fn test_index_basic() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("file:auth.rs".to_string(), MapNodeState::Open);

        // インデックスに登録
        map.index_node(root, |data| data.clone());

        // キーで検索
        let found = map.get_by_key(&"file:auth.rs".to_string());
        assert_eq!(found, Some(root));

        // 存在しないキー
        let not_found = map.get_by_key(&"file:other.rs".to_string());
        assert!(not_found.is_none());
    }

    #[test]
    fn test_contains_key() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map.create_root("task-1".to_string(), MapNodeState::Open);
        map.index_node(root, |data| data.clone());

        assert!(map.contains_key(&"task-1".to_string()));
        assert!(!map.contains_key(&"task-2".to_string()));
    }

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

        let child = match map.apply(GraphMapUpdate::AddChild {
            parent: root,
            edge_data: "edge".to_string(),
            node_data: "child".to_string(),
            node_state: MapNodeState::Open,
            dedup_key: "child".to_string(),
        }) {
            MapApplyResult::NodeCreated { node_id, .. } => node_id,
            r => panic!("Expected NodeCreated, got {:?}", r),
        };

        // インデックスを再構築
        map.rebuild_index(|data| data.clone());

        // 両方検索できる
        assert_eq!(map.get_by_key(&"root".to_string()), Some(root));
        assert_eq!(map.get_by_key(&"child".to_string()), Some(child));
    }

    // ========================================================================
    // Add with Dedup Tests
    // ========================================================================

    #[test]
    fn test_create_root_if_absent() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();

        // 最初の追加
        let result1 =
            map.create_root_if_absent("task-1".to_string(), MapNodeState::Open, |d| d.clone());
        assert!(result1.is_added());
        let id1 = result1.into_inner();

        // 同じキーで追加しようとすると AlreadyExists
        let result2 =
            map.create_root_if_absent("task-1".to_string(), MapNodeState::Open, |d| d.clone());
        assert!(result2.is_already_exists());
        assert_eq!(result2.into_inner(), id1);

        // 違うキーは追加できる
        let result3 =
            map.create_root_if_absent("task-2".to_string(), MapNodeState::Open, |d| d.clone());
        assert!(result3.is_added());
        assert_ne!(result3.into_inner(), id1);
    }

    #[test]
    fn test_add_child_if_absent() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map
            .create_root_if_absent("root".to_string(), MapNodeState::Open, |d| d.clone())
            .into_inner();

        // 子ノードを追加
        let result1 = map
            .add_child_if_absent(
                root,
                "edge-1".to_string(),
                "child-1".to_string(),
                MapNodeState::Open,
                |d| d.clone(),
            )
            .unwrap();
        assert!(result1.is_added());
        let child1 = result1.into_inner();

        // 同じキーで追加しようとすると AlreadyExists
        let result2 = map
            .add_child_if_absent(
                root,
                "edge-2".to_string(),
                "child-1".to_string(),
                MapNodeState::Open,
                |d| d.clone(),
            )
            .unwrap();
        assert!(result2.is_already_exists());
        assert_eq!(result2.into_inner(), child1);

        // 違うキーは追加できる
        let result3 = map
            .add_child_if_absent(
                root,
                "edge-3".to_string(),
                "child-2".to_string(),
                MapNodeState::Open,
                |d| d.clone(),
            )
            .unwrap();
        assert!(result3.is_added());
    }

    #[test]
    fn test_add_child_if_absent_parent_not_found() {
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();

        // 存在しない親に追加しようとするとエラー
        let result = map.add_child_if_absent(
            MapNodeId(999),
            "edge".to_string(),
            "child".to_string(),
            MapNodeState::Open,
            |d| d.clone(),
        );
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), MapError::ParentNotFound(_)));
    }

    #[test]
    fn test_dedup_prevents_infinite_loop() {
        // シナリオ: Grep で同じファイルが繰り返し発見される
        let mut map: GraphMap<String, String, MapNodeState> = GraphMap::new();
        let root = map
            .create_root_if_absent("search:auth".to_string(), MapNodeState::Open, |d| d.clone())
            .into_inner();

        // Worker A: auth.rs を発見
        let result_a = map.add_child_if_absent(
            root,
            "grep".to_string(),
            "file:auth.rs".to_string(),
            MapNodeState::Open,
            |d| d.clone(),
        );
        assert!(result_a.unwrap().is_added());

        // Worker B: 同じ auth.rs を発見(重複追加されない)
        let result_b = map.add_child_if_absent(
            root,
            "grep".to_string(),
            "file:auth.rs".to_string(),
            MapNodeState::Open,
            |d| d.clone(),
        );
        assert!(result_b.unwrap().is_already_exists());

        // Worker C: 別のファイル user.rs を発見
        let result_c = map.add_child_if_absent(
            root,
            "grep".to_string(),
            "file:user.rs".to_string(),
            MapNodeState::Open,
            |d| d.clone(),
        );
        assert!(result_c.unwrap().is_added());

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

    #[test]
    fn test_add_result_methods() {
        let added: AddResult<i32> = AddResult::Added(42);
        assert!(added.is_added());
        assert!(!added.is_already_exists());
        assert_eq!(*added.as_inner(), 42);
        assert_eq!(added.into_inner(), 42);

        let exists: AddResult<i32> = AddResult::AlreadyExists(42);
        assert!(!exists.is_added());
        assert!(exists.is_already_exists());
        assert_eq!(*exists.as_inner(), 42);
        assert_eq!(exists.into_inner(), 42);
    }
}