Skip to main content

fallow_cli/report/
markdown.rs

1use std::fmt::Write;
2use std::path::Path;
3
4use fallow_core::duplicates::DuplicationReport;
5use fallow_core::results::{AnalysisResults, UnusedExport, UnusedMember};
6
7use super::{normalize_uri, relative_path};
8
9/// Escape backticks in user-controlled strings to prevent breaking markdown code spans.
10fn escape_backticks(s: &str) -> String {
11    s.replace('`', "\\`")
12}
13
14pub(super) fn print_markdown(results: &AnalysisResults, root: &Path) {
15    println!("{}", build_markdown(results, root));
16}
17
18/// Build markdown output for analysis results.
19pub fn build_markdown(results: &AnalysisResults, root: &Path) -> String {
20    let rel = |p: &Path| {
21        escape_backticks(&normalize_uri(
22            &relative_path(p, root).display().to_string(),
23        ))
24    };
25
26    let total = results.total_issues();
27    let mut out = String::new();
28
29    if total == 0 {
30        out.push_str("## Fallow: no issues found\n");
31        return out;
32    }
33
34    let _ = write!(
35        out,
36        "## Fallow: {total} issue{} found\n\n",
37        if total == 1 { "" } else { "s" }
38    );
39
40    // ── Unused files ──
41    markdown_section(&mut out, &results.unused_files, "Unused files", |file| {
42        vec![format!("- `{}`", rel(&file.path))]
43    });
44
45    // ── Unused exports ──
46    markdown_grouped_section(
47        &mut out,
48        &results.unused_exports,
49        "Unused exports",
50        root,
51        |e| e.path.as_path(),
52        format_export,
53    );
54
55    // ── Unused types ──
56    markdown_grouped_section(
57        &mut out,
58        &results.unused_types,
59        "Unused type exports",
60        root,
61        |e| e.path.as_path(),
62        format_export,
63    );
64
65    // ── Unused dependencies ──
66    markdown_section(
67        &mut out,
68        &results.unused_dependencies,
69        "Unused dependencies",
70        |dep| format_dependency(&dep.package_name, &dep.path, root),
71    );
72
73    // ── Unused devDependencies ──
74    markdown_section(
75        &mut out,
76        &results.unused_dev_dependencies,
77        "Unused devDependencies",
78        |dep| format_dependency(&dep.package_name, &dep.path, root),
79    );
80
81    // ── Unused optionalDependencies ──
82    markdown_section(
83        &mut out,
84        &results.unused_optional_dependencies,
85        "Unused optionalDependencies",
86        |dep| format_dependency(&dep.package_name, &dep.path, root),
87    );
88
89    // ── Unused enum members ──
90    markdown_grouped_section(
91        &mut out,
92        &results.unused_enum_members,
93        "Unused enum members",
94        root,
95        |m| m.path.as_path(),
96        format_member,
97    );
98
99    // ── Unused class members ──
100    markdown_grouped_section(
101        &mut out,
102        &results.unused_class_members,
103        "Unused class members",
104        root,
105        |m| m.path.as_path(),
106        format_member,
107    );
108
109    // ── Unresolved imports ──
110    markdown_grouped_section(
111        &mut out,
112        &results.unresolved_imports,
113        "Unresolved imports",
114        root,
115        |i| i.path.as_path(),
116        |i| format!(":{} `{}`", i.line, escape_backticks(&i.specifier)),
117    );
118
119    // ── Unlisted dependencies ──
120    markdown_section(
121        &mut out,
122        &results.unlisted_dependencies,
123        "Unlisted dependencies",
124        |dep| vec![format!("- `{}`", escape_backticks(&dep.package_name))],
125    );
126
127    // ── Duplicate exports ──
128    markdown_section(
129        &mut out,
130        &results.duplicate_exports,
131        "Duplicate exports",
132        |dup| {
133            let locations: Vec<String> = dup
134                .locations
135                .iter()
136                .map(|loc| format!("`{}`", rel(&loc.path)))
137                .collect();
138            vec![format!(
139                "- `{}` in {}",
140                escape_backticks(&dup.export_name),
141                locations.join(", ")
142            )]
143        },
144    );
145
146    // ── Type-only dependencies ──
147    markdown_section(
148        &mut out,
149        &results.type_only_dependencies,
150        "Type-only dependencies (consider moving to devDependencies)",
151        |dep| format_dependency(&dep.package_name, &dep.path, root),
152    );
153
154    // ── Circular dependencies ──
155    markdown_section(
156        &mut out,
157        &results.circular_dependencies,
158        "Circular dependencies",
159        |cycle| {
160            let chain: Vec<String> = cycle.files.iter().map(|p| rel(p)).collect();
161            let mut display_chain = chain.clone();
162            if let Some(first) = chain.first() {
163                display_chain.push(first.clone());
164            }
165            vec![format!(
166                "- {}",
167                display_chain
168                    .iter()
169                    .map(|s| format!("`{s}`"))
170                    .collect::<Vec<_>>()
171                    .join(" \u{2192} ")
172            )]
173        },
174    );
175
176    out
177}
178
179fn format_export(e: &UnusedExport) -> String {
180    let re = if e.is_re_export { " (re-export)" } else { "" };
181    format!(":{} `{}`{re}", e.line, escape_backticks(&e.export_name))
182}
183
184fn format_member(m: &UnusedMember) -> String {
185    format!(
186        ":{} `{}.{}`",
187        m.line,
188        escape_backticks(&m.parent_name),
189        escape_backticks(&m.member_name)
190    )
191}
192
193fn format_dependency(dep_name: &str, pkg_path: &Path, root: &Path) -> Vec<String> {
194    let name = escape_backticks(dep_name);
195    let pkg_label = relative_path(pkg_path, root).display().to_string();
196    if pkg_label == "package.json" {
197        vec![format!("- `{name}`")]
198    } else {
199        let label = escape_backticks(&pkg_label);
200        vec![format!("- `{name}` ({label})")]
201    }
202}
203
204/// Emit a markdown section with a header and per-item lines. Skipped if empty.
205fn markdown_section<T>(
206    out: &mut String,
207    items: &[T],
208    title: &str,
209    format_lines: impl Fn(&T) -> Vec<String>,
210) {
211    if items.is_empty() {
212        return;
213    }
214    let _ = write!(out, "### {title} ({})\n\n", items.len());
215    for item in items {
216        for line in format_lines(item) {
217            out.push_str(&line);
218            out.push('\n');
219        }
220    }
221    out.push('\n');
222}
223
224/// Emit a markdown section whose items are grouped by file path.
225fn markdown_grouped_section<'a, T>(
226    out: &mut String,
227    items: &'a [T],
228    title: &str,
229    root: &Path,
230    get_path: impl Fn(&'a T) -> &'a Path,
231    format_detail: impl Fn(&T) -> String,
232) {
233    if items.is_empty() {
234        return;
235    }
236    let _ = write!(out, "### {title} ({})\n\n", items.len());
237
238    let mut indices: Vec<usize> = (0..items.len()).collect();
239    indices.sort_by(|&a, &b| get_path(&items[a]).cmp(get_path(&items[b])));
240
241    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
242    let mut last_file = String::new();
243    for &i in &indices {
244        let item = &items[i];
245        let file_str = rel(get_path(item));
246        if file_str != last_file {
247            let _ = writeln!(out, "- `{file_str}`");
248            last_file = file_str;
249        }
250        let _ = writeln!(out, "  - {}", format_detail(item));
251    }
252    out.push('\n');
253}
254
255// ── Duplication markdown output ──────────────────────────────────
256
257pub(super) fn print_duplication_markdown(report: &DuplicationReport, root: &Path) {
258    println!("{}", build_duplication_markdown(report, root));
259}
260
261/// Build markdown output for duplication results.
262pub fn build_duplication_markdown(report: &DuplicationReport, root: &Path) -> String {
263    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
264
265    let mut out = String::new();
266
267    if report.clone_groups.is_empty() {
268        out.push_str("## Fallow: no code duplication found\n");
269        return out;
270    }
271
272    let stats = &report.stats;
273    let _ = write!(
274        out,
275        "## Fallow: {} clone group{} found ({:.1}% duplication)\n\n",
276        stats.clone_groups,
277        if stats.clone_groups == 1 { "" } else { "s" },
278        stats.duplication_percentage,
279    );
280
281    out.push_str("### Duplicates\n\n");
282    for (i, group) in report.clone_groups.iter().enumerate() {
283        let instance_count = group.instances.len();
284        let _ = write!(
285            out,
286            "**Clone group {}** ({} lines, {instance_count} instance{})\n\n",
287            i + 1,
288            group.line_count,
289            if instance_count == 1 { "" } else { "s" }
290        );
291        for instance in &group.instances {
292            let relative = rel(&instance.file);
293            let _ = writeln!(
294                out,
295                "- `{relative}:{}-{}`",
296                instance.start_line, instance.end_line
297            );
298        }
299        out.push('\n');
300    }
301
302    // Clone families
303    if !report.clone_families.is_empty() {
304        out.push_str("### Clone Families\n\n");
305        for (i, family) in report.clone_families.iter().enumerate() {
306            let file_names: Vec<_> = family.files.iter().map(|f| rel(f)).collect();
307            let _ = write!(
308                out,
309                "**Family {}** ({} group{}, {} lines across {})\n\n",
310                i + 1,
311                family.groups.len(),
312                if family.groups.len() == 1 { "" } else { "s" },
313                family.total_duplicated_lines,
314                file_names
315                    .iter()
316                    .map(|s| format!("`{s}`"))
317                    .collect::<Vec<_>>()
318                    .join(", "),
319            );
320            for suggestion in &family.suggestions {
321                let savings = if suggestion.estimated_savings > 0 {
322                    format!(" (~{} lines saved)", suggestion.estimated_savings)
323                } else {
324                    String::new()
325                };
326                let _ = writeln!(out, "- {}{savings}", suggestion.description);
327            }
328            out.push('\n');
329        }
330    }
331
332    // Summary line
333    let _ = writeln!(
334        out,
335        "**Summary:** {} duplicated lines ({:.1}%) across {} file{}",
336        stats.duplicated_lines,
337        stats.duplication_percentage,
338        stats.files_with_clones,
339        if stats.files_with_clones == 1 {
340            ""
341        } else {
342            "s"
343        },
344    );
345
346    out
347}
348
349// ── Health markdown output ──────────────────────────────────────────
350
351pub(super) fn print_health_markdown(report: &crate::health_types::HealthReport, root: &Path) {
352    println!("{}", build_health_markdown(report, root));
353}
354
355/// Build markdown output for health (complexity) results.
356pub fn build_health_markdown(report: &crate::health_types::HealthReport, root: &Path) -> String {
357    let rel = |p: &Path| {
358        escape_backticks(&normalize_uri(
359            &relative_path(p, root).display().to_string(),
360        ))
361    };
362
363    let mut out = String::new();
364
365    if report.findings.is_empty() && report.file_scores.is_empty() {
366        let _ = write!(
367            out,
368            "## Fallow: no functions exceed complexity thresholds\n\n\
369             **{}** functions analyzed (max cyclomatic: {}, max cognitive: {})\n",
370            report.summary.functions_analyzed,
371            report.summary.max_cyclomatic_threshold,
372            report.summary.max_cognitive_threshold,
373        );
374        return out;
375    }
376
377    if !report.findings.is_empty() {
378        let count = report.summary.functions_above_threshold;
379        let shown = report.findings.len();
380        if shown < count {
381            let _ = write!(
382                out,
383                "## Fallow: {count} high complexity function{} ({shown} shown)\n\n",
384                if count == 1 { "" } else { "s" },
385            );
386        } else {
387            let _ = write!(
388                out,
389                "## Fallow: {count} high complexity function{}\n\n",
390                if count == 1 { "" } else { "s" },
391            );
392        }
393
394        out.push_str("| File | Function | Cyclomatic | Cognitive | Lines |\n");
395        out.push_str("|:-----|:---------|:-----------|:----------|:------|\n");
396
397        for finding in &report.findings {
398            let file_str = rel(&finding.path);
399            let cyc_marker = if finding.cyclomatic > report.summary.max_cyclomatic_threshold {
400                " **!**"
401            } else {
402                ""
403            };
404            let cog_marker = if finding.cognitive > report.summary.max_cognitive_threshold {
405                " **!**"
406            } else {
407                ""
408            };
409            let _ = writeln!(
410                out,
411                "| `{file_str}:{line}` | `{name}` | {cyc}{cyc_marker} | {cog}{cog_marker} | {lines} |",
412                line = finding.line,
413                name = escape_backticks(&finding.name),
414                cyc = finding.cyclomatic,
415                cog = finding.cognitive,
416                lines = finding.line_count,
417            );
418        }
419
420        let s = &report.summary;
421        let _ = write!(
422            out,
423            "\n**{files}** files, **{funcs}** functions analyzed \
424             (thresholds: cyclomatic > {cyc}, cognitive > {cog})\n",
425            files = s.files_analyzed,
426            funcs = s.functions_analyzed,
427            cyc = s.max_cyclomatic_threshold,
428            cog = s.max_cognitive_threshold,
429        );
430    }
431
432    // File health scores table
433    if !report.file_scores.is_empty() {
434        out.push('\n');
435        let _ = writeln!(
436            out,
437            "### File Health Scores ({} files)\n",
438            report.file_scores.len(),
439        );
440        out.push_str("| File | MI | Fan-in | Fan-out | Dead Code | Density |\n");
441        out.push_str("|:-----|:---|:-------|:--------|:----------|:--------|\n");
442
443        for score in &report.file_scores {
444            let file_str = rel(&score.path);
445            let _ = writeln!(
446                out,
447                "| `{file_str}` | {mi:.1} | {fi} | {fo} | {dead:.0}% | {density:.2} |",
448                mi = score.maintainability_index,
449                fi = score.fan_in,
450                fo = score.fan_out,
451                dead = score.dead_code_ratio * 100.0,
452                density = score.complexity_density,
453            );
454        }
455
456        if let Some(avg) = report.summary.average_maintainability {
457            let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
458        }
459    }
460
461    out
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use fallow_core::duplicates::{
468        CloneFamily, CloneGroup, CloneInstance, DuplicationReport, DuplicationStats,
469        RefactoringKind, RefactoringSuggestion,
470    };
471    use fallow_core::extract::MemberKind;
472    use fallow_core::results::*;
473    use std::path::PathBuf;
474
475    /// Helper: build an `AnalysisResults` populated with one issue of every type.
476    fn sample_results(root: &Path) -> AnalysisResults {
477        let mut r = AnalysisResults::default();
478
479        r.unused_files.push(UnusedFile {
480            path: root.join("src/dead.ts"),
481        });
482        r.unused_exports.push(UnusedExport {
483            path: root.join("src/utils.ts"),
484            export_name: "helperFn".to_string(),
485            is_type_only: false,
486            line: 10,
487            col: 4,
488            span_start: 120,
489            is_re_export: false,
490        });
491        r.unused_types.push(UnusedExport {
492            path: root.join("src/types.ts"),
493            export_name: "OldType".to_string(),
494            is_type_only: true,
495            line: 5,
496            col: 0,
497            span_start: 60,
498            is_re_export: false,
499        });
500        r.unused_dependencies.push(UnusedDependency {
501            package_name: "lodash".to_string(),
502            location: DependencyLocation::Dependencies,
503            path: root.join("package.json"),
504            line: 5,
505        });
506        r.unused_dev_dependencies.push(UnusedDependency {
507            package_name: "jest".to_string(),
508            location: DependencyLocation::DevDependencies,
509            path: root.join("package.json"),
510            line: 5,
511        });
512        r.unused_enum_members.push(UnusedMember {
513            path: root.join("src/enums.ts"),
514            parent_name: "Status".to_string(),
515            member_name: "Deprecated".to_string(),
516            kind: MemberKind::EnumMember,
517            line: 8,
518            col: 2,
519        });
520        r.unused_class_members.push(UnusedMember {
521            path: root.join("src/service.ts"),
522            parent_name: "UserService".to_string(),
523            member_name: "legacyMethod".to_string(),
524            kind: MemberKind::ClassMethod,
525            line: 42,
526            col: 4,
527        });
528        r.unresolved_imports.push(UnresolvedImport {
529            path: root.join("src/app.ts"),
530            specifier: "./missing-module".to_string(),
531            line: 3,
532            col: 0,
533        });
534        r.unlisted_dependencies.push(UnlistedDependency {
535            package_name: "chalk".to_string(),
536            imported_from: vec![ImportSite {
537                path: root.join("src/cli.ts"),
538                line: 2,
539                col: 0,
540            }],
541        });
542        r.duplicate_exports.push(DuplicateExport {
543            export_name: "Config".to_string(),
544            locations: vec![
545                DuplicateLocation {
546                    path: root.join("src/config.ts"),
547                    line: 15,
548                    col: 0,
549                },
550                DuplicateLocation {
551                    path: root.join("src/types.ts"),
552                    line: 30,
553                    col: 0,
554                },
555            ],
556        });
557        r.type_only_dependencies.push(TypeOnlyDependency {
558            package_name: "zod".to_string(),
559            path: root.join("package.json"),
560            line: 8,
561        });
562        r.circular_dependencies.push(CircularDependency {
563            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
564            length: 2,
565            line: 3,
566            col: 0,
567        });
568
569        r
570    }
571
572    #[test]
573    fn markdown_empty_results_no_issues() {
574        let root = PathBuf::from("/project");
575        let results = AnalysisResults::default();
576        let md = build_markdown(&results, &root);
577        assert_eq!(md, "## Fallow: no issues found\n");
578    }
579
580    #[test]
581    fn markdown_contains_header_with_count() {
582        let root = PathBuf::from("/project");
583        let results = sample_results(&root);
584        let md = build_markdown(&results, &root);
585        assert!(md.starts_with(&format!(
586            "## Fallow: {} issues found\n",
587            results.total_issues()
588        )));
589    }
590
591    #[test]
592    fn markdown_contains_all_sections() {
593        let root = PathBuf::from("/project");
594        let results = sample_results(&root);
595        let md = build_markdown(&results, &root);
596
597        assert!(md.contains("### Unused files (1)"));
598        assert!(md.contains("### Unused exports (1)"));
599        assert!(md.contains("### Unused type exports (1)"));
600        assert!(md.contains("### Unused dependencies (1)"));
601        assert!(md.contains("### Unused devDependencies (1)"));
602        assert!(md.contains("### Unused enum members (1)"));
603        assert!(md.contains("### Unused class members (1)"));
604        assert!(md.contains("### Unresolved imports (1)"));
605        assert!(md.contains("### Unlisted dependencies (1)"));
606        assert!(md.contains("### Duplicate exports (1)"));
607        assert!(md.contains("### Type-only dependencies"));
608        assert!(md.contains("### Circular dependencies (1)"));
609    }
610
611    #[test]
612    fn markdown_unused_file_format() {
613        let root = PathBuf::from("/project");
614        let mut results = AnalysisResults::default();
615        results.unused_files.push(UnusedFile {
616            path: root.join("src/dead.ts"),
617        });
618        let md = build_markdown(&results, &root);
619        assert!(md.contains("- `src/dead.ts`"));
620    }
621
622    #[test]
623    fn markdown_unused_export_grouped_by_file() {
624        let root = PathBuf::from("/project");
625        let mut results = AnalysisResults::default();
626        results.unused_exports.push(UnusedExport {
627            path: root.join("src/utils.ts"),
628            export_name: "helperFn".to_string(),
629            is_type_only: false,
630            line: 10,
631            col: 4,
632            span_start: 120,
633            is_re_export: false,
634        });
635        let md = build_markdown(&results, &root);
636        assert!(md.contains("- `src/utils.ts`"));
637        assert!(md.contains(":10 `helperFn`"));
638    }
639
640    #[test]
641    fn markdown_re_export_tagged() {
642        let root = PathBuf::from("/project");
643        let mut results = AnalysisResults::default();
644        results.unused_exports.push(UnusedExport {
645            path: root.join("src/index.ts"),
646            export_name: "reExported".to_string(),
647            is_type_only: false,
648            line: 1,
649            col: 0,
650            span_start: 0,
651            is_re_export: true,
652        });
653        let md = build_markdown(&results, &root);
654        assert!(md.contains("(re-export)"));
655    }
656
657    #[test]
658    fn markdown_unused_dep_format() {
659        let root = PathBuf::from("/project");
660        let mut results = AnalysisResults::default();
661        results.unused_dependencies.push(UnusedDependency {
662            package_name: "lodash".to_string(),
663            location: DependencyLocation::Dependencies,
664            path: root.join("package.json"),
665            line: 5,
666        });
667        let md = build_markdown(&results, &root);
668        assert!(md.contains("- `lodash`"));
669    }
670
671    #[test]
672    fn markdown_circular_dep_format() {
673        let root = PathBuf::from("/project");
674        let mut results = AnalysisResults::default();
675        results.circular_dependencies.push(CircularDependency {
676            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
677            length: 2,
678            line: 3,
679            col: 0,
680        });
681        let md = build_markdown(&results, &root);
682        assert!(md.contains("`src/a.ts`"));
683        assert!(md.contains("`src/b.ts`"));
684        assert!(md.contains("\u{2192}"));
685    }
686
687    #[test]
688    fn markdown_strips_root_prefix() {
689        let root = PathBuf::from("/project");
690        let mut results = AnalysisResults::default();
691        results.unused_files.push(UnusedFile {
692            path: PathBuf::from("/project/src/deep/nested/file.ts"),
693        });
694        let md = build_markdown(&results, &root);
695        assert!(md.contains("`src/deep/nested/file.ts`"));
696        assert!(!md.contains("/project/"));
697    }
698
699    #[test]
700    fn markdown_single_issue_no_plural() {
701        let root = PathBuf::from("/project");
702        let mut results = AnalysisResults::default();
703        results.unused_files.push(UnusedFile {
704            path: root.join("src/dead.ts"),
705        });
706        let md = build_markdown(&results, &root);
707        assert!(md.starts_with("## Fallow: 1 issue found\n"));
708    }
709
710    #[test]
711    fn markdown_type_only_dep_format() {
712        let root = PathBuf::from("/project");
713        let mut results = AnalysisResults::default();
714        results.type_only_dependencies.push(TypeOnlyDependency {
715            package_name: "zod".to_string(),
716            path: root.join("package.json"),
717            line: 8,
718        });
719        let md = build_markdown(&results, &root);
720        assert!(md.contains("### Type-only dependencies"));
721        assert!(md.contains("- `zod`"));
722    }
723
724    #[test]
725    fn markdown_escapes_backticks_in_export_names() {
726        let root = PathBuf::from("/project");
727        let mut results = AnalysisResults::default();
728        results.unused_exports.push(UnusedExport {
729            path: root.join("src/utils.ts"),
730            export_name: "foo`bar".to_string(),
731            is_type_only: false,
732            line: 1,
733            col: 0,
734            span_start: 0,
735            is_re_export: false,
736        });
737        let md = build_markdown(&results, &root);
738        assert!(md.contains("foo\\`bar"));
739        assert!(!md.contains("foo`bar`"));
740    }
741
742    #[test]
743    fn markdown_escapes_backticks_in_package_names() {
744        let root = PathBuf::from("/project");
745        let mut results = AnalysisResults::default();
746        results.unused_dependencies.push(UnusedDependency {
747            package_name: "pkg`name".to_string(),
748            location: DependencyLocation::Dependencies,
749            path: root.join("package.json"),
750            line: 5,
751        });
752        let md = build_markdown(&results, &root);
753        assert!(md.contains("pkg\\`name"));
754    }
755
756    // ── Duplication markdown ──
757
758    #[test]
759    fn duplication_markdown_empty() {
760        let report = DuplicationReport::default();
761        let root = PathBuf::from("/project");
762        let md = build_duplication_markdown(&report, &root);
763        assert_eq!(md, "## Fallow: no code duplication found\n");
764    }
765
766    #[test]
767    fn duplication_markdown_contains_groups() {
768        let root = PathBuf::from("/project");
769        let report = DuplicationReport {
770            clone_groups: vec![CloneGroup {
771                instances: vec![
772                    CloneInstance {
773                        file: root.join("src/a.ts"),
774                        start_line: 1,
775                        end_line: 10,
776                        start_col: 0,
777                        end_col: 0,
778                        fragment: String::new(),
779                    },
780                    CloneInstance {
781                        file: root.join("src/b.ts"),
782                        start_line: 5,
783                        end_line: 14,
784                        start_col: 0,
785                        end_col: 0,
786                        fragment: String::new(),
787                    },
788                ],
789                token_count: 50,
790                line_count: 10,
791            }],
792            clone_families: vec![],
793            stats: DuplicationStats {
794                total_files: 10,
795                files_with_clones: 2,
796                total_lines: 500,
797                duplicated_lines: 20,
798                total_tokens: 2500,
799                duplicated_tokens: 100,
800                clone_groups: 1,
801                clone_instances: 2,
802                duplication_percentage: 4.0,
803            },
804        };
805        let md = build_duplication_markdown(&report, &root);
806        assert!(md.contains("**Clone group 1**"));
807        assert!(md.contains("`src/a.ts:1-10`"));
808        assert!(md.contains("`src/b.ts:5-14`"));
809        assert!(md.contains("4.0% duplication"));
810    }
811
812    #[test]
813    fn duplication_markdown_contains_families() {
814        let root = PathBuf::from("/project");
815        let report = DuplicationReport {
816            clone_groups: vec![CloneGroup {
817                instances: vec![CloneInstance {
818                    file: root.join("src/a.ts"),
819                    start_line: 1,
820                    end_line: 5,
821                    start_col: 0,
822                    end_col: 0,
823                    fragment: String::new(),
824                }],
825                token_count: 30,
826                line_count: 5,
827            }],
828            clone_families: vec![CloneFamily {
829                files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
830                groups: vec![],
831                total_duplicated_lines: 20,
832                total_duplicated_tokens: 100,
833                suggestions: vec![RefactoringSuggestion {
834                    kind: RefactoringKind::ExtractFunction,
835                    description: "Extract shared utility function".to_string(),
836                    estimated_savings: 15,
837                }],
838            }],
839            stats: DuplicationStats {
840                clone_groups: 1,
841                clone_instances: 1,
842                duplication_percentage: 2.0,
843                ..Default::default()
844            },
845        };
846        let md = build_duplication_markdown(&report, &root);
847        assert!(md.contains("### Clone Families"));
848        assert!(md.contains("**Family 1**"));
849        assert!(md.contains("Extract shared utility function"));
850        assert!(md.contains("~15 lines saved"));
851    }
852
853    // ── Health markdown ──
854
855    #[test]
856    fn health_markdown_empty_no_findings() {
857        let root = PathBuf::from("/project");
858        let report = crate::health_types::HealthReport {
859            findings: vec![],
860            summary: crate::health_types::HealthSummary {
861                files_analyzed: 10,
862                functions_analyzed: 50,
863                functions_above_threshold: 0,
864                max_cyclomatic_threshold: 20,
865                max_cognitive_threshold: 15,
866                files_scored: None,
867                average_maintainability: None,
868            },
869            file_scores: vec![],
870        };
871        let md = build_health_markdown(&report, &root);
872        assert!(md.contains("no functions exceed complexity thresholds"));
873        assert!(md.contains("**50** functions analyzed"));
874    }
875
876    #[test]
877    fn health_markdown_table_format() {
878        let root = PathBuf::from("/project");
879        let report = crate::health_types::HealthReport {
880            findings: vec![crate::health_types::HealthFinding {
881                path: root.join("src/utils.ts"),
882                name: "parseExpression".to_string(),
883                line: 42,
884                col: 0,
885                cyclomatic: 25,
886                cognitive: 30,
887                line_count: 80,
888                exceeded: crate::health_types::ExceededThreshold::Both,
889            }],
890            summary: crate::health_types::HealthSummary {
891                files_analyzed: 10,
892                functions_analyzed: 50,
893                functions_above_threshold: 1,
894                max_cyclomatic_threshold: 20,
895                max_cognitive_threshold: 15,
896                files_scored: None,
897                average_maintainability: None,
898            },
899            file_scores: vec![],
900        };
901        let md = build_health_markdown(&report, &root);
902        assert!(md.contains("## Fallow: 1 high complexity function\n"));
903        assert!(md.contains("| File | Function |"));
904        assert!(md.contains("`src/utils.ts:42`"));
905        assert!(md.contains("`parseExpression`"));
906        assert!(md.contains("25 **!**"));
907        assert!(md.contains("30 **!**"));
908        assert!(md.contains("| 80 |"));
909    }
910
911    #[test]
912    fn health_markdown_no_marker_when_below_threshold() {
913        let root = PathBuf::from("/project");
914        let report = crate::health_types::HealthReport {
915            findings: vec![crate::health_types::HealthFinding {
916                path: root.join("src/utils.ts"),
917                name: "helper".to_string(),
918                line: 10,
919                col: 0,
920                cyclomatic: 15,
921                cognitive: 20,
922                line_count: 30,
923                exceeded: crate::health_types::ExceededThreshold::Cognitive,
924            }],
925            summary: crate::health_types::HealthSummary {
926                files_analyzed: 5,
927                functions_analyzed: 20,
928                functions_above_threshold: 1,
929                max_cyclomatic_threshold: 20,
930                max_cognitive_threshold: 15,
931                files_scored: None,
932                average_maintainability: None,
933            },
934            file_scores: vec![],
935        };
936        let md = build_health_markdown(&report, &root);
937        // Cyclomatic 15 is below threshold 20, no marker
938        assert!(md.contains("| 15 |"));
939        // Cognitive 20 exceeds threshold 15, has marker
940        assert!(md.contains("20 **!**"));
941    }
942}