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