repotoire 0.8.2

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
//! React Hooks Rules Detector
//!
//! Graph-enhanced detection of React hooks violations:
//! - Hooks called conditionally
//! - Hooks called in loops
//! - Hooks called in nested functions
//! - Missing dependencies in useEffect/useMemo/useCallback
//! - Use graph to check component hierarchy

use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphQueryExt;
use crate::models::{deterministic_finding_id, Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::path::PathBuf;
use std::sync::LazyLock;
use tracing::info;

static HOOK_CALL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\b(useState|useEffect|useContext|useReducer|useCallback|useMemo|useRef|useImperativeHandle|useLayoutEffect|useDebugValue|useTransition|useDeferredValue|useId|useSyncExternalStore|useInsertionEffect|use[A-Z]\w*)\s*\(").expect("valid regex")
});
static CONDITIONAL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(if\s*\(|else\s*\{|switch\s*\(|\?\s*$|&&\s*$|\|\|\s*$|.*\?\s*use[A-Z]|.*&&\s*use[A-Z]|.*\|\|\s*use[A-Z])")
            .expect("valid regex")
});
static LOOP: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(for\s*\(|while\s*\(|\.forEach\(|\.map\(|\.filter\(|\.reduce\(|\.flatMap\()")
        .expect("valid regex")
});
static NESTED_FUNC: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(function\s+\w+|const\s+\w+\s*=\s*(async\s+)?\(|const\s+\w+\s*=\s*(async\s+)?function)").expect("valid regex")
});
static COMPONENT: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?:function|const)\s+([A-Z][a-zA-Z0-9]*)\s*[=(]|export\s+(?:default\s+)?(?:function|const)\s+([A-Z][a-zA-Z0-9]*)").expect("valid regex")
});
#[allow(dead_code)] // Used by USE_EFFECT for future hook dependency analysis
static USE_EFFECT: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(useEffect|useMemo|useCallback)\s*\(\s*(?:\([^)]*\)|[^,]+)\s*,\s*\[([^\]]*)\]")
        .expect("valid regex")
});

/// Extract hook name from line
fn extract_hook_name(line: &str) -> Option<String> {
    if let Some(matched) = HOOK_CALL.find(line) {
        let hook = matched.as_str();
        Some(hook.trim_end_matches(['(', ' ']).to_string())
    } else {
        None
    }
}

/// Categorize the violation type
fn categorize_violation(
    in_conditional: bool,
    in_loop: bool,
    in_nested: bool,
) -> (&'static str, &'static str) {
    if in_loop {
        return ("loop", "Hook called inside a loop");
    }
    if in_conditional {
        return ("conditional", "Hook called conditionally");
    }
    if in_nested {
        return ("nested", "Hook called in nested function");
    }
    ("unknown", "Hooks rule violation")
}

pub struct ReactHooksDetector {
    #[allow(dead_code)] // Part of detector pattern, used for file scanning
    repository_path: PathBuf,
    max_findings: usize,
}

impl ReactHooksDetector {
    crate::detectors::detector_new!(50);

    /// Find containing component from graph
    fn find_component(
        graph: &dyn crate::graph::GraphQuery,
        file_path: &str,
        line: u32,
    ) -> Option<String> {
        let i = graph.interner();
        graph
            .get_functions()
            .into_iter()
            .find(|f| {
                f.path(i) == file_path
                    && f.line_start <= line
                    && f.line_end >= line
                    && f.node_name(i)
                        .chars()
                        .next()
                        .map(|c| c.is_uppercase())
                        .unwrap_or(false)
            })
            .map(|f| f.node_name(i).to_string())
    }

    /// Check for custom hooks (functions starting with 'use')
    #[allow(dead_code)] // Helper for React hooks analysis
    fn is_custom_hook(func_name: &str) -> bool {
        func_name.starts_with("use")
            && func_name
                .chars()
                .nth(3)
                .map(|c| c.is_uppercase())
                .unwrap_or(false)
    }
}

impl Detector for ReactHooksDetector {
    fn name(&self) -> &'static str {
        "react-hooks"
    }
    fn description(&self) -> &'static str {
        "Detects React hooks rules violations"
    }

    fn bypass_postprocessor(&self) -> bool {
        true
    }

    fn requires_graph(&self) -> bool {
        false
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &["js", "ts", "jsx", "tsx"]
    }

    fn content_requirements(&self) -> crate::detectors::detector_context::ContentFlags {
        crate::detectors::detector_context::ContentFlags::HAS_REACT
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        // Codebase-level pre-filter: skip if no file uses React
        let has_react = files
            .files_with_extensions(&["jsx", "tsx", "js", "ts"])
            .iter()
            .any(|p| {
                files.content(p).is_some_and(|c| {
                    c.contains("react")
                        || c.contains("React")
                        || c.contains("useState")
                        || c.contains("useEffect")
                })
            });
        if !has_react {
            return Ok(vec![]);
        }

        let mut findings = vec![];

        for path in files.files_with_extensions(&["js", "jsx", "ts", "tsx"]) {
            if findings.len() >= self.max_findings {
                break;
            }

            let path_str = path.to_string_lossy().to_string();

            // Skip test files
            if crate::detectors::base::is_test_path(&path_str) {
                continue;
            }

            // Skip React framework source itself (packages/react*, packages/shared, etc.)
            // These files DEFINE hooks, they don't misuse them
            if path_str.contains("/packages/react")
                || path_str.contains("/packages/shared")
                || path_str.contains("/packages/scheduler")
                || path_str.contains("/packages/use-")
            {
                continue;
            }

            // Skip playground/examples/apps (demo code, not production)
            if path_str.contains("/playground/")
                || path_str.contains("/apps/")
                || path_str.contains("/fixtures/")
            {
                continue;
            }

            // Skip non-production paths
            if crate::detectors::content_classifier::is_non_production_path(&path_str) {
                continue;
            }

            if let Some(content) = files.content(path) {
                // Skip if no React hooks
                if !HOOK_CALL.is_match(&content) {
                    continue;
                }

                let lines: Vec<&str> = content.lines().collect();
                let mut in_conditional = false;
                let mut in_loop = false;
                let mut in_nested_func = false;
                let mut cond_depth = 0;
                let mut loop_depth = 0;
                let mut nested_depth = 0;
                let mut component_depth = 0;

                for (i, line) in lines.iter().enumerate() {
                    let opens = line.matches('{').count() as i32;
                    let closes = line.matches('}').count() as i32;

                    // Track component boundaries.
                    // IMPORTANT: reset all scope flags here so that stale in_loop /
                    // in_conditional / in_nested_func state from a previous component
                    // (e.g. a .map() in its JSX return) never bleeds into the next
                    // component's top-level hook calls.
                    if COMPONENT.is_match(line) {
                        component_depth = 0;
                        in_loop = false;
                        loop_depth = 0;
                        in_conditional = false;
                        cond_depth = 0;
                        in_nested_func = false;
                        nested_depth = 0;
                    }

                    // Track conditional blocks.
                    // Use `else if` to avoid double-counting the entry line's braces:
                    // the SET block initialises the depth, so the UPDATE block must
                    // only run on subsequent lines.
                    if CONDITIONAL.is_match(line) {
                        in_conditional = true;
                        cond_depth = opens - closes;
                        if cond_depth <= 0 {
                            in_conditional = false;
                        }
                    } else if in_conditional {
                        cond_depth += opens;
                        cond_depth -= closes;
                        if cond_depth <= 0 {
                            in_conditional = false;
                        }
                    }

                    // Track loops.
                    // Use `else if` (same double-count fix as above) and track only
                    // braces — not parens.  Mixing parens into loop_depth caused the
                    // original false-positive: a one-liner `.map(s => <C {...s} />)}`
                    // set loop_depth to `opens + opens_paren` (e.g. 9), which the
                    // closing `}` of the component body couldn't drain to zero, leaving
                    // in_loop=true as it leaked into the next component's scope.
                    if LOOP.is_match(line) {
                        in_loop = true;
                        loop_depth = opens - closes;
                        if loop_depth <= 0 {
                            in_loop = false;
                        }
                    } else if in_loop {
                        loop_depth += opens;
                        loop_depth -= closes;
                        if loop_depth <= 0 {
                            in_loop = false;
                        }
                    }

                    // Track nested functions (not at component level)
                    // IMPORTANT: exclude lines where the RHS is a hook call, e.g.:
                    //   const mutation = useMutation({...})
                    //   const query = useQuery(...)
                    //   const cb = useCallback(() => {}, [])
                    // These match NESTED_FUNC because of "const x = (" pattern, but the
                    // callback/options inside a hook invocation are NOT nested hook calls —
                    // the hook itself is called at the component level.
                    // Track hook call option blocks — anything inside useMutation({...}),
                    // useQuery({...}), useCallback(() => {...}), etc. is NOT a nested function.
                    let is_hook_call_line = HOOK_CALL.is_match(line)
                        && (line.contains("useMutation")
                            || line.contains("useQuery")
                            || line.contains("useCallback")
                            || line.contains("useMemo")
                            || line.contains("useEffect")
                            || line.contains("useLayoutEffect")
                            || line.contains("useInfiniteQuery"));

                    let is_hook_call_assignment =
                        NESTED_FUNC.is_match(line) && HOOK_CALL.is_match(line);
                    if NESTED_FUNC.is_match(line)
                        && component_depth > 0
                        && !is_hook_call_assignment
                        && !is_hook_call_line
                    {
                        // Same double-count fix: initialise on entry line, update
                        // on subsequent lines via the else branch.
                        in_nested_func = true;
                        nested_depth = opens - closes;
                        if nested_depth <= 0 {
                            in_nested_func = false;
                        }
                    } else if in_nested_func {
                        nested_depth += opens;
                        nested_depth -= closes;
                        if nested_depth <= 0 {
                            in_nested_func = false;
                        }
                    }

                    component_depth += opens;
                    component_depth -= closes;

                    // Check for hooks violations
                    if HOOK_CALL.is_match(line) {
                        let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
                        if crate::detectors::is_line_suppressed(line, prev_line) {
                            continue;
                        }

                        let is_violation = in_conditional || in_loop || in_nested_func;

                        if is_violation {
                            let hook_name =
                                extract_hook_name(line).unwrap_or_else(|| "useHook".to_string());
                            let component_name =
                                Self::find_component(graph, &path_str, (i + 1) as u32);
                            let (violation_type, violation_desc) =
                                categorize_violation(in_conditional, in_loop, in_nested_func);

                            // Build notes
                            let mut notes = Vec::new();
                            notes.push(format!("🪝 Hook: `{}`", hook_name));
                            if let Some(comp) = &component_name {
                                notes.push(format!("📦 Component: `{}`", comp));
                            }
                            match violation_type {
                                "conditional" => notes
                                    .push("⚠️ Called inside `if/else/switch/ternary`".to_string()),
                                "loop" => notes
                                    .push("⚠️ Called inside `for/while/map/forEach`".to_string()),
                                "nested" => {
                                    notes.push("⚠️ Called inside nested function".to_string())
                                }
                                _ => {}
                            }

                            let context_notes = format!("\n\n**Analysis:**\n{}", notes.join("\n"));

                            let suggestion = match violation_type {
                                "conditional" => format!(
                                    "Move `{}` outside the conditional:\n\n\
                                     ```jsx\n\
                                     // ❌ Wrong\n\
                                     function Component({{ show }}) {{\n\
                                     if (show) {{\n\
                                         const [state, setState] = useState(0); // Violation!\n\
                                     }}\n\
                                     }}\n\
                                     \n\
                                     // ✅ Correct\n\
                                     function Component({{ show }}) {{\n\
                                     const [state, setState] = useState(0);\n\
                                     if (!show) return null;\n\
                                     // Use state here...\n\
                                     }}\n\
                                     ```",
                                    hook_name
                                ),
                                "loop" => format!(
                                    "Extract loop body to a separate component:\n\n\
                                     ```jsx\n\
                                     // ❌ Wrong\n\
                                     items.map(item => {{\n\
                                     const [value, setValue] = {}(item.initial); // Violation!\n\
                                     return <Item value={{value}} />;\n\
                                     }});\n\
                                     \n\
                                     // ✅ Correct: Create a component for each item\n\
                                     function ItemWrapper({{ item }}) {{\n\
                                     const [value, setValue] = {}(item.initial);\n\
                                     return <Item value={{value}} />;\n\
                                     }}\n\
                                     \n\
                                     items.map(item => <ItemWrapper key={{item.id}} item={{item}} />);\n\
                                     ```",
                                    hook_name, hook_name
                                ),
                                "nested" => format!(
                                    "Move `{}` to component level or use a custom hook:\n\n\
                                     ```jsx\n\
                                     // ❌ Wrong\n\
                                     function Component() {{\n\
                                     const handleClick = () => {{\n\
                                         const [state] = {}(); // Violation!\n\
                                     }};\n\
                                     }}\n\
                                     \n\
                                     // ✅ Correct\n\
                                     function Component() {{\n\
                                     const [state, setState] = {}();\n\
                                     const handleClick = () => {{\n\
                                         // Use state/setState here\n\
                                     }};\n\
                                     }}\n\
                                     ```",
                                    hook_name, hook_name, hook_name
                                ),
                                _ => "Move hooks to the top level of your component.".to_string(),
                            };

                            findings.push(Finding {
                                id: String::new(),
                                detector: "ReactHooksDetector".to_string(),
                                severity: Severity::High,
                                title: format!("{}: `{}`", violation_desc, hook_name),
                                description: format!(
                                    "React hooks must be called in the exact same order on every render.{}",
                                    context_notes
                                ),
                                affected_files: vec![path.to_path_buf()],
                                line_start: Some((i + 1) as u32),
                                line_end: Some((i + 1) as u32),
                                suggested_fix: Some(suggestion),
                                estimated_effort: Some("15 minutes".to_string()),
                                category: Some("bug-risk".to_string()),
                                cwe_id: None,
                                why_it_matters: Some(
                                    "This violates the Rules of Hooks. React relies on the order of hook calls \
                                     to track state correctly. Conditional/loop/nested hooks cause:\n\
                                     • State getting out of sync\n\
                                     • Crashes and rendering bugs\n\
                                     • Unpredictable behavior".to_string()
                                ),
                                ..Default::default()
                            });
                        }
                    }
                }
            }
        }

        info!(
            "ReactHooksDetector found {} findings (graph-aware)",
            findings.len()
        );
        Ok(findings)
    }
}

impl crate::detectors::RegisteredDetector for ReactHooksDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builder::GraphBuilder;

    #[test]
    fn test_hook_in_conditional() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("Component.tsx", "function MyComponent({ show }) {\n  if (show) {\n    const [val, setVal] = useState(0);\n  }\n  return <div />;\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(!findings.is_empty(), "Should detect hook in conditional");
        assert!(
            findings
                .iter()
                .any(|f| f.title.contains("conditionally") && f.title.contains("useState")),
            "Finding should mention conditional useState violation. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hook_in_loop() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("LoopComponent.tsx", "function ListComponent({ items }) {\n  for (let i = 0; i < items.length; i++) {\n    const [val, setVal] = useState(items[i]);\n  }\n  return <div />;\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(!findings.is_empty(), "Should detect hook in loop");
        assert!(
            findings
                .iter()
                .any(|f| f.title.contains("loop") && f.title.contains("useState")),
            "Finding should mention loop useState violation. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_correct_hook_usage_no_findings() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("GoodComponent.tsx", "function GoodComponent({ items }) {\n  const [count, setCount] = useState(0);\n  const [name, setName] = useState(\"\");\n  useEffect(() => {\n    console.log(count);\n  }, [count]);\n  return <div>{count} {name}</div>;\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Correct hook usage should produce no findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hook_in_nested_function() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("NestedComponent.tsx", "function ParentComponent() {\n  function helperFunc() {\n    const [state, setState] = useState(0);\n    return state;\n  }\n  return <div />;\n}\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect hook in nested function"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.title.contains("nested") && f.title.contains("useState")),
            "Finding should mention nested function useState violation. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_use_effect_in_conditional() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "ConditionalEffect.tsx",
            "function Dashboard({ isAdmin }) {\n  if (isAdmin) {\n    useEffect(() => {\n      fetchAdminData();\n    }, []);\n  }\n  return <div />;\n}\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect useEffect inside an if block"
        );
        assert!(
            findings
                .iter()
                .any(|f| f.title.contains("conditionally") && f.title.contains("useEffect")),
            "Finding should mention conditional useEffect violation. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hooks_in_custom_hook_no_findings() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        // Custom hooks (functions starting with "use" + uppercase) are valid hook containers.
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "useAuth.ts",
            "function useAuth() {\n  const [user, setUser] = useState(null);\n  useEffect(() => {\n    fetchUser().then(setUser);\n  }, []);\n  return { user };\n}\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Hooks at top level of custom hook should produce no findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hook_in_map_callback() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        // The loop_pattern regex requires .map( at the start of the line (after whitespace),
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "ListItems.tsx",
            "function ItemList({ items }) {\n  items\n  .map((item) => {\n    const [expanded, setExpanded] = useState(false);\n    return <div key={item.id}>{expanded && item.detail}</div>;\n  });\n  return <div />;\n}\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect hook inside .map() callback"
        );
        assert!(
            findings.iter().any(|f| f.title.contains("loop")),
            "Finding should mention loop violation for .map(). Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn repro_lazy_init_with_math_random() {
        // PR #87 FP guard: useState lazy init with Math.random() must NOT be
        // flagged by the hooks detector. The lazy initializer in
        // `useState(() => ...)` runs once on mount; nondeterministic calls
        // inside it (Math.random, Date.now, crypto.randomUUID) are the
        // canonical React 18+ pattern for capturing mount-stable values.
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "RandomWidths.tsx",
                "function RandomWidths({ columns, items }) {\n  const [randomWidths] = useState(() =>\n    Array.from({ length: columns }, () => Math.floor(60 + Math.random() * 40))\n  );\n  const [mapped] = useState(() =>\n    items.map((item) => ({ ...item, key: Math.random() }))\n  );\n  return <div>{randomWidths.length} {mapped.length}</div>;\n}\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "useState lazy init with Math.random() should NOT be flagged, got: {:?}",
            findings
                .iter()
                .map(|f| format!("{} (line {})", f.title, f.line_start.unwrap_or(0)))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_hooks_in_pascal_case_component_no_findings() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "UserProfile.tsx",
            "function UserProfile({ userId }) {\n  const [profile, setProfile] = useState(null);\n  const [loading, setLoading] = useState(true);\n  const memoized = useMemo(() => computeExpensive(profile), [profile]);\n  useEffect(() => {\n    fetchProfile(userId).then(data => {\n      setProfile(data);\n      setLoading(false);\n    });\n  }, [userId]);\n  if (loading) return <Spinner />;\n  return <div>{profile.name}</div>;\n}\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "PascalCase component with top-level hooks should produce no findings, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Regression: hooks at the TOP of a component must never be flagged as
    /// "in a loop", even when another component in the same file renders via
    /// .map() or when a parent uses .map() in its JSX return.
    ///
    /// The triggering pattern is `.map(` on its OWN line (chained from the
    /// previous line), which the LOOP regex `^\s*\.map\(` matches.  If the
    /// brace-counting for `loop_depth` doesn't properly account for JSX
    /// expression containers (`{...}` inside the callback), `in_loop` stays
    /// true past the end of the `.map()` callback and into the NEXT component
    /// function, causing the top-level hooks there to be falsely flagged.
    #[test]
    fn test_top_level_hooks_not_flagged_as_in_loop_regression() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        // ChatHistory uses a one-liner `.map(` (matching `^\s*\.map\(`) with
        // inline JSX spread and an inline arrow function — the exact pattern
        // that triggers the brace-count overflow in the original code:
        //   loop_depth = opens + opens_paren  (parens never decremented)
        //   then the if-in_loop block double-counts the same line's opens
        // This leaves loop_depth >> 0, so in_loop bleeds into SessionRow.
        let src = "\
function ChatHistory({ sessions }) {
  return (
    <div>
      {sessions
        .map(s => <SessionRow key={s.id} {...s} onSelect={() => {}} />)}
    </div>
  );
}

function SessionRow(props) {
  const cb = useCallback(() => {}, []);
  const [x, setX] = useState(0);
  return <div>{props.name}</div>;
}
";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("SessionHistory.tsx", src)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        let loop_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.title.contains("loop"))
            .collect();
        assert!(
            loop_findings.is_empty(),
            "Top-level hooks must NOT be flagged as 'in a loop'. Got loop findings: {:?}",
            loop_findings
                .iter()
                .map(|f| format!("{} (line {})", f.title, f.line_start.unwrap_or(0)))
                .collect::<Vec<_>>()
        );
        // The whole file should be clean — no spurious findings at all.
        assert!(
            findings.is_empty(),
            "Top-level hooks in components should produce no findings, but got: {:?}",
            findings
                .iter()
                .map(|f| format!("{} (line {})", f.title, f.line_start.unwrap_or(0)))
                .collect::<Vec<_>>()
        );
    }

    /// Positive control: a hook called literally inside a for-loop body MUST
    /// still be flagged even after fixing the false-positive above.
    #[test]
    fn test_hook_genuinely_in_for_loop_still_flagged() {
        let store = GraphBuilder::new().freeze();
        let detector = ReactHooksDetector::new("/mock/repo");
        let src = "\
function L({ items }) {
  for (const item of items) {
    const [v, setV] = useState(item);
    console.log(v);
  }
  return <div />;
}
";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("LoopHook.tsx", src)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Hook inside a genuine for-loop must be flagged"
        );
        assert!(
            findings.iter().any(|f| f.title.contains("loop")),
            "Finding must be categorised as 'loop'. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }
}