Skip to main content

fallow_engine/
viz.rs

1//! Typed data contract and builder for `fallow viz`.
2//!
3//! The CLI runs one project analysis (dead code + duplication + complexity)
4//! through [`crate::session::AnalysisSession`] and hands the retained
5//! artifacts to [`build_viz_data`]. The resulting [`VizData`] is embedded as
6//! JSON in the self-contained interactive HTML the `viz` command writes.
7//!
8//! The contract is engine-owned so the graph internals never leak past the
9//! engine boundary: everything the frontend needs is resolved to file
10//! indices, relative paths, and plain counts here.
11
12use std::path::Path;
13
14use rustc_hash::FxHashMap;
15use serde::Serialize;
16use serde_json::Value;
17
18use fallow_config::{ResolvedConfig, WorkspaceInfo};
19use fallow_output::HealthReport;
20use fallow_types::discover::DiscoveredFile;
21use fallow_types::duplicates::{CloneInstance, DuplicationReport};
22use fallow_types::extract::{FunctionComplexity, ModuleInfo};
23use fallow_types::results::{AnalysisResults, FeatureFlag, SecurityFinding};
24
25use crate::module_graph::RetainedModuleGraph;
26
27#[path = "viz_files.rs"]
28mod files;
29use files::build_files;
30
31/// A file counts as a complexity hotspot at or above this cyclomatic score.
32const HOTSPOT_CYCLOMATIC_FLOOR: u16 = 10;
33/// Maximum bytes of clone-fragment preview shipped per clone group. The
34/// budget is measured in bytes, not characters; truncation only ever cuts
35/// at a line boundary, so multi-byte source cannot be sliced mid-character.
36const CLONE_PREVIEW_MAX_BYTES: usize = 2000;
37/// Maximum lines of clone-fragment preview shipped per clone group. The
38/// preview grows to its content in the panel (no inner scroll), so this can
39/// be generous; big blocks still truncate, keeping the leading context.
40const CLONE_PREVIEW_MAX_LINES: usize = 32;
41/// Source lines of context included on each side of the duplicated block
42/// in a clone preview. A fixed window is universal: clones are frequently
43/// not functions (interface fields, object literals, type aliases), so no
44/// enclosing-scope detection is attempted.
45const CLONE_PREVIEW_CONTEXT: usize = 4;
46/// Maximum clone groups serialized into the payload. Far above any
47/// legitimate report; a guardrail against multi-MB HTML on monorepos.
48/// Groups keep the detector's report order, so the cap keeps the first N.
49const MAX_CLONE_GROUPS: usize = 500;
50/// Maximum specialized finding records serialized per analysis family.
51const MAX_ANALYSIS_FINDINGS: usize = 1000;
52/// Maximum located security blind-spot samples beyond the aggregate rows.
53const MAX_SECURITY_BLIND_SPOT_SAMPLES: usize = 100;
54/// Maximum file-health rows serialized into the browser payload.
55const MAX_HEALTH_FILES: usize = 2000;
56/// Edge flag bit: every import of this edge is type-only.
57const EDGE_FLAG_TYPE_ONLY: u32 = 1;
58/// Edge flag bit: the edge carries a runtime value but no static one, so the
59/// target loads only on demand (`import()`, a lazy pattern) or on another
60/// thread (a worker, a fork). The graph view draws it dashed.
61const EDGE_FLAG_DYNAMIC: u32 = 2;
62/// Reason reported by every family that needs runtime evidence viz was not
63/// given. Viz takes no runtime coverage input, so the Health and Security
64/// lenses say so instead of presenting a static-only answer as the whole one.
65const NO_RUNTIME_COVERAGE_REASON: &str = "No runtime coverage input was provided";
66
67/// Everything [`build_viz_data`] needs from one project analysis run.
68pub struct VizBuildInput<'a> {
69    /// Dead-code analysis results (unused files/exports, cycles, boundaries).
70    pub results: &'a AnalysisResults,
71    /// Retained module graph for edges, entry points, and export counts.
72    pub graph: &'a RetainedModuleGraph,
73    /// Parsed modules with complexity data, when retained.
74    pub modules: Option<&'a [ModuleInfo]>,
75    /// Discovered source files, in `FileId` order.
76    pub files: &'a [DiscoveredFile],
77    /// Duplication report from the same session.
78    pub duplication: &'a DuplicationReport,
79    /// Discovered monorepo workspaces.
80    pub workspaces: &'a [WorkspaceInfo],
81    /// Resolved config (project root + boundary zones).
82    pub config: &'a ResolvedConfig,
83    /// Feature flag records derived from the same parsed session.
84    pub feature_flags: &'a [FeatureFlag],
85    /// Whether to project the HTML-only lens detail payloads.
86    pub include_analysis_details: bool,
87}
88
89/// Serialized payload embedded in the viz HTML.
90#[derive(Serialize)]
91pub struct VizData {
92    /// Project display name (root directory basename).
93    pub root: String,
94    /// One entry per analyzed source file, indexed by position.
95    pub files: Vec<VizFile>,
96    /// Import edges as `[from, to, flags]` file-index pairs.
97    /// `flags` bit 0 marks an edge whose imports are all type-only; bit 1
98    /// marks an edge that loads its target only on demand or on another
99    /// thread (`import()`, a lazy pattern, a worker, a fork).
100    pub edges: Vec<[u32; 3]>,
101    /// Project-wide totals for the header stat boxes.
102    pub summary: VizSummary,
103    /// Discovered workspaces; `VizFile.workspace` indexes into this.
104    pub workspaces: Vec<VizWorkspace>,
105    /// Boundary zones; `VizFile.zone` and violations index into this.
106    pub zones: Vec<VizZone>,
107    /// Circular-dependency cycles as file-index lists.
108    pub cycles: Vec<Vec<u32>>,
109    /// Clone groups; `VizFile.clone_groups` indexes into this.
110    pub clones: Vec<VizCloneGroup>,
111    /// Boundary violations resolved to file indices.
112    pub violations: Vec<VizViolation>,
113    /// Architecture findings that do not fit the legacy graph overlays alone.
114    pub architecture: VizFindingAnalysis,
115    /// Dependency and public-API findings, excluding unused dependencies.
116    pub dependencies: VizFindingAnalysis,
117    /// Real health scoring and hotspot data from the shared analysis session.
118    pub health: VizHealthData,
119    /// Static security candidates and explicit blind spots.
120    pub security: VizSecurityData,
121    /// Framework-specific findings and detector diagnostics.
122    pub frameworks: VizFrameworkData,
123    /// CSS and design-system findings from health analysis.
124    pub styling: VizStylingData,
125    /// Detected feature flag use sites.
126    pub feature_flags: VizFindingAnalysis,
127}
128
129/// Honest availability state for one Viz analysis family.
130#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
131#[serde(rename_all = "camelCase")]
132pub enum VizAvailabilityState {
133    /// The analysis ran and its count is the whole answer.
134    Complete,
135    /// The analysis is switched off by configuration.
136    Disabled,
137    /// The analysis has nothing to say about this project.
138    NotApplicable,
139    /// The analysis could not run, so no count can be claimed.
140    Unavailable,
141}
142
143/// Count contract and availability for one analysis family.
144///
145/// A count is meaningful only when `state` is
146/// [`VizAvailabilityState::Complete`]. Every other state carries a count of
147/// zero that the frontend must render as missing data rather than as zero
148/// findings.
149#[derive(Serialize)]
150pub struct VizAvailability {
151    /// Whether the count below can be read as a result.
152    pub state: VizAvailabilityState,
153    /// Number of items in `unit`, valid only in the `Complete` state.
154    pub count: usize,
155    /// What `count` counts, such as `findings` or `files`.
156    pub unit: &'static str,
157    /// Why the analysis is not complete, for every non-complete state.
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub reason: Option<String>,
160    /// Total before payload truncation, when the payload carries fewer items
161    /// than `count`.
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub truncated: Option<usize>,
164}
165
166impl VizAvailability {
167    const fn complete(count: usize, unit: &'static str, truncated: Option<usize>) -> Self {
168        Self {
169            state: VizAvailabilityState::Complete,
170            count,
171            unit,
172            reason: None,
173            truncated,
174        }
175    }
176
177    fn unavailable(unit: &'static str, reason: impl Into<String>) -> Self {
178        Self {
179            state: VizAvailabilityState::Unavailable,
180            count: 0,
181            unit,
182            reason: Some(reason.into()),
183            truncated: None,
184        }
185    }
186
187    fn disabled(unit: &'static str, reason: impl Into<String>) -> Self {
188        Self {
189            state: VizAvailabilityState::Disabled,
190            count: 0,
191            unit,
192            reason: Some(reason.into()),
193            truncated: None,
194        }
195    }
196}
197
198/// Stable presentation record shared by finding-oriented Viz families.
199#[derive(Serialize)]
200pub struct VizFinding {
201    kind: String,
202    title: String,
203    #[serde(skip_serializing_if = "Option::is_none")]
204    file: Option<u32>,
205    #[serde(skip_serializing_if = "Option::is_none")]
206    path: Option<String>,
207    #[serde(skip_serializing_if = "Option::is_none")]
208    line: Option<u32>,
209    #[serde(skip_serializing_if = "Vec::is_empty")]
210    files: Vec<u32>,
211    #[serde(skip_serializing_if = "Vec::is_empty")]
212    paths: Vec<String>,
213    #[serde(skip_serializing_if = "Option::is_none")]
214    description: Option<String>,
215    #[serde(skip_serializing_if = "Option::is_none")]
216    severity: Option<String>,
217    #[serde(skip_serializing_if = "Vec::is_empty")]
218    facts: Vec<VizFindingFact>,
219    actions: Vec<VizFindingAction>,
220}
221
222/// One stable scalar fact from an analyzer-specific record.
223#[derive(Serialize)]
224pub struct VizFindingFact {
225    label: String,
226    value: String,
227}
228
229/// One stable action projected from an analyzer-specific record.
230#[derive(Serialize)]
231pub struct VizFindingAction {
232    label: String,
233    #[serde(skip_serializing_if = "Option::is_none")]
234    kind: Option<String>,
235    auto_fixable: bool,
236    #[serde(skip_serializing_if = "Option::is_none")]
237    command: Option<String>,
238    #[serde(skip_serializing_if = "Option::is_none")]
239    comment: Option<String>,
240    #[serde(skip_serializing_if = "Option::is_none")]
241    config_key: Option<String>,
242    #[serde(skip_serializing_if = "Option::is_none")]
243    value: Option<Value>,
244    #[serde(skip_serializing_if = "Option::is_none")]
245    description: Option<String>,
246}
247
248/// One finding-oriented analysis family.
249#[derive(Serialize)]
250pub struct VizFindingAnalysis {
251    /// Whether this family ran, and how many findings it stands behind.
252    pub availability: VizAvailability,
253    /// Total finding count before the payload was capped.
254    #[serde(skip_serializing_if = "Option::is_none")]
255    pub findings_truncated: Option<usize>,
256    /// The findings carried in the payload.
257    pub findings: Vec<VizFinding>,
258}
259
260/// Framework findings plus detector capability metadata.
261#[derive(Serialize)]
262pub struct VizFrameworkData {
263    /// Whether framework analysis ran, and how many findings it produced.
264    pub availability: VizAvailability,
265    /// Whether the per-detector capability list is trustworthy. A detector
266    /// can be unavailable while findings from other detectors are complete.
267    pub detector_availability: VizAvailability,
268    /// Total finding count before the payload was capped.
269    #[serde(skip_serializing_if = "Option::is_none")]
270    pub findings_truncated: Option<usize>,
271    /// The findings carried in the payload.
272    pub findings: Vec<VizFinding>,
273    /// Frameworks detected in the project.
274    pub detected_frameworks: Vec<String>,
275    /// Per-detector status, so a silent detector is distinguishable from a
276    /// detector that ran and found nothing.
277    pub detectors: Vec<VizFrameworkDetector>,
278}
279
280/// Status of one framework-specific detector.
281#[derive(Serialize)]
282pub struct VizFrameworkDetector {
283    id: String,
284    framework: String,
285    status: String,
286    #[serde(skip_serializing_if = "Option::is_none")]
287    reason: Option<String>,
288}
289
290/// Availability of the individual Health signal families.
291#[derive(Serialize)]
292pub struct VizHealthCapabilities {
293    /// Cyclomatic and cognitive complexity findings.
294    pub complexity: VizAvailability,
295    /// Per-file maintainability index scores.
296    pub maintainability: VizAvailability,
297    /// CRAP risk scores, which need coverage to be meaningful.
298    pub crap: VizAvailability,
299    /// Istanbul coverage ingestion.
300    pub coverage: VizAvailability,
301    /// Runtime execution evidence, which needs a runtime coverage input.
302    pub runtime: VizAvailability,
303    /// Git churn, which needs a history walk viz does not perform.
304    pub churn: VizAvailability,
305    /// Churn-weighted complexity hotspots, gated on churn.
306    pub hotspots: VizAvailability,
307    /// Ownership attribution, which needs a history walk viz does not perform.
308    pub ownership: VizAvailability,
309}
310
311/// Real file-health metrics.
312#[derive(Serialize)]
313pub struct VizHealthFile {
314    file: u32,
315    path: String,
316    maintainability_index: f64,
317    crap_max: f64,
318    complexity_density: f64,
319    fan_in: usize,
320    fan_out: usize,
321    #[serde(skip_serializing_if = "Option::is_none")]
322    hotspot_score: Option<f64>,
323    #[serde(skip_serializing_if = "Option::is_none")]
324    commits: Option<u32>,
325    #[serde(skip_serializing_if = "Option::is_none")]
326    ownership: Option<Value>,
327}
328
329/// Health lens payload populated after the shared health runner completes.
330#[derive(Serialize)]
331pub struct VizHealthData {
332    /// Whether the health runner completed, and how many files it scored.
333    pub availability: VizAvailability,
334    /// Per-signal availability, so the lens can dim what did not run.
335    pub capabilities: VizHealthCapabilities,
336    /// Whether the run reused the viz session's parse instead of reparsing.
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub shared_parse: Option<bool>,
339    /// Overall health score.
340    #[serde(skip_serializing_if = "Option::is_none")]
341    pub score: Option<f64>,
342    /// Letter grade derived from `score`.
343    #[serde(skip_serializing_if = "Option::is_none")]
344    pub grade: Option<String>,
345    /// Mean maintainability index across scored files.
346    #[serde(skip_serializing_if = "Option::is_none")]
347    pub average_maintainability: Option<f64>,
348    /// Per-file metrics carried in the payload.
349    pub files: Vec<VizHealthFile>,
350    /// Total scored-file count before the payload was capped.
351    #[serde(skip_serializing_if = "Option::is_none")]
352    pub files_truncated: Option<usize>,
353    /// Total finding count before the payload was capped.
354    #[serde(skip_serializing_if = "Option::is_none")]
355    pub findings_truncated: Option<usize>,
356    /// The health findings carried in the payload.
357    pub findings: Vec<VizFinding>,
358}
359
360/// Styling findings plus the project-level CSS analytics and score.
361#[derive(Serialize)]
362pub struct VizStylingData {
363    /// Whether styling analysis ran, and how many findings it produced.
364    pub availability: VizAvailability,
365    /// Total finding count before the payload was capped.
366    #[serde(skip_serializing_if = "Option::is_none")]
367    pub findings_truncated: Option<usize>,
368    /// The styling findings carried in the payload.
369    pub findings: Vec<VizFinding>,
370    /// Project-level styling score.
371    #[serde(skip_serializing_if = "Option::is_none")]
372    pub score: Option<f64>,
373    /// Letter grade derived from `score`.
374    #[serde(skip_serializing_if = "Option::is_none")]
375    pub grade: Option<String>,
376    /// How much evidence the score rests on.
377    #[serde(skip_serializing_if = "Option::is_none")]
378    pub confidence: Option<String>,
379    /// Project-level CSS analytics, rendered as-is by the lens.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    pub summary: Option<Value>,
382}
383
384/// One hop in a static security trace.
385#[derive(Serialize)]
386pub struct VizSecurityTraceHop {
387    #[serde(skip_serializing_if = "Option::is_none")]
388    file: Option<u32>,
389    path: String,
390    line: u32,
391    col: u32,
392    role: String,
393}
394
395/// One endpoint in a typed Security taint flow.
396#[derive(Serialize)]
397pub struct VizSecurityEndpoint {
398    #[serde(skip_serializing_if = "Option::is_none")]
399    file: Option<u32>,
400    path: String,
401    line: u32,
402    col: u32,
403}
404
405/// Typed source-to-sink flow summary.
406#[derive(Serialize)]
407pub struct VizSecurityTaintFlow {
408    source: VizSecurityEndpoint,
409    sink: VizSecurityEndpoint,
410    intra_module: bool,
411    cross_module_hops: u32,
412}
413
414/// Static security candidate. The record deliberately contains no
415/// exploitability verdict.
416#[derive(Serialize)]
417pub struct VizSecurityCandidate {
418    id: String,
419    kind: String,
420    #[serde(skip_serializing_if = "Option::is_none")]
421    category: Option<String>,
422    #[serde(skip_serializing_if = "Option::is_none")]
423    cwe: Option<u32>,
424    #[serde(skip_serializing_if = "Option::is_none")]
425    file: Option<u32>,
426    path: String,
427    line: u32,
428    col: u32,
429    evidence: String,
430    severity: String,
431    #[serde(skip_serializing_if = "Option::is_none")]
432    taint_confidence: Option<String>,
433    #[serde(skip_serializing_if = "Option::is_none")]
434    source_kind: Option<String>,
435    #[serde(skip_serializing_if = "Option::is_none")]
436    sink: Option<String>,
437    #[serde(skip_serializing_if = "Option::is_none")]
438    url_shape: Option<String>,
439    #[serde(skip_serializing_if = "Option::is_none")]
440    network_destination: Option<String>,
441    #[serde(skip_serializing_if = "Option::is_none")]
442    reachable_from_entry: Option<bool>,
443    #[serde(skip_serializing_if = "Option::is_none")]
444    reachable_from_untrusted_source: Option<bool>,
445    #[serde(skip_serializing_if = "Option::is_none")]
446    blast_radius: Option<u32>,
447    crosses_boundary: bool,
448    client_server_boundary: bool,
449    cross_module_boundary: bool,
450    #[serde(skip_serializing_if = "Option::is_none")]
451    architecture_zone: Option<String>,
452    #[serde(skip_serializing_if = "Option::is_none")]
453    dead_code: Option<Value>,
454    #[serde(skip_serializing_if = "Option::is_none")]
455    runtime: Option<Value>,
456    #[serde(skip_serializing_if = "Option::is_none")]
457    taint_flow: Option<VizSecurityTaintFlow>,
458    #[serde(skip_serializing_if = "Vec::is_empty")]
459    observed_controls: Vec<Value>,
460    #[serde(skip_serializing_if = "Option::is_none")]
461    control_verification_prompt: Option<String>,
462    trace: Vec<VizSecurityTraceHop>,
463    #[serde(skip_serializing_if = "Vec::is_empty")]
464    taint_trace: Vec<VizSecurityTraceHop>,
465    actions: Value,
466}
467
468/// Explicitly counted security blind spot.
469#[derive(Serialize)]
470pub struct VizSecurityBlindSpot {
471    kind: String,
472    count: usize,
473    #[serde(skip_serializing_if = "Option::is_none")]
474    path: Option<String>,
475    #[serde(skip_serializing_if = "Option::is_none")]
476    file: Option<u32>,
477    #[serde(skip_serializing_if = "Option::is_none")]
478    line: Option<u32>,
479    #[serde(skip_serializing_if = "Option::is_none")]
480    reason: Option<String>,
481}
482
483/// Security lens payload. Runtime evidence is a separate capability from the
484/// always-local static candidate pass.
485#[derive(Serialize)]
486pub struct VizSecurityData {
487    /// Whether the static candidate pass ran, and how many candidates it
488    /// surfaced. Candidates are unverified, never vulnerability verdicts.
489    pub availability: VizAvailability,
490    /// Runtime evidence availability. Without a runtime coverage input this
491    /// stays `Unavailable`, never a complete count of zero.
492    pub runtime_availability: VizAvailability,
493    /// The static candidates carried in the payload.
494    pub candidates: Vec<VizSecurityCandidate>,
495    /// How many places the static pass could not see into.
496    pub blind_spot_count: usize,
497    /// Total blind-spot count before the payload was capped.
498    #[serde(skip_serializing_if = "Option::is_none")]
499    pub blind_spots_truncated: Option<usize>,
500    /// The blind spots carried in the payload.
501    pub blind_spots: Vec<VizSecurityBlindSpot>,
502}
503
504/// One analyzed source file.
505#[derive(Serialize)]
506pub struct VizFile {
507    /// Root-relative path with forward slashes.
508    pub path: String,
509    /// File size in bytes (treemap area).
510    pub size: u64,
511    /// Dead-code status classification.
512    pub status: VizFileStatus,
513    /// Number of exports declared by the file.
514    pub export_count: u16,
515    /// Number of exports (values + types) reported unused.
516    pub unused_export_count: u16,
517    /// Whether the file is an entry point.
518    pub is_entry: bool,
519    /// Number of files importing this file.
520    pub importer_count: u16,
521    /// Number of files this file imports.
522    pub import_count: u16,
523    /// Index into `VizData.workspaces`, if the file belongs to one.
524    #[serde(skip_serializing_if = "Option::is_none")]
525    pub workspace: Option<u16>,
526    /// Index into `VizData.zones`, if the file matches a boundary zone.
527    #[serde(skip_serializing_if = "Option::is_none")]
528    pub zone: Option<u16>,
529    /// Names of unused exports (for actionable tooltips).
530    #[serde(skip_serializing_if = "Vec::is_empty")]
531    pub unused_exports: Vec<String>,
532    /// Number of functions parsed in the file.
533    pub fn_count: u16,
534    /// Highest cyclomatic complexity of any function in the file.
535    pub max_cyclomatic: u16,
536    /// Highest cognitive complexity of any function in the file.
537    pub max_cognitive: u16,
538    /// Total React hook calls across the file's functions.
539    pub react_hooks: u16,
540    /// Deepest JSX nesting across the file's functions.
541    pub jsx_depth: u16,
542    /// Every function in the file, sorted hardest-first.
543    #[serde(skip_serializing_if = "Vec::is_empty")]
544    pub functions: Vec<VizFunction>,
545    /// Duplicated lines in this file across all clone groups.
546    pub dup_lines: u32,
547    /// Indices into `VizData.clones` this file participates in.
548    #[serde(skip_serializing_if = "Vec::is_empty")]
549    pub clone_groups: Vec<u32>,
550    /// Whether the file participates in any circular dependency.
551    pub in_cycle: bool,
552}
553
554/// Dead-code status of a file, ordered by severity in the frontend.
555#[derive(Serialize, Clone, Copy, PartialEq, Eq)]
556#[serde(rename_all = "camelCase")]
557pub enum VizFileStatus {
558    /// No findings.
559    Clean,
560    /// Live file with one or more unused exports.
561    HasUnusedExports,
562    /// Entire file is unreachable.
563    Unused,
564    /// Configured or detected entry point.
565    EntryPoint,
566}
567
568/// One function inside a file, with its complexity metrics.
569#[derive(Serialize)]
570pub struct VizFunction {
571    /// Function name, or `<anonymous>`.
572    name: String,
573    /// 1-based start line.
574    line: u32,
575    /// McCabe cyclomatic complexity.
576    cyclomatic: u16,
577    /// SonarSource cognitive complexity.
578    cognitive: u16,
579    /// Body line count.
580    lines: u32,
581    /// React hook calls made directly in the body.
582    hooks: u16,
583    /// Deepest JSX nesting in the body.
584    jsx_depth: u16,
585    /// Props destructured from the first parameter.
586    props: u16,
587}
588
589/// Project-wide totals for the header stat boxes.
590#[derive(Serialize)]
591pub struct VizSummary {
592    /// Total analyzed files.
593    pub total_files: usize,
594    /// Total bytes across analyzed files.
595    pub total_size: u64,
596    /// Total import edges.
597    pub total_edges: usize,
598    /// Fully unused files.
599    pub unused_files: usize,
600    /// Unused exports (values + types).
601    pub unused_exports: usize,
602    /// Unused exported types.
603    pub unused_types: usize,
604    /// Unused dependencies (prod + dev + optional).
605    pub unused_deps: usize,
606    /// Imports that resolve to nothing.
607    pub unresolved_imports: usize,
608    /// Circular dependency cycles.
609    pub circular_deps: usize,
610    /// Clone groups detected.
611    pub clone_groups: usize,
612    /// Total duplicated lines across clone groups.
613    pub duplicated_lines: usize,
614    /// Boundary violations.
615    pub boundary_violations: usize,
616    /// Files at or above the complexity hotspot floor.
617    pub hotspot_files: usize,
618    /// Kept clone groups dropped by the `MAX_CLONE_GROUPS` payload cap.
619    /// Present only when the clone payload was truncated.
620    #[serde(skip_serializing_if = "Option::is_none")]
621    pub clone_groups_truncated: Option<u32>,
622}
623
624/// One discovered workspace.
625#[derive(Serialize)]
626pub struct VizWorkspace {
627    /// Package name.
628    name: String,
629    /// Root-relative workspace root.
630    root: String,
631}
632
633/// One configured boundary zone.
634#[derive(Serialize)]
635pub struct VizZone {
636    /// Zone name from the boundaries config.
637    name: String,
638    /// Number of files classified into this zone.
639    files: u32,
640}
641
642/// One clone group resolved to file indices.
643#[derive(Serialize)]
644pub struct VizCloneGroup {
645    /// Lines per duplicated block.
646    lines: usize,
647    /// Tokens per duplicated block.
648    tokens: usize,
649    /// Where the duplicated block appears.
650    instances: Vec<VizCloneInstance>,
651    /// Source preview: a context window around the duplicated block, the
652    /// copied lines flanked by up to `CLONE_PREVIEW_CONTEXT` surrounding
653    /// source lines on each side.
654    preview: String,
655    /// 0-based index, among the lines of `preview`, of the first copied
656    /// line. Lines before it are dimmed context.
657    highlight_start: u32,
658    /// Number of copied lines present in `preview`. The frontend highlights
659    /// `preview` lines `[highlight_start, highlight_start + highlight_lines)`
660    /// and dims the rest.
661    highlight_lines: u32,
662}
663
664/// One location of a duplicated block.
665#[derive(Serialize)]
666pub struct VizCloneInstance {
667    /// File index into `VizData.files`.
668    file: u32,
669    /// 1-based start line.
670    start_line: u32,
671    /// 1-based end line.
672    end_line: u32,
673}
674
675/// One boundary violation resolved to file indices.
676#[derive(Serialize)]
677pub struct VizViolation {
678    /// Importing file index.
679    from: u32,
680    /// Imported file index.
681    to: u32,
682    /// Index into `VizData.zones` for the importing file's zone.
683    from_zone: u16,
684    /// Index into `VizData.zones` for the imported file's zone.
685    to_zone: u16,
686    /// 1-based line of the offending import.
687    line: u32,
688    /// Raw import specifier.
689    specifier: String,
690}
691
692/// Build the viz payload from one project analysis run.
693#[must_use]
694pub fn build_viz_data(input: &VizBuildInput<'_>) -> VizData {
695    let root = &input.config.root;
696    let index = FileIndex::new(input.files);
697    let workspaces = build_workspaces(input.workspaces, root);
698    let (zones, zone_by_file) = classify_zones(input, &index);
699    let (clones, clone_groups_by_file, dup_lines_by_file, clone_groups_truncated) =
700        build_clones(input.duplication, &index, MAX_CLONE_GROUPS);
701    let cycles = build_cycles(input.results, &index);
702    let violations = build_violations(input.results, &zones, &index);
703    let (architecture, dependencies, security, frameworks, feature_flags) =
704        if input.include_analysis_details {
705            (
706                build_architecture(input.results, &index, root),
707                build_dependencies(input.results, &index, root),
708                build_security(input.results, &index, root),
709                build_frameworks(input.results, &index, root),
710                build_feature_flags(input.feature_flags, &index, root),
711            )
712        } else {
713            skipped_analysis_details()
714        };
715
716    let files = build_files(
717        input,
718        &index,
719        &FilePropertyMaps {
720            zone_by_file: &zone_by_file,
721            clone_groups_by_file: &clone_groups_by_file,
722            dup_lines_by_file: &dup_lines_by_file,
723            cycles: &cycles,
724        },
725    );
726
727    let summary = build_summary(
728        input,
729        &files,
730        &clones,
731        &cycles,
732        &violations,
733        clone_groups_truncated,
734    );
735
736    VizData {
737        root: display_root(root),
738        files,
739        edges: build_edges(input.graph, &index),
740        summary,
741        workspaces,
742        zones,
743        cycles,
744        clones,
745        violations,
746        architecture,
747        dependencies,
748        health: VizHealthData {
749            availability: VizAvailability::unavailable("files", "Health analysis did not complete"),
750            capabilities: unavailable_health_capabilities("Health analysis did not complete"),
751            shared_parse: None,
752            score: None,
753            grade: None,
754            average_maintainability: None,
755            files: Vec::new(),
756            files_truncated: None,
757            findings_truncated: None,
758            findings: Vec::new(),
759        },
760        security,
761        frameworks,
762        styling: VizStylingData {
763            availability: VizAvailability::unavailable(
764                "findings",
765                "Styling analysis did not complete",
766            ),
767            findings_truncated: None,
768            findings: Vec::new(),
769            score: None,
770            grade: None,
771            confidence: None,
772            summary: None,
773        },
774        feature_flags,
775    }
776}
777
778fn skipped_analysis_details() -> (
779    VizFindingAnalysis,
780    VizFindingAnalysis,
781    VizSecurityData,
782    VizFrameworkData,
783    VizFindingAnalysis,
784) {
785    let skipped = |unit| VizFindingAnalysis {
786        availability: VizAvailability::disabled(unit, "Not needed for this Viz output format"),
787        findings_truncated: None,
788        findings: Vec::new(),
789    };
790    (
791        skipped("violations"),
792        skipped("findings"),
793        VizSecurityData {
794            availability: VizAvailability::disabled(
795                "candidates",
796                "Not needed for this Viz output format",
797            ),
798            runtime_availability: VizAvailability::disabled(
799                "observations",
800                "Not needed for this Viz output format",
801            ),
802            candidates: Vec::new(),
803            blind_spot_count: 0,
804            blind_spots_truncated: None,
805            blind_spots: Vec::new(),
806        },
807        VizFrameworkData {
808            availability: VizAvailability::disabled(
809                "findings",
810                "Not needed for this Viz output format",
811            ),
812            detector_availability: VizAvailability::disabled(
813                "detectors",
814                "Not needed for this Viz output format",
815            ),
816            findings_truncated: None,
817            findings: Vec::new(),
818            detected_frameworks: Vec::new(),
819            detectors: Vec::new(),
820        },
821        skipped("flags"),
822    )
823}
824
825/// Maps absolute paths to dense viz file indices in `FileId` order.
826struct FileIndex<'a> {
827    ordered: Vec<&'a DiscoveredFile>,
828    by_path: FxHashMap<&'a Path, u32>,
829    by_file_id: FxHashMap<u32, u32>,
830}
831
832impl<'a> FileIndex<'a> {
833    fn new(files: &'a [DiscoveredFile]) -> Self {
834        let mut ordered: Vec<&DiscoveredFile> = files.iter().collect();
835        ordered.sort_by_key(|f| f.id.0);
836        let mut by_path = FxHashMap::default();
837        let mut by_file_id = FxHashMap::default();
838        for (i, f) in ordered.iter().enumerate() {
839            let idx = clamp_u32(i);
840            by_path.insert(f.path.as_path(), idx);
841            by_file_id.insert(f.id.0, idx);
842        }
843        Self {
844            ordered,
845            by_path,
846            by_file_id,
847        }
848    }
849
850    fn index_of_path(&self, path: &Path) -> Option<u32> {
851        self.by_path.get(path).copied()
852    }
853
854    fn index_of_file_id(&self, file_id: u32) -> Option<u32> {
855        self.by_file_id.get(&file_id).copied()
856    }
857}
858
859fn analysis_from_records(
860    mut findings: Vec<VizFinding>,
861    total_findings: usize,
862    primary_count: usize,
863    unit: &'static str,
864) -> VizFindingAnalysis {
865    let findings_truncated = (total_findings > MAX_ANALYSIS_FINDINGS)
866        .then_some(total_findings.saturating_sub(MAX_ANALYSIS_FINDINGS));
867    let primary_truncated = (primary_count > MAX_ANALYSIS_FINDINGS)
868        .then_some(primary_count.saturating_sub(MAX_ANALYSIS_FINDINGS));
869    findings.truncate(MAX_ANALYSIS_FINDINGS);
870    VizFindingAnalysis {
871        availability: VizAvailability::complete(primary_count, unit, primary_truncated),
872        findings_truncated,
873        findings,
874    }
875}
876
877fn push_findings<T: Serialize>(
878    out: &mut Vec<VizFinding>,
879    kind: &str,
880    title: &str,
881    values: &[T],
882    root: &Path,
883    index: &FileIndex<'_>,
884) {
885    let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
886    out.extend(values.iter().take(remaining).filter_map(|value| {
887        serde_json::to_value(value).ok().map(|detail| {
888            finding_from_value(kind, title, detail, root, &|path| index.index_of_path(path))
889        })
890    }));
891}
892
893fn finding_from_value(
894    kind: &str,
895    title: &str,
896    mut detail: Value,
897    root: &Path,
898    resolve_file: &dyn Fn(&Path) -> Option<u32>,
899) -> VizFinding {
900    let raw_path = find_string_key(&detail, &["path", "from_path", "consumer_path", "file"])
901        .map(str::to_owned);
902    let mut raw_paths = Vec::new();
903    collect_path_values(&detail, &mut raw_paths);
904    let mut paths = Vec::new();
905    let mut files = Vec::new();
906    for raw in raw_paths {
907        let raw_path = Path::new(&raw);
908        // has_root, not is_absolute: joining a Windows rooted path that carries
909        // no drive letter onto root would reinterpret an external path as
910        // project-relative and expose its components instead of redacting it.
911        let absolute_path = if raw_path.has_root() {
912            raw_path.to_path_buf()
913        } else {
914            root.join(raw_path)
915        };
916        let display = relative_path(&absolute_path, root);
917        if !paths.contains(&display) {
918            paths.push(display);
919        }
920        if let Some(file) = resolve_file(&absolute_path)
921            && !files.contains(&file)
922        {
923            files.push(file);
924        }
925    }
926    let absolute = raw_path.as_deref().map(Path::new).map(|path| {
927        if path.has_root() {
928            path.to_path_buf()
929        } else {
930            root.join(path)
931        }
932    });
933    let file = absolute.as_deref().and_then(resolve_file);
934    let path = absolute.as_deref().map(|path| relative_path(path, root));
935    let line = find_u64_key(&detail, &["line", "start_line"])
936        .map(|value| u32::try_from(value).unwrap_or(u32::MAX));
937    relativize_value_paths(&mut detail, root);
938    let description =
939        find_string_key(&detail, &["message", "evidence", "reason"]).map(str::to_owned);
940    let severity = find_string_key(&detail, &["severity"]).map(str::to_owned);
941    let facts = finding_facts(&detail);
942    let actions = finding_actions(&detail);
943    VizFinding {
944        kind: kind.to_string(),
945        title: title.to_string(),
946        file,
947        path,
948        line,
949        files,
950        paths,
951        description,
952        severity,
953        facts,
954        actions,
955    }
956}
957
958fn finding_facts(detail: &Value) -> Vec<VizFindingFact> {
959    const EXCLUDED: &[&str] = &[
960        "path",
961        "from_path",
962        "to_path",
963        "consumer_path",
964        "file",
965        "files",
966        "paths",
967        "line",
968        "start_line",
969        "message",
970        "evidence",
971        "reason",
972        "severity",
973        "actions",
974    ];
975    let Some(fields) = detail.as_object() else {
976        return Vec::new();
977    };
978    fields
979        .iter()
980        .filter(|(label, _)| !EXCLUDED.contains(&label.as_str()))
981        .filter_map(|(label, value)| {
982            scalar_fact_value(value).map(|value| VizFindingFact {
983                label: label.clone(),
984                value,
985            })
986        })
987        .take(12)
988        .collect()
989}
990
991fn scalar_fact_value(value: &Value) -> Option<String> {
992    match value {
993        Value::String(value) => Some(value.clone()),
994        Value::Number(value) => Some(value.to_string()),
995        Value::Bool(value) => Some(value.to_string()),
996        Value::Array(values) if values.iter().all(Value::is_string) => Some(
997            values
998                .iter()
999                .filter_map(Value::as_str)
1000                .collect::<Vec<_>>()
1001                .join(", "),
1002        ),
1003        Value::Null | Value::Array(_) | Value::Object(_) => None,
1004    }
1005}
1006
1007fn finding_actions(detail: &Value) -> Vec<VizFindingAction> {
1008    let mut actions = Vec::new();
1009    if let Some(record) = detail.as_object() {
1010        for key in ["verify_command", "trace_command", "command"] {
1011            if let Some(command) = record.get(key).and_then(Value::as_str) {
1012                actions.push(VizFindingAction {
1013                    label: "Verify".to_string(),
1014                    kind: None,
1015                    auto_fixable: false,
1016                    command: Some(command.to_string()),
1017                    comment: None,
1018                    config_key: None,
1019                    value: None,
1020                    description: None,
1021                });
1022            }
1023        }
1024        if let Some(value) = record.get("actions") {
1025            append_projected_actions(&mut actions, value);
1026        }
1027    }
1028    actions
1029}
1030
1031fn append_projected_actions(actions: &mut Vec<VizFindingAction>, value: &Value) {
1032    match value {
1033        Value::Array(values) => {
1034            for value in values {
1035                if let Some(action) = projected_action(value) {
1036                    actions.push(action);
1037                }
1038            }
1039        }
1040        Value::Object(values) => {
1041            for (label, value) in values {
1042                if let Some(command) = value.as_str() {
1043                    actions.push(VizFindingAction {
1044                        label: label.clone(),
1045                        kind: Some(label.clone()),
1046                        auto_fixable: false,
1047                        command: Some(command.to_string()),
1048                        comment: None,
1049                        config_key: None,
1050                        value: None,
1051                        description: None,
1052                    });
1053                }
1054            }
1055        }
1056        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1057    }
1058}
1059
1060fn projected_action(value: &Value) -> Option<VizFindingAction> {
1061    let action = value.as_object()?;
1062    let kind = ["kind", "type"]
1063        .iter()
1064        .find_map(|key| action.get(*key).and_then(Value::as_str))
1065        .map(str::to_owned);
1066    let label = ["label", "title"]
1067        .iter()
1068        .find_map(|key| action.get(*key).and_then(Value::as_str))
1069        .map(str::to_owned)
1070        .or_else(|| kind.clone())
1071        .unwrap_or_else(|| "Review".to_string());
1072    let command = action
1073        .get("command")
1074        .and_then(Value::as_str)
1075        .map(str::to_owned);
1076    let comment = action
1077        .get("comment")
1078        .and_then(Value::as_str)
1079        .map(str::to_owned);
1080    let auto_fixable = action
1081        .get("auto_fixable")
1082        .and_then(Value::as_bool)
1083        .unwrap_or(false);
1084    let config_key = action
1085        .get("config_key")
1086        .and_then(Value::as_str)
1087        .map(str::to_owned);
1088    let projected_value = action.get("value").cloned();
1089    let description = ["description", "note"]
1090        .iter()
1091        .find_map(|key| action.get(*key).and_then(Value::as_str))
1092        .map(str::to_owned);
1093    (command.is_some()
1094        || comment.is_some()
1095        || description.is_some()
1096        || config_key.is_some()
1097        || projected_value.is_some())
1098    .then_some(VizFindingAction {
1099        label,
1100        kind,
1101        auto_fixable,
1102        command,
1103        comment,
1104        config_key,
1105        value: projected_value,
1106        description,
1107    })
1108}
1109
1110fn collect_path_values(value: &Value, out: &mut Vec<String>) {
1111    match value {
1112        Value::Object(map) => {
1113            for (key, value) in map {
1114                if is_path_key(key)
1115                    && let Some(path) = value.as_str()
1116                {
1117                    out.push(path.to_string());
1118                }
1119                if is_path_collection_key(key)
1120                    && let Some(values) = value.as_array()
1121                {
1122                    out.extend(values.iter().filter_map(Value::as_str).map(str::to_string));
1123                }
1124                collect_path_values(value, out);
1125            }
1126        }
1127        Value::Array(values) => {
1128            for value in values {
1129                collect_path_values(value, out);
1130            }
1131        }
1132        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1133    }
1134}
1135
1136fn find_string_key<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {
1137    match value {
1138        Value::Object(map) => {
1139            for key in keys {
1140                if let Some(value) = map.get(*key).and_then(Value::as_str) {
1141                    return Some(value);
1142                }
1143            }
1144            map.values().find_map(|value| find_string_key(value, keys))
1145        }
1146        Value::Array(values) => values.iter().find_map(|value| find_string_key(value, keys)),
1147        _ => None,
1148    }
1149}
1150
1151fn find_u64_key(value: &Value, keys: &[&str]) -> Option<u64> {
1152    match value {
1153        Value::Object(map) => {
1154            for key in keys {
1155                if let Some(value) = map.get(*key).and_then(Value::as_u64) {
1156                    return Some(value);
1157                }
1158            }
1159            map.values().find_map(|value| find_u64_key(value, keys))
1160        }
1161        Value::Array(values) => values.iter().find_map(|value| find_u64_key(value, keys)),
1162        _ => None,
1163    }
1164}
1165
1166fn relativize_value_paths(value: &mut Value, root: &Path) {
1167    relativize_keyed_paths(value, root, false);
1168}
1169
1170fn relativize_keyed_paths(value: &mut Value, root: &Path, is_path: bool) {
1171    match value {
1172        Value::String(text) if is_path => {
1173            let path = Path::new(text);
1174            // has_root, not is_absolute, for the same reason as relative_path:
1175            // a Windows rooted path without a drive letter is not absolute, so
1176            // gating on is_absolute left it unredacted in the payload. Only
1177            // values under a path key reach this arm, so a route specifier such
1178            // as `/api/v1` is excluded by the key gate rather than by this test.
1179            if path.has_root() {
1180                *text = relative_path(path, root);
1181            }
1182        }
1183        Value::Array(values) => {
1184            for value in values {
1185                relativize_keyed_paths(value, root, is_path);
1186            }
1187        }
1188        Value::Object(map) => {
1189            for (key, value) in map {
1190                let is_path = is_path_key(key) || is_path_collection_key(key);
1191                relativize_keyed_paths(value, root, is_path);
1192            }
1193        }
1194        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => {}
1195    }
1196}
1197
1198fn is_path_key(key: &str) -> bool {
1199    matches!(
1200        key,
1201        "path"
1202            | "file"
1203            | "from_path"
1204            | "to_path"
1205            | "consumer_path"
1206            | "source_path"
1207            | "definition_path"
1208            | "template_path"
1209            | "inherited_from"
1210            | "reachable_via"
1211            | "new_path"
1212            | "old_path"
1213            | "cycle_path"
1214            | "docs_path"
1215            | "meta_docs_path"
1216            | "full_report_path"
1217    )
1218}
1219
1220fn is_path_collection_key(key: &str) -> bool {
1221    matches!(
1222        key,
1223        "files"
1224            | "paths"
1225            | "conflicting_paths"
1226            | "used_in_workspaces"
1227            | "hardcoded_consumers"
1228            | "hot_paths"
1229    )
1230}
1231
1232fn serialized_label<T: Serialize>(value: &T) -> String {
1233    serde_json::to_value(value)
1234        .ok()
1235        .and_then(|value| value.as_str().map(str::to_owned))
1236        .unwrap_or_else(|| "unknown".to_string())
1237}
1238
1239fn build_architecture(
1240    results: &AnalysisResults,
1241    index: &FileIndex<'_>,
1242    root: &Path,
1243) -> VizFindingAnalysis {
1244    let mut findings = Vec::new();
1245    push_findings(
1246        &mut findings,
1247        "boundary-violation",
1248        "Forbidden import",
1249        &results.boundary_violations,
1250        root,
1251        index,
1252    );
1253    push_findings(
1254        &mut findings,
1255        "boundary-coverage",
1256        "File outside architecture zones",
1257        &results.boundary_coverage_violations,
1258        root,
1259        index,
1260    );
1261    push_findings(
1262        &mut findings,
1263        "boundary-call",
1264        "Forbidden call",
1265        &results.boundary_call_violations,
1266        root,
1267        index,
1268    );
1269    push_findings(
1270        &mut findings,
1271        "policy-violation",
1272        "Policy violation",
1273        &results.policy_violations,
1274        root,
1275        index,
1276    );
1277    push_findings(
1278        &mut findings,
1279        "circular-dependency",
1280        "Import cycle",
1281        &results.circular_dependencies,
1282        root,
1283        index,
1284    );
1285    push_findings(
1286        &mut findings,
1287        "re-export-cycle",
1288        "Re-export cycle",
1289        &results.re_export_cycles,
1290        root,
1291        index,
1292    );
1293    push_findings(
1294        &mut findings,
1295        "package-cycle",
1296        "Package cycle",
1297        &results.package_cycles,
1298        root,
1299        index,
1300    );
1301    let violation_count = results.boundary_violations.len()
1302        + results.boundary_coverage_violations.len()
1303        + results.boundary_call_violations.len()
1304        + results.policy_violations.len();
1305    let total_findings = violation_count
1306        + results.circular_dependencies.len()
1307        + results.re_export_cycles.len()
1308        + results.package_cycles.len();
1309    analysis_from_records(findings, total_findings, violation_count, "violations")
1310}
1311
1312fn build_dependencies(
1313    results: &AnalysisResults,
1314    index: &FileIndex<'_>,
1315    root: &Path,
1316) -> VizFindingAnalysis {
1317    let mut findings = Vec::new();
1318    let mut count = 0;
1319    macro_rules! add {
1320        ($field:ident, $kind:literal, $title:literal) => {
1321            count += results.$field.len();
1322            push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1323        };
1324    }
1325    add!(unresolved_imports, "unresolved-import", "Unresolved import");
1326    add!(
1327        unlisted_dependencies,
1328        "unlisted-dependency",
1329        "Unlisted dependency"
1330    );
1331    add!(unlisted_binaries, "unlisted-binary", "Unlisted binary");
1332    add!(
1333        type_only_dependencies,
1334        "type-only-dependency",
1335        "Type-only dependency"
1336    );
1337    add!(
1338        test_only_dependencies,
1339        "test-only-dependency",
1340        "Test-only dependency"
1341    );
1342    add!(
1343        dev_dependencies_in_production,
1344        "dev-dependency-in-production",
1345        "Development dependency used in production"
1346    );
1347    add!(
1348        duplicate_exports,
1349        "duplicate-export",
1350        "Duplicate public export"
1351    );
1352    add!(
1353        duplicate_export_aliases,
1354        "duplicate-export-alias",
1355        "Binding exported under several names"
1356    );
1357    add!(
1358        private_type_leaks,
1359        "private-type-leak",
1360        "Private type leaked by public API"
1361    );
1362    add!(
1363        deprecated_exports_in_use,
1364        "deprecated-export-in-use",
1365        "Deprecated export still in use"
1366    );
1367    add!(
1368        unused_catalog_entries,
1369        "unused-catalog-entry",
1370        "Unused catalog entry"
1371    );
1372    add!(
1373        empty_catalog_groups,
1374        "empty-catalog-group",
1375        "Empty catalog group"
1376    );
1377    add!(
1378        unresolved_catalog_references,
1379        "unresolved-catalog-reference",
1380        "Unresolved catalog reference"
1381    );
1382    add!(
1383        unused_dependency_overrides,
1384        "unused-dependency-override",
1385        "Unused dependency override"
1386    );
1387    add!(
1388        misconfigured_dependency_overrides,
1389        "misconfigured-dependency-override",
1390        "Misconfigured dependency override"
1391    );
1392    analysis_from_records(findings, count, count, "findings")
1393}
1394
1395fn build_frameworks(
1396    results: &AnalysisResults,
1397    index: &FileIndex<'_>,
1398    root: &Path,
1399) -> VizFrameworkData {
1400    let analysis = build_framework_findings(results, index, root);
1401    VizFrameworkData {
1402        availability: analysis.availability,
1403        detector_availability: VizAvailability::unavailable(
1404            "detectors",
1405            "Framework detector coverage did not complete",
1406        ),
1407        findings_truncated: analysis.findings_truncated,
1408        findings: analysis.findings,
1409        detected_frameworks: Vec::new(),
1410        detectors: Vec::new(),
1411    }
1412}
1413
1414/// Push the Effect framework findings and return how many were seen.
1415fn push_effect_findings(
1416    findings: &mut Vec<VizFinding>,
1417    results: &AnalysisResults,
1418    index: &FileIndex<'_>,
1419    root: &Path,
1420) -> usize {
1421    push_findings(
1422        findings,
1423        "unused-effect-layer",
1424        "Unused Effect layer",
1425        &results.unused_effect_layers,
1426        root,
1427        index,
1428    );
1429    push_findings(
1430        findings,
1431        "unused-tagged-error",
1432        "Unused tagged error",
1433        &results.unused_tagged_errors,
1434        root,
1435        index,
1436    );
1437    push_findings(
1438        findings,
1439        "unproduced-catch-tag",
1440        "Unproduced catch tag",
1441        &results.unproduced_catch_tags,
1442        root,
1443        index,
1444    );
1445    results.unused_effect_layers.len()
1446        + results.unused_tagged_errors.len()
1447        + results.unproduced_catch_tags.len()
1448}
1449
1450fn build_framework_findings(
1451    results: &AnalysisResults,
1452    index: &FileIndex<'_>,
1453    root: &Path,
1454) -> VizFindingAnalysis {
1455    let mut findings = Vec::new();
1456    let mut count = 0;
1457    macro_rules! add {
1458        ($field:ident, $kind:literal, $title:literal) => {
1459            count += results.$field.len();
1460            push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1461        };
1462    }
1463    add!(
1464        invalid_client_exports,
1465        "invalid-client-export",
1466        "Invalid client export"
1467    );
1468    add!(
1469        mixed_client_server_barrels,
1470        "mixed-client-server-barrel",
1471        "Mixed client/server barrel"
1472    );
1473    add!(
1474        misplaced_directives,
1475        "misplaced-directive",
1476        "Misplaced framework directive"
1477    );
1478    add!(
1479        unprovided_injects,
1480        "unprovided-inject",
1481        "Injected value is never provided"
1482    );
1483    add!(
1484        unrendered_components,
1485        "unrendered-component",
1486        "Component is never rendered"
1487    );
1488    add!(route_collisions, "route-collision", "Route collision");
1489    add!(
1490        dynamic_segment_name_conflicts,
1491        "dynamic-segment-conflict",
1492        "Dynamic segment conflict"
1493    );
1494    add!(
1495        unused_component_props,
1496        "unused-component-prop",
1497        "Unused component prop"
1498    );
1499    add!(
1500        absent_component_props,
1501        "absent-component-prop",
1502        "Optional prop review candidate"
1503    );
1504    add!(
1505        unused_component_emits,
1506        "unused-component-emit",
1507        "Unused component event"
1508    );
1509    add!(
1510        unused_component_inputs,
1511        "unused-component-input",
1512        "Unused component input"
1513    );
1514    add!(
1515        unused_component_outputs,
1516        "unused-component-output",
1517        "Unused component output"
1518    );
1519    add!(
1520        unused_svelte_events,
1521        "unused-svelte-event",
1522        "Unused Svelte event"
1523    );
1524    count += push_effect_findings(&mut findings, results, index, root);
1525    add!(
1526        unused_server_actions,
1527        "unused-server-action",
1528        "Unused server action"
1529    );
1530    add!(
1531        unused_load_data_keys,
1532        "unused-load-data-key",
1533        "Unused load-data key"
1534    );
1535    add!(prop_drilling_chains, "prop-drilling", "Prop-drilling chain");
1536    add!(thin_wrappers, "thin-wrapper", "Thin component wrapper");
1537    add!(
1538        duplicate_prop_shapes,
1539        "duplicate-prop-shape",
1540        "Duplicate prop shape"
1541    );
1542    let mut analysis = analysis_from_records(findings, count, count, "findings");
1543    if results.unused_load_data_keys_global_abstain {
1544        analysis.availability.reason = Some(
1545            "Load-data-key analysis abstained because whole-object page data usage was detected"
1546                .to_string(),
1547        );
1548    }
1549    analysis
1550}
1551
1552fn build_feature_flags(
1553    flags: &[FeatureFlag],
1554    index: &FileIndex<'_>,
1555    root: &Path,
1556) -> VizFindingAnalysis {
1557    let mut findings = Vec::new();
1558    push_findings(
1559        &mut findings,
1560        "feature-flag",
1561        "Feature flag use",
1562        flags,
1563        root,
1564        index,
1565    );
1566    analysis_from_records(findings, flags.len(), flags.len(), "flags")
1567}
1568
1569fn build_security(
1570    results: &AnalysisResults,
1571    index: &FileIndex<'_>,
1572    root: &Path,
1573) -> VizSecurityData {
1574    let total = results.security_findings.len();
1575    let truncated =
1576        (total > MAX_ANALYSIS_FINDINGS).then_some(total.saturating_sub(MAX_ANALYSIS_FINDINGS));
1577    let mut sorted_findings: Vec<&SecurityFinding> = results.security_findings.iter().collect();
1578    sorted_findings.sort_by_key(|finding| {
1579        let severity = serialized_label(&crate::security::derive_security_severity(finding));
1580        let priority = match severity.as_str() {
1581            "high" => 0,
1582            "medium" => 1,
1583            _ => 2,
1584        };
1585        (priority, relative_path(&finding.path, root), finding.line)
1586    });
1587    let candidates = sorted_findings
1588        .into_iter()
1589        .take(MAX_ANALYSIS_FINDINGS)
1590        .map(|finding| build_security_candidate(finding, index, root))
1591        .collect();
1592
1593    let mut blind_spots = Vec::new();
1594    if results.security_unresolved_edge_files > 0 {
1595        blind_spots.push(VizSecurityBlindSpot {
1596            kind: "unresolved-dynamic-imports".to_string(),
1597            count: results.security_unresolved_edge_files,
1598            path: None,
1599            file: None,
1600            line: None,
1601            reason: Some("Dynamic imports prevent complete client/server reachability".to_string()),
1602        });
1603    }
1604    if results.security_unresolved_callee_sites > 0 {
1605        blind_spots.push(VizSecurityBlindSpot {
1606            kind: "unresolved-callee-sites".to_string(),
1607            count: results.security_unresolved_callee_sites,
1608            path: None,
1609            file: None,
1610            line: None,
1611            reason: Some(
1612                "Dynamic or computed callees could not be matched to the sink catalogue"
1613                    .to_string(),
1614            ),
1615        });
1616    }
1617    let diagnostic_count = results.security_unresolved_callee_diagnostics.len();
1618    for diagnostic in results
1619        .security_unresolved_callee_diagnostics
1620        .iter()
1621        .take(MAX_SECURITY_BLIND_SPOT_SAMPLES)
1622    {
1623        blind_spots.push(VizSecurityBlindSpot {
1624            kind: "unresolved-callee-sample".to_string(),
1625            count: 1,
1626            path: Some(relative_path(&diagnostic.path, root)),
1627            file: index.index_of_path(&diagnostic.path),
1628            line: Some(diagnostic.line),
1629            reason: Some(serialized_label(&diagnostic.reason)),
1630        });
1631    }
1632
1633    VizSecurityData {
1634        availability: VizAvailability::complete(total, "candidates", truncated),
1635        runtime_availability: VizAvailability::unavailable(
1636            "observations",
1637            NO_RUNTIME_COVERAGE_REASON,
1638        ),
1639        candidates,
1640        blind_spot_count: results.security_unresolved_edge_files
1641            + results.security_unresolved_callee_sites,
1642        blind_spots_truncated: (diagnostic_count > MAX_SECURITY_BLIND_SPOT_SAMPLES)
1643            .then_some(diagnostic_count.saturating_sub(MAX_SECURITY_BLIND_SPOT_SAMPLES)),
1644        blind_spots,
1645    }
1646}
1647
1648fn build_security_candidate(
1649    finding: &SecurityFinding,
1650    index: &FileIndex<'_>,
1651    root: &Path,
1652) -> VizSecurityCandidate {
1653    let kind = serialized_label(&finding.kind);
1654    let path = relative_path(&finding.path, root);
1655    let severity = serialized_label(&crate::security::derive_security_severity(finding));
1656    // The engine session stamps `finding_id` right after detection, so viz
1657    // reads the same id as the JSON and SARIF output.
1658    let id = finding.finding_id.clone();
1659    let reachability = finding.reachability.as_ref();
1660    let architecture_zone = finding
1661        .candidate
1662        .boundary
1663        .architecture_zone
1664        .as_ref()
1665        .map(|zone| format!("{} -> {}", zone.from, zone.to));
1666    let dead_code = serialize_relative(finding.dead_code.as_ref(), root);
1667    let runtime = serialize_relative(finding.runtime.as_ref(), root);
1668    let taint_flow = security_taint_flow(finding, index, root);
1669    let observed_controls = security_controls(finding, root);
1670    let actions = serialize_relative_value(&finding.actions, root)
1671        .unwrap_or_else(|| Value::Array(Vec::new()));
1672    let trace = security_trace(finding, index, root);
1673    let taint_trace = finding
1674        .reachability
1675        .as_ref()
1676        .map_or_else(Vec::new, |reachability| {
1677            trace_hops(&reachability.untrusted_source_trace, index, root)
1678        });
1679    VizSecurityCandidate {
1680        id,
1681        kind,
1682        category: finding.category.clone(),
1683        cwe: finding.cwe,
1684        file: index.index_of_path(&finding.path),
1685        path,
1686        line: finding.line,
1687        col: finding.col,
1688        evidence: finding.evidence.clone(),
1689        severity,
1690        taint_confidence: reachability
1691            .and_then(|reachability| reachability.taint_confidence.as_ref())
1692            .map(serialized_label),
1693        source_kind: finding.candidate.source_kind.clone(),
1694        sink: finding.candidate.sink.callee.clone(),
1695        url_shape: finding
1696            .candidate
1697            .sink
1698            .url_shape
1699            .as_ref()
1700            .map(serialized_label),
1701        network_destination: finding
1702            .candidate
1703            .network
1704            .as_ref()
1705            .and_then(|network| network.destination.clone()),
1706        reachable_from_entry: reachability.map(|value| value.reachable_from_entry),
1707        reachable_from_untrusted_source: reachability
1708            .map(|value| value.reachable_from_untrusted_source),
1709        blast_radius: reachability.map(|value| value.blast_radius),
1710        crosses_boundary: reachability.is_some_and(|value| value.crosses_boundary)
1711            || finding.candidate.boundary.client_server
1712            || finding.candidate.boundary.cross_module
1713            || architecture_zone.is_some(),
1714        client_server_boundary: finding.candidate.boundary.client_server,
1715        cross_module_boundary: finding.candidate.boundary.cross_module,
1716        architecture_zone,
1717        dead_code,
1718        runtime,
1719        taint_flow,
1720        observed_controls,
1721        control_verification_prompt: finding
1722            .attack_surface
1723            .as_ref()
1724            .map(|surface| surface.defensive_boundary.verification_prompt.clone()),
1725        trace,
1726        taint_trace,
1727        actions,
1728    }
1729}
1730
1731fn serialize_relative<T: Serialize>(value: Option<&T>, root: &Path) -> Option<Value> {
1732    value.and_then(|value| serialize_relative_value(value, root))
1733}
1734
1735fn serialize_relative_value<T: Serialize>(value: &T, root: &Path) -> Option<Value> {
1736    let mut serialized = serde_json::to_value(value).ok()?;
1737    relativize_value_paths(&mut serialized, root);
1738    Some(serialized)
1739}
1740
1741fn security_controls(finding: &SecurityFinding, root: &Path) -> Vec<Value> {
1742    finding
1743        .attack_surface
1744        .as_ref()
1745        .map_or_else(Vec::new, |surface| {
1746            surface
1747                .defensive_boundary
1748                .controls
1749                .iter()
1750                .filter_map(|control| serialize_relative_value(control, root))
1751                .collect()
1752        })
1753}
1754
1755fn security_trace(
1756    finding: &SecurityFinding,
1757    index: &FileIndex<'_>,
1758    root: &Path,
1759) -> Vec<VizSecurityTraceHop> {
1760    trace_hops(&finding.trace, index, root)
1761}
1762
1763fn trace_hops(
1764    hops: &[fallow_types::results::TraceHop],
1765    index: &FileIndex<'_>,
1766    root: &Path,
1767) -> Vec<VizSecurityTraceHop> {
1768    hops.iter()
1769        .map(|hop| VizSecurityTraceHop {
1770            file: index.index_of_path(&hop.path),
1771            path: relative_path(&hop.path, root),
1772            line: hop.line,
1773            col: hop.col,
1774            role: serialized_label(&hop.role),
1775        })
1776        .collect()
1777}
1778
1779fn security_taint_flow(
1780    finding: &SecurityFinding,
1781    index: &FileIndex<'_>,
1782    root: &Path,
1783) -> Option<VizSecurityTaintFlow> {
1784    let flow = finding.taint_flow.as_ref()?;
1785    let endpoint = |value: &fallow_types::results::TaintEndpoint| VizSecurityEndpoint {
1786        file: index.index_of_path(&value.path),
1787        path: relative_path(&value.path, root),
1788        line: value.line,
1789        col: value.col,
1790    };
1791    Some(VizSecurityTaintFlow {
1792        source: endpoint(&flow.source),
1793        sink: endpoint(&flow.sink),
1794        intra_module: flow.path.intra_module,
1795        cross_module_hops: flow.path.cross_module_hops,
1796    })
1797}
1798
1799/// Populate Health, Framework diagnostics, and Styling from the health runner
1800/// that consumed the same session artifacts.
1801pub fn apply_health_report(data: &mut VizData, report: &HealthReport, root: &Path) {
1802    let by_path: FxHashMap<String, u32> = data
1803        .files
1804        .iter()
1805        .enumerate()
1806        .map(|(index, file)| (file.path.clone(), clamp_u32(index)))
1807        .collect();
1808    apply_health_data(data, report, root, &by_path);
1809    apply_framework_data(data, report);
1810    apply_styling_data(data, report, root, &by_path);
1811}
1812
1813fn apply_health_data(
1814    data: &mut VizData,
1815    report: &HealthReport,
1816    root: &Path,
1817    by_path: &FxHashMap<String, u32>,
1818) {
1819    let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1820    let hotspot_by_path: FxHashMap<String, &fallow_output::HotspotFinding> = report
1821        .hotspots
1822        .iter()
1823        .map(|hotspot| (relative_path(&hotspot.path, root), hotspot))
1824        .collect();
1825    let files = health_files(report, root, by_path, &hotspot_by_path);
1826    let (findings, total_findings) = health_findings(report, root, &resolve);
1827    let concern_count = health_concern_count(report, root, by_path);
1828    data.health = VizHealthData {
1829        availability: VizAvailability::complete(concern_count, "files", None),
1830        capabilities: health_capabilities(report),
1831        shared_parse: data.health.shared_parse,
1832        score: report.health_score.as_ref().map(|score| score.score),
1833        grade: report
1834            .health_score
1835            .as_ref()
1836            .map(|score| score.grade.to_string()),
1837        average_maintainability: report.summary.average_maintainability,
1838        files_truncated: report
1839            .file_scores
1840            .len()
1841            .checked_sub(MAX_HEALTH_FILES)
1842            .filter(|count| *count > 0),
1843        findings_truncated: total_findings
1844            .checked_sub(findings.len())
1845            .filter(|count| *count > 0),
1846        files,
1847        findings,
1848    };
1849}
1850
1851fn health_concern_count(
1852    report: &HealthReport,
1853    root: &Path,
1854    by_path: &FxHashMap<String, u32>,
1855) -> usize {
1856    let mut files = rustc_hash::FxHashSet::default();
1857    let mut add = |path: &Path| {
1858        if let Some(file) = by_path.get(&relative_path(path, root)) {
1859            files.insert(*file);
1860        }
1861    };
1862    for finding in &report.findings {
1863        add(&finding.path);
1864    }
1865    for hotspot in &report.hotspots {
1866        add(&hotspot.path);
1867    }
1868    if let Some(gaps) = &report.coverage_gaps {
1869        for finding in &gaps.files {
1870            add(&finding.file.path);
1871        }
1872        for finding in &gaps.exports {
1873            add(&finding.export.path);
1874        }
1875    }
1876    files.len()
1877}
1878
1879fn health_files(
1880    report: &HealthReport,
1881    root: &Path,
1882    by_path: &FxHashMap<String, u32>,
1883    hotspots: &FxHashMap<String, &fallow_output::HotspotFinding>,
1884) -> Vec<VizHealthFile> {
1885    report
1886        .file_scores
1887        .iter()
1888        .take(MAX_HEALTH_FILES)
1889        .filter_map(|score| {
1890            let path = relative_path(&score.path, root);
1891            let file = by_path.get(&path).copied()?;
1892            let hotspot = hotspots.get(&path).copied();
1893            Some(VizHealthFile {
1894                file,
1895                path,
1896                maintainability_index: score.maintainability_index,
1897                crap_max: score.crap_max,
1898                complexity_density: score.complexity_density,
1899                fan_in: score.fan_in,
1900                fan_out: score.fan_out,
1901                hotspot_score: hotspot.map(|entry| entry.score),
1902                commits: hotspot.map(|entry| entry.commits),
1903                ownership: hotspot
1904                    .and_then(|entry| serialize_relative(entry.ownership.as_ref(), root)),
1905            })
1906        })
1907        .collect()
1908}
1909
1910fn health_findings(
1911    report: &HealthReport,
1912    root: &Path,
1913    resolve: &dyn Fn(&Path) -> Option<u32>,
1914) -> (Vec<VizFinding>, usize) {
1915    let coverage_count = report
1916        .coverage_gaps
1917        .as_ref()
1918        .map_or(0, |gaps| gaps.files.len() + gaps.exports.len());
1919    let total = report.findings.len() + report.hotspots.len() + coverage_count;
1920    let mut findings = Vec::with_capacity(total.min(MAX_ANALYSIS_FINDINGS));
1921    append_findings(
1922        &mut findings,
1923        &report.findings,
1924        "health-finding",
1925        "Health threshold exceeded",
1926        root,
1927        resolve,
1928    );
1929    append_findings(
1930        &mut findings,
1931        &report.hotspots,
1932        "git-hotspot",
1933        "Complex and frequently changed file",
1934        root,
1935        resolve,
1936    );
1937    if let Some(gaps) = &report.coverage_gaps {
1938        append_findings(
1939            &mut findings,
1940            &gaps.files,
1941            "coverage-gap-file",
1942            "File has no test path",
1943            root,
1944            resolve,
1945        );
1946        append_findings(
1947            &mut findings,
1948            &gaps.exports,
1949            "coverage-gap-export",
1950            "Export has no test path",
1951            root,
1952            resolve,
1953        );
1954    }
1955    (findings, total)
1956}
1957
1958fn append_findings<T: Serialize>(
1959    out: &mut Vec<VizFinding>,
1960    values: &[T],
1961    kind: &str,
1962    title: &str,
1963    root: &Path,
1964    resolve: &dyn Fn(&Path) -> Option<u32>,
1965) {
1966    let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
1967    out.extend(values.iter().take(remaining).filter_map(|value| {
1968        serde_json::to_value(value)
1969            .ok()
1970            .map(|detail| finding_from_value(kind, title, detail, root, resolve))
1971    }));
1972}
1973
1974fn health_capabilities(report: &HealthReport) -> VizHealthCapabilities {
1975    let file_count = report.file_scores.len();
1976    let coverage = report.coverage_gaps.as_ref().map_or_else(
1977        || VizAvailability::unavailable("gaps", "Coverage gap analysis did not produce a result"),
1978        |gaps| VizAvailability::complete(gaps.files.len() + gaps.exports.len(), "gaps", None),
1979    );
1980    let runtime = report.runtime_coverage.as_ref().map_or_else(
1981        || VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1982        |runtime| {
1983            VizAvailability::complete(runtime.summary.observed_functions(), "observations", None)
1984        },
1985    );
1986    VizHealthCapabilities {
1987        complexity: VizAvailability::complete(report.findings.len(), "findings", None),
1988        maintainability: VizAvailability::complete(file_count, "files", None),
1989        crap: VizAvailability::complete(file_count, "files", None),
1990        coverage,
1991        runtime,
1992        churn: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1993        hotspots: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1994        ownership: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1995    }
1996}
1997
1998fn unavailable_health_capabilities(reason: &str) -> VizHealthCapabilities {
1999    VizHealthCapabilities {
2000        complexity: VizAvailability::unavailable("findings", reason),
2001        maintainability: VizAvailability::unavailable("files", reason),
2002        crap: VizAvailability::unavailable("files", reason),
2003        coverage: VizAvailability::unavailable("gaps", reason),
2004        runtime: VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
2005        churn: VizAvailability::unavailable("files", reason),
2006        hotspots: VizAvailability::unavailable("files", reason),
2007        ownership: VizAvailability::unavailable("files", reason),
2008    }
2009}
2010
2011fn apply_framework_data(data: &mut VizData, report: &HealthReport) {
2012    let count = data.frameworks.availability.count;
2013    let Some(diagnostics) = &report.framework_health else {
2014        if count == 0 {
2015            data.frameworks.detector_availability = VizAvailability {
2016                state: VizAvailabilityState::NotApplicable,
2017                count: 0,
2018                unit: "detectors",
2019                reason: Some("No supported framework was detected".to_string()),
2020                truncated: None,
2021            };
2022            data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
2023            data.frameworks.availability.reason =
2024                Some("No supported framework was detected".to_string());
2025        } else {
2026            data.frameworks.detector_availability = VizAvailability::unavailable(
2027                "detectors",
2028                "Framework detector metadata was not produced",
2029            );
2030        }
2031        return;
2032    };
2033    data.frameworks
2034        .detected_frameworks
2035        .clone_from(&diagnostics.detected_frameworks);
2036    data.frameworks.detectors = diagnostics
2037        .detectors
2038        .iter()
2039        .map(|detector| VizFrameworkDetector {
2040            id: detector.id.clone(),
2041            framework: detector.framework.clone(),
2042            status: serialized_label(&detector.status),
2043            reason: detector.reason.clone(),
2044        })
2045        .collect();
2046    data.frameworks.detector_availability =
2047        VizAvailability::complete(diagnostics.detectors.len(), "detectors", None);
2048    if diagnostics.detected_frameworks.is_empty() && count == 0 {
2049        data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
2050        data.frameworks.availability.reason =
2051            Some("No supported framework was detected".to_string());
2052        data.frameworks.detector_availability.state = VizAvailabilityState::NotApplicable;
2053        data.frameworks.detector_availability.reason =
2054            Some("No supported framework was detected".to_string());
2055    }
2056}
2057
2058fn apply_styling_data(
2059    data: &mut VizData,
2060    report: &HealthReport,
2061    root: &Path,
2062    by_path: &FxHashMap<String, u32>,
2063) {
2064    let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
2065    let count = report.styling_findings.len();
2066    let mut findings = Vec::with_capacity(count.min(MAX_ANALYSIS_FINDINGS));
2067    append_findings(
2068        &mut findings,
2069        &report.styling_findings,
2070        "styling-finding",
2071        "Styling health finding",
2072        root,
2073        &resolve,
2074    );
2075    let truncated = count.checked_sub(findings.len()).filter(|value| *value > 0);
2076    let styling = report.styling_health.as_ref();
2077    data.styling = VizStylingData {
2078        availability: report.css_analytics.as_ref().map_or_else(
2079            || VizAvailability {
2080                state: VizAvailabilityState::NotApplicable,
2081                count: 0,
2082                unit: "findings",
2083                reason: Some("No supported CSS or component styling was detected".to_string()),
2084                truncated: None,
2085            },
2086            |_| VizAvailability::complete(count, "findings", truncated),
2087        ),
2088        findings_truncated: truncated,
2089        findings,
2090        score: styling.map(|health| health.score),
2091        grade: styling.map(|health| health.grade.to_string()),
2092        confidence: styling.map(|health| serialized_label(&health.confidence)),
2093        summary: report
2094            .css_analytics
2095            .as_ref()
2096            .and_then(|analytics| serde_json::to_value(&analytics.summary).ok()),
2097    };
2098}
2099
2100/// Per-file lookup maps threaded into [`build_files`].
2101struct FilePropertyMaps<'a> {
2102    zone_by_file: &'a FxHashMap<u32, u16>,
2103    clone_groups_by_file: &'a FxHashMap<u32, Vec<u32>>,
2104    dup_lines_by_file: &'a FxHashMap<u32, u32>,
2105    cycles: &'a [Vec<u32>],
2106}
2107
2108fn display_root(root: &Path) -> String {
2109    root.file_name().map_or_else(
2110        || root.to_string_lossy().into_owned(),
2111        |n| n.to_string_lossy().into_owned(),
2112    )
2113}
2114
2115fn relative_path(path: &Path, root: &Path) -> String {
2116    if let Ok(relative) = path.strip_prefix(root) {
2117        return relative.to_string_lossy().replace('\\', "/");
2118    }
2119    // has_root, not is_absolute: on Windows a drive-less rooted path such as
2120    // `\\Users\\private\\secret.ts` is rooted but NOT absolute, so gating on
2121    // is_absolute let it skip redaction and leak the full path into the payload.
2122    // has_root is a strict superset and covers `C:\\...` and `/...` alike.
2123    if path.has_root() {
2124        let name = path
2125            .file_name()
2126            .map_or_else(|| "path".into(), |name| name.to_string_lossy());
2127        return format!("<external>/{name}");
2128    }
2129    path.to_string_lossy().replace('\\', "/")
2130}
2131
2132fn build_workspaces(workspaces: &[WorkspaceInfo], root: &Path) -> Vec<VizWorkspace> {
2133    workspaces
2134        .iter()
2135        .map(|ws| VizWorkspace {
2136            name: ws.name.clone(),
2137            root: relative_path(&ws.root, root),
2138        })
2139        .collect()
2140}
2141
2142fn workspace_index_for(path: &Path, workspaces: &[WorkspaceInfo]) -> Option<u16> {
2143    let mut best: Option<(usize, usize)> = None;
2144    for (i, ws) in workspaces.iter().enumerate() {
2145        if path.starts_with(&ws.root) {
2146            let depth = ws.root.components().count();
2147            if best.is_none_or(|(_, d)| depth > d) {
2148                best = Some((i, depth));
2149            }
2150        }
2151    }
2152    best.map(|(i, _)| clamp_u16(i))
2153}
2154
2155fn classify_zones(
2156    input: &VizBuildInput<'_>,
2157    index: &FileIndex<'_>,
2158) -> (Vec<VizZone>, FxHashMap<u32, u16>) {
2159    let boundaries = &input.config.boundaries;
2160    let mut zones: Vec<VizZone> = boundaries
2161        .zones
2162        .iter()
2163        .map(|z| VizZone {
2164            name: z.name.clone(),
2165            files: 0,
2166        })
2167        .collect();
2168    let name_to_index: FxHashMap<&str, u16> = boundaries
2169        .zones
2170        .iter()
2171        .enumerate()
2172        .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2173        .collect();
2174
2175    let mut zone_by_file = FxHashMap::default();
2176    if zones.is_empty() {
2177        return (zones, zone_by_file);
2178    }
2179
2180    for (i, file) in index.ordered.iter().enumerate() {
2181        let rel = relative_path(&file.path, &input.config.root);
2182        if let Some(zone_name) = boundaries.classify_zone(&rel)
2183            && let Some(&zone_idx) = name_to_index.get(zone_name)
2184        {
2185            zone_by_file.insert(clamp_u32(i), zone_idx);
2186            zones[zone_idx as usize].files += 1;
2187        }
2188    }
2189
2190    (zones, zone_by_file)
2191}
2192
2193/// Clone payload maps: kept groups, per-file group ids, per-file duplicated
2194/// lines, and how many kept-groups the payload cap dropped.
2195type CloneMaps = (
2196    Vec<VizCloneGroup>,
2197    FxHashMap<u32, Vec<u32>>,
2198    FxHashMap<u32, u32>,
2199    u32,
2200);
2201
2202fn build_clones(
2203    duplication: &DuplicationReport,
2204    index: &FileIndex<'_>,
2205    max_groups: usize,
2206) -> CloneMaps {
2207    let mut clones = Vec::new();
2208    let mut groups_by_file: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
2209    let mut dup_lines_by_file: FxHashMap<u32, u32> = FxHashMap::default();
2210    let mut truncated: usize = 0;
2211
2212    for group in &duplication.clone_groups {
2213        let instances: Vec<VizCloneInstance> = group
2214            .instances
2215            .iter()
2216            .filter_map(|inst| {
2217                index
2218                    .index_of_path(&inst.file)
2219                    .map(|file| VizCloneInstance {
2220                        file,
2221                        start_line: clamp_u32(inst.start_line),
2222                        end_line: clamp_u32(inst.end_line),
2223                    })
2224            })
2225            .collect();
2226        if instances.len() < 2 {
2227            continue;
2228        }
2229        if clones.len() >= max_groups {
2230            truncated += 1;
2231            continue;
2232        }
2233
2234        let group_idx = clamp_u32(clones.len());
2235        for inst in &instances {
2236            let entry = groups_by_file.entry(inst.file).or_default();
2237            if entry.last() != Some(&group_idx) {
2238                entry.push(group_idx);
2239            }
2240            *dup_lines_by_file.entry(inst.file).or_default() +=
2241                inst.end_line.saturating_sub(inst.start_line) + 1;
2242        }
2243
2244        let (preview, highlight_start, highlight_lines) = group
2245            .instances
2246            .first()
2247            .map(build_clone_preview)
2248            .unwrap_or_default();
2249
2250        clones.push(VizCloneGroup {
2251            lines: group.line_count,
2252            tokens: group.token_count,
2253            instances,
2254            preview,
2255            highlight_start,
2256            highlight_lines,
2257        });
2258    }
2259
2260    (
2261        clones,
2262        groups_by_file,
2263        dup_lines_by_file,
2264        clamp_u32(truncated),
2265    )
2266}
2267
2268fn truncate_preview(fragment: &str) -> String {
2269    let mut out = String::new();
2270    for (i, line) in fragment.lines().enumerate() {
2271        if i >= CLONE_PREVIEW_MAX_LINES || out.len() + line.len() > CLONE_PREVIEW_MAX_BYTES {
2272            out.push('\u{2026}');
2273            break;
2274        }
2275        if i > 0 {
2276            out.push('\n');
2277        }
2278        out.push_str(line);
2279    }
2280    out
2281}
2282
2283/// Build the representative clone preview: a context window around the
2284/// duplicated block, with the highlight range located within it. Returns
2285/// `(preview, highlight_start, highlight_lines)` where `highlight_start`
2286/// is the 0-based index of the first copied line among the preview lines
2287/// and `highlight_lines` is the copied line count present in `preview`.
2288///
2289/// Falls back to the bare fragment with the whole block highlighted on
2290/// any read failure, empty source, or an out-of-range line span. Never
2291/// panics.
2292fn build_clone_preview(inst: &CloneInstance) -> (String, u32, u32) {
2293    let Ok(source) = std::fs::read_to_string(&inst.file) else {
2294        return fragment_fallback(&inst.fragment);
2295    };
2296    let lines: Vec<&str> = source.lines().collect();
2297    let total = lines.len();
2298    if total == 0 || inst.start_line == 0 || inst.start_line > total {
2299        return fragment_fallback(&inst.fragment);
2300    }
2301
2302    // Block bounds as a 0-based `[block_start, block_end)` range, clamped
2303    // to the file and guaranteed to hold at least one line.
2304    let block_start = inst.start_line - 1;
2305    let block_end = inst.end_line.min(total).max(inst.start_line);
2306    let mut block_lines = block_end - block_start;
2307    let mut before = block_start.min(CLONE_PREVIEW_CONTEXT);
2308    let mut after = (total - block_end).min(CLONE_PREVIEW_CONTEXT);
2309
2310    // Line cap: when the block plus its context fits, trim context
2311    // symmetrically to fit. When the block alone fills the cap, keep the
2312    // leading context (so the highlight always reads against some dimmed
2313    // lines) and truncate the block's tail, always keeping >= 1 block line.
2314    if before + block_lines + after > CLONE_PREVIEW_MAX_LINES {
2315        if before + block_lines >= CLONE_PREVIEW_MAX_LINES {
2316            after = 0;
2317            block_lines = CLONE_PREVIEW_MAX_LINES.saturating_sub(before).max(1);
2318        } else {
2319            trim_context(
2320                &mut before,
2321                &mut after,
2322                CLONE_PREVIEW_MAX_LINES - block_lines,
2323            );
2324        }
2325    }
2326
2327    enforce_byte_cap(
2328        &lines,
2329        block_start,
2330        &mut before,
2331        &mut after,
2332        &mut block_lines,
2333    );
2334
2335    let win_start = block_start - before;
2336    let win_end = win_start + before + block_lines + after;
2337    let preview = lines[win_start..win_end].join("\n");
2338    (preview, clamp_u32(before), clamp_u32(block_lines))
2339}
2340
2341/// Fallback preview: the bare fragment, capped, with the whole block
2342/// highlighted (nothing dimmed).
2343fn fragment_fallback(fragment: &str) -> (String, u32, u32) {
2344    let preview = truncate_preview(fragment);
2345    let highlight_lines = if preview.is_empty() {
2346        0
2347    } else {
2348        preview.lines().count()
2349    };
2350    (preview, 0, clamp_u32(highlight_lines))
2351}
2352
2353/// Reduce `before`/`after` so their sum fits `budget`, dropping from the
2354/// larger side first (ties favor keeping `after`) so the two flanks stay
2355/// balanced. Deterministic.
2356fn trim_context(before: &mut usize, after: &mut usize, budget: usize) {
2357    while *before + *after > budget {
2358        if *before >= *after {
2359            *before -= 1;
2360        } else {
2361            *after -= 1;
2362        }
2363    }
2364}
2365
2366/// Trim the preview window to `CLONE_PREVIEW_MAX_BYTES`, dropping context
2367/// lines (larger side first) before ever cutting into the highlighted
2368/// block. If the block alone still overflows, its tail lines are dropped,
2369/// but at least one line is always kept.
2370fn enforce_byte_cap(
2371    lines: &[&str],
2372    block_start: usize,
2373    before: &mut usize,
2374    after: &mut usize,
2375    block_lines: &mut usize,
2376) {
2377    let window_bytes = |before: usize, after: usize, block_lines: usize| -> usize {
2378        let start = block_start - before;
2379        let end = start + before + block_lines + after;
2380        let separators = (end - start).saturating_sub(1);
2381        lines[start..end].iter().map(|l| l.len()).sum::<usize>() + separators
2382    };
2383    while window_bytes(*before, *after, *block_lines) > CLONE_PREVIEW_MAX_BYTES {
2384        if *before + *after > 0 {
2385            if *before >= *after {
2386                *before -= 1;
2387            } else {
2388                *after -= 1;
2389            }
2390        } else if *block_lines > 1 {
2391            *block_lines -= 1;
2392        } else {
2393            break;
2394        }
2395    }
2396}
2397
2398fn build_cycles(results: &AnalysisResults, index: &FileIndex<'_>) -> Vec<Vec<u32>> {
2399    results
2400        .circular_dependencies
2401        .iter()
2402        .filter_map(|cd| {
2403            let ids: Vec<u32> = cd
2404                .cycle
2405                .files
2406                .iter()
2407                .filter_map(|p| index.index_of_path(p))
2408                .collect();
2409            (ids.len() == cd.cycle.files.len()).then_some(ids)
2410        })
2411        .collect()
2412}
2413
2414fn build_violations(
2415    results: &AnalysisResults,
2416    zones: &[VizZone],
2417    index: &FileIndex<'_>,
2418) -> Vec<VizViolation> {
2419    let name_to_index: FxHashMap<&str, u16> = zones
2420        .iter()
2421        .enumerate()
2422        .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2423        .collect();
2424
2425    results
2426        .boundary_violations
2427        .iter()
2428        .filter_map(|finding| {
2429            let v = &finding.violation;
2430            let from = index.index_of_path(&v.from_path)?;
2431            let to = index.index_of_path(&v.to_path)?;
2432            let from_zone = *name_to_index.get(v.from_zone.as_str())?;
2433            let to_zone = *name_to_index.get(v.to_zone.as_str())?;
2434            Some(VizViolation {
2435                from,
2436                to,
2437                from_zone,
2438                to_zone,
2439                line: v.line,
2440                specifier: v.import_specifier.clone(),
2441            })
2442        })
2443        .collect()
2444}
2445
2446fn build_edges(graph: &RetainedModuleGraph, index: &FileIndex<'_>) -> Vec<[u32; 3]> {
2447    let graph = graph.as_graph();
2448    let mut edges = Vec::with_capacity(graph.edge_count());
2449    for node in &graph.modules {
2450        let Some(source) = index.index_of_file_id(node.file_id.0) else {
2451            continue;
2452        };
2453        for (target_id, symbols) in graph.outgoing_symbol_edges(node.file_id) {
2454            let Some(target) = index.index_of_file_id(target_id.0) else {
2455                continue;
2456            };
2457            let all_type_only = !symbols.is_empty() && symbols.iter().all(|s| s.is_type_only);
2458            let flags = if all_type_only {
2459                EDGE_FLAG_TYPE_ONLY
2460            } else if symbols.iter().any(|s| s.is_eager_value()) {
2461                0
2462            } else {
2463                EDGE_FLAG_DYNAMIC
2464            };
2465            edges.push([source, target, flags]);
2466        }
2467    }
2468    edges
2469}
2470
2471/// Complexity aggregates for one file, folded from its parsed functions.
2472#[derive(Default)]
2473struct ComplexityRollup {
2474    fn_count: u16,
2475    max_cyclomatic: u16,
2476    max_cognitive: u16,
2477    react_hooks: u16,
2478    jsx_depth: u16,
2479    functions: Vec<VizFunction>,
2480}
2481
2482fn rollup_complexity(functions: &[FunctionComplexity]) -> ComplexityRollup {
2483    let mut rollup = ComplexityRollup {
2484        fn_count: clamp_u16(functions.len()),
2485        ..ComplexityRollup::default()
2486    };
2487    for f in functions {
2488        rollup.max_cyclomatic = rollup.max_cyclomatic.max(f.cyclomatic);
2489        rollup.max_cognitive = rollup.max_cognitive.max(f.cognitive);
2490        rollup.react_hooks = rollup.react_hooks.saturating_add(f.react_hook_count);
2491        rollup.jsx_depth = rollup.jsx_depth.max(f.react_jsx_max_depth);
2492    }
2493
2494    // Named functions only, hardest-first: the panel lists these and folds the
2495    // (often many) anonymous arrow/callback functions into a single count via
2496    // `fn_count`. Placeholder names for unnamed functions are `<arrow>` /
2497    // `<anonymous>`, so a leading `<` marks the ones to fold away.
2498    let mut named: Vec<&FunctionComplexity> = functions
2499        .iter()
2500        .filter(|f| !f.name.starts_with('<'))
2501        .collect();
2502    named.sort_by(|a, b| {
2503        b.cyclomatic
2504            .cmp(&a.cyclomatic)
2505            .then(b.cognitive.cmp(&a.cognitive))
2506    });
2507    rollup.functions = named
2508        .into_iter()
2509        .map(|f| VizFunction {
2510            name: f.name.clone(),
2511            line: f.line,
2512            cyclomatic: f.cyclomatic,
2513            cognitive: f.cognitive,
2514            lines: f.line_count,
2515            hooks: f.react_hook_count,
2516            jsx_depth: f.react_jsx_max_depth,
2517            props: f.react_prop_count,
2518        })
2519        .collect();
2520    rollup
2521}
2522
2523fn build_summary(
2524    input: &VizBuildInput<'_>,
2525    files: &[VizFile],
2526    clones: &[VizCloneGroup],
2527    cycles: &[Vec<u32>],
2528    violations: &[VizViolation],
2529    clone_groups_truncated: u32,
2530) -> VizSummary {
2531    let results = input.results;
2532    VizSummary {
2533        total_files: files.len(),
2534        total_size: files.iter().map(|f| f.size).sum(),
2535        total_edges: input.graph.edge_count(),
2536        unused_files: results.unused_files.len(),
2537        unused_exports: results.unused_exports.len() + results.unused_types.len(),
2538        unused_types: results.unused_types.len(),
2539        unused_deps: results.unused_dependencies.len()
2540            + results.unused_dev_dependencies.len()
2541            + results.unused_optional_dependencies.len(),
2542        unresolved_imports: results.unresolved_imports.len(),
2543        circular_deps: cycles.len(),
2544        clone_groups: clones.len(),
2545        duplicated_lines: clones.iter().map(|c| c.lines * c.instances.len()).sum(),
2546        boundary_violations: violations.len(),
2547        hotspot_files: files
2548            .iter()
2549            .filter(|f| f.max_cyclomatic >= HOTSPOT_CYCLOMATIC_FLOOR)
2550            .count(),
2551        clone_groups_truncated: (clone_groups_truncated > 0).then_some(clone_groups_truncated),
2552    }
2553}
2554
2555fn clamp_u16(value: usize) -> u16 {
2556    u16::try_from(value).unwrap_or(u16::MAX)
2557}
2558
2559fn clamp_u32(value: usize) -> u32 {
2560    u32::try_from(value).unwrap_or(u32::MAX)
2561}
2562
2563#[cfg(test)]
2564#[path = "viz_tests.rs"]
2565mod tests;