gid-core 0.3.2

Graph-Indexed Development core library — graph-based project management and code analysis for AI agents
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
//! Graph validation: detect cycles, orphan nodes, missing references, etc.

use std::collections::{HashMap, HashSet, VecDeque};
use crate::graph::Graph;

/// Validation result with all issues found.
#[derive(Debug, Default)]
pub struct ValidationResult {
    pub orphan_nodes: Vec<String>,
    pub missing_refs: Vec<MissingRef>,
    pub cycles: Vec<Vec<String>>,
    pub duplicate_nodes: Vec<String>,
    pub duplicate_edges: Vec<DuplicateEdge>,
    pub self_edges: Vec<SelfEdge>,
}

#[derive(Debug)]
pub struct MissingRef {
    pub edge_from: String,
    pub edge_to: String,
    pub missing_node: String,
}

#[derive(Debug)]
pub struct DuplicateEdge {
    pub from: String,
    pub to: String,
    pub relation: String,
}

#[derive(Debug)]
pub struct SelfEdge {
    pub node: String,
    pub relation: String,
}

impl ValidationResult {
    pub fn is_valid(&self) -> bool {
        self.orphan_nodes.is_empty()
            && self.missing_refs.is_empty()
            && self.cycles.is_empty()
            && self.duplicate_nodes.is_empty()
            && self.duplicate_edges.is_empty()
            && self.self_edges.is_empty()
    }

    pub fn issue_count(&self) -> usize {
        self.orphan_nodes.len()
            + self.missing_refs.len()
            + self.cycles.len()
            + self.duplicate_nodes.len()
            + self.duplicate_edges.len()
            + self.self_edges.len()
    }
}

impl std::fmt::Display for ValidationResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_valid() {
            return write!(f, "✓ Graph is valid");
        }

        let mut lines = Vec::new();

        if !self.orphan_nodes.is_empty() {
            lines.push(format!(
                "Orphan nodes (no edges): {}",
                self.orphan_nodes.join(", ")
            ));
        }

        for mr in &self.missing_refs {
            lines.push(format!(
                "Missing node '{}' referenced by edge {}{}",
                mr.missing_node, mr.edge_from, mr.edge_to
            ));
        }

        for cycle in &self.cycles {
            lines.push(format!("Cycle detected: {}", cycle.join("")));
        }

        if !self.duplicate_nodes.is_empty() {
            lines.push(format!(
                "Duplicate node IDs: {}",
                self.duplicate_nodes.join(", ")
            ));
        }

        for de in &self.duplicate_edges {
            lines.push(format!(
                "Duplicate edge: {}{} ({})",
                de.from, de.to, de.relation
            ));
        }

        for se in &self.self_edges {
            lines.push(format!(
                "Self-referential edge: {}{} ({})",
                se.node, se.node, se.relation
            ));
        }

        write!(f, "{} issues found:\n  {}", self.issue_count(), lines.join("\n  "))
    }
}

/// Validator for graph integrity.
pub struct Validator<'a> {
    graph: &'a Graph,
}

impl<'a> Validator<'a> {
    pub fn new(graph: &'a Graph) -> Self {
        Self { graph }
    }

    /// Run all validations and return combined result.
    pub fn validate(&self) -> ValidationResult {
        let mut result = ValidationResult::default();

        result.duplicate_nodes = self.find_duplicate_nodes();
        result.missing_refs = self.find_missing_refs();
        result.orphan_nodes = self.find_orphan_nodes();
        result.cycles = self.find_cycles();
        result.duplicate_edges = self.find_duplicate_edges();
        result.self_edges = self.find_self_edges();

        result
    }

    /// Find nodes that have no edges (neither incoming nor outgoing).
    pub fn find_orphan_nodes(&self) -> Vec<String> {
        let connected: HashSet<&str> = self.graph.edges.iter()
            .flat_map(|e| [e.from.as_str(), e.to.as_str()])
            .collect();

        self.graph.nodes.iter()
            .filter(|n| !connected.contains(n.id.as_str()))
            .map(|n| n.id.clone())
            .collect()
    }

    /// Find edges that reference non-existent nodes.
    pub fn find_missing_refs(&self) -> Vec<MissingRef> {
        let node_ids: HashSet<&str> = self.graph.nodes.iter()
            .map(|n| n.id.as_str())
            .collect();

        let mut missing = Vec::new();

        for edge in &self.graph.edges {
            if !node_ids.contains(edge.from.as_str()) {
                missing.push(MissingRef {
                    edge_from: edge.from.clone(),
                    edge_to: edge.to.clone(),
                    missing_node: edge.from.clone(),
                });
            }
            if !node_ids.contains(edge.to.as_str()) {
                missing.push(MissingRef {
                    edge_from: edge.from.clone(),
                    edge_to: edge.to.clone(),
                    missing_node: edge.to.clone(),
                });
            }
        }

        missing
    }

    /// Find cycles in the graph using Tarjan's SCC algorithm.
    /// By default checks depends_on edges. Any SCC with size > 1 is a cycle.
    pub fn find_cycles(&self) -> Vec<Vec<String>> {
        self.find_cycles_for_relations(&["depends_on"])
    }

    /// Find cycles considering specific edge relations.
    pub fn find_cycles_for_relations(&self, relations: &[&str]) -> Vec<Vec<String>> {
        let relation_set: HashSet<&str> = relations.iter().copied().collect();

        // Build adjacency list for specified edge relations
        let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
        for node in &self.graph.nodes {
            adj.entry(&node.id).or_default();
        }
        for edge in &self.graph.edges {
            if relation_set.contains(edge.relation.as_str()) {
                adj.entry(&edge.from).or_default().push(&edge.to);
            }
        }

        // Tarjan's SCC
        let mut index_counter: usize = 0;
        let mut stack: Vec<&str> = Vec::new();
        let mut on_stack: HashSet<&str> = HashSet::new();
        let mut indices: HashMap<&str, usize> = HashMap::new();
        let mut lowlinks: HashMap<&str, usize> = HashMap::new();
        let mut sccs: Vec<Vec<String>> = Vec::new();

        fn strongconnect<'a>(
            node: &'a str,
            adj: &HashMap<&'a str, Vec<&'a str>>,
            index_counter: &mut usize,
            stack: &mut Vec<&'a str>,
            on_stack: &mut HashSet<&'a str>,
            indices: &mut HashMap<&'a str, usize>,
            lowlinks: &mut HashMap<&'a str, usize>,
            sccs: &mut Vec<Vec<String>>,
        ) {
            indices.insert(node, *index_counter);
            lowlinks.insert(node, *index_counter);
            *index_counter += 1;
            stack.push(node);
            on_stack.insert(node);

            if let Some(neighbors) = adj.get(node) {
                for &neighbor in neighbors {
                    if !indices.contains_key(neighbor) {
                        strongconnect(neighbor, adj, index_counter, stack, on_stack, indices, lowlinks, sccs);
                        let neighbor_low = lowlinks[neighbor];
                        let node_low = lowlinks.get_mut(node).unwrap();
                        if neighbor_low < *node_low {
                            *node_low = neighbor_low;
                        }
                    } else if on_stack.contains(neighbor) {
                        let neighbor_idx = indices[neighbor];
                        let node_low = lowlinks.get_mut(node).unwrap();
                        if neighbor_idx < *node_low {
                            *node_low = neighbor_idx;
                        }
                    }
                }
            }

            // If node is a root of an SCC
            if lowlinks[node] == indices[node] {
                let mut scc = Vec::new();
                loop {
                    let w = stack.pop().unwrap();
                    on_stack.remove(w);
                    scc.push(w.to_string());
                    if w == node {
                        break;
                    }
                }
                // Only report SCCs with size > 1 (actual cycles)
                if scc.len() > 1 {
                    scc.reverse(); // Put in traversal order
                    // Add closing node to match the existing format: [a, b, c, a]
                    if let Some(first) = scc.first().cloned() {
                        scc.push(first);
                    }
                    sccs.push(scc);
                }
            }
        }

        for node in &self.graph.nodes {
            if !indices.contains_key(node.id.as_str()) {
                strongconnect(
                    &node.id, &adj, &mut index_counter, &mut stack,
                    &mut on_stack, &mut indices, &mut lowlinks, &mut sccs,
                );
            }
        }

        sccs
    }

    /// Find duplicate node IDs.
    pub fn find_duplicate_nodes(&self) -> Vec<String> {
        let mut seen = HashSet::new();
        let mut duplicates = Vec::new();

        for node in &self.graph.nodes {
            if !seen.insert(&node.id) {
                duplicates.push(node.id.clone());
            }
        }

        duplicates
    }

    /// Find duplicate edges (same from, to, relation).
    pub fn find_duplicate_edges(&self) -> Vec<DuplicateEdge> {
        let mut seen = HashSet::new();
        let mut duplicates = Vec::new();

        for edge in &self.graph.edges {
            let key = (&edge.from, &edge.to, &edge.relation);
            if !seen.insert(key) {
                duplicates.push(DuplicateEdge {
                    from: edge.from.clone(),
                    to: edge.to.clone(),
                    relation: edge.relation.clone(),
                });
            }
        }

        duplicates
    }

    /// Find self-referential edges (from == to).
    pub fn find_self_edges(&self) -> Vec<SelfEdge> {
        self.graph.edges.iter()
            .filter(|e| e.from == e.to)
            .map(|e| SelfEdge {
                node: e.from.clone(),
                relation: e.relation.clone(),
            })
            .collect()
    }

    /// Check if adding an edge would create a cycle.
    pub fn would_create_cycle(&self, from: &str, to: &str) -> bool {
        // Adding from -> to creates a cycle if there's already a path from to -> from
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back(to);
        visited.insert(to);

        while let Some(current) = queue.pop_front() {
            if current == from {
                return true;
            }
            for edge in &self.graph.edges {
                if edge.from == current && edge.relation == "depends_on" {
                    if visited.insert(&edge.to) {
                        queue.push_back(&edge.to);
                    }
                }
            }
        }

        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{Edge, Node};

    #[test]
    fn test_orphan_detection() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.add_node(Node::new("c", "C"));
        graph.add_edge(Edge::depends_on("a", "b"));
        
        let validator = Validator::new(&graph);
        let orphans = validator.find_orphan_nodes();
        assert_eq!(orphans, vec!["c"]);
    }

    #[test]
    fn test_missing_refs() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.edges.push(Edge::depends_on("a", "missing"));

        let validator = Validator::new(&graph);
        let missing = validator.find_missing_refs();
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0].missing_node, "missing");
    }

    #[test]
    fn test_self_edge_detection() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.edges.push(Edge::depends_on("a", "a")); // self-edge
        graph.add_edge(Edge::depends_on("a", "b"));    // normal edge

        let validator = Validator::new(&graph);
        let self_edges = validator.find_self_edges();
        assert_eq!(self_edges.len(), 1);
        assert_eq!(self_edges[0].node, "a");
        assert_eq!(self_edges[0].relation, "depends_on");
    }

    #[test]
    fn test_self_edge_makes_graph_invalid() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.add_edge(Edge::depends_on("a", "b"));

        let validator = Validator::new(&graph);
        assert!(validator.find_self_edges().is_empty());

        // Add self-edge
        graph.edges.push(Edge::depends_on("b", "b"));
        let validator = Validator::new(&graph);
        let result = validator.validate();
        assert!(!result.self_edges.is_empty());
        // self_edges contribute to issue_count and is_valid
        assert!(result.issue_count() > 0);
    }

    #[test]
    fn test_no_self_edges_in_clean_graph() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.add_node(Node::new("c", "C"));
        graph.add_edge(Edge::depends_on("a", "b"));
        graph.add_edge(Edge::depends_on("b", "c"));

        let validator = Validator::new(&graph);
        assert!(validator.find_self_edges().is_empty());
    }

    #[test]
    fn test_cycle_detection() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.add_node(Node::new("c", "C"));
        graph.add_edge(Edge::depends_on("a", "b"));
        graph.add_edge(Edge::depends_on("b", "c"));
        graph.add_edge(Edge::depends_on("c", "a")); // cycle!

        let validator = Validator::new(&graph);
        let cycles = validator.find_cycles();
        assert!(!cycles.is_empty());
    }

    #[test]
    fn test_multiple_independent_cycles() {
        let mut graph = Graph::new();
        // Cycle 1: a -> b -> a
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.add_edge(Edge::depends_on("a", "b"));
        graph.add_edge(Edge::depends_on("b", "a"));
        // Cycle 2: c -> d -> c
        graph.add_node(Node::new("c", "C"));
        graph.add_node(Node::new("d", "D"));
        graph.add_edge(Edge::depends_on("c", "d"));
        graph.add_edge(Edge::depends_on("d", "c"));
        // Unconnected node
        graph.add_node(Node::new("e", "E"));

        let validator = Validator::new(&graph);
        let cycles = validator.find_cycles();
        assert_eq!(cycles.len(), 2, "Should find both independent cycles");
    }

    #[test]
    fn test_no_false_positives_on_dag() {
        let mut graph = Graph::new();
        // Diamond DAG: a -> b, a -> c, b -> d, c -> d
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        graph.add_node(Node::new("c", "C"));
        graph.add_node(Node::new("d", "D"));
        graph.add_edge(Edge::depends_on("a", "b"));
        graph.add_edge(Edge::depends_on("a", "c"));
        graph.add_edge(Edge::depends_on("b", "d"));
        graph.add_edge(Edge::depends_on("c", "d"));

        let validator = Validator::new(&graph);
        let cycles = validator.find_cycles();
        assert!(cycles.is_empty(), "Diamond DAG should have no cycles");
    }

    #[test]
    fn test_cycle_detection_multi_relation() {
        let mut graph = Graph::new();
        graph.add_node(Node::new("a", "A"));
        graph.add_node(Node::new("b", "B"));
        // No depends_on cycle, but blocks creates one
        graph.add_edge(Edge::new("a", "b", "blocks"));
        graph.add_edge(Edge::new("b", "a", "blocks"));

        let validator = Validator::new(&graph);
        // Default: only depends_on — no cycles
        let cycles = validator.find_cycles();
        assert!(cycles.is_empty());
        // With blocks relation — finds cycle
        let cycles = validator.find_cycles_for_relations(&["blocks"]);
        assert_eq!(cycles.len(), 1);
    }
}