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