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