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