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::{
6    AnalysisResults, UnusedClassMemberFinding, UnusedEnumMemberFinding, UnusedExport,
7    UnusedExportFinding, UnusedMember, UnusedTypeFinding,
8};
9
10use super::grouping::ResultGroup;
11use super::{normalize_uri, plural, relative_path};
12
13/// Escape backticks in user-controlled strings to prevent breaking markdown code spans.
14fn escape_backticks(s: &str) -> String {
15    s.replace('`', "\\`")
16}
17
18pub(super) fn print_markdown(results: &AnalysisResults, root: &Path) {
19    println!("{}", build_markdown(results, root));
20}
21
22/// Build markdown output for analysis results.
23#[expect(
24    clippy::too_many_lines,
25    reason = "one section per issue type; splitting would fragment the output builder"
26)]
27pub fn build_markdown(results: &AnalysisResults, root: &Path) -> String {
28    let rel = |p: &Path| {
29        escape_backticks(&normalize_uri(
30            &relative_path(p, root).display().to_string(),
31        ))
32    };
33
34    let total = results.total_issues();
35    let mut out = String::new();
36
37    if total == 0 {
38        out.push_str("## Fallow: no issues found\n");
39        return out;
40    }
41
42    let _ = write!(out, "## Fallow: {total} issue{} found\n\n", plural(total));
43
44    // ── Unused files ──
45    markdown_section(&mut out, &results.unused_files, "Unused files", |file| {
46        vec![format!("- `{}`", rel(&file.file.path))]
47    });
48
49    // ── Unused exports ──
50    markdown_grouped_section(
51        &mut out,
52        &results.unused_exports,
53        "Unused exports",
54        root,
55        |e| e.export.path.as_path(),
56        |e: &UnusedExportFinding| format_export(&e.export),
57    );
58
59    // ── Unused types ──
60    markdown_grouped_section(
61        &mut out,
62        &results.unused_types,
63        "Unused type exports",
64        root,
65        |e| e.export.path.as_path(),
66        |e: &UnusedTypeFinding| format_export(&e.export),
67    );
68
69    markdown_grouped_section(
70        &mut out,
71        &results.private_type_leaks,
72        "Private type leaks",
73        root,
74        |e| e.leak.path.as_path(),
75        format_private_type_leak,
76    );
77
78    // ── Unused dependencies ──
79    markdown_section(
80        &mut out,
81        &results.unused_dependencies,
82        "Unused dependencies",
83        |dep| {
84            format_dependency(
85                &dep.dep.package_name,
86                &dep.dep.path,
87                &dep.dep.used_in_workspaces,
88                root,
89            )
90        },
91    );
92
93    // ── Unused devDependencies ──
94    markdown_section(
95        &mut out,
96        &results.unused_dev_dependencies,
97        "Unused devDependencies",
98        |dep| {
99            format_dependency(
100                &dep.dep.package_name,
101                &dep.dep.path,
102                &dep.dep.used_in_workspaces,
103                root,
104            )
105        },
106    );
107
108    // ── Unused optionalDependencies ──
109    markdown_section(
110        &mut out,
111        &results.unused_optional_dependencies,
112        "Unused optionalDependencies",
113        |dep| {
114            format_dependency(
115                &dep.dep.package_name,
116                &dep.dep.path,
117                &dep.dep.used_in_workspaces,
118                root,
119            )
120        },
121    );
122
123    // ── Unused enum members ──
124    markdown_grouped_section(
125        &mut out,
126        &results.unused_enum_members,
127        "Unused enum members",
128        root,
129        |m| m.member.path.as_path(),
130        |m: &UnusedEnumMemberFinding| format_member(&m.member),
131    );
132
133    // ── Unused class members ──
134    markdown_grouped_section(
135        &mut out,
136        &results.unused_class_members,
137        "Unused class members",
138        root,
139        |m| m.member.path.as_path(),
140        |m: &UnusedClassMemberFinding| format_member(&m.member),
141    );
142
143    // ── Unresolved imports ──
144    markdown_grouped_section(
145        &mut out,
146        &results.unresolved_imports,
147        "Unresolved imports",
148        root,
149        |i| i.import.path.as_path(),
150        |i| {
151            format!(
152                ":{} `{}`",
153                i.import.line,
154                escape_backticks(&i.import.specifier)
155            )
156        },
157    );
158
159    // ── Unlisted dependencies ──
160    markdown_section(
161        &mut out,
162        &results.unlisted_dependencies,
163        "Unlisted dependencies",
164        |dep| vec![format!("- `{}`", escape_backticks(&dep.dep.package_name))],
165    );
166
167    // ── Duplicate exports ──
168    markdown_section(
169        &mut out,
170        &results.duplicate_exports,
171        "Duplicate exports",
172        |dup| {
173            let locations: Vec<String> = dup
174                .export
175                .locations
176                .iter()
177                .map(|loc| format!("`{}`", rel(&loc.path)))
178                .collect();
179            vec![format!(
180                "- `{}` in {}",
181                escape_backticks(&dup.export.export_name),
182                locations.join(", ")
183            )]
184        },
185    );
186
187    // ── Type-only dependencies ──
188    markdown_section(
189        &mut out,
190        &results.type_only_dependencies,
191        "Type-only dependencies (consider moving to devDependencies)",
192        |dep| format_dependency(&dep.dep.package_name, &dep.dep.path, &[], root),
193    );
194
195    // ── Test-only dependencies ──
196    markdown_section(
197        &mut out,
198        &results.test_only_dependencies,
199        "Test-only production dependencies (consider moving to devDependencies)",
200        |dep| format_dependency(&dep.dep.package_name, &dep.dep.path, &[], root),
201    );
202
203    // ── Circular dependencies ──
204    markdown_section(
205        &mut out,
206        &results.circular_dependencies,
207        "Circular dependencies",
208        |cycle| {
209            let chain: Vec<String> = cycle.cycle.files.iter().map(|p| rel(p)).collect();
210            let mut display_chain = chain.clone();
211            if let Some(first) = chain.first() {
212                display_chain.push(first.clone());
213            }
214            let cross_pkg_tag = if cycle.cycle.is_cross_package {
215                " *(cross-package)*"
216            } else {
217                ""
218            };
219            vec![format!(
220                "- {}{}",
221                display_chain
222                    .iter()
223                    .map(|s| format!("`{s}`"))
224                    .collect::<Vec<_>>()
225                    .join(" \u{2192} "),
226                cross_pkg_tag
227            )]
228        },
229    );
230
231    // ── Re-export cycles ──
232    markdown_section(
233        &mut out,
234        &results.re_export_cycles,
235        "Re-export cycles",
236        |cycle| {
237            let chain: Vec<String> = cycle.cycle.files.iter().map(|p| rel(p)).collect();
238            let kind_tag = match cycle.cycle.kind {
239                fallow_core::results::ReExportCycleKind::SelfLoop => " *(self-loop)*",
240                fallow_core::results::ReExportCycleKind::MultiNode => "",
241            };
242            vec![format!(
243                "- {}{}",
244                chain
245                    .iter()
246                    .map(|s| format!("`{s}`"))
247                    .collect::<Vec<_>>()
248                    .join(" <-> "),
249                kind_tag
250            )]
251        },
252    );
253
254    // ── Boundary violations ──
255    markdown_section(
256        &mut out,
257        &results.boundary_violations,
258        "Boundary violations",
259        |v| {
260            vec![format!(
261                "- `{}`:{}  \u{2192} `{}` ({} \u{2192} {})",
262                rel(&v.violation.from_path),
263                v.violation.line,
264                rel(&v.violation.to_path),
265                v.violation.from_zone,
266                v.violation.to_zone,
267            )]
268        },
269    );
270
271    // ── Stale suppressions ──
272    markdown_section(
273        &mut out,
274        &results.stale_suppressions,
275        "Stale suppressions",
276        |s| {
277            vec![format!(
278                "- `{}`:{} `{}` ({})",
279                rel(&s.path),
280                s.line,
281                escape_backticks(&s.description()),
282                escape_backticks(&s.explanation()),
283            )]
284        },
285    );
286    markdown_section(
287        &mut out,
288        &results.unused_catalog_entries,
289        "Unused catalog entries",
290        |entry| {
291            let mut row = format!(
292                "- `{}` (`{}`) `{}`:{}",
293                escape_backticks(&entry.entry.entry_name),
294                escape_backticks(&entry.entry.catalog_name),
295                rel(&entry.entry.path),
296                entry.entry.line,
297            );
298            if !entry.entry.hardcoded_consumers.is_empty() {
299                use std::fmt::Write as _;
300                let consumers = entry
301                    .entry
302                    .hardcoded_consumers
303                    .iter()
304                    .map(|p| format!("`{}`", rel(p)))
305                    .collect::<Vec<_>>()
306                    .join(", ");
307                let _ = write!(row, " (hardcoded in {consumers})");
308            }
309            vec![row]
310        },
311    );
312    markdown_section(
313        &mut out,
314        &results.empty_catalog_groups,
315        "Empty catalog groups",
316        |group| {
317            vec![format!(
318                "- `{}` `{}`:{}",
319                escape_backticks(&group.group.catalog_name),
320                rel(&group.group.path),
321                group.group.line,
322            )]
323        },
324    );
325    markdown_section(
326        &mut out,
327        &results.unresolved_catalog_references,
328        "Unresolved catalog references",
329        |finding| {
330            let mut row = format!(
331                "- `{}` (`{}`) `{}`:{}",
332                escape_backticks(&finding.reference.entry_name),
333                escape_backticks(&finding.reference.catalog_name),
334                rel(&finding.reference.path),
335                finding.reference.line,
336            );
337            if !finding.reference.available_in_catalogs.is_empty() {
338                use std::fmt::Write as _;
339                let alts = finding
340                    .reference
341                    .available_in_catalogs
342                    .iter()
343                    .map(|c| format!("`{}`", escape_backticks(c)))
344                    .collect::<Vec<_>>()
345                    .join(", ");
346                let _ = write!(row, " (available in: {alts})");
347            }
348            vec![row]
349        },
350    );
351    markdown_section(
352        &mut out,
353        &results.unused_dependency_overrides,
354        "Unused dependency overrides",
355        |finding| {
356            use std::fmt::Write as _;
357            let mut row = format!(
358                "- `{}` -> `{}` (`{}`) `{}`:{}",
359                escape_backticks(&finding.entry.raw_key),
360                escape_backticks(&finding.entry.version_range),
361                finding.entry.source.as_label(),
362                rel(&finding.entry.path),
363                finding.entry.line,
364            );
365            if let Some(hint) = &finding.entry.hint {
366                let _ = write!(row, " (hint: {})", escape_backticks(hint));
367            }
368            vec![row]
369        },
370    );
371    markdown_section(
372        &mut out,
373        &results.misconfigured_dependency_overrides,
374        "Misconfigured dependency overrides",
375        |finding| {
376            vec![format!(
377                "- `{}` -> `{}` (`{}`) `{}`:{} ({})",
378                escape_backticks(&finding.entry.raw_key),
379                escape_backticks(&finding.entry.raw_value),
380                finding.entry.source.as_label(),
381                rel(&finding.entry.path),
382                finding.entry.line,
383                finding.entry.reason.describe(),
384            )]
385        },
386    );
387
388    out
389}
390
391/// Print grouped markdown output: each group gets an `## owner (N issues)` heading.
392pub(super) fn print_grouped_markdown(groups: &[ResultGroup], root: &Path) {
393    let total: usize = groups.iter().map(|g| g.results.total_issues()).sum();
394
395    if total == 0 {
396        println!("## Fallow: no issues found");
397        return;
398    }
399
400    println!(
401        "## Fallow: {total} issue{} found (grouped)\n",
402        plural(total)
403    );
404
405    for group in groups {
406        let count = group.results.total_issues();
407        if count == 0 {
408            continue;
409        }
410        println!(
411            "## {} ({count} issue{})\n",
412            escape_backticks(&group.key),
413            plural(count)
414        );
415        // Section-mode: surface the section's default owners under the heading
416        // so PR comment dashboards can see who approves without re-opening
417        // CODEOWNERS. `owners` is `None` outside of `--group-by section` and
418        // empty for the `(no section)` / `(unowned)` buckets.
419        if let Some(ref owners) = group.owners
420            && !owners.is_empty()
421        {
422            let joined = owners
423                .iter()
424                .map(|o| escape_backticks(o))
425                .collect::<Vec<_>>()
426                .join(" ");
427            println!("Owners: {joined}\n");
428        }
429        // build_markdown already emits its own `## Fallow: N issues found` header;
430        // we re-use the section-level rendering by extracting just the section body.
431        let body = build_markdown(&group.results, root);
432        // Skip the first `## Fallow: ...` line from build_markdown and print the rest.
433        let sections = body
434            .strip_prefix("## Fallow: no issues found\n")
435            .or_else(|| body.find("\n\n").map(|pos| &body[pos + 2..]))
436            .unwrap_or(&body);
437        print!("{sections}");
438    }
439}
440
441fn format_export(e: &UnusedExport) -> String {
442    let re = if e.is_re_export { " (re-export)" } else { "" };
443    format!(":{} `{}`{re}", e.line, escape_backticks(&e.export_name))
444}
445
446fn format_private_type_leak(
447    entry: &fallow_types::output_dead_code::PrivateTypeLeakFinding,
448) -> String {
449    let e = &entry.leak;
450    format!(
451        ":{} `{}` references private type `{}`",
452        e.line,
453        escape_backticks(&e.export_name),
454        escape_backticks(&e.type_name)
455    )
456}
457
458fn format_member(m: &UnusedMember) -> String {
459    format!(
460        ":{} `{}.{}`",
461        m.line,
462        escape_backticks(&m.parent_name),
463        escape_backticks(&m.member_name)
464    )
465}
466
467fn format_dependency(
468    dep_name: &str,
469    pkg_path: &Path,
470    used_in_workspaces: &[std::path::PathBuf],
471    root: &Path,
472) -> Vec<String> {
473    let name = escape_backticks(dep_name);
474    let pkg_label = relative_path(pkg_path, root).display().to_string();
475    let workspace_context = if used_in_workspaces.is_empty() {
476        String::new()
477    } else {
478        let workspaces = used_in_workspaces
479            .iter()
480            .map(|path| escape_backticks(&relative_path(path, root).display().to_string()))
481            .collect::<Vec<_>>()
482            .join(", ");
483        format!("; imported in {workspaces}")
484    };
485    if pkg_label == "package.json" && workspace_context.is_empty() {
486        vec![format!("- `{name}`")]
487    } else {
488        let label = if pkg_label == "package.json" {
489            workspace_context.trim_start_matches("; ").to_string()
490        } else {
491            format!("{}{workspace_context}", escape_backticks(&pkg_label))
492        };
493        vec![format!("- `{name}` ({label})")]
494    }
495}
496
497/// Emit a markdown section with a header and per-item lines. Skipped if empty.
498fn markdown_section<T>(
499    out: &mut String,
500    items: &[T],
501    title: &str,
502    format_lines: impl Fn(&T) -> Vec<String>,
503) {
504    if items.is_empty() {
505        return;
506    }
507    let _ = write!(out, "### {title} ({})\n\n", items.len());
508    for item in items {
509        for line in format_lines(item) {
510            out.push_str(&line);
511            out.push('\n');
512        }
513    }
514    out.push('\n');
515}
516
517/// Emit a markdown section whose items are grouped by file path.
518fn markdown_grouped_section<'a, T>(
519    out: &mut String,
520    items: &'a [T],
521    title: &str,
522    root: &Path,
523    get_path: impl Fn(&'a T) -> &'a Path,
524    format_detail: impl Fn(&T) -> String,
525) {
526    if items.is_empty() {
527        return;
528    }
529    let _ = write!(out, "### {title} ({})\n\n", items.len());
530
531    let mut indices: Vec<usize> = (0..items.len()).collect();
532    indices.sort_by(|&a, &b| get_path(&items[a]).cmp(get_path(&items[b])));
533
534    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
535    let mut last_file = String::new();
536    for &i in &indices {
537        let item = &items[i];
538        let file_str = rel(get_path(item));
539        if file_str != last_file {
540            let _ = writeln!(out, "- `{file_str}`");
541            last_file = file_str;
542        }
543        let _ = writeln!(out, "  - {}", format_detail(item));
544    }
545    out.push('\n');
546}
547
548// ── Duplication markdown output ──────────────────────────────────
549
550pub(super) fn print_duplication_markdown(report: &DuplicationReport, root: &Path) {
551    println!("{}", build_duplication_markdown(report, root));
552}
553
554/// Build markdown output for duplication results.
555#[must_use]
556pub fn build_duplication_markdown(report: &DuplicationReport, root: &Path) -> String {
557    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
558
559    let mut out = String::new();
560
561    if report.clone_groups.is_empty() {
562        out.push_str("## Fallow: no code duplication found\n");
563        return out;
564    }
565
566    let stats = &report.stats;
567    let _ = write!(
568        out,
569        "## Fallow: {} clone group{} found ({:.1}% duplication)\n\n",
570        stats.clone_groups,
571        plural(stats.clone_groups),
572        stats.duplication_percentage,
573    );
574
575    out.push_str("### Duplicates\n\n");
576    for (i, group) in report.clone_groups.iter().enumerate() {
577        let instance_count = group.instances.len();
578        let _ = write!(
579            out,
580            "**Clone group {}** ({} lines, {instance_count} instance{})\n\n",
581            i + 1,
582            group.line_count,
583            plural(instance_count)
584        );
585        for instance in &group.instances {
586            let relative = rel(&instance.file);
587            let _ = writeln!(
588                out,
589                "- `{relative}:{}-{}`",
590                instance.start_line, instance.end_line
591            );
592        }
593        out.push('\n');
594    }
595
596    // Clone families
597    if !report.clone_families.is_empty() {
598        out.push_str("### Clone Families\n\n");
599        for (i, family) in report.clone_families.iter().enumerate() {
600            let file_names: Vec<_> = family.files.iter().map(|f| rel(f)).collect();
601            let _ = write!(
602                out,
603                "**Family {}** ({} group{}, {} lines across {})\n\n",
604                i + 1,
605                family.groups.len(),
606                plural(family.groups.len()),
607                family.total_duplicated_lines,
608                file_names
609                    .iter()
610                    .map(|s| format!("`{s}`"))
611                    .collect::<Vec<_>>()
612                    .join(", "),
613            );
614            for suggestion in &family.suggestions {
615                let savings = if suggestion.estimated_savings > 0 {
616                    format!(" (~{} lines saved)", suggestion.estimated_savings)
617                } else {
618                    String::new()
619                };
620                let _ = writeln!(out, "- {}{savings}", suggestion.description);
621            }
622            out.push('\n');
623        }
624    }
625
626    // Summary line
627    let _ = writeln!(
628        out,
629        "**Summary:** {} duplicated lines ({:.1}%) across {} file{}",
630        stats.duplicated_lines,
631        stats.duplication_percentage,
632        stats.files_with_clones,
633        plural(stats.files_with_clones),
634    );
635
636    out
637}
638
639// ── Health markdown output ──────────────────────────────────────────
640
641pub(super) fn print_health_markdown(report: &crate::health_types::HealthReport, root: &Path) {
642    println!("{}", build_health_markdown(report, root));
643}
644
645/// Build markdown output for health (complexity) results.
646#[must_use]
647pub fn build_health_markdown(report: &crate::health_types::HealthReport, root: &Path) -> String {
648    let mut out = String::new();
649
650    if let Some(ref hs) = report.health_score {
651        let _ = writeln!(out, "## Health Score: {:.0} ({})\n", hs.score, hs.grade);
652    }
653
654    write_trend_section(&mut out, report);
655    write_vital_signs_section(&mut out, report);
656
657    if report.findings.is_empty()
658        && report.file_scores.is_empty()
659        && report.coverage_gaps.is_none()
660        && report.hotspots.is_empty()
661        && report.targets.is_empty()
662        && report.runtime_coverage.is_none()
663    {
664        if report.vital_signs.is_none() {
665            let _ = write!(
666                out,
667                "## Fallow: no functions exceed complexity thresholds\n\n\
668                 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {}, max CRAP: {:.1})\n",
669                report.summary.functions_analyzed,
670                report.summary.max_cyclomatic_threshold,
671                report.summary.max_cognitive_threshold,
672                report.summary.max_crap_threshold,
673            );
674        }
675        return out;
676    }
677
678    write_findings_section(&mut out, report, root);
679    write_runtime_coverage_section(&mut out, report, root);
680    write_coverage_gaps_section(&mut out, report, root);
681    write_file_scores_section(&mut out, report, root);
682    write_hotspots_section(&mut out, report, root);
683    write_targets_section(&mut out, report, root);
684    write_metric_legend(&mut out, report);
685
686    out
687}
688
689fn write_runtime_coverage_section(
690    out: &mut String,
691    report: &crate::health_types::HealthReport,
692    root: &Path,
693) {
694    let Some(ref production) = report.runtime_coverage else {
695        return;
696    };
697    // Prepend a blank line so the heading is not concatenated to the previous
698    // section (GFM requires a blank line before headings to avoid the heading
699    // being parsed as a paragraph continuation).
700    if !out.is_empty() && !out.ends_with("\n\n") {
701        out.push('\n');
702    }
703    let _ = writeln!(
704        out,
705        "## Runtime Coverage\n\n- Verdict: {}\n- Functions tracked: {}\n- Hit: {}\n- Unhit: {}\n- Untracked: {}\n- Coverage: {:.1}%\n- Traces observed: {}\n- Period: {} day(s), {} deployment(s)\n",
706        production.verdict,
707        production.summary.functions_tracked,
708        production.summary.functions_hit,
709        production.summary.functions_unhit,
710        production.summary.functions_untracked,
711        production.summary.coverage_percent,
712        production.summary.trace_count,
713        production.summary.period_days,
714        production.summary.deployments_seen,
715    );
716    if let Some(watermark) = production.watermark {
717        let _ = writeln!(out, "- Watermark: {watermark}\n");
718    }
719    if let Some(ref quality) = production.summary.capture_quality
720        && quality.lazy_parse_warning
721    {
722        let window = super::human::health::format_window(quality.window_seconds);
723        let _ = writeln!(
724            out,
725            "- Capture quality: short window ({} from {} instance(s), {:.1}% of functions untracked); lazy-parsed scripts may not appear.\n",
726            window, quality.instances_observed, quality.untracked_ratio_percent,
727        );
728    }
729    let rel = |p: &Path| {
730        escape_backticks(&normalize_uri(
731            &relative_path(p, root).display().to_string(),
732        ))
733    };
734    if !production.findings.is_empty() {
735        out.push_str("| ID | Path | Function | Verdict | Invocations | Confidence |\n");
736        out.push_str("|:---|:-----|:---------|:--------|------------:|:-----------|\n");
737        for finding in &production.findings {
738            let invocations = finding
739                .invocations
740                .map_or_else(|| "-".to_owned(), |hits| hits.to_string());
741            let _ = writeln!(
742                out,
743                "| `{}` | `{}`:{} | `{}` | {} | {} | {} |",
744                escape_backticks(&finding.id),
745                rel(&finding.path),
746                finding.line,
747                escape_backticks(&finding.function),
748                finding.verdict,
749                invocations,
750                finding.confidence,
751            );
752        }
753        out.push('\n');
754    }
755    if !production.hot_paths.is_empty() {
756        out.push_str("| ID | Hot path | Function | Invocations | Percentile |\n");
757        out.push_str("|:---|:---------|:---------|------------:|-----------:|\n");
758        for entry in &production.hot_paths {
759            let _ = writeln!(
760                out,
761                "| `{}` | `{}`:{} | `{}` | {} | {} |",
762                escape_backticks(&entry.id),
763                rel(&entry.path),
764                entry.line,
765                escape_backticks(&entry.function),
766                entry.invocations,
767                entry.percentile,
768            );
769        }
770        out.push('\n');
771    }
772}
773
774/// Write the trend comparison table to the output.
775fn write_trend_section(out: &mut String, report: &crate::health_types::HealthReport) {
776    let Some(ref trend) = report.health_trend else {
777        return;
778    };
779    let sha_str = trend
780        .compared_to
781        .git_sha
782        .as_deref()
783        .map_or(String::new(), |sha| format!(" ({sha})"));
784    let _ = writeln!(
785        out,
786        "## Trend (vs {}{})\n",
787        trend
788            .compared_to
789            .timestamp
790            .get(..10)
791            .unwrap_or(&trend.compared_to.timestamp),
792        sha_str,
793    );
794    out.push_str("| Metric | Previous | Current | Delta | Direction |\n");
795    out.push_str("|:-------|:---------|:--------|:------|:----------|\n");
796    for m in &trend.metrics {
797        let fmt_val = |v: f64| -> String {
798            if m.unit == "%" {
799                format!("{v:.1}%")
800            } else if (v - v.round()).abs() < 0.05 {
801                format!("{v:.0}")
802            } else {
803                format!("{v:.1}")
804            }
805        };
806        let prev = fmt_val(m.previous);
807        let cur = fmt_val(m.current);
808        let delta = if m.unit == "%" {
809            format!("{:+.1}%", m.delta)
810        } else if (m.delta - m.delta.round()).abs() < 0.05 {
811            format!("{:+.0}", m.delta)
812        } else {
813            format!("{:+.1}", m.delta)
814        };
815        let _ = writeln!(
816            out,
817            "| {} | {} | {} | {} | {} {} |",
818            m.label,
819            prev,
820            cur,
821            delta,
822            m.direction.arrow(),
823            m.direction.label(),
824        );
825    }
826    let md_sha = trend
827        .compared_to
828        .git_sha
829        .as_deref()
830        .map_or(String::new(), |sha| format!(" ({sha})"));
831    let _ = writeln!(
832        out,
833        "\n*vs {}{} · {} {} available*\n",
834        trend
835            .compared_to
836            .timestamp
837            .get(..10)
838            .unwrap_or(&trend.compared_to.timestamp),
839        md_sha,
840        trend.snapshots_loaded,
841        if trend.snapshots_loaded == 1 {
842            "snapshot"
843        } else {
844            "snapshots"
845        },
846    );
847}
848
849/// Write the vital signs summary table to the output.
850fn write_vital_signs_section(out: &mut String, report: &crate::health_types::HealthReport) {
851    let Some(ref vs) = report.vital_signs else {
852        return;
853    };
854    out.push_str("## Vital Signs\n\n");
855    out.push_str("| Metric | Value |\n");
856    out.push_str("|:-------|------:|\n");
857    if vs.total_loc > 0 {
858        let _ = writeln!(out, "| Total LOC | {} |", vs.total_loc);
859    }
860    let _ = writeln!(out, "| Avg Cyclomatic | {:.1} |", vs.avg_cyclomatic);
861    let _ = writeln!(out, "| P90 Cyclomatic | {} |", vs.p90_cyclomatic);
862    if let Some(v) = vs.dead_file_pct {
863        let _ = writeln!(out, "| Dead Files | {v:.1}% |");
864    }
865    if let Some(v) = vs.dead_export_pct {
866        let _ = writeln!(out, "| Dead Exports | {v:.1}% |");
867    }
868    if let Some(v) = vs.maintainability_avg {
869        let _ = writeln!(out, "| Maintainability (avg) | {v:.1} |");
870    }
871    if let Some(v) = vs.hotspot_count {
872        let _ = writeln!(out, "| Hotspots | {v} |");
873    }
874    if let Some(v) = vs.circular_dep_count {
875        let _ = writeln!(out, "| Circular Deps | {v} |");
876    }
877    if let Some(v) = vs.unused_dep_count {
878        let _ = writeln!(out, "| Unused Deps | {v} |");
879    }
880    out.push('\n');
881}
882
883/// Write the complexity findings table to the output.
884fn write_findings_section(
885    out: &mut String,
886    report: &crate::health_types::HealthReport,
887    root: &Path,
888) {
889    if report.findings.is_empty() {
890        return;
891    }
892
893    let rel = |p: &Path| {
894        escape_backticks(&normalize_uri(
895            &relative_path(p, root).display().to_string(),
896        ))
897    };
898
899    let count = report.summary.functions_above_threshold;
900    let shown = report.findings.len();
901    if shown < count {
902        let _ = write!(
903            out,
904            "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
905            plural(count),
906        );
907    } else {
908        let _ = write!(
909            out,
910            "## Fallow: {count} high complexity function{}\n\n",
911            plural(count),
912        );
913    }
914
915    out.push_str("| File | Function | Severity | Cyclomatic | Cognitive | CRAP | Lines |\n");
916    out.push_str("|:-----|:---------|:---------|:-----------|:----------|:-----|:------|\n");
917
918    for finding in &report.findings {
919        let file_str = rel(&finding.path);
920        let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
921            " **!**"
922        } else {
923            ""
924        };
925        let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
926            " **!**"
927        } else {
928            ""
929        };
930        let severity_label = match finding.severity {
931            crate::health_types::FindingSeverity::Critical => "critical",
932            crate::health_types::FindingSeverity::High => "high",
933            crate::health_types::FindingSeverity::Moderate => "moderate",
934        };
935        let crap_cell = match finding.crap {
936            Some(crap) => {
937                let marker = if crap >= report.summary.max_crap_threshold {
938                    " **!**"
939                } else {
940                    ""
941                };
942                format!("{crap:.1}{marker}")
943            }
944            None => "-".to_string(),
945        };
946        let _ = writeln!(
947            out,
948            "| `{file_str}:{line}` | `{name}` | {severity_label} | {cyc}{cyc_marker} | {cog}{cog_marker} | {crap_cell} | {lines} |",
949            line = finding.line,
950            name = escape_backticks(&finding.name),
951            cyc = finding.cyclomatic,
952            cog = finding.cognitive,
953            lines = finding.line_count,
954        );
955    }
956
957    let s = &report.summary;
958    let _ = write!(
959        out,
960        "\n**{files}** files, **{funcs}** functions analyzed \
961         (thresholds: cyclomatic > {cyc}, cognitive > {cog}, CRAP >= {crap:.1})\n",
962        files = s.files_analyzed,
963        funcs = s.functions_analyzed,
964        cyc = s.max_cyclomatic_threshold,
965        cog = s.max_cognitive_threshold,
966        crap = s.max_crap_threshold,
967    );
968}
969
970/// Write the file health scores table to the output.
971fn write_file_scores_section(
972    out: &mut String,
973    report: &crate::health_types::HealthReport,
974    root: &Path,
975) {
976    if report.file_scores.is_empty() {
977        return;
978    }
979
980    let rel = |p: &Path| {
981        escape_backticks(&normalize_uri(
982            &relative_path(p, root).display().to_string(),
983        ))
984    };
985
986    out.push('\n');
987    let _ = writeln!(
988        out,
989        "### File Health Scores ({} files)\n",
990        report.file_scores.len(),
991    );
992    out.push_str("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density | Risk |\n");
993    out.push_str("|:-----|:---------------|:-------|:--------|:----------|:--------|:-----|\n");
994
995    for score in &report.file_scores {
996        let file_str = rel(&score.path);
997        let _ = writeln!(
998            out,
999            "| `{file_str}` | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} | {crap:.1} |",
1000            mi = score.maintainability_index,
1001            fi = score.fan_in,
1002            fan_out = score.fan_out,
1003            dead = score.dead_code_ratio * 100.0,
1004            density = score.complexity_density,
1005            crap = score.crap_max,
1006        );
1007    }
1008
1009    if let Some(avg) = report.summary.average_maintainability {
1010        let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
1011    }
1012}
1013
1014fn write_coverage_gaps_section(
1015    out: &mut String,
1016    report: &crate::health_types::HealthReport,
1017    root: &Path,
1018) {
1019    let Some(ref gaps) = report.coverage_gaps else {
1020        return;
1021    };
1022
1023    out.push('\n');
1024    let _ = writeln!(out, "### Coverage Gaps\n");
1025    let _ = writeln!(
1026        out,
1027        "*{} untested files · {} untested exports · {:.1}% file coverage*\n",
1028        gaps.summary.untested_files, gaps.summary.untested_exports, gaps.summary.file_coverage_pct,
1029    );
1030
1031    if gaps.files.is_empty() && gaps.exports.is_empty() {
1032        out.push_str("_No coverage gaps found in scope._\n");
1033        return;
1034    }
1035
1036    if !gaps.files.is_empty() {
1037        out.push_str("#### Files\n");
1038        for item in &gaps.files {
1039            let file_str = escape_backticks(&normalize_uri(
1040                &relative_path(&item.file.path, root).display().to_string(),
1041            ));
1042            let _ = writeln!(
1043                out,
1044                "- `{file_str}` ({count} value export{})",
1045                if item.file.value_export_count == 1 {
1046                    ""
1047                } else {
1048                    "s"
1049                },
1050                count = item.file.value_export_count,
1051            );
1052        }
1053        out.push('\n');
1054    }
1055
1056    if !gaps.exports.is_empty() {
1057        out.push_str("#### Exports\n");
1058        for item in &gaps.exports {
1059            let file_str = escape_backticks(&normalize_uri(
1060                &relative_path(&item.export.path, root).display().to_string(),
1061            ));
1062            let _ = writeln!(
1063                out,
1064                "- `{file_str}`:{} `{}`",
1065                item.export.line, item.export.export_name
1066            );
1067        }
1068    }
1069}
1070
1071/// Write the hotspots table to the output.
1072/// Render the four ownership table cells (bus, top contributor, declared
1073/// owner, notes) for the markdown hotspots table. Cells fall back to an
1074/// en-dash (U+2013) when ownership data is missing for an entry.
1075fn ownership_md_cells(
1076    ownership: Option<&crate::health_types::OwnershipMetrics>,
1077) -> (String, String, String, String) {
1078    let Some(o) = ownership else {
1079        let dash = "\u{2013}".to_string();
1080        return (dash.clone(), dash.clone(), dash.clone(), dash);
1081    };
1082    let bus = o.bus_factor.to_string();
1083    let top = format!(
1084        "`{}` ({:.0}%)",
1085        o.top_contributor.identifier,
1086        o.top_contributor.share * 100.0,
1087    );
1088    let owner = o
1089        .declared_owner
1090        .as_deref()
1091        .map_or_else(|| "\u{2013}".to_string(), str::to_string);
1092    let mut notes: Vec<&str> = Vec::new();
1093    if o.unowned == Some(true) {
1094        notes.push("**unowned**");
1095    }
1096    if o.drift {
1097        notes.push("drift");
1098    }
1099    let notes_str = if notes.is_empty() {
1100        "\u{2013}".to_string()
1101    } else {
1102        notes.join(", ")
1103    };
1104    (bus, top, owner, notes_str)
1105}
1106
1107fn write_hotspots_section(
1108    out: &mut String,
1109    report: &crate::health_types::HealthReport,
1110    root: &Path,
1111) {
1112    if report.hotspots.is_empty() {
1113        return;
1114    }
1115
1116    let rel = |p: &Path| {
1117        escape_backticks(&normalize_uri(
1118            &relative_path(p, root).display().to_string(),
1119        ))
1120    };
1121
1122    out.push('\n');
1123    let header = report.hotspot_summary.as_ref().map_or_else(
1124        || format!("### Hotspots ({} files)\n", report.hotspots.len()),
1125        |summary| {
1126            format!(
1127                "### Hotspots ({} files, since {})\n",
1128                report.hotspots.len(),
1129                summary.since,
1130            )
1131        },
1132    );
1133    let _ = writeln!(out, "{header}");
1134    // Add ownership columns when at least one entry has ownership data.
1135    let any_ownership = report.hotspots.iter().any(|e| e.ownership.is_some());
1136    if any_ownership {
1137        out.push_str(
1138            "| File | Score | Commits | Churn | Density | Fan-in | Trend | Bus | Top | Owner | Notes |\n"
1139        );
1140        out.push_str(
1141            "|:-----|:------|:--------|:------|:--------|:-------|:------|:----|:----|:------|:------|\n"
1142        );
1143    } else {
1144        out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
1145        out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
1146    }
1147
1148    for entry in &report.hotspots {
1149        let file_str = rel(&entry.path);
1150        if any_ownership {
1151            let (bus, top, owner, notes) = ownership_md_cells(entry.ownership.as_ref());
1152            let _ = writeln!(
1153                out,
1154                "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} | {bus} | {top} | {owner} | {notes} |",
1155                score = entry.score,
1156                commits = entry.commits,
1157                churn = entry.lines_added + entry.lines_deleted,
1158                density = entry.complexity_density,
1159                fi = entry.fan_in,
1160                trend = entry.trend,
1161            );
1162        } else {
1163            let _ = writeln!(
1164                out,
1165                "| `{file_str}` | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
1166                score = entry.score,
1167                commits = entry.commits,
1168                churn = entry.lines_added + entry.lines_deleted,
1169                density = entry.complexity_density,
1170                fi = entry.fan_in,
1171                trend = entry.trend,
1172            );
1173        }
1174    }
1175
1176    if let Some(ref summary) = report.hotspot_summary
1177        && summary.files_excluded > 0
1178    {
1179        let _ = write!(
1180            out,
1181            "\n*{} file{} excluded (< {} commits)*\n",
1182            summary.files_excluded,
1183            plural(summary.files_excluded),
1184            summary.min_commits,
1185        );
1186    }
1187}
1188
1189/// Write the refactoring targets table to the output.
1190fn write_targets_section(
1191    out: &mut String,
1192    report: &crate::health_types::HealthReport,
1193    root: &Path,
1194) {
1195    if report.targets.is_empty() {
1196        return;
1197    }
1198    let _ = write!(
1199        out,
1200        "\n### Refactoring Targets ({})\n\n",
1201        report.targets.len()
1202    );
1203    out.push_str("| Efficiency | Category | Effort / Confidence | File | Recommendation |\n");
1204    out.push_str("|:-----------|:---------|:--------------------|:-----|:---------------|\n");
1205    for target in &report.targets {
1206        let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
1207        let category = target.category.label();
1208        let effort = target.effort.label();
1209        let confidence = target.confidence.label();
1210        let _ = writeln!(
1211            out,
1212            "| {:.1} | {category} | {effort} / {confidence} | `{file_str}` | {} |",
1213            target.efficiency, target.recommendation,
1214        );
1215    }
1216}
1217
1218/// Write the metric legend collapsible section to the output.
1219fn write_metric_legend(out: &mut String, report: &crate::health_types::HealthReport) {
1220    let has_scores = !report.file_scores.is_empty();
1221    let has_coverage = report.coverage_gaps.is_some();
1222    let has_hotspots = !report.hotspots.is_empty();
1223    let has_targets = !report.targets.is_empty();
1224    if !has_scores && !has_coverage && !has_hotspots && !has_targets {
1225        return;
1226    }
1227    out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
1228    if has_scores {
1229        out.push_str("- **MI**: Maintainability Index (0\u{2013}100, higher is better)\n");
1230        out.push_str("- **Fan-in**: files that import this file (blast radius)\n");
1231        out.push_str("- **Fan-out**: files this file imports (coupling)\n");
1232        out.push_str("- **Dead Code**: % of value exports with zero references\n");
1233        out.push_str("- **Density**: cyclomatic complexity / lines of code\n");
1234    }
1235    if has_coverage {
1236        out.push_str(
1237            "- **File coverage**: runtime files also reachable from a discovered test root\n",
1238        );
1239        out.push_str("- **Untested export**: export with no reference chain from any test-reachable module\n");
1240    }
1241    if has_hotspots {
1242        out.push_str("- **Score**: churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n");
1243        out.push_str("- **Commits**: commits in the analysis window\n");
1244        out.push_str("- **Churn**: total lines added + deleted\n");
1245        out.push_str("- **Trend**: accelerating / stable / cooling\n");
1246    }
1247    if has_targets {
1248        out.push_str(
1249            "- **Efficiency**: priority / effort (higher = better quick-win value, default sort)\n",
1250        );
1251        out.push_str("- **Category**: recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
1252        out.push_str("- **Effort**: estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
1253        out.push_str("- **Confidence**: recommendation reliability (high = deterministic analysis, medium = heuristic, low = git-dependent)\n");
1254    }
1255    out.push_str(
1256        "\n[Full metric reference](https://docs.fallow.tools/explanations/metrics)\n\n</details>\n",
1257    );
1258}
1259
1260#[cfg(test)]
1261mod tests {
1262    use super::*;
1263    use crate::report::test_helpers::sample_results;
1264    use fallow_core::duplicates::{
1265        CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
1266        RefactoringKind, RefactoringSuggestion,
1267    };
1268    use fallow_core::results::*;
1269    use std::path::PathBuf;
1270
1271    #[test]
1272    fn markdown_empty_results_no_issues() {
1273        let root = PathBuf::from("/project");
1274        let results = AnalysisResults::default();
1275        let md = build_markdown(&results, &root);
1276        assert_eq!(md, "## Fallow: no issues found\n");
1277    }
1278
1279    #[test]
1280    fn markdown_contains_header_with_count() {
1281        let root = PathBuf::from("/project");
1282        let results = sample_results(&root);
1283        let md = build_markdown(&results, &root);
1284        assert!(md.starts_with(&format!(
1285            "## Fallow: {} issues found\n",
1286            results.total_issues()
1287        )));
1288    }
1289
1290    #[test]
1291    fn markdown_contains_all_sections() {
1292        let root = PathBuf::from("/project");
1293        let results = sample_results(&root);
1294        let md = build_markdown(&results, &root);
1295
1296        assert!(md.contains("### Unused files (1)"));
1297        assert!(md.contains("### Unused exports (1)"));
1298        assert!(md.contains("### Unused type exports (1)"));
1299        assert!(md.contains("### Unused dependencies (1)"));
1300        assert!(md.contains("### Unused devDependencies (1)"));
1301        assert!(md.contains("### Unused enum members (1)"));
1302        assert!(md.contains("### Unused class members (1)"));
1303        assert!(md.contains("### Unresolved imports (1)"));
1304        assert!(md.contains("### Unlisted dependencies (1)"));
1305        assert!(md.contains("### Duplicate exports (1)"));
1306        assert!(md.contains("### Type-only dependencies"));
1307        assert!(md.contains("### Test-only production dependencies"));
1308        assert!(md.contains("### Circular dependencies (1)"));
1309    }
1310
1311    #[test]
1312    fn markdown_unused_file_format() {
1313        let root = PathBuf::from("/project");
1314        let mut results = AnalysisResults::default();
1315        results
1316            .unused_files
1317            .push(UnusedFileFinding::with_actions(UnusedFile {
1318                path: root.join("src/dead.ts"),
1319            }));
1320        let md = build_markdown(&results, &root);
1321        assert!(md.contains("- `src/dead.ts`"));
1322    }
1323
1324    #[test]
1325    fn markdown_unused_export_grouped_by_file() {
1326        let root = PathBuf::from("/project");
1327        let mut results = AnalysisResults::default();
1328        results
1329            .unused_exports
1330            .push(UnusedExportFinding::with_actions(UnusedExport {
1331                path: root.join("src/utils.ts"),
1332                export_name: "helperFn".to_string(),
1333                is_type_only: false,
1334                line: 10,
1335                col: 4,
1336                span_start: 120,
1337                is_re_export: false,
1338            }));
1339        let md = build_markdown(&results, &root);
1340        assert!(md.contains("- `src/utils.ts`"));
1341        assert!(md.contains(":10 `helperFn`"));
1342    }
1343
1344    #[test]
1345    fn markdown_re_export_tagged() {
1346        let root = PathBuf::from("/project");
1347        let mut results = AnalysisResults::default();
1348        results
1349            .unused_exports
1350            .push(UnusedExportFinding::with_actions(UnusedExport {
1351                path: root.join("src/index.ts"),
1352                export_name: "reExported".to_string(),
1353                is_type_only: false,
1354                line: 1,
1355                col: 0,
1356                span_start: 0,
1357                is_re_export: true,
1358            }));
1359        let md = build_markdown(&results, &root);
1360        assert!(md.contains("(re-export)"));
1361    }
1362
1363    #[test]
1364    fn markdown_unused_dep_format() {
1365        let root = PathBuf::from("/project");
1366        let mut results = AnalysisResults::default();
1367        results
1368            .unused_dependencies
1369            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1370                package_name: "lodash".to_string(),
1371                location: DependencyLocation::Dependencies,
1372                path: root.join("package.json"),
1373                line: 5,
1374                used_in_workspaces: Vec::new(),
1375            }));
1376        let md = build_markdown(&results, &root);
1377        assert!(md.contains("- `lodash`"));
1378    }
1379
1380    #[test]
1381    fn markdown_circular_dep_format() {
1382        let root = PathBuf::from("/project");
1383        let mut results = AnalysisResults::default();
1384        results
1385            .circular_dependencies
1386            .push(CircularDependencyFinding::with_actions(
1387                CircularDependency {
1388                    files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1389                    length: 2,
1390                    line: 3,
1391                    col: 0,
1392                    is_cross_package: false,
1393                },
1394            ));
1395        let md = build_markdown(&results, &root);
1396        assert!(md.contains("`src/a.ts`"));
1397        assert!(md.contains("`src/b.ts`"));
1398        assert!(md.contains("\u{2192}"));
1399    }
1400
1401    #[test]
1402    fn markdown_strips_root_prefix() {
1403        let root = PathBuf::from("/project");
1404        let mut results = AnalysisResults::default();
1405        results
1406            .unused_files
1407            .push(UnusedFileFinding::with_actions(UnusedFile {
1408                path: PathBuf::from("/project/src/deep/nested/file.ts"),
1409            }));
1410        let md = build_markdown(&results, &root);
1411        assert!(md.contains("`src/deep/nested/file.ts`"));
1412        assert!(!md.contains("/project/"));
1413    }
1414
1415    #[test]
1416    fn markdown_single_issue_no_plural() {
1417        let root = PathBuf::from("/project");
1418        let mut results = AnalysisResults::default();
1419        results
1420            .unused_files
1421            .push(UnusedFileFinding::with_actions(UnusedFile {
1422                path: root.join("src/dead.ts"),
1423            }));
1424        let md = build_markdown(&results, &root);
1425        assert!(md.starts_with("## Fallow: 1 issue found\n"));
1426    }
1427
1428    #[test]
1429    fn markdown_type_only_dep_format() {
1430        let root = PathBuf::from("/project");
1431        let mut results = AnalysisResults::default();
1432        results
1433            .type_only_dependencies
1434            .push(TypeOnlyDependencyFinding::with_actions(
1435                TypeOnlyDependency {
1436                    package_name: "zod".to_string(),
1437                    path: root.join("package.json"),
1438                    line: 8,
1439                },
1440            ));
1441        let md = build_markdown(&results, &root);
1442        assert!(md.contains("### Type-only dependencies"));
1443        assert!(md.contains("- `zod`"));
1444    }
1445
1446    #[test]
1447    fn markdown_escapes_backticks_in_export_names() {
1448        let root = PathBuf::from("/project");
1449        let mut results = AnalysisResults::default();
1450        results
1451            .unused_exports
1452            .push(UnusedExportFinding::with_actions(UnusedExport {
1453                path: root.join("src/utils.ts"),
1454                export_name: "foo`bar".to_string(),
1455                is_type_only: false,
1456                line: 1,
1457                col: 0,
1458                span_start: 0,
1459                is_re_export: false,
1460            }));
1461        let md = build_markdown(&results, &root);
1462        assert!(md.contains("foo\\`bar"));
1463        assert!(!md.contains("foo`bar`"));
1464    }
1465
1466    #[test]
1467    fn markdown_escapes_backticks_in_package_names() {
1468        let root = PathBuf::from("/project");
1469        let mut results = AnalysisResults::default();
1470        results
1471            .unused_dependencies
1472            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1473                package_name: "pkg`name".to_string(),
1474                location: DependencyLocation::Dependencies,
1475                path: root.join("package.json"),
1476                line: 5,
1477                used_in_workspaces: Vec::new(),
1478            }));
1479        let md = build_markdown(&results, &root);
1480        assert!(md.contains("pkg\\`name"));
1481    }
1482
1483    // ── Duplication markdown ──
1484
1485    #[test]
1486    fn duplication_markdown_empty() {
1487        let report = DuplicationReport::default();
1488        let root = PathBuf::from("/project");
1489        let md = build_duplication_markdown(&report, &root);
1490        assert_eq!(md, "## Fallow: no code duplication found\n");
1491    }
1492
1493    #[test]
1494    fn duplication_markdown_contains_groups() {
1495        let root = PathBuf::from("/project");
1496        let report = DuplicationReport {
1497            clone_groups: vec![CloneGroup {
1498                instances: vec![
1499                    CloneInstance {
1500                        file: root.join("src/a.ts"),
1501                        start_line: 1,
1502                        end_line: 10,
1503                        start_col: 0,
1504                        end_col: 0,
1505                        fragment: String::new(),
1506                    },
1507                    CloneInstance {
1508                        file: root.join("src/b.ts"),
1509                        start_line: 5,
1510                        end_line: 14,
1511                        start_col: 0,
1512                        end_col: 0,
1513                        fragment: String::new(),
1514                    },
1515                ],
1516                token_count: 50,
1517                line_count: 10,
1518            }],
1519            clone_families: vec![],
1520            mirrored_directories: vec![],
1521            stats: DuplicationStats {
1522                total_files: 10,
1523                files_with_clones: 2,
1524                total_lines: 500,
1525                duplicated_lines: 20,
1526                total_tokens: 2500,
1527                duplicated_tokens: 100,
1528                clone_groups: 1,
1529                clone_instances: 2,
1530                duplication_percentage: 4.0,
1531                clone_groups_below_min_occurrences: 0,
1532            },
1533        };
1534        let md = build_duplication_markdown(&report, &root);
1535        assert!(md.contains("**Clone group 1**"));
1536        assert!(md.contains("`src/a.ts:1-10`"));
1537        assert!(md.contains("`src/b.ts:5-14`"));
1538        assert!(md.contains("4.0% duplication"));
1539    }
1540
1541    #[test]
1542    fn duplication_markdown_contains_families() {
1543        let root = PathBuf::from("/project");
1544        let report = DuplicationReport {
1545            clone_groups: vec![CloneGroup {
1546                instances: vec![CloneInstance {
1547                    file: root.join("src/a.ts"),
1548                    start_line: 1,
1549                    end_line: 5,
1550                    start_col: 0,
1551                    end_col: 0,
1552                    fragment: String::new(),
1553                }],
1554                token_count: 30,
1555                line_count: 5,
1556            }],
1557            clone_families: vec![CloneFamily {
1558                files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
1559                groups: vec![],
1560                total_duplicated_lines: 20,
1561                total_duplicated_tokens: 100,
1562                suggestions: vec![RefactoringSuggestion {
1563                    kind: RefactoringKind::ExtractFunction,
1564                    description: "Extract shared utility function".to_string(),
1565                    estimated_savings: 15,
1566                }],
1567            }],
1568            mirrored_directories: vec![],
1569            stats: DuplicationStats {
1570                clone_groups: 1,
1571                clone_instances: 1,
1572                duplication_percentage: 2.0,
1573                ..Default::default()
1574            },
1575        };
1576        let md = build_duplication_markdown(&report, &root);
1577        assert!(md.contains("### Clone Families"));
1578        assert!(md.contains("**Family 1**"));
1579        assert!(md.contains("Extract shared utility function"));
1580        assert!(md.contains("~15 lines saved"));
1581    }
1582
1583    // ── Health markdown ──
1584
1585    #[test]
1586    fn health_markdown_empty_no_findings() {
1587        let root = PathBuf::from("/project");
1588        let report = crate::health_types::HealthReport {
1589            summary: crate::health_types::HealthSummary {
1590                files_analyzed: 10,
1591                functions_analyzed: 50,
1592                ..Default::default()
1593            },
1594            ..Default::default()
1595        };
1596        let md = build_health_markdown(&report, &root);
1597        assert!(md.contains("no functions exceed complexity thresholds"));
1598        assert!(md.contains("**50** functions analyzed"));
1599    }
1600
1601    #[test]
1602    fn health_markdown_table_format() {
1603        let root = PathBuf::from("/project");
1604        let report = crate::health_types::HealthReport {
1605            findings: vec![
1606                crate::health_types::ComplexityViolation {
1607                    path: root.join("src/utils.ts"),
1608                    name: "parseExpression".to_string(),
1609                    line: 42,
1610                    col: 0,
1611                    cyclomatic: 25,
1612                    cognitive: 30,
1613                    line_count: 80,
1614                    param_count: 0,
1615                    exceeded: crate::health_types::ExceededThreshold::Both,
1616                    severity: crate::health_types::FindingSeverity::High,
1617                    crap: None,
1618                    coverage_pct: None,
1619                    coverage_tier: None,
1620                    coverage_source: None,
1621                    inherited_from: None,
1622                    component_rollup: None,
1623                }
1624                .into(),
1625            ],
1626            summary: crate::health_types::HealthSummary {
1627                files_analyzed: 10,
1628                functions_analyzed: 50,
1629                functions_above_threshold: 1,
1630                ..Default::default()
1631            },
1632            ..Default::default()
1633        };
1634        let md = build_health_markdown(&report, &root);
1635        assert!(md.contains("## Fallow: 1 high complexity function\n"));
1636        assert!(md.contains("| File | Function |"));
1637        assert!(md.contains("`src/utils.ts:42`"));
1638        assert!(md.contains("`parseExpression`"));
1639        assert!(md.contains("25 **!**"));
1640        assert!(md.contains("30 **!**"));
1641        assert!(md.contains("| 80 |"));
1642        // CRAP column renders `-` when the finding didn't trigger on CRAP.
1643        assert!(md.contains("| - |"));
1644    }
1645
1646    #[test]
1647    fn health_markdown_crap_column_shows_score_and_marker() {
1648        let root = PathBuf::from("/project");
1649        let report = crate::health_types::HealthReport {
1650            findings: vec![
1651                crate::health_types::ComplexityViolation {
1652                    path: root.join("src/risky.ts"),
1653                    name: "branchy".to_string(),
1654                    line: 1,
1655                    col: 0,
1656                    cyclomatic: 67,
1657                    cognitive: 10,
1658                    line_count: 80,
1659                    param_count: 1,
1660                    exceeded: crate::health_types::ExceededThreshold::CyclomaticCrap,
1661                    severity: crate::health_types::FindingSeverity::Critical,
1662                    crap: Some(182.0),
1663                    coverage_pct: None,
1664                    coverage_tier: None,
1665                    coverage_source: None,
1666                    inherited_from: None,
1667                    component_rollup: None,
1668                }
1669                .into(),
1670            ],
1671            summary: crate::health_types::HealthSummary {
1672                files_analyzed: 1,
1673                functions_analyzed: 1,
1674                functions_above_threshold: 1,
1675                ..Default::default()
1676            },
1677            ..Default::default()
1678        };
1679        let md = build_health_markdown(&report, &root);
1680        assert!(
1681            md.contains("| CRAP |"),
1682            "markdown table should have CRAP column header: {md}"
1683        );
1684        assert!(
1685            md.contains("182.0 **!**"),
1686            "CRAP value should be rendered with a threshold marker: {md}"
1687        );
1688        assert!(
1689            md.contains("CRAP >="),
1690            "trailing summary line should reference the CRAP threshold: {md}"
1691        );
1692    }
1693
1694    #[test]
1695    fn health_markdown_no_marker_when_below_threshold() {
1696        let root = PathBuf::from("/project");
1697        let report = crate::health_types::HealthReport {
1698            findings: vec![
1699                crate::health_types::ComplexityViolation {
1700                    path: root.join("src/utils.ts"),
1701                    name: "helper".to_string(),
1702                    line: 10,
1703                    col: 0,
1704                    cyclomatic: 15,
1705                    cognitive: 20,
1706                    line_count: 30,
1707                    param_count: 0,
1708                    exceeded: crate::health_types::ExceededThreshold::Cognitive,
1709                    severity: crate::health_types::FindingSeverity::High,
1710                    crap: None,
1711                    coverage_pct: None,
1712                    coverage_tier: None,
1713                    coverage_source: None,
1714                    inherited_from: None,
1715                    component_rollup: None,
1716                }
1717                .into(),
1718            ],
1719            summary: crate::health_types::HealthSummary {
1720                files_analyzed: 5,
1721                functions_analyzed: 20,
1722                functions_above_threshold: 1,
1723                ..Default::default()
1724            },
1725            ..Default::default()
1726        };
1727        let md = build_health_markdown(&report, &root);
1728        // Cyclomatic 15 is below threshold 20, no marker
1729        assert!(md.contains("| 15 |"));
1730        // Cognitive 20 exceeds threshold 15, has marker
1731        assert!(md.contains("20 **!**"));
1732    }
1733
1734    #[test]
1735    fn health_markdown_with_targets() {
1736        use crate::health_types::*;
1737
1738        let root = PathBuf::from("/project");
1739        let report = HealthReport {
1740            summary: HealthSummary {
1741                files_analyzed: 10,
1742                functions_analyzed: 50,
1743                ..Default::default()
1744            },
1745            targets: vec![
1746                RefactoringTarget {
1747                    path: PathBuf::from("/project/src/complex.ts"),
1748                    priority: 82.5,
1749                    efficiency: 27.5,
1750                    recommendation: "Split high-impact file".into(),
1751                    category: RecommendationCategory::SplitHighImpact,
1752                    effort: crate::health_types::EffortEstimate::High,
1753                    confidence: crate::health_types::Confidence::Medium,
1754                    factors: vec![ContributingFactor {
1755                        metric: "fan_in",
1756                        value: 25.0,
1757                        threshold: 10.0,
1758                        detail: "25 files depend on this".into(),
1759                    }],
1760                    evidence: None,
1761                }
1762                .into(),
1763                RefactoringTarget {
1764                    path: PathBuf::from("/project/src/legacy.ts"),
1765                    priority: 45.0,
1766                    efficiency: 45.0,
1767                    recommendation: "Remove 5 unused exports".into(),
1768                    category: RecommendationCategory::RemoveDeadCode,
1769                    effort: crate::health_types::EffortEstimate::Low,
1770                    confidence: crate::health_types::Confidence::High,
1771                    factors: vec![],
1772                    evidence: None,
1773                }
1774                .into(),
1775            ],
1776            ..Default::default()
1777        };
1778        let md = build_health_markdown(&report, &root);
1779
1780        // Should have refactoring targets section
1781        assert!(
1782            md.contains("Refactoring Targets"),
1783            "should contain targets heading"
1784        );
1785        assert!(
1786            md.contains("src/complex.ts"),
1787            "should contain target file path"
1788        );
1789        assert!(md.contains("27.5"), "should contain efficiency score");
1790        assert!(
1791            md.contains("Split high-impact file"),
1792            "should contain recommendation"
1793        );
1794        assert!(md.contains("src/legacy.ts"), "should contain second target");
1795    }
1796
1797    #[test]
1798    fn health_markdown_with_coverage_gaps() {
1799        use crate::health_types::*;
1800
1801        let root = PathBuf::from("/project");
1802        let report = HealthReport {
1803            summary: HealthSummary {
1804                files_analyzed: 10,
1805                functions_analyzed: 50,
1806                ..Default::default()
1807            },
1808            coverage_gaps: Some(CoverageGaps {
1809                summary: CoverageGapSummary {
1810                    runtime_files: 2,
1811                    covered_files: 0,
1812                    file_coverage_pct: 0.0,
1813                    untested_files: 1,
1814                    untested_exports: 1,
1815                },
1816                files: vec![UntestedFileFinding::with_actions(
1817                    UntestedFile {
1818                        path: root.join("src/app.ts"),
1819                        value_export_count: 2,
1820                    },
1821                    &root,
1822                )],
1823                exports: vec![UntestedExportFinding::with_actions(
1824                    UntestedExport {
1825                        path: root.join("src/app.ts"),
1826                        export_name: "loader".into(),
1827                        line: 12,
1828                        col: 4,
1829                    },
1830                    &root,
1831                )],
1832            }),
1833            ..Default::default()
1834        };
1835
1836        let md = build_health_markdown(&report, &root);
1837        assert!(md.contains("### Coverage Gaps"));
1838        assert!(md.contains("*1 untested files"));
1839        assert!(md.contains("`src/app.ts` (2 value exports)"));
1840        assert!(md.contains("`src/app.ts`:12 `loader`"));
1841    }
1842
1843    // ── Dependency in workspace package ──
1844
1845    #[test]
1846    fn markdown_dep_in_workspace_shows_package_label() {
1847        let root = PathBuf::from("/project");
1848        let mut results = AnalysisResults::default();
1849        results
1850            .unused_dependencies
1851            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1852                package_name: "lodash".to_string(),
1853                location: DependencyLocation::Dependencies,
1854                path: root.join("packages/core/package.json"),
1855                line: 5,
1856                used_in_workspaces: Vec::new(),
1857            }));
1858        let md = build_markdown(&results, &root);
1859        // Non-root package.json should show the label
1860        assert!(md.contains("(packages/core/package.json)"));
1861    }
1862
1863    #[test]
1864    fn markdown_dep_at_root_no_extra_label() {
1865        let root = PathBuf::from("/project");
1866        let mut results = AnalysisResults::default();
1867        results
1868            .unused_dependencies
1869            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1870                package_name: "lodash".to_string(),
1871                location: DependencyLocation::Dependencies,
1872                path: root.join("package.json"),
1873                line: 5,
1874                used_in_workspaces: Vec::new(),
1875            }));
1876        let md = build_markdown(&results, &root);
1877        assert!(md.contains("- `lodash`"));
1878        assert!(!md.contains("(package.json)"));
1879    }
1880
1881    #[test]
1882    fn markdown_root_dep_with_cross_workspace_context_uses_context_label() {
1883        let root = PathBuf::from("/project");
1884        let mut results = AnalysisResults::default();
1885        results
1886            .unused_dependencies
1887            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1888                package_name: "lodash-es".to_string(),
1889                location: DependencyLocation::Dependencies,
1890                path: root.join("package.json"),
1891                line: 5,
1892                used_in_workspaces: vec![root.join("packages/consumer")],
1893            }));
1894        let md = build_markdown(&results, &root);
1895        assert!(md.contains("- `lodash-es` (imported in packages/consumer)"));
1896        assert!(!md.contains("(package.json; imported in packages/consumer)"));
1897    }
1898
1899    // ── Multiple exports same file grouped ──
1900
1901    #[test]
1902    fn markdown_exports_grouped_by_file() {
1903        let root = PathBuf::from("/project");
1904        let mut results = AnalysisResults::default();
1905        results
1906            .unused_exports
1907            .push(UnusedExportFinding::with_actions(UnusedExport {
1908                path: root.join("src/utils.ts"),
1909                export_name: "alpha".to_string(),
1910                is_type_only: false,
1911                line: 5,
1912                col: 0,
1913                span_start: 0,
1914                is_re_export: false,
1915            }));
1916        results
1917            .unused_exports
1918            .push(UnusedExportFinding::with_actions(UnusedExport {
1919                path: root.join("src/utils.ts"),
1920                export_name: "beta".to_string(),
1921                is_type_only: false,
1922                line: 10,
1923                col: 0,
1924                span_start: 0,
1925                is_re_export: false,
1926            }));
1927        results
1928            .unused_exports
1929            .push(UnusedExportFinding::with_actions(UnusedExport {
1930                path: root.join("src/other.ts"),
1931                export_name: "gamma".to_string(),
1932                is_type_only: false,
1933                line: 1,
1934                col: 0,
1935                span_start: 0,
1936                is_re_export: false,
1937            }));
1938        let md = build_markdown(&results, &root);
1939        // File header should appear only once for utils.ts
1940        let utils_count = md.matches("- `src/utils.ts`").count();
1941        assert_eq!(utils_count, 1, "file header should appear once per file");
1942        // Both exports should be under it as sub-items
1943        assert!(md.contains(":5 `alpha`"));
1944        assert!(md.contains(":10 `beta`"));
1945    }
1946
1947    // ── Multiple issues plural header ──
1948
1949    #[test]
1950    fn markdown_multiple_issues_plural() {
1951        let root = PathBuf::from("/project");
1952        let mut results = AnalysisResults::default();
1953        results
1954            .unused_files
1955            .push(UnusedFileFinding::with_actions(UnusedFile {
1956                path: root.join("src/a.ts"),
1957            }));
1958        results
1959            .unused_files
1960            .push(UnusedFileFinding::with_actions(UnusedFile {
1961                path: root.join("src/b.ts"),
1962            }));
1963        let md = build_markdown(&results, &root);
1964        assert!(md.starts_with("## Fallow: 2 issues found\n"));
1965    }
1966
1967    // ── Duplication markdown with zero estimated savings ──
1968
1969    #[test]
1970    fn duplication_markdown_zero_savings_no_suffix() {
1971        let root = PathBuf::from("/project");
1972        let report = DuplicationReport {
1973            clone_groups: vec![CloneGroup {
1974                instances: vec![CloneInstance {
1975                    file: root.join("src/a.ts"),
1976                    start_line: 1,
1977                    end_line: 5,
1978                    start_col: 0,
1979                    end_col: 0,
1980                    fragment: String::new(),
1981                }],
1982                token_count: 30,
1983                line_count: 5,
1984            }],
1985            clone_families: vec![CloneFamily {
1986                files: vec![root.join("src/a.ts")],
1987                groups: vec![],
1988                total_duplicated_lines: 5,
1989                total_duplicated_tokens: 30,
1990                suggestions: vec![RefactoringSuggestion {
1991                    kind: RefactoringKind::ExtractFunction,
1992                    description: "Extract function".to_string(),
1993                    estimated_savings: 0,
1994                }],
1995            }],
1996            mirrored_directories: vec![],
1997            stats: DuplicationStats {
1998                clone_groups: 1,
1999                clone_instances: 1,
2000                duplication_percentage: 1.0,
2001                ..Default::default()
2002            },
2003        };
2004        let md = build_duplication_markdown(&report, &root);
2005        assert!(md.contains("Extract function"));
2006        assert!(!md.contains("lines saved"));
2007    }
2008
2009    // ── Health markdown vital signs ──
2010
2011    #[test]
2012    fn health_markdown_vital_signs_table() {
2013        let root = PathBuf::from("/project");
2014        let report = crate::health_types::HealthReport {
2015            summary: crate::health_types::HealthSummary {
2016                files_analyzed: 10,
2017                functions_analyzed: 50,
2018                ..Default::default()
2019            },
2020            vital_signs: Some(crate::health_types::VitalSigns {
2021                avg_cyclomatic: 3.5,
2022                p90_cyclomatic: 12,
2023                dead_file_pct: Some(5.0),
2024                dead_export_pct: Some(10.2),
2025                duplication_pct: None,
2026                maintainability_avg: Some(72.3),
2027                hotspot_count: Some(3),
2028                circular_dep_count: Some(1),
2029                unused_dep_count: Some(2),
2030                counts: None,
2031                unit_size_profile: None,
2032                unit_interfacing_profile: None,
2033                p95_fan_in: None,
2034                coupling_high_pct: None,
2035                total_loc: 15_200,
2036                ..Default::default()
2037            }),
2038            ..Default::default()
2039        };
2040        let md = build_health_markdown(&report, &root);
2041        assert!(md.contains("## Vital Signs"));
2042        assert!(md.contains("| Metric | Value |"));
2043        assert!(md.contains("| Total LOC | 15200 |"));
2044        assert!(md.contains("| Avg Cyclomatic | 3.5 |"));
2045        assert!(md.contains("| P90 Cyclomatic | 12 |"));
2046        assert!(md.contains("| Dead Files | 5.0% |"));
2047        assert!(md.contains("| Dead Exports | 10.2% |"));
2048        assert!(md.contains("| Maintainability (avg) | 72.3 |"));
2049        assert!(md.contains("| Hotspots | 3 |"));
2050        assert!(md.contains("| Circular Deps | 1 |"));
2051        assert!(md.contains("| Unused Deps | 2 |"));
2052    }
2053
2054    // ── Health markdown file scores ──
2055
2056    #[test]
2057    fn health_markdown_file_scores_table() {
2058        let root = PathBuf::from("/project");
2059        let report = crate::health_types::HealthReport {
2060            findings: vec![
2061                crate::health_types::ComplexityViolation {
2062                    path: root.join("src/dummy.ts"),
2063                    name: "fn".to_string(),
2064                    line: 1,
2065                    col: 0,
2066                    cyclomatic: 25,
2067                    cognitive: 20,
2068                    line_count: 50,
2069                    param_count: 0,
2070                    exceeded: crate::health_types::ExceededThreshold::Both,
2071                    severity: crate::health_types::FindingSeverity::High,
2072                    crap: None,
2073                    coverage_pct: None,
2074                    coverage_tier: None,
2075                    coverage_source: None,
2076                    inherited_from: None,
2077                    component_rollup: None,
2078                }
2079                .into(),
2080            ],
2081            summary: crate::health_types::HealthSummary {
2082                files_analyzed: 5,
2083                functions_analyzed: 10,
2084                functions_above_threshold: 1,
2085                files_scored: Some(1),
2086                average_maintainability: Some(65.0),
2087                ..Default::default()
2088            },
2089            file_scores: vec![crate::health_types::FileHealthScore {
2090                path: root.join("src/utils.ts"),
2091                fan_in: 5,
2092                fan_out: 3,
2093                dead_code_ratio: 0.25,
2094                complexity_density: 0.8,
2095                maintainability_index: 72.5,
2096                total_cyclomatic: 40,
2097                total_cognitive: 30,
2098                function_count: 10,
2099                lines: 200,
2100                crap_max: 0.0,
2101                crap_above_threshold: 0,
2102            }],
2103            ..Default::default()
2104        };
2105        let md = build_health_markdown(&report, &root);
2106        assert!(md.contains("### File Health Scores (1 files)"));
2107        assert!(md.contains("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density |"));
2108        assert!(md.contains("| `src/utils.ts` | 72.5 | 5 | 3 | 25% | 0.80 |"));
2109        assert!(md.contains("**Average maintainability index:** 65.0/100"));
2110    }
2111
2112    // ── Health markdown hotspots ──
2113
2114    #[test]
2115    fn health_markdown_hotspots_table() {
2116        let root = PathBuf::from("/project");
2117        let report = crate::health_types::HealthReport {
2118            findings: vec![
2119                crate::health_types::ComplexityViolation {
2120                    path: root.join("src/dummy.ts"),
2121                    name: "fn".to_string(),
2122                    line: 1,
2123                    col: 0,
2124                    cyclomatic: 25,
2125                    cognitive: 20,
2126                    line_count: 50,
2127                    param_count: 0,
2128                    exceeded: crate::health_types::ExceededThreshold::Both,
2129                    severity: crate::health_types::FindingSeverity::High,
2130                    crap: None,
2131                    coverage_pct: None,
2132                    coverage_tier: None,
2133                    coverage_source: None,
2134                    inherited_from: None,
2135                    component_rollup: None,
2136                }
2137                .into(),
2138            ],
2139            summary: crate::health_types::HealthSummary {
2140                files_analyzed: 5,
2141                functions_analyzed: 10,
2142                functions_above_threshold: 1,
2143                ..Default::default()
2144            },
2145            hotspots: vec![
2146                crate::health_types::HotspotEntry {
2147                    path: root.join("src/hot.ts"),
2148                    score: 85.0,
2149                    commits: 42,
2150                    weighted_commits: 35.0,
2151                    lines_added: 500,
2152                    lines_deleted: 200,
2153                    complexity_density: 1.2,
2154                    fan_in: 10,
2155                    trend: fallow_core::churn::ChurnTrend::Accelerating,
2156                    ownership: None,
2157                    is_test_path: false,
2158                }
2159                .into(),
2160            ],
2161            hotspot_summary: Some(crate::health_types::HotspotSummary {
2162                since: "6 months".to_string(),
2163                min_commits: 3,
2164                files_analyzed: 50,
2165                files_excluded: 5,
2166                shallow_clone: false,
2167            }),
2168            ..Default::default()
2169        };
2170        let md = build_health_markdown(&report, &root);
2171        assert!(md.contains("### Hotspots (1 files, since 6 months)"));
2172        assert!(md.contains("| `src/hot.ts` | 85.0 | 42 | 700 | 1.20 | 10 | accelerating |"));
2173        assert!(md.contains("*5 files excluded (< 3 commits)*"));
2174    }
2175
2176    // ── Health markdown metric legend ──
2177
2178    #[test]
2179    fn health_markdown_metric_legend_with_scores() {
2180        let root = PathBuf::from("/project");
2181        let report = crate::health_types::HealthReport {
2182            findings: vec![
2183                crate::health_types::ComplexityViolation {
2184                    path: root.join("src/x.ts"),
2185                    name: "f".to_string(),
2186                    line: 1,
2187                    col: 0,
2188                    cyclomatic: 25,
2189                    cognitive: 20,
2190                    line_count: 10,
2191                    param_count: 0,
2192                    exceeded: crate::health_types::ExceededThreshold::Both,
2193                    severity: crate::health_types::FindingSeverity::High,
2194                    crap: None,
2195                    coverage_pct: None,
2196                    coverage_tier: None,
2197                    coverage_source: None,
2198                    inherited_from: None,
2199                    component_rollup: None,
2200                }
2201                .into(),
2202            ],
2203            summary: crate::health_types::HealthSummary {
2204                files_analyzed: 1,
2205                functions_analyzed: 1,
2206                functions_above_threshold: 1,
2207                files_scored: Some(1),
2208                average_maintainability: Some(70.0),
2209                ..Default::default()
2210            },
2211            file_scores: vec![crate::health_types::FileHealthScore {
2212                path: root.join("src/x.ts"),
2213                fan_in: 1,
2214                fan_out: 1,
2215                dead_code_ratio: 0.0,
2216                complexity_density: 0.5,
2217                maintainability_index: 80.0,
2218                total_cyclomatic: 10,
2219                total_cognitive: 8,
2220                function_count: 2,
2221                lines: 50,
2222                crap_max: 0.0,
2223                crap_above_threshold: 0,
2224            }],
2225            ..Default::default()
2226        };
2227        let md = build_health_markdown(&report, &root);
2228        assert!(md.contains("<details><summary>Metric definitions</summary>"));
2229        assert!(md.contains("**MI**: Maintainability Index"));
2230        assert!(md.contains("**Fan-in**"));
2231        assert!(md.contains("Full metric reference"));
2232    }
2233
2234    // ── Health markdown truncated findings ──
2235
2236    #[test]
2237    fn health_markdown_truncated_findings_shown_count() {
2238        let root = PathBuf::from("/project");
2239        let report = crate::health_types::HealthReport {
2240            findings: vec![
2241                crate::health_types::ComplexityViolation {
2242                    path: root.join("src/x.ts"),
2243                    name: "f".to_string(),
2244                    line: 1,
2245                    col: 0,
2246                    cyclomatic: 25,
2247                    cognitive: 20,
2248                    line_count: 10,
2249                    param_count: 0,
2250                    exceeded: crate::health_types::ExceededThreshold::Both,
2251                    severity: crate::health_types::FindingSeverity::High,
2252                    crap: None,
2253                    coverage_pct: None,
2254                    coverage_tier: None,
2255                    coverage_source: None,
2256                    inherited_from: None,
2257                    component_rollup: None,
2258                }
2259                .into(),
2260            ],
2261            summary: crate::health_types::HealthSummary {
2262                files_analyzed: 10,
2263                functions_analyzed: 50,
2264                functions_above_threshold: 5, // 5 total but only 1 shown
2265                ..Default::default()
2266            },
2267            ..Default::default()
2268        };
2269        let md = build_health_markdown(&report, &root);
2270        assert!(md.contains("5 high complexity functions (1 shown)"));
2271    }
2272
2273    // ── escape_backticks ──
2274
2275    #[test]
2276    fn escape_backticks_handles_multiple() {
2277        assert_eq!(escape_backticks("a`b`c"), "a\\`b\\`c");
2278    }
2279
2280    #[test]
2281    fn escape_backticks_no_backticks_unchanged() {
2282        assert_eq!(escape_backticks("hello"), "hello");
2283    }
2284
2285    // ── Unresolved import in markdown ──
2286
2287    #[test]
2288    fn markdown_unresolved_import_grouped_by_file() {
2289        let root = PathBuf::from("/project");
2290        let mut results = AnalysisResults::default();
2291        results
2292            .unresolved_imports
2293            .push(UnresolvedImportFinding::with_actions(UnresolvedImport {
2294                path: root.join("src/app.ts"),
2295                specifier: "./missing".to_string(),
2296                line: 3,
2297                col: 0,
2298                specifier_col: 0,
2299            }));
2300        let md = build_markdown(&results, &root);
2301        assert!(md.contains("### Unresolved imports (1)"));
2302        assert!(md.contains("- `src/app.ts`"));
2303        assert!(md.contains(":3 `./missing`"));
2304    }
2305
2306    // ── Markdown optional dep ──
2307
2308    #[test]
2309    fn markdown_unused_optional_dep() {
2310        let root = PathBuf::from("/project");
2311        let mut results = AnalysisResults::default();
2312        results
2313            .unused_optional_dependencies
2314            .push(UnusedOptionalDependencyFinding::with_actions(
2315                UnusedDependency {
2316                    package_name: "fsevents".to_string(),
2317                    location: DependencyLocation::OptionalDependencies,
2318                    path: root.join("package.json"),
2319                    line: 12,
2320                    used_in_workspaces: Vec::new(),
2321                },
2322            ));
2323        let md = build_markdown(&results, &root);
2324        assert!(md.contains("### Unused optionalDependencies (1)"));
2325        assert!(md.contains("- `fsevents`"));
2326    }
2327
2328    // ── Health markdown no hotspot exclusion message when 0 excluded ──
2329
2330    #[test]
2331    fn health_markdown_hotspots_no_excluded_message() {
2332        let root = PathBuf::from("/project");
2333        let report = crate::health_types::HealthReport {
2334            findings: vec![
2335                crate::health_types::ComplexityViolation {
2336                    path: root.join("src/x.ts"),
2337                    name: "f".to_string(),
2338                    line: 1,
2339                    col: 0,
2340                    cyclomatic: 25,
2341                    cognitive: 20,
2342                    line_count: 10,
2343                    param_count: 0,
2344                    exceeded: crate::health_types::ExceededThreshold::Both,
2345                    severity: crate::health_types::FindingSeverity::High,
2346                    crap: None,
2347                    coverage_pct: None,
2348                    coverage_tier: None,
2349                    coverage_source: None,
2350                    inherited_from: None,
2351                    component_rollup: None,
2352                }
2353                .into(),
2354            ],
2355            summary: crate::health_types::HealthSummary {
2356                files_analyzed: 5,
2357                functions_analyzed: 10,
2358                functions_above_threshold: 1,
2359                ..Default::default()
2360            },
2361            hotspots: vec![
2362                crate::health_types::HotspotEntry {
2363                    path: root.join("src/hot.ts"),
2364                    score: 50.0,
2365                    commits: 10,
2366                    weighted_commits: 8.0,
2367                    lines_added: 100,
2368                    lines_deleted: 50,
2369                    complexity_density: 0.5,
2370                    fan_in: 3,
2371                    trend: fallow_core::churn::ChurnTrend::Stable,
2372                    ownership: None,
2373                    is_test_path: false,
2374                }
2375                .into(),
2376            ],
2377            hotspot_summary: Some(crate::health_types::HotspotSummary {
2378                since: "6 months".to_string(),
2379                min_commits: 3,
2380                files_analyzed: 50,
2381                files_excluded: 0,
2382                shallow_clone: false,
2383            }),
2384            ..Default::default()
2385        };
2386        let md = build_health_markdown(&report, &root);
2387        assert!(!md.contains("files excluded"));
2388    }
2389
2390    // ── Duplication markdown plural ──
2391
2392    #[test]
2393    fn duplication_markdown_single_group_no_plural() {
2394        let root = PathBuf::from("/project");
2395        let report = DuplicationReport {
2396            clone_groups: vec![CloneGroup {
2397                instances: vec![CloneInstance {
2398                    file: root.join("src/a.ts"),
2399                    start_line: 1,
2400                    end_line: 5,
2401                    start_col: 0,
2402                    end_col: 0,
2403                    fragment: String::new(),
2404                }],
2405                token_count: 30,
2406                line_count: 5,
2407            }],
2408            clone_families: vec![],
2409            mirrored_directories: vec![],
2410            stats: DuplicationStats {
2411                clone_groups: 1,
2412                clone_instances: 1,
2413                duplication_percentage: 2.0,
2414                ..Default::default()
2415            },
2416        };
2417        let md = build_duplication_markdown(&report, &root);
2418        assert!(md.contains("1 clone group found"));
2419        assert!(!md.contains("1 clone groups found"));
2420    }
2421}