Skip to main content

fallow_cli/report/
markdown.rs

1use std::fmt::Write;
2use std::path::Path;
3
4use fallow_core::duplicates::DuplicationReport;
5use fallow_core::results::{AnalysisResults, UnusedExport, UnusedMember};
6
7use super::grouping::ResultGroup;
8use super::{normalize_uri, plural, relative_path};
9
10/// Escape backticks in user-controlled strings to prevent breaking markdown code spans.
11fn escape_backticks(s: &str) -> String {
12    s.replace('`', "\\`")
13}
14
15pub(super) fn print_markdown(results: &AnalysisResults, root: &Path) {
16    println!("{}", build_markdown(results, root));
17}
18
19/// Build markdown output for analysis results.
20pub fn build_markdown(results: &AnalysisResults, root: &Path) -> String {
21    let rel = |p: &Path| {
22        escape_backticks(&normalize_uri(
23            &relative_path(p, root).display().to_string(),
24        ))
25    };
26
27    let total = results.total_issues();
28    let mut out = String::new();
29
30    if total == 0 {
31        out.push_str("## Fallow: no issues found\n");
32        return out;
33    }
34
35    let _ = write!(out, "## Fallow: {total} issue{} found\n\n", plural(total));
36
37    // ── Unused files ──
38    markdown_section(&mut out, &results.unused_files, "Unused files", |file| {
39        vec![format!("- `{}`", rel(&file.path))]
40    });
41
42    // ── Unused exports ──
43    markdown_grouped_section(
44        &mut out,
45        &results.unused_exports,
46        "Unused exports",
47        root,
48        |e| e.path.as_path(),
49        format_export,
50    );
51
52    // ── Unused types ──
53    markdown_grouped_section(
54        &mut out,
55        &results.unused_types,
56        "Unused type exports",
57        root,
58        |e| e.path.as_path(),
59        format_export,
60    );
61
62    // ── Unused dependencies ──
63    markdown_section(
64        &mut out,
65        &results.unused_dependencies,
66        "Unused dependencies",
67        |dep| format_dependency(&dep.package_name, &dep.path, root),
68    );
69
70    // ── Unused devDependencies ──
71    markdown_section(
72        &mut out,
73        &results.unused_dev_dependencies,
74        "Unused devDependencies",
75        |dep| format_dependency(&dep.package_name, &dep.path, root),
76    );
77
78    // ── Unused optionalDependencies ──
79    markdown_section(
80        &mut out,
81        &results.unused_optional_dependencies,
82        "Unused optionalDependencies",
83        |dep| format_dependency(&dep.package_name, &dep.path, root),
84    );
85
86    // ── Unused enum members ──
87    markdown_grouped_section(
88        &mut out,
89        &results.unused_enum_members,
90        "Unused enum members",
91        root,
92        |m| m.path.as_path(),
93        format_member,
94    );
95
96    // ── Unused class members ──
97    markdown_grouped_section(
98        &mut out,
99        &results.unused_class_members,
100        "Unused class members",
101        root,
102        |m| m.path.as_path(),
103        format_member,
104    );
105
106    // ── Unresolved imports ──
107    markdown_grouped_section(
108        &mut out,
109        &results.unresolved_imports,
110        "Unresolved imports",
111        root,
112        |i| i.path.as_path(),
113        |i| format!(":{} `{}`", i.line, escape_backticks(&i.specifier)),
114    );
115
116    // ── Unlisted dependencies ──
117    markdown_section(
118        &mut out,
119        &results.unlisted_dependencies,
120        "Unlisted dependencies",
121        |dep| vec![format!("- `{}`", escape_backticks(&dep.package_name))],
122    );
123
124    // ── Duplicate exports ──
125    markdown_section(
126        &mut out,
127        &results.duplicate_exports,
128        "Duplicate exports",
129        |dup| {
130            let locations: Vec<String> = dup
131                .locations
132                .iter()
133                .map(|loc| format!("`{}`", rel(&loc.path)))
134                .collect();
135            vec![format!(
136                "- `{}` in {}",
137                escape_backticks(&dup.export_name),
138                locations.join(", ")
139            )]
140        },
141    );
142
143    // ── Type-only dependencies ──
144    markdown_section(
145        &mut out,
146        &results.type_only_dependencies,
147        "Type-only dependencies (consider moving to devDependencies)",
148        |dep| format_dependency(&dep.package_name, &dep.path, root),
149    );
150
151    // ── Test-only dependencies ──
152    markdown_section(
153        &mut out,
154        &results.test_only_dependencies,
155        "Test-only production dependencies (consider moving to devDependencies)",
156        |dep| format_dependency(&dep.package_name, &dep.path, root),
157    );
158
159    // ── Circular dependencies ──
160    markdown_section(
161        &mut out,
162        &results.circular_dependencies,
163        "Circular dependencies",
164        |cycle| {
165            let chain: Vec<String> = cycle.files.iter().map(|p| rel(p)).collect();
166            let mut display_chain = chain.clone();
167            if let Some(first) = chain.first() {
168                display_chain.push(first.clone());
169            }
170            let cross_pkg_tag = if cycle.is_cross_package {
171                " *(cross-package)*"
172            } else {
173                ""
174            };
175            vec![format!(
176                "- {}{}",
177                display_chain
178                    .iter()
179                    .map(|s| format!("`{s}`"))
180                    .collect::<Vec<_>>()
181                    .join(" \u{2192} "),
182                cross_pkg_tag
183            )]
184        },
185    );
186
187    // ── Boundary violations ──
188    markdown_section(
189        &mut out,
190        &results.boundary_violations,
191        "Boundary violations",
192        |v| {
193            vec![format!(
194                "- `{}`:{}  \u{2192} `{}` ({} \u{2192} {})",
195                rel(&v.from_path),
196                v.line,
197                rel(&v.to_path),
198                v.from_zone,
199                v.to_zone,
200            )]
201        },
202    );
203
204    out
205}
206
207/// Print grouped markdown output: each group gets an `## owner (N issues)` heading.
208pub(super) fn print_grouped_markdown(groups: &[ResultGroup], root: &Path) {
209    let total: usize = groups.iter().map(|g| g.results.total_issues()).sum();
210
211    if total == 0 {
212        println!("## Fallow: no issues found");
213        return;
214    }
215
216    println!(
217        "## Fallow: {total} issue{} found (grouped)\n",
218        plural(total)
219    );
220
221    for group in groups {
222        let count = group.results.total_issues();
223        if count == 0 {
224            continue;
225        }
226        println!(
227            "## {} ({count} issue{})\n",
228            escape_backticks(&group.key),
229            plural(count)
230        );
231        // build_markdown already emits its own `## Fallow: N issues found` header;
232        // we re-use the section-level rendering by extracting just the section body.
233        let body = build_markdown(&group.results, root);
234        // Skip the first `## Fallow: ...` line from build_markdown and print the rest.
235        let sections = body
236            .strip_prefix("## Fallow: no issues found\n")
237            .or_else(|| body.find("\n\n").map(|pos| &body[pos + 2..]))
238            .unwrap_or(&body);
239        print!("{sections}");
240    }
241}
242
243fn format_export(e: &UnusedExport) -> String {
244    let re = if e.is_re_export { " (re-export)" } else { "" };
245    format!(":{} `{}`{re}", e.line, escape_backticks(&e.export_name))
246}
247
248fn format_member(m: &UnusedMember) -> String {
249    format!(
250        ":{} `{}.{}`",
251        m.line,
252        escape_backticks(&m.parent_name),
253        escape_backticks(&m.member_name)
254    )
255}
256
257fn format_dependency(dep_name: &str, pkg_path: &Path, root: &Path) -> Vec<String> {
258    let name = escape_backticks(dep_name);
259    let pkg_label = relative_path(pkg_path, root).display().to_string();
260    if pkg_label == "package.json" {
261        vec![format!("- `{name}`")]
262    } else {
263        let label = escape_backticks(&pkg_label);
264        vec![format!("- `{name}` ({label})")]
265    }
266}
267
268/// Emit a markdown section with a header and per-item lines. Skipped if empty.
269fn markdown_section<T>(
270    out: &mut String,
271    items: &[T],
272    title: &str,
273    format_lines: impl Fn(&T) -> Vec<String>,
274) {
275    if items.is_empty() {
276        return;
277    }
278    let _ = write!(out, "### {title} ({})\n\n", items.len());
279    for item in items {
280        for line in format_lines(item) {
281            out.push_str(&line);
282            out.push('\n');
283        }
284    }
285    out.push('\n');
286}
287
288/// Emit a markdown section whose items are grouped by file path.
289fn markdown_grouped_section<'a, T>(
290    out: &mut String,
291    items: &'a [T],
292    title: &str,
293    root: &Path,
294    get_path: impl Fn(&'a T) -> &'a Path,
295    format_detail: impl Fn(&T) -> String,
296) {
297    if items.is_empty() {
298        return;
299    }
300    let _ = write!(out, "### {title} ({})\n\n", items.len());
301
302    let mut indices: Vec<usize> = (0..items.len()).collect();
303    indices.sort_by(|&a, &b| get_path(&items[a]).cmp(get_path(&items[b])));
304
305    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
306    let mut last_file = String::new();
307    for &i in &indices {
308        let item = &items[i];
309        let file_str = rel(get_path(item));
310        if file_str != last_file {
311            let _ = writeln!(out, "- `{file_str}`");
312            last_file = file_str;
313        }
314        let _ = writeln!(out, "  - {}", format_detail(item));
315    }
316    out.push('\n');
317}
318
319// ── Duplication markdown output ──────────────────────────────────
320
321pub(super) fn print_duplication_markdown(report: &DuplicationReport, root: &Path) {
322    println!("{}", build_duplication_markdown(report, root));
323}
324
325/// Build markdown output for duplication results.
326#[must_use]
327pub fn build_duplication_markdown(report: &DuplicationReport, root: &Path) -> String {
328    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
329
330    let mut out = String::new();
331
332    if report.clone_groups.is_empty() {
333        out.push_str("## Fallow: no code duplication found\n");
334        return out;
335    }
336
337    let stats = &report.stats;
338    let _ = write!(
339        out,
340        "## Fallow: {} clone group{} found ({:.1}% duplication)\n\n",
341        stats.clone_groups,
342        plural(stats.clone_groups),
343        stats.duplication_percentage,
344    );
345
346    out.push_str("### Duplicates\n\n");
347    for (i, group) in report.clone_groups.iter().enumerate() {
348        let instance_count = group.instances.len();
349        let _ = write!(
350            out,
351            "**Clone group {}** ({} lines, {instance_count} instance{})\n\n",
352            i + 1,
353            group.line_count,
354            plural(instance_count)
355        );
356        for instance in &group.instances {
357            let relative = rel(&instance.file);
358            let _ = writeln!(
359                out,
360                "- `{relative}:{}-{}`",
361                instance.start_line, instance.end_line
362            );
363        }
364        out.push('\n');
365    }
366
367    // Clone families
368    if !report.clone_families.is_empty() {
369        out.push_str("### Clone Families\n\n");
370        for (i, family) in report.clone_families.iter().enumerate() {
371            let file_names: Vec<_> = family.files.iter().map(|f| rel(f)).collect();
372            let _ = write!(
373                out,
374                "**Family {}** ({} group{}, {} lines across {})\n\n",
375                i + 1,
376                family.groups.len(),
377                plural(family.groups.len()),
378                family.total_duplicated_lines,
379                file_names
380                    .iter()
381                    .map(|s| format!("`{s}`"))
382                    .collect::<Vec<_>>()
383                    .join(", "),
384            );
385            for suggestion in &family.suggestions {
386                let savings = if suggestion.estimated_savings > 0 {
387                    format!(" (~{} lines saved)", suggestion.estimated_savings)
388                } else {
389                    String::new()
390                };
391                let _ = writeln!(out, "- {}{savings}", suggestion.description);
392            }
393            out.push('\n');
394        }
395    }
396
397    // Summary line
398    let _ = writeln!(
399        out,
400        "**Summary:** {} duplicated lines ({:.1}%) across {} file{}",
401        stats.duplicated_lines,
402        stats.duplication_percentage,
403        stats.files_with_clones,
404        plural(stats.files_with_clones),
405    );
406
407    out
408}
409
410// ── Health markdown output ──────────────────────────────────────────
411
412pub(super) fn print_health_markdown(report: &crate::health_types::HealthReport, root: &Path) {
413    println!("{}", build_health_markdown(report, root));
414}
415
416/// Build markdown output for health (complexity) results.
417#[must_use]
418pub fn build_health_markdown(report: &crate::health_types::HealthReport, root: &Path) -> String {
419    let mut out = String::new();
420
421    if let Some(ref hs) = report.health_score {
422        let _ = writeln!(out, "## Health Score: {:.0} ({})\n", hs.score, hs.grade);
423    }
424
425    write_trend_section(&mut out, report);
426    write_vital_signs_section(&mut out, report);
427
428    if report.findings.is_empty()
429        && report.file_scores.is_empty()
430        && report.coverage_gaps.is_none()
431        && report.hotspots.is_empty()
432        && report.targets.is_empty()
433    {
434        if report.vital_signs.is_none() {
435            let _ = write!(
436                out,
437                "## Fallow: no functions exceed complexity thresholds\n\n\
438                 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {})\n",
439                report.summary.functions_analyzed,
440                report.summary.max_cyclomatic_threshold,
441                report.summary.max_cognitive_threshold,
442            );
443        }
444        return out;
445    }
446
447    write_findings_section(&mut out, report, root);
448    write_coverage_gaps_section(&mut out, report, root);
449    write_file_scores_section(&mut out, report, root);
450    write_hotspots_section(&mut out, report, root);
451    write_targets_section(&mut out, report, root);
452    write_metric_legend(&mut out, report);
453
454    out
455}
456
457/// Write the trend comparison table to the output.
458fn write_trend_section(out: &mut String, report: &crate::health_types::HealthReport) {
459    let Some(ref trend) = report.health_trend else {
460        return;
461    };
462    let sha_str = trend
463        .compared_to
464        .git_sha
465        .as_deref()
466        .map_or(String::new(), |sha| format!(" ({sha})"));
467    let _ = writeln!(
468        out,
469        "## Trend (vs {}{})\n",
470        trend
471            .compared_to
472            .timestamp
473            .get(..10)
474            .unwrap_or(&trend.compared_to.timestamp),
475        sha_str,
476    );
477    out.push_str("| Metric | Previous | Current | Delta | Direction |\n");
478    out.push_str("|:-------|:---------|:--------|:------|:----------|\n");
479    for m in &trend.metrics {
480        let fmt_val = |v: f64| -> String {
481            if m.unit == "%" {
482                format!("{v:.1}%")
483            } else if (v - v.round()).abs() < 0.05 {
484                format!("{v:.0}")
485            } else {
486                format!("{v:.1}")
487            }
488        };
489        let prev = fmt_val(m.previous);
490        let cur = fmt_val(m.current);
491        let delta = if m.unit == "%" {
492            format!("{:+.1}%", m.delta)
493        } else if (m.delta - m.delta.round()).abs() < 0.05 {
494            format!("{:+.0}", m.delta)
495        } else {
496            format!("{:+.1}", m.delta)
497        };
498        let _ = writeln!(
499            out,
500            "| {} | {} | {} | {} | {} {} |",
501            m.label,
502            prev,
503            cur,
504            delta,
505            m.direction.arrow(),
506            m.direction.label(),
507        );
508    }
509    let md_sha = trend
510        .compared_to
511        .git_sha
512        .as_deref()
513        .map_or(String::new(), |sha| format!(" ({sha})"));
514    let _ = writeln!(
515        out,
516        "\n*vs {}{} · {} {} available*\n",
517        trend
518            .compared_to
519            .timestamp
520            .get(..10)
521            .unwrap_or(&trend.compared_to.timestamp),
522        md_sha,
523        trend.snapshots_loaded,
524        if trend.snapshots_loaded == 1 {
525            "snapshot"
526        } else {
527            "snapshots"
528        },
529    );
530}
531
532/// Write the vital signs summary table to the output.
533fn write_vital_signs_section(out: &mut String, report: &crate::health_types::HealthReport) {
534    let Some(ref vs) = report.vital_signs else {
535        return;
536    };
537    out.push_str("## Vital Signs\n\n");
538    out.push_str("| Metric | Value |\n");
539    out.push_str("|:-------|------:|\n");
540    let _ = writeln!(out, "| Avg Cyclomatic | {:.1} |", vs.avg_cyclomatic);
541    let _ = writeln!(out, "| P90 Cyclomatic | {} |", vs.p90_cyclomatic);
542    if let Some(v) = vs.dead_file_pct {
543        let _ = writeln!(out, "| Dead Files | {v:.1}% |");
544    }
545    if let Some(v) = vs.dead_export_pct {
546        let _ = writeln!(out, "| Dead Exports | {v:.1}% |");
547    }
548    if let Some(v) = vs.maintainability_avg {
549        let _ = writeln!(out, "| Maintainability (avg) | {v:.1} |");
550    }
551    if let Some(v) = vs.hotspot_count {
552        let _ = writeln!(out, "| Hotspots | {v} |");
553    }
554    if let Some(v) = vs.circular_dep_count {
555        let _ = writeln!(out, "| Circular Deps | {v} |");
556    }
557    if let Some(v) = vs.unused_dep_count {
558        let _ = writeln!(out, "| Unused Deps | {v} |");
559    }
560    out.push('\n');
561}
562
563/// Write the complexity findings table to the output.
564fn write_findings_section(
565    out: &mut String,
566    report: &crate::health_types::HealthReport,
567    root: &Path,
568) {
569    if report.findings.is_empty() {
570        return;
571    }
572
573    let rel = |p: &Path| {
574        escape_backticks(&normalize_uri(
575            &relative_path(p, root).display().to_string(),
576        ))
577    };
578
579    let count = report.summary.functions_above_threshold;
580    let shown = report.findings.len();
581    if shown < count {
582        let _ = write!(
583            out,
584            "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
585            plural(count),
586        );
587    } else {
588        let _ = write!(
589            out,
590            "## Fallow: {count} high complexity function{}\n\n",
591            plural(count),
592        );
593    }
594
595    out.push_str("| File | Function | Cyclomatic | Cognitive | Lines |\n");
596    out.push_str("|:-----|:---------|:-----------|:----------|:------|\n");
597
598    for finding in &report.findings {
599        let file_str = rel(&finding.path);
600        let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
601            " **!**"
602        } else {
603            ""
604        };
605        let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
606            " **!**"
607        } else {
608            ""
609        };
610        let _ = writeln!(
611            out,
612            "| `{file_str}:{line}` | `{name}` | {cyc}{cyc_marker} | {cog}{cog_marker} | {lines} |",
613            line = finding.line,
614            name = escape_backticks(&finding.name),
615            cyc = finding.cyclomatic,
616            cog = finding.cognitive,
617            lines = finding.line_count,
618        );
619    }
620
621    let s = &report.summary;
622    let _ = write!(
623        out,
624        "\n**{files}** files, **{funcs}** functions analyzed \
625         (thresholds: cyclomatic > {cyc}, cognitive > {cog})\n",
626        files = s.files_analyzed,
627        funcs = s.functions_analyzed,
628        cyc = s.max_cyclomatic_threshold,
629        cog = s.max_cognitive_threshold,
630    );
631}
632
633/// Write the file health scores table to the output.
634fn write_file_scores_section(
635    out: &mut String,
636    report: &crate::health_types::HealthReport,
637    root: &Path,
638) {
639    if report.file_scores.is_empty() {
640        return;
641    }
642
643    let rel = |p: &Path| {
644        escape_backticks(&normalize_uri(
645            &relative_path(p, root).display().to_string(),
646        ))
647    };
648
649    out.push('\n');
650    let _ = writeln!(
651        out,
652        "### File Health Scores ({} files)\n",
653        report.file_scores.len(),
654    );
655    out.push_str("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density | Risk |\n");
656    out.push_str("|:-----|:---------------|:-------|:--------|:----------|:--------|:-----|\n");
657
658    for score in &report.file_scores {
659        let file_str = rel(&score.path);
660        let _ = writeln!(
661            out,
662            "| `{file_str}` | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} | {crap:.1} |",
663            mi = score.maintainability_index,
664            fi = score.fan_in,
665            fan_out = score.fan_out,
666            dead = score.dead_code_ratio * 100.0,
667            density = score.complexity_density,
668            crap = score.crap_max,
669        );
670    }
671
672    if let Some(avg) = report.summary.average_maintainability {
673        let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
674    }
675}
676
677fn write_coverage_gaps_section(
678    out: &mut String,
679    report: &crate::health_types::HealthReport,
680    root: &Path,
681) {
682    let Some(ref gaps) = report.coverage_gaps else {
683        return;
684    };
685
686    out.push('\n');
687    let _ = writeln!(out, "### Coverage Gaps\n");
688    let _ = writeln!(
689        out,
690        "*{} untested files · {} untested exports · {:.1}% file coverage*\n",
691        gaps.summary.untested_files, gaps.summary.untested_exports, gaps.summary.file_coverage_pct,
692    );
693
694    if gaps.files.is_empty() && gaps.exports.is_empty() {
695        out.push_str("_No coverage gaps found in scope._\n");
696        return;
697    }
698
699    if !gaps.files.is_empty() {
700        out.push_str("#### Files\n");
701        for item in &gaps.files {
702            let file_str = escape_backticks(&normalize_uri(
703                &relative_path(&item.path, root).display().to_string(),
704            ));
705            let _ = writeln!(
706                out,
707                "- `{file_str}` ({count} value export{})",
708                if item.value_export_count == 1 {
709                    ""
710                } else {
711                    "s"
712                },
713                count = item.value_export_count,
714            );
715        }
716        out.push('\n');
717    }
718
719    if !gaps.exports.is_empty() {
720        out.push_str("#### Exports\n");
721        for item in &gaps.exports {
722            let file_str = escape_backticks(&normalize_uri(
723                &relative_path(&item.path, root).display().to_string(),
724            ));
725            let _ = writeln!(out, "- `{file_str}`:{} `{}`", item.line, item.export_name);
726        }
727    }
728}
729
730/// Write the hotspots table to the output.
731fn write_hotspots_section(
732    out: &mut String,
733    report: &crate::health_types::HealthReport,
734    root: &Path,
735) {
736    if report.hotspots.is_empty() {
737        return;
738    }
739
740    let rel = |p: &Path| {
741        escape_backticks(&normalize_uri(
742            &relative_path(p, root).display().to_string(),
743        ))
744    };
745
746    out.push('\n');
747    let header = report.hotspot_summary.as_ref().map_or_else(
748        || format!("### Hotspots ({} files)\n", report.hotspots.len()),
749        |summary| {
750            format!(
751                "### Hotspots ({} files, since {})\n",
752                report.hotspots.len(),
753                summary.since,
754            )
755        },
756    );
757    let _ = writeln!(out, "{header}");
758    out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
759    out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
760
761    for entry in &report.hotspots {
762        let file_str = rel(&entry.path);
763        let _ = writeln!(
764            out,
765            "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
766            score = entry.score,
767            commits = entry.commits,
768            churn = entry.lines_added + entry.lines_deleted,
769            density = entry.complexity_density,
770            fi = entry.fan_in,
771            trend = entry.trend,
772        );
773    }
774
775    if let Some(ref summary) = report.hotspot_summary
776        && summary.files_excluded > 0
777    {
778        let _ = write!(
779            out,
780            "\n*{} file{} excluded (< {} commits)*\n",
781            summary.files_excluded,
782            plural(summary.files_excluded),
783            summary.min_commits,
784        );
785    }
786}
787
788/// Write the refactoring targets table to the output.
789fn write_targets_section(
790    out: &mut String,
791    report: &crate::health_types::HealthReport,
792    root: &Path,
793) {
794    if report.targets.is_empty() {
795        return;
796    }
797    let _ = write!(
798        out,
799        "\n### Refactoring Targets ({})\n\n",
800        report.targets.len()
801    );
802    out.push_str("| Efficiency | Category | Effort / Confidence | File | Recommendation |\n");
803    out.push_str("|:-----------|:---------|:--------------------|:-----|:---------------|\n");
804    for target in &report.targets {
805        let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
806        let category = target.category.label();
807        let effort = target.effort.label();
808        let confidence = target.confidence.label();
809        let _ = writeln!(
810            out,
811            "| {:.1} | {category} | {effort} / {confidence} | `{file_str}` | {} |",
812            target.efficiency, target.recommendation,
813        );
814    }
815}
816
817/// Write the metric legend collapsible section to the output.
818fn write_metric_legend(out: &mut String, report: &crate::health_types::HealthReport) {
819    let has_scores = !report.file_scores.is_empty();
820    let has_coverage = report.coverage_gaps.is_some();
821    let has_hotspots = !report.hotspots.is_empty();
822    let has_targets = !report.targets.is_empty();
823    if !has_scores && !has_coverage && !has_hotspots && !has_targets {
824        return;
825    }
826    out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
827    if has_scores {
828        out.push_str("- **MI** — Maintainability Index (0\u{2013}100, higher is better)\n");
829        out.push_str("- **Fan-in** — files that import this file (blast radius)\n");
830        out.push_str("- **Fan-out** — files this file imports (coupling)\n");
831        out.push_str("- **Dead Code** — % of value exports with zero references\n");
832        out.push_str("- **Density** — cyclomatic complexity / lines of code\n");
833    }
834    if has_coverage {
835        out.push_str(
836            "- **File coverage** — runtime files also reachable from a discovered test root\n",
837        );
838        out.push_str("- **Untested export** — export with no reference chain from any test-reachable module\n");
839    }
840    if has_hotspots {
841        out.push_str("- **Score** — churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n");
842        out.push_str("- **Commits** — commits in the analysis window\n");
843        out.push_str("- **Churn** — total lines added + deleted\n");
844        out.push_str("- **Trend** — accelerating / stable / cooling\n");
845    }
846    if has_targets {
847        out.push_str("- **Efficiency** — priority / effort (higher = better quick-win value, default sort)\n");
848        out.push_str("- **Category** — recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
849        out.push_str("- **Effort** — estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
850        out.push_str("- **Confidence** — recommendation reliability (high = deterministic analysis, medium = heuristic, low = git-dependent)\n");
851    }
852    out.push_str(
853        "\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n",
854    );
855}
856
857#[cfg(test)]
858mod tests {
859    use super::*;
860    use crate::report::test_helpers::sample_results;
861    use fallow_core::duplicates::{
862        CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
863        RefactoringKind, RefactoringSuggestion,
864    };
865    use fallow_core::results::*;
866    use std::path::PathBuf;
867
868    #[test]
869    fn markdown_empty_results_no_issues() {
870        let root = PathBuf::from("/project");
871        let results = AnalysisResults::default();
872        let md = build_markdown(&results, &root);
873        assert_eq!(md, "## Fallow: no issues found\n");
874    }
875
876    #[test]
877    fn markdown_contains_header_with_count() {
878        let root = PathBuf::from("/project");
879        let results = sample_results(&root);
880        let md = build_markdown(&results, &root);
881        assert!(md.starts_with(&format!(
882            "## Fallow: {} issues found\n",
883            results.total_issues()
884        )));
885    }
886
887    #[test]
888    fn markdown_contains_all_sections() {
889        let root = PathBuf::from("/project");
890        let results = sample_results(&root);
891        let md = build_markdown(&results, &root);
892
893        assert!(md.contains("### Unused files (1)"));
894        assert!(md.contains("### Unused exports (1)"));
895        assert!(md.contains("### Unused type exports (1)"));
896        assert!(md.contains("### Unused dependencies (1)"));
897        assert!(md.contains("### Unused devDependencies (1)"));
898        assert!(md.contains("### Unused enum members (1)"));
899        assert!(md.contains("### Unused class members (1)"));
900        assert!(md.contains("### Unresolved imports (1)"));
901        assert!(md.contains("### Unlisted dependencies (1)"));
902        assert!(md.contains("### Duplicate exports (1)"));
903        assert!(md.contains("### Type-only dependencies"));
904        assert!(md.contains("### Test-only production dependencies"));
905        assert!(md.contains("### Circular dependencies (1)"));
906    }
907
908    #[test]
909    fn markdown_unused_file_format() {
910        let root = PathBuf::from("/project");
911        let mut results = AnalysisResults::default();
912        results.unused_files.push(UnusedFile {
913            path: root.join("src/dead.ts"),
914        });
915        let md = build_markdown(&results, &root);
916        assert!(md.contains("- `src/dead.ts`"));
917    }
918
919    #[test]
920    fn markdown_unused_export_grouped_by_file() {
921        let root = PathBuf::from("/project");
922        let mut results = AnalysisResults::default();
923        results.unused_exports.push(UnusedExport {
924            path: root.join("src/utils.ts"),
925            export_name: "helperFn".to_string(),
926            is_type_only: false,
927            line: 10,
928            col: 4,
929            span_start: 120,
930            is_re_export: false,
931        });
932        let md = build_markdown(&results, &root);
933        assert!(md.contains("- `src/utils.ts`"));
934        assert!(md.contains(":10 `helperFn`"));
935    }
936
937    #[test]
938    fn markdown_re_export_tagged() {
939        let root = PathBuf::from("/project");
940        let mut results = AnalysisResults::default();
941        results.unused_exports.push(UnusedExport {
942            path: root.join("src/index.ts"),
943            export_name: "reExported".to_string(),
944            is_type_only: false,
945            line: 1,
946            col: 0,
947            span_start: 0,
948            is_re_export: true,
949        });
950        let md = build_markdown(&results, &root);
951        assert!(md.contains("(re-export)"));
952    }
953
954    #[test]
955    fn markdown_unused_dep_format() {
956        let root = PathBuf::from("/project");
957        let mut results = AnalysisResults::default();
958        results.unused_dependencies.push(UnusedDependency {
959            package_name: "lodash".to_string(),
960            location: DependencyLocation::Dependencies,
961            path: root.join("package.json"),
962            line: 5,
963        });
964        let md = build_markdown(&results, &root);
965        assert!(md.contains("- `lodash`"));
966    }
967
968    #[test]
969    fn markdown_circular_dep_format() {
970        let root = PathBuf::from("/project");
971        let mut results = AnalysisResults::default();
972        results.circular_dependencies.push(CircularDependency {
973            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
974            length: 2,
975            line: 3,
976            col: 0,
977            is_cross_package: false,
978        });
979        let md = build_markdown(&results, &root);
980        assert!(md.contains("`src/a.ts`"));
981        assert!(md.contains("`src/b.ts`"));
982        assert!(md.contains("\u{2192}"));
983    }
984
985    #[test]
986    fn markdown_strips_root_prefix() {
987        let root = PathBuf::from("/project");
988        let mut results = AnalysisResults::default();
989        results.unused_files.push(UnusedFile {
990            path: PathBuf::from("/project/src/deep/nested/file.ts"),
991        });
992        let md = build_markdown(&results, &root);
993        assert!(md.contains("`src/deep/nested/file.ts`"));
994        assert!(!md.contains("/project/"));
995    }
996
997    #[test]
998    fn markdown_single_issue_no_plural() {
999        let root = PathBuf::from("/project");
1000        let mut results = AnalysisResults::default();
1001        results.unused_files.push(UnusedFile {
1002            path: root.join("src/dead.ts"),
1003        });
1004        let md = build_markdown(&results, &root);
1005        assert!(md.starts_with("## Fallow: 1 issue found\n"));
1006    }
1007
1008    #[test]
1009    fn markdown_type_only_dep_format() {
1010        let root = PathBuf::from("/project");
1011        let mut results = AnalysisResults::default();
1012        results.type_only_dependencies.push(TypeOnlyDependency {
1013            package_name: "zod".to_string(),
1014            path: root.join("package.json"),
1015            line: 8,
1016        });
1017        let md = build_markdown(&results, &root);
1018        assert!(md.contains("### Type-only dependencies"));
1019        assert!(md.contains("- `zod`"));
1020    }
1021
1022    #[test]
1023    fn markdown_escapes_backticks_in_export_names() {
1024        let root = PathBuf::from("/project");
1025        let mut results = AnalysisResults::default();
1026        results.unused_exports.push(UnusedExport {
1027            path: root.join("src/utils.ts"),
1028            export_name: "foo`bar".to_string(),
1029            is_type_only: false,
1030            line: 1,
1031            col: 0,
1032            span_start: 0,
1033            is_re_export: false,
1034        });
1035        let md = build_markdown(&results, &root);
1036        assert!(md.contains("foo\\`bar"));
1037        assert!(!md.contains("foo`bar`"));
1038    }
1039
1040    #[test]
1041    fn markdown_escapes_backticks_in_package_names() {
1042        let root = PathBuf::from("/project");
1043        let mut results = AnalysisResults::default();
1044        results.unused_dependencies.push(UnusedDependency {
1045            package_name: "pkg`name".to_string(),
1046            location: DependencyLocation::Dependencies,
1047            path: root.join("package.json"),
1048            line: 5,
1049        });
1050        let md = build_markdown(&results, &root);
1051        assert!(md.contains("pkg\\`name"));
1052    }
1053
1054    // ── Duplication markdown ──
1055
1056    #[test]
1057    fn duplication_markdown_empty() {
1058        let report = DuplicationReport::default();
1059        let root = PathBuf::from("/project");
1060        let md = build_duplication_markdown(&report, &root);
1061        assert_eq!(md, "## Fallow: no code duplication found\n");
1062    }
1063
1064    #[test]
1065    fn duplication_markdown_contains_groups() {
1066        let root = PathBuf::from("/project");
1067        let report = DuplicationReport {
1068            clone_groups: vec![CloneGroup {
1069                instances: vec![
1070                    CloneInstance {
1071                        file: root.join("src/a.ts"),
1072                        start_line: 1,
1073                        end_line: 10,
1074                        start_col: 0,
1075                        end_col: 0,
1076                        fragment: String::new(),
1077                    },
1078                    CloneInstance {
1079                        file: root.join("src/b.ts"),
1080                        start_line: 5,
1081                        end_line: 14,
1082                        start_col: 0,
1083                        end_col: 0,
1084                        fragment: String::new(),
1085                    },
1086                ],
1087                token_count: 50,
1088                line_count: 10,
1089            }],
1090            clone_families: vec![],
1091            mirrored_directories: vec![],
1092            stats: DuplicationStats {
1093                total_files: 10,
1094                files_with_clones: 2,
1095                total_lines: 500,
1096                duplicated_lines: 20,
1097                total_tokens: 2500,
1098                duplicated_tokens: 100,
1099                clone_groups: 1,
1100                clone_instances: 2,
1101                duplication_percentage: 4.0,
1102            },
1103        };
1104        let md = build_duplication_markdown(&report, &root);
1105        assert!(md.contains("**Clone group 1**"));
1106        assert!(md.contains("`src/a.ts:1-10`"));
1107        assert!(md.contains("`src/b.ts:5-14`"));
1108        assert!(md.contains("4.0% duplication"));
1109    }
1110
1111    #[test]
1112    fn duplication_markdown_contains_families() {
1113        let root = PathBuf::from("/project");
1114        let report = DuplicationReport {
1115            clone_groups: vec![CloneGroup {
1116                instances: vec![CloneInstance {
1117                    file: root.join("src/a.ts"),
1118                    start_line: 1,
1119                    end_line: 5,
1120                    start_col: 0,
1121                    end_col: 0,
1122                    fragment: String::new(),
1123                }],
1124                token_count: 30,
1125                line_count: 5,
1126            }],
1127            clone_families: vec![CloneFamily {
1128                files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1129                groups: vec![],
1130                total_duplicated_lines: 20,
1131                total_duplicated_tokens: 100,
1132                suggestions: vec![RefactoringSuggestion {
1133                    kind: RefactoringKind::ExtractFunction,
1134                    description: "Extract shared utility function".to_string(),
1135                    estimated_savings: 15,
1136                }],
1137            }],
1138            mirrored_directories: vec![],
1139            stats: DuplicationStats {
1140                clone_groups: 1,
1141                clone_instances: 1,
1142                duplication_percentage: 2.0,
1143                ..Default::default()
1144            },
1145        };
1146        let md = build_duplication_markdown(&report, &root);
1147        assert!(md.contains("### Clone Families"));
1148        assert!(md.contains("**Family 1**"));
1149        assert!(md.contains("Extract shared utility function"));
1150        assert!(md.contains("~15 lines saved"));
1151    }
1152
1153    // ── Health markdown ──
1154
1155    #[test]
1156    fn health_markdown_empty_no_findings() {
1157        let root = PathBuf::from("/project");
1158        let report = crate::health_types::HealthReport {
1159            findings: vec![],
1160            summary: crate::health_types::HealthSummary {
1161                files_analyzed: 10,
1162                functions_analyzed: 50,
1163                functions_above_threshold: 0,
1164                max_cyclomatic_threshold: 20,
1165                max_cognitive_threshold: 15,
1166                files_scored: None,
1167                average_maintainability: None,
1168                coverage_model: None,
1169            },
1170            vital_signs: None,
1171            health_score: None,
1172            file_scores: vec![],
1173            coverage_gaps: None,
1174            hotspots: vec![],
1175            hotspot_summary: None,
1176            targets: vec![],
1177            target_thresholds: None,
1178            health_trend: None,
1179        };
1180        let md = build_health_markdown(&report, &root);
1181        assert!(md.contains("no functions exceed complexity thresholds"));
1182        assert!(md.contains("**50** functions analyzed"));
1183    }
1184
1185    #[test]
1186    fn health_markdown_table_format() {
1187        let root = PathBuf::from("/project");
1188        let report = crate::health_types::HealthReport {
1189            findings: vec![crate::health_types::HealthFinding {
1190                path: root.join("src/utils.ts"),
1191                name: "parseExpression".to_string(),
1192                line: 42,
1193                col: 0,
1194                cyclomatic: 25,
1195                cognitive: 30,
1196                line_count: 80,
1197                exceeded: crate::health_types::ExceededThreshold::Both,
1198            }],
1199            summary: crate::health_types::HealthSummary {
1200                files_analyzed: 10,
1201                functions_analyzed: 50,
1202                functions_above_threshold: 1,
1203                max_cyclomatic_threshold: 20,
1204                max_cognitive_threshold: 15,
1205                files_scored: None,
1206                average_maintainability: None,
1207                coverage_model: None,
1208            },
1209            vital_signs: None,
1210            health_score: None,
1211            file_scores: vec![],
1212            coverage_gaps: None,
1213            hotspots: vec![],
1214            hotspot_summary: None,
1215            targets: vec![],
1216            target_thresholds: None,
1217            health_trend: None,
1218        };
1219        let md = build_health_markdown(&report, &root);
1220        assert!(md.contains("## Fallow: 1 high complexity function\n"));
1221        assert!(md.contains("| File | Function |"));
1222        assert!(md.contains("`src/utils.ts:42`"));
1223        assert!(md.contains("`parseExpression`"));
1224        assert!(md.contains("25 **!**"));
1225        assert!(md.contains("30 **!**"));
1226        assert!(md.contains("| 80 |"));
1227    }
1228
1229    #[test]
1230    fn health_markdown_no_marker_when_below_threshold() {
1231        let root = PathBuf::from("/project");
1232        let report = crate::health_types::HealthReport {
1233            findings: vec![crate::health_types::HealthFinding {
1234                path: root.join("src/utils.ts"),
1235                name: "helper".to_string(),
1236                line: 10,
1237                col: 0,
1238                cyclomatic: 15,
1239                cognitive: 20,
1240                line_count: 30,
1241                exceeded: crate::health_types::ExceededThreshold::Cognitive,
1242            }],
1243            summary: crate::health_types::HealthSummary {
1244                files_analyzed: 5,
1245                functions_analyzed: 20,
1246                functions_above_threshold: 1,
1247                max_cyclomatic_threshold: 20,
1248                max_cognitive_threshold: 15,
1249                files_scored: None,
1250                average_maintainability: None,
1251                coverage_model: None,
1252            },
1253            vital_signs: None,
1254            health_score: None,
1255            file_scores: vec![],
1256            coverage_gaps: None,
1257            hotspots: vec![],
1258            hotspot_summary: None,
1259            targets: vec![],
1260            target_thresholds: None,
1261            health_trend: None,
1262        };
1263        let md = build_health_markdown(&report, &root);
1264        // Cyclomatic 15 is below threshold 20, no marker
1265        assert!(md.contains("| 15 |"));
1266        // Cognitive 20 exceeds threshold 15, has marker
1267        assert!(md.contains("20 **!**"));
1268    }
1269
1270    #[test]
1271    fn health_markdown_with_targets() {
1272        use crate::health_types::*;
1273
1274        let root = PathBuf::from("/project");
1275        let report = HealthReport {
1276            findings: vec![],
1277            summary: HealthSummary {
1278                files_analyzed: 10,
1279                functions_analyzed: 50,
1280                functions_above_threshold: 0,
1281                max_cyclomatic_threshold: 20,
1282                max_cognitive_threshold: 15,
1283                files_scored: None,
1284                average_maintainability: None,
1285                coverage_model: None,
1286            },
1287            vital_signs: None,
1288            health_score: None,
1289            file_scores: vec![],
1290            coverage_gaps: None,
1291            hotspots: vec![],
1292            hotspot_summary: None,
1293            targets: vec![
1294                RefactoringTarget {
1295                    path: PathBuf::from("/project/src/complex.ts"),
1296                    priority: 82.5,
1297                    efficiency: 27.5,
1298                    recommendation: "Split high-impact file".into(),
1299                    category: RecommendationCategory::SplitHighImpact,
1300                    effort: crate::health_types::EffortEstimate::High,
1301                    confidence: crate::health_types::Confidence::Medium,
1302                    factors: vec![ContributingFactor {
1303                        metric: "fan_in",
1304                        value: 25.0,
1305                        threshold: 10.0,
1306                        detail: "25 files depend on this".into(),
1307                    }],
1308                    evidence: None,
1309                },
1310                RefactoringTarget {
1311                    path: PathBuf::from("/project/src/legacy.ts"),
1312                    priority: 45.0,
1313                    efficiency: 45.0,
1314                    recommendation: "Remove 5 unused exports".into(),
1315                    category: RecommendationCategory::RemoveDeadCode,
1316                    effort: crate::health_types::EffortEstimate::Low,
1317                    confidence: crate::health_types::Confidence::High,
1318                    factors: vec![],
1319                    evidence: None,
1320                },
1321            ],
1322            target_thresholds: None,
1323            health_trend: None,
1324        };
1325        let md = build_health_markdown(&report, &root);
1326
1327        // Should have refactoring targets section
1328        assert!(
1329            md.contains("Refactoring Targets"),
1330            "should contain targets heading"
1331        );
1332        assert!(
1333            md.contains("src/complex.ts"),
1334            "should contain target file path"
1335        );
1336        assert!(md.contains("27.5"), "should contain efficiency score");
1337        assert!(
1338            md.contains("Split high-impact file"),
1339            "should contain recommendation"
1340        );
1341        assert!(md.contains("src/legacy.ts"), "should contain second target");
1342    }
1343
1344    #[test]
1345    fn health_markdown_with_coverage_gaps() {
1346        use crate::health_types::*;
1347
1348        let root = PathBuf::from("/project");
1349        let report = HealthReport {
1350            findings: vec![],
1351            summary: HealthSummary {
1352                files_analyzed: 10,
1353                functions_analyzed: 50,
1354                functions_above_threshold: 0,
1355                max_cyclomatic_threshold: 20,
1356                max_cognitive_threshold: 15,
1357                files_scored: None,
1358                average_maintainability: None,
1359                coverage_model: None,
1360            },
1361            vital_signs: None,
1362            health_score: None,
1363            file_scores: vec![],
1364            coverage_gaps: Some(CoverageGaps {
1365                summary: CoverageGapSummary {
1366                    runtime_files: 2,
1367                    covered_files: 0,
1368                    file_coverage_pct: 0.0,
1369                    untested_files: 1,
1370                    untested_exports: 1,
1371                },
1372                files: vec![UntestedFile {
1373                    path: root.join("src/app.ts"),
1374                    value_export_count: 2,
1375                }],
1376                exports: vec![UntestedExport {
1377                    path: root.join("src/app.ts"),
1378                    export_name: "loader".into(),
1379                    line: 12,
1380                    col: 4,
1381                }],
1382            }),
1383            hotspots: vec![],
1384            hotspot_summary: None,
1385            targets: vec![],
1386            target_thresholds: None,
1387            health_trend: None,
1388        };
1389
1390        let md = build_health_markdown(&report, &root);
1391        assert!(md.contains("### Coverage Gaps"));
1392        assert!(md.contains("*1 untested files"));
1393        assert!(md.contains("`src/app.ts` (2 value exports)"));
1394        assert!(md.contains("`src/app.ts`:12 `loader`"));
1395    }
1396
1397    // ── Dependency in workspace package ──
1398
1399    #[test]
1400    fn markdown_dep_in_workspace_shows_package_label() {
1401        let root = PathBuf::from("/project");
1402        let mut results = AnalysisResults::default();
1403        results.unused_dependencies.push(UnusedDependency {
1404            package_name: "lodash".to_string(),
1405            location: DependencyLocation::Dependencies,
1406            path: root.join("packages/core/package.json"),
1407            line: 5,
1408        });
1409        let md = build_markdown(&results, &root);
1410        // Non-root package.json should show the label
1411        assert!(md.contains("(packages/core/package.json)"));
1412    }
1413
1414    #[test]
1415    fn markdown_dep_at_root_no_extra_label() {
1416        let root = PathBuf::from("/project");
1417        let mut results = AnalysisResults::default();
1418        results.unused_dependencies.push(UnusedDependency {
1419            package_name: "lodash".to_string(),
1420            location: DependencyLocation::Dependencies,
1421            path: root.join("package.json"),
1422            line: 5,
1423        });
1424        let md = build_markdown(&results, &root);
1425        assert!(md.contains("- `lodash`"));
1426        assert!(!md.contains("(package.json)"));
1427    }
1428
1429    // ── Multiple exports same file grouped ──
1430
1431    #[test]
1432    fn markdown_exports_grouped_by_file() {
1433        let root = PathBuf::from("/project");
1434        let mut results = AnalysisResults::default();
1435        results.unused_exports.push(UnusedExport {
1436            path: root.join("src/utils.ts"),
1437            export_name: "alpha".to_string(),
1438            is_type_only: false,
1439            line: 5,
1440            col: 0,
1441            span_start: 0,
1442            is_re_export: false,
1443        });
1444        results.unused_exports.push(UnusedExport {
1445            path: root.join("src/utils.ts"),
1446            export_name: "beta".to_string(),
1447            is_type_only: false,
1448            line: 10,
1449            col: 0,
1450            span_start: 0,
1451            is_re_export: false,
1452        });
1453        results.unused_exports.push(UnusedExport {
1454            path: root.join("src/other.ts"),
1455            export_name: "gamma".to_string(),
1456            is_type_only: false,
1457            line: 1,
1458            col: 0,
1459            span_start: 0,
1460            is_re_export: false,
1461        });
1462        let md = build_markdown(&results, &root);
1463        // File header should appear only once for utils.ts
1464        let utils_count = md.matches("- `src/utils.ts`").count();
1465        assert_eq!(utils_count, 1, "file header should appear once per file");
1466        // Both exports should be under it as sub-items
1467        assert!(md.contains(":5 `alpha`"));
1468        assert!(md.contains(":10 `beta`"));
1469    }
1470
1471    // ── Multiple issues plural header ──
1472
1473    #[test]
1474    fn markdown_multiple_issues_plural() {
1475        let root = PathBuf::from("/project");
1476        let mut results = AnalysisResults::default();
1477        results.unused_files.push(UnusedFile {
1478            path: root.join("src/a.ts"),
1479        });
1480        results.unused_files.push(UnusedFile {
1481            path: root.join("src/b.ts"),
1482        });
1483        let md = build_markdown(&results, &root);
1484        assert!(md.starts_with("## Fallow: 2 issues found\n"));
1485    }
1486
1487    // ── Duplication markdown with zero estimated savings ──
1488
1489    #[test]
1490    fn duplication_markdown_zero_savings_no_suffix() {
1491        let root = PathBuf::from("/project");
1492        let report = DuplicationReport {
1493            clone_groups: vec![CloneGroup {
1494                instances: vec![CloneInstance {
1495                    file: root.join("src/a.ts"),
1496                    start_line: 1,
1497                    end_line: 5,
1498                    start_col: 0,
1499                    end_col: 0,
1500                    fragment: String::new(),
1501                }],
1502                token_count: 30,
1503                line_count: 5,
1504            }],
1505            clone_families: vec![CloneFamily {
1506                files: vec![root.join("src/a.ts")],
1507                groups: vec![],
1508                total_duplicated_lines: 5,
1509                total_duplicated_tokens: 30,
1510                suggestions: vec![RefactoringSuggestion {
1511                    kind: RefactoringKind::ExtractFunction,
1512                    description: "Extract function".to_string(),
1513                    estimated_savings: 0,
1514                }],
1515            }],
1516            mirrored_directories: vec![],
1517            stats: DuplicationStats {
1518                clone_groups: 1,
1519                clone_instances: 1,
1520                duplication_percentage: 1.0,
1521                ..Default::default()
1522            },
1523        };
1524        let md = build_duplication_markdown(&report, &root);
1525        assert!(md.contains("Extract function"));
1526        assert!(!md.contains("lines saved"));
1527    }
1528
1529    // ── Health markdown vital signs ──
1530
1531    #[test]
1532    fn health_markdown_vital_signs_table() {
1533        let root = PathBuf::from("/project");
1534        let report = crate::health_types::HealthReport {
1535            findings: vec![],
1536            summary: crate::health_types::HealthSummary {
1537                files_analyzed: 10,
1538                functions_analyzed: 50,
1539                functions_above_threshold: 0,
1540                max_cyclomatic_threshold: 20,
1541                max_cognitive_threshold: 15,
1542                files_scored: None,
1543                average_maintainability: None,
1544                coverage_model: None,
1545            },
1546            vital_signs: Some(crate::health_types::VitalSigns {
1547                avg_cyclomatic: 3.5,
1548                p90_cyclomatic: 12,
1549                dead_file_pct: Some(5.0),
1550                dead_export_pct: Some(10.2),
1551                duplication_pct: None,
1552                maintainability_avg: Some(72.3),
1553                hotspot_count: Some(3),
1554                circular_dep_count: Some(1),
1555                unused_dep_count: Some(2),
1556                counts: None,
1557            }),
1558            health_score: None,
1559            file_scores: vec![],
1560            coverage_gaps: None,
1561            hotspots: vec![],
1562            hotspot_summary: None,
1563            targets: vec![],
1564            target_thresholds: None,
1565            health_trend: None,
1566        };
1567        let md = build_health_markdown(&report, &root);
1568        assert!(md.contains("## Vital Signs"));
1569        assert!(md.contains("| Metric | Value |"));
1570        assert!(md.contains("| Avg Cyclomatic | 3.5 |"));
1571        assert!(md.contains("| P90 Cyclomatic | 12 |"));
1572        assert!(md.contains("| Dead Files | 5.0% |"));
1573        assert!(md.contains("| Dead Exports | 10.2% |"));
1574        assert!(md.contains("| Maintainability (avg) | 72.3 |"));
1575        assert!(md.contains("| Hotspots | 3 |"));
1576        assert!(md.contains("| Circular Deps | 1 |"));
1577        assert!(md.contains("| Unused Deps | 2 |"));
1578    }
1579
1580    // ── Health markdown file scores ──
1581
1582    #[test]
1583    fn health_markdown_file_scores_table() {
1584        let root = PathBuf::from("/project");
1585        let report = crate::health_types::HealthReport {
1586            findings: vec![crate::health_types::HealthFinding {
1587                path: root.join("src/dummy.ts"),
1588                name: "fn".to_string(),
1589                line: 1,
1590                col: 0,
1591                cyclomatic: 25,
1592                cognitive: 20,
1593                line_count: 50,
1594                exceeded: crate::health_types::ExceededThreshold::Both,
1595            }],
1596            summary: crate::health_types::HealthSummary {
1597                files_analyzed: 5,
1598                functions_analyzed: 10,
1599                functions_above_threshold: 1,
1600                max_cyclomatic_threshold: 20,
1601                max_cognitive_threshold: 15,
1602                files_scored: Some(1),
1603                average_maintainability: Some(65.0),
1604                coverage_model: None,
1605            },
1606            vital_signs: None,
1607            health_score: None,
1608            file_scores: vec![crate::health_types::FileHealthScore {
1609                path: root.join("src/utils.ts"),
1610                fan_in: 5,
1611                fan_out: 3,
1612                dead_code_ratio: 0.25,
1613                complexity_density: 0.8,
1614                maintainability_index: 72.5,
1615                total_cyclomatic: 40,
1616                total_cognitive: 30,
1617                function_count: 10,
1618                lines: 200,
1619                crap_max: 0.0,
1620                crap_above_threshold: 0,
1621            }],
1622            coverage_gaps: None,
1623            hotspots: vec![],
1624            hotspot_summary: None,
1625            targets: vec![],
1626            target_thresholds: None,
1627            health_trend: None,
1628        };
1629        let md = build_health_markdown(&report, &root);
1630        assert!(md.contains("### File Health Scores (1 files)"));
1631        assert!(md.contains("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density |"));
1632        assert!(md.contains("| `src/utils.ts` | 72.5 | 5 | 3 | 25% | 0.80 |"));
1633        assert!(md.contains("**Average maintainability index:** 65.0/100"));
1634    }
1635
1636    // ── Health markdown hotspots ──
1637
1638    #[test]
1639    fn health_markdown_hotspots_table() {
1640        let root = PathBuf::from("/project");
1641        let report = crate::health_types::HealthReport {
1642            findings: vec![crate::health_types::HealthFinding {
1643                path: root.join("src/dummy.ts"),
1644                name: "fn".to_string(),
1645                line: 1,
1646                col: 0,
1647                cyclomatic: 25,
1648                cognitive: 20,
1649                line_count: 50,
1650                exceeded: crate::health_types::ExceededThreshold::Both,
1651            }],
1652            summary: crate::health_types::HealthSummary {
1653                files_analyzed: 5,
1654                functions_analyzed: 10,
1655                functions_above_threshold: 1,
1656                max_cyclomatic_threshold: 20,
1657                max_cognitive_threshold: 15,
1658                files_scored: None,
1659                average_maintainability: None,
1660                coverage_model: None,
1661            },
1662            vital_signs: None,
1663            health_score: None,
1664            file_scores: vec![],
1665            coverage_gaps: None,
1666            hotspots: vec![crate::health_types::HotspotEntry {
1667                path: root.join("src/hot.ts"),
1668                score: 85.0,
1669                commits: 42,
1670                weighted_commits: 35.0,
1671                lines_added: 500,
1672                lines_deleted: 200,
1673                complexity_density: 1.2,
1674                fan_in: 10,
1675                trend: fallow_core::churn::ChurnTrend::Accelerating,
1676            }],
1677            hotspot_summary: Some(crate::health_types::HotspotSummary {
1678                since: "6 months".to_string(),
1679                min_commits: 3,
1680                files_analyzed: 50,
1681                files_excluded: 5,
1682                shallow_clone: false,
1683            }),
1684            targets: vec![],
1685            target_thresholds: None,
1686            health_trend: None,
1687        };
1688        let md = build_health_markdown(&report, &root);
1689        assert!(md.contains("### Hotspots (1 files, since 6 months)"));
1690        assert!(md.contains("| `src/hot.ts` | 85.0 | 42 | 700 | 1.20 | 10 | accelerating |"));
1691        assert!(md.contains("*5 files excluded (< 3 commits)*"));
1692    }
1693
1694    // ── Health markdown metric legend ──
1695
1696    #[test]
1697    fn health_markdown_metric_legend_with_scores() {
1698        let root = PathBuf::from("/project");
1699        let report = crate::health_types::HealthReport {
1700            findings: vec![crate::health_types::HealthFinding {
1701                path: root.join("src/x.ts"),
1702                name: "f".to_string(),
1703                line: 1,
1704                col: 0,
1705                cyclomatic: 25,
1706                cognitive: 20,
1707                line_count: 10,
1708                exceeded: crate::health_types::ExceededThreshold::Both,
1709            }],
1710            summary: crate::health_types::HealthSummary {
1711                files_analyzed: 1,
1712                functions_analyzed: 1,
1713                functions_above_threshold: 1,
1714                max_cyclomatic_threshold: 20,
1715                max_cognitive_threshold: 15,
1716                files_scored: Some(1),
1717                average_maintainability: Some(70.0),
1718                coverage_model: None,
1719            },
1720            vital_signs: None,
1721            health_score: None,
1722            file_scores: vec![crate::health_types::FileHealthScore {
1723                path: root.join("src/x.ts"),
1724                fan_in: 1,
1725                fan_out: 1,
1726                dead_code_ratio: 0.0,
1727                complexity_density: 0.5,
1728                maintainability_index: 80.0,
1729                total_cyclomatic: 10,
1730                total_cognitive: 8,
1731                function_count: 2,
1732                lines: 50,
1733                crap_max: 0.0,
1734                crap_above_threshold: 0,
1735            }],
1736            coverage_gaps: None,
1737            hotspots: vec![],
1738            hotspot_summary: None,
1739            targets: vec![],
1740            target_thresholds: None,
1741            health_trend: None,
1742        };
1743        let md = build_health_markdown(&report, &root);
1744        assert!(md.contains("<details><summary>Metric definitions</summary>"));
1745        assert!(md.contains("**MI** \u{2014} Maintainability Index"));
1746        assert!(md.contains("**Fan-in**"));
1747        assert!(md.contains("Full metric reference"));
1748    }
1749
1750    // ── Health markdown truncated findings ──
1751
1752    #[test]
1753    fn health_markdown_truncated_findings_shown_count() {
1754        let root = PathBuf::from("/project");
1755        let report = crate::health_types::HealthReport {
1756            findings: vec![crate::health_types::HealthFinding {
1757                path: root.join("src/x.ts"),
1758                name: "f".to_string(),
1759                line: 1,
1760                col: 0,
1761                cyclomatic: 25,
1762                cognitive: 20,
1763                line_count: 10,
1764                exceeded: crate::health_types::ExceededThreshold::Both,
1765            }],
1766            summary: crate::health_types::HealthSummary {
1767                files_analyzed: 10,
1768                functions_analyzed: 50,
1769                functions_above_threshold: 5, // 5 total but only 1 shown
1770                max_cyclomatic_threshold: 20,
1771                max_cognitive_threshold: 15,
1772                files_scored: None,
1773                average_maintainability: None,
1774                coverage_model: None,
1775            },
1776            vital_signs: None,
1777            health_score: None,
1778            file_scores: vec![],
1779            coverage_gaps: None,
1780            hotspots: vec![],
1781            hotspot_summary: None,
1782            targets: vec![],
1783            target_thresholds: None,
1784            health_trend: None,
1785        };
1786        let md = build_health_markdown(&report, &root);
1787        assert!(md.contains("5 high complexity functions (1 shown)"));
1788    }
1789
1790    // ── escape_backticks ──
1791
1792    #[test]
1793    fn escape_backticks_handles_multiple() {
1794        assert_eq!(escape_backticks("a`b`c"), "a\\`b\\`c");
1795    }
1796
1797    #[test]
1798    fn escape_backticks_no_backticks_unchanged() {
1799        assert_eq!(escape_backticks("hello"), "hello");
1800    }
1801
1802    // ── Unresolved import in markdown ──
1803
1804    #[test]
1805    fn markdown_unresolved_import_grouped_by_file() {
1806        let root = PathBuf::from("/project");
1807        let mut results = AnalysisResults::default();
1808        results.unresolved_imports.push(UnresolvedImport {
1809            path: root.join("src/app.ts"),
1810            specifier: "./missing".to_string(),
1811            line: 3,
1812            col: 0,
1813            specifier_col: 0,
1814        });
1815        let md = build_markdown(&results, &root);
1816        assert!(md.contains("### Unresolved imports (1)"));
1817        assert!(md.contains("- `src/app.ts`"));
1818        assert!(md.contains(":3 `./missing`"));
1819    }
1820
1821    // ── Markdown optional dep ──
1822
1823    #[test]
1824    fn markdown_unused_optional_dep() {
1825        let root = PathBuf::from("/project");
1826        let mut results = AnalysisResults::default();
1827        results.unused_optional_dependencies.push(UnusedDependency {
1828            package_name: "fsevents".to_string(),
1829            location: DependencyLocation::OptionalDependencies,
1830            path: root.join("package.json"),
1831            line: 12,
1832        });
1833        let md = build_markdown(&results, &root);
1834        assert!(md.contains("### Unused optionalDependencies (1)"));
1835        assert!(md.contains("- `fsevents`"));
1836    }
1837
1838    // ── Health markdown no hotspot exclusion message when 0 excluded ──
1839
1840    #[test]
1841    fn health_markdown_hotspots_no_excluded_message() {
1842        let root = PathBuf::from("/project");
1843        let report = crate::health_types::HealthReport {
1844            findings: vec![crate::health_types::HealthFinding {
1845                path: root.join("src/x.ts"),
1846                name: "f".to_string(),
1847                line: 1,
1848                col: 0,
1849                cyclomatic: 25,
1850                cognitive: 20,
1851                line_count: 10,
1852                exceeded: crate::health_types::ExceededThreshold::Both,
1853            }],
1854            summary: crate::health_types::HealthSummary {
1855                files_analyzed: 5,
1856                functions_analyzed: 10,
1857                functions_above_threshold: 1,
1858                max_cyclomatic_threshold: 20,
1859                max_cognitive_threshold: 15,
1860                files_scored: None,
1861                average_maintainability: None,
1862                coverage_model: None,
1863            },
1864            vital_signs: None,
1865            health_score: None,
1866            file_scores: vec![],
1867            coverage_gaps: None,
1868            hotspots: vec![crate::health_types::HotspotEntry {
1869                path: root.join("src/hot.ts"),
1870                score: 50.0,
1871                commits: 10,
1872                weighted_commits: 8.0,
1873                lines_added: 100,
1874                lines_deleted: 50,
1875                complexity_density: 0.5,
1876                fan_in: 3,
1877                trend: fallow_core::churn::ChurnTrend::Stable,
1878            }],
1879            hotspot_summary: Some(crate::health_types::HotspotSummary {
1880                since: "6 months".to_string(),
1881                min_commits: 3,
1882                files_analyzed: 50,
1883                files_excluded: 0,
1884                shallow_clone: false,
1885            }),
1886            targets: vec![],
1887            target_thresholds: None,
1888            health_trend: None,
1889        };
1890        let md = build_health_markdown(&report, &root);
1891        assert!(!md.contains("files excluded"));
1892    }
1893
1894    // ── Duplication markdown plural ──
1895
1896    #[test]
1897    fn duplication_markdown_single_group_no_plural() {
1898        let root = PathBuf::from("/project");
1899        let report = DuplicationReport {
1900            clone_groups: vec![CloneGroup {
1901                instances: vec![CloneInstance {
1902                    file: root.join("src/a.ts"),
1903                    start_line: 1,
1904                    end_line: 5,
1905                    start_col: 0,
1906                    end_col: 0,
1907                    fragment: String::new(),
1908                }],
1909                token_count: 30,
1910                line_count: 5,
1911            }],
1912            clone_families: vec![],
1913            mirrored_directories: vec![],
1914            stats: DuplicationStats {
1915                clone_groups: 1,
1916                clone_instances: 1,
1917                duplication_percentage: 2.0,
1918                ..Default::default()
1919            },
1920        };
1921        let md = build_duplication_markdown(&report, &root);
1922        assert!(md.contains("1 clone group found"));
1923        assert!(!md.contains("1 clone groups found"));
1924    }
1925}