infigraph-cli 1.0.0

CLI for infigraph — AST-powered code analysis and impact review
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
use std::path::PathBuf;

use anyhow::Result;
use infigraph_core::graph::{CozoStore, GraphStore};

fn main() -> Result<()> {
    let project_root = std::env::args()
        .nth(1)
        .map(PathBuf::from)
        .unwrap_or_else(|| std::env::current_dir().unwrap());

    let kuzu_path = project_root.join(".infigraph/graph");
    if !kuzu_path.exists() {
        anyhow::bail!("No Kuzu graph at {}", kuzu_path.display());
    }

    let cozo_path = project_root.join(".infigraph/graph.cozo");
    if cozo_path.exists() {
        std::fs::remove_file(&cozo_path)?;
    }

    eprintln!("Opening Kuzu graph at {}", kuzu_path.display());
    let kuzu = GraphStore::open(&kuzu_path)?;
    let conn = kuzu.connection()?;

    eprintln!("Creating CozoDB at {}", cozo_path.display());
    let cozo = CozoStore::open(&cozo_path)?;

    // ── 1. Symbols ─────────────────────────────────────────────────────
    eprintln!("Migrating symbols...");
    let mut result = conn.query(
        "MATCH (s:Symbol) RETURN s.id, s.name, s.kind, s.file, s.start_line, s.end_line, \
         s.signature_hash, s.language, s.visibility, s.parent, s.docstring, s.complexity, \
         s.parameters, s.return_type"
    ).map_err(|e| anyhow::anyhow!("query symbols: {e}"))?;

    let mut symbols = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 14 {
            symbols.push((
                row[0].to_string(),  // id
                row[1].to_string(),  // name
                row[2].to_string(),  // kind
                row[3].to_string(),  // file
                parse_i64(&row[4]),  // start_line
                parse_i64(&row[5]),  // end_line
                row[6].to_string(),  // signature_hash
                row[7].to_string(),  // language
                row[8].to_string(),  // visibility
                row[9].to_string(),  // parent
                row[10].to_string(), // docstring
                parse_i64(&row[11]), // complexity
                row[12].to_string(), // parameters
                row[13].to_string(), // return_type
            ));
        }
    }
    let sym_count = symbols.len();
    cozo.import_symbols(&symbols)?;
    eprintln!("  {} symbols", sym_count);
    drop(symbols);

    // ── 2. Modules ─────────────────────────────────────────────────────
    eprintln!("Migrating modules...");
    let mut result = conn.query(
        "MATCH (m:Module) RETURN m.id, m.name, m.file, m.language, m.content_hash, m.summary"
    ).map_err(|e| anyhow::anyhow!("query modules: {e}"))?;

    let mut modules = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 6 {
            modules.push((
                row[0].to_string(),
                row[1].to_string(),
                row[2].to_string(),
                row[3].to_string(),
                row[4].to_string(),
                row[5].to_string(),
            ));
        }
    }
    let mod_count = modules.len();
    cozo.import_modules(&modules)?;
    eprintln!("  {} modules", mod_count);
    drop(modules);

    // ── 3. Files ──────────────────────────────────────────────────────
    eprintln!("Migrating files...");
    let mut result = conn.query(
        "MATCH (f:File) RETURN f.id, f.name, f.path, f.language, f.symbol_count"
    ).map_err(|e| anyhow::anyhow!("query files: {e}"))?;

    let mut files = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 5 {
            files.push((
                row[0].to_string(),
                row[1].to_string(),
                row[2].to_string(),
                row[3].to_string(),
                parse_i64(&row[4]),
            ));
        }
    }
    let file_count = files.len();
    cozo.import_files(&files)?;
    eprintln!("  {} files", file_count);
    drop(files);

    // ── 4. Statements ─────────────────────────────────────────────────
    eprintln!("Migrating statements...");
    let mut result = conn.query(
        "MATCH (st:Statement) RETURN st.id, st.kind, st.condition, st.start_line, st.end_line, st.depth, st.parent_symbol"
    ).map_err(|e| anyhow::anyhow!("query statements: {e}"))?;

    let mut stmts = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 7 {
            stmts.push((
                row[0].to_string(),
                row[1].to_string(),
                row[2].to_string(),
                parse_i64(&row[3]),
                parse_i64(&row[4]),
                parse_i64(&row[5]),
                row[6].to_string(),
            ));
        }
    }
    let stmt_count = stmts.len();
    cozo.import_statements(&stmts)?;
    eprintln!("  {} statements", stmt_count);
    drop(stmts);

    // ── 5. Folders ─────────────────────────────────────────────────────
    eprintln!("Migrating folders...");
    let mut result = conn.query(
        "MATCH (f:Folder) RETURN f.id, f.name, f.path"
    ).map_err(|e| anyhow::anyhow!("query folders: {e}"))?;

    let mut folders = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 3 {
            folders.push((
                row[0].to_string(),
                row[1].to_string(),
                row[2].to_string(),
            ));
        }
    }
    let folder_count = folders.len();
    cozo.import_folders(&folders)?;
    eprintln!("  {} folders", folder_count);
    drop(folders);

    // ── 6. Dependencies ──────────────────────────────────────────────
    eprintln!("Migrating dependencies...");
    let mut result = conn.query(
        "MATCH (d:Dependency) RETURN d.id, d.name, d.version, d.ecosystem, d.is_dev"
    ).map_err(|e| anyhow::anyhow!("query dependencies: {e}"))?;

    let mut deps = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 5 {
            deps.push((
                row[0].to_string(),
                row[1].to_string(),
                row[2].to_string(),
                row[3].to_string(),
                parse_bool(&row[4]),
            ));
        }
    }
    let dep_count = deps.len();
    cozo.import_dependencies(&deps)?;
    eprintln!("  {} dependencies", dep_count);
    drop(deps);

    // ── 7. Clusters ──────────────────────────────────────────────────
    eprintln!("Migrating clusters...");
    let mut result = conn.query(
        "MATCH (c:Cluster) RETURN c.id, c.name, c.description"
    ).map_err(|e| anyhow::anyhow!("query clusters: {e}"))?;

    let mut clusters = Vec::new();
    while let Some(row) = result.next() {
        if row.len() >= 3 {
            clusters.push((
                row[0].to_string(),
                row[1].to_string(),
                row[2].to_string(),
            ));
        }
    }
    let cluster_count = clusters.len();
    cozo.import_clusters(&clusters)?;
    eprintln!("  {} clusters", cluster_count);
    drop(clusters);

    // ── 8. Simple edge relations (2 columns) ─────────────────────────
    let simple_edges = [
        ("CALLS",         "calls",         "(a:Symbol)-[r:CALLS]->(b:Symbol)", "a.id, b.id"),
        ("DEFINES",       "defines",       "(a:File)-[r:DEFINES]->(b:Symbol)", "a.id, b.id"),
        ("CONTAINS",      "contains",      "(a:Module)-[r:CONTAINS]->(b:Symbol)", "a.id, b.id"),
        ("INHERITS",      "inherits",      "(a:Symbol)-[r:INHERITS]->(b:Symbol)", "a.id, b.id"),
        ("TESTED_BY",     "tested_by",     "(a:Symbol)-[r:TESTED_BY]->(b:Symbol)", "a.id, b.id"),
        ("IMPORTS",       "imports",       "(a:Module)-[r:IMPORTS]->(b:Module)", "a.id, b.id"),
        ("READS",         "reads_rel",     "(a:Symbol)-[r:READS]->(b:Symbol)", "a.id, b.id"),
        ("WRITES",        "writes_rel",    "(a:Symbol)-[r:WRITES]->(b:Symbol)", "a.id, b.id"),
        ("HAS_STATEMENT", "has_statement", "(a:Symbol)-[r:HAS_STATEMENT]->(b:Statement)", "a.id, b.id"),
        ("MEMBER_OF",     "member_of",     "(a:Symbol)-[r:MEMBER_OF]->(b:Cluster)", "a.id, b.id"),
        ("CONTAINS_FILE",   "contains_file",   "(a:Folder)-[r:CONTAINS_FILE]->(b:File)", "a.id, b.id"),
        ("CONTAINS_FOLDER", "contains_folder", "(a:Folder)-[r:CONTAINS_FOLDER]->(b:Folder)", "a.id, b.id"),
    ];

    for (label, relation, pattern, ret) in &simple_edges {
        eprint!("Migrating {label}...");
        let q = format!("MATCH {pattern} RETURN {ret}");
        let mut result = conn.query(&q)
            .map_err(|e| anyhow::anyhow!("query {label}: {e}"))?;

        let mut pairs = Vec::new();
        while let Some(row) = result.next() {
            if row.len() >= 2 {
                pairs.push((row[0].to_string(), row[1].to_string()));
            }
        }
        let count = pairs.len();
        cozo.import_edges(relation, &pairs)?;
        eprintln!(" {} edges", count);
    }

    // ── 9. Rich edge relations (extra columns) ──────────────────────
    // DEPENDS_ON: module_id, dep_id, is_dev
    {
        eprint!("Migrating DEPENDS_ON...");
        let mut result = conn.query(
            "MATCH (a:Module)-[r:DEPENDS_ON]->(b:Dependency) RETURN a.id, b.id, r.is_dev"
        ).map_err(|e| anyhow::anyhow!("query DEPENDS_ON: {e}"))?;

        let headers = vec!["module_id".into(), "dep_id".into(), "is_dev".into()];
        let mut rows = Vec::new();
        while let Some(row) = result.next() {
            if row.len() >= 3 {
                rows.push(vec![
                    cozo::DataValue::Str(row[0].to_string().into()),
                    cozo::DataValue::Str(row[1].to_string().into()),
                    cozo::DataValue::Bool(parse_bool(&row[2])),
                ]);
            }
        }
        let count = rows.len();
        cozo.import_raw("depends_on", headers, rows)?;
        eprintln!(" {} edges", count);
    }

    // SIMILAR_TO: symbol_a, symbol_b, score
    {
        eprint!("Migrating SIMILAR_TO...");
        let mut result = conn.query(
            "MATCH (a:Symbol)-[r:SIMILAR_TO]->(b:Symbol) RETURN a.id, b.id, r.score"
        ).map_err(|e| anyhow::anyhow!("query SIMILAR_TO: {e}"))?;

        let headers = vec!["symbol_a".into(), "symbol_b".into(), "score".into()];
        let mut rows = Vec::new();
        while let Some(row) = result.next() {
            if row.len() >= 3 {
                rows.push(vec![
                    cozo::DataValue::Str(row[0].to_string().into()),
                    cozo::DataValue::Str(row[1].to_string().into()),
                    cozo::DataValue::from(parse_f64(&row[2])),
                ]);
            }
        }
        let count = rows.len();
        cozo.import_raw("similar_to", headers, rows)?;
        eprintln!(" {} edges", count);
    }

    // BRIDGE_TO: source, target, bridge_kind, detail
    {
        eprint!("Migrating BRIDGE_TO...");
        let mut result = conn.query(
            "MATCH (a:Symbol)-[r:BRIDGE_TO]->(b:Symbol) RETURN a.id, b.id, r.bridge_kind, r.detail"
        ).map_err(|e| anyhow::anyhow!("query BRIDGE_TO: {e}"))?;

        let headers = vec!["source".into(), "target".into(), "bridge_kind".into(), "detail".into()];
        let mut rows = Vec::new();
        while let Some(row) = result.next() {
            if row.len() >= 4 {
                rows.push(vec![
                    cozo::DataValue::Str(row[0].to_string().into()),
                    cozo::DataValue::Str(row[1].to_string().into()),
                    cozo::DataValue::Str(row[2].to_string().into()),
                    cozo::DataValue::Str(row[3].to_string().into()),
                ]);
            }
        }
        let count = rows.len();
        cozo.import_raw("bridge_to", headers, rows)?;
        eprintln!(" {} edges", count);
    }

    // CALLS_SERVICE: caller, target, method, path, target_service
    {
        eprint!("Migrating CALLS_SERVICE...");
        let mut result = conn.query(
            "MATCH (a:Symbol)-[r:CALLS_SERVICE]->(b:Symbol) RETURN a.id, b.id, r.method, r.path, r.target_service"
        ).map_err(|e| anyhow::anyhow!("query CALLS_SERVICE: {e}"))?;

        let headers = vec!["caller".into(), "target".into(), "method".into(), "path".into(), "target_service".into()];
        let mut rows = Vec::new();
        while let Some(row) = result.next() {
            if row.len() >= 5 {
                rows.push(vec![
                    cozo::DataValue::Str(row[0].to_string().into()),
                    cozo::DataValue::Str(row[1].to_string().into()),
                    cozo::DataValue::Str(row[2].to_string().into()),
                    cozo::DataValue::Str(row[3].to_string().into()),
                    cozo::DataValue::Str(row[4].to_string().into()),
                ]);
            }
        }
        let count = rows.len();
        cozo.import_raw("calls_service", headers, rows)?;
        eprintln!(" {} edges", count);
    }

    // ── 10. Custom language edges (dynamic) ──────────────────────────
    {
        let known_edges: std::collections::HashSet<&str> = [
            "CALLS", "DEPENDS_ON", "IMPORTS", "CONTAINS", "INHERITS",
            "TESTED_BY", "READS", "WRITES", "MEMBER_OF", "SIMILAR_TO",
            "BRIDGE_TO", "CONTAINS_FILE", "CONTAINS_FOLDER", "DEFINES",
            "CALLS_SERVICE", "HAS_STATEMENT",
        ].into_iter().collect();

        let mut result = conn.query("CALL show_tables() RETURN *")
            .map_err(|e| anyhow::anyhow!("show_tables: {e}"))?;

        let mut custom_edges = Vec::new();
        while let Some(row) = result.next() {
            if row.len() >= 2 {
                let name = row[0].to_string();
                let ttype = row[1].to_string();
                if ttype == "REL" && !known_edges.contains(name.as_str()) {
                    custom_edges.push(name);
                }
            }
        }

        for edge_name in &custom_edges {
            eprint!("Migrating custom edge {edge_name}...");
            let lower = edge_name.to_lowercase();
            let schema_ddl = format!(
                ":create {lower} {{source: String, target: String}}"
            );
            match cozo.create_custom_edge(&schema_ddl) {
                Ok(_) => {}
                Err(_) => {} // already exists
            }

            let q = format!(
                "MATCH (a:Symbol)-[r:{edge_name}]->(b:Symbol) RETURN a.id, b.id"
            );
            let mut result = conn.query(&q)
                .map_err(|e| anyhow::anyhow!("query {edge_name}: {e}"))?;

            let mut pairs = Vec::new();
            while let Some(row) = result.next() {
                if row.len() >= 2 {
                    pairs.push((row[0].to_string(), row[1].to_string()));
                }
            }
            let count = pairs.len();
            cozo.import_edges(&lower, &pairs)?;
            eprintln!(" {} edges", count);
        }
    }

    // ── 11. Verify all relation counts ─────────────────────────────────
    let cozo_counts = cozo.relation_counts()?;

    let kuzu_count_queries: &[(&str, &str, &str)] = &[
        ("symbol",         "MATCH (n:Symbol) RETURN count(n)",     "symbol"),
        ("module",         "MATCH (n:Module) RETURN count(n)",     "module"),
        ("cluster",        "MATCH (n:Cluster) RETURN count(n)",    "cluster"),
        ("file",           "MATCH (n:File) RETURN count(n)",       "file"),
        ("folder",         "MATCH (n:Folder) RETURN count(n)",     "folder"),
        ("dependency",     "MATCH (n:Dependency) RETURN count(n)", "dependency"),
        ("statement",      "MATCH (n:Statement) RETURN count(n)",  "statement"),
        ("calls",          "MATCH ()-[r:CALLS]->() RETURN count(r)",         "calls"),
        ("depends_on",     "MATCH ()-[r:DEPENDS_ON]->() RETURN count(r)",    "depends_on"),
        ("imports",        "MATCH ()-[r:IMPORTS]->() RETURN count(r)",       "imports"),
        ("contains",       "MATCH ()-[r:CONTAINS]->() RETURN count(r)",      "contains"),
        ("inherits",       "MATCH ()-[r:INHERITS]->() RETURN count(r)",      "inherits"),
        ("tested_by",      "MATCH ()-[r:TESTED_BY]->() RETURN count(r)",     "tested_by"),
        ("reads_rel",      "MATCH ()-[r:READS]->() RETURN count(r)",         "reads_rel"),
        ("writes_rel",     "MATCH ()-[r:WRITES]->() RETURN count(r)",        "writes_rel"),
        ("member_of",      "MATCH ()-[r:MEMBER_OF]->() RETURN count(r)",     "member_of"),
        ("similar_to",     "MATCH ()-[r:SIMILAR_TO]->() RETURN count(r)",    "similar_to"),
        ("bridge_to",      "MATCH ()-[r:BRIDGE_TO]->() RETURN count(r)",     "bridge_to"),
        ("contains_file",  "MATCH ()-[r:CONTAINS_FILE]->() RETURN count(r)", "contains_file"),
        ("contains_folder","MATCH ()-[r:CONTAINS_FOLDER]->() RETURN count(r)","contains_folder"),
        ("defines",        "MATCH ()-[r:DEFINES]->() RETURN count(r)",       "defines"),
        ("calls_service",  "MATCH ()-[r:CALLS_SERVICE]->() RETURN count(r)", "calls_service"),
        ("has_statement",  "MATCH ()-[r:HAS_STATEMENT]->() RETURN count(r)", "has_statement"),
    ];

    eprintln!("\n=== Migration Verification ===");
    eprintln!("{:<20} {:>8} {:>8}  {}", "Relation", "Kuzu", "CozoDB", "Status");
    eprintln!("{}", "-".repeat(55));

    let mut mismatches = Vec::new();
    for (label, query, cozo_key) in kuzu_count_queries {
        let mut result = conn.query(query)
            .map_err(|e| anyhow::anyhow!("count {label}: {e}"))?;
        let kuzu_count = result.next()
            .map(|row| row[0].to_string().parse::<u64>().unwrap_or(0))
            .unwrap_or(0);
        let cozo_count = cozo_counts.get(*cozo_key).copied().unwrap_or(0);

        let status = if kuzu_count == cozo_count {
            ""
        } else if *label == "calls" && kuzu_count > cozo_count {
            "⚠️  dedup"
        } else {
            mismatches.push((*label, kuzu_count, cozo_count));
            "❌ MISMATCH"
        };
        eprintln!("{:<20} {:>8} {:>8}  {}", label, kuzu_count, cozo_count, status);
    }

    if !mismatches.is_empty() {
        for (label, kuzu, cozo) in &mismatches {
            eprintln!("ERROR: {label} count mismatch: Kuzu={kuzu}, CozoDB={cozo}");
        }
        anyhow::bail!("{} relation(s) have count mismatches", mismatches.len());
    }

    eprintln!("\nMigration complete! CozoDB at {}", cozo_path.display());
    Ok(())
}

fn parse_i64(v: &kuzu::Value) -> i64 {
    v.to_string().parse().unwrap_or(0)
}

fn parse_bool(v: &kuzu::Value) -> bool {
    let s = v.to_string();
    s == "True" || s == "true" || s == "1"
}

fn parse_f64(v: &kuzu::Value) -> f64 {
    v.to_string().parse().unwrap_or(0.0)
}