pmat 3.30.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
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
//! Architectural bottleneck detection handler
//!
//! Analyzes git history to find files with disproportionate churn
//! that indicate registry/dispatch architectural bottlenecks.

use anyhow::Result;
use std::collections::HashMap;
use std::path::Path;

/// Git churn data: (file touch counts, commit file groups, total commits)
type GitChurnData = (HashMap<String, usize>, Vec<Vec<String>>, usize);

/// Largest lookback git's approxidate parser handles reliably.
///
/// `--since=<n> days ago` silently stops matching anything once the resulting
/// date crosses the Unix epoch — measured here, 20 000 days (≈1971) still
/// returns every commit and 21 000 returns none. That is why `--period
/// 99999999` reported "Total commits: 0" for a repository with one commit while
/// `--period 100000` reported 1 (GH #665): a *larger* window matched *fewer*
/// commits, and the empty result was printed as a legitimate zero.
const MAX_LOOKBACK_DAYS: u32 = 20_000;

/// `--since` argument for a user-supplied lookback.
///
/// `None` means "no `--since` at all" — a lookback past the epoch is a request
/// for the whole history, and asking git for the whole history is exactly how
/// you get the whole history. See
/// `contracts/pmat-no-fabrication-v1.yaml`, equation `bounded_time_arithmetic`.
fn since_arg(period: u32) -> Option<String> {
    (period <= MAX_LOOKBACK_DAYS).then(|| format!("--since={period} days ago"))
}

/// `git log` argument list with the lookback applied.
fn git_log_args(period: u32, extra: &[&str]) -> Vec<String> {
    let mut args = vec!["log".to_string()];
    args.extend(since_arg(period));
    args.extend(extra.iter().map(|s| (*s).to_string()));
    args
}

/// A detected bottleneck file
#[derive(Debug, serde::Serialize)]
struct BottleneckFile {
    path: String,
    touches: usize,
    authors: usize,
    lines: usize,
    churn_ratio: f64,
    pattern: String,
    recommendation: String,
}

/// Co-change coupling between files
#[derive(Debug, serde::Serialize)]
struct CouplingPair {
    file_a: String,
    file_b: String,
    co_changes: usize,
}

/// Full bottleneck analysis result
#[derive(Debug, serde::Serialize)]
struct BottleneckAnalysis {
    period_days: u32,
    total_commits: usize,
    total_files_changed: usize,
    bottlenecks: Vec<BottleneckFile>,
    couplings: Vec<CouplingPair>,
}

/// Handle the bottleneck analysis command
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_bottleneck(
    path: &Path,
    format: &crate::cli::enums::OutputFormat,
    period: u32,
    threshold: usize,
    output: Option<&Path>,
) -> Result<()> {
    use crate::cli::colors as c;

    crate::status_eprintln!(
        "{}",
        c::dim(&format!("Analyzing git churn for last {} days...", period))
    );

    let analysis = analyze_bottlenecks(path, period, threshold)?;

    let formatted = format_analysis(&analysis, format)?;

    if let Some(output_path) = output {
        std::fs::write(output_path, &formatted)?;
        crate::status_eprintln!(
            "{} Written to: {}",
            c::pass(""),
            c::path(&output_path.display().to_string())
        );
    } else {
        println!("{formatted}");
    }

    Ok(())
}

/// Main analysis function
fn analyze_bottlenecks(path: &Path, period: u32, threshold: usize) -> Result<BottleneckAnalysis> {
    // Get per-file touch counts from git log
    let (file_touches, commit_files, total_commits) = get_git_churn(path, period)?;

    // Get file sizes
    let file_sizes = get_file_sizes(path, &file_touches)?;

    // Get author counts per file
    let file_authors = get_file_authors(path, period, &file_touches)?;

    // Build bottleneck list
    let mut bottlenecks: Vec<BottleneckFile> = file_touches
        .iter()
        .filter(|(_, &count)| count >= threshold)
        .filter(|(path, _)| !is_generated_file(path))
        .filter(|(file_path, _)| file_sizes.contains_key(file_path.as_str()))
        .map(|(file_path, &touches)| {
            let lines = file_sizes.get(file_path.as_str()).copied().unwrap_or(0);
            let authors = file_authors.get(file_path.as_str()).copied().unwrap_or(1);
            let churn_ratio = if lines > 0 {
                touches as f64 / (lines as f64 / 100.0)
            } else {
                touches as f64
            };
            let pattern = classify_pattern(file_path, touches, lines);
            let recommendation = get_recommendation(&pattern);

            BottleneckFile {
                path: file_path.clone(),
                touches,
                authors,
                lines,
                churn_ratio,
                pattern,
                recommendation,
            }
        })
        .collect();

    // Sort by touches descending. DETERMINISM: `touches` is not a total order
    // (most files tie), the source is a `HashMap`, and `sort_by_key` is stable —
    // so which of the tied files survived `truncate(20)` came out of the
    // process's hash seed. Eight identical runs produced four distinct outputs.
    // Path breaks the tie.
    bottlenecks.sort_by(|a, b| b.touches.cmp(&a.touches).then_with(|| a.path.cmp(&b.path)));
    bottlenecks.truncate(20);

    // Detect co-change coupling
    let couplings = detect_coupling(&commit_files, threshold);

    Ok(BottleneckAnalysis {
        period_days: period,
        total_commits,
        total_files_changed: file_touches.len(),
        bottlenecks,
        couplings,
    })
}

/// Get file touch counts from git log
fn get_git_churn(path: &Path, period: u32) -> Result<GitChurnData> {
    let output = std::process::Command::new("git")
        .args(git_log_args(
            period,
            &["--name-only", "--pretty=format:COMMIT_SEPARATOR"],
        ))
        .current_dir(path)
        .output()?;

    // A failed `git log` used to be parsed as an empty log, so a missing
    // repository or a rejected revision range was reported as a legitimate
    // "Total commits: 0" (GH #665).
    if !output.status.success() {
        anyhow::bail!(
            "git log failed in {}: {}",
            path.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut file_touches: HashMap<String, usize> = HashMap::new();
    let mut commit_files: Vec<Vec<String>> = Vec::new();
    let mut current_files: Vec<String> = Vec::new();
    let mut total_commits = 0;

    for line in stdout.lines() {
        let line = line.trim();
        if line == "COMMIT_SEPARATOR" {
            if !current_files.is_empty() {
                commit_files.push(current_files.clone());
                current_files.clear();
            }
            total_commits += 1;
        } else if !line.is_empty() {
            *file_touches.entry(line.to_string()).or_default() += 1;
            current_files.push(line.to_string());
        }
    }
    if !current_files.is_empty() {
        commit_files.push(current_files);
    }

    Ok((file_touches, commit_files, total_commits))
}

/// Get file line counts
fn get_file_sizes(path: &Path, files: &HashMap<String, usize>) -> Result<HashMap<String, usize>> {
    let mut sizes = HashMap::new();
    for file_path in files.keys() {
        let full_path = path.join(file_path);
        if full_path.exists() {
            if let Ok(content) = std::fs::read_to_string(&full_path) {
                sizes.insert(file_path.clone(), content.lines().count());
            }
        }
    }
    Ok(sizes)
}

/// Get unique author counts per file
fn get_file_authors(
    path: &Path,
    period: u32,
    files: &HashMap<String, usize>,
) -> Result<HashMap<String, usize>> {
    let mut author_map: HashMap<String, std::collections::HashSet<String>> = HashMap::new();

    let output = std::process::Command::new("git")
        .args(git_log_args(period, &["--format=%H %an", "--name-only"]))
        .current_dir(path)
        .output()?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut current_author = String::new();

    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        // Lines with commit hash + author name are 40+ chars with a space
        if line.len() > 41 && line.chars().nth(40) == Some(' ') {
            current_author = line[41..].to_string();
        } else if !current_author.is_empty() && files.contains_key(line) {
            author_map
                .entry(line.to_string())
                .or_default()
                .insert(current_author.clone());
        }
    }

    Ok(author_map.into_iter().map(|(k, v)| (k, v.len())).collect())
}

/// Check if a file is auto-generated
fn is_generated_file(path: &str) -> bool {
    path.contains(".pmat/")
        || path.ends_with("Cargo.lock")
        || path.ends_with(".pmat/baseline.json")
        || path.contains("target/")
        || path.ends_with(".json") && path.contains("cache")
}

/// Classify the churn pattern
fn classify_pattern(path: &str, touches: usize, lines: usize) -> String {
    let filename = path.rsplit('/').next().unwrap_or(path);

    if filename == "mod.rs" || filename.contains("registry") || filename.contains("dispatch") {
        return "Registry/Dispatch".to_string();
    }
    if filename == "Cargo.toml" || filename == "Cargo.lock" {
        return "Dependency Config".to_string();
    }
    if path.contains("workflows/") || path.contains(".github/") {
        return "CI/CD Config".to_string();
    }
    if filename.contains("test") {
        return "Test Churn".to_string();
    }
    if path.contains("roadmap") || path.contains("docs/") {
        return "Documentation".to_string();
    }
    if lines > 500 && touches > 10 {
        return "Monolith".to_string();
    }
    if touches as f64 / lines.max(1) as f64 * 100.0 > 5.0 {
        return "High Churn Ratio".to_string();
    }

    "Feature Development".to_string()
}

/// Get recommendation based on pattern
fn get_recommendation(pattern: &str) -> String {
    match pattern {
        "Registry/Dispatch" => {
            "Consider proc-macro auto-discovery (inventory/linkme) to avoid touching this file for every new feature".to_string()
        }
        "Dependency Config" => {
            "Use workspace inheritance or cargo-edit for batch dependency updates".to_string()
        }
        "CI/CD Config" => {
            "Use reusable workflows and test CI changes locally with `pmat ci-local`".to_string()
        }
        "Monolith" => {
            "Split this file into focused submodules with `pmat split --auto`".to_string()
        }
        "High Churn Ratio" => {
            "This file changes too often relative to its size — consider architectural refactoring"
                .to_string()
        }
        _ => String::new(),
    }
}

/// Detect file co-change coupling
fn detect_coupling(commit_files: &[Vec<String>], min_co_changes: usize) -> Vec<CouplingPair> {
    let mut co_changes: HashMap<(String, String), usize> = HashMap::new();

    for files in commit_files {
        // Only consider commits with 2-10 files (larger commits are usually bulk changes)
        if files.len() < 2 || files.len() > 10 {
            continue;
        }
        for i in 0..files.len() {
            for j in (i + 1)..files.len() {
                let a = &files[i];
                let b = &files[j];
                if a == b {
                    continue;
                }
                let key = if a < b {
                    (a.clone(), b.clone())
                } else {
                    (b.clone(), a.clone())
                };
                *co_changes.entry(key).or_default() += 1;
            }
        }
    }

    let mut pairs: Vec<CouplingPair> = co_changes
        .into_iter()
        .filter(|(_, count)| *count >= min_co_changes)
        .filter(|((a, b), _)| !is_generated_file(a) && !is_generated_file(b))
        .map(|((a, b), count)| CouplingPair {
            file_a: a,
            file_b: b,
            co_changes: count,
        })
        .collect();

    // Same tie-break as `analyze_bottlenecks`: `co_changes` ties constantly and
    // the pairs come out of a `HashMap`, so the surviving 15 were hash-seed
    // dependent.
    pairs.sort_by(|x, y| {
        y.co_changes
            .cmp(&x.co_changes)
            .then_with(|| (&x.file_a, &x.file_b).cmp(&(&y.file_a, &y.file_b)))
    });
    pairs.truncate(15);
    pairs
}

/// Render the analysis in the format the user asked for.
///
/// This used to be `match format { Json => .., _ => format_text() }`: eight of
/// the nine formats `--help` advertises fell through the catch-all, so
/// `-f csv`, `-f yaml` and `-f junit` all wrote the same ANSI-decorated table
/// into files that were supposed to be CSV, YAML and JUnit XML — byte-identical
/// output for every one of them.
fn format_analysis(
    analysis: &BottleneckAnalysis,
    format: &crate::cli::enums::OutputFormat,
) -> Result<String> {
    use crate::cli::enums::OutputFormat as F;
    Ok(match format {
        F::Json => serde_json::to_string_pretty(analysis)?,
        F::Yaml => serde_yaml_ng::to_string(analysis)?,
        F::Markdown => format_markdown(analysis),
        F::Csv => format_csv(analysis),
        F::Junit => format_junit(analysis),
        F::Summary => format_summary(analysis),
        // The colour-free twins of the table: a redirected `-f text` had ANSI
        // escapes in it.
        F::Text | F::Plain => strip_ansi(&format_text(analysis)),
        F::Table => format_text(analysis),
    })
}

/// Drop SGR escape sequences — for the formats that promise plain text.
fn strip_ansi(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars();
    while let Some(ch) = chars.next() {
        if ch == '\u{1b}' {
            for esc in chars.by_ref() {
                if esc.is_ascii_alphabetic() {
                    break;
                }
            }
            continue;
        }
        out.push(ch);
    }
    out
}

/// One CSV field, quoted per RFC 4180 when it has to be.
fn csv_field(value: &str) -> String {
    if value.contains([',', '"', '\n']) {
        format!("\"{}\"", value.replace('"', "\"\""))
    } else {
        value.to_string()
    }
}

/// CSV: the bottleneck rows, then the coupling rows as a second block with its
/// own header (a spreadsheet reads the first block; `csvkit` reads both).
fn format_csv(analysis: &BottleneckAnalysis) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let _ = writeln!(
        out,
        "path,touches,authors,lines,churn_ratio,pattern,recommendation"
    );
    for b in &analysis.bottlenecks {
        let _ = writeln!(
            out,
            "{},{},{},{},{:.1},{},{}",
            csv_field(&b.path),
            b.touches,
            b.authors,
            b.lines,
            b.churn_ratio,
            csv_field(&b.pattern),
            csv_field(&b.recommendation)
        );
    }
    if !analysis.couplings.is_empty() {
        let _ = writeln!(out);
        let _ = writeln!(out, "file_a,file_b,co_changes");
        for pair in &analysis.couplings {
            let _ = writeln!(
                out,
                "{},{},{}",
                csv_field(&pair.file_a),
                csv_field(&pair.file_b),
                pair.co_changes
            );
        }
    }
    out
}

/// Markdown report.
fn format_markdown(analysis: &BottleneckAnalysis) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let _ = writeln!(out, "# Architectural Bottleneck Analysis\n");
    let _ = writeln!(out, "- **Period**: {} days", analysis.period_days);
    let _ = writeln!(out, "- **Total commits**: {}", analysis.total_commits);
    let _ = writeln!(
        out,
        "- **Files changed**: {}\n",
        analysis.total_files_changed
    );

    if analysis.bottlenecks.is_empty() {
        let _ = writeln!(out, "No bottleneck files detected.\n");
    } else {
        let _ = writeln!(out, "## Bottleneck Files\n");
        let _ = writeln!(
            out,
            "| File | Touches | Authors | Lines | Churn ratio | Pattern | Recommendation |"
        );
        let _ = writeln!(out, "|---|---|---|---|---|---|---|");
        for b in &analysis.bottlenecks {
            let _ = writeln!(
                out,
                "| `{}` | {} | {} | {} | {:.1} | {} | {} |",
                b.path, b.touches, b.authors, b.lines, b.churn_ratio, b.pattern, b.recommendation
            );
        }
        let _ = writeln!(out);
    }

    if !analysis.couplings.is_empty() {
        let _ = writeln!(out, "## Co-Change Coupling\n");
        let _ = writeln!(out, "| File A | File B | Co-changes |");
        let _ = writeln!(out, "|---|---|---|");
        for pair in &analysis.couplings {
            let _ = writeln!(
                out,
                "| `{}` | `{}` | {} |",
                pair.file_a, pair.file_b, pair.co_changes
            );
        }
    }
    out
}

/// Three lines, no decoration.
fn format_summary(analysis: &BottleneckAnalysis) -> String {
    format!(
        "period_days={}\ncommits={}\nfiles_changed={}\nbottlenecks={}\ncouplings={}\n",
        analysis.period_days,
        analysis.total_commits,
        analysis.total_files_changed,
        analysis.bottlenecks.len(),
        analysis.couplings.len()
    )
}

fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

/// JUnit XML: every detected bottleneck is a failing testcase, so CI can gate
/// on it.
fn format_junit(analysis: &BottleneckAnalysis) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let tests = analysis.bottlenecks.len() + analysis.couplings.len();
    let _ = writeln!(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    let _ = writeln!(
        out,
        "<testsuites name=\"Architectural Bottlenecks\" tests=\"{tests}\" failures=\"{tests}\">"
    );
    let _ = writeln!(
        out,
        "  <testsuite name=\"Bottleneck Files\" tests=\"{}\" failures=\"{}\">",
        analysis.bottlenecks.len(),
        analysis.bottlenecks.len()
    );
    for b in &analysis.bottlenecks {
        let _ = writeln!(
            out,
            "    <testcase name=\"{}\" classname=\"Bottleneck\">",
            xml_escape(&b.path)
        );
        let _ = writeln!(
            out,
            "      <failure message=\"{} ({} touches, {} lines, churn ratio {:.1})\">{}</failure>",
            xml_escape(&b.pattern),
            b.touches,
            b.lines,
            b.churn_ratio,
            xml_escape(&b.recommendation)
        );
        let _ = writeln!(out, "    </testcase>");
    }
    let _ = writeln!(out, "  </testsuite>");
    let _ = writeln!(
        out,
        "  <testsuite name=\"Co-Change Coupling\" tests=\"{}\" failures=\"{}\">",
        analysis.couplings.len(),
        analysis.couplings.len()
    );
    for pair in &analysis.couplings {
        let _ = writeln!(
            out,
            "    <testcase name=\"{} &lt;-&gt; {}\" classname=\"Coupling\">",
            xml_escape(&pair.file_a),
            xml_escape(&pair.file_b)
        );
        let _ = writeln!(
            out,
            "      <failure message=\"{} co-changes\" />",
            pair.co_changes
        );
        let _ = writeln!(out, "    </testcase>");
    }
    let _ = writeln!(out, "  </testsuite>");
    let _ = writeln!(out, "</testsuites>");
    out
}

/// Format results as colorized text
fn format_text(analysis: &BottleneckAnalysis) -> String {
    use crate::cli::colors as c;
    use std::fmt::Write;

    let mut out = String::new();

    let _ = writeln!(out, "{}\n", c::header("Architectural Bottleneck Analysis"));
    let _ = writeln!(
        out,
        "  {}Period:{} {} days",
        c::BOLD,
        c::RESET,
        c::number(&analysis.period_days.to_string())
    );
    let _ = writeln!(
        out,
        "  {}Total commits:{} {}",
        c::BOLD,
        c::RESET,
        c::number(&analysis.total_commits.to_string())
    );
    let _ = writeln!(
        out,
        "  {}Files changed:{} {}\n",
        c::BOLD,
        c::RESET,
        c::number(&analysis.total_files_changed.to_string())
    );

    if analysis.bottlenecks.is_empty() {
        let _ = writeln!(out, "  {}", c::pass("No bottleneck files detected"));
        return out;
    }

    let _ = writeln!(out, "{}\n", c::subheader("Bottleneck Files"));

    for (i, b) in analysis.bottlenecks.iter().enumerate() {
        let pattern_color = match b.pattern.as_str() {
            "Registry/Dispatch" | "Monolith" => c::RED,
            "CI/CD Config" | "High Churn Ratio" => c::YELLOW,
            _ => c::DIM,
        };
        let _ = writeln!(
            out,
            "  {}. {} {}({})",
            c::number(&(i + 1).to_string()),
            c::path(&b.path),
            pattern_color,
            b.pattern,
        );
        let _ = writeln!(
            out,
            "{}     {}Touches:{} {}  {}Authors:{} {}  {}Lines:{} {}  {}Churn ratio:{} {:.1}",
            c::RESET,
            c::BOLD,
            c::RESET,
            c::number(&b.touches.to_string()),
            c::BOLD,
            c::RESET,
            c::number(&b.authors.to_string()),
            c::BOLD,
            c::RESET,
            c::number(&b.lines.to_string()),
            c::BOLD,
            c::RESET,
            b.churn_ratio,
        );
        if !b.recommendation.is_empty() {
            let _ = writeln!(
                out,
                "     {}Recommendation:{} {}",
                c::BOLD,
                c::RESET,
                b.recommendation
            );
        }
        let _ = writeln!(out);
    }

    if !analysis.couplings.is_empty() {
        let _ = writeln!(out, "{}\n", c::subheader("Co-Change Coupling"));
        for pair in &analysis.couplings {
            let _ = writeln!(
                out,
                "  {} <-> {} ({} co-changes)",
                c::path(&pair.file_a),
                c::path(&pair.file_b),
                c::number(&pair.co_changes.to_string()),
            );
        }
    }

    out
}

/// `analyze bottleneck --quiet` was byte-identical to `analyze bottleneck`.
///
/// On the flag-efficacy gate's ~120-file corpus the command wrote 40 bytes of
/// "Analyzing git churn for last 30 days..." to stderr through an unguarded
/// stderr macro, so no suppression rule could reach it. Both status lines in
/// this handler now go through `status_eprintln!`, i.e. through
/// `cli::progress::quiet_mode_enabled` — the one predicate. The report itself
/// keeps going to stdout unconditionally.
#[cfg(test)]
pub(crate) mod quiet_chatter_tests {
    /// Lines carrying an *unguarded* stderr status macro.
    ///
    /// The needle is assembled at compile time so this probe cannot match its
    /// own source. `status_eprintln!` ends in `_` immediately before the
    /// needle, which is what distinguishes a guarded call from a bare one.
    pub(crate) fn unguarded_stderr_lines(source: &str) -> Vec<&str> {
        let needle = concat!("eprint", "ln!");
        source
            .lines()
            .filter(|line| {
                let mut from = 0;
                while let Some(i) = line[from..].find(needle) {
                    let at = from + i;
                    if !line[..at].ends_with('_') {
                        return true;
                    }
                    from = at + needle.len();
                }
                false
            })
            .collect()
    }

    #[test]
    fn churn_banner_obeys_quiet() {
        let source = include_str!("bottleneck_handler.rs");
        assert!(
            source.contains("Analyzing git churn for last"),
            "the banner this test pins must still exist"
        );
        let leaking = unguarded_stderr_lines(source);
        assert!(
            leaking.is_empty(),
            "bottleneck's stderr is chatter only, so every line must be \
             suppressible; unguarded: {leaking:?}"
        );
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_classify_pattern_registry() {
        assert_eq!(
            classify_pattern("src/commands/mod.rs", 10, 50),
            "Registry/Dispatch"
        );
        assert_eq!(
            classify_pattern("src/registry.rs", 5, 100),
            "Registry/Dispatch"
        );
        assert_eq!(
            classify_pattern("src/dispatch.rs", 5, 100),
            "Registry/Dispatch"
        );
    }

    #[test]
    fn test_classify_pattern_cargo() {
        assert_eq!(classify_pattern("Cargo.toml", 10, 50), "Dependency Config");
    }

    #[test]
    fn test_classify_pattern_ci() {
        assert_eq!(
            classify_pattern(".github/workflows/ci.yml", 7, 100),
            "CI/CD Config"
        );
    }

    #[test]
    fn test_classify_pattern_monolith() {
        assert_eq!(classify_pattern("src/big_file.rs", 12, 800), "Monolith");
    }

    #[test]
    fn test_is_generated_file() {
        assert!(is_generated_file(".pmat/baseline.json"));
        assert!(is_generated_file("Cargo.lock"));
        assert!(!is_generated_file("src/main.rs"));
    }

    #[test]
    fn test_get_recommendation() {
        let rec = get_recommendation("Registry/Dispatch");
        assert!(rec.contains("proc-macro"));

        let rec = get_recommendation("Monolith");
        assert!(rec.contains("split"));
    }

    #[test]
    fn test_detect_coupling_empty() {
        let pairs = detect_coupling(&[], 3);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_detect_coupling_below_threshold() {
        let commits = vec![vec!["a.rs".to_string(), "b.rs".to_string()]];
        let pairs = detect_coupling(&commits, 3);
        assert!(pairs.is_empty());
    }

    #[test]
    fn test_detect_coupling_above_threshold() {
        let commits = vec![
            vec!["a.rs".to_string(), "b.rs".to_string()],
            vec!["a.rs".to_string(), "b.rs".to_string()],
            vec!["a.rs".to_string(), "b.rs".to_string()],
        ];
        let pairs = detect_coupling(&commits, 3);
        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0].co_changes, 3);
    }

    #[test]
    fn test_format_text_empty() {
        let analysis = BottleneckAnalysis {
            period_days: 14,
            total_commits: 0,
            total_files_changed: 0,
            bottlenecks: vec![],
            couplings: vec![],
        };
        let text = format_text(&analysis);
        assert!(text.contains("No bottleneck files detected"));
    }

    #[tokio::test]
    async fn test_handle_bottleneck_runs() {
        // Just verify it doesn't panic on the actual repo
        let result = handle_bottleneck(
            Path::new("."),
            &crate::cli::enums::OutputFormat::Json,
            14,
            5,
            None,
        )
        .await;
        assert!(result.is_ok());
    }

    fn sample_analysis() -> BottleneckAnalysis {
        BottleneckAnalysis {
            period_days: 30,
            total_commits: 13,
            total_files_changed: 709,
            bottlenecks: vec![BottleneckFile {
                path: "src/cli/mod.rs".to_string(),
                touches: 9,
                authors: 2,
                lines: 1200,
                churn_ratio: 0.75,
                pattern: "Registry/Dispatch".to_string(),
                recommendation: "Consider proc-macro auto-discovery, e.g. inventory".to_string(),
            }],
            couplings: vec![CouplingPair {
                file_a: "a.rs".to_string(),
                file_b: "b.rs".to_string(),
                co_changes: 4,
            }],
        }
    }

    /// `--help` advertises nine formats; eight of them fell through a catch-all
    /// arm and emitted the SAME ANSI table (956 bytes each), so `-f csv` wrote
    /// escape sequences into a .csv and `-f junit` was not XML.
    #[test]
    fn every_advertised_format_renders_itself() {
        use crate::cli::enums::OutputFormat as F;
        let analysis = sample_analysis();

        let yaml = format_analysis(&analysis, &F::Yaml).unwrap();
        let parsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&yaml).expect("valid yaml");
        assert_eq!(parsed["total_commits"].as_u64(), Some(13));

        let csv = format_analysis(&analysis, &F::Csv).unwrap();
        assert!(csv.starts_with("path,touches,authors,lines,churn_ratio,pattern,recommendation\n"));
        assert!(csv.contains("src/cli/mod.rs,9,2,1200,0.8,Registry/Dispatch,"));
        assert!(csv.contains("file_a,file_b,co_changes\na.rs,b.rs,4"));

        let junit = format_analysis(&analysis, &F::Junit).unwrap();
        assert!(junit.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
        assert!(junit.contains("<testsuites"));
        assert!(junit.contains("src/cli/mod.rs"));

        let md = format_analysis(&analysis, &F::Markdown).unwrap();
        assert!(md.starts_with("# Architectural Bottleneck Analysis"));
        assert!(md.contains("| `src/cli/mod.rs` | 9 |"));

        let summary = format_analysis(&analysis, &F::Summary).unwrap();
        assert!(summary.contains("bottlenecks=1"));

        let json = format_analysis(&analysis, &F::Json).unwrap();
        let _: serde_json::Value = serde_json::from_str(&json).expect("valid json");

        // No two formats may be byte-identical, and only the table may carry
        // colour.
        for (name, rendered) in [
            ("yaml", &yaml),
            ("csv", &csv),
            ("junit", &junit),
            ("markdown", &md),
            ("summary", &summary),
            ("json", &json),
        ] {
            assert!(
                !rendered.contains('\u{1b}'),
                "{name} carries ANSI escapes: {rendered:?}"
            );
        }
    }

    /// `-f text` / `-f plain` keep the table's shape but must not carry colour
    /// into a redirected file.
    #[test]
    fn text_and_plain_are_the_table_without_escapes() {
        use crate::cli::enums::OutputFormat as F;
        let analysis = sample_analysis();
        let text = format_analysis(&analysis, &F::Text).unwrap();
        let plain = format_analysis(&analysis, &F::Plain).unwrap();
        assert_eq!(text, plain);
        assert!(!text.contains('\u{1b}'), "{text:?}");
        assert!(text.contains("Architectural Bottleneck Analysis"));
        assert!(text.contains("src/cli/mod.rs"));
    }

    /// GH #665: a monotonically larger `--period` must never report fewer
    /// commits. `--since=99999999 days ago` overflowed git's approxidate into a
    /// future date, so the window matched nothing and the swallowed failure was
    /// printed as "Total commits: 0" for a repo that has commits.
    #[test]
    fn since_arg_drops_the_bound_past_the_epoch() {
        assert_eq!(since_arg(30).as_deref(), Some("--since=30 days ago"));
        assert_eq!(
            since_arg(MAX_LOOKBACK_DAYS).as_deref(),
            Some("--since=20000 days ago")
        );
        // Past the epoch git's approxidate stops matching anything, so ask for
        // the whole history instead of an unparseable bound.
        assert_eq!(since_arg(100_000), None);
        assert_eq!(since_arg(99_999_999), None);
        assert_eq!(since_arg(u32::MAX), None);
    }

    #[test]
    fn git_log_args_omit_since_for_a_huge_period() {
        let bounded = git_log_args(30, &["--name-only"]);
        assert_eq!(bounded[0], "log");
        assert_eq!(bounded[1], "--since=30 days ago");
        assert_eq!(bounded[2], "--name-only");

        let unbounded = git_log_args(99_999_999, &["--name-only"]);
        assert_eq!(unbounded, vec!["log", "--name-only"]);
        assert!(!unbounded.iter().any(|a| a.starts_with("--since")));
    }

    /// End-to-end: the count for a huge period must match the count for a
    /// modest one on a repo whose history is entirely inside both windows.
    #[test]
    fn huge_period_reports_the_same_commit_count_as_a_normal_one() {
        use std::process::Command;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let repo = temp.path();
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(repo)
                .output()
                .expect("git must be available")
        };
        if !git(&["init"]).status.success() {
            return;
        }
        let _ = git(&["config", "user.email", "t@example.com"]);
        let _ = git(&["config", "user.name", "T"]);
        std::fs::write(repo.join("a.rs"), "pub fn f() {}\n").unwrap();
        let _ = git(&["add", "-A"]);
        if !git(&["commit", "-m", "init", "--no-verify"])
            .status
            .success()
        {
            return;
        }

        let (_, _, small) = get_git_churn(repo, 30).expect("small window");
        let (_, _, huge) = get_git_churn(repo, 99_999_999).expect("huge window");
        assert_eq!(small, 1, "the fixture repo has exactly one commit");
        assert_eq!(
            huge, small,
            "a larger --period reported fewer commits (pre-fix: 0)"
        );
    }

    // ── determinism ─────────────────────────────────────────────────────────
    //
    // `analyze bottleneck` produced four distinct md5s over eight identical
    // runs: both result lists are built from a `HashMap`, ranked by a key that
    // ties constantly (`touches` / `co_changes`) with a *stable* sort, and then
    // truncated — so which of the tied entries survived came out of the
    // process's hash seed. `RandomState` reseeds per `HashMap` instance, so
    // repeated calls inside one test process reproduce the run-to-run variance.

    /// Enough tied pairs to overflow `truncate(15)`, so an unstable tie-break
    /// changes the *contents*, not just the order.
    fn tied_commits() -> Vec<Vec<String>> {
        (0..30)
            .map(|i| vec!["src/shared.rs".to_string(), format!("src/mod_{i:02}.rs")])
            .collect()
    }

    #[test]
    fn detect_coupling_is_deterministic_across_runs() {
        let commits = tied_commits();
        let first = detect_coupling(&commits, 1);
        assert_eq!(first.len(), 15, "the fixture must exercise the truncation");
        for run in 1..25 {
            let again = detect_coupling(&commits, 1);
            let as_tuples = |p: &[CouplingPair]| {
                p.iter()
                    .map(|c| (c.file_a.clone(), c.file_b.clone(), c.co_changes))
                    .collect::<Vec<_>>()
            };
            assert_eq!(
                as_tuples(&first),
                as_tuples(&again),
                "run {run} disagreed with run 0: coupling output depends on HashMap order"
            );
        }
    }

    #[test]
    fn detect_coupling_breaks_ties_by_path() {
        let pairs = detect_coupling(&tied_commits(), 1);
        let mut expected: Vec<(String, String)> = pairs
            .iter()
            .map(|p| (p.file_a.clone(), p.file_b.clone()))
            .collect();
        expected.sort();
        let actual: Vec<(String, String)> = pairs
            .iter()
            .map(|p| (p.file_a.clone(), p.file_b.clone()))
            .collect();
        assert_eq!(actual, expected, "tied pairs must be ordered by path");
    }

    #[test]
    fn analyze_bottlenecks_is_deterministic_across_runs() {
        use std::process::Command;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let repo = temp.path();
        let git = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(repo)
                .output()
                .expect("git must be available")
        };
        if !git(&["init"]).status.success() {
            return;
        }
        let _ = git(&["config", "user.email", "t@example.com"]);
        let _ = git(&["config", "user.name", "T"]);
        std::fs::create_dir_all(repo.join("src")).unwrap();
        // 30 files, each touched exactly once: every `touches` value ties, and
        // the list is truncated to 20.
        for i in 0..30 {
            std::fs::write(
                repo.join(format!("src/f{i:02}.rs")),
                "pub fn f() {}\npub fn g() {}\n",
            )
            .unwrap();
        }
        let _ = git(&["add", "-A"]);
        if !git(&["commit", "-m", "init", "--no-verify"])
            .status
            .success()
        {
            return;
        }

        let first = analyze_bottlenecks(repo, 99_999_999, 1).expect("analysis must run");
        assert_eq!(
            first.bottlenecks.len(),
            20,
            "the fixture must exercise the truncation"
        );
        let paths = |a: &BottleneckAnalysis| {
            a.bottlenecks
                .iter()
                .map(|b| b.path.clone())
                .collect::<Vec<_>>()
        };
        for run in 1..10 {
            let again = analyze_bottlenecks(repo, 99_999_999, 1).expect("analysis must run");
            assert_eq!(
                paths(&first),
                paths(&again),
                "run {run} disagreed with run 0: bottleneck output depends on HashMap order"
            );
        }
        let mut sorted = paths(&first);
        sorted.sort();
        assert_eq!(paths(&first), sorted, "tied files must be ordered by path");
    }
}