repotoire 0.7.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Benchmark display formatting for ecosystem context output.

use serde::Serialize;

#[derive(Serialize)]
pub struct EcosystemContext {
    pub score_percentile: f64,
    pub comparison_group: String,
    pub sample_size: u64,
    pub pillar_percentiles: Option<PillarPercentiles>,
    pub modularity_percentile: Option<f64>,
    pub coupling_percentile: Option<f64>,
    pub trend: Option<TrendInfo>,
}

#[derive(Serialize)]
pub struct PillarPercentiles {
    pub structure: f64,
    pub quality: f64,
    pub architecture: f64,
}

#[derive(Serialize)]
pub struct TrendInfo {
    pub score_delta: f64,
    pub ecosystem_avg_improvement: f64,
}

/// Format a number with comma separators (e.g. 1247 → "1,247").
fn format_number(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, ch) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.push(',');
        }
        result.push(ch);
    }
    result.chars().rev().collect()
}

/// Convert a percentile value to a "top N%" string.
/// A percentile of 70.0 means "better than 70%" → top 30%.
/// Clamps to "top 1%" (never "top 0%") and "top 99%" (never "top 100%").
fn percentile_to_top(p: f64) -> String {
    let top = (100.0 - p).round() as u64;
    let clamped = top.clamp(1, 99);
    format!("top {}%", clamped)
}

/// Render the compact "Ecosystem Context" box shown after analysis.
pub fn format_ecosystem_context(ctx: &EcosystemContext) -> String {
    let border = "".repeat(51);
    let header = format!("── Ecosystem Context ──{}", "".repeat(29));
    let footer = border.clone();

    // Clamp percentile to 1-99 range
    let pct = (ctx.score_percentile.round() as u64).clamp(1, 99);

    // Add "early data" qualifier for small samples
    let qualifier = if ctx.sample_size < 50 {
        " (early data — limited sample)"
    } else {
        ""
    };

    let score_line = format!(
        "  Score:         better than {}% of {}{}",
        pct, ctx.comparison_group, qualifier
    );

    let mut lines = vec![header, score_line];

    if let Some(ref pillars) = ctx.pillar_percentiles {
        let pillar_line = format!(
            "  Structure:     {}  |  Quality: {}  |  Architecture: {}",
            percentile_to_top(pillars.structure),
            percentile_to_top(pillars.quality),
            percentile_to_top(pillars.architecture),
        );
        lines.push(pillar_line);
    }

    if let Some(mod_p) = ctx.modularity_percentile {
        let mod_line = format!(
            "  Modularity:    {} for projects your size",
            percentile_to_top(mod_p)
        );
        lines.push(mod_line);
    }

    if let Some(coup_p) = ctx.coupling_percentile {
        let coup_line = format!(
            "  Coupling:      lower than {}% — well-decoupled",
            coup_p.round() as u64
        );
        lines.push(coup_line);
    }

    if let Some(ref trend) = ctx.trend {
        let sign = if trend.score_delta >= 0.0 { "+" } else { "" };
        let trend_line = format!(
            "  Trend:         {}{:.1} since last analysis (avg across ecosystem: {:.1})",
            sign, trend.score_delta, trend.ecosystem_avg_improvement
        );
        lines.push(trend_line);
    }

    lines.push(String::new());
    lines.push(format!(
        "  Compared against {} {} (last 90 days)",
        format_number(ctx.sample_size),
        ctx.comparison_group
    ));
    lines.push(footer);

    lines.join("\n")
}

/// Shown when fewer than 50 repos exist in the segment.
pub fn format_insufficient_data(segment_name: &str) -> String {
    let header = format!("── Ecosystem Context ──{}", "".repeat(29));
    let footer = "".repeat(51);
    format!(
        "{}\n  Not enough data for {} yet.\n  Your analyses help build these benchmarks.\n{}",
        header, segment_name, footer
    )
}

/// Shown when telemetry is off.
pub fn format_telemetry_tip() -> String {
    "  Tip: Enable telemetry to see how your project compares\n       to the ecosystem. Run: repotoire config telemetry on"
        .to_string()
}

/// Footer line shown when telemetry is enabled.
pub fn format_telemetry_footer() -> String {
    "  telemetry: on (repotoire config telemetry off to disable)".to_string()
}

/// Full `repotoire benchmark` command output (longer form).
///
/// Renders ecosystem context plus detailed sections for graph health,
/// top findings, detector accuracy, and trend history.
pub fn format_benchmark_full(
    ctx: &EcosystemContext,
    data: &crate::telemetry::benchmarks::BenchmarkData,
    score_history: Option<&[crate::telemetry::cache::ScoreEntry]>,
) -> String {
    let mut sections = vec![format_ecosystem_context(ctx)];
    let border = "───────────────────────────────────────────────────";

    // Graph Health
    {
        let mod_pct = crate::telemetry::benchmarks::interpolate_percentile(
            ctx.modularity_percentile.unwrap_or(0.0),
            &data.graph_modularity,
        );
        let deg_pct = crate::telemetry::benchmarks::interpolate_percentile(
            ctx.coupling_percentile.unwrap_or(0.0),
            &data.graph_avg_degree,
        );
        let scc_pct = data.graph_scc_count.pct_zero;
        let mut lines = vec!["── Graph Health ───────────────────────────────────".to_string()];
        lines.push(format!("  Modularity:      {}", percentile_to_top(mod_pct)));
        lines.push(format!("  Avg degree:      {}", percentile_to_top(deg_pct)));
        lines.push(format!(
            "  Cycle-free:      {:.0}% of projects have zero SCCs",
            scc_pct * 100.0
        ));
        lines.push(border.to_string());
        sections.push(lines.join("\n"));
    }

    // Top Findings
    {
        let mut lines = vec!["── Top Findings ───────────────────────────────────".to_string()];
        if data.top_detectors.is_empty() {
            lines.push("  (no detector data available)".to_string());
        } else {
            for det in data.top_detectors.iter().take(10) {
                lines.push(format!(
                    "  {:<32} {:.0}% of repos",
                    det.name,
                    det.pct_repos_with_findings * 100.0
                ));
            }
        }
        lines.push(border.to_string());
        sections.push(lines.join("\n"));
    }

    // Detector Accuracy
    {
        let mut lines = vec!["── Detector Accuracy ──────────────────────────────".to_string()];
        if data.detector_accuracy.is_empty() {
            lines.push("  (no accuracy data available)".to_string());
        } else {
            for acc in data.detector_accuracy.iter().take(10) {
                lines.push(format!(
                    "  {:<32} TP rate: {:.0}%  ({} feedback)",
                    acc.name,
                    acc.true_positive_rate * 100.0,
                    acc.feedback_count
                ));
            }
        }
        lines.push(border.to_string());
        sections.push(lines.join("\n"));
    }

    // Trend History
    {
        let mut lines = vec!["── Trend History ──────────────────────────────────".to_string()];
        match score_history {
            Some(entries) if !entries.is_empty() => {
                for entry in entries.iter().rev().take(10) {
                    lines.push(format!(
                        "  {}   score: {:.1}",
                        entry.timestamp.format("%Y-%m-%d"),
                        entry.score
                    ));
                }
                lines.push(format!(
                    "  Ecosystem avg improvement/analysis: {:.2}",
                    data.avg_improvement_per_analysis
                ));
            }
            _ => {
                lines.push("  (no trend history yet — run more analyses)".to_string());
            }
        }
        lines.push(border.to_string());
        sections.push(lines.join("\n"));
    }

    sections.push(format_telemetry_footer());

    sections.join("\n\n")
}

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

    #[test]
    fn test_format_number() {
        assert_eq!(format_number(0), "0");
        assert_eq!(format_number(999), "999");
        assert_eq!(format_number(1000), "1,000");
        assert_eq!(format_number(1247), "1,247");
        assert_eq!(format_number(1_000_000), "1,000,000");
    }

    #[test]
    fn test_percentile_to_top() {
        assert_eq!(percentile_to_top(70.0), "top 30%");
        assert_eq!(percentile_to_top(85.0), "top 15%");
        assert_eq!(percentile_to_top(80.0), "top 20%");
        // Edge cases: never show 0% or 100%
        assert_eq!(percentile_to_top(100.0), "top 1%");
        assert_eq!(percentile_to_top(0.0), "top 99%");
        assert_eq!(percentile_to_top(99.9), "top 1%");
    }

    #[test]
    fn test_format_ecosystem_context_basic() {
        let ctx = EcosystemContext {
            score_percentile: 68.0,
            comparison_group: "Rust projects".into(),
            sample_size: 1247,
            pillar_percentiles: Some(PillarPercentiles {
                structure: 70.0,
                quality: 45.0,
                architecture: 80.0,
            }),
            modularity_percentile: Some(85.0),
            coupling_percentile: Some(60.0),
            trend: None,
        };
        let output = format_ecosystem_context(&ctx);
        assert!(output.contains("better than 68%"));
        assert!(output.contains("Rust projects"));
        assert!(output.contains("1,247"));
    }

    #[test]
    fn test_format_ecosystem_context_pillars() {
        let ctx = EcosystemContext {
            score_percentile: 68.0,
            comparison_group: "Rust projects".into(),
            sample_size: 500,
            pillar_percentiles: Some(PillarPercentiles {
                structure: 70.0,
                quality: 45.0,
                architecture: 80.0,
            }),
            modularity_percentile: None,
            coupling_percentile: None,
            trend: None,
        };
        let output = format_ecosystem_context(&ctx);
        assert!(output.contains("top 30%")); // structure: 100 - 70
        assert!(output.contains("top 55%")); // quality: 100 - 45
        assert!(output.contains("top 20%")); // architecture: 100 - 80
    }

    #[test]
    fn test_early_data_qualifier() {
        let ctx = EcosystemContext {
            score_percentile: 95.0,
            comparison_group: "rust projects".into(),
            sample_size: 6, // small sample
            pillar_percentiles: None,
            modularity_percentile: None,
            coupling_percentile: None,
            trend: None,
        };
        let output = format_ecosystem_context(&ctx);
        assert!(
            output.contains("early data"),
            "Small samples should show early data qualifier"
        );
        assert!(
            output.contains("limited sample"),
            "Small samples should show limited sample note"
        );
        assert!(
            output.contains("better than 95%"),
            "Should show clamped percentile"
        );
    }

    #[test]
    fn test_no_early_data_for_large_samples() {
        let ctx = EcosystemContext {
            score_percentile: 68.0,
            comparison_group: "rust projects".into(),
            sample_size: 100,
            pillar_percentiles: None,
            modularity_percentile: None,
            coupling_percentile: None,
            trend: None,
        };
        let output = format_ecosystem_context(&ctx);
        assert!(
            !output.contains("early data"),
            "Large samples should not show qualifier"
        );
    }

    #[test]
    fn test_format_insufficient_data() {
        let output = format_insufficient_data("Rust workspace");
        assert!(output.contains("Not enough data"));
        assert!(output.contains("Rust workspace"));
    }

    #[test]
    fn test_format_telemetry_tip() {
        let output = format_telemetry_tip();
        assert!(output.contains("repotoire config telemetry on"));
    }

    #[test]
    fn test_format_telemetry_footer() {
        let output = format_telemetry_footer();
        assert!(output.contains("telemetry: on"));
        assert!(output.contains("repotoire config telemetry off"));
    }

    #[test]
    fn test_format_with_trend() {
        let ctx = EcosystemContext {
            score_percentile: 68.0,
            comparison_group: "Rust projects".into(),
            sample_size: 500,
            pillar_percentiles: None,
            modularity_percentile: None,
            coupling_percentile: None,
            trend: Some(TrendInfo {
                score_delta: 4.2,
                ecosystem_avg_improvement: 1.8,
            }),
        };
        let output = format_ecosystem_context(&ctx);
        assert!(output.contains("+4.2"));
        assert!(output.contains("1.8"));
    }

    #[test]
    fn test_format_with_negative_trend() {
        let ctx = EcosystemContext {
            score_percentile: 40.0,
            comparison_group: "Go projects".into(),
            sample_size: 200,
            pillar_percentiles: None,
            modularity_percentile: None,
            coupling_percentile: None,
            trend: Some(TrendInfo {
                score_delta: -2.5,
                ecosystem_avg_improvement: 0.5,
            }),
        };
        let output = format_ecosystem_context(&ctx);
        assert!(output.contains("-2.5"));
        // negative delta should not have a leading '+'
        assert!(!output.contains("+-2.5"));
    }

    #[test]
    fn test_format_benchmark_full_contains_ecosystem() {
        use crate::telemetry::benchmarks::*;
        let ctx = EcosystemContext {
            score_percentile: 75.0,
            comparison_group: "TypeScript projects".into(),
            sample_size: 3000,
            pillar_percentiles: None,
            modularity_percentile: None,
            coupling_percentile: None,
            trend: None,
        };
        let data = BenchmarkData {
            schema_version: 1,
            segment: BenchmarkSegment {
                language: Some("TypeScript".into()),
                kloc_bucket: None,
            },
            sample_size: 3000,
            updated_at: "2026-01-01".into(),
            score: PercentileDistribution {
                p25: 40.0,
                p50: 55.0,
                p75: 70.0,
                p90: 85.0,
            },
            pillar_structure: PercentileDistribution {
                p25: 40.0,
                p50: 55.0,
                p75: 70.0,
                p90: 85.0,
            },
            pillar_quality: PercentileDistribution {
                p25: 40.0,
                p50: 55.0,
                p75: 70.0,
                p90: 85.0,
            },
            pillar_architecture: PercentileDistribution {
                p25: 40.0,
                p50: 55.0,
                p75: 70.0,
                p90: 85.0,
            },
            graph_modularity: PercentileDistribution {
                p25: 0.2,
                p50: 0.4,
                p75: 0.6,
                p90: 0.8,
            },
            graph_avg_degree: PercentileDistribution {
                p25: 1.0,
                p50: 2.0,
                p75: 3.0,
                p90: 5.0,
            },
            graph_scc_count: SccDistribution {
                pct_zero: 0.65,
                p50: 1.0,
                p75: 3.0,
                p90: 7.0,
            },
            grade_distribution: std::collections::HashMap::new(),
            top_detectors: vec![DetectorStat {
                name: "god-class".into(),
                pct_repos_with_findings: 0.42,
            }],
            detector_accuracy: vec![DetectorAccuracy {
                name: "god-class".into(),
                true_positive_rate: 0.88,
                feedback_count: 150,
            }],
            avg_improvement_per_analysis: 1.2,
        };
        let output = format_benchmark_full(&ctx, &data, None);
        assert!(output.contains("Ecosystem Context"));
        assert!(output.contains("better than 75%"));
        assert!(output.contains("3,000"));
        assert!(output.contains("telemetry: on"));
        assert!(output.contains("Graph Health"));
        assert!(output.contains("god-class"));
    }
}