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