vibe-graph-core 0.2.5

Core domain model for the Vibe-Graph neural OS
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
//! Core domain types shared across the entire Vibe-Graph workspace.

use petgraph::stable_graph::{NodeIndex, StableDiGraph};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

// Use web-time for WASM (std::time::Instant panics in WASM)
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[cfg(target_arch = "wasm32")]
use web_time::Instant;

// =============================================================================
// Git Change Tracking Types
// =============================================================================

/// Type of change detected for a file in git.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GitChangeKind {
    /// File was modified (content changed)
    Modified,
    /// File was newly added (staged new file)
    Added,
    /// File was deleted
    Deleted,
    /// File was renamed (old path)
    RenamedFrom,
    /// File was renamed (new path)
    RenamedTo,
    /// File is untracked (new file not yet staged)
    Untracked,
}

impl GitChangeKind {
    /// Get a display label for the change kind.
    pub fn label(&self) -> &'static str {
        match self {
            GitChangeKind::Modified => "Modified",
            GitChangeKind::Added => "Added",
            GitChangeKind::Deleted => "Deleted",
            GitChangeKind::RenamedFrom => "Renamed (from)",
            GitChangeKind::RenamedTo => "Renamed (to)",
            GitChangeKind::Untracked => "Untracked",
        }
    }

    /// Get a short symbol for the change kind.
    pub fn symbol(&self) -> &'static str {
        match self {
            GitChangeKind::Modified => "M",
            GitChangeKind::Added => "+",
            GitChangeKind::Deleted => "-",
            GitChangeKind::RenamedFrom => "R←",
            GitChangeKind::RenamedTo => "R→",
            GitChangeKind::Untracked => "?",
        }
    }
}

/// Represents a single file change detected in git.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitFileChange {
    /// Relative path of the changed file.
    pub path: PathBuf,
    /// Kind of change.
    pub kind: GitChangeKind,
    /// Whether this is a staged change (vs working directory).
    pub staged: bool,
}

/// Snapshot of git changes for an entire repository.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GitChangeSnapshot {
    /// All detected changes.
    pub changes: Vec<GitFileChange>,
    /// Timestamp when this snapshot was taken.
    #[serde(skip)]
    pub captured_at: Option<Instant>,
}

impl GitChangeSnapshot {
    /// Create a new empty snapshot.
    pub fn new() -> Self {
        Self {
            changes: Vec::new(),
            captured_at: Some(Instant::now()),
        }
    }

    /// Check if a path has any changes.
    pub fn has_changes(&self, path: &Path) -> bool {
        self.changes.iter().any(|c| c.path == path)
    }

    /// Get the change kind for a path, if any.
    pub fn get_change(&self, path: &Path) -> Option<&GitFileChange> {
        self.changes.iter().find(|c| c.path == path)
    }

    /// Get all paths that have changes.
    pub fn changed_paths(&self) -> impl Iterator<Item = &Path> {
        self.changes.iter().map(|c| c.path.as_path())
    }

    /// Count changes by kind.
    pub fn count_by_kind(&self, kind: GitChangeKind) -> usize {
        self.changes.iter().filter(|c| c.kind == kind).count()
    }

    /// Check if snapshot is stale (older than given duration).
    pub fn is_stale(&self, max_age: Duration) -> bool {
        match self.captured_at {
            Some(at) => at.elapsed() > max_age,
            None => true,
        }
    }

    /// Get age of this snapshot.
    pub fn age(&self) -> Option<Duration> {
        self.captured_at.map(|at| at.elapsed())
    }
}

/// State for animating change indicators.
#[derive(Debug, Clone)]
pub struct ChangeIndicatorState {
    /// Animation phase (0.0 to 1.0, loops).
    pub phase: f32,
    /// Animation speed multiplier.
    pub speed: f32,
    /// Whether animation is enabled.
    pub enabled: bool,
}

impl Default for ChangeIndicatorState {
    fn default() -> Self {
        Self {
            phase: 0.0,
            speed: 1.0,
            enabled: true,
        }
    }
}

impl ChangeIndicatorState {
    /// Advance the animation by delta time.
    pub fn tick(&mut self, dt: f32) {
        if self.enabled {
            self.phase = (self.phase + dt * self.speed) % 1.0;
        }
    }

    /// Get the current pulse scale (1.0 to 1.3).
    pub fn pulse_scale(&self) -> f32 {
        // Smooth sine-based pulse
        let t = self.phase * std::f32::consts::TAU;
        1.0 + 0.15 * (t.sin() * 0.5 + 0.5)
    }

    /// Get the current alpha for outer ring (fades in/out).
    pub fn ring_alpha(&self) -> f32 {
        let t = self.phase * std::f32::consts::TAU;
        0.3 + 0.4 * (t.sin() * 0.5 + 0.5)
    }
}

/// Identifier for nodes within the `SourceCodeGraph`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeId(pub u64);

/// Identifier for edges within the `SourceCodeGraph`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EdgeId(pub u64);

/// Enumerates the kinds of nodes that can populate the `SourceCodeGraph`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum GraphNodeKind {
    /// A logical module, typically aligned to a crate or package.
    Module,
    /// A discrete file in the repository.
    File,
    /// Directory or folder that contains additional nodes.
    Directory,
    /// A long-running service entry point.
    Service,
    /// Automated test suites or harnesses.
    Test,
    /// Any other kind that does not fit the curated list.
    #[default]
    Other,
}

/// Captures metadata for a node in the graph.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct GraphNode {
    /// Unique identifier for this node.
    pub id: NodeId,
    /// Human readable name.
    pub name: String,
    /// Category associated with the node.
    pub kind: GraphNodeKind,
    /// Arbitrary metadata, e.g. language, path, ownership.
    pub metadata: HashMap<String, String>,
}

/// Represents connections between graph nodes.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct GraphEdge {
    /// Unique identifier for this edge.
    pub id: EdgeId,
    /// Originating node identifier.
    pub from: NodeId,
    /// Destination node identifier.
    pub to: NodeId,
    /// Description of the relationship ("imports", "calls", etc.).
    pub relationship: String,
    /// Arbitrary metadata for the relationship.
    pub metadata: HashMap<String, String>,
}

/// Aggregate graph describing the full software project topology.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct SourceCodeGraph {
    /// All nodes that make up the graph.
    pub nodes: Vec<GraphNode>,
    /// All edges that connect nodes in the graph.
    pub edges: Vec<GraphEdge>,
    /// Arbitrary metadata about the entire graph snapshot.
    pub metadata: HashMap<String, String>,
}

impl SourceCodeGraph {
    /// Creates an empty graph with no nodes or edges.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Returns the number of nodes currently tracked.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Returns the number of edges currently tracked.
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// Convert to petgraph StableDiGraph for visualization/analysis.
    /// Returns the graph and a mapping from NodeIndex to NodeId.
    pub fn to_petgraph(&self) -> (StableDiGraph<GraphNode, String>, HashMap<NodeId, NodeIndex>) {
        let mut graph = StableDiGraph::new();
        let mut id_to_index = HashMap::new();

        // Add all nodes
        for node in &self.nodes {
            let idx = graph.add_node(node.clone());
            id_to_index.insert(node.id, idx);
        }

        // Add all edges
        for edge in &self.edges {
            if let (Some(&from_idx), Some(&to_idx)) =
                (id_to_index.get(&edge.from), id_to_index.get(&edge.to))
            {
                graph.add_edge(from_idx, to_idx, edge.relationship.clone());
            }
        }

        (graph, id_to_index)
    }
}

/// Types of references detected between source files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReferenceKind {
    /// Rust `use` statement
    Uses,
    /// Python/JS/TS `import` statement
    Imports,
    /// Trait or interface implementation
    Implements,
    /// Filesystem hierarchy (parent->child)
    Contains,
}

impl std::fmt::Display for ReferenceKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReferenceKind::Uses => write!(f, "uses"),
            ReferenceKind::Imports => write!(f, "imports"),
            ReferenceKind::Implements => write!(f, "implements"),
            ReferenceKind::Contains => write!(f, "contains"),
        }
    }
}

/// A detected reference from one source to another.
#[derive(Debug, Clone)]
pub struct SourceReference {
    /// Path of the source file containing the reference
    pub source_path: PathBuf,
    /// Type of reference
    pub kind: ReferenceKind,
    /// Target path (may be partial, resolved later)
    pub target_route: PathBuf,
}

/// Builder for constructing a `SourceCodeGraph` from project data.
#[derive(Debug, Default)]
pub struct SourceCodeGraphBuilder {
    nodes: Vec<GraphNode>,
    edges: Vec<GraphEdge>,
    path_to_node: HashMap<PathBuf, NodeId>,
    next_node_id: u64,
    next_edge_id: u64,
    metadata: HashMap<String, String>,
}

impl SourceCodeGraphBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set metadata for the graph.
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Add a directory node.
    pub fn add_directory(&mut self, path: &Path) -> NodeId {
        if let Some(&id) = self.path_to_node.get(path) {
            return id;
        }

        let id = NodeId(self.next_node_id);
        self.next_node_id += 1;

        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_else(|| path.to_str().unwrap_or("."))
            .to_string();

        let mut metadata = HashMap::new();
        metadata.insert("path".to_string(), path.to_string_lossy().to_string());

        self.nodes.push(GraphNode {
            id,
            name,
            kind: GraphNodeKind::Directory,
            metadata,
        });

        self.path_to_node.insert(path.to_path_buf(), id);
        id
    }

    /// Add a file node with optional language detection.
    pub fn add_file(&mut self, path: &Path, relative_path: &str) -> NodeId {
        if let Some(&id) = self.path_to_node.get(path) {
            return id;
        }

        let id = NodeId(self.next_node_id);
        self.next_node_id += 1;

        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_else(|| path.to_str().unwrap_or("unknown"))
            .to_string();

        // Determine kind based on extension
        let kind = match path.extension().and_then(|e| e.to_str()) {
            Some("rs") | Some("py") | Some("js") | Some("ts") | Some("tsx") | Some("jsx")
            | Some("go") | Some("java") | Some("c") | Some("cpp") | Some("h") | Some("hpp") => {
                if relative_path.contains("test") || name.starts_with("test_") {
                    GraphNodeKind::Test
                } else if name == "mod.rs"
                    || name == "__init__.py"
                    || name == "index.ts"
                    || name == "index.js"
                {
                    GraphNodeKind::Module
                } else {
                    GraphNodeKind::File
                }
            }
            _ => GraphNodeKind::File,
        };

        let mut metadata = HashMap::new();
        metadata.insert("path".to_string(), path.to_string_lossy().to_string());
        metadata.insert("relative_path".to_string(), relative_path.to_string());

        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
            metadata.insert("extension".to_string(), ext.to_string());
            metadata.insert(
                "language".to_string(),
                extension_to_language(ext).to_string(),
            );
        }

        self.nodes.push(GraphNode {
            id,
            name,
            kind,
            metadata,
        });

        self.path_to_node.insert(path.to_path_buf(), id);
        id
    }

    /// Add a hierarchy edge (parent contains child).
    pub fn add_hierarchy_edge(&mut self, parent_path: &Path, child_path: &Path) {
        if let (Some(&parent_id), Some(&child_id)) = (
            self.path_to_node.get(parent_path),
            self.path_to_node.get(child_path),
        ) {
            if parent_id != child_id {
                self.add_edge(parent_id, child_id, ReferenceKind::Contains);
            }
        }
    }

    /// Add an edge between two nodes.
    pub fn add_edge(&mut self, from: NodeId, to: NodeId, kind: ReferenceKind) {
        let id = EdgeId(self.next_edge_id);
        self.next_edge_id += 1;

        self.edges.push(GraphEdge {
            id,
            from,
            to,
            relationship: kind.to_string(),
            metadata: HashMap::new(),
        });
    }

    /// Get NodeId for a path if it exists.
    pub fn get_node_id(&self, path: &Path) -> Option<NodeId> {
        self.path_to_node.get(path).copied()
    }

    /// Find a node by matching path suffix (for reference resolution).
    pub fn find_node_by_path_suffix(&self, route: &Path) -> Option<NodeId> {
        let route_str = route.to_string_lossy();

        for (path, &node_id) in &self.path_to_node {
            let path_str = path.to_string_lossy();

            // Strategy 1: Direct suffix match
            if path_str.ends_with(route_str.as_ref()) {
                return Some(node_id);
            }

            // Strategy 2: Normalized comparison
            let normalized_path: String = path_str.trim_start_matches("./").replace('\\', "/");
            let normalized_route: String = route_str.trim_start_matches("./").replace('\\', "/");
            if normalized_path.ends_with(&normalized_route) {
                return Some(node_id);
            }

            // Strategy 3: Module path matching (e.g., core/models.rs -> src/core/models.rs)
            let route_parts: Vec<&str> = normalized_route.split('/').collect();
            let path_parts: Vec<&str> = normalized_path.split('/').collect();
            if route_parts.len() <= path_parts.len() {
                for window in path_parts.windows(route_parts.len()) {
                    if window == route_parts.as_slice() {
                        return Some(node_id);
                    }
                }
            }

            // Strategy 4: Filename match
            if let (Some(file_name), Some(route_name)) = (
                path.file_name().and_then(|n| n.to_str()),
                route.file_name().and_then(|n| n.to_str()),
            ) {
                if file_name == route_name {
                    return Some(node_id);
                }
            }
        }

        None
    }

    /// Set a metadata key on an existing node.
    pub fn set_node_metadata(
        &mut self,
        node_id: NodeId,
        key: impl Into<String>,
        value: impl Into<String>,
    ) {
        if let Some(node) = self.nodes.iter_mut().find(|n| n.id == node_id) {
            node.metadata.insert(key.into(), value.into());
        }
    }

    /// Get the current node count.
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Get the current edge count.
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// Build the final `SourceCodeGraph`.
    pub fn build(self) -> SourceCodeGraph {
        SourceCodeGraph {
            nodes: self.nodes,
            edges: self.edges,
            metadata: self.metadata,
        }
    }
}

/// Detect references in Rust source code.
pub fn detect_rust_references(content: &str, source_path: &Path) -> Vec<SourceReference> {
    let mut refs = Vec::new();

    for line in content.lines() {
        let trimmed = line.trim();

        // Handle 'mod' declarations
        if trimmed.starts_with("pub mod ") || trimmed.starts_with("mod ") {
            let mod_part = trimmed
                .strip_prefix("pub mod ")
                .or_else(|| trimmed.strip_prefix("mod "))
                .unwrap_or("")
                .split(';')
                .next()
                .unwrap_or("")
                .trim();

            if !mod_part.is_empty() && !mod_part.contains('{') {
                refs.push(SourceReference {
                    source_path: source_path.to_path_buf(),
                    kind: ReferenceKind::Uses,
                    target_route: PathBuf::from(format!("{}.rs", mod_part)),
                });
                refs.push(SourceReference {
                    source_path: source_path.to_path_buf(),
                    kind: ReferenceKind::Uses,
                    target_route: PathBuf::from(format!("{}/mod.rs", mod_part)),
                });
            }
        }

        if !trimmed.starts_with("use ") {
            continue;
        }

        // Extract module path from use statement
        let use_part = trimmed
            .strip_prefix("use ")
            .unwrap_or("")
            .split(';')
            .next()
            .unwrap_or("")
            .split('{')
            .next()
            .unwrap_or("")
            .trim();

        if use_part.is_empty() {
            continue;
        }

        // Propose everything that looks like a path.
        // The graph builder will filter out references that don't resolve to actual nodes.
        let module_path = use_part
            .strip_prefix("crate::")
            .or_else(|| use_part.strip_prefix("self::"))
            .or_else(|| use_part.strip_prefix("super::"))
            .unwrap_or(use_part);

        // Convert module path to file path
        let path_str = module_path
            .replace("::", "/")
            .trim_end_matches(|c: char| !c.is_alphanumeric() && c != '_')
            .to_string();

        refs.push(SourceReference {
            source_path: source_path.to_path_buf(),
            kind: ReferenceKind::Uses,
            target_route: PathBuf::from(format!("{}.rs", path_str)),
        });
    }

    refs
}

/// Detect references in Python source code.
pub fn detect_python_references(content: &str, source_path: &Path) -> Vec<SourceReference> {
    let mut refs = Vec::new();

    for line in content.lines() {
        let trimmed = line.trim();

        // Match "import module" statements
        if trimmed.starts_with("import ") && !trimmed.starts_with("import(") {
            let import_part = trimmed
                .strip_prefix("import ")
                .unwrap_or("")
                .split_whitespace()
                .next()
                .unwrap_or("")
                .split(',')
                .next()
                .unwrap_or("")
                .trim();

            if !import_part.is_empty() {
                let path_str = import_part.replace('.', "/");
                refs.push(SourceReference {
                    source_path: source_path.to_path_buf(),
                    kind: ReferenceKind::Imports,
                    target_route: PathBuf::from(format!("{}.py", path_str)),
                });
            }
        }

        // Match "from module import something" statements
        if let Some(module_part) = trimmed
            .strip_prefix("from ")
            .and_then(|s| s.split(" import ").next())
        {
            let module = module_part.trim();
            if !module.is_empty() && module != "." && !module.starts_with("..") {
                let path_str = module.replace('.', "/");
                refs.push(SourceReference {
                    source_path: source_path.to_path_buf(),
                    kind: ReferenceKind::Imports,
                    target_route: PathBuf::from(format!("{}.py", path_str)),
                });
            }
        }
    }

    refs
}

/// Detect references in TypeScript/JavaScript source code.
pub fn detect_ts_references(content: &str, source_path: &Path) -> Vec<SourceReference> {
    let mut refs = Vec::new();

    for line in content.lines() {
        let trimmed = line.trim();

        // Match import statements: import X from 'path' or import 'path'
        if trimmed.starts_with("import ") {
            // Extract path from quotes
            if let Some(path_start) = trimmed.find(['\'', '"']) {
                let quote_char = trimmed.chars().nth(path_start).unwrap();
                let rest = &trimmed[path_start + 1..];
                if let Some(path_end) = rest.find(quote_char) {
                    let import_path = &rest[..path_end];
                    // Only track relative imports
                    if import_path.starts_with('.') {
                        refs.push(SourceReference {
                            source_path: source_path.to_path_buf(),
                            kind: ReferenceKind::Imports,
                            target_route: PathBuf::from(import_path),
                        });
                    }
                }
            }
        }
    }

    refs
}

/// Detect references in Lean 4 source code.
///
/// Handles `import` statements (e.g. `import Mathlib.Topology.Basic`)
/// and `open` namespace declarations.
pub fn detect_lean_references(content: &str, source_path: &Path) -> Vec<SourceReference> {
    let mut refs = Vec::new();

    for line in content.lines() {
        let trimmed = line.trim();

        // Skip comments and empty lines
        if trimmed.is_empty() || trimmed.starts_with("--") || trimmed.starts_with("/-") {
            continue;
        }

        // `import Mathlib.Topology.Basic` or `public import Mathlib.Foo.Bar`
        let import_part = trimmed
            .strip_prefix("public import ")
            .or_else(|| trimmed.strip_prefix("import "));

        if let Some(module_path) = import_part {
            let module = module_path.split_whitespace().next().unwrap_or("").trim();

            if !module.is_empty() {
                let file_path = module.replace('.', "/");
                refs.push(SourceReference {
                    source_path: source_path.to_path_buf(),
                    kind: ReferenceKind::Imports,
                    target_route: PathBuf::from(format!("{}.lean", file_path)),
                });
            }
            continue;
        }

        // `open Topology Filter in` or `open Topology`
        // These represent namespace dependencies worth capturing.
        if let Some(rest) = trimmed.strip_prefix("open ") {
            let namespaces = rest.split(" in").next().unwrap_or(rest).split_whitespace();

            for ns in namespaces {
                let ns = ns.trim_end_matches(|c: char| !c.is_alphanumeric() && c != '.');
                if ns.is_empty() || ns == "scoped" {
                    continue;
                }
                let file_path = ns.replace('.', "/");
                refs.push(SourceReference {
                    source_path: source_path.to_path_buf(),
                    kind: ReferenceKind::Uses,
                    target_route: PathBuf::from(format!("{}.lean", file_path)),
                });
            }
        }
    }

    refs
}

/// Detect references based on file extension.
pub fn detect_references(content: &str, source_path: &Path) -> Vec<SourceReference> {
    match source_path.extension().and_then(|e| e.to_str()) {
        Some("rs") => detect_rust_references(content, source_path),
        Some("py") => detect_python_references(content, source_path),
        Some("ts") | Some("tsx") | Some("js") | Some("jsx") => {
            detect_ts_references(content, source_path)
        }
        Some("lean") => detect_lean_references(content, source_path),
        _ => Vec::new(),
    }
}

/// Map file extension to language name.
fn extension_to_language(ext: &str) -> &'static str {
    match ext {
        "rs" => "rust",
        "py" => "python",
        "js" => "javascript",
        "ts" => "typescript",
        "tsx" => "typescript",
        "jsx" => "javascript",
        "go" => "go",
        "java" => "java",
        "lean" => "lean",
        "c" | "h" => "c",
        "cpp" | "hpp" | "cc" | "cxx" => "cpp",
        "md" => "markdown",
        "json" => "json",
        "yaml" | "yml" => "yaml",
        "toml" => "toml",
        _ => "unknown",
    }
}

/// Represents an explicitly declared vibe (intent/spec/decision) attached to graph regions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Vibe {
    /// Stable identifier for referencing the vibe.
    pub id: String,
    /// Short title summarizing the intent.
    pub title: String,
    /// Richer description with context.
    pub description: String,
    /// Target nodes within the graph impacted by the vibe.
    pub targets: Vec<NodeId>,
    /// Actor (human or machine) responsible for the vibe.
    pub created_by: String,
    /// Timestamp when the vibe entered the system.
    pub created_at: SystemTime,
    /// Optional tags or attributes.
    pub metadata: HashMap<String, String>,
}

/// Canonical definition of governing rules in effect for a graph.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Constitution {
    /// Unique name of the constitution.
    pub name: String,
    /// Semantic version or revision identifier.
    pub version: String,
    /// Human-readable description of the guardrails.
    pub description: String,
    /// Simple list of policies; future versions may embed richer data.
    pub policies: Vec<String>,
}

/// Generic payload that cells in the automaton can store.
pub type StatePayload = Value;

/// Captures the state of an individual cell in the LLM cellular automaton.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CellState {
    /// Node the cell is associated with.
    pub node_id: NodeId,
    /// Arbitrary structured state payload.
    pub payload: StatePayload,
    /// Tracking field for energy, confidence, or strength indicators.
    pub activation: f32,
    /// Timestamp for the most recent update.
    pub last_updated: SystemTime,
    /// Free-form annotations (signals, metrics, citations, etc.).
    pub annotations: HashMap<String, String>,
}

impl CellState {
    /// Creates a fresh `CellState` wrapping the provided payload.
    pub fn new(node_id: NodeId, payload: StatePayload) -> Self {
        Self {
            node_id,
            payload,
            activation: 0.0,
            last_updated: SystemTime::now(),
            annotations: HashMap::new(),
        }
    }
}

/// Represents a snapshot of the entire system ready to be fossilized in Git.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Snapshot {
    /// Identifier suitable for referencing the snapshot in storage.
    pub id: String,
    /// Captured graph at the time of snapshot.
    pub graph: SourceCodeGraph,
    /// All vibes considered part of the snapshot.
    pub vibes: Vec<Vibe>,
    /// Cell states for the automaton corresponding to the snapshot.
    pub cell_states: Vec<CellState>,
    /// Constitution in effect when the snapshot was created.
    pub constitution: Constitution,
    /// Timestamp for when the snapshot was recorded.
    pub created_at: SystemTime,
}

/// Strategies for mapping a logical graph to a filesystem hierarchy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum LayoutStrategy {
    /// Everything in one directory (flat).
    #[default]
    Flat,
    /// Spatial organization for lattice-like graphs (rows/cols).
    Lattice { width: usize, group_by_row: bool },
    /// Direct mapping (trusts existing paths or uses heuristics).
    Direct,
    /// Preserves existing directory structure (Identity).
    Preserve,
    /// Modular clustering (auto-detected modules).
    Modular,
}

// =============================================================================
// Sampler Abstraction
// =============================================================================
//
// A Sampler generalizes the pattern of:  Select(nodes) → Compute(local_fn) → Emit(artifact)
//
// Existing operations (automaton Rules, impact_analysis, evolution planning)
// are all special cases. The Sampler trait makes the pattern explicit, composable,
// and reusable across native and WASM targets.

/// Local context provided to a [`Sampler`] during computation.
///
/// Gathers everything known about a single node at the time of sampling:
/// structural position, optional content, previously-computed annotations,
/// and the edges connecting it to its neighbors.
#[derive(Debug, Clone)]
pub struct SampleContext<'a> {
    /// The node being sampled.
    pub node: &'a GraphNode,
    /// Direct neighbors (both incoming and outgoing edges resolved to nodes).
    pub neighbors: Vec<NeighborRef<'a>>,
    /// Source file content, when available and requested.
    pub content: Option<&'a str>,
    /// Previously-computed artifacts attached to this node (keyed by sampler id).
    /// Enables sampler composition: earlier samplers deposit artifacts that
    /// later samplers can read.
    pub annotations: &'a HashMap<String, Value>,
    /// Graph-level metadata (project name, workspace root, etc.).
    pub graph_metadata: &'a HashMap<String, String>,
}

/// A neighbor node together with the edge that connects it.
#[derive(Debug, Clone)]
pub struct NeighborRef<'a> {
    /// The neighboring node.
    pub node: &'a GraphNode,
    /// The connecting edge (direction implied by the edge's from/to fields).
    pub edge: &'a GraphEdge,
}

/// Typed output produced by a sampler for one node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SampleArtifact {
    /// Which node this artifact belongs to.
    pub node_id: NodeId,
    /// Structured payload (schema depends on the sampler).
    pub value: Value,
}

/// Collected output of a full sampling pass.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SampleResult {
    /// Identifier of the sampler that produced these artifacts.
    pub sampler_id: String,
    /// Per-node artifacts, ordered by the sampler's iteration order.
    pub artifacts: Vec<SampleArtifact>,
    /// Aggregate / summary metadata for the entire pass.
    pub metadata: HashMap<String, Value>,
}

impl SampleResult {
    /// Look up the artifact for a specific node.
    pub fn get(&self, node_id: NodeId) -> Option<&SampleArtifact> {
        self.artifacts.iter().find(|a| a.node_id == node_id)
    }

    /// Number of artifacts produced.
    pub fn len(&self) -> usize {
        self.artifacts.len()
    }

    /// Whether no artifacts were produced.
    pub fn is_empty(&self) -> bool {
        self.artifacts.is_empty()
    }

    /// Iterate over (NodeId, &Value) pairs.
    pub fn iter(&self) -> impl Iterator<Item = (NodeId, &Value)> {
        self.artifacts.iter().map(|a| (a.node_id, &a.value))
    }
}

/// Determines which nodes a sampler should operate on.
#[derive(Default)]
pub enum NodeSelector {
    /// Sample every node in the graph.
    #[default]
    All,
    /// Only nodes whose kind matches.
    ByKind(GraphNodeKind),
    /// Only nodes with these specific IDs.
    Explicit(Vec<NodeId>),
    /// Only nodes whose metadata contains the given key.
    HasMetadata(String),
    /// Custom predicate (not serializable — use for in-process composition).
    Predicate(Box<dyn Fn(&GraphNode) -> bool + Send + Sync>),
}

impl std::fmt::Debug for NodeSelector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NodeSelector::All => write!(f, "All"),
            NodeSelector::ByKind(k) => write!(f, "ByKind({:?})", k),
            NodeSelector::Explicit(ids) => write!(f, "Explicit({:?})", ids),
            NodeSelector::HasMetadata(key) => write!(f, "HasMetadata({:?})", key),
            NodeSelector::Predicate(_) => write!(f, "Predicate(<fn>)"),
        }
    }
}

impl NodeSelector {
    /// Test whether a node passes this selector.
    pub fn matches(&self, node: &GraphNode) -> bool {
        match self {
            NodeSelector::All => true,
            NodeSelector::ByKind(kind) => node.kind == *kind,
            NodeSelector::Explicit(ids) => ids.contains(&node.id),
            NodeSelector::HasMetadata(key) => node.metadata.contains_key(key),
            NodeSelector::Predicate(f) => f(node),
        }
    }
}

/// Per-node annotation map produced and consumed by [`Sampler`] stages.
pub type AnnotationMap = HashMap<NodeId, HashMap<String, Value>>;

/// The core sampling primitive.
///
/// A sampler selects nodes from a graph, computes a local function for each,
/// and collects the results into a [`SampleResult`]. Samplers are composable:
/// the output of one can be fed into the `annotations` of the next via
/// [`SamplerPipeline`].
pub trait Sampler: Send + Sync {
    /// Stable identifier (used as key in annotation maps and persistence).
    fn id(&self) -> &str;

    /// Which nodes this sampler operates on.
    fn selector(&self) -> NodeSelector {
        NodeSelector::All
    }

    /// Compute the artifact for a single node.
    /// Return `Ok(None)` to skip a node without error.
    fn compute(&self, ctx: &SampleContext<'_>) -> Result<Option<Value>, SamplerError>;

    /// Run the full sampling pass over a graph.
    ///
    /// Default implementation: select → build context → compute → collect.
    /// Override only when the sampler needs batch-level optimizations
    /// (e.g. batched embedding inference).
    fn sample(
        &self,
        graph: &SourceCodeGraph,
        annotations: &AnnotationMap,
    ) -> Result<SampleResult, SamplerError> {
        let selector = self.selector();
        let selected: Vec<&GraphNode> =
            graph.nodes.iter().filter(|n| selector.matches(n)).collect();

        let mut artifacts = Vec::with_capacity(selected.len());

        for node in &selected {
            let neighbors = graph.neighbors(node.id);
            let empty = HashMap::new();
            let node_annotations = annotations.get(&node.id).unwrap_or(&empty);

            let ctx = SampleContext {
                node,
                neighbors,
                content: None,
                annotations: node_annotations,
                graph_metadata: &graph.metadata,
            };

            if let Some(value) = self.compute(&ctx)? {
                artifacts.push(SampleArtifact {
                    node_id: node.id,
                    value,
                });
            }
        }

        Ok(SampleResult {
            sampler_id: self.id().to_string(),
            artifacts,
            metadata: HashMap::new(),
        })
    }
}

/// Errors that can occur during sampling.
#[derive(Debug, Clone)]
pub struct SamplerError {
    pub sampler_id: String,
    pub message: String,
}

impl std::fmt::Display for SamplerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "sampler '{}': {}", self.sampler_id, self.message)
    }
}

impl std::error::Error for SamplerError {}

impl SamplerError {
    pub fn new(sampler_id: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            sampler_id: sampler_id.into(),
            message: message.into(),
        }
    }
}

/// Chains multiple samplers so each one's output enriches the annotations
/// available to the next.
pub struct SamplerPipeline {
    stages: Vec<Box<dyn Sampler>>,
}

impl SamplerPipeline {
    pub fn new() -> Self {
        Self { stages: Vec::new() }
    }

    /// Append a sampler stage to the pipeline.
    pub fn with_stage(mut self, sampler: Box<dyn Sampler>) -> Self {
        self.stages.push(sampler);
        self
    }

    /// Execute all stages in order, threading annotations forward.
    /// Returns the per-stage results and the accumulated annotation map.
    pub fn run(
        &self,
        graph: &SourceCodeGraph,
    ) -> Result<(Vec<SampleResult>, AnnotationMap), SamplerError> {
        let mut annotations: AnnotationMap = HashMap::new();
        let mut results = Vec::with_capacity(self.stages.len());

        for stage in &self.stages {
            let result = stage.sample(graph, &annotations)?;

            for artifact in &result.artifacts {
                annotations
                    .entry(artifact.node_id)
                    .or_default()
                    .insert(result.sampler_id.clone(), artifact.value.clone());
            }

            results.push(result);
        }

        Ok((results, annotations))
    }
}

impl Default for SamplerPipeline {
    fn default() -> Self {
        Self::new()
    }
}

// -- Helper: graph neighborhood lookup used by the default Sampler::sample --

impl SourceCodeGraph {
    /// Collect direct neighbors of a node (both directions) with their edges.
    pub fn neighbors(&self, node_id: NodeId) -> Vec<NeighborRef<'_>> {
        let node_map: HashMap<NodeId, &GraphNode> = self.nodes.iter().map(|n| (n.id, n)).collect();

        self.edges
            .iter()
            .filter_map(|edge| {
                let peer_id = if edge.from == node_id {
                    Some(edge.to)
                } else if edge.to == node_id {
                    Some(edge.from)
                } else {
                    None
                };
                peer_id.and_then(|pid| {
                    node_map.get(&pid).map(|peer_node| NeighborRef {
                        node: peer_node,
                        edge,
                    })
                })
            })
            .collect()
    }
}

/// A sampler that produces no artifacts — useful as a pipeline placeholder
/// and for testing.
pub struct NoOpSampler;

impl Sampler for NoOpSampler {
    fn id(&self) -> &str {
        "noop"
    }

    fn compute(&self, _ctx: &SampleContext<'_>) -> Result<Option<Value>, SamplerError> {
        Ok(None)
    }
}

/// A sampler that counts each node's direct neighbors (degree centrality).
/// Demonstrates the pattern and is useful as a lightweight structural signal.
pub struct DegreeSampler;

impl Sampler for DegreeSampler {
    fn id(&self) -> &str {
        "degree"
    }

    fn selector(&self) -> NodeSelector {
        NodeSelector::ByKind(GraphNodeKind::File)
    }

    fn compute(&self, ctx: &SampleContext<'_>) -> Result<Option<Value>, SamplerError> {
        let incoming = ctx
            .neighbors
            .iter()
            .filter(|n| n.edge.to == ctx.node.id)
            .count();
        let outgoing = ctx
            .neighbors
            .iter()
            .filter(|n| n.edge.from == ctx.node.id)
            .count();

        Ok(Some(serde_json::json!({
            "in": incoming,
            "out": outgoing,
            "total": incoming + outgoing,
        })))
    }
}

/// A sampler that extracts metadata from nodes as-is, useful for exposing
/// node properties (language, extension, has_tests) into the annotation
/// pipeline without transformation.
pub struct MetadataSampler {
    keys: Vec<String>,
}

impl MetadataSampler {
    /// Create a sampler that extracts the specified metadata keys.
    pub fn new(keys: Vec<String>) -> Self {
        Self { keys }
    }

    /// Extract all available metadata.
    pub fn all() -> Self {
        Self { keys: Vec::new() }
    }
}

impl Sampler for MetadataSampler {
    fn id(&self) -> &str {
        "metadata"
    }

    fn compute(&self, ctx: &SampleContext<'_>) -> Result<Option<Value>, SamplerError> {
        let extracted: serde_json::Map<String, Value> = if self.keys.is_empty() {
            ctx.node
                .metadata
                .iter()
                .map(|(k, v)| (k.clone(), Value::String(v.clone())))
                .collect()
        } else {
            self.keys
                .iter()
                .filter_map(|key| {
                    ctx.node
                        .metadata
                        .get(key)
                        .map(|v| (key.clone(), Value::String(v.clone())))
                })
                .collect()
        };

        if extracted.is_empty() {
            Ok(None)
        } else {
            Ok(Some(Value::Object(extracted)))
        }
    }
}

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

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

    fn test_graph() -> SourceCodeGraph {
        let mut meta_a = HashMap::new();
        meta_a.insert("relative_path".to_string(), "src/main.rs".to_string());
        meta_a.insert("extension".to_string(), "rs".to_string());
        meta_a.insert("language".to_string(), "rust".to_string());

        let mut meta_b = HashMap::new();
        meta_b.insert("relative_path".to_string(), "src/lib.rs".to_string());
        meta_b.insert("extension".to_string(), "rs".to_string());
        meta_b.insert("language".to_string(), "rust".to_string());

        let mut meta_dir = HashMap::new();
        meta_dir.insert("relative_path".to_string(), "src".to_string());

        SourceCodeGraph {
            nodes: vec![
                GraphNode {
                    id: NodeId(0),
                    name: "src".to_string(),
                    kind: GraphNodeKind::Directory,
                    metadata: meta_dir,
                },
                GraphNode {
                    id: NodeId(1),
                    name: "main.rs".to_string(),
                    kind: GraphNodeKind::File,
                    metadata: meta_a,
                },
                GraphNode {
                    id: NodeId(2),
                    name: "lib.rs".to_string(),
                    kind: GraphNodeKind::Module,
                    metadata: meta_b,
                },
            ],
            edges: vec![
                GraphEdge {
                    id: EdgeId(0),
                    from: NodeId(0),
                    to: NodeId(1),
                    relationship: "contains".to_string(),
                    metadata: HashMap::new(),
                },
                GraphEdge {
                    id: EdgeId(1),
                    from: NodeId(0),
                    to: NodeId(2),
                    relationship: "contains".to_string(),
                    metadata: HashMap::new(),
                },
                GraphEdge {
                    id: EdgeId(2),
                    from: NodeId(1),
                    to: NodeId(2),
                    relationship: "uses".to_string(),
                    metadata: HashMap::new(),
                },
            ],
            metadata: {
                let mut m = HashMap::new();
                m.insert("name".to_string(), "test-project".to_string());
                m
            },
        }
    }

    // -- SourceCodeGraph::neighbors --

    #[test]
    fn test_neighbors_returns_both_directions() {
        let graph = test_graph();
        // Node 2 (lib.rs): contained by src (edge 1), used by main.rs (edge 2)
        let neighbors = graph.neighbors(NodeId(2));
        assert_eq!(neighbors.len(), 2);

        let peer_ids: Vec<NodeId> = neighbors.iter().map(|n| n.node.id).collect();
        assert!(peer_ids.contains(&NodeId(0))); // src dir
        assert!(peer_ids.contains(&NodeId(1))); // main.rs
    }

    #[test]
    fn test_neighbors_empty_for_unknown_node() {
        let graph = test_graph();
        let neighbors = graph.neighbors(NodeId(999));
        assert!(neighbors.is_empty());
    }

    // -- NodeSelector --

    #[test]
    fn test_selector_all() {
        let graph = test_graph();
        let sel = NodeSelector::All;
        assert!(graph.nodes.iter().all(|n| sel.matches(n)));
    }

    #[test]
    fn test_selector_by_kind() {
        let graph = test_graph();
        let sel = NodeSelector::ByKind(GraphNodeKind::File);
        let matched: Vec<_> = graph.nodes.iter().filter(|n| sel.matches(n)).collect();
        assert_eq!(matched.len(), 1);
        assert_eq!(matched[0].name, "main.rs");
    }

    #[test]
    fn test_selector_explicit() {
        let graph = test_graph();
        let sel = NodeSelector::Explicit(vec![NodeId(0), NodeId(2)]);
        let matched: Vec<_> = graph.nodes.iter().filter(|n| sel.matches(n)).collect();
        assert_eq!(matched.len(), 2);
    }

    #[test]
    fn test_selector_has_metadata() {
        let graph = test_graph();
        let sel = NodeSelector::HasMetadata("language".to_string());
        let matched: Vec<_> = graph.nodes.iter().filter(|n| sel.matches(n)).collect();
        assert_eq!(matched.len(), 2); // main.rs and lib.rs, not src dir
    }

    #[test]
    fn test_selector_predicate() {
        let graph = test_graph();
        let sel = NodeSelector::Predicate(Box::new(|n| n.name.ends_with(".rs")));
        let matched: Vec<_> = graph.nodes.iter().filter(|n| sel.matches(n)).collect();
        assert_eq!(matched.len(), 2);
    }

    // -- NoOpSampler --

    #[test]
    fn test_noop_sampler_produces_nothing() {
        let graph = test_graph();
        let sampler = NoOpSampler;
        let result = sampler.sample(&graph, &HashMap::new()).unwrap();
        assert!(result.is_empty());
        assert_eq!(result.sampler_id, "noop");
    }

    // -- DegreeSampler --

    #[test]
    fn test_degree_sampler() {
        let graph = test_graph();
        let sampler = DegreeSampler;
        let result = sampler.sample(&graph, &HashMap::new()).unwrap();
        assert_eq!(result.sampler_id, "degree");

        // Only File-kind nodes are selected (main.rs = NodeId(1))
        assert_eq!(result.len(), 1);
        let artifact = result.get(NodeId(1)).unwrap();
        // main.rs: contained by src (in=1), uses lib.rs (out=1)
        assert_eq!(artifact.value["in"], 1);
        assert_eq!(artifact.value["out"], 1);
        assert_eq!(artifact.value["total"], 2);
    }

    // -- MetadataSampler --

    #[test]
    fn test_metadata_sampler_specific_keys() {
        let graph = test_graph();
        let sampler = MetadataSampler::new(vec!["language".to_string()]);
        let result = sampler.sample(&graph, &HashMap::new()).unwrap();
        // src dir has no "language" key → skipped
        assert_eq!(result.len(), 2);
        for (_, val) in result.iter() {
            assert_eq!(val["language"], "rust");
        }
    }

    #[test]
    fn test_metadata_sampler_all_keys() {
        let graph = test_graph();
        let sampler = MetadataSampler::all();
        let result = sampler.sample(&graph, &HashMap::new()).unwrap();
        assert_eq!(result.len(), 3); // all nodes have at least relative_path
    }

    // -- SampleResult --

    #[test]
    fn test_sample_result_get_and_iter() {
        let result = SampleResult {
            sampler_id: "test".to_string(),
            artifacts: vec![
                SampleArtifact {
                    node_id: NodeId(1),
                    value: json!({"score": 0.9}),
                },
                SampleArtifact {
                    node_id: NodeId(2),
                    value: json!({"score": 0.5}),
                },
            ],
            metadata: HashMap::new(),
        };
        assert_eq!(result.len(), 2);
        assert!(!result.is_empty());
        assert_eq!(result.get(NodeId(1)).unwrap().value["score"], 0.9);
        assert!(result.get(NodeId(99)).is_none());
        assert_eq!(result.iter().count(), 2);
    }

    // -- SamplerPipeline --

    #[test]
    fn test_pipeline_threads_annotations() {
        let graph = test_graph();
        let pipeline = SamplerPipeline::new()
            .with_stage(Box::new(MetadataSampler::all()))
            .with_stage(Box::new(DegreeSampler));

        let (results, annotations) = pipeline.run(&graph).unwrap();
        assert_eq!(results.len(), 2);

        // main.rs (NodeId 1) should have annotations from both stages
        let main_annot = annotations.get(&NodeId(1)).unwrap();
        assert!(main_annot.contains_key("metadata"));
        assert!(main_annot.contains_key("degree"));
    }

    #[test]
    fn test_pipeline_empty() {
        let graph = test_graph();
        let pipeline = SamplerPipeline::new();
        let (results, annotations) = pipeline.run(&graph).unwrap();
        assert!(results.is_empty());
        assert!(annotations.is_empty());
    }

    // -- SamplerError --

    #[test]
    fn test_sampler_error_display() {
        let err = SamplerError::new("embed", "model not loaded");
        assert_eq!(err.to_string(), "sampler 'embed': model not loaded");
    }

    // -- Failing sampler --

    struct FailingSampler;
    impl Sampler for FailingSampler {
        fn id(&self) -> &str {
            "failing"
        }
        fn compute(&self, _ctx: &SampleContext<'_>) -> Result<Option<Value>, SamplerError> {
            Err(SamplerError::new("failing", "intentional test failure"))
        }
    }

    #[test]
    fn test_sampler_propagates_error() {
        let graph = test_graph();
        let sampler = FailingSampler;
        let result = sampler.sample(&graph, &HashMap::new());
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().sampler_id, "failing");
    }

    // -- Lean 4 reference detection --

    #[test]
    fn test_detect_lean_references_imports() {
        let content = r#"/-
Copyright (c) 2024 Someone. All rights reserved.
-/
module

public import Mathlib.Topology.ContinuousMap.Compact
public import Mathlib.Topology.MetricSpace.Ultra.Basic
import Aesop

/-!
# Some module docs
-/

open Topology Filter in

def someDef := sorry
"#;
        let path = std::path::Path::new("Mathlib/Topology/Example.lean");
        let refs = detect_lean_references(content, path);

        let import_targets: Vec<String> = refs
            .iter()
            .filter(|r| matches!(r.kind, ReferenceKind::Imports))
            .map(|r| r.target_route.to_string_lossy().to_string())
            .collect();
        assert_eq!(import_targets.len(), 3);
        assert!(import_targets.contains(&"Mathlib/Topology/ContinuousMap/Compact.lean".to_string()));
        assert!(
            import_targets.contains(&"Mathlib/Topology/MetricSpace/Ultra/Basic.lean".to_string())
        );
        assert!(import_targets.contains(&"Aesop.lean".to_string()));

        let uses_targets: Vec<String> = refs
            .iter()
            .filter(|r| matches!(r.kind, ReferenceKind::Uses))
            .map(|r| r.target_route.to_string_lossy().to_string())
            .collect();
        assert_eq!(uses_targets.len(), 2);
        assert!(uses_targets.contains(&"Topology.lean".to_string()));
        assert!(uses_targets.contains(&"Filter.lean".to_string()));
    }

    #[test]
    fn test_detect_lean_references_empty() {
        let content = "-- just a comment\ndef x := 42\n";
        let path = std::path::Path::new("test.lean");
        let refs = detect_lean_references(content, path);
        assert!(refs.is_empty());
    }
}