morpharch 2.2.3

Monorepo architecture drift visualizer with animated TUI
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
// =============================================================================
// commands/analyze.rs — Analyze command: detailed drift report
// =============================================================================
//
//  For the specified commit (or HEAD):
//   1. Fetches graph snapshot from DB
//   2. Displays drift score and sub-metrics
//   3. Computes temporal delta with the previous 3 commits
//   4. Lists top boundary violators
//   5. Reports cycle information
//   6. Offers improvement recommendations
//
// Usage:
//   morpharch analyze           → HEAD commit analysis
//   morpharch analyze main~5    → Specified commit analysis
// =============================================================================

use std::collections::HashSet;
use std::path::Path;

use anyhow::{Context, Result};
use tracing::info;

use crate::analysis;
use crate::config::ProjectConfig;
use crate::db::Database;
use crate::graph_builder;
use crate::models::DriftScore;
use crate::scoring;

/// Runs the analyze command: produces a detailed drift report.
pub fn run_analyze(
    repo_path: &Path,
    repo_id: &str,
    commit_ish: Option<&str>,
    db: &Database,
    project_config: &ProjectConfig,
) -> Result<()> {
    // ── Resolve commit hash ──
    let commit_hash = resolve_commit(repo_path, commit_ish)?;
    let short_hash = if commit_hash.len() >= 7 {
        &commit_hash[..7]
    } else {
        &commit_hash
    };

    info!(hash = %commit_hash, "Analyzing commit");

    // ── Fetch graph snapshot ──
    let mut snapshot = db
        .get_graph_snapshot(repo_id, &commit_hash)?
        .with_context(|| format!("No graph snapshot found for this commit: {short_hash}"))?;
    if snapshot.requires_core_recompute() || snapshot.needs_full_analysis() {
        let prev_snapshot = match db.get_scan_order(repo_id, &commit_hash)? {
            Some(scan_order) => db.get_previous_snapshot(repo_id, scan_order)?,
            None => None,
        };
        let prev_graph = prev_snapshot.map(|previous| {
            let nodes: HashSet<String> = previous.nodes.into_iter().collect();
            graph_builder::build_graph(&nodes, &previous.edges)
        });
        let nodes: HashSet<String> = snapshot.nodes.iter().cloned().collect();
        let artifacts = analysis::build_snapshot_artifacts(
            &nodes,
            &snapshot.edges,
            prev_graph.as_ref(),
            snapshot.timestamp,
            &project_config.scoring,
            analysis::SnapshotAnalysisDetail::Full,
        );
        snapshot.node_count = artifacts.graph.node_count();
        snapshot.edge_count = artifacts.graph.edge_count();
        snapshot.drift = Some(artifacts.drift);
        snapshot.blast_radius = artifacts.blast_radius;
        snapshot.instability_metrics = artifacts.instability_metrics;
        snapshot.diagnostics = artifacts.diagnostics;
    }

    println!("  Commit Analysis: {short_hash}");
    println!();

    // ── Drift report ──
    if let Some(ref drift) = snapshot.drift {
        print_drift_report(
            drift,
            snapshot.node_count,
            snapshot.edge_count,
            project_config,
        );
    } else {
        println!("  No drift score calculated for this commit.");
        println!("   Run 'morpharch scan <path>' to re-scan first.");
        return Ok(());
    }

    // ── Temporal analysis: compare with previous 3 commits ──
    println!();
    println!("  Temporal Analysis (comparison with previous commits):");
    println!();

    if let Some(scan_order) = db.get_scan_order(repo_id, &commit_hash)? {
        let prev_commits = db.list_previous_drift_entries(repo_id, scan_order, 3)?;

        if prev_commits.is_empty() {
            println!("  No earlier commits available.");
        } else {
            let header = format!(
                "  {:<9} {:>6} {:>6} {:>7} {:>8}",
                "HASH", "NODES", "EDGES", "DRIFT", "DELTA"
            );
            println!("{header}");
            let separator = format!("  {}", "-".repeat(45));
            println!("{separator}");

            let current_drift = snapshot.drift.as_ref().map(|d| d.total).unwrap_or(0);

            for (prev_hash, _msg, prev_nodes, prev_edges, prev_drift, _ts) in &prev_commits {
                let prev_short = if prev_hash.len() >= 7 {
                    &prev_hash[..7]
                } else {
                    prev_hash
                };
                let drift_str = prev_drift
                    .map(|d| format!("{d}"))
                    .unwrap_or_else(|| "?".to_string());
                let delta = prev_drift
                    .map(|d| current_drift as i32 - d as i32)
                    .map(|d| {
                        if d > 0 {
                            format!("+{d}")
                        } else {
                            format!("{d}")
                        }
                    })
                    .unwrap_or_else(|| "?".to_string());

                println!(
                    "  {:<9} {:>6} {:>6} {:>7} {:>8}",
                    prev_short, prev_nodes, prev_edges, drift_str, delta
                );
            }
        }
    } else {
        println!("  This commit was not found in the trend data.");
    }

    // ── Boundary violation details ──
    println!();
    print_boundary_details(&snapshot.edges, project_config);

    // ── Cycle information ──
    println!();
    print_cycle_info(&snapshot.nodes, &snapshot.edges);

    // ── Blast Radius Analysis ──
    println!();
    print_blast_radius(&snapshot);

    // ── Recommendations ──
    println!();
    print_recommendations(&snapshot.drift);

    Ok(())
}

fn resolve_commit(repo_path: &Path, commit_ish: Option<&str>) -> Result<String> {
    let repo = gix::discover(repo_path)
        .with_context(|| format!("Git repository not found: {}", repo_path.display()))?;

    let reference = commit_ish.unwrap_or("HEAD");

    let object = repo
        .rev_parse_single(reference)
        .with_context(|| format!("Failed to resolve commit reference: '{reference}'"))?;

    Ok(object.detach().to_string())
}

fn print_drift_report(
    drift: &DriftScore,
    node_count: usize,
    edge_count: usize,
    config: &ProjectConfig,
) {
    let (emoji, level) = match drift.total {
        0..=15 => ("  ", "Excellent"),
        16..=30 => ("  ", "Healthy"),
        31..=55 => ("  ", "Warning"),
        56..=80 => ("  ", "Degraded"),
        _ => ("  ", "Critical"),
    };

    let n = config.scoring.weights.normalized();
    let pct = |v: f64| -> u32 { (v * 100.0).round() as u32 };

    println!("{emoji} Drift Score: {}/100 ({level})", drift.total);
    println!("     Health: {}%", 100u8.saturating_sub(drift.total));
    println!();
    println!("  Graph Statistics:");
    println!("     Node (module) count:      {node_count}");
    println!("     Edge (dependency) count:   {edge_count}");
    println!();
    println!("  Component Breakdown (6-factor analysis):");
    println!(
        "     Cycles      ({:>2}%):  {:5.1}/100  {} SCCs",
        pct(n.cycle),
        drift.cycle_debt,
        drift.new_cycles
    );
    println!(
        "     Layering    ({:>2}%):  {:5.1}/100  {} cross-links",
        pct(n.layering),
        drift.layering_debt,
        drift.layering_violations
    );
    println!(
        "     Hub/God     ({:>2}%):  {:5.1}/100",
        pct(n.hub),
        drift.hub_debt
    );
    println!(
        "     Coupling    ({:>2}%):  {:5.1}/100",
        pct(n.coupling),
        drift.coupling_debt
    );
    println!(
        "     Cognitive   ({:>2}%):  {:5.1}/100",
        pct(n.cognitive),
        drift.cognitive_debt
    );
    println!(
        "     Instability ({:>2}%):  {:5.1}/100",
        pct(n.instability),
        drift.instability_debt
    );
    println!();
    println!("  Delta Metrics:");
    println!("     Fan-in change (median):   {:+}", drift.fan_in_delta);
    println!("     Fan-out change (median):  {:+}", drift.fan_out_delta);
}

fn print_boundary_details(edges: &[crate::models::DependencyEdge], config: &ProjectConfig) {
    let pairs = scoring::edges_to_pairs(edges);

    let violations: Vec<_> = if config.scoring.boundaries.is_empty() {
        // Fall back to legacy rules when no boundaries are configured
        pairs
            .iter()
            .filter(|(from, to)| {
                scoring::LEGACY_BOUNDARY_RULES
                    .iter()
                    .any(|(fp, tp)| from.starts_with(fp) && to.starts_with(tp))
            })
            .collect()
    } else {
        // Use configured boundary rules with prefix matching
        pairs
            .iter()
            .filter(|(from, to)| {
                config
                    .scoring
                    .boundaries
                    .iter()
                    .any(|rule| rule.matches(from, to))
            })
            .collect()
    };

    if violations.is_empty() {
        println!("  Boundary Violations: None — package boundaries are clean.");
    } else {
        println!("  Boundary Violations ({} found):", violations.len());
        for (i, (from, to)) in violations.iter().enumerate().take(10) {
            println!("     {}. {} -> {}", i + 1, from, to);
        }
        if violations.len() > 10 {
            println!("     ... and {} more", violations.len() - 10);
        }
    }
}

fn print_cycle_info(nodes: &[String], edges: &[crate::models::DependencyEdge]) {
    let node_set: HashSet<String> = nodes.iter().cloned().collect();
    let graph = graph_builder::build_graph(&node_set, edges);
    let cycle_count = scoring::count_cycles_public(&graph);

    if cycle_count == 0 {
        println!("  Cyclic Dependencies: None — DAG structure is maintained.");
    } else {
        println!("  Cyclic Dependencies: {cycle_count} cycle(s) detected.");
        println!("     Cycles increase architectural complexity and make refactoring harder.");
    }
}

fn print_recommendations(drift: &Option<DriftScore>) {
    println!("  Recommendations:");

    let Some(d) = drift else {
        println!("   No drift score calculated — run 'morpharch scan' first.");
        return;
    };

    let mut suggestions = Vec::new();

    if d.cycle_debt > 20.0 {
        suggestions.push(format!(
            "   {} circular dependency group(s) detected (score: {:.0}/100). \
             Some modules depend on each other in loops — breaking these cycles \
             with interfaces or traits will make the code easier to maintain.",
            d.new_cycles, d.cycle_debt
        ));
    }

    if d.layering_debt > 20.0 {
        suggestions.push(format!(
            "   {} extra edge(s) inside dependency cycles (score: {:.0}/100). \
             The dependency flow isn't clean — organizing layers to depend \
             only in one direction would improve clarity.",
            d.layering_violations, d.layering_debt
        ));
    }

    if d.hub_debt > 20.0 {
        suggestions.push(format!(
            "   Some modules are doing too much (score: {:.0}/100). They connect to \
             many others in both directions. Splitting them into smaller, \
             focused modules would reduce the blast radius of changes.",
            d.hub_debt
        ));
    }

    if d.coupling_debt > 20.0 {
        suggestions.push(format!(
            "   Modules are more tightly connected than expected (score: {:.0}/100). \
             Adding abstractions between heavily coupled modules would \
             improve flexibility and make changes safer.",
            d.coupling_debt
        ));
    }

    if d.cognitive_debt > 20.0 {
        suggestions.push(format!(
            "   The dependency structure is complex (score: {:.0}/100). \
             There are more connections than needed. Simplifying the wiring \
             would make the architecture easier to understand and navigate.",
            d.cognitive_debt
        ));
    }

    if d.instability_debt > 20.0 {
        suggestions.push(format!(
            "   Some core modules are fragile (score: {:.0}/100). They depend \
             heavily on others, so upstream changes may cascade through them. \
             Adding abstractions would help stabilize them.",
            d.instability_debt
        ));
    }

    if d.total <= 15 {
        suggestions.push(
            "   Architecture looks great — clean structure with minimal coupling.".to_string(),
        );
    } else if d.total <= 30 {
        suggestions
            .push("   Overall healthy architecture with minor areas for improvement.".to_string());
    }

    if suggestions.is_empty() {
        suggestions.push("   Architecture is in an acceptable state.".to_string());
    }

    for suggestion in &suggestions {
        println!("{suggestion}");
    }
}

fn print_blast_radius(snapshot: &crate::models::GraphSnapshot) {
    println!("  ── Blast Radius Analysis ──");
    println!();

    match &snapshot.blast_radius {
        Some(br) => {
            // Articulation points
            if br.articulation_points.is_empty() {
                println!("     Structural Keystones: None — graph has good redundancy.");
            } else {
                println!(
                    "     Structural Keystones ({} found):",
                    br.articulation_points.len()
                );
                for (i, ap) in br.articulation_points.iter().enumerate().take(5) {
                    println!(
                        "       {}. {} (bridges {} components, {}in/{}out)",
                        i + 1,
                        ap.module_name,
                        ap.components_bridged,
                        ap.fan_in,
                        ap.fan_out
                    );
                }
            }
            println!();

            // Top impact modules
            println!("     Highest Impact Modules:");
            for (i, m) in br.impacts.iter().take(5).enumerate() {
                let ap_marker = if m.is_articulation_point {
                    " [keystone]"
                } else {
                    ""
                };
                println!(
                    "       {}. {}{:.0}% blast radius ({} downstream){}",
                    i + 1,
                    m.module_name,
                    m.blast_score * 100.0,
                    m.downstream_count,
                    ap_marker,
                );
            }
            println!();

            // Critical paths
            if !br.critical_paths.is_empty() {
                println!("     Critical Dependency Chains:");
                for (i, path) in br.critical_paths.iter().take(3).enumerate() {
                    println!(
                        "       {}. {} (depth {}, weight {})",
                        i + 1,
                        path.chain.join(""),
                        path.depth,
                        path.total_weight,
                    );
                }
            }
        }
        None => {
            println!("     Not computed. Re-scan to generate blast radius data.");
        }
    }
}