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    push_findings(
1290        &mut findings,
1291        "package-cycle",
1292        "Package cycle",
1293        &results.package_cycles,
1294        root,
1295        index,
1296    );
1297    let violation_count = results.boundary_violations.len()
1298        + results.boundary_coverage_violations.len()
1299        + results.boundary_call_violations.len()
1300        + results.policy_violations.len();
1301    let total_findings = violation_count
1302        + results.circular_dependencies.len()
1303        + results.re_export_cycles.len()
1304        + results.package_cycles.len();
1305    analysis_from_records(findings, total_findings, violation_count, "violations")
1306}
1307
1308fn build_dependencies(
1309    results: &AnalysisResults,
1310    index: &FileIndex<'_>,
1311    root: &Path,
1312) -> VizFindingAnalysis {
1313    let mut findings = Vec::new();
1314    let mut count = 0;
1315    macro_rules! add {
1316        ($field:ident, $kind:literal, $title:literal) => {
1317            count += results.$field.len();
1318            push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1319        };
1320    }
1321    add!(unresolved_imports, "unresolved-import", "Unresolved import");
1322    add!(
1323        unlisted_dependencies,
1324        "unlisted-dependency",
1325        "Unlisted dependency"
1326    );
1327    add!(
1328        type_only_dependencies,
1329        "type-only-dependency",
1330        "Type-only dependency"
1331    );
1332    add!(
1333        test_only_dependencies,
1334        "test-only-dependency",
1335        "Test-only dependency"
1336    );
1337    add!(
1338        dev_dependencies_in_production,
1339        "dev-dependency-in-production",
1340        "Development dependency used in production"
1341    );
1342    add!(
1343        duplicate_exports,
1344        "duplicate-export",
1345        "Duplicate public export"
1346    );
1347    add!(
1348        private_type_leaks,
1349        "private-type-leak",
1350        "Private type leaked by public API"
1351    );
1352    add!(
1353        deprecated_exports_in_use,
1354        "deprecated-export-in-use",
1355        "Deprecated export still in use"
1356    );
1357    add!(
1358        unused_catalog_entries,
1359        "unused-catalog-entry",
1360        "Unused catalog entry"
1361    );
1362    add!(
1363        empty_catalog_groups,
1364        "empty-catalog-group",
1365        "Empty catalog group"
1366    );
1367    add!(
1368        unresolved_catalog_references,
1369        "unresolved-catalog-reference",
1370        "Unresolved catalog reference"
1371    );
1372    add!(
1373        unused_dependency_overrides,
1374        "unused-dependency-override",
1375        "Unused dependency override"
1376    );
1377    add!(
1378        misconfigured_dependency_overrides,
1379        "misconfigured-dependency-override",
1380        "Misconfigured dependency override"
1381    );
1382    analysis_from_records(findings, count, count, "findings")
1383}
1384
1385fn build_frameworks(
1386    results: &AnalysisResults,
1387    index: &FileIndex<'_>,
1388    root: &Path,
1389) -> VizFrameworkData {
1390    let analysis = build_framework_findings(results, index, root);
1391    VizFrameworkData {
1392        availability: analysis.availability,
1393        detector_availability: VizAvailability::unavailable(
1394            "detectors",
1395            "Framework detector coverage did not complete",
1396        ),
1397        findings_truncated: analysis.findings_truncated,
1398        findings: analysis.findings,
1399        detected_frameworks: Vec::new(),
1400        detectors: Vec::new(),
1401    }
1402}
1403
1404fn build_framework_findings(
1405    results: &AnalysisResults,
1406    index: &FileIndex<'_>,
1407    root: &Path,
1408) -> VizFindingAnalysis {
1409    let mut findings = Vec::new();
1410    let mut count = 0;
1411    macro_rules! add {
1412        ($field:ident, $kind:literal, $title:literal) => {
1413            count += results.$field.len();
1414            push_findings(&mut findings, $kind, $title, &results.$field, root, index);
1415        };
1416    }
1417    add!(
1418        invalid_client_exports,
1419        "invalid-client-export",
1420        "Invalid client export"
1421    );
1422    add!(
1423        mixed_client_server_barrels,
1424        "mixed-client-server-barrel",
1425        "Mixed client/server barrel"
1426    );
1427    add!(
1428        misplaced_directives,
1429        "misplaced-directive",
1430        "Misplaced framework directive"
1431    );
1432    add!(
1433        unprovided_injects,
1434        "unprovided-inject",
1435        "Injected value is never provided"
1436    );
1437    add!(
1438        unrendered_components,
1439        "unrendered-component",
1440        "Component is never rendered"
1441    );
1442    add!(route_collisions, "route-collision", "Route collision");
1443    add!(
1444        dynamic_segment_name_conflicts,
1445        "dynamic-segment-conflict",
1446        "Dynamic segment conflict"
1447    );
1448    add!(
1449        unused_component_props,
1450        "unused-component-prop",
1451        "Unused component prop"
1452    );
1453    add!(
1454        absent_component_props,
1455        "absent-component-prop",
1456        "Optional prop review candidate"
1457    );
1458    add!(
1459        unused_component_emits,
1460        "unused-component-emit",
1461        "Unused component event"
1462    );
1463    add!(
1464        unused_component_inputs,
1465        "unused-component-input",
1466        "Unused component input"
1467    );
1468    add!(
1469        unused_component_outputs,
1470        "unused-component-output",
1471        "Unused component output"
1472    );
1473    add!(
1474        unused_svelte_events,
1475        "unused-svelte-event",
1476        "Unused Svelte event"
1477    );
1478    add!(
1479        unused_server_actions,
1480        "unused-server-action",
1481        "Unused server action"
1482    );
1483    add!(
1484        unused_load_data_keys,
1485        "unused-load-data-key",
1486        "Unused load-data key"
1487    );
1488    add!(prop_drilling_chains, "prop-drilling", "Prop-drilling chain");
1489    add!(thin_wrappers, "thin-wrapper", "Thin component wrapper");
1490    add!(
1491        duplicate_prop_shapes,
1492        "duplicate-prop-shape",
1493        "Duplicate prop shape"
1494    );
1495    let mut analysis = analysis_from_records(findings, count, count, "findings");
1496    if results.unused_load_data_keys_global_abstain {
1497        analysis.availability.reason = Some(
1498            "Load-data-key analysis abstained because whole-object page data usage was detected"
1499                .to_string(),
1500        );
1501    }
1502    analysis
1503}
1504
1505fn build_feature_flags(
1506    flags: &[FeatureFlag],
1507    index: &FileIndex<'_>,
1508    root: &Path,
1509) -> VizFindingAnalysis {
1510    let mut findings = Vec::new();
1511    push_findings(
1512        &mut findings,
1513        "feature-flag",
1514        "Feature flag use",
1515        flags,
1516        root,
1517        index,
1518    );
1519    analysis_from_records(findings, flags.len(), flags.len(), "flags")
1520}
1521
1522fn build_security(
1523    results: &AnalysisResults,
1524    index: &FileIndex<'_>,
1525    root: &Path,
1526) -> VizSecurityData {
1527    let total = results.security_findings.len();
1528    let truncated =
1529        (total > MAX_ANALYSIS_FINDINGS).then_some(total.saturating_sub(MAX_ANALYSIS_FINDINGS));
1530    let mut sorted_findings: Vec<&SecurityFinding> = results.security_findings.iter().collect();
1531    sorted_findings.sort_by_key(|finding| {
1532        let severity = serialized_label(&crate::security::derive_security_severity(finding));
1533        let priority = match severity.as_str() {
1534            "high" => 0,
1535            "medium" => 1,
1536            _ => 2,
1537        };
1538        (priority, relative_path(&finding.path, root), finding.line)
1539    });
1540    let candidates = sorted_findings
1541        .into_iter()
1542        .take(MAX_ANALYSIS_FINDINGS)
1543        .map(|finding| build_security_candidate(finding, index, root))
1544        .collect();
1545
1546    let mut blind_spots = Vec::new();
1547    if results.security_unresolved_edge_files > 0 {
1548        blind_spots.push(VizSecurityBlindSpot {
1549            kind: "unresolved-dynamic-imports".to_string(),
1550            count: results.security_unresolved_edge_files,
1551            path: None,
1552            file: None,
1553            line: None,
1554            reason: Some("Dynamic imports prevent complete client/server reachability".to_string()),
1555        });
1556    }
1557    if results.security_unresolved_callee_sites > 0 {
1558        blind_spots.push(VizSecurityBlindSpot {
1559            kind: "unresolved-callee-sites".to_string(),
1560            count: results.security_unresolved_callee_sites,
1561            path: None,
1562            file: None,
1563            line: None,
1564            reason: Some(
1565                "Dynamic or computed callees could not be matched to the sink catalogue"
1566                    .to_string(),
1567            ),
1568        });
1569    }
1570    let diagnostic_count = results.security_unresolved_callee_diagnostics.len();
1571    for diagnostic in results
1572        .security_unresolved_callee_diagnostics
1573        .iter()
1574        .take(MAX_SECURITY_BLIND_SPOT_SAMPLES)
1575    {
1576        blind_spots.push(VizSecurityBlindSpot {
1577            kind: "unresolved-callee-sample".to_string(),
1578            count: 1,
1579            path: Some(relative_path(&diagnostic.path, root)),
1580            file: index.index_of_path(&diagnostic.path),
1581            line: Some(diagnostic.line),
1582            reason: Some(serialized_label(&diagnostic.reason)),
1583        });
1584    }
1585
1586    VizSecurityData {
1587        availability: VizAvailability::complete(total, "candidates", truncated),
1588        runtime_availability: VizAvailability::unavailable(
1589            "observations",
1590            NO_RUNTIME_COVERAGE_REASON,
1591        ),
1592        candidates,
1593        blind_spot_count: results.security_unresolved_edge_files
1594            + results.security_unresolved_callee_sites,
1595        blind_spots_truncated: (diagnostic_count > MAX_SECURITY_BLIND_SPOT_SAMPLES)
1596            .then_some(diagnostic_count.saturating_sub(MAX_SECURITY_BLIND_SPOT_SAMPLES)),
1597        blind_spots,
1598    }
1599}
1600
1601fn build_security_candidate(
1602    finding: &SecurityFinding,
1603    index: &FileIndex<'_>,
1604    root: &Path,
1605) -> VizSecurityCandidate {
1606    let kind = serialized_label(&finding.kind);
1607    let path = relative_path(&finding.path, root);
1608    let severity = serialized_label(&crate::security::derive_security_severity(finding));
1609    // The engine session stamps `finding_id` right after detection, so viz
1610    // reads the same id as the JSON and SARIF output.
1611    let id = finding.finding_id.clone();
1612    let reachability = finding.reachability.as_ref();
1613    let architecture_zone = finding
1614        .candidate
1615        .boundary
1616        .architecture_zone
1617        .as_ref()
1618        .map(|zone| format!("{} -> {}", zone.from, zone.to));
1619    let dead_code = serialize_relative(finding.dead_code.as_ref(), root);
1620    let runtime = serialize_relative(finding.runtime.as_ref(), root);
1621    let taint_flow = security_taint_flow(finding, index, root);
1622    let observed_controls = security_controls(finding, root);
1623    let actions = serialize_relative_value(&finding.actions, root)
1624        .unwrap_or_else(|| Value::Array(Vec::new()));
1625    let trace = security_trace(finding, index, root);
1626    let taint_trace = finding
1627        .reachability
1628        .as_ref()
1629        .map_or_else(Vec::new, |reachability| {
1630            trace_hops(&reachability.untrusted_source_trace, index, root)
1631        });
1632    VizSecurityCandidate {
1633        id,
1634        kind,
1635        category: finding.category.clone(),
1636        cwe: finding.cwe,
1637        file: index.index_of_path(&finding.path),
1638        path,
1639        line: finding.line,
1640        col: finding.col,
1641        evidence: finding.evidence.clone(),
1642        severity,
1643        taint_confidence: reachability
1644            .and_then(|reachability| reachability.taint_confidence.as_ref())
1645            .map(serialized_label),
1646        source_kind: finding.candidate.source_kind.clone(),
1647        sink: finding.candidate.sink.callee.clone(),
1648        url_shape: finding
1649            .candidate
1650            .sink
1651            .url_shape
1652            .as_ref()
1653            .map(serialized_label),
1654        network_destination: finding
1655            .candidate
1656            .network
1657            .as_ref()
1658            .and_then(|network| network.destination.clone()),
1659        reachable_from_entry: reachability.map(|value| value.reachable_from_entry),
1660        reachable_from_untrusted_source: reachability
1661            .map(|value| value.reachable_from_untrusted_source),
1662        blast_radius: reachability.map(|value| value.blast_radius),
1663        crosses_boundary: reachability.is_some_and(|value| value.crosses_boundary)
1664            || finding.candidate.boundary.client_server
1665            || finding.candidate.boundary.cross_module
1666            || architecture_zone.is_some(),
1667        client_server_boundary: finding.candidate.boundary.client_server,
1668        cross_module_boundary: finding.candidate.boundary.cross_module,
1669        architecture_zone,
1670        dead_code,
1671        runtime,
1672        taint_flow,
1673        observed_controls,
1674        control_verification_prompt: finding
1675            .attack_surface
1676            .as_ref()
1677            .map(|surface| surface.defensive_boundary.verification_prompt.clone()),
1678        trace,
1679        taint_trace,
1680        actions,
1681    }
1682}
1683
1684fn serialize_relative<T: Serialize>(value: Option<&T>, root: &Path) -> Option<Value> {
1685    value.and_then(|value| serialize_relative_value(value, root))
1686}
1687
1688fn serialize_relative_value<T: Serialize>(value: &T, root: &Path) -> Option<Value> {
1689    let mut serialized = serde_json::to_value(value).ok()?;
1690    relativize_value_paths(&mut serialized, root);
1691    Some(serialized)
1692}
1693
1694fn security_controls(finding: &SecurityFinding, root: &Path) -> Vec<Value> {
1695    finding
1696        .attack_surface
1697        .as_ref()
1698        .map_or_else(Vec::new, |surface| {
1699            surface
1700                .defensive_boundary
1701                .controls
1702                .iter()
1703                .filter_map(|control| serialize_relative_value(control, root))
1704                .collect()
1705        })
1706}
1707
1708fn security_trace(
1709    finding: &SecurityFinding,
1710    index: &FileIndex<'_>,
1711    root: &Path,
1712) -> Vec<VizSecurityTraceHop> {
1713    trace_hops(&finding.trace, index, root)
1714}
1715
1716fn trace_hops(
1717    hops: &[fallow_types::results::TraceHop],
1718    index: &FileIndex<'_>,
1719    root: &Path,
1720) -> Vec<VizSecurityTraceHop> {
1721    hops.iter()
1722        .map(|hop| VizSecurityTraceHop {
1723            file: index.index_of_path(&hop.path),
1724            path: relative_path(&hop.path, root),
1725            line: hop.line,
1726            col: hop.col,
1727            role: serialized_label(&hop.role),
1728        })
1729        .collect()
1730}
1731
1732fn security_taint_flow(
1733    finding: &SecurityFinding,
1734    index: &FileIndex<'_>,
1735    root: &Path,
1736) -> Option<VizSecurityTaintFlow> {
1737    let flow = finding.taint_flow.as_ref()?;
1738    let endpoint = |value: &fallow_types::results::TaintEndpoint| VizSecurityEndpoint {
1739        file: index.index_of_path(&value.path),
1740        path: relative_path(&value.path, root),
1741        line: value.line,
1742        col: value.col,
1743    };
1744    Some(VizSecurityTaintFlow {
1745        source: endpoint(&flow.source),
1746        sink: endpoint(&flow.sink),
1747        intra_module: flow.path.intra_module,
1748        cross_module_hops: flow.path.cross_module_hops,
1749    })
1750}
1751
1752/// Populate Health, Framework diagnostics, and Styling from the health runner
1753/// that consumed the same session artifacts.
1754pub fn apply_health_report(data: &mut VizData, report: &HealthReport, root: &Path) {
1755    let by_path: FxHashMap<String, u32> = data
1756        .files
1757        .iter()
1758        .enumerate()
1759        .map(|(index, file)| (file.path.clone(), clamp_u32(index)))
1760        .collect();
1761    apply_health_data(data, report, root, &by_path);
1762    apply_framework_data(data, report);
1763    apply_styling_data(data, report, root, &by_path);
1764}
1765
1766fn apply_health_data(
1767    data: &mut VizData,
1768    report: &HealthReport,
1769    root: &Path,
1770    by_path: &FxHashMap<String, u32>,
1771) {
1772    let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
1773    let hotspot_by_path: FxHashMap<String, &fallow_output::HotspotFinding> = report
1774        .hotspots
1775        .iter()
1776        .map(|hotspot| (relative_path(&hotspot.path, root), hotspot))
1777        .collect();
1778    let files = health_files(report, root, by_path, &hotspot_by_path);
1779    let (findings, total_findings) = health_findings(report, root, &resolve);
1780    let concern_count = health_concern_count(report, root, by_path);
1781    data.health = VizHealthData {
1782        availability: VizAvailability::complete(concern_count, "files", None),
1783        capabilities: health_capabilities(report),
1784        shared_parse: data.health.shared_parse,
1785        score: report.health_score.as_ref().map(|score| score.score),
1786        grade: report
1787            .health_score
1788            .as_ref()
1789            .map(|score| score.grade.to_string()),
1790        average_maintainability: report.summary.average_maintainability,
1791        files_truncated: report
1792            .file_scores
1793            .len()
1794            .checked_sub(MAX_HEALTH_FILES)
1795            .filter(|count| *count > 0),
1796        findings_truncated: total_findings
1797            .checked_sub(findings.len())
1798            .filter(|count| *count > 0),
1799        files,
1800        findings,
1801    };
1802}
1803
1804fn health_concern_count(
1805    report: &HealthReport,
1806    root: &Path,
1807    by_path: &FxHashMap<String, u32>,
1808) -> usize {
1809    let mut files = rustc_hash::FxHashSet::default();
1810    let mut add = |path: &Path| {
1811        if let Some(file) = by_path.get(&relative_path(path, root)) {
1812            files.insert(*file);
1813        }
1814    };
1815    for finding in &report.findings {
1816        add(&finding.path);
1817    }
1818    for hotspot in &report.hotspots {
1819        add(&hotspot.path);
1820    }
1821    if let Some(gaps) = &report.coverage_gaps {
1822        for finding in &gaps.files {
1823            add(&finding.file.path);
1824        }
1825        for finding in &gaps.exports {
1826            add(&finding.export.path);
1827        }
1828    }
1829    files.len()
1830}
1831
1832fn health_files(
1833    report: &HealthReport,
1834    root: &Path,
1835    by_path: &FxHashMap<String, u32>,
1836    hotspots: &FxHashMap<String, &fallow_output::HotspotFinding>,
1837) -> Vec<VizHealthFile> {
1838    report
1839        .file_scores
1840        .iter()
1841        .take(MAX_HEALTH_FILES)
1842        .filter_map(|score| {
1843            let path = relative_path(&score.path, root);
1844            let file = by_path.get(&path).copied()?;
1845            let hotspot = hotspots.get(&path).copied();
1846            Some(VizHealthFile {
1847                file,
1848                path,
1849                maintainability_index: score.maintainability_index,
1850                crap_max: score.crap_max,
1851                complexity_density: score.complexity_density,
1852                fan_in: score.fan_in,
1853                fan_out: score.fan_out,
1854                hotspot_score: hotspot.map(|entry| entry.score),
1855                commits: hotspot.map(|entry| entry.commits),
1856                ownership: hotspot
1857                    .and_then(|entry| serialize_relative(entry.ownership.as_ref(), root)),
1858            })
1859        })
1860        .collect()
1861}
1862
1863fn health_findings(
1864    report: &HealthReport,
1865    root: &Path,
1866    resolve: &dyn Fn(&Path) -> Option<u32>,
1867) -> (Vec<VizFinding>, usize) {
1868    let coverage_count = report
1869        .coverage_gaps
1870        .as_ref()
1871        .map_or(0, |gaps| gaps.files.len() + gaps.exports.len());
1872    let total = report.findings.len() + report.hotspots.len() + coverage_count;
1873    let mut findings = Vec::with_capacity(total.min(MAX_ANALYSIS_FINDINGS));
1874    append_findings(
1875        &mut findings,
1876        &report.findings,
1877        "health-finding",
1878        "Health threshold exceeded",
1879        root,
1880        resolve,
1881    );
1882    append_findings(
1883        &mut findings,
1884        &report.hotspots,
1885        "git-hotspot",
1886        "Complex and frequently changed file",
1887        root,
1888        resolve,
1889    );
1890    if let Some(gaps) = &report.coverage_gaps {
1891        append_findings(
1892            &mut findings,
1893            &gaps.files,
1894            "coverage-gap-file",
1895            "File has no test path",
1896            root,
1897            resolve,
1898        );
1899        append_findings(
1900            &mut findings,
1901            &gaps.exports,
1902            "coverage-gap-export",
1903            "Export has no test path",
1904            root,
1905            resolve,
1906        );
1907    }
1908    (findings, total)
1909}
1910
1911fn append_findings<T: Serialize>(
1912    out: &mut Vec<VizFinding>,
1913    values: &[T],
1914    kind: &str,
1915    title: &str,
1916    root: &Path,
1917    resolve: &dyn Fn(&Path) -> Option<u32>,
1918) {
1919    let remaining = MAX_ANALYSIS_FINDINGS.saturating_sub(out.len());
1920    out.extend(values.iter().take(remaining).filter_map(|value| {
1921        serde_json::to_value(value)
1922            .ok()
1923            .map(|detail| finding_from_value(kind, title, detail, root, resolve))
1924    }));
1925}
1926
1927fn health_capabilities(report: &HealthReport) -> VizHealthCapabilities {
1928    let file_count = report.file_scores.len();
1929    let coverage = report.coverage_gaps.as_ref().map_or_else(
1930        || VizAvailability::unavailable("gaps", "Coverage gap analysis did not produce a result"),
1931        |gaps| VizAvailability::complete(gaps.files.len() + gaps.exports.len(), "gaps", None),
1932    );
1933    let runtime = report.runtime_coverage.as_ref().map_or_else(
1934        || VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1935        |runtime| {
1936            VizAvailability::complete(runtime.summary.functions_tracked, "observations", None)
1937        },
1938    );
1939    VizHealthCapabilities {
1940        complexity: VizAvailability::complete(report.findings.len(), "findings", None),
1941        maintainability: VizAvailability::complete(file_count, "files", None),
1942        crap: VizAvailability::complete(file_count, "files", None),
1943        coverage,
1944        runtime,
1945        churn: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1946        hotspots: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1947        ownership: VizAvailability::disabled("files", "Git history is not loaded by Viz"),
1948    }
1949}
1950
1951fn unavailable_health_capabilities(reason: &str) -> VizHealthCapabilities {
1952    VizHealthCapabilities {
1953        complexity: VizAvailability::unavailable("findings", reason),
1954        maintainability: VizAvailability::unavailable("files", reason),
1955        crap: VizAvailability::unavailable("files", reason),
1956        coverage: VizAvailability::unavailable("gaps", reason),
1957        runtime: VizAvailability::unavailable("observations", NO_RUNTIME_COVERAGE_REASON),
1958        churn: VizAvailability::unavailable("files", reason),
1959        hotspots: VizAvailability::unavailable("files", reason),
1960        ownership: VizAvailability::unavailable("files", reason),
1961    }
1962}
1963
1964fn apply_framework_data(data: &mut VizData, report: &HealthReport) {
1965    let count = data.frameworks.availability.count;
1966    let Some(diagnostics) = &report.framework_health else {
1967        if count == 0 {
1968            data.frameworks.detector_availability = VizAvailability {
1969                state: VizAvailabilityState::NotApplicable,
1970                count: 0,
1971                unit: "detectors",
1972                reason: Some("No supported framework was detected".to_string()),
1973                truncated: None,
1974            };
1975            data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
1976            data.frameworks.availability.reason =
1977                Some("No supported framework was detected".to_string());
1978        } else {
1979            data.frameworks.detector_availability = VizAvailability::unavailable(
1980                "detectors",
1981                "Framework detector metadata was not produced",
1982            );
1983        }
1984        return;
1985    };
1986    data.frameworks
1987        .detected_frameworks
1988        .clone_from(&diagnostics.detected_frameworks);
1989    data.frameworks.detectors = diagnostics
1990        .detectors
1991        .iter()
1992        .map(|detector| VizFrameworkDetector {
1993            id: detector.id.clone(),
1994            framework: detector.framework.clone(),
1995            status: serialized_label(&detector.status),
1996            reason: detector.reason.clone(),
1997        })
1998        .collect();
1999    data.frameworks.detector_availability =
2000        VizAvailability::complete(diagnostics.detectors.len(), "detectors", None);
2001    if diagnostics.detected_frameworks.is_empty() && count == 0 {
2002        data.frameworks.availability.state = VizAvailabilityState::NotApplicable;
2003        data.frameworks.availability.reason =
2004            Some("No supported framework was detected".to_string());
2005        data.frameworks.detector_availability.state = VizAvailabilityState::NotApplicable;
2006        data.frameworks.detector_availability.reason =
2007            Some("No supported framework was detected".to_string());
2008    }
2009}
2010
2011fn apply_styling_data(
2012    data: &mut VizData,
2013    report: &HealthReport,
2014    root: &Path,
2015    by_path: &FxHashMap<String, u32>,
2016) {
2017    let resolve = |path: &Path| by_path.get(&relative_path(path, root)).copied();
2018    let count = report.styling_findings.len();
2019    let mut findings = Vec::with_capacity(count.min(MAX_ANALYSIS_FINDINGS));
2020    append_findings(
2021        &mut findings,
2022        &report.styling_findings,
2023        "styling-finding",
2024        "Styling health finding",
2025        root,
2026        &resolve,
2027    );
2028    let truncated = count.checked_sub(findings.len()).filter(|value| *value > 0);
2029    let styling = report.styling_health.as_ref();
2030    data.styling = VizStylingData {
2031        availability: report.css_analytics.as_ref().map_or_else(
2032            || VizAvailability {
2033                state: VizAvailabilityState::NotApplicable,
2034                count: 0,
2035                unit: "findings",
2036                reason: Some("No supported CSS or component styling was detected".to_string()),
2037                truncated: None,
2038            },
2039            |_| VizAvailability::complete(count, "findings", truncated),
2040        ),
2041        findings_truncated: truncated,
2042        findings,
2043        score: styling.map(|health| health.score),
2044        grade: styling.map(|health| health.grade.to_string()),
2045        confidence: styling.map(|health| serialized_label(&health.confidence)),
2046        summary: report
2047            .css_analytics
2048            .as_ref()
2049            .and_then(|analytics| serde_json::to_value(&analytics.summary).ok()),
2050    };
2051}
2052
2053/// Per-file lookup maps threaded into [`build_files`].
2054struct FilePropertyMaps<'a> {
2055    zone_by_file: &'a FxHashMap<u32, u16>,
2056    clone_groups_by_file: &'a FxHashMap<u32, Vec<u32>>,
2057    dup_lines_by_file: &'a FxHashMap<u32, u32>,
2058    cycles: &'a [Vec<u32>],
2059}
2060
2061fn display_root(root: &Path) -> String {
2062    root.file_name().map_or_else(
2063        || root.to_string_lossy().into_owned(),
2064        |n| n.to_string_lossy().into_owned(),
2065    )
2066}
2067
2068fn relative_path(path: &Path, root: &Path) -> String {
2069    if let Ok(relative) = path.strip_prefix(root) {
2070        return relative.to_string_lossy().replace('\\', "/");
2071    }
2072    // has_root, not is_absolute: on Windows a drive-less rooted path such as
2073    // `\\Users\\private\\secret.ts` is rooted but NOT absolute, so gating on
2074    // is_absolute let it skip redaction and leak the full path into the payload.
2075    // has_root is a strict superset and covers `C:\\...` and `/...` alike.
2076    if path.has_root() {
2077        let name = path
2078            .file_name()
2079            .map_or_else(|| "path".into(), |name| name.to_string_lossy());
2080        return format!("<external>/{name}");
2081    }
2082    path.to_string_lossy().replace('\\', "/")
2083}
2084
2085fn build_workspaces(workspaces: &[WorkspaceInfo], root: &Path) -> Vec<VizWorkspace> {
2086    workspaces
2087        .iter()
2088        .map(|ws| VizWorkspace {
2089            name: ws.name.clone(),
2090            root: relative_path(&ws.root, root),
2091        })
2092        .collect()
2093}
2094
2095fn workspace_index_for(path: &Path, workspaces: &[WorkspaceInfo]) -> Option<u16> {
2096    let mut best: Option<(usize, usize)> = None;
2097    for (i, ws) in workspaces.iter().enumerate() {
2098        if path.starts_with(&ws.root) {
2099            let depth = ws.root.components().count();
2100            if best.is_none_or(|(_, d)| depth > d) {
2101                best = Some((i, depth));
2102            }
2103        }
2104    }
2105    best.map(|(i, _)| clamp_u16(i))
2106}
2107
2108fn classify_zones(
2109    input: &VizBuildInput<'_>,
2110    index: &FileIndex<'_>,
2111) -> (Vec<VizZone>, FxHashMap<u32, u16>) {
2112    let boundaries = &input.config.boundaries;
2113    let mut zones: Vec<VizZone> = boundaries
2114        .zones
2115        .iter()
2116        .map(|z| VizZone {
2117            name: z.name.clone(),
2118            files: 0,
2119        })
2120        .collect();
2121    let name_to_index: FxHashMap<&str, u16> = boundaries
2122        .zones
2123        .iter()
2124        .enumerate()
2125        .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2126        .collect();
2127
2128    let mut zone_by_file = FxHashMap::default();
2129    if zones.is_empty() {
2130        return (zones, zone_by_file);
2131    }
2132
2133    for (i, file) in index.ordered.iter().enumerate() {
2134        let rel = relative_path(&file.path, &input.config.root);
2135        if let Some(zone_name) = boundaries.classify_zone(&rel)
2136            && let Some(&zone_idx) = name_to_index.get(zone_name)
2137        {
2138            zone_by_file.insert(clamp_u32(i), zone_idx);
2139            zones[zone_idx as usize].files += 1;
2140        }
2141    }
2142
2143    (zones, zone_by_file)
2144}
2145
2146/// Clone payload maps: kept groups, per-file group ids, per-file duplicated
2147/// lines, and how many kept-groups the payload cap dropped.
2148type CloneMaps = (
2149    Vec<VizCloneGroup>,
2150    FxHashMap<u32, Vec<u32>>,
2151    FxHashMap<u32, u32>,
2152    u32,
2153);
2154
2155fn build_clones(
2156    duplication: &DuplicationReport,
2157    index: &FileIndex<'_>,
2158    max_groups: usize,
2159) -> CloneMaps {
2160    let mut clones = Vec::new();
2161    let mut groups_by_file: FxHashMap<u32, Vec<u32>> = FxHashMap::default();
2162    let mut dup_lines_by_file: FxHashMap<u32, u32> = FxHashMap::default();
2163    let mut truncated: usize = 0;
2164
2165    for group in &duplication.clone_groups {
2166        let instances: Vec<VizCloneInstance> = group
2167            .instances
2168            .iter()
2169            .filter_map(|inst| {
2170                index
2171                    .index_of_path(&inst.file)
2172                    .map(|file| VizCloneInstance {
2173                        file,
2174                        start_line: clamp_u32(inst.start_line),
2175                        end_line: clamp_u32(inst.end_line),
2176                    })
2177            })
2178            .collect();
2179        if instances.len() < 2 {
2180            continue;
2181        }
2182        if clones.len() >= max_groups {
2183            truncated += 1;
2184            continue;
2185        }
2186
2187        let group_idx = clamp_u32(clones.len());
2188        for inst in &instances {
2189            let entry = groups_by_file.entry(inst.file).or_default();
2190            if entry.last() != Some(&group_idx) {
2191                entry.push(group_idx);
2192            }
2193            *dup_lines_by_file.entry(inst.file).or_default() +=
2194                inst.end_line.saturating_sub(inst.start_line) + 1;
2195        }
2196
2197        let (preview, highlight_start, highlight_lines) = group
2198            .instances
2199            .first()
2200            .map(build_clone_preview)
2201            .unwrap_or_default();
2202
2203        clones.push(VizCloneGroup {
2204            lines: group.line_count,
2205            tokens: group.token_count,
2206            instances,
2207            preview,
2208            highlight_start,
2209            highlight_lines,
2210        });
2211    }
2212
2213    (
2214        clones,
2215        groups_by_file,
2216        dup_lines_by_file,
2217        clamp_u32(truncated),
2218    )
2219}
2220
2221fn truncate_preview(fragment: &str) -> String {
2222    let mut out = String::new();
2223    for (i, line) in fragment.lines().enumerate() {
2224        if i >= CLONE_PREVIEW_MAX_LINES || out.len() + line.len() > CLONE_PREVIEW_MAX_BYTES {
2225            out.push('\u{2026}');
2226            break;
2227        }
2228        if i > 0 {
2229            out.push('\n');
2230        }
2231        out.push_str(line);
2232    }
2233    out
2234}
2235
2236/// Build the representative clone preview: a context window around the
2237/// duplicated block, with the highlight range located within it. Returns
2238/// `(preview, highlight_start, highlight_lines)` where `highlight_start`
2239/// is the 0-based index of the first copied line among the preview lines
2240/// and `highlight_lines` is the copied line count present in `preview`.
2241///
2242/// Falls back to the bare fragment with the whole block highlighted on
2243/// any read failure, empty source, or an out-of-range line span. Never
2244/// panics.
2245fn build_clone_preview(inst: &CloneInstance) -> (String, u32, u32) {
2246    let Ok(source) = std::fs::read_to_string(&inst.file) else {
2247        return fragment_fallback(&inst.fragment);
2248    };
2249    let lines: Vec<&str> = source.lines().collect();
2250    let total = lines.len();
2251    if total == 0 || inst.start_line == 0 || inst.start_line > total {
2252        return fragment_fallback(&inst.fragment);
2253    }
2254
2255    // Block bounds as a 0-based `[block_start, block_end)` range, clamped
2256    // to the file and guaranteed to hold at least one line.
2257    let block_start = inst.start_line - 1;
2258    let block_end = inst.end_line.min(total).max(inst.start_line);
2259    let mut block_lines = block_end - block_start;
2260    let mut before = block_start.min(CLONE_PREVIEW_CONTEXT);
2261    let mut after = (total - block_end).min(CLONE_PREVIEW_CONTEXT);
2262
2263    // Line cap: when the block plus its context fits, trim context
2264    // symmetrically to fit. When the block alone fills the cap, keep the
2265    // leading context (so the highlight always reads against some dimmed
2266    // lines) and truncate the block's tail, always keeping >= 1 block line.
2267    if before + block_lines + after > CLONE_PREVIEW_MAX_LINES {
2268        if before + block_lines >= CLONE_PREVIEW_MAX_LINES {
2269            after = 0;
2270            block_lines = CLONE_PREVIEW_MAX_LINES.saturating_sub(before).max(1);
2271        } else {
2272            trim_context(
2273                &mut before,
2274                &mut after,
2275                CLONE_PREVIEW_MAX_LINES - block_lines,
2276            );
2277        }
2278    }
2279
2280    enforce_byte_cap(
2281        &lines,
2282        block_start,
2283        &mut before,
2284        &mut after,
2285        &mut block_lines,
2286    );
2287
2288    let win_start = block_start - before;
2289    let win_end = win_start + before + block_lines + after;
2290    let preview = lines[win_start..win_end].join("\n");
2291    (preview, clamp_u32(before), clamp_u32(block_lines))
2292}
2293
2294/// Fallback preview: the bare fragment, capped, with the whole block
2295/// highlighted (nothing dimmed).
2296fn fragment_fallback(fragment: &str) -> (String, u32, u32) {
2297    let preview = truncate_preview(fragment);
2298    let highlight_lines = if preview.is_empty() {
2299        0
2300    } else {
2301        preview.lines().count()
2302    };
2303    (preview, 0, clamp_u32(highlight_lines))
2304}
2305
2306/// Reduce `before`/`after` so their sum fits `budget`, dropping from the
2307/// larger side first (ties favor keeping `after`) so the two flanks stay
2308/// balanced. Deterministic.
2309fn trim_context(before: &mut usize, after: &mut usize, budget: usize) {
2310    while *before + *after > budget {
2311        if *before >= *after {
2312            *before -= 1;
2313        } else {
2314            *after -= 1;
2315        }
2316    }
2317}
2318
2319/// Trim the preview window to `CLONE_PREVIEW_MAX_BYTES`, dropping context
2320/// lines (larger side first) before ever cutting into the highlighted
2321/// block. If the block alone still overflows, its tail lines are dropped,
2322/// but at least one line is always kept.
2323fn enforce_byte_cap(
2324    lines: &[&str],
2325    block_start: usize,
2326    before: &mut usize,
2327    after: &mut usize,
2328    block_lines: &mut usize,
2329) {
2330    let window_bytes = |before: usize, after: usize, block_lines: usize| -> usize {
2331        let start = block_start - before;
2332        let end = start + before + block_lines + after;
2333        let separators = (end - start).saturating_sub(1);
2334        lines[start..end].iter().map(|l| l.len()).sum::<usize>() + separators
2335    };
2336    while window_bytes(*before, *after, *block_lines) > CLONE_PREVIEW_MAX_BYTES {
2337        if *before + *after > 0 {
2338            if *before >= *after {
2339                *before -= 1;
2340            } else {
2341                *after -= 1;
2342            }
2343        } else if *block_lines > 1 {
2344            *block_lines -= 1;
2345        } else {
2346            break;
2347        }
2348    }
2349}
2350
2351fn build_cycles(results: &AnalysisResults, index: &FileIndex<'_>) -> Vec<Vec<u32>> {
2352    results
2353        .circular_dependencies
2354        .iter()
2355        .filter_map(|cd| {
2356            let ids: Vec<u32> = cd
2357                .cycle
2358                .files
2359                .iter()
2360                .filter_map(|p| index.index_of_path(p))
2361                .collect();
2362            (ids.len() == cd.cycle.files.len()).then_some(ids)
2363        })
2364        .collect()
2365}
2366
2367fn build_violations(
2368    results: &AnalysisResults,
2369    zones: &[VizZone],
2370    index: &FileIndex<'_>,
2371) -> Vec<VizViolation> {
2372    let name_to_index: FxHashMap<&str, u16> = zones
2373        .iter()
2374        .enumerate()
2375        .map(|(i, z)| (z.name.as_str(), clamp_u16(i)))
2376        .collect();
2377
2378    results
2379        .boundary_violations
2380        .iter()
2381        .filter_map(|finding| {
2382            let v = &finding.violation;
2383            let from = index.index_of_path(&v.from_path)?;
2384            let to = index.index_of_path(&v.to_path)?;
2385            let from_zone = *name_to_index.get(v.from_zone.as_str())?;
2386            let to_zone = *name_to_index.get(v.to_zone.as_str())?;
2387            Some(VizViolation {
2388                from,
2389                to,
2390                from_zone,
2391                to_zone,
2392                line: v.line,
2393                specifier: v.import_specifier.clone(),
2394            })
2395        })
2396        .collect()
2397}
2398
2399fn build_edges(graph: &RetainedModuleGraph, index: &FileIndex<'_>) -> Vec<[u32; 3]> {
2400    let graph = graph.as_graph();
2401    let mut edges = Vec::with_capacity(graph.edge_count());
2402    for node in &graph.modules {
2403        let Some(source) = index.index_of_file_id(node.file_id.0) else {
2404            continue;
2405        };
2406        for (target_id, symbols) in graph.outgoing_symbol_edges(node.file_id) {
2407            let Some(target) = index.index_of_file_id(target_id.0) else {
2408                continue;
2409            };
2410            let all_type_only = !symbols.is_empty() && symbols.iter().all(|s| s.is_type_only);
2411            let flags = if all_type_only {
2412                EDGE_FLAG_TYPE_ONLY
2413            } else if symbols.iter().any(|s| s.is_eager_value()) {
2414                0
2415            } else {
2416                EDGE_FLAG_DYNAMIC
2417            };
2418            edges.push([source, target, flags]);
2419        }
2420    }
2421    edges
2422}
2423
2424/// Complexity aggregates for one file, folded from its parsed functions.
2425#[derive(Default)]
2426struct ComplexityRollup {
2427    fn_count: u16,
2428    max_cyclomatic: u16,
2429    max_cognitive: u16,
2430    react_hooks: u16,
2431    jsx_depth: u16,
2432    functions: Vec<VizFunction>,
2433}
2434
2435fn rollup_complexity(functions: &[FunctionComplexity]) -> ComplexityRollup {
2436    let mut rollup = ComplexityRollup {
2437        fn_count: clamp_u16(functions.len()),
2438        ..ComplexityRollup::default()
2439    };
2440    for f in functions {
2441        rollup.max_cyclomatic = rollup.max_cyclomatic.max(f.cyclomatic);
2442        rollup.max_cognitive = rollup.max_cognitive.max(f.cognitive);
2443        rollup.react_hooks = rollup.react_hooks.saturating_add(f.react_hook_count);
2444        rollup.jsx_depth = rollup.jsx_depth.max(f.react_jsx_max_depth);
2445    }
2446
2447    // Named functions only, hardest-first: the panel lists these and folds the
2448    // (often many) anonymous arrow/callback functions into a single count via
2449    // `fn_count`. Placeholder names for unnamed functions are `<arrow>` /
2450    // `<anonymous>`, so a leading `<` marks the ones to fold away.
2451    let mut named: Vec<&FunctionComplexity> = functions
2452        .iter()
2453        .filter(|f| !f.name.starts_with('<'))
2454        .collect();
2455    named.sort_by(|a, b| {
2456        b.cyclomatic
2457            .cmp(&a.cyclomatic)
2458            .then(b.cognitive.cmp(&a.cognitive))
2459    });
2460    rollup.functions = named
2461        .into_iter()
2462        .map(|f| VizFunction {
2463            name: f.name.clone(),
2464            line: f.line,
2465            cyclomatic: f.cyclomatic,
2466            cognitive: f.cognitive,
2467            lines: f.line_count,
2468            hooks: f.react_hook_count,
2469            jsx_depth: f.react_jsx_max_depth,
2470            props: f.react_prop_count,
2471        })
2472        .collect();
2473    rollup
2474}
2475
2476fn build_files(
2477    input: &VizBuildInput<'_>,
2478    index: &FileIndex<'_>,
2479    maps: &FilePropertyMaps<'_>,
2480) -> Vec<VizFile> {
2481    let graph = input.graph.as_graph();
2482    let unused_file_paths: rustc_hash::FxHashSet<&Path> = input
2483        .results
2484        .unused_files
2485        .iter()
2486        .map(|f| f.file.path.as_path())
2487        .collect();
2488
2489    let mut unused_exports_by_file: FxHashMap<&Path, Vec<String>> = FxHashMap::default();
2490    for export in &input.results.unused_exports {
2491        unused_exports_by_file
2492            .entry(export.export.path.as_path())
2493            .or_default()
2494            .push(export.export.export_name.clone());
2495    }
2496    for export in &input.results.unused_types {
2497        unused_exports_by_file
2498            .entry(export.export.path.as_path())
2499            .or_default()
2500            .push(export.export.export_name.clone());
2501    }
2502
2503    let mut complexity_by_file_id: FxHashMap<u32, ComplexityRollup> = FxHashMap::default();
2504    if let Some(modules) = input.modules {
2505        for module in modules {
2506            if !module.complexity.is_empty() {
2507                complexity_by_file_id
2508                    .insert(module.file_id.0, rollup_complexity(&module.complexity));
2509            }
2510        }
2511    }
2512
2513    let mut in_cycle = vec![false; index.ordered.len()];
2514    for cycle in maps.cycles {
2515        for &idx in cycle {
2516            if let Some(slot) = in_cycle.get_mut(idx as usize) {
2517                *slot = true;
2518            }
2519        }
2520    }
2521
2522    index
2523        .ordered
2524        .iter()
2525        .enumerate()
2526        .map(|(i, file)| {
2527            let viz_idx = clamp_u32(i);
2528            let node_idx = file.id.0 as usize;
2529            let node = graph.modules.get(node_idx);
2530            let is_entry = node.is_some_and(|n| n.is_entry_point());
2531            let export_count = node.map_or(0, |n| clamp_u16(n.exports.len()));
2532            let import_count = clamp_u16(graph.edges_for(file.id).len());
2533            let importer_count = clamp_u16(input.graph.direct_importer_count(file.id));
2534
2535            let unused_export_names = unused_exports_by_file
2536                .remove(file.path.as_path())
2537                .unwrap_or_default();
2538            let unused_export_count = clamp_u16(unused_export_names.len());
2539
2540            let status = if unused_file_paths.contains(file.path.as_path()) {
2541                VizFileStatus::Unused
2542            } else if unused_export_count > 0 {
2543                VizFileStatus::HasUnusedExports
2544            } else if is_entry {
2545                VizFileStatus::EntryPoint
2546            } else {
2547                VizFileStatus::Clean
2548            };
2549
2550            let complexity = complexity_by_file_id.remove(&file.id.0).unwrap_or_default();
2551
2552            VizFile {
2553                path: relative_path(&file.path, &input.config.root),
2554                size: file.size_bytes,
2555                status,
2556                export_count,
2557                unused_export_count,
2558                is_entry,
2559                importer_count,
2560                import_count,
2561                workspace: workspace_index_for(&file.path, input.workspaces),
2562                zone: maps.zone_by_file.get(&viz_idx).copied(),
2563                unused_exports: unused_export_names,
2564                fn_count: complexity.fn_count,
2565                max_cyclomatic: complexity.max_cyclomatic,
2566                max_cognitive: complexity.max_cognitive,
2567                react_hooks: complexity.react_hooks,
2568                jsx_depth: complexity.jsx_depth,
2569                functions: complexity.functions,
2570                dup_lines: maps.dup_lines_by_file.get(&viz_idx).copied().unwrap_or(0),
2571                clone_groups: maps
2572                    .clone_groups_by_file
2573                    .get(&viz_idx)
2574                    .cloned()
2575                    .unwrap_or_default(),
2576                in_cycle: in_cycle[i],
2577            }
2578        })
2579        .collect()
2580}
2581
2582fn build_summary(
2583    input: &VizBuildInput<'_>,
2584    files: &[VizFile],
2585    clones: &[VizCloneGroup],
2586    cycles: &[Vec<u32>],
2587    violations: &[VizViolation],
2588    clone_groups_truncated: u32,
2589) -> VizSummary {
2590    let results = input.results;
2591    VizSummary {
2592        total_files: files.len(),
2593        total_size: files.iter().map(|f| f.size).sum(),
2594        total_edges: input.graph.edge_count(),
2595        unused_files: results.unused_files.len(),
2596        unused_exports: results.unused_exports.len() + results.unused_types.len(),
2597        unused_types: results.unused_types.len(),
2598        unused_deps: results.unused_dependencies.len()
2599            + results.unused_dev_dependencies.len()
2600            + results.unused_optional_dependencies.len(),
2601        unresolved_imports: results.unresolved_imports.len(),
2602        circular_deps: cycles.len(),
2603        clone_groups: clones.len(),
2604        duplicated_lines: clones.iter().map(|c| c.lines * c.instances.len()).sum(),
2605        boundary_violations: violations.len(),
2606        hotspot_files: files
2607            .iter()
2608            .filter(|f| f.max_cyclomatic >= HOTSPOT_CYCLOMATIC_FLOOR)
2609            .count(),
2610        clone_groups_truncated: (clone_groups_truncated > 0).then_some(clone_groups_truncated),
2611    }
2612}
2613
2614fn clamp_u16(value: usize) -> u16 {
2615    u16::try_from(value).unwrap_or(u16::MAX)
2616}
2617
2618fn clamp_u32(value: usize) -> u32 {
2619    u32::try_from(value).unwrap_or(u32::MAX)
2620}
2621
2622#[cfg(test)]
2623mod tests {
2624    use std::path::PathBuf;
2625
2626    use fallow_config::{BoundaryConfig, BoundaryZone, FallowConfig};
2627    use fallow_graph::graph::ModuleGraph;
2628    use fallow_graph::resolve::{ResolveResult, ResolvedImport, ResolvedModule};
2629    use fallow_types::duplicates::{CloneGroup, CloneInstance};
2630    use fallow_types::extract::{ImportInfo, ImportedName};
2631    use fallow_types::output_dead_code::{BoundaryViolationFinding, CircularDependencyFinding};
2632    use fallow_types::output_format::OutputFormat;
2633    use fallow_types::results::{BoundaryViolation, CircularDependency};
2634
2635    use super::*;
2636    use crate::discover::{EntryPoint, EntryPointSource, FileId};
2637
2638    /// Owned fixture parts backing one [`VizBuildInput`].
2639    struct Fixture {
2640        config: ResolvedConfig,
2641        files: Vec<DiscoveredFile>,
2642        results: AnalysisResults,
2643        graph: crate::module_graph::RetainedModuleGraph,
2644        duplication: DuplicationReport,
2645        workspaces: Vec<WorkspaceInfo>,
2646    }
2647
2648    impl Fixture {
2649        fn input(&self) -> VizBuildInput<'_> {
2650            VizBuildInput {
2651                results: &self.results,
2652                graph: &self.graph,
2653                modules: None,
2654                files: &self.files,
2655                duplication: &self.duplication,
2656                workspaces: &self.workspaces,
2657                config: &self.config,
2658                feature_flags: &[],
2659                include_analysis_details: true,
2660            }
2661        }
2662    }
2663
2664    fn project_root() -> PathBuf {
2665        PathBuf::from("/viz-project")
2666    }
2667
2668    fn discovered(id: u32, path: PathBuf, size_bytes: u64) -> DiscoveredFile {
2669        DiscoveredFile {
2670            id: FileId(id),
2671            path,
2672            size_bytes,
2673        }
2674    }
2675
2676    fn import_of(target: FileId, specifier: &str) -> ResolvedImport {
2677        ResolvedImport {
2678            info: ImportInfo {
2679                source: specifier.to_owned(),
2680                imported_name: ImportedName::Named("value".to_owned()),
2681                local_name: "value".to_owned(),
2682                is_type_only: false,
2683                is_type_only_star: false,
2684                from_style: false,
2685                span: oxc_span::Span::new(0, 0),
2686                source_span: oxc_span::Span::new(0, 0),
2687            },
2688            target: ResolveResult::InternalModule(target),
2689        }
2690    }
2691
2692    fn zone(name: &str, pattern: &str) -> BoundaryZone {
2693        BoundaryZone {
2694            name: name.to_owned(),
2695            patterns: vec![pattern.to_owned()],
2696            auto_discover: Vec::new(),
2697            root: None,
2698        }
2699    }
2700
2701    fn resolved_config(root: &Path) -> ResolvedConfig {
2702        let config = FallowConfig {
2703            boundaries: BoundaryConfig {
2704                zones: vec![zone("app", "src/**"), zone("shared", "lib/**")],
2705                ..BoundaryConfig::default()
2706            },
2707            ..FallowConfig::default()
2708        };
2709        config.resolve(root.to_path_buf(), OutputFormat::Json, 1, false, true, None)
2710    }
2711
2712    fn cycle_finding(files: Vec<PathBuf>) -> CircularDependencyFinding {
2713        let length = files.len();
2714        CircularDependencyFinding::with_actions(CircularDependency {
2715            files,
2716            length,
2717            line: 1,
2718            col: 0,
2719            edges: Vec::new(),
2720            is_cross_package: false,
2721        })
2722    }
2723
2724    fn violation_finding(from_path: PathBuf, to_path: PathBuf) -> BoundaryViolationFinding {
2725        BoundaryViolationFinding::with_actions(BoundaryViolation {
2726            from_path,
2727            to_path,
2728            from_zone: "app".to_owned(),
2729            to_zone: "shared".to_owned(),
2730            import_specifier: "../lib/c".to_owned(),
2731            line: 2,
2732            col: 0,
2733            via_path: None,
2734        })
2735    }
2736
2737    fn clone_instance(file: PathBuf, start_line: usize, end_line: usize) -> CloneInstance {
2738        CloneInstance {
2739            is_symlink: false,
2740            file,
2741            start_line,
2742            end_line,
2743            start_col: 0,
2744            end_col: 0,
2745            fragment: "const shared = 1;\nconst repeated = 2;\nconst block = 3;".to_owned(),
2746        }
2747    }
2748
2749    fn clone_group(instances: Vec<CloneInstance>) -> CloneGroup {
2750        CloneGroup {
2751            instances,
2752            token_count: 12,
2753            line_count: 3,
2754            similarity: None,
2755        }
2756    }
2757
2758    /// Synthetic project: 3 files, one import edge a to b, one resolvable
2759    /// cycle (a, b) plus one unresolvable, one clone group over (a, c) plus a
2760    /// dropped and a same-file group, one resolvable boundary violation a to
2761    /// c plus one unresolvable, two zones, one workspace over `lib/`.
2762    fn fixture_with(extra_graph_file: bool) -> Fixture {
2763        let root = project_root();
2764        let a = root.join("src/a.ts");
2765        let b = root.join("src/b.ts");
2766        let c = root.join("lib/c.ts");
2767        let missing = root.join("src/missing.ts");
2768
2769        let files = vec![
2770            discovered(0, a.clone(), 100),
2771            discovered(1, b.clone(), 50),
2772            discovered(2, c.clone(), 25),
2773        ];
2774
2775        let mut graph_files = files.clone();
2776        let mut imports = vec![import_of(FileId(1), "./b")];
2777        if extra_graph_file {
2778            graph_files.push(discovered(3, root.join("src/d.ts"), 10));
2779            imports.push(import_of(FileId(3), "./d"));
2780        }
2781        let resolved = vec![ResolvedModule {
2782            file_id: FileId(0),
2783            path: a.clone(),
2784            resolved_imports: imports,
2785            ..ResolvedModule::default()
2786        }];
2787        let entry_points = vec![EntryPoint {
2788            path: a.clone(),
2789            source: EntryPointSource::PackageJsonMain,
2790        }];
2791        let graph = crate::module_graph::RetainedModuleGraph::from(ModuleGraph::build(
2792            &resolved,
2793            &entry_points,
2794            &graph_files,
2795        ));
2796
2797        let results = AnalysisResults {
2798            circular_dependencies: vec![
2799                cycle_finding(vec![a.clone(), b]),
2800                cycle_finding(vec![a.clone(), missing.clone()]),
2801            ],
2802            boundary_violations: vec![
2803                violation_finding(a.clone(), c.clone()),
2804                violation_finding(a.clone(), missing),
2805            ],
2806            ..AnalysisResults::default()
2807        };
2808
2809        let duplication = DuplicationReport {
2810            clone_groups: vec![
2811                clone_group(vec![
2812                    clone_instance(a.clone(), 1, 3),
2813                    clone_instance(c, 10, 12),
2814                ]),
2815                clone_group(vec![
2816                    clone_instance(a.clone(), 20, 22),
2817                    clone_instance(root.join("outside.ts"), 1, 3),
2818                ]),
2819                clone_group(vec![
2820                    clone_instance(a.clone(), 30, 32),
2821                    clone_instance(a, 40, 42),
2822                ]),
2823            ],
2824            ..DuplicationReport::default()
2825        };
2826
2827        let workspaces = vec![WorkspaceInfo {
2828            root: root.join("lib"),
2829            name: "shared-lib".to_owned(),
2830            is_internal_dependency: false,
2831        }];
2832
2833        Fixture {
2834            config: resolved_config(&root),
2835            files,
2836            results,
2837            graph,
2838            duplication,
2839            workspaces,
2840        }
2841    }
2842
2843    fn fixture() -> Fixture {
2844        fixture_with(false)
2845    }
2846
2847    #[test]
2848    fn files_and_edges_use_stable_indices() {
2849        let fx = fixture();
2850        let data = build_viz_data(&fx.input());
2851
2852        let paths: Vec<&str> = data.files.iter().map(|f| f.path.as_str()).collect();
2853        assert_eq!(paths, ["src/a.ts", "src/b.ts", "lib/c.ts"]);
2854        assert_eq!(data.edges, vec![[0, 1, 0]]);
2855        assert!(data.files[0].is_entry);
2856        assert!(matches!(data.files[0].status, VizFileStatus::EntryPoint));
2857        assert!(matches!(data.files[1].status, VizFileStatus::Clean));
2858        assert_eq!(data.files[0].import_count, 1);
2859        assert_eq!(data.files[1].importer_count, 1);
2860        assert_eq!(data.files[0].workspace, None);
2861        assert_eq!(data.files[2].workspace, Some(0));
2862        assert_eq!(data.workspaces.len(), 1);
2863        assert_eq!(data.workspaces[0].root, "lib");
2864    }
2865
2866    #[test]
2867    fn a_dynamic_import_edge_carries_the_dynamic_flag() {
2868        let root = project_root();
2869        let a = root.join("src/a.ts");
2870        let files = vec![
2871            discovered(0, a.clone(), 100),
2872            discovered(1, root.join("src/b.ts"), 50),
2873            discovered(2, root.join("src/c.ts"), 25),
2874        ];
2875        let resolved = vec![ResolvedModule {
2876            file_id: FileId(0),
2877            path: a.clone(),
2878            resolved_imports: vec![import_of(FileId(1), "./b")],
2879            resolved_dynamic_imports: vec![import_of(FileId(2), "./c")],
2880            ..ResolvedModule::default()
2881        }];
2882        let entry_points = vec![EntryPoint {
2883            path: a,
2884            source: EntryPointSource::PackageJsonMain,
2885        }];
2886        let fx = Fixture {
2887            graph: crate::module_graph::RetainedModuleGraph::from(ModuleGraph::build(
2888                &resolved,
2889                &entry_points,
2890                &files,
2891            )),
2892            files,
2893            ..fixture()
2894        };
2895        let data = build_viz_data(&fx.input());
2896
2897        assert_eq!(data.edges, vec![[0, 1, 0], [0, 2, EDGE_FLAG_DYNAMIC]]);
2898    }
2899
2900    #[test]
2901    fn edges_to_files_missing_from_input_are_dropped() {
2902        let fx = fixture_with(true);
2903        let data = build_viz_data(&fx.input());
2904
2905        // The graph carries a to b AND a to d, but d is not in `input.files`,
2906        // so build_edges drops the second edge instead of emitting a
2907        // dangling index.
2908        assert_eq!(fx.graph.edge_count(), 2);
2909        assert_eq!(data.edges, vec![[0, 1, 0]]);
2910    }
2911
2912    #[test]
2913    fn clone_groups_drop_unresolvable_and_dedup_per_file() {
2914        let fx = fixture();
2915        let data = build_viz_data(&fx.input());
2916
2917        // The group whose second instance lives outside `input.files` keeps
2918        // only 1 resolvable instance and is dropped entirely.
2919        assert_eq!(data.clones.len(), 2);
2920        assert_eq!(data.clones[0].instances.len(), 2);
2921        assert_eq!(data.clones[0].instances[0].file, 0);
2922        assert_eq!(data.clones[0].instances[1].file, 2);
2923        assert_eq!(data.clones[0].lines, 3);
2924        assert_eq!(data.clones[0].tokens, 12);
2925        // Two same-file instances in one group dedup to a single group id.
2926        assert_eq!(data.files[0].clone_groups, vec![0, 1]);
2927        assert_eq!(data.files[2].clone_groups, vec![0]);
2928        // dup_lines sums (end minus start plus 1) per resolvable instance.
2929        assert_eq!(data.files[0].dup_lines, 9);
2930        assert_eq!(data.files[2].dup_lines, 3);
2931        assert_eq!(data.files[1].dup_lines, 0);
2932    }
2933
2934    #[test]
2935    fn truncate_preview_caps_lines_and_bytes() {
2936        // Line cap: more lines than the cap in, CLONE_PREVIEW_MAX_LINES out
2937        // plus the ellipsis appended directly after the last kept line.
2938        let last_kept = CLONE_PREVIEW_MAX_LINES - 1;
2939        let many_lines = (0..CLONE_PREVIEW_MAX_LINES + 5)
2940            .map(|i| format!("line {i}"))
2941            .collect::<Vec<_>>();
2942        let out = truncate_preview(&many_lines.join("\n"));
2943        assert_eq!(out.matches('\n').count(), CLONE_PREVIEW_MAX_LINES - 1);
2944        assert!(out.contains(&format!("line {last_kept}")));
2945        assert!(!out.contains(&format!("line {CLONE_PREVIEW_MAX_LINES}")));
2946        assert!(out.ends_with('\u{2026}'));
2947
2948        // Byte budget: the second big line would exceed CLONE_PREVIEW_MAX_BYTES,
2949        // so output stops after the first line.
2950        let big = CLONE_PREVIEW_MAX_BYTES * 3 / 4;
2951        let two_long_lines = format!("{}\n{}", "a".repeat(big), "b".repeat(big));
2952        let out = truncate_preview(&two_long_lines);
2953        assert_eq!(out, format!("{}\u{2026}", "a".repeat(big)));
2954
2955        // Multi-byte content over budget truncates at a line boundary and
2956        // never slices inside a character (4 bytes per emoji, well over budget).
2957        let emoji_line = "\u{1f389}".repeat(CLONE_PREVIEW_MAX_BYTES);
2958        let out = truncate_preview(&emoji_line);
2959        assert_eq!(out, "\u{2026}");
2960    }
2961
2962    #[test]
2963    fn clone_preview_windows_context_around_the_block() {
2964        use std::io::Write as _;
2965
2966        // 20 numbered source lines; the copied block covers lines 8..=11.
2967        let mut file = tempfile::NamedTempFile::new().expect("temp file");
2968        let body = (1..=20)
2969            .map(|i| format!("line {i}"))
2970            .collect::<Vec<_>>()
2971            .join("\n");
2972        file.write_all(body.as_bytes()).expect("write source");
2973        let inst = clone_instance(file.path().to_path_buf(), 8, 11);
2974
2975        let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
2976        let preview_lines: Vec<&str> = preview.lines().collect();
2977
2978        // Block (4 lines) plus 4 lines of context each side fits the cap, so
2979        // the full window is kept: 4 dimmed + 4 highlighted + 4 dimmed.
2980        assert_eq!(preview_lines.len(), 12);
2981        assert_eq!(highlight_start, 4);
2982        assert_eq!(highlight_lines, 4);
2983        assert_eq!(preview_lines.first(), Some(&"line 4"));
2984        let start = highlight_start as usize;
2985        let end = start + highlight_lines as usize;
2986        assert_eq!(
2987            &preview_lines[start..end],
2988            ["line 8", "line 9", "line 10", "line 11"],
2989        );
2990        // The line directly above the block is dimmed context, not copied.
2991        assert_eq!(preview_lines[start - 1], "line 7");
2992    }
2993
2994    #[test]
2995    fn clone_preview_keeps_leading_context_when_the_block_fills_the_cap() {
2996        use std::io::Write as _;
2997
2998        // A block far larger than the cap. The old logic zeroed the context
2999        // and highlighted the whole (truncated) window; the fix keeps the
3000        // leading context dimmed so the highlight still reads against it.
3001        let mut file = tempfile::NamedTempFile::new().expect("temp file");
3002        let body = (1..=200)
3003            .map(|i| format!("line {i}"))
3004            .collect::<Vec<_>>()
3005            .join("\n");
3006        file.write_all(body.as_bytes()).expect("write source");
3007        let inst = clone_instance(file.path().to_path_buf(), 50, 150);
3008
3009        let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
3010        let preview_lines: Vec<&str> = preview.lines().collect();
3011
3012        assert_eq!(highlight_start, CLONE_PREVIEW_CONTEXT as u32);
3013        assert!(
3014            highlight_start > 0,
3015            "leading context must survive a huge block"
3016        );
3017        assert_eq!(preview_lines.len(), CLONE_PREVIEW_MAX_LINES);
3018        assert_eq!(
3019            highlight_lines as usize,
3020            CLONE_PREVIEW_MAX_LINES - CLONE_PREVIEW_CONTEXT,
3021        );
3022        assert_eq!(preview_lines[highlight_start as usize - 1], "line 49");
3023        assert_eq!(preview_lines[highlight_start as usize], "line 50");
3024    }
3025
3026    #[test]
3027    fn clone_preview_clamps_context_at_file_start() {
3028        use std::io::Write as _;
3029
3030        let mut file = tempfile::NamedTempFile::new().expect("temp file");
3031        file.write_all(b"line 1\nline 2\nline 3\nline 4\nline 5")
3032            .expect("write source");
3033        // Block at the very top: no context fits above it, so the highlight
3034        // starts at index 0 and the trailing lines are dimmed context.
3035        let inst = clone_instance(file.path().to_path_buf(), 1, 2);
3036
3037        let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
3038        assert_eq!(highlight_start, 0);
3039        assert_eq!(highlight_lines, 2);
3040        assert_eq!(preview, "line 1\nline 2\nline 3\nline 4\nline 5");
3041    }
3042
3043    #[test]
3044    fn clone_preview_falls_back_when_source_is_unreadable() {
3045        // A missing file forces the fragment fallback: the whole block is
3046        // highlighted so nothing is dimmed.
3047        let inst = clone_instance(project_root().join("does-not-exist.ts"), 1, 3);
3048        let (preview, highlight_start, highlight_lines) = build_clone_preview(&inst);
3049        assert_eq!(preview, inst.fragment);
3050        assert_eq!(highlight_start, 0);
3051        assert_eq!(highlight_lines as usize, preview.lines().count());
3052    }
3053
3054    #[test]
3055    fn cycles_drop_when_any_member_unresolved() {
3056        let fx = fixture();
3057        let data = build_viz_data(&fx.input());
3058
3059        // The a/b cycle resolves fully; the cycle referencing the missing
3060        // file yields no entry at all (not a partial one).
3061        assert_eq!(data.cycles, vec![vec![0, 1]]);
3062        assert!(data.files[0].in_cycle);
3063        assert!(data.files[1].in_cycle);
3064        assert!(!data.files[2].in_cycle);
3065        // The summary counts the rendered cycles, not the raw results, so
3066        // the dropped cycle does not inflate the header number.
3067        assert_eq!(data.summary.circular_deps, data.cycles.len());
3068    }
3069
3070    #[test]
3071    fn violations_resolve_zone_and_file_indices() {
3072        let fx = fixture();
3073        let data = build_viz_data(&fx.input());
3074
3075        assert_eq!(data.zones.len(), 2);
3076        assert_eq!(data.zones[0].name, "app");
3077        assert_eq!(data.zones[0].files, 2);
3078        assert_eq!(data.zones[1].name, "shared");
3079        assert_eq!(data.zones[1].files, 1);
3080        assert_eq!(data.files[0].zone, Some(0));
3081        assert_eq!(data.files[1].zone, Some(0));
3082        assert_eq!(data.files[2].zone, Some(1));
3083
3084        // The violation whose to_path is not in `input.files` is dropped.
3085        assert_eq!(data.violations.len(), 1);
3086        let v = &data.violations[0];
3087        assert_eq!((v.from, v.to), (0, 2));
3088        assert_eq!((v.from_zone, v.to_zone), (0, 1));
3089        assert_eq!(v.line, 2);
3090        assert_eq!(v.specifier, "../lib/c");
3091    }
3092
3093    #[test]
3094    fn clone_group_cap_counts_truncated_groups() {
3095        let fx = fixture();
3096        let index = FileIndex::new(&fx.files);
3097
3098        // The fixture report has two keepable groups plus one dropped for
3099        // unresolvable instances; a cap of 1 keeps the first keepable group
3100        // and counts only the second as truncated (the unresolvable drop is
3101        // not a truncation).
3102        let (clones, groups_by_file, _dup_lines, truncated) =
3103            build_clones(&fx.duplication, &index, 1);
3104        assert_eq!(clones.len(), 1);
3105        assert_eq!(truncated, 1);
3106        assert!(
3107            groups_by_file
3108                .values()
3109                .all(|ids| ids.iter().all(|&id| (id as usize) < clones.len()))
3110        );
3111
3112        // The default cap leaves a small report untouched and unflagged.
3113        let data = build_viz_data(&fx.input());
3114        assert_eq!(data.clones.len(), 2);
3115        assert_eq!(data.summary.clone_groups_truncated, None);
3116    }
3117
3118    #[test]
3119    fn summary_flags_clone_truncation_only_when_nonzero() {
3120        let fx = fixture();
3121        let data = build_viz_data(&fx.input());
3122
3123        let summary = build_summary(&fx.input(), &data.files, &data.clones, &[], &[], 3);
3124        assert_eq!(summary.clone_groups_truncated, Some(3));
3125        let summary = build_summary(&fx.input(), &data.files, &data.clones, &[], &[], 0);
3126        assert_eq!(summary.clone_groups_truncated, None);
3127    }
3128
3129    #[test]
3130    fn summary_counts_match_rendered_arrays() {
3131        let fx = fixture();
3132        let data = build_viz_data(&fx.input());
3133        let s = &data.summary;
3134
3135        assert_eq!(s.total_files, data.files.len());
3136        assert_eq!(s.total_size, 175);
3137        assert_eq!(s.total_edges, data.edges.len());
3138        assert_eq!(s.clone_groups, data.clones.len());
3139        assert_eq!(s.duplicated_lines, 12);
3140        assert_eq!(s.hotspot_files, 0);
3141        assert_eq!(s.unused_files, 0);
3142        assert_eq!(s.unused_exports, 0);
3143        // The raw results carry one unresolvable cycle and one unresolvable
3144        // violation; the header counts only what the arrays render.
3145        assert_eq!(s.circular_deps, data.cycles.len());
3146        assert_eq!(s.circular_deps, 1);
3147        assert_eq!(s.boundary_violations, data.violations.len());
3148        assert_eq!(s.boundary_violations, 1);
3149    }
3150
3151    #[test]
3152    fn payload_keeps_counts_and_availability_explicit() {
3153        let fx = fixture();
3154        let data = build_viz_data(&fx.input());
3155        let value = serde_json::to_value(&data).expect("viz data serializes");
3156
3157        assert_eq!(value["architecture"]["availability"]["unit"], "violations");
3158        assert_eq!(value["dependencies"]["availability"]["unit"], "findings");
3159        assert_eq!(value["security"]["availability"]["unit"], "candidates");
3160        assert_eq!(value["security"]["availability"]["state"], "complete");
3161        assert_eq!(
3162            value["security"]["runtime_availability"]["state"],
3163            "unavailable"
3164        );
3165        assert_eq!(value["health"]["availability"]["state"], "unavailable");
3166        assert_eq!(
3167            value["health"]["capabilities"]["coverage"]["state"],
3168            "unavailable"
3169        );
3170        assert!(value["frameworks"]["detectors"].is_array());
3171        assert_eq!(
3172            value["frameworks"]["detector_availability"]["state"],
3173            "unavailable"
3174        );
3175        assert!(value["styling"].get("score").is_none());
3176    }
3177
3178    /// A completed Health run still knows nothing about production execution
3179    /// unless a runtime coverage input was supplied. The lens must say that
3180    /// instead of letting a complete static answer imply a complete one.
3181    #[test]
3182    fn health_reports_runtime_evidence_as_unavailable_without_a_runtime_input() {
3183        let fx = fixture();
3184        let mut data = build_viz_data(&fx.input());
3185        apply_health_report(&mut data, &HealthReport::default(), Path::new("/project"));
3186        let value = serde_json::to_value(&data).expect("viz data serializes");
3187
3188        assert_eq!(value["health"]["availability"]["state"], "complete");
3189        let runtime = &value["health"]["capabilities"]["runtime"];
3190        assert_eq!(runtime["state"], "unavailable");
3191        assert_eq!(runtime["unit"], "observations");
3192        assert_eq!(runtime["reason"], NO_RUNTIME_COVERAGE_REASON);
3193        assert_eq!(runtime["count"], 0);
3194        assert_eq!(
3195            value["security"]["runtime_availability"]["reason"],
3196            NO_RUNTIME_COVERAGE_REASON
3197        );
3198    }
3199
3200    /// A drive-less rooted path is rooted but NOT absolute on Windows, so a
3201    /// redaction gated on `is_absolute` skipped it there and leaked the full
3202    /// path. Pinned on every platform because the predicate must not regress.
3203    #[test]
3204    fn rooted_paths_without_a_drive_are_redacted() {
3205        let root = Path::new("/project");
3206        assert_eq!(
3207            relative_path(Path::new("/Users/private/secret.ts"), root),
3208            "<external>/secret.ts"
3209        );
3210        assert_eq!(
3211            relative_path(Path::new("/etc/passwd"), root),
3212            "<external>/passwd"
3213        );
3214        // A genuinely relative path is not redacted; it is project-relative.
3215        assert_eq!(relative_path(Path::new("src/a.ts"), root), "src/a.ts");
3216
3217        // The JSON layer gates on the same predicate and must agree.
3218        let mut detail = serde_json::json!({ "path": "/Users/private/secret.ts" });
3219        relativize_value_paths(&mut detail, root);
3220        assert_eq!(detail["path"], "<external>/secret.ts");
3221
3222        // A value that is not under a path key is left alone regardless, so a
3223        // route specifier does not get treated as a filesystem path.
3224        let mut route = serde_json::json!({ "specifier": "/api/v1" });
3225        relativize_value_paths(&mut route, root);
3226        assert_eq!(route["specifier"], "/api/v1");
3227    }
3228
3229    #[test]
3230    fn external_absolute_paths_are_redacted() {
3231        let root = Path::new("/project");
3232        assert_eq!(
3233            relative_path(Path::new("/project/src/a.ts"), root),
3234            "src/a.ts"
3235        );
3236        assert_eq!(
3237            relative_path(Path::new("/Users/private/secret.ts"), root),
3238            "<external>/secret.ts"
3239        );
3240
3241        let mut detail = serde_json::json!({ "path": "/Users/private/secret.ts" });
3242        relativize_value_paths(&mut detail, root);
3243        assert_eq!(detail["path"], "<external>/secret.ts");
3244
3245        let mut route = serde_json::json!({ "specifier": "/api/v1" });
3246        relativize_value_paths(&mut route, root);
3247        assert_eq!(route["specifier"], "/api/v1");
3248
3249        let mut conflicts = serde_json::json!({
3250            "conflicting_paths": ["/project/app/a.ts", "/project/app/b.ts"]
3251        });
3252        relativize_value_paths(&mut conflicts, root);
3253        assert_eq!(conflicts["conflicting_paths"][0], "app/a.ts");
3254        assert_eq!(conflicts["conflicting_paths"][1], "app/b.ts");
3255    }
3256
3257    #[test]
3258    fn config_action_values_are_not_rendered_as_commands() {
3259        let finding = finding_from_value(
3260            "dependency",
3261            "Dependency finding",
3262            serde_json::json!({
3263                "actions": [{
3264                    "kind": "add-to-config",
3265                    "auto_fixable": false,
3266                    "config_key": "entry",
3267                    "value": "./errors",
3268                    "description": "Add the entry to configuration"
3269                }]
3270            }),
3271            Path::new("/project"),
3272            &|_| None,
3273        );
3274        assert_eq!(finding.actions.len(), 1);
3275        let action = &finding.actions[0];
3276        assert_eq!(action.kind.as_deref(), Some("add-to-config"));
3277        assert!(!action.auto_fixable);
3278        assert_eq!(action.config_key.as_deref(), Some("entry"));
3279        assert_eq!(action.value, Some(Value::String("./errors".to_string())));
3280        assert!(action.command.is_none());
3281    }
3282}