Skip to main content

fallow_api/
markdown_output.rs

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