Skip to main content

fallow_api/
markdown_output.rs

1#[path = "markdown_runtime_summary.rs"]
2mod runtime_summary;
3
4use std::borrow::Cow;
5use std::fmt::Write;
6use std::path::Path;
7
8use fallow_types::duplicates::DuplicationReport;
9use fallow_types::output_dead_code::*;
10use fallow_types::results::{AnalysisResults, UnusedExport, UnusedMember};
11
12use fallow_output::{
13    markdown_code_span, markdown_table_code_span, markdown_table_text, normalize_uri,
14};
15
16use crate::ResultGroup;
17
18fn relative_path<'a>(path: &'a Path, root: &Path) -> &'a Path {
19    path.strip_prefix(root).unwrap_or(path)
20}
21
22fn plural(count: usize) -> &'static str {
23    if count == 1 { "" } else { "s" }
24}
25
26fn format_window(seconds: u64) -> String {
27    if seconds < 60 {
28        return format!("{seconds} s");
29    }
30    let minutes = seconds / 60;
31    if minutes < 120 {
32        return format!("{minutes} min");
33    }
34    let hours = minutes / 60;
35    if hours < 48 {
36        format!("{hours} h")
37    } else {
38        format!("{} d", hours / 24)
39    }
40}
41
42fn escape_markdown_prose(s: &str) -> String {
43    s.replace('`', "\\`")
44}
45
46/// Escape every character that inline markdown treats as syntax, so free
47/// text from a source comment renders as plain text.
48fn escape_markdown_inline(s: &str) -> String {
49    let mut out = String::with_capacity(s.len());
50    for c in s.chars() {
51        if matches!(
52            c,
53            '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '|' | '#'
54        ) {
55            out.push('\\');
56        }
57        out.push(c);
58    }
59    out
60}
61
62fn display_complexity_entry_name(name: &str) -> Cow<'_, str> {
63    match name {
64        "<template>" => Cow::Borrowed("<template> (template complexity)"),
65        "<component>" => Cow::Borrowed("<component> (component rollup)"),
66        fallow_output::FILE_LINES_FINDING_NAME => Cow::Borrowed("<file> (file length)"),
67        name if fallow_types::extract::is_synthetic_template_unit(name) => {
68            Cow::Owned(format!("{name} (snippet complexity)"))
69        }
70        _ => Cow::Borrowed(name),
71    }
72}
73
74/// Build markdown output for analysis results.
75pub fn build_markdown(results: &AnalysisResults, root: &Path) -> String {
76    let total = results.total_issues();
77    let mut out = String::new();
78
79    if total == 0 {
80        out.push_str("## Fallow: no issues found\n");
81        if health_signal_count(results) == 0 {
82            push_cascade_note(&mut out, results.cascade_hidden);
83            return out;
84        }
85        out.push('\n');
86    } else {
87        let _ = write!(out, "## Fallow: {total} issue{} found\n\n", plural(total));
88    }
89
90    push_markdown_sections(&mut out, results, root);
91    push_cascade_note(&mut out, results.cascade_hidden);
92    out
93}
94
95/// One line that names the findings the cascade filter hid. Markdown has no
96/// entry for a hidden finding, so this line is the only sign of them.
97fn push_cascade_note(out: &mut String, hidden: usize) {
98    if hidden == 0 {
99        return;
100    }
101    if !out.ends_with("\n\n") {
102        out.push('\n');
103    }
104    let verb = if hidden == 1 { "is" } else { "are" };
105    let _ = writeln!(
106        out,
107        "_{hidden} finding{} in unused files {verb} hidden; use `--show-cascade` to list them._",
108        plural(hidden)
109    );
110}
111
112/// The number of advisory component health signals in `results`. These do not
113/// count toward `total_issues`, but the report lists them.
114fn health_signal_count(results: &AnalysisResults) -> usize {
115    results.prop_drilling_chains.len() - results.enforced_prop_drilling_count()
116        + results.thin_wrappers.len()
117        + results.duplicate_prop_shapes.len()
118}
119
120fn push_markdown_sections(out: &mut String, results: &AnalysisResults, root: &Path) {
121    push_markdown_primary_sections(out, results, root);
122    push_markdown_import_sections(out, results, root);
123    push_markdown_dependency_detail_sections(out, results, root);
124    push_markdown_graph_sections(out, results, &|path| markdown_relative_path(path, root));
125    push_markdown_catalog_sections(out, results, &|path| markdown_relative_path(path, root));
126}
127
128fn markdown_relative_path(path: &Path, root: &Path) -> String {
129    normalize_uri(&relative_path(path, root).display().to_string())
130}
131
132fn push_markdown_primary_sections(out: &mut String, results: &AnalysisResults, root: &Path) {
133    markdown_section(out, &results.unused_files, "Unused files", |file| {
134        vec![format!(
135            "- {}{}",
136            markdown_code_span(&markdown_relative_path(&file.file.path, root)),
137            markdown_caveat_suffix(&file.reachability_caveats)
138        )]
139    });
140
141    markdown_grouped_section(
142        out,
143        &results.unused_exports,
144        "Unused exports",
145        root,
146        |e| e.export.path.as_path(),
147        |e: &UnusedExportFinding| format_export(&e.export, &e.reachability_caveats),
148    );
149
150    markdown_grouped_section(
151        out,
152        &results.unused_types,
153        "Unused type exports",
154        root,
155        |e| e.export.path.as_path(),
156        |e: &UnusedTypeFinding| format_export(&e.export, &e.reachability_caveats),
157    );
158
159    markdown_grouped_section(
160        out,
161        &results.private_type_leaks,
162        "Private type leaks",
163        root,
164        |e| e.leak.path.as_path(),
165        format_private_type_leak,
166    );
167
168    markdown_grouped_section(
169        out,
170        &results.deprecated_exports_in_use,
171        "Deprecated exports in use",
172        root,
173        |e| e.export.path.as_path(),
174        format_deprecated_export_in_use,
175    );
176
177    push_markdown_dependency_sections(out, results, root);
178    push_markdown_member_sections(out, results, root);
179}
180
181fn push_markdown_import_sections(out: &mut String, results: &AnalysisResults, root: &Path) {
182    markdown_grouped_section(
183        out,
184        &results.unresolved_imports,
185        "Unresolved imports",
186        root,
187        |i| i.import.path.as_path(),
188        |i| {
189            format!(
190                ":{} {}",
191                i.import.line,
192                markdown_code_span(&i.import.specifier)
193            )
194        },
195    );
196
197    markdown_section(
198        out,
199        &results.unlisted_dependencies,
200        "Unlisted dependencies",
201        |dep| vec![format!("- {}", markdown_code_span(&dep.dep.package_name))],
202    );
203
204    markdown_section(
205        out,
206        &results.unlisted_binaries,
207        "Unlisted binaries",
208        |binary| {
209            let sites: Vec<String> = binary
210                .binary
211                .used_in
212                .iter()
213                .map(|site| {
214                    markdown_code_span(&format!(
215                        "{}:{}",
216                        markdown_relative_path(&site.path, root),
217                        site.line
218                    ))
219                })
220                .collect();
221            vec![format!(
222                "- {} used in {}",
223                markdown_code_span(&binary.binary.binary_name),
224                sites.join(", ")
225            )]
226        },
227    );
228
229    markdown_section(
230        out,
231        &results.duplicate_export_aliases,
232        "Duplicate export aliases",
233        |f| {
234            vec![format!(
235                "- {}:{} {} is exported as {}",
236                markdown_code_span(&markdown_relative_path(&f.alias.path, root)),
237                f.alias.line,
238                markdown_code_span(&f.alias.local_name),
239                f.alias
240                    .export_names
241                    .iter()
242                    .map(|name| markdown_code_span(name))
243                    .collect::<Vec<_>>()
244                    .join(", "),
245            )]
246        },
247    );
248
249    markdown_section(
250        out,
251        &results.duplicate_exports,
252        "Duplicate exports",
253        |dup| {
254            let locations: Vec<String> = dup
255                .export
256                .locations
257                .iter()
258                .map(|loc| markdown_code_span(&markdown_relative_path(&loc.path, root)))
259                .collect();
260            vec![format!(
261                "- {} in {}",
262                markdown_code_span(&dup.export.export_name),
263                locations.join(", ")
264            )]
265        },
266    );
267}
268
269fn push_markdown_dependency_sections(out: &mut String, results: &AnalysisResults, root: &Path) {
270    markdown_section(
271        out,
272        &results.unused_dependencies,
273        "Unused dependencies",
274        |dep| {
275            format_dependency(
276                &dep.dep.package_name,
277                &dep.dep.path,
278                &dep.dep.used_in_workspaces,
279                root,
280                &dep.reachability_caveats,
281            )
282        },
283    );
284    markdown_section(
285        out,
286        &results.unused_dev_dependencies,
287        "Unused devDependencies",
288        |dep| {
289            format_dependency(
290                &dep.dep.package_name,
291                &dep.dep.path,
292                &dep.dep.used_in_workspaces,
293                root,
294                &dep.reachability_caveats,
295            )
296        },
297    );
298    markdown_section(
299        out,
300        &results.unused_optional_dependencies,
301        "Unused optionalDependencies",
302        |dep| {
303            format_dependency(
304                &dep.dep.package_name,
305                &dep.dep.path,
306                &dep.dep.used_in_workspaces,
307                root,
308                &dep.reachability_caveats,
309            )
310        },
311    );
312}
313
314fn push_markdown_member_sections(out: &mut String, results: &AnalysisResults, root: &Path) {
315    markdown_grouped_section(
316        out,
317        &results.unused_enum_members,
318        "Unused enum members",
319        root,
320        |m| m.member.path.as_path(),
321        |m: &UnusedEnumMemberFinding| format_member(&m.member, &m.reachability_caveats),
322    );
323    markdown_grouped_section(
324        out,
325        &results.unused_class_members,
326        "Unused class members",
327        root,
328        |m| m.member.path.as_path(),
329        |m: &UnusedClassMemberFinding| format_member(&m.member, &m.reachability_caveats),
330    );
331    markdown_grouped_section(
332        out,
333        &results.unused_store_members,
334        "Unused store members",
335        root,
336        |m| m.member.path.as_path(),
337        |m: &UnusedStoreMemberFinding| format_member(&m.member, &m.reachability_caveats),
338    );
339    markdown_grouped_section(
340        out,
341        &results.unused_namespace_members,
342        "Unused namespace members",
343        root,
344        |m| m.member.path.as_path(),
345        |m: &UnusedNamespaceMemberFinding| format_member(&m.member, &m.reachability_caveats),
346    );
347}
348
349fn push_markdown_dependency_detail_sections(
350    out: &mut String,
351    results: &AnalysisResults,
352    root: &Path,
353) {
354    markdown_section(
355        out,
356        &results.type_only_dependencies,
357        "Type-only dependencies (consider moving to devDependencies)",
358        |dep| format_dependency(&dep.dep.package_name, &dep.dep.path, &[], root, &[]),
359    );
360    markdown_section(
361        out,
362        &results.test_only_dependencies,
363        "Test-only production dependencies (consider moving to devDependencies)",
364        |dep| format_dependency(&dep.dep.package_name, &dep.dep.path, &[], root, &[]),
365    );
366    markdown_section(
367        out,
368        &results.dev_dependencies_in_production,
369        "Dev dependencies used in production (consider moving to dependencies)",
370        |dep| format_dependency(&dep.dep.package_name, &dep.dep.path, &[], root, &[]),
371    );
372}
373
374fn push_markdown_graph_sections(
375    out: &mut String,
376    results: &AnalysisResults,
377    rel: &dyn Fn(&Path) -> String,
378) {
379    push_markdown_structure_sections(out, results, rel);
380    push_markdown_framework_sections(out, results, rel);
381    push_markdown_component_sections(out, results, rel);
382    push_markdown_component_health_sections(out, results, rel);
383    push_markdown_suppression_sections(out, results, rel);
384}
385
386/// The opt-in React/Preact component health signals. Advisory findings do not count
387/// toward `total_issues`, but the other full reports list them.
388fn push_markdown_component_health_sections(
389    out: &mut String,
390    results: &AnalysisResults,
391    rel: &dyn Fn(&Path) -> String,
392) {
393    markdown_section(out, &results.prop_drilling_chains, "Prop drilling", |c| {
394        format_markdown_prop_drilling_chain(c, rel)
395    });
396    markdown_section(out, &results.thin_wrappers, "Thin wrappers", |w| {
397        let w = &w.wrapper;
398        vec![format!(
399            "- {}:{} {} is a thin wrapper around {} (candidate for inlining at call sites or deleting)",
400            markdown_code_span(&rel(&w.file)),
401            w.line,
402            markdown_code_span(&w.component),
403            markdown_code_span(&w.child_component),
404        )]
405    });
406    markdown_section(
407        out,
408        &results.duplicate_prop_shapes,
409        "Duplicate prop shapes",
410        |d| {
411            let d = &d.shape;
412            vec![format!(
413                "- {}:{} {} shares an identical prop shape {} with {} other component(s) (extract a shared Props type)",
414                markdown_code_span(&rel(&d.file)),
415                d.line,
416                markdown_code_span(&d.component),
417                markdown_code_span(&format!("{{{}}}", d.shape.join(", "))),
418                d.group_size.saturating_sub(1),
419            )]
420        },
421    );
422}
423
424fn format_markdown_prop_drilling_chain(
425    entry: &PropDrillingChainFinding,
426    rel: &dyn Fn(&Path) -> String,
427) -> Vec<String> {
428    let c = &entry.chain;
429    let (path, line) = c
430        .hops
431        .first()
432        .map_or((String::new(), 0), |hop| (rel(&hop.file), hop.line));
433    let trail = c
434        .hops
435        .iter()
436        .map(|hop| escape_markdown_prose(&hop.component))
437        .collect::<Vec<_>>()
438        .join(" \u{2192} ");
439    vec![format!(
440        "- {}:{line} {} is forwarded unused through {trail} (depth {}); colocate the consumer or lift it to a context at a mid-chain hop",
441        markdown_code_span(&path),
442        markdown_code_span(&c.prop),
443        c.depth,
444    )]
445}
446
447fn push_markdown_structure_sections(
448    out: &mut String,
449    results: &AnalysisResults,
450    rel: &dyn Fn(&Path) -> String,
451) {
452    markdown_section(
453        out,
454        &results.circular_dependencies,
455        "Circular dependencies",
456        |cycle| format_markdown_circular_dependency(cycle, rel),
457    );
458    markdown_section(
459        out,
460        &results.re_export_cycles,
461        "Re-export cycles",
462        |cycle| format_markdown_re_export_cycle(cycle, rel),
463    );
464    markdown_section(out, &results.package_cycles, "Package cycles", |cycle| {
465        format_markdown_package_cycle(cycle, rel)
466    });
467    markdown_section(
468        out,
469        &results.boundary_violations,
470        "Boundary violations",
471        |v| format_markdown_boundary_violation(v, rel),
472    );
473    markdown_section(
474        out,
475        &results.boundary_coverage_violations,
476        "Boundary coverage",
477        |v| format_markdown_boundary_coverage(v, rel),
478    );
479    markdown_section(
480        out,
481        &results.boundary_call_violations,
482        "Boundary calls",
483        |v| format_markdown_boundary_call(v, rel),
484    );
485    markdown_section(out, &results.policy_violations, "Policy violations", |v| {
486        format_markdown_policy_violation(v, rel)
487    });
488}
489
490fn push_markdown_framework_sections(
491    out: &mut String,
492    results: &AnalysisResults,
493    rel: &dyn Fn(&Path) -> String,
494) {
495    markdown_section(
496        out,
497        &results.invalid_client_exports,
498        "Invalid client exports",
499        |e| format_markdown_invalid_client_export(e, rel),
500    );
501    markdown_section(
502        out,
503        &results.mixed_client_server_barrels,
504        "Mixed client/server barrels",
505        |b| format_markdown_mixed_client_server_barrel(b, rel),
506    );
507    markdown_section(
508        out,
509        &results.misplaced_directives,
510        "Misplaced directives",
511        |d| format_markdown_misplaced_directive(d, rel),
512    );
513    markdown_section(out, &results.route_collisions, "Route collisions", |c| {
514        format_markdown_route_collision(c, rel)
515    });
516    markdown_section(
517        out,
518        &results.dynamic_segment_name_conflicts,
519        "Dynamic segment conflicts",
520        |c| format_markdown_dynamic_segment_name_conflict(c, rel),
521    );
522    markdown_section(
523        out,
524        &results.unprovided_injects,
525        "Unprovided injects",
526        |i| format_markdown_unprovided_inject(i, rel),
527    );
528}
529
530/// Push the Effect sections: unused layers, unused tagged errors and
531/// unproduced catch tags.
532fn push_markdown_effect_sections(
533    out: &mut String,
534    results: &AnalysisResults,
535    rel: &dyn Fn(&Path) -> String,
536) {
537    markdown_section(
538        out,
539        &results.unused_effect_layers,
540        "Unused Effect layers",
541        |f| {
542            vec![format!(
543                "- {}:{} {} is composed only into layers that nothing uses ({})",
544                markdown_code_span(&rel(&f.layer.path)),
545                f.layer.line,
546                markdown_code_span(&f.layer.name),
547                f.layer.dead_consumers.join(", "),
548            )]
549        },
550    );
551    markdown_section(
552        out,
553        &results.unused_tagged_errors,
554        "Unused tagged errors",
555        |f| {
556            vec![format!(
557                "- {}:{} {} is never constructed or failed with (remove it or fail with it)",
558                markdown_code_span(&rel(&f.error.path)),
559                f.error.line,
560                markdown_code_span(&f.error.name),
561            )]
562        },
563    );
564    markdown_section(
565        out,
566        &results.unproduced_catch_tags,
567        "Unproduced catch tags",
568        |f| {
569            vec![format!(
570                "- {}:{} catchTag {} handles a tag that no code produces",
571                markdown_code_span(&rel(&f.catch_tag.path)),
572                f.catch_tag.line,
573                markdown_code_span(&f.catch_tag.tag),
574            )]
575        },
576    );
577}
578
579fn push_markdown_component_sections(
580    out: &mut String,
581    results: &AnalysisResults,
582    rel: &dyn Fn(&Path) -> String,
583) {
584    markdown_section(
585        out,
586        &results.unrendered_components,
587        "Unrendered components",
588        |c| format_markdown_unrendered_component(c, rel),
589    );
590    markdown_section(
591        out,
592        &results.absent_component_props,
593        "Absent optional component props",
594        |finding| {
595            let prop = &finding.prop;
596            let callers = prop
597                .inspected_call_sites
598                .iter()
599                .map(|site| markdown_code_span(&format!("{}:{}", rel(&site.path), site.line)))
600                .collect::<Vec<_>>()
601                .join(", ");
602            vec![format!(
603                "- {} in {} ({}; default: {}). {} Inspected callers: {}",
604                markdown_code_span(&format!("{}.{}", prop.component_name, prop.prop_name)),
605                markdown_code_span(&format!("{}:{}", rel(&prop.path), prop.line)),
606                prop.framework,
607                if prop.has_default {
608                    "present"
609                } else {
610                    "absent"
611                },
612                prop.explanation,
613                callers
614            )]
615        },
616    );
617    markdown_section(
618        out,
619        &results.unused_component_props,
620        "Unused component props",
621        |p| format_markdown_unused_component_prop(p, rel),
622    );
623    markdown_section(
624        out,
625        &results.unused_component_emits,
626        "Unused component emits",
627        |e| format_markdown_unused_component_emit(e, rel),
628    );
629    markdown_section(
630        out,
631        &results.unused_component_inputs,
632        "Unused component inputs",
633        |i| format_markdown_unused_component_input(i, rel),
634    );
635    markdown_section(
636        out,
637        &results.unused_component_outputs,
638        "Unused component outputs",
639        |o| format_markdown_unused_component_output(o, rel),
640    );
641    markdown_section(
642        out,
643        &results.unused_svelte_events,
644        "Unused Svelte events",
645        |e| format_markdown_unused_svelte_event(e, rel),
646    );
647    push_markdown_effect_sections(out, results, rel);
648    markdown_section(
649        out,
650        &results.unused_server_actions,
651        "Unused server actions",
652        |a| format_markdown_unused_server_action(a, rel),
653    );
654    markdown_section(
655        out,
656        &results.unused_load_data_keys,
657        "Unused load data keys",
658        |k| format_markdown_unused_load_data_key(k, rel),
659    );
660}
661
662fn push_markdown_suppression_sections(
663    out: &mut String,
664    results: &AnalysisResults,
665    rel: &dyn Fn(&Path) -> String,
666) {
667    markdown_section(
668        out,
669        &results.stale_suppressions,
670        "Stale suppressions",
671        |s| {
672            vec![format!(
673                "- {}:{} {} ({})",
674                markdown_code_span(&rel(&s.path)),
675                s.line,
676                markdown_code_span(&s.description()),
677                escape_markdown_prose(&s.explanation()),
678            )]
679        },
680    );
681}
682
683fn format_markdown_circular_dependency(
684    cycle: &fallow_types::output_dead_code::CircularDependencyFinding,
685    rel: &dyn Fn(&Path) -> String,
686) -> Vec<String> {
687    let chain: Vec<String> = cycle.cycle.files.iter().map(|p| rel(p)).collect();
688    let mut display_chain = chain.clone();
689    if let Some(first) = chain.first() {
690        display_chain.push(first.clone());
691    }
692    let cross_pkg_tag = if cycle.cycle.is_cross_package {
693        " *(cross-package)*"
694    } else {
695        ""
696    };
697    vec![format!(
698        "- {}{}",
699        display_chain
700            .iter()
701            .map(|s| markdown_code_span(s))
702            .collect::<Vec<_>>()
703            .join(" \u{2192} "),
704        cross_pkg_tag
705    )]
706}
707
708fn format_markdown_re_export_cycle(
709    cycle: &fallow_types::output_dead_code::ReExportCycleFinding,
710    rel: &dyn Fn(&Path) -> String,
711) -> Vec<String> {
712    let chain: Vec<String> = cycle.cycle.files.iter().map(|p| rel(p)).collect();
713    let kind_tag = match cycle.cycle.kind {
714        fallow_types::results::ReExportCycleKind::SelfLoop => " *(self-loop)*",
715        fallow_types::results::ReExportCycleKind::MultiNode => "",
716    };
717    vec![format!(
718        "- {}{}",
719        chain
720            .iter()
721            .map(|s| markdown_code_span(s))
722            .collect::<Vec<_>>()
723            .join(" <-> "),
724        kind_tag
725    )]
726}
727
728fn format_markdown_package_cycle(
729    cycle: &fallow_types::output_dead_code::PackageCycleFinding,
730    rel: &dyn Fn(&Path) -> String,
731) -> Vec<String> {
732    let mut chain: Vec<String> = cycle
733        .cycle
734        .packages
735        .iter()
736        .map(|name| markdown_code_span(name))
737        .collect();
738    if let Some(first) = chain.first().cloned() {
739        chain.push(first);
740    }
741    let note = if cycle.cycle.group_truncated {
742        format!(
743            " *({})*",
744            fallow_types::results::PackageCycle::GROUP_TRUNCATED_NOTE
745        )
746    } else {
747        String::new()
748    };
749    let mut lines = vec![format!("- {}{note}", chain.join(" \u{2192} "))];
750    for edge in &cycle.cycle.edges {
751        let type_tag = if edge.type_only { " *(type-only)*" } else { "" };
752        lines.push(format!(
753            "  - {} imports {}{}",
754            markdown_code_span(&format!("{}:{}", rel(&edge.path), edge.line)),
755            markdown_code_span(&rel(&edge.target_path)),
756            type_tag
757        ));
758    }
759    lines
760}
761
762fn format_markdown_boundary_violation(
763    v: &fallow_types::output_dead_code::BoundaryViolationFinding,
764    rel: &dyn Fn(&Path) -> String,
765) -> Vec<String> {
766    let via = v
767        .violation
768        .via_path
769        .as_ref()
770        .map_or_else(String::new, |via| {
771            format!(" via {}", markdown_code_span(&rel(via)))
772        });
773    vec![format!(
774        "- {}:{}  \u{2192} {} ({} \u{2192} {}){}",
775        markdown_code_span(&rel(&v.violation.from_path)),
776        v.violation.line,
777        markdown_code_span(&rel(&v.violation.to_path)),
778        v.violation.from_zone,
779        v.violation.to_zone,
780        via,
781    )]
782}
783
784fn format_markdown_boundary_coverage(
785    v: &fallow_types::output_dead_code::BoundaryCoverageViolationFinding,
786    rel: &dyn Fn(&Path) -> String,
787) -> Vec<String> {
788    vec![format!(
789        "- {}:{} no matching boundary zone",
790        markdown_code_span(&rel(&v.violation.path)),
791        v.violation.line,
792    )]
793}
794
795fn format_markdown_boundary_call(
796    v: &fallow_types::output_dead_code::BoundaryCallViolationFinding,
797    rel: &dyn Fn(&Path) -> String,
798) -> Vec<String> {
799    vec![format!(
800        "- {}:{} {} forbidden in zone {} (pattern {})",
801        markdown_code_span(&rel(&v.violation.path)),
802        v.violation.line,
803        markdown_code_span(&v.violation.callee),
804        markdown_code_span(&v.violation.zone),
805        markdown_code_span(&v.violation.pattern),
806    )]
807}
808
809fn format_markdown_policy_violation(
810    v: &fallow_types::output_dead_code::PolicyViolationFinding,
811    rel: &dyn Fn(&Path) -> String,
812) -> Vec<String> {
813    let policy = format!("{}/{}", v.violation.pack, v.violation.rule_id);
814    vec![format!(
815        "- {}:{} {} banned by {}{}",
816        markdown_code_span(&rel(&v.violation.path)),
817        v.violation.line,
818        markdown_code_span(&v.violation.matched),
819        markdown_code_span(&policy),
820        v.violation
821            .message
822            .as_deref()
823            .map(|m| format!(" ({m})"))
824            .unwrap_or_default(),
825    )]
826}
827
828fn format_markdown_invalid_client_export(
829    e: &fallow_types::output_dead_code::InvalidClientExportFinding,
830    rel: &dyn Fn(&Path) -> String,
831) -> Vec<String> {
832    let directive = format!("\"{}\"", e.export.directive);
833    vec![format!(
834        "- {}:{} {} (from {})",
835        markdown_code_span(&rel(&e.export.path)),
836        e.export.line,
837        markdown_code_span(&e.export.export_name),
838        markdown_code_span(&directive),
839    )]
840}
841
842fn format_markdown_mixed_client_server_barrel(
843    b: &fallow_types::output_dead_code::MixedClientServerBarrelFinding,
844    rel: &dyn Fn(&Path) -> String,
845) -> Vec<String> {
846    vec![format!(
847        "- {}:{} re-exports client {} and server-only {}",
848        markdown_code_span(&rel(&b.barrel.path)),
849        b.barrel.line,
850        markdown_code_span(&b.barrel.client_origin),
851        markdown_code_span(&b.barrel.server_origin),
852    )]
853}
854
855fn format_markdown_misplaced_directive(
856    d: &fallow_types::output_dead_code::MisplacedDirectiveFinding,
857    rel: &dyn Fn(&Path) -> String,
858) -> Vec<String> {
859    let directive = format!("\"{}\"", d.directive_site.directive);
860    vec![format!(
861        "- {}:{} {} is not in the leading position and is ignored",
862        markdown_code_span(&rel(&d.directive_site.path)),
863        d.directive_site.line,
864        markdown_code_span(&directive),
865    )]
866}
867
868fn format_markdown_unprovided_inject(
869    i: &fallow_types::output_dead_code::UnprovidedInjectFinding,
870    rel: &dyn Fn(&Path) -> String,
871) -> Vec<String> {
872    vec![format!(
873        "- {}:{} {} has no matching provide({}) in this project; at runtime it returns undefined",
874        markdown_code_span(&rel(&i.inject.path)),
875        i.inject.line,
876        markdown_code_span(&i.inject.key_name),
877        markdown_code_span(&i.inject.key_name),
878    )]
879}
880
881fn format_markdown_unrendered_component(
882    c: &fallow_types::output_dead_code::UnrenderedComponentFinding,
883    rel: &dyn Fn(&Path) -> String,
884) -> Vec<String> {
885    // Lit: `component_name` is the registered TAG, so render it as a custom
886    // element `<x-foo>` (mirrors the human formatter's `framework == "lit"`
887    // branch so the two human-facing surfaces stay consistent).
888    if c.component.framework == "lit" {
889        let component = format!("<{}>", c.component.component_name);
890        return vec![format!(
891            "- {}:{} {} is a registered custom element but rendered in no template (render it or remove it)",
892            markdown_code_span(&rel(&c.component.path)),
893            c.component.line,
894            markdown_code_span(&component),
895        )];
896    }
897    vec![format!(
898        "- {}:{} {} is reachable but rendered nowhere in this project (render it somewhere or remove it)",
899        markdown_code_span(&rel(&c.component.path)),
900        c.component.line,
901        markdown_code_span(&c.component.component_name),
902    )]
903}
904
905fn format_markdown_unused_component_prop(
906    p: &fallow_types::output_dead_code::UnusedComponentPropFinding,
907    rel: &dyn Fn(&Path) -> String,
908) -> Vec<String> {
909    vec![format!(
910        "- {}:{} {} is declared but referenced nowhere in this component (remove it or use it)",
911        markdown_code_span(&rel(&p.prop.path)),
912        p.prop.line,
913        markdown_code_span(&p.prop.prop_name),
914    )]
915}
916
917fn format_markdown_unused_component_emit(
918    e: &fallow_types::output_dead_code::UnusedComponentEmitFinding,
919    rel: &dyn Fn(&Path) -> String,
920) -> Vec<String> {
921    vec![format!(
922        "- {}:{} {} is declared but emitted nowhere in this component (remove it or emit it)",
923        markdown_code_span(&rel(&e.emit.path)),
924        e.emit.line,
925        markdown_code_span(&e.emit.emit_name),
926    )]
927}
928
929fn format_markdown_unused_svelte_event(
930    e: &fallow_types::output_dead_code::UnusedSvelteEventFinding,
931    rel: &dyn Fn(&Path) -> String,
932) -> Vec<String> {
933    vec![format!(
934        "- {}:{} {} is dispatched but listened to nowhere in the project (remove it or listen for it)",
935        markdown_code_span(&rel(&e.event.path)),
936        e.event.line,
937        markdown_code_span(&e.event.event_name),
938    )]
939}
940
941fn format_markdown_unused_component_input(
942    i: &fallow_types::output_dead_code::UnusedComponentInputFinding,
943    rel: &dyn Fn(&Path) -> String,
944) -> Vec<String> {
945    vec![format!(
946        "- {}:{} {} is declared but referenced nowhere in this component (remove it or use it)",
947        markdown_code_span(&rel(&i.input.path)),
948        i.input.line,
949        markdown_code_span(&i.input.input_name),
950    )]
951}
952
953fn format_markdown_unused_component_output(
954    o: &fallow_types::output_dead_code::UnusedComponentOutputFinding,
955    rel: &dyn Fn(&Path) -> String,
956) -> Vec<String> {
957    vec![format!(
958        "- {}:{} {} is declared but emitted nowhere in this component (remove it or emit it)",
959        markdown_code_span(&rel(&o.output.path)),
960        o.output.line,
961        markdown_code_span(&o.output.output_name),
962    )]
963}
964
965fn format_markdown_unused_server_action(
966    a: &fallow_types::output_dead_code::UnusedServerActionFinding,
967    rel: &dyn Fn(&Path) -> String,
968) -> Vec<String> {
969    vec![format!(
970        "- {}:{} {} is exported from a \"use server\" file but no code in this project references it",
971        markdown_code_span(&rel(&a.action.path)),
972        a.action.line,
973        markdown_code_span(&a.action.action_name),
974    )]
975}
976
977fn format_markdown_unused_load_data_key(
978    k: &fallow_types::output_dead_code::UnusedLoadDataKeyFinding,
979    rel: &dyn Fn(&Path) -> String,
980) -> Vec<String> {
981    vec![format!(
982        "- {}:{} {} is returned from load() but no consumer reads it",
983        markdown_code_span(&rel(&k.key.path)),
984        k.key.line,
985        markdown_code_span(&k.key.key_name),
986    )]
987}
988
989fn format_markdown_route_collision(
990    c: &fallow_types::output_dead_code::RouteCollisionFinding,
991    rel: &dyn Fn(&Path) -> String,
992) -> Vec<String> {
993    vec![format!(
994        "- {} resolves to {} (shared with {} other route file(s))",
995        markdown_code_span(&rel(&c.collision.path)),
996        markdown_code_span(&c.collision.url),
997        c.collision.conflicting_paths.len(),
998    )]
999}
1000
1001fn format_markdown_dynamic_segment_name_conflict(
1002    c: &fallow_types::output_dead_code::DynamicSegmentNameConflictFinding,
1003    rel: &dyn Fn(&Path) -> String,
1004) -> Vec<String> {
1005    vec![format!(
1006        "- {} crashes at runtime: different slug names ({}) at the same dynamic path {}; \
1007         `next build` passes but the route fails on its first request (rename to one consistent slug)",
1008        markdown_code_span(&rel(&c.conflict.path)),
1009        c.conflict.conflicting_segments.join(" vs "),
1010        markdown_code_span(&c.conflict.position),
1011    )]
1012}
1013
1014fn push_markdown_catalog_sections(
1015    out: &mut String,
1016    results: &AnalysisResults,
1017    rel: &dyn Fn(&Path) -> String,
1018) {
1019    markdown_section(
1020        out,
1021        &results.unused_catalog_entries,
1022        "Unused catalog entries",
1023        |entry| format_unused_catalog_entry(entry, rel),
1024    );
1025    markdown_section(
1026        out,
1027        &results.empty_catalog_groups,
1028        "Empty catalog groups",
1029        |group| {
1030            vec![format!(
1031                "- {} {}:{}",
1032                markdown_code_span(&group.group.catalog_name),
1033                markdown_code_span(&rel(&group.group.path)),
1034                group.group.line,
1035            )]
1036        },
1037    );
1038    markdown_section(
1039        out,
1040        &results.unresolved_catalog_references,
1041        "Unresolved catalog references",
1042        |finding| format_unresolved_catalog_reference(finding, rel),
1043    );
1044    markdown_section(
1045        out,
1046        &results.unused_dependency_overrides,
1047        "Unused dependency overrides",
1048        |finding| format_unused_dependency_override(finding, rel),
1049    );
1050    markdown_section(
1051        out,
1052        &results.misconfigured_dependency_overrides,
1053        "Misconfigured dependency overrides",
1054        |finding| {
1055            vec![format!(
1056                "- {} -> {} ({}) {}:{} ({})",
1057                markdown_code_span(&finding.entry.raw_key),
1058                markdown_code_span(&finding.entry.raw_value),
1059                markdown_code_span(finding.entry.source.as_label()),
1060                markdown_code_span(&rel(&finding.entry.path)),
1061                finding.entry.line,
1062                finding.entry.reason.describe(),
1063            )]
1064        },
1065    );
1066}
1067
1068fn format_unused_catalog_entry(
1069    entry: &UnusedCatalogEntryFinding,
1070    rel: &dyn Fn(&Path) -> String,
1071) -> Vec<String> {
1072    let mut row = format!(
1073        "- {} ({}) {}:{}",
1074        markdown_code_span(&entry.entry.entry_name),
1075        markdown_code_span(&entry.entry.catalog_name),
1076        markdown_code_span(&rel(&entry.entry.path)),
1077        entry.entry.line,
1078    );
1079    if !entry.entry.hardcoded_consumers.is_empty() {
1080        let consumers = entry
1081            .entry
1082            .hardcoded_consumers
1083            .iter()
1084            .map(|p| markdown_code_span(&rel(p)))
1085            .collect::<Vec<_>>()
1086            .join(", ");
1087        let _ = write!(row, " (hardcoded in {consumers})");
1088    }
1089    vec![row]
1090}
1091
1092fn format_unresolved_catalog_reference(
1093    finding: &UnresolvedCatalogReferenceFinding,
1094    rel: &dyn Fn(&Path) -> String,
1095) -> Vec<String> {
1096    let mut row = format!(
1097        "- {} ({}) {}:{}",
1098        markdown_code_span(&finding.reference.entry_name),
1099        markdown_code_span(&finding.reference.catalog_name),
1100        markdown_code_span(&rel(&finding.reference.path)),
1101        finding.reference.line,
1102    );
1103    if !finding.reference.available_in_catalogs.is_empty() {
1104        let alts = finding
1105            .reference
1106            .available_in_catalogs
1107            .iter()
1108            .map(|c| markdown_code_span(c))
1109            .collect::<Vec<_>>()
1110            .join(", ");
1111        let _ = write!(row, " (available in: {alts})");
1112    }
1113    vec![row]
1114}
1115
1116fn format_unused_dependency_override(
1117    finding: &UnusedDependencyOverrideFinding,
1118    rel: &dyn Fn(&Path) -> String,
1119) -> Vec<String> {
1120    let mut row = format!(
1121        "- {} -> {} ({}) {}:{}",
1122        markdown_code_span(&finding.entry.raw_key),
1123        markdown_code_span(&finding.entry.version_range),
1124        markdown_code_span(finding.entry.source.as_label()),
1125        markdown_code_span(&rel(&finding.entry.path)),
1126        finding.entry.line,
1127    );
1128    if let Some(hint) = &finding.entry.hint {
1129        let _ = write!(row, " (hint: {})", escape_markdown_prose(hint));
1130    }
1131    vec![row]
1132}
1133
1134/// Build grouped markdown output: each group gets a heading and issue sections.
1135///
1136/// `cascade_hidden` is the count of the whole run. The groups do not carry
1137/// it, so the report names it once, after the last group.
1138#[must_use]
1139pub fn build_grouped_markdown(
1140    groups: &[ResultGroup],
1141    root: &Path,
1142    cascade_hidden: usize,
1143) -> String {
1144    let total: usize = groups.iter().map(|g| g.results.total_issues()).sum();
1145    let signals: usize = groups.iter().map(|g| health_signal_count(&g.results)).sum();
1146    let mut out = String::new();
1147
1148    if total == 0 && signals == 0 {
1149        out.push_str("## Fallow: no issues found\n");
1150        push_cascade_note(&mut out, cascade_hidden);
1151        return out;
1152    }
1153
1154    if total == 0 {
1155        out.push_str("## Fallow: no issues found (grouped)\n\n");
1156    } else {
1157        let _ = writeln!(
1158            out,
1159            "## Fallow: {total} issue{} found (grouped)\n",
1160            plural(total)
1161        );
1162    }
1163
1164    for group in groups {
1165        let count = group.results.total_issues();
1166        let group_signals = health_signal_count(&group.results);
1167        if count == 0 && group_signals == 0 {
1168            continue;
1169        }
1170        let signal_part = crate::grouped_output::health_signal_header_part(&group.results);
1171        let _ = writeln!(
1172            out,
1173            "## {} ({count} issue{}{signal_part})\n",
1174            escape_markdown_prose(&group.key),
1175            plural(count)
1176        );
1177        if let Some(ref owners) = group.owners
1178            && !owners.is_empty()
1179        {
1180            let joined = owners
1181                .iter()
1182                .map(|owner| escape_markdown_prose(owner))
1183                .collect::<Vec<_>>()
1184                .join(" ");
1185            let _ = writeln!(out, "Owners: {joined}\n");
1186        }
1187        push_markdown_sections(&mut out, &group.results, root);
1188    }
1189
1190    push_cascade_note(&mut out, cascade_hidden);
1191    out
1192}
1193
1194/// The italic caveat parenthetical a markdown finding line ends with, or an
1195/// empty string when the run analyzed every file it discovered.
1196///
1197/// Markdown is the PR-comment surface, so a reader acts on this listing. The
1198/// same words the human report and the SARIF message use, italicized so the
1199/// hedge is visible without competing with the finding itself.
1200fn markdown_caveat_suffix(caveats: &[ReachabilityCaveat]) -> String {
1201    caveat_labels(caveats).map_or_else(String::new, |labels| format!(" *(caveat: {labels})*"))
1202}
1203
1204fn format_export(e: &UnusedExport, caveats: &[ReachabilityCaveat]) -> String {
1205    let re = if e.is_re_export { " (re-export)" } else { "" };
1206    let deprecated = if e.deprecated {
1207        " (marked @deprecated)"
1208    } else {
1209        ""
1210    };
1211    format!(
1212        ":{} {}{re}{deprecated}{}",
1213        e.line,
1214        markdown_code_span(&e.export_name),
1215        markdown_caveat_suffix(caveats)
1216    )
1217}
1218
1219fn format_deprecated_export_in_use(
1220    entry: &fallow_types::output_dead_code::DeprecatedExportInUseFinding,
1221) -> String {
1222    let e = &entry.export;
1223    let consumers = format!("{} consumer{}", e.consumer_count, plural(e.consumer_count));
1224    let scope = if e.public_api { " (public API)" } else { "" };
1225    let reason = e
1226        .deprecated_reason
1227        .as_deref()
1228        .map_or_else(String::new, |reason| {
1229            format!(": {}", escape_markdown_inline(reason))
1230        });
1231    format!(
1232        ":{} {} still used by {consumers}{scope}{reason}",
1233        e.line,
1234        markdown_code_span(&e.export_name),
1235    )
1236}
1237
1238fn format_private_type_leak(
1239    entry: &fallow_types::output_dead_code::PrivateTypeLeakFinding,
1240) -> String {
1241    let e = &entry.leak;
1242    format!(
1243        ":{} {} references private type {}",
1244        e.line,
1245        markdown_code_span(&e.export_name),
1246        markdown_code_span(&e.type_name)
1247    )
1248}
1249
1250fn format_member(m: &UnusedMember, caveats: &[ReachabilityCaveat]) -> String {
1251    let member = format!("{}.{}", m.parent_name, m.member_name);
1252    format!(
1253        ":{} {}{}",
1254        m.line,
1255        markdown_code_span(&member),
1256        markdown_caveat_suffix(caveats)
1257    )
1258}
1259
1260fn format_dependency(
1261    dep_name: &str,
1262    pkg_path: &Path,
1263    used_in_workspaces: &[std::path::PathBuf],
1264    root: &Path,
1265    caveats: &[ReachabilityCaveat],
1266) -> Vec<String> {
1267    let caveat = markdown_caveat_suffix(caveats);
1268    let name = markdown_code_span(dep_name);
1269    let pkg_label = relative_path(pkg_path, root).display().to_string();
1270    let workspace_context = if used_in_workspaces.is_empty() {
1271        String::new()
1272    } else {
1273        let workspaces = used_in_workspaces
1274            .iter()
1275            .map(|path| markdown_code_span(&relative_path(path, root).display().to_string()))
1276            .collect::<Vec<_>>()
1277            .join(", ");
1278        format!("; imported in {workspaces}")
1279    };
1280    if pkg_label == "package.json" && workspace_context.is_empty() {
1281        vec![format!("- {name}{caveat}")]
1282    } else {
1283        let label = if pkg_label == "package.json" {
1284            workspace_context.trim_start_matches("; ").to_string()
1285        } else {
1286            format!("{}{workspace_context}", markdown_code_span(&pkg_label))
1287        };
1288        vec![format!("- {name} ({label}){caveat}")]
1289    }
1290}
1291
1292/// Emit a markdown section with a header and per-item lines. Skipped if empty.
1293fn markdown_section<T>(
1294    out: &mut String,
1295    items: &[T],
1296    title: &str,
1297    format_lines: impl Fn(&T) -> Vec<String>,
1298) {
1299    if items.is_empty() {
1300        return;
1301    }
1302    let _ = write!(out, "### {title} ({})\n\n", items.len());
1303    for item in items {
1304        for line in format_lines(item) {
1305            out.push_str(&line);
1306            out.push('\n');
1307        }
1308    }
1309    out.push('\n');
1310}
1311
1312fn markdown_grouped_section<'a, T>(
1313    out: &mut String,
1314    items: &'a [T],
1315    title: &str,
1316    root: &Path,
1317    get_path: impl Fn(&'a T) -> &'a Path,
1318    format_detail: impl Fn(&T) -> String,
1319) {
1320    if items.is_empty() {
1321        return;
1322    }
1323    let _ = write!(out, "### {title} ({})\n\n", items.len());
1324
1325    let mut indices: Vec<usize> = (0..items.len()).collect();
1326    indices.sort_by(|&a, &b| get_path(&items[a]).cmp(get_path(&items[b])));
1327
1328    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
1329    let mut last_file = String::new();
1330    for &i in &indices {
1331        let item = &items[i];
1332        let file_str = rel(get_path(item));
1333        if file_str != last_file {
1334            let _ = writeln!(out, "- {}", markdown_code_span(&file_str));
1335            last_file = file_str;
1336        }
1337        let _ = writeln!(out, "  - {}", format_detail(item));
1338    }
1339    out.push('\n');
1340}
1341
1342/// Name what a display limit withheld from the listing below, so the corpus
1343/// counts in the heading and summary are not read as the size of the listing.
1344///
1345/// Emits nothing on an untruncated run, which keeps the default document
1346/// byte-identical.
1347fn write_duplication_omission_note(out: &mut String, report: &DuplicationReport) {
1348    let groups_omitted = report.clone_groups_omitted();
1349    let families_omitted = report.clone_families_omitted();
1350    if groups_omitted == 0 && families_omitted == 0 {
1351        return;
1352    }
1353
1354    let mut withheld: Vec<String> = Vec::with_capacity(2);
1355    if groups_omitted > 0 {
1356        withheld.push(format!(
1357            "{} more clone group{}",
1358            groups_omitted,
1359            plural(groups_omitted)
1360        ));
1361    }
1362    if families_omitted > 0 {
1363        withheld.push(format!(
1364            "{} more clone famil{}",
1365            families_omitted,
1366            if families_omitted == 1 { "y" } else { "ies" }
1367        ));
1368    }
1369
1370    let _ = write!(
1371        out,
1372        "_Listing {} of them; {} withheld by a display limit._\n\n",
1373        report.clone_groups_shown(),
1374        withheld.join(" and "),
1375    );
1376}
1377
1378/// Build markdown output for duplication results.
1379#[must_use]
1380pub fn build_duplication_markdown(report: &DuplicationReport, root: &Path) -> String {
1381    let mut out = String::new();
1382
1383    if report.clone_groups.is_empty() {
1384        out.push_str("## Fallow: no code duplication found\n");
1385        return out;
1386    }
1387
1388    let stats = &report.stats;
1389    // The heading and the duplication rate beside it must describe one scope.
1390    // `--top` narrows the listing below, never the corpus the run measured, so
1391    // the heading counts the corpus and a separate note names what a display
1392    // limit withheld.
1393    let corpus_groups = report.clone_groups_total();
1394    let _ = write!(
1395        out,
1396        "## Fallow: {} clone group{} found ({:.1}% duplication)\n\n",
1397        corpus_groups,
1398        plural(corpus_groups),
1399        stats.duplication_percentage,
1400    );
1401    write_duplication_omission_note(&mut out, report);
1402
1403    write_duplication_groups(&mut out, report, root);
1404    write_duplication_families(&mut out, report, root);
1405
1406    let _ = writeln!(
1407        out,
1408        "**Summary:** {} duplicated lines ({:.1}%) across {} file{}",
1409        stats.duplicated_lines,
1410        stats.duplication_percentage,
1411        stats.files_with_clones,
1412        plural(stats.files_with_clones),
1413    );
1414
1415    out
1416}
1417
1418/// Write the clone-groups subsection of the duplication markdown.
1419fn write_duplication_groups(out: &mut String, report: &DuplicationReport, root: &Path) {
1420    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
1421    out.push_str("### Duplicates\n\n");
1422    for (i, group) in report.clone_groups.iter().enumerate() {
1423        let instance_count = group.instances.len();
1424        let _ = write!(
1425            out,
1426            "**Clone group {}** ({} lines, {instance_count} instance{})\n\n",
1427            i + 1,
1428            group.line_count,
1429            plural(instance_count)
1430        );
1431        for instance in &group.instances {
1432            let relative = rel(&instance.file);
1433            let location = format!("{relative}:{}-{}", instance.start_line, instance.end_line);
1434            let _ = writeln!(out, "- {}", markdown_code_span(&location));
1435        }
1436        out.push('\n');
1437    }
1438}
1439
1440/// Write the clone-families subsection of the duplication markdown.
1441fn write_duplication_families(out: &mut String, report: &DuplicationReport, root: &Path) {
1442    if report.clone_families.is_empty() {
1443        return;
1444    }
1445    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
1446    out.push_str("### Clone Families\n\n");
1447    for (i, family) in report.clone_families.iter().enumerate() {
1448        let file_names: Vec<_> = family.files.iter().map(|f| rel(f)).collect();
1449        let _ = write!(
1450            out,
1451            "**Family {}** ({} group{}, {} lines across {})\n\n",
1452            i + 1,
1453            family.groups.len(),
1454            plural(family.groups.len()),
1455            family.total_duplicated_lines,
1456            file_names
1457                .iter()
1458                .map(|s| markdown_code_span(s))
1459                .collect::<Vec<_>>()
1460                .join(", "),
1461        );
1462        for suggestion in &family.suggestions {
1463            let savings = if suggestion.estimated_savings > 0 {
1464                format!(" (~{} lines saved)", suggestion.estimated_savings)
1465            } else {
1466                String::new()
1467            };
1468            let _ = writeln!(out, "- {}{savings}", suggestion.description);
1469        }
1470        out.push('\n');
1471    }
1472}
1473
1474/// What a health report says about its complexity findings. Markdown and the
1475/// job summary build it from the report and use one rule, so the two
1476/// surfaces agree.
1477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1478pub struct ComplexityListing {
1479    /// The length of the finding list.
1480    pub listed: usize,
1481    /// `summary.functions_above_threshold`, which fallow counts before the
1482    /// baseline.
1483    pub above: usize,
1484    /// `Some(true)` when `sections` contains `complexity`, `Some(false)` when
1485    /// `sections` does not, and `None` for an older report without `sections`.
1486    pub complexity_section: Option<bool>,
1487    /// True when the report has no `vital_signs`, which only a score-only run
1488    /// omits. The rule reads it only when `complexity_section` is `None`.
1489    pub score_only: bool,
1490    /// True when the run loaded a baseline.
1491    pub baselined: bool,
1492    /// `summary.baseline_staleness.remaining_findings`: the functions above a
1493    /// threshold that the baseline does not accept. `None` without a baseline
1494    /// and in an older report.
1495    pub remaining: Option<usize>,
1496}
1497
1498impl ComplexityListing {
1499    /// Tell if the complexity section gives the count of functions above a
1500    /// threshold instead of a clean result.
1501    ///
1502    /// A run that did not produce the `complexity` section does not list
1503    /// findings, so an empty list does not make it clean. A run that lists
1504    /// findings, with an empty list and a baseline, is clean: the baseline
1505    /// accepts every finding.
1506    ///
1507    /// An older report without `sections` falls back to the earlier rule: a
1508    /// score-only run gives the count, and another run gives the count only
1509    /// without a baseline.
1510    #[must_use]
1511    pub const fn count_unlisted(&self) -> bool {
1512        if self.above == 0 {
1513            return false;
1514        }
1515        match self.complexity_section {
1516            Some(listed_section) => !listed_section,
1517            None => self.listed == 0 && (self.score_only || !self.baselined),
1518        }
1519    }
1520
1521    /// The sentences after the count of functions that the run does not list.
1522    ///
1523    /// With a baseline, the note tells how many functions the baseline accepts
1524    /// and how many are new. An older report without `remaining_findings`
1525    /// says that the count includes the accepted functions.
1526    #[must_use]
1527    pub fn not_listed_note(&self) -> String {
1528        const NOT_LISTED: &str = "This run does not list the functions.";
1529        if !self.baselined {
1530            return format!("{NOT_LISTED} Run `fallow health --complexity` to list them.");
1531        }
1532        let Some(remaining) = self.remaining else {
1533            return format!(
1534                "{NOT_LISTED} The count includes the functions that the baseline accepts. \
1535                 Run `fallow health --complexity` with the same `--baseline` to list the \
1536                 functions that the baseline does not accept."
1537            );
1538        };
1539        let accepted = self.above.saturating_sub(remaining);
1540        let verb = if remaining == 1 { "is" } else { "are" };
1541        let mut note =
1542            format!("The baseline accepts {accepted}. {remaining} {verb} new. {NOT_LISTED}");
1543        if remaining > 0 {
1544            note.push_str(
1545                " Run `fallow health --complexity` with the same `--baseline` to list the \
1546                 new functions.",
1547            );
1548        }
1549        note
1550    }
1551}
1552
1553/// The complexity listing facts of a typed health report.
1554fn complexity_listing(report: &fallow_output::HealthReport) -> ComplexityListing {
1555    let staleness = report.summary.baseline_staleness.as_ref();
1556    ComplexityListing {
1557        listed: report.findings.len(),
1558        above: report.summary.functions_above_threshold,
1559        complexity_section: report
1560            .sections
1561            .as_ref()
1562            .map(|sections| sections.contains(&fallow_output::HealthSection::Complexity)),
1563        score_only: report.vital_signs.is_none(),
1564        baselined: staleness.is_some(),
1565        remaining: staleness.and_then(|staleness| staleness.remaining_findings),
1566    }
1567}
1568
1569fn write_complexity_not_listed(
1570    out: &mut String,
1571    summary: &fallow_output::HealthSummary,
1572    listing: &ComplexityListing,
1573) {
1574    let above = summary.functions_above_threshold;
1575    let _ = writeln!(
1576        out,
1577        "## Fallow: {above} function{} exceed{} complexity thresholds\n\n\
1578         **{}** functions analyzed (max cyclomatic: {}, max cognitive: {}, max CRAP: {:.1}). {}",
1579        if above == 1 { "" } else { "s" },
1580        if above == 1 { "s" } else { "" },
1581        summary.functions_analyzed,
1582        summary.max_cyclomatic_threshold,
1583        summary.max_cognitive_threshold,
1584        summary.max_crap_threshold,
1585        listing.not_listed_note(),
1586    );
1587}
1588
1589/// Build markdown output for health (complexity) results.
1590#[must_use]
1591pub fn build_health_markdown(report: &fallow_output::HealthReport, root: &Path) -> String {
1592    let mut out = String::new();
1593
1594    if let Some(ref hs) = report.health_score {
1595        let _ = writeln!(out, "## Health Score: {:.0} ({})\n", hs.score, hs.grade);
1596    }
1597
1598    write_trend_section(&mut out, report);
1599    write_vital_signs_section(&mut out, report);
1600
1601    if report.findings.is_empty()
1602        && report.file_scores.is_empty()
1603        && report.coverage_gaps.is_none()
1604        && report.hotspots.is_empty()
1605        && report
1606            .change_coupling
1607            .as_ref()
1608            .is_none_or(|coupling| coupling.pairs.is_empty())
1609        && report.targets.is_empty()
1610        && report.runtime_coverage.is_none()
1611        && report.coverage_intelligence.is_none()
1612        && report.threshold_overrides.is_empty()
1613        && report.css_analytics.is_none()
1614        && report.styling_findings.is_empty()
1615    {
1616        // Only a score-only run omits `vital_signs`. Another run that does not
1617        // list complexity findings has no complexity section, as in the human
1618        // output.
1619        let listing = complexity_listing(report);
1620        if report.vital_signs.is_none() && listing.count_unlisted() {
1621            write_complexity_not_listed(&mut out, &report.summary, &listing);
1622        } else if report.vital_signs.is_none() {
1623            let _ = write!(
1624                out,
1625                "## Fallow: no functions exceed complexity thresholds\n\n\
1626                 **{}** functions analyzed (max cyclomatic: {}, max cognitive: {}, max CRAP: {:.1})\n",
1627                report.summary.functions_analyzed,
1628                report.summary.max_cyclomatic_threshold,
1629                report.summary.max_cognitive_threshold,
1630                report.summary.max_crap_threshold,
1631            );
1632        }
1633        return out;
1634    }
1635
1636    write_findings_section(&mut out, report, root);
1637    write_styling_findings_section(&mut out, report, root);
1638    write_threshold_overrides_section(&mut out, report, root);
1639    write_runtime_coverage_section(&mut out, report, root);
1640    write_coverage_intelligence_section(&mut out, report, root);
1641    write_coverage_gaps_section(&mut out, report, root);
1642    write_file_scores_section(&mut out, report, root);
1643    write_hotspots_section(&mut out, report, root);
1644    write_change_coupling_section(&mut out, report, root);
1645    write_targets_section(&mut out, report, root);
1646    write_css_analytics_section(&mut out, report);
1647    write_metric_legend(&mut out, report);
1648
1649    out
1650}
1651
1652/// Markdown section for the diff-risk findings of `fallow audit`: one table
1653/// row for each finding. Every finding is introduced by the change and can set
1654/// the verdict, so the table has no cap. Empty when there is no finding.
1655#[must_use]
1656pub fn build_diff_risk_markdown(report: &fallow_output::DiffRiskReport) -> String {
1657    if report.findings.is_empty() {
1658        return String::new();
1659    }
1660    let count = report.findings.len();
1661    let mut out = format!("## Fallow: {count} diff-risk finding{}\n\n", plural(count));
1662    out.push_str("| Location | Rule | Severity | Evidence |\n");
1663    out.push_str("|:---------|:-----|:---------|:---------|\n");
1664    for finding in &report.findings {
1665        let location = finding.line.map_or_else(
1666            || finding.path.clone(),
1667            |line| format!("{}:{line}", finding.path),
1668        );
1669        let rule = finding.kind.map_or_else(
1670            || markdown_table_code_span(finding.rule.code()),
1671            |kind| {
1672                format!(
1673                    "{} / {}",
1674                    markdown_table_code_span(finding.rule.code()),
1675                    markdown_table_code_span(kind.code())
1676                )
1677            },
1678        );
1679        let _ = writeln!(
1680            out,
1681            "| {} | {rule} | {} | {} |",
1682            markdown_table_code_span(&location),
1683            finding.severity.code(),
1684            markdown_table_code_span(&finding.evidence),
1685        );
1686    }
1687    out
1688}
1689
1690fn write_styling_findings_section(
1691    out: &mut String,
1692    report: &fallow_output::HealthReport,
1693    root: &Path,
1694) {
1695    if report.styling_findings.is_empty() {
1696        return;
1697    }
1698    if !out.is_empty() && !out.ends_with("\n\n") {
1699        out.push('\n');
1700    }
1701    out.push_str("## Styling Findings\n\n");
1702    out.push_str("| File | Rule | Severity | Value |\n");
1703    out.push_str("|:-----|:-----|:---------|:------|\n");
1704    for finding in report.styling_findings.iter().take(20) {
1705        let path = markdown_relative_path(Path::new(&finding.path), root);
1706        let location = format!("{path}:{}", finding.line);
1707        let severity = match finding.effective_severity {
1708            fallow_output::StylingFindingSeverity::Error => "error",
1709            fallow_output::StylingFindingSeverity::Warn => "warn",
1710        };
1711        let _ = writeln!(
1712            out,
1713            "| {} | {} / {} | {severity} | {} |",
1714            markdown_table_code_span(&location),
1715            markdown_table_code_span(&finding.code),
1716            markdown_table_code_span(&finding.sub_kind),
1717            markdown_table_code_span(&finding.value),
1718        );
1719    }
1720    if report.styling_findings.len() > 20 {
1721        let more = report.styling_findings.len() - 20;
1722        let _ = writeln!(out, "\n... and {more} more styling findings.");
1723    }
1724    out.push('\n');
1725}
1726
1727/// Render the opt-in `## CSS Health` section (only with `--css`): structural metrics,
1728/// value sprawl, candidate counts and a bounded list of located candidates.
1729fn write_css_analytics_section(out: &mut String, report: &fallow_output::HealthReport) {
1730    let Some(ref css) = report.css_analytics else {
1731        return;
1732    };
1733    let s = &css.summary;
1734    if !out.is_empty() && !out.ends_with("\n\n") {
1735        out.push('\n');
1736    }
1737    out.push_str("## CSS Health\n\n");
1738    let important_pct = if s.total_declarations > 0 {
1739        f64::from(s.important_declarations) / f64::from(s.total_declarations) * 100.0
1740    } else {
1741        0.0
1742    };
1743    let _ = writeln!(
1744        out,
1745        "- Stylesheets: {} | Rules: {} | !important: {important_pct:.1}% | Empty rules: {} | Max nesting: {}",
1746        s.files_analyzed, s.total_rules, s.empty_rules, s.max_nesting_depth,
1747    );
1748    let _ = writeln!(
1749        out,
1750        "- Value sprawl: {} colors | {} font sizes | {} z-index | {} shadows | {} radii | {} line-heights",
1751        s.unique_colors,
1752        s.unique_font_sizes,
1753        s.unique_z_indexes,
1754        s.unique_box_shadows,
1755        s.unique_border_radii,
1756        s.unique_line_heights,
1757    );
1758    let unchecked_keyframes = fallow_output::keyframes_unchecked_suffix(s);
1759    let _ = writeln!(
1760        out,
1761        "- Candidates: {} unreferenced + {} undefined @keyframes{unchecked_keyframes} | {} duplicate blocks | {} scoped-unused classes | {} Tailwind arbitrary values | {} unused @property | {} unused @layer | {} likely class typos | {} unreferenced classes | {} unused @font-face | {} unused @theme tokens",
1762        s.keyframes_unreferenced,
1763        s.keyframes_undefined,
1764        s.duplicate_declaration_blocks,
1765        s.scoped_unused_classes,
1766        s.tailwind_arbitrary_values,
1767        s.unused_property_registrations,
1768        s.unused_layers,
1769        s.unresolved_class_references,
1770        s.unreferenced_css_classes,
1771        s.unused_font_faces,
1772        s.unused_theme_tokens,
1773    );
1774    write_css_candidate_details(out, css);
1775    out.push('\n');
1776}
1777
1778fn write_css_candidate_details(out: &mut String, css: &fallow_output::CssAnalyticsReport) {
1779    write_css_keyframe_details(out, css);
1780    write_css_tailwind_details(out, css);
1781    write_css_class_candidate_details(out, css);
1782    write_css_font_candidate_details(out, css);
1783    write_css_font_size_mix_details(out, css);
1784}
1785
1786fn write_css_keyframe_details(out: &mut String, css: &fallow_output::CssAnalyticsReport) {
1787    if !css.undefined_keyframes.is_empty() {
1788        let named: Vec<String> = css
1789            .undefined_keyframes
1790            .iter()
1791            .take(5)
1792            .map(|kf| format!("{} ({})", markdown_code_span(&kf.name), kf.path))
1793            .collect();
1794        let _ = writeln!(
1795            out,
1796            "- Undefined @keyframes (candidates; likely typo or CSS-in-JS): {}",
1797            named.join(", "),
1798        );
1799    }
1800}
1801
1802fn write_css_tailwind_details(out: &mut String, css: &fallow_output::CssAnalyticsReport) {
1803    if !css.tailwind_arbitrary_values.is_empty() {
1804        let named: Vec<String> = css
1805            .tailwind_arbitrary_values
1806            .iter()
1807            .take(5)
1808            .map(|a| format!("{} ({}x)", markdown_code_span(&a.value), a.count))
1809            .collect();
1810        let _ = writeln!(out, "- Top Tailwind arbitrary values: {}", named.join(", "));
1811    }
1812}
1813
1814fn write_css_class_candidate_details(out: &mut String, css: &fallow_output::CssAnalyticsReport) {
1815    if !css.unresolved_class_references.is_empty() {
1816        let named: Vec<String> = css
1817            .unresolved_class_references
1818            .iter()
1819            .take(5)
1820            .map(|u| {
1821                format!(
1822                    "{} -> {} ({}:{})",
1823                    markdown_code_span(&u.class),
1824                    markdown_code_span(&u.suggestion),
1825                    u.path,
1826                    u.line
1827                )
1828            })
1829            .collect();
1830        let _ = writeln!(
1831            out,
1832            "- Likely class typos (candidates; verify, may be CSS-in-JS or external): {}",
1833            named.join(", "),
1834        );
1835    }
1836    if !css.unreferenced_css_classes.is_empty() {
1837        let named: Vec<String> = css
1838            .unreferenced_css_classes
1839            .iter()
1840            .take(5)
1841            .map(|u| {
1842                format!(
1843                    "{} ({}:{})",
1844                    markdown_code_span(&format!(".{}", u.class)),
1845                    u.path,
1846                    u.line
1847                )
1848            })
1849            .collect();
1850        let _ = writeln!(
1851            out,
1852            "- Unreferenced global classes (candidates; verify no email / server / CMS / Markdown applies them): {}",
1853            named.join(", "),
1854        );
1855    }
1856}
1857
1858fn write_css_font_candidate_details(out: &mut String, css: &fallow_output::CssAnalyticsReport) {
1859    if !css.unused_font_faces.is_empty() {
1860        let named: Vec<String> = css
1861            .unused_font_faces
1862            .iter()
1863            .take(5)
1864            .map(|u| format!("{} ({})", markdown_code_span(&u.family), u.path))
1865            .collect();
1866        let _ = writeln!(
1867            out,
1868            "- Unused @font-face (dead web-font; candidates, may be set from JS/inline): {}",
1869            named.join(", "),
1870        );
1871    }
1872    if !css.unused_theme_tokens.is_empty() {
1873        let named: Vec<String> = css
1874            .unused_theme_tokens
1875            .iter()
1876            .take(5)
1877            .map(|u| format!("{} ({}:{})", markdown_code_span(&u.token), u.path, u.line))
1878            .collect();
1879        let _ = writeln!(
1880            out,
1881            "- Unused @theme tokens (dead Tailwind v4 design tokens; candidates, may be consumed by a plugin or downstream repo): {}",
1882            named.join(", "),
1883        );
1884    }
1885}
1886
1887fn write_css_font_size_mix_details(out: &mut String, css: &fallow_output::CssAnalyticsReport) {
1888    if let Some(mix) = &css.font_size_unit_mix {
1889        let breakdown: Vec<String> = mix
1890            .notations
1891            .iter()
1892            .map(|n| format!("{} {}", n.count, n.notation))
1893            .collect();
1894        let _ = writeln!(
1895            out,
1896            "- Font sizes mix {} units (candidate, standardize unless intentional): {}",
1897            mix.notations.len(),
1898            breakdown.join(", "),
1899        );
1900    }
1901}
1902
1903fn write_coverage_intelligence_section(
1904    out: &mut String,
1905    report: &fallow_output::HealthReport,
1906    root: &Path,
1907) {
1908    let Some(ref intelligence) = report.coverage_intelligence else {
1909        return;
1910    };
1911    if !out.is_empty() && !out.ends_with("\n\n") {
1912        out.push('\n');
1913    }
1914    let _ = writeln!(
1915        out,
1916        "## Coverage Intelligence\n\n- Verdict: {}\n- Findings: {}\n- Ambiguous matches skipped: {}\n",
1917        intelligence.verdict,
1918        intelligence.summary.findings,
1919        intelligence.summary.skipped_ambiguous_matches,
1920    );
1921    if intelligence.findings.is_empty() {
1922        if intelligence.summary.skipped_ambiguous_matches > 0 {
1923            let match_phrase = if intelligence.summary.skipped_ambiguous_matches == 1 {
1924                "evidence match was"
1925            } else {
1926                "evidence matches were"
1927            };
1928            let _ = writeln!(
1929                out,
1930                "No actionable findings were emitted because {} ambiguous {match_phrase} skipped.\n",
1931                intelligence.summary.skipped_ambiguous_matches,
1932            );
1933        }
1934        return;
1935    }
1936    out.push_str("| ID | Path | Identity | Verdict | Recommendation | Confidence | Signals |\n");
1937    out.push_str("|:---|:-----|:---------|:--------|:---------------|:-----------|:--------|\n");
1938    for finding in &intelligence.findings {
1939        write_coverage_intelligence_row(out, finding, root);
1940    }
1941    out.push('\n');
1942}
1943
1944/// Write one coverage-intelligence finding row.
1945fn write_coverage_intelligence_row(
1946    out: &mut String,
1947    finding: &fallow_output::CoverageIntelligenceFinding,
1948    root: &Path,
1949) {
1950    let path = normalize_uri(&relative_path(&finding.path, root).display().to_string());
1951    let identity = finding.identity.as_deref().unwrap_or("-");
1952    let signals = finding
1953        .signals
1954        .iter()
1955        .map(ToString::to_string)
1956        .collect::<Vec<_>>()
1957        .join(", ");
1958    let _ = writeln!(
1959        out,
1960        "| {} | {}:{} | {} | {} | {} | {} | {} |",
1961        markdown_table_code_span(&finding.id),
1962        markdown_table_code_span(&path),
1963        finding.line,
1964        markdown_table_code_span(identity),
1965        finding.verdict,
1966        finding.recommendation,
1967        finding.confidence,
1968        signals,
1969    );
1970}
1971
1972fn write_runtime_coverage_section(
1973    out: &mut String,
1974    report: &fallow_output::HealthReport,
1975    root: &Path,
1976) {
1977    let Some(ref production) = report.runtime_coverage else {
1978        return;
1979    };
1980    if !out.is_empty() && !out.ends_with("\n\n") {
1981        out.push('\n');
1982    }
1983    runtime_summary::write_runtime_coverage_summary(out, production);
1984    write_runtime_coverage_findings(out, production, root);
1985    write_runtime_coverage_hot_paths(out, production, root);
1986}
1987
1988/// Write the runtime-coverage per-finding table.
1989fn write_runtime_coverage_findings(
1990    out: &mut String,
1991    production: &fallow_output::RuntimeCoverageReport,
1992    root: &Path,
1993) {
1994    if production.findings.is_empty() {
1995        return;
1996    }
1997    out.push_str("| ID | Path | Function | Verdict | Invocations | Confidence |\n");
1998    out.push_str("|:---|:-----|:---------|:--------|------------:|:-----------|\n");
1999    for finding in &production.findings {
2000        let invocations = finding
2001            .invocations
2002            .map_or_else(|| "-".to_owned(), |hits| hits.to_string());
2003        let path = normalize_uri(&relative_path(&finding.path, root).display().to_string());
2004        let _ = writeln!(
2005            out,
2006            "| {} | {}:{} | {} | {} | {} | {} |",
2007            markdown_table_code_span(&finding.id),
2008            markdown_table_code_span(&path),
2009            finding.line,
2010            markdown_table_code_span(&finding.function),
2011            finding.verdict,
2012            invocations,
2013            finding.confidence,
2014        );
2015    }
2016    out.push('\n');
2017}
2018
2019/// Write the runtime-coverage hot-paths table.
2020fn write_runtime_coverage_hot_paths(
2021    out: &mut String,
2022    production: &fallow_output::RuntimeCoverageReport,
2023    root: &Path,
2024) {
2025    if production.hot_paths.is_empty() {
2026        return;
2027    }
2028    out.push_str("| ID | Hot path | Function | Invocations | Percentile |\n");
2029    out.push_str("|:---|:---------|:---------|------------:|-----------:|\n");
2030    for entry in &production.hot_paths {
2031        let path = normalize_uri(&relative_path(&entry.path, root).display().to_string());
2032        let _ = writeln!(
2033            out,
2034            "| {} | {}:{} | {} | {} | {} |",
2035            markdown_table_code_span(&entry.id),
2036            markdown_table_code_span(&path),
2037            entry.line,
2038            markdown_table_code_span(&entry.function),
2039            entry.invocations,
2040            entry.percentile,
2041        );
2042    }
2043    out.push('\n');
2044}
2045
2046/// Write the trend comparison table to the output.
2047fn write_trend_section(out: &mut String, report: &fallow_output::HealthReport) {
2048    let Some(ref trend) = report.health_trend else {
2049        return;
2050    };
2051    let sha_str = trend
2052        .compared_to
2053        .git_sha
2054        .as_deref()
2055        .map_or(String::new(), |sha| format!(" ({sha})"));
2056    let _ = writeln!(
2057        out,
2058        "## Trend (vs {}{})\n",
2059        trend
2060            .compared_to
2061            .timestamp
2062            .get(..10)
2063            .unwrap_or(&trend.compared_to.timestamp),
2064        sha_str,
2065    );
2066    if let Some(current) = report.health_score.as_ref()
2067        && trend.compared_to.score.is_some()
2068        && !trend.metrics.iter().any(|metric| metric.name == "score")
2069        && let Some(note) = fallow_output::health_score_comparison_note(
2070            trend.compared_to.score_formula_version,
2071            Some(current.formula_version),
2072        )
2073    {
2074        let _ = writeln!(out, "*{note}*\n");
2075    }
2076    out.push_str("| Metric | Previous | Current | Delta | Direction |\n");
2077    out.push_str("|:-------|:---------|:--------|:------|:----------|\n");
2078    for m in &trend.metrics {
2079        write_trend_metric_row(out, m);
2080    }
2081    let md_sha = trend
2082        .compared_to
2083        .git_sha
2084        .as_deref()
2085        .map_or(String::new(), |sha| format!(" ({sha})"));
2086    let _ = writeln!(
2087        out,
2088        "\n*vs {}{} · {} {} available*\n",
2089        trend
2090            .compared_to
2091            .timestamp
2092            .get(..10)
2093            .unwrap_or(&trend.compared_to.timestamp),
2094        md_sha,
2095        trend.snapshots_loaded,
2096        if trend.snapshots_loaded == 1 {
2097            "snapshot"
2098        } else {
2099            "snapshots"
2100        },
2101    );
2102}
2103
2104/// Write one trend metric row with unit-aware value and delta formatting.
2105fn write_trend_metric_row(out: &mut String, m: &fallow_output::TrendMetric) {
2106    let fmt_val = |v: f64| -> String {
2107        if m.unit == "%" {
2108            format!("{v:.1}%")
2109        } else if (v - v.round()).abs() < 0.05 {
2110            format!("{v:.0}")
2111        } else {
2112            format!("{v:.1}")
2113        }
2114    };
2115    let prev = fmt_val(m.previous);
2116    let cur = fmt_val(m.current);
2117    let delta = if m.unit == "%" {
2118        format!("{:+.1}%", m.delta)
2119    } else if (m.delta - m.delta.round()).abs() < 0.05 {
2120        format!("{:+.0}", m.delta)
2121    } else {
2122        format!("{:+.1}", m.delta)
2123    };
2124    let _ = writeln!(
2125        out,
2126        "| {} | {} | {} | {} | {} {} |",
2127        m.label,
2128        prev,
2129        cur,
2130        delta,
2131        m.direction.arrow(),
2132        m.direction.label(),
2133    );
2134}
2135
2136/// Write the vital signs summary table to the output.
2137fn write_vital_signs_section(out: &mut String, report: &fallow_output::HealthReport) {
2138    let Some(ref vs) = report.vital_signs else {
2139        return;
2140    };
2141    out.push_str("## Vital Signs\n\n");
2142    out.push_str("| Metric | Value |\n");
2143    out.push_str("|:-------|------:|\n");
2144    if vs.total_loc > 0 {
2145        let _ = writeln!(out, "| Total LOC | {} |", vs.total_loc);
2146    }
2147    let _ = writeln!(out, "| Avg Cyclomatic | {:.1} |", vs.avg_cyclomatic);
2148    let _ = writeln!(out, "| P90 Cyclomatic | {} |", vs.p90_cyclomatic);
2149    if let Some(population) = &vs.cyclomatic_population {
2150        let _ = writeln!(
2151            out,
2152            "| Cyclomatic units | Functions: {}, module scopes: {}, templates: {} |",
2153            population.functions.count, population.modules.count, population.templates.count
2154        );
2155        if let Some(max) = population.modules.max {
2156            let _ = writeln!(
2157                out,
2158                "| Module-scope max cyclomatic (aggregate only) | {max} |"
2159            );
2160        }
2161    }
2162    if let Some(v) = vs.dead_file_pct {
2163        let _ = writeln!(out, "| Dead Files | {v:.1}% |");
2164    }
2165    if let Some(v) = vs.dead_export_pct {
2166        let _ = writeln!(out, "| Dead Exports | {v:.1}% |");
2167    }
2168    if let Some(v) = vs.maintainability_avg {
2169        let _ = writeln!(out, "| Maintainability (avg) | {v:.1} |");
2170    }
2171    if let Some(v) = vs.hotspot_count {
2172        let label = report.hotspot_summary.as_ref().map_or_else(
2173            || "Hotspots".to_string(),
2174            |summary| format!("Hotspots (since {})", summary.since),
2175        );
2176        let _ = writeln!(out, "| {label} | {v} |");
2177    }
2178    if let Some(v) = vs.circular_dep_count {
2179        let _ = writeln!(out, "| Circular Deps | {v} |");
2180    }
2181    if let Some(v) = vs.unused_dep_count {
2182        let _ = writeln!(out, "| Unused Deps | {v} |");
2183    }
2184    out.push('\n');
2185}
2186
2187/// Write the complexity findings table to the output.
2188fn write_findings_section(out: &mut String, report: &fallow_output::HealthReport, root: &Path) {
2189    if report.findings.is_empty() {
2190        return;
2191    }
2192
2193    let has_synthetic = report.findings.iter().any(|finding| {
2194        fallow_types::extract::is_synthetic_template_unit(&finding.name)
2195            || finding.name == "<component>"
2196            || finding.exceeded.is_file_lines()
2197    });
2198    write_findings_heading(out, report, has_synthetic);
2199    write_findings_table_header(out, has_synthetic);
2200
2201    for finding in &report.findings {
2202        write_findings_row(out, finding, root);
2203    }
2204
2205    let s = &report.summary;
2206    out.push_str("\n**!** marks the dimension that breached.\n");
2207    let _ = write!(
2208        out,
2209        "\n**{files}** files, **{funcs}** functions analyzed \
2210         (thresholds: cyclomatic > {cyc}, cognitive > {cog}, CRAP >= {crap:.1}{file_lines})\n",
2211        files = s.files_analyzed,
2212        funcs = s.functions_analyzed,
2213        cyc = s.max_cyclomatic_threshold,
2214        cog = s.max_cognitive_threshold,
2215        crap = s.max_crap_threshold,
2216        file_lines = s
2217            .max_file_lines_threshold
2218            .map(|max| format!(", file lines > {max}"))
2219            .unwrap_or_default(),
2220    );
2221}
2222
2223/// Write the heading line for the complexity findings section.
2224fn write_findings_heading(
2225    out: &mut String,
2226    report: &fallow_output::HealthReport,
2227    has_synthetic: bool,
2228) {
2229    let count = report.summary.functions_above_threshold;
2230    let shown = report.findings.len();
2231    let subject = if has_synthetic {
2232        "high complexity finding"
2233    } else {
2234        "high complexity function"
2235    };
2236    if shown < count {
2237        let _ = write!(
2238            out,
2239            "## Fallow: {count} {subject}{} ({shown} shown)\n\n",
2240            plural(count),
2241        );
2242    } else {
2243        let _ = write!(out, "## Fallow: {count} {subject}{}\n\n", plural(count));
2244    }
2245}
2246
2247/// Write the table header row for the complexity findings section.
2248fn write_findings_table_header(out: &mut String, has_synthetic: bool) {
2249    let name_header = if has_synthetic { "Entry" } else { "Function" };
2250    let _ = writeln!(
2251        out,
2252        "| File | {name_header} | Severity | Cyclomatic | Cognitive | CRAP | Lines |"
2253    );
2254    out.push_str("|:-----|:---------|:---------|:-----------|:----------|:-----|:------|\n");
2255}
2256
2257/// Write one complexity finding row, including threshold-breach markers.
2258fn write_findings_row(out: &mut String, finding: &fallow_output::HealthFinding, root: &Path) {
2259    let file_str = normalize_uri(&relative_path(&finding.path, root).display().to_string());
2260    let location = format!("{file_str}:{}", finding.line);
2261    // Markers come from `exceeded`, the engine's own discriminant, rather than
2262    // a second re-comparison that could drift from it (issue #2163).
2263    let cyc_marker = if finding.exceeded.includes_cyclomatic() {
2264        " **!**"
2265    } else {
2266        ""
2267    };
2268    let cog_marker = if finding.exceeded.includes_cognitive() {
2269        " **!**"
2270    } else {
2271        ""
2272    };
2273    let severity_label = match finding.severity {
2274        fallow_output::FindingSeverity::Critical => "critical",
2275        fallow_output::FindingSeverity::High => "high",
2276        fallow_output::FindingSeverity::Moderate => "moderate",
2277    };
2278    let crap_cell = match finding.crap {
2279        Some(crap) => {
2280            let marker = if finding.exceeded.includes_crap() {
2281                " **!**"
2282            } else {
2283                ""
2284            };
2285            format!("{crap:.1}{marker}")
2286        }
2287        None => "-".to_string(),
2288    };
2289    if let Some(max_file_lines) = finding.max_file_lines {
2290        // A file-length finding has no complexity values of its own.
2291        let _ = writeln!(
2292            out,
2293            "| {} | {} | {severity_label} | - | - | - | {lines} **!** (threshold: {max_file_lines}) |",
2294            markdown_table_code_span(&location),
2295            markdown_table_code_span(display_complexity_entry_name(&finding.name).as_ref()),
2296            lines = finding.line_count,
2297        );
2298        return;
2299    }
2300    let _ = writeln!(
2301        out,
2302        "| {} | {} | {severity_label} | {cyc}{cyc_marker} | {cog}{cog_marker} | {crap_cell} | {lines} |",
2303        markdown_table_code_span(&location),
2304        markdown_table_code_span(display_complexity_entry_name(&finding.name).as_ref()),
2305        cyc = finding.cyclomatic,
2306        cog = finding.cognitive,
2307        lines = finding.line_count,
2308    );
2309}
2310
2311fn write_threshold_overrides_section(
2312    out: &mut String,
2313    report: &fallow_output::HealthReport,
2314    root: &Path,
2315) {
2316    if report.threshold_overrides.is_empty() {
2317        return;
2318    }
2319    if !out.is_empty() && !out.ends_with("\n\n") {
2320        out.push('\n');
2321    }
2322    out.push_str("## Health Threshold Overrides\n\n");
2323    out.push_str("| Override | Dimension | Status | Target | Metrics | Outstanding |\n");
2324    out.push_str("|---------:|:----------|:-------|:-------|:--------|:------------|\n");
2325    for entry in &report.threshold_overrides {
2326        let status = match entry.status {
2327            fallow_output::ThresholdOverrideStatus::Active => "active",
2328            fallow_output::ThresholdOverrideStatus::Stale => "stale",
2329            fallow_output::ThresholdOverrideStatus::Insufficient => "insufficient",
2330            fallow_output::ThresholdOverrideStatus::NoMatch => "no_match",
2331        };
2332        let dimension = threshold_override_dimension_label(entry.dimension);
2333        let outstanding = if entry.outstanding.is_empty() {
2334            "-".to_string()
2335        } else {
2336            entry
2337                .outstanding
2338                .iter()
2339                .map(|value| threshold_override_dimension_label(*value))
2340                .collect::<Vec<_>>()
2341                .join(", ")
2342        };
2343        let target = entry.path.as_ref().map_or_else(
2344            || "<no matching file or function>".to_string(),
2345            |path| {
2346                entry.target_label(&normalize_uri(
2347                    &relative_path(path, root).display().to_string(),
2348                ))
2349            },
2350        );
2351        let metrics = entry.metrics.map_or_else(
2352            || "-".to_string(),
2353            |metrics| {
2354                let crap = metrics
2355                    .crap
2356                    .map_or(String::new(), |value| format!(", CRAP {value:.1}"));
2357                let line_count = metrics
2358                    .line_count
2359                    .map_or(String::new(), |value| format!(", {value} lines"));
2360                format!(
2361                    "cyclomatic {}, cognitive {}{}{}",
2362                    metrics.cyclomatic, metrics.cognitive, line_count, crap
2363                )
2364            },
2365        );
2366        // Mirror of the human renderer's copy: a crap-dimension row against a
2367        // template-family unit reports a dimension the unit is not scored on,
2368        // so the row must read as removable, not as an unqualified success.
2369        let metrics = if threshold_override_crap_not_applicable(entry) {
2370            format!("{metrics}; not scored on CRAP (this entry can be removed)")
2371        } else {
2372            metrics
2373        };
2374        let _ = writeln!(
2375            out,
2376            "| {} | {} | {} | {} | {} | {} |",
2377            entry.override_index,
2378            dimension,
2379            status,
2380            markdown_table_code_span(&target),
2381            metrics,
2382            outstanding
2383        );
2384    }
2385    out.push('\n');
2386}
2387
2388fn threshold_override_dimension_label(
2389    dimension: fallow_output::ThresholdOverrideDimension,
2390) -> &'static str {
2391    match dimension {
2392        fallow_output::ThresholdOverrideDimension::Complexity => "complexity",
2393        fallow_output::ThresholdOverrideDimension::Crap => "crap",
2394    }
2395}
2396
2397/// True for a crap-dimension override row recorded against a synthetic
2398/// template-family unit: measured complexity metrics present, CRAP value
2399/// absent because the unit is excluded from the CRAP dimension.
2400fn threshold_override_crap_not_applicable(entry: &fallow_output::ThresholdOverrideState) -> bool {
2401    matches!(
2402        entry.dimension,
2403        fallow_output::ThresholdOverrideDimension::Crap
2404    ) && entry.metrics.is_some_and(|metrics| metrics.crap.is_none())
2405        && entry
2406            .function
2407            .as_deref()
2408            .is_some_and(fallow_types::extract::is_synthetic_template_unit)
2409}
2410
2411/// Write the file health scores table to the output.
2412fn write_file_scores_section(out: &mut String, report: &fallow_output::HealthReport, root: &Path) {
2413    if report.file_scores.is_empty() {
2414        return;
2415    }
2416
2417    let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
2418
2419    out.push('\n');
2420    let count = report.file_scores.len();
2421    let _ = writeln!(
2422        out,
2423        "### File Health Scores ({count} file{})\n",
2424        plural(count),
2425    );
2426    out.push_str("| File | Maintainability | Fan-in | Fan-out | Dead Code | Density | Risk |\n");
2427    out.push_str("|:-----|:---------------|:-------|:--------|:----------|:--------|:-----|\n");
2428
2429    for score in &report.file_scores {
2430        let file_str = rel(&score.path);
2431        let signal = fallow_engine::health::scoring::file_score_crap_signal(
2432            score,
2433            report.summary.max_crap_threshold,
2434        );
2435        let suppression = if score.crap_suppressed > 0 {
2436            " (complexity suppression)"
2437        } else {
2438            ""
2439        };
2440        let _ = writeln!(
2441            out,
2442            "| {} | {mi:.1} | {fi} | {fan_out} | {dead:.0}% | {density:.2} | {crap:.1}{suppression} |",
2443            markdown_table_code_span(&file_str),
2444            mi = score.maintainability_index,
2445            fi = score.fan_in,
2446            fan_out = score.fan_out,
2447            dead = score.dead_code_ratio * 100.0,
2448            density = score.complexity_density,
2449            crap = signal.maximum,
2450        );
2451    }
2452
2453    if let Some(avg) = report.summary.average_maintainability {
2454        let _ = write!(out, "\n**Average maintainability index:** {avg:.1}/100\n");
2455    }
2456}
2457
2458fn write_coverage_gaps_section(
2459    out: &mut String,
2460    report: &fallow_output::HealthReport,
2461    root: &Path,
2462) {
2463    let Some(ref gaps) = report.coverage_gaps else {
2464        return;
2465    };
2466
2467    out.push('\n');
2468    let _ = writeln!(out, "### Coverage Gaps\n");
2469    let _ = writeln!(
2470        out,
2471        "*{} untested files · {} untested exports · {:.1}% file coverage*\n",
2472        gaps.summary.untested_files, gaps.summary.untested_exports, gaps.summary.file_coverage_pct,
2473    );
2474
2475    if gaps.files.is_empty() && gaps.exports.is_empty() {
2476        out.push_str("_No coverage gaps found in scope._\n");
2477        return;
2478    }
2479
2480    if !gaps.files.is_empty() {
2481        out.push_str("#### Files\n");
2482        for item in &gaps.files {
2483            let file_str =
2484                normalize_uri(&relative_path(&item.file.path, root).display().to_string());
2485            let _ = writeln!(
2486                out,
2487                "- {} ({count} value export{})",
2488                markdown_code_span(&file_str),
2489                if item.file.value_export_count == 1 {
2490                    ""
2491                } else {
2492                    "s"
2493                },
2494                count = item.file.value_export_count,
2495            );
2496        }
2497        out.push('\n');
2498    }
2499
2500    if !gaps.exports.is_empty() {
2501        out.push_str("#### Exports\n");
2502        for item in &gaps.exports {
2503            let file_str =
2504                normalize_uri(&relative_path(&item.export.path, root).display().to_string());
2505            let _ = writeln!(
2506                out,
2507                "- {}:{} {}",
2508                markdown_code_span(&file_str),
2509                item.export.line,
2510                markdown_code_span(&item.export.export_name)
2511            );
2512        }
2513    }
2514}
2515
2516/// Write the hotspots table to the output.
2517/// Render the four ownership table cells (bus, top contributor, declared
2518/// owner, notes) for the markdown hotspots table. Cells fall back to an
2519/// en-dash (U+2013) when ownership data is missing for an entry.
2520fn ownership_md_cells(
2521    ownership: Option<&fallow_output::OwnershipMetrics>,
2522) -> (String, String, String, String) {
2523    let Some(o) = ownership else {
2524        let dash = "\u{2013}".to_string();
2525        return (dash.clone(), dash.clone(), dash.clone(), dash);
2526    };
2527    let bus = o.bus_factor.to_string();
2528    let top = format!(
2529        "{} ({:.0}%)",
2530        markdown_table_code_span(&o.top_contributor.identifier),
2531        o.top_contributor.share * 100.0,
2532    );
2533    let owner = o
2534        .declared_owner
2535        .as_deref()
2536        .map_or_else(|| "\u{2013}".to_string(), str::to_string);
2537    let mut notes: Vec<&str> = Vec::new();
2538    if o.unowned == Some(true) {
2539        notes.push("**unowned**");
2540    }
2541    if o.ownership_state == fallow_output::OwnershipState::DeclaredInactive {
2542        notes.push("declared owner inactive");
2543    }
2544    if o.drift {
2545        notes.push("drift");
2546    }
2547    let notes_str = if notes.is_empty() {
2548        "\u{2013}".to_string()
2549    } else {
2550        notes.join(", ")
2551    };
2552    (bus, top, owner, notes_str)
2553}
2554
2555fn write_hotspots_section(out: &mut String, report: &fallow_output::HealthReport, root: &Path) {
2556    if report.hotspots.is_empty() {
2557        return;
2558    }
2559
2560    out.push('\n');
2561    let count = report.hotspots.len();
2562    let header = report.hotspot_summary.as_ref().map_or_else(
2563        || format!("### Hotspots ({count} file{})\n", plural(count)),
2564        |summary| {
2565            format!(
2566                "### Hotspots ({count} file{}, since {})\n",
2567                plural(count),
2568                summary.since,
2569            )
2570        },
2571    );
2572    let _ = writeln!(out, "{header}");
2573    let any_ownership = report.hotspots.iter().any(|e| e.ownership.is_some());
2574    write_hotspots_table_header(out, any_ownership);
2575
2576    for entry in &report.hotspots {
2577        write_hotspots_row(out, entry, any_ownership, root);
2578    }
2579
2580    if let Some(ref summary) = report.hotspot_summary
2581        && summary.files_excluded > 0
2582    {
2583        let _ = write!(
2584            out,
2585            "\n*{} file{} excluded (< {} commits)*\n",
2586            summary.files_excluded,
2587            plural(summary.files_excluded),
2588            summary.min_commits,
2589        );
2590    }
2591}
2592
2593/// Write the hidden change-coupling pairs. Silent when the section is absent
2594/// or lists no pair.
2595fn write_change_coupling_section(
2596    out: &mut String,
2597    report: &fallow_output::HealthReport,
2598    root: &Path,
2599) {
2600    let Some(coupling) = report.change_coupling.as_ref() else {
2601        return;
2602    };
2603    if coupling.pairs.is_empty() {
2604        return;
2605    }
2606    let count = coupling.total_pairs;
2607    let _ = write!(
2608        out,
2609        "\n### Hidden Change Coupling ({count} pair{}, since {})\n\n",
2610        plural(count),
2611        coupling.since,
2612    );
2613    out.push_str("| File A | File B | Degree | Shared | Commits A | Commits B | Strong |\n");
2614    out.push_str("|:-------|:-------|:-------|:-------|:----------|:----------|:-------|\n");
2615    for pair in &coupling.pairs {
2616        let path_a = normalize_uri(&relative_path(&pair.path_a, root).display().to_string());
2617        let path_b = normalize_uri(&relative_path(&pair.path_b, root).display().to_string());
2618        let _ = writeln!(
2619            out,
2620            "| {} | {} | {:.0}% | {} | {} | {} | {} |",
2621            markdown_table_code_span(&path_a),
2622            markdown_table_code_span(&path_b),
2623            pair.degree * 100.0,
2624            pair.shared_revisions,
2625            pair.revisions_a,
2626            pair.revisions_b,
2627            if pair.strong { "**strong**" } else { "" },
2628        );
2629    }
2630    let hidden = count.saturating_sub(coupling.pairs.len());
2631    if hidden > 0 {
2632        let _ = writeln!(out, "\n*{hidden} more pair{} not shown*", plural(hidden));
2633    }
2634    out.push_str(
2635        "\n*Files that change together in the commit history with no import between them.*\n",
2636    );
2637}
2638
2639/// Write the hotspots table header, widening with ownership columns when present.
2640fn write_hotspots_table_header(out: &mut String, any_ownership: bool) {
2641    if any_ownership {
2642        out.push_str(
2643            "| File | Score | Commits | Churn | Density | Fan-in | Trend | Bus | Top | Owner | Notes |\n"
2644        );
2645        out.push_str(
2646            "|:-----|:------|:--------|:------|:--------|:-------|:------|:----|:----|:------|:------|\n"
2647        );
2648    } else {
2649        out.push_str("| File | Score | Commits | Churn | Density | Fan-in | Trend |\n");
2650        out.push_str("|:-----|:------|:--------|:------|:--------|:-------|:------|\n");
2651    }
2652}
2653
2654/// Write one hotspot row, including ownership cells when the table is widened.
2655fn write_hotspots_row(
2656    out: &mut String,
2657    entry: &fallow_output::HotspotFinding,
2658    any_ownership: bool,
2659    root: &Path,
2660) {
2661    let file_str = normalize_uri(&relative_path(&entry.path, root).display().to_string());
2662    let file_span = markdown_table_code_span(&file_str);
2663    if any_ownership {
2664        let (bus, top, owner, notes) = ownership_md_cells(entry.ownership.as_ref());
2665        let _ = writeln!(
2666            out,
2667            "| {file_span} | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} | {bus} | {top} | {owner} | {notes} |",
2668            score = entry.score,
2669            commits = entry.commits,
2670            churn = entry.lines_added + entry.lines_deleted,
2671            density = entry.complexity_density,
2672            fi = entry.fan_in,
2673            trend = entry.trend,
2674        );
2675    } else {
2676        let _ = writeln!(
2677            out,
2678            "| {file_span} | {score:.1} | {commits} | {churn} | {density:.2} | {fi} | {trend} |",
2679            score = entry.score,
2680            commits = entry.commits,
2681            churn = entry.lines_added + entry.lines_deleted,
2682            density = entry.complexity_density,
2683            fi = entry.fan_in,
2684            trend = entry.trend,
2685        );
2686    }
2687}
2688
2689/// Write the refactoring targets table to the output.
2690fn write_targets_section(out: &mut String, report: &fallow_output::HealthReport, root: &Path) {
2691    if report.targets.is_empty() {
2692        return;
2693    }
2694    let _ = write!(
2695        out,
2696        "\n### Refactoring Targets ({})\n\n",
2697        report.targets.len()
2698    );
2699    out.push_str("| Efficiency | Category | Effort / Confidence | File | Recommendation |\n");
2700    out.push_str("|:-----------|:---------|:--------------------|:-----|:---------------|\n");
2701    for target in &report.targets {
2702        let file_str = normalize_uri(&relative_path(&target.path, root).display().to_string());
2703        let category = target.category.label();
2704        let effort = target.effort.label();
2705        let confidence = target.confidence.label();
2706        let _ = writeln!(
2707            out,
2708            "| {:.1} | {category} | {effort} / {confidence} | {} | {} |",
2709            target.efficiency,
2710            markdown_table_code_span(&file_str),
2711            markdown_table_text(&target.recommendation),
2712        );
2713    }
2714}
2715
2716/// Write the metric legend collapsible section to the output.
2717fn write_metric_legend(out: &mut String, report: &fallow_output::HealthReport) {
2718    let has_scores = !report.file_scores.is_empty();
2719    let has_coverage = report.coverage_gaps.is_some();
2720    let has_hotspots = !report.hotspots.is_empty();
2721    let has_targets = !report.targets.is_empty();
2722    if !has_scores && !has_coverage && !has_hotspots && !has_targets {
2723        return;
2724    }
2725    out.push_str("\n---\n\n<details><summary>Metric definitions</summary>\n\n");
2726    if has_scores {
2727        out.push_str("- **MI**: Maintainability Index (0\u{2013}100, higher is better)\n");
2728        out.push_str("- **Order**: risk-aware triage order using the larger of low-MI concern and CRAP risk\n");
2729        out.push_str("- **Fan-in**: files that import this file (blast radius)\n");
2730        out.push_str("- **Fan-out**: files this file imports (coupling)\n");
2731        out.push_str("- **Dead Code**: % of value exports with zero references\n");
2732        out.push_str("- **Density**: cyclomatic complexity / lines of code\n");
2733        out.push_str(
2734            "- **Risk**: max CRAP score for the file; low <15, moderate 15-30, high >=30\n",
2735        );
2736    }
2737    if has_coverage {
2738        out.push_str(
2739            "- **File coverage**: runtime files also reachable from a discovered test root\n",
2740        );
2741        out.push_str("- **Untested export**: export with no reference chain from any test-reachable module\n");
2742    }
2743    if has_hotspots {
2744        out.push_str("- **Score**: churn \u{00d7} complexity (0\u{2013}100, higher = riskier)\n");
2745        out.push_str("- **Commits**: commits in the analysis window\n");
2746        out.push_str("- **Churn**: total lines added + deleted\n");
2747        out.push_str("- **Trend**: accelerating / stable / cooling\n");
2748    }
2749    if has_targets {
2750        out.push_str(
2751            "- **Efficiency**: priority / effort (higher = better quick-win value, default sort)\n",
2752        );
2753        out.push_str("- **Category**: recommendation type (churn+complexity, high impact, dead code, complexity, coupling, circular dep)\n");
2754        out.push_str("- **Effort**: estimated effort (low / medium / high) based on file size, function count, and fan-in\n");
2755        out.push_str("- **Confidence**: recommendation reliability (high = deterministic analysis, medium = heuristic, low = git-dependent)\n");
2756    }
2757    out.push_str(
2758        "\n[Full metric reference](https://fallow.tools/docs/explanations/health/)\n\n</details>\n",
2759    );
2760}
2761
2762/// Build a paste-into-PR markdown rendering of the existing walkthrough guide.
2763///
2764/// Mirrors the human terminal tour: a Focus line, Stage 1 (affects code outside the
2765/// PR) and Stage 2 (self-contained) sections partitioned by `concern_lens`, with synthesized
2766/// badges as inline code spans, then a collapsible Cleared panel. The JSON guide
2767/// path is untouched; this is the only NEW walkthrough markdown surface. No ANSI.
2768///
2769/// `viewed` is the root-relative file list the local ledger marked viewed (the
2770/// `--mark-viewed` state). Viewed files collapse out of their stage and into the
2771/// Cleared panel, and the Cleared summary reports the viewed count, so the
2772/// markdown surface honors `--mark-viewed` the same way the human surface does
2773/// instead of silently ignoring it.
2774#[must_use]
2775pub fn build_walkthrough_markdown(
2776    guide: &fallow_output::StandardWalkthroughGuide,
2777    root: &Path,
2778    viewed: &[String],
2779) -> String {
2780    let mut out = String::new();
2781    out.push_str("## Fallow Review: Walkthrough\n\n");
2782    push_walkthrough_focus(&mut out, guide, viewed);
2783
2784    let unstaged = fallow_output::decisions_outside_units(guide);
2785    if guide.direction.order.is_empty() && unstaged.is_empty() {
2786        out.push_str("_No reviewable units in this change (orientation only)._\n");
2787        return out;
2788    }
2789
2790    let (stage1, stage2) = partition_walkthrough_stages(guide, viewed);
2791    push_walkthrough_stage(
2792        &mut out,
2793        "Stage 1 \u{00b7} Affects code outside this PR",
2794        &stage1,
2795        guide,
2796        root,
2797    );
2798    push_walkthrough_stage(
2799        &mut out,
2800        "Stage 2 \u{00b7} Self-contained",
2801        &stage2,
2802        guide,
2803        root,
2804    );
2805    push_walkthrough_unstaged_decisions(&mut out, &unstaged, root);
2806    push_walkthrough_cleared(&mut out, guide, root, viewed);
2807    out
2808}
2809
2810/// Decisions whose anchor is not a staged unit (a manifest), rendered as their
2811/// own section so a dependency-only change never reads as "nothing to review".
2812fn push_walkthrough_unstaged_decisions(
2813    out: &mut String,
2814    decisions: &[&fallow_output::Decision],
2815    root: &Path,
2816) {
2817    if decisions.is_empty() {
2818        return;
2819    }
2820    let _ = writeln!(
2821        out,
2822        "### Decisions outside the staged files ({})\n",
2823        decisions.len()
2824    );
2825    for decision in decisions {
2826        let token = match decision.category {
2827            fallow_output::DecisionCategory::CouplingBoundary => "COUPLING",
2828            fallow_output::DecisionCategory::PublicApiContract => "PUBLIC-API",
2829            fallow_output::DecisionCategory::Dependency => "DEPENDENCY",
2830        };
2831        let _ = writeln!(
2832            out,
2833            "- {} `{token}`  \n  {}",
2834            markdown_code_span(&markdown_relative_path_str(&decision.anchor_file, root)),
2835            fallow_output::clean_decision_fact(
2836                &decision.question,
2837                &decision.anchor_file,
2838                fallow_output::MAX_CONTRACT_MEMBERS
2839            )
2840        );
2841    }
2842    out.push('\n');
2843}
2844
2845/// Push the `**Focus:**` line built from the guide's triage, with the reconciled
2846/// file accounting (staged + cleared + excluded) so the count matches the real
2847/// changed set and non-source files are surfaced, not silently dropped.
2848fn push_walkthrough_focus(
2849    out: &mut String,
2850    guide: &fallow_output::StandardWalkthroughGuide,
2851    viewed: &[String],
2852) {
2853    let triage = &guide.digest.triage;
2854    let acc = fallow_output::WalkthroughAccounting::compute(guide, viewed);
2855    let total = acc.header_total();
2856    let _ = write!(
2857        out,
2858        "**Focus:** {} risk \u{00b7} {} \u{00b7} {} file{}",
2859        walkthrough_risk_label(triage.risk_class),
2860        walkthrough_effort_label(triage.review_effort),
2861        total,
2862        plural(total),
2863    );
2864    let mut parts = vec![format!("{} in stages", acc.staged)];
2865    if acc.cleared > 0 {
2866        parts.push(format!("{} cleared", acc.cleared));
2867    }
2868    if acc.excluded > 0 {
2869        parts.push(format!("{} non-source not reviewed", acc.excluded));
2870    }
2871    if acc.cleared > 0 || acc.excluded > 0 {
2872        let _ = write!(out, " ({})", parts.join(" \u{00b7} "));
2873    }
2874    out.push_str("\n\n");
2875}
2876
2877/// Partition the guide's VISIBLE stage units (de-prioritized AND viewed files
2878/// collapsed out into Cleared) into (contract-break, orientation), each in
2879/// `direction.order`.
2880fn partition_walkthrough_stages<'a>(
2881    guide: &'a fallow_output::StandardWalkthroughGuide,
2882    viewed: &[String],
2883) -> (
2884    Vec<&'a fallow_output::DirectionUnit>,
2885    Vec<&'a fallow_output::DirectionUnit>,
2886) {
2887    let mut load_bearing = Vec::new();
2888    let mut mechanical = Vec::new();
2889    for unit in fallow_output::visible_stage_units(guide, viewed) {
2890        if unit.concern_lens == "contract-break" {
2891            load_bearing.push(unit);
2892        } else {
2893            mechanical.push(unit);
2894        }
2895    }
2896    (load_bearing, mechanical)
2897}
2898
2899/// Push one markdown stage section. Skipped when empty.
2900fn push_walkthrough_stage(
2901    out: &mut String,
2902    title: &str,
2903    units: &[&fallow_output::DirectionUnit],
2904    guide: &fallow_output::StandardWalkthroughGuide,
2905    root: &Path,
2906) {
2907    if units.is_empty() {
2908        return;
2909    }
2910    let _ = write!(out, "### {title}\n\n");
2911    for unit in units {
2912        let rel = markdown_relative_path_str(&unit.file, root);
2913        let badges = walkthrough_markdown_badges(unit, guide);
2914        let suffix = if badges.is_empty() {
2915            String::new()
2916        } else {
2917            format!("  {}", badges.join(" "))
2918        };
2919        // The raw composite "(score N)" is omitted: it is an opaque attention total
2920        // that did not explain the within-stage order. `walkthrough_fact` is the
2921        // concrete "why" each row carries (out-of-diff count, importer count), which
2922        // is also the number the within-stage order follows, so a row's position is
2923        // explained by the count it shows.
2924        let _ = writeln!(
2925            out,
2926            "- {}: {}{suffix}",
2927            markdown_code_span(&rel),
2928            walkthrough_fact(unit, guide)
2929        );
2930    }
2931    out.push('\n');
2932}
2933
2934/// Synthesize the inline-code-span badges for a file in markdown (paste-safe).
2935fn walkthrough_markdown_badges(
2936    unit: &fallow_output::DirectionUnit,
2937    guide: &fallow_output::StandardWalkthroughGuide,
2938) -> Vec<String> {
2939    let mut badges: Vec<String> = Vec::new();
2940    for decision in &guide.digest.decisions.decisions {
2941        if decision.anchor_file != unit.file {
2942            continue;
2943        }
2944        let token = match decision.category {
2945            fallow_output::DecisionCategory::CouplingBoundary => "COUPLING",
2946            fallow_output::DecisionCategory::PublicApiContract => "PUBLIC-API",
2947            fallow_output::DecisionCategory::Dependency => "DEPENDENCY",
2948        };
2949        let chip = format!("`{token}`");
2950        if !badges.contains(&chip) {
2951            badges.push(chip);
2952        }
2953    }
2954    if walkthrough_introduced(&unit.file, guide) {
2955        badges.push("`INTRODUCED`".to_string());
2956    }
2957    if unit.concern_lens == "contract-break" {
2958        badges.push("`OUT-OF-DIFF`".to_string());
2959    }
2960    if let Some(owner) = unit.expert.first() {
2961        badges.push(markdown_code_span(&format!("OWNER:{owner}")));
2962    }
2963    if walkthrough_bus_factor(&unit.file, guide) {
2964        badges.push("`BUS-FACTOR-1`".to_string());
2965    }
2966    if walkthrough_weakened(&unit.file, guide) {
2967        badges.push("`WEAKENED`".to_string());
2968    }
2969    if unit.test_adjacency == Some(fallow_output::TestAdjacency::None) {
2970        badges.push("`NO-DIRECT-TEST`".to_string());
2971    }
2972    badges
2973}
2974
2975/// The one-line "why" for a markdown file row. The cascade is decision question >
2976/// out-of-diff count > focus reason > orientation only. The concrete count it
2977/// carries (consumers, importers) is the same number the within-stage order
2978/// follows, so the order mirrors the human surface (the count it shows).
2979fn walkthrough_fact(
2980    unit: &fallow_output::DirectionUnit,
2981    guide: &fallow_output::StandardWalkthroughGuide,
2982) -> String {
2983    if let Some(decision) = guide
2984        .digest
2985        .decisions
2986        .decisions
2987        .iter()
2988        .find(|d| d.anchor_file == unit.file)
2989    {
2990        // Strip the redundant leading path (the bullet already shows it) and cap
2991        // the contract-member list, PRESERVING the trailing guidance question. The
2992        // result is plain prose with no backticks, so it never emits a
2993        // backslash-backtick sequence and never re-prints the path.
2994        return fallow_output::clean_decision_fact(
2995            &decision.question,
2996            &unit.file,
2997            fallow_output::MAX_CONTRACT_MEMBERS,
2998        );
2999    }
3000    if !unit.out_of_diff.is_empty() {
3001        return format!(
3002            "{} out-of-diff consumer{}",
3003            unit.out_of_diff.len(),
3004            plural(unit.out_of_diff.len())
3005        );
3006    }
3007    if let Some(fu) = guide
3008        .digest
3009        .focus
3010        .review_here
3011        .iter()
3012        .chain(guide.digest.focus.deprioritized.iter())
3013        .find(|fu| fu.file == unit.file)
3014    {
3015        return escape_markdown_prose(&fu.reason);
3016    }
3017    "orientation only".to_string()
3018}
3019
3020fn walkthrough_introduced(file: &str, guide: &fallow_output::StandardWalkthroughGuide) -> bool {
3021    let deltas = &guide.digest.deltas;
3022    deltas
3023        .boundary_introduced
3024        .iter()
3025        .chain(deltas.cycle_introduced.iter())
3026        .chain(deltas.public_api_added.iter())
3027        .any(|entry| entry.contains(file))
3028}
3029
3030fn walkthrough_bus_factor(file: &str, guide: &fallow_output::StandardWalkthroughGuide) -> bool {
3031    guide
3032        .digest
3033        .routing
3034        .units
3035        .iter()
3036        .any(|u| u.file == file && u.bus_factor_one)
3037}
3038
3039fn walkthrough_weakened(file: &str, guide: &fallow_output::StandardWalkthroughGuide) -> bool {
3040    guide.digest.weakening.iter().any(|w| w.file == file)
3041}
3042
3043/// Push the collapsible Cleared `<details>` panel: de-prioritized files plus any
3044/// `--mark-viewed` files (collapsed out of their stage), with both counts in the
3045/// summary so the panel reports the same `N de-prioritized, M viewed` split the
3046/// human surface does.
3047fn push_walkthrough_cleared(
3048    out: &mut String,
3049    guide: &fallow_output::StandardWalkthroughGuide,
3050    root: &Path,
3051    viewed: &[String],
3052) {
3053    let deprioritized = &guide.digest.focus.deprioritized;
3054    // Viewed files NOT already de-prioritized, so a viewed-and-de-prioritized file
3055    // lands in exactly one bucket (no double count), mirroring the human surface.
3056    let viewed_only: Vec<&String> = viewed
3057        .iter()
3058        .filter(|file| !deprioritized.iter().any(|u| &u.file == *file))
3059        .collect();
3060    if deprioritized.is_empty() && viewed_only.is_empty() {
3061        return;
3062    }
3063    let _ = write!(
3064        out,
3065        "<details><summary>Cleared ({} de-prioritized, {} viewed)</summary>\n\n",
3066        deprioritized.len(),
3067        viewed_only.len(),
3068    );
3069    for unit in deprioritized {
3070        let _ = writeln!(
3071            out,
3072            "- {}: {}",
3073            markdown_code_span(&markdown_relative_path_str(&unit.file, root)),
3074            escape_markdown_prose(&unit.reason),
3075        );
3076    }
3077    for file in viewed_only {
3078        let _ = writeln!(
3079            out,
3080            "- {}: \u{2713} viewed",
3081            markdown_code_span(&markdown_relative_path_str(file, root)),
3082        );
3083    }
3084    out.push_str("\n</details>\n");
3085}
3086
3087/// A file-path string already relative to `root` (the guide stores root-relative
3088/// paths), normalized for a markdown code span.
3089fn markdown_relative_path_str(file: &str, root: &Path) -> String {
3090    let path = Path::new(file);
3091    if path.is_absolute() {
3092        return markdown_relative_path(path, root);
3093    }
3094    normalize_uri(file)
3095}
3096
3097fn walkthrough_risk_label(risk: fallow_output::RiskClass) -> &'static str {
3098    match risk {
3099        fallow_output::RiskClass::Low => "low",
3100        fallow_output::RiskClass::Medium => "medium",
3101        fallow_output::RiskClass::High => "high",
3102    }
3103}
3104
3105fn walkthrough_effort_label(effort: fallow_output::ReviewEffort) -> &'static str {
3106    match effort {
3107        fallow_output::ReviewEffort::Glance => "glance",
3108        fallow_output::ReviewEffort::Review => "review",
3109        fallow_output::ReviewEffort::DeepDive => "deep-dive",
3110    }
3111}
3112
3113#[cfg(test)]
3114#[path = "markdown_output_duplication_markdown_tests.rs"]
3115mod duplication_markdown_tests;
3116
3117#[cfg(test)]
3118#[path = "markdown_output_health_tests.rs"]
3119mod health_markdown_tests;
3120
3121#[cfg(test)]
3122#[path = "markdown_output_caveat_tests.rs"]
3123mod caveat_markdown_tests;
3124
3125#[cfg(test)]
3126#[path = "markdown_code_span_tests.rs"]
3127mod markdown_code_span_tests;
3128
3129#[cfg(test)]
3130mod walkthrough_markdown_tests {
3131    use super::build_walkthrough_markdown;
3132    use fallow_output::{
3133        AgentSchema, Decision, DecisionCategory, DecisionSurface, DiffTriage, DirectionUnit,
3134        FocusLabel, FocusMap, FocusScore, FocusUnit, GraphFacts, INJECTION_NOTE,
3135        ImpactClosureFacts, PartitionFacts, ReviewBriefSchemaVersion, ReviewDeltas,
3136        ReviewDirection, ReviewEffort, RiskClass, RoutingFacts, StandardReviewBriefOutput,
3137        StandardWalkthroughGuide,
3138    };
3139    use std::path::Path;
3140
3141    fn guide_with_question(file: &str, question: &str) -> StandardWalkthroughGuide {
3142        let unit = DirectionUnit {
3143            file: file.to_string(),
3144            concern_lens: "contract-break".to_string(),
3145            scoring_budget: 3,
3146            out_of_diff: vec!["src/consumer.ts".to_string()],
3147            expert: Vec::new(),
3148            test_adjacency: None,
3149        };
3150        // The direction unit comes FROM the focus map's review_here in reality, so
3151        // mirror that here: review_here has the one source unit and triage.files
3152        // matches it, keeping the excluded bucket at 0 for this synthetic guide.
3153        let review_unit = FocusUnit {
3154            file: file.to_string(),
3155            score: FocusScore::default(),
3156            label: FocusLabel::ReviewHere,
3157            reason: "reason".to_string(),
3158            confidence: Vec::new(),
3159        };
3160        let decision = Decision {
3161            signal_id: "sig:1".to_string(),
3162            category: DecisionCategory::CouplingBoundary,
3163            question: question.to_string(),
3164            anchor_file: file.to_string(),
3165            anchor_line: 1,
3166            signal_key: "k".to_string(),
3167            previous_signal_id: None,
3168            blast: 1,
3169            consequence: 2,
3170            expert: Vec::new(),
3171            bus_factor_one: false,
3172            internal_consumer_count: 0,
3173            tradeoff: String::new(),
3174        };
3175        let digest = StandardReviewBriefOutput {
3176            branching: None,
3177            test_reach: None,
3178            schema_version: ReviewBriefSchemaVersion::default(),
3179            version: "test".to_string(),
3180            command: "audit-brief".to_string(),
3181            triage: DiffTriage {
3182                files: 1,
3183                hunks: None,
3184                net_lines: None,
3185                risk_class: RiskClass::Low,
3186                review_effort: ReviewEffort::Glance,
3187            },
3188            graph_facts: GraphFacts {
3189                exports_added: 0,
3190                api_width_delta: 0,
3191                boundaries_touched: Vec::new(),
3192            },
3193            partition: PartitionFacts::default(),
3194            impact_closure: ImpactClosureFacts::default(),
3195            focus: FocusMap {
3196                review_here: vec![review_unit],
3197                deprioritized: Vec::new(),
3198            },
3199            deltas: ReviewDeltas::default(),
3200            weakening: Vec::new(),
3201            routing: RoutingFacts::default(),
3202            ownership: None,
3203            decisions: DecisionSurface {
3204                decisions: vec![decision],
3205                truncated: None,
3206                emitted_signal_ids: Vec::new(),
3207            },
3208        };
3209        StandardWalkthroughGuide {
3210            schema_version: ReviewBriefSchemaVersion::default(),
3211            version: "test".to_string(),
3212            command: "review-walkthrough-guide".to_string(),
3213            graph_snapshot_hash: "graph:abc".to_string(),
3214            digest,
3215            direction: ReviewDirection {
3216                order: vec![file.to_string()],
3217                units: vec![unit],
3218            },
3219            change_anchors: Vec::new(),
3220            agent_schema: AgentSchema {
3221                judgment_shape: "",
3222                echo_field: "graph_snapshot_hash",
3223                anchoring_rule: "",
3224                action_vocabulary: &[],
3225                concern_vocabulary: &[],
3226            },
3227            injection_note: INJECTION_NOTE,
3228        }
3229    }
3230
3231    #[test]
3232    fn renders_header_stage_and_code_span_badges() {
3233        let guide = guide_with_question("src/page.ts", "Couple ui to db?");
3234        let md = build_walkthrough_markdown(&guide, Path::new("/project"), &[]);
3235        assert!(md.starts_with("## Fallow Review"), "got: {md}");
3236        assert!(md.contains("### Stage 1"), "got: {md}");
3237        assert!(md.contains("`COUPLING`"), "badges are code spans: {md}");
3238        assert!(md.contains("`OUT-OF-DIFF`"), "got: {md}");
3239        assert!(!md.contains('\u{1b}'), "no ANSI in markdown");
3240        // The file->description separator is a colon, not the house-style-banned
3241        // em-dash that the list items used to lead with.
3242        assert!(
3243            md.contains("- `src/page.ts`: "),
3244            "list items use a colon separator: {md}"
3245        );
3246        assert!(
3247            !md.contains("- `src/page.ts` \u{2014} "),
3248            "no em-dash file separator: {md}"
3249        );
3250    }
3251
3252    #[test]
3253    fn ungrouped_walkthrough_paths_use_safe_code_spans() {
3254        let guide = guide_with_question("src/one`# injected.md", "Review this path?");
3255
3256        let md = build_walkthrough_markdown(&guide, Path::new("/project"), &[]);
3257
3258        assert!(
3259            md.contains("- ``src/one`# injected.md``: "),
3260            "path remains inside one code span: {md}"
3261        );
3262        assert!(!md.contains("\\`"));
3263    }
3264
3265    // The markdown surface honors `--mark-viewed`: a viewed file collapses out of
3266    // its stage into the Cleared panel, and the summary reports the viewed count
3267    // (the same on-disk state the human surface reads), no longer ignored.
3268    #[test]
3269    fn viewed_file_collapses_into_cleared_in_markdown() {
3270        let guide = guide_with_question("src/page.ts", "Couple ui to db?");
3271        let viewed = vec!["src/page.ts".to_string()];
3272        let md = build_walkthrough_markdown(&guide, Path::new("/project"), &viewed);
3273        // The viewed file is no longer rendered in a stage section.
3274        assert!(
3275            !md.contains("### Stage 1"),
3276            "viewed file left its stage: {md}"
3277        );
3278        // The Cleared panel reports the viewed count and lists the viewed file.
3279        assert!(
3280            md.contains("Cleared (0 de-prioritized, 1 viewed)"),
3281            "cleared reports viewed count: {md}"
3282        );
3283        assert!(
3284            md.contains("- `src/page.ts`: \u{2713} viewed"),
3285            "viewed file listed under cleared: {md}"
3286        );
3287    }
3288
3289    // F5/F7: a coordination question must NOT re-print the anchor path inside the
3290    // fact text, must NOT emit a backslash-backtick sequence, must cap the
3291    // contract member list, and drops the trailing question in the tour.
3292    #[test]
3293    fn fact_does_not_reprint_path_or_emit_escaped_backticks() {
3294        let q = "`src/page.ts` changes exports (a, b, c, d, e, f, g, h, i) imported by 9 files outside this PR. Does this change break or alter what those callers expect?";
3295        let guide = guide_with_question("src/page.ts", q);
3296        let md = build_walkthrough_markdown(&guide, Path::new("/project"), &[]);
3297        // No backslash-backtick anywhere (the F5 corruption).
3298        assert!(
3299            !md.contains("\\`"),
3300            "fact must never emit a backslash-backtick sequence: {md}"
3301        );
3302        // The path is printed once (the bullet lead), not a second time in the fact.
3303        assert!(
3304            !md.contains("`src/page.ts` changes exports"),
3305            "fact must not re-print the path: {md}"
3306        );
3307        // The member list is capped with a "+N more".
3308        assert!(md.contains("+3 more"), "member list capped: {md}");
3309        // The trailing decision question is dropped in the tour (it lives in the brief).
3310        assert!(
3311            !md.contains("break or alter"),
3312            "the per-file question must be dropped in the tour: {md}"
3313        );
3314        // The raw "(score N)" is gone.
3315        assert!(!md.contains("(score "), "raw score removed: {md}");
3316    }
3317
3318    #[test]
3319    fn empty_order_renders_orientation_only_note() {
3320        let mut guide = guide_with_question("src/page.ts", "q");
3321        guide.direction.order.clear();
3322        guide.direction.units.clear();
3323        guide.digest.decisions.decisions.clear();
3324        let md = build_walkthrough_markdown(&guide, Path::new("/project"), &[]);
3325        assert!(md.contains("orientation only"), "got: {md}");
3326    }
3327
3328    // A decision whose anchor is not a staged unit (a manifest) still renders,
3329    // so a dependency-only change never reads as "nothing to review".
3330    #[test]
3331    fn decision_outside_staged_units_renders_its_own_section() {
3332        let mut guide = guide_with_question(
3333            "package.json",
3334            "`package.json` moves 1 dependency across a major version (`react` ^18 -> ^19), imported by 8 in-repo modules. Which changelog-listed behavior changes reach those importers?",
3335        );
3336        guide.direction.order.clear();
3337        guide.direction.units.clear();
3338        let md = build_walkthrough_markdown(&guide, Path::new("/project"), &[]);
3339        assert!(
3340            md.contains("### Decisions outside the staged files (1)"),
3341            "got: {md}"
3342        );
3343        assert!(md.contains("`package.json`"), "got: {md}");
3344        assert!(!md.contains("orientation only"), "got: {md}");
3345    }
3346}
3347
3348#[cfg(test)]
3349#[path = "markdown_output_diff_risk_tests.rs"]
3350mod diff_risk_markdown_tests;