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