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