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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
//! Pure Rust code analysis detectors — zero external dependencies.
#![allow(unused_imports)]
//!
//! All 110 detectors are built-in Rust. No shelling out to Python, Node, or any external tool.
//!
//! # Architecture
//!
//! ```text
//! run_detectors() → Detector trait → detect(ctx) → Vec<Finding>
//! ```
//!
//! Detectors are organized by category:
//! - `security/` — vulnerabilities, injection, auth, crypto (28 detectors)
//! - `bugs/` — runtime errors, logic errors, missing async (13 detectors)
//! - `architecture/` — coupling, dependencies, graph topology, bus factor (16 detectors)
//! - `performance/` — N+1 queries, sync-in-async, hot loops (3 detectors)
//! - `quality/` — code smells, complexity, naming, style (27 detectors)
//! - `ai/` — AI-generated code patterns (6 detectors)
//! - `ml_smells/` — ML/data science specific (8 detectors)
//! - `rust_smells/` — Rust-specific patterns (7 detectors)
//!
//! Detectors run in parallel via rayon. Each receives the code graph
//! and returns findings. Security detectors also use SSA-based
//! intra-function taint analysis via tree-sitter ASTs.

/// Shared helper: convert absolute path to relative using repository_path.
pub(crate) fn detector_relative_path(
    repository_path: &std::path::Path,
    path: &std::path::Path,
) -> std::path::PathBuf {
    path.strip_prefix(repository_path)
        .unwrap_or(path)
        .to_path_buf()
}

/// Macro for the standard detector `new()` constructor.
///
/// Generates: `pub fn new(repository_path: impl Into<PathBuf>) -> Self`
/// with fields `repository_path` and `max_findings`.
macro_rules! detector_new {
    ($max:expr) => {
        pub fn new(repository_path: impl Into<std::path::PathBuf>) -> Self {
            Self {
                repository_path: repository_path.into(),
                max_findings: $max,
            }
        }
    };
}
pub(crate) use detector_new;

/// Macro for the standard `set_precomputed_taint` trait override.
///
/// Expects `self.precomputed_cross` and `self.precomputed_intra` to be `OnceLock` fields.
macro_rules! impl_taint_precompute {
    () => {
        fn set_precomputed_taint(
            &self,
            cross: Vec<crate::detectors::security::taint::TaintPath>,
            intra: Vec<crate::detectors::security::taint::TaintPath>,
        ) {
            let _ = self.precomputed_cross.set(cross);
            let _ = self.precomputed_intra.set(intra);
        }
    };
}
pub(crate) use impl_taint_precompute;

// ── Registry infrastructure ────────────────────────────────────────────────

/// Everything a detector needs for construction.
/// Built once per analysis from ProjectConfig + StyleProfile.
pub struct DetectorInit<'a> {
    pub repo_path: &'a std::path::Path,
    pub project_config: &'a crate::config::ProjectConfig,
    pub resolver: crate::calibrate::ThresholdResolver,
    pub ngram_model: Option<&'a crate::calibrate::NgramModel>,
}

impl<'a> DetectorInit<'a> {
    /// Build a per-detector config with adaptive thresholds.
    pub fn config_for(&self, detector_name: &str) -> DetectorConfig {
        DetectorConfig::from_project_config_with_type(
            detector_name,
            self.project_config,
            self.repo_path,
        )
        .with_adaptive(self.resolver.clone())
    }

    #[cfg(test)]
    pub fn test_default() -> DetectorInit<'static> {
        let path: &'static std::path::Path =
            Box::leak(std::env::current_dir().unwrap().into_boxed_path());
        DetectorInit {
            repo_path: path,
            project_config: Box::leak(Box::new(crate::config::ProjectConfig::default())),
            resolver: crate::calibrate::ThresholdResolver::default(),
            ngram_model: None,
        }
    }
}

/// Trait for detectors that participate in the automatic registry.
/// Every registered detector implements create() as its canonical factory.
pub trait RegisteredDetector: Detector {
    fn create(init: &DetectorInit) -> Arc<dyn Detector>
    where
        Self: Sized;
}

/// Function pointer type for detector factories.
type DetectorFactory = fn(&DetectorInit) -> Arc<dyn Detector>;

/// Compile-time enforcement that D implements RegisteredDetector.
const fn register<D: RegisteredDetector>() -> DetectorFactory {
    D::create
}

/// Default detectors — high-value detectors that catch real bugs, security issues,
/// performance problems, and architectural debt. These run by default.
pub const DEFAULT_DETECTOR_FACTORIES: &[DetectorFactory] = &[
    // Security (all — these catch real vulnerabilities)
    register::<CircularDependencyDetector>(),
    register::<SQLInjectionDetector>(),
    register::<XssDetector>(),
    register::<CommandInjectionDetector>(),
    register::<SsrfDetector>(),
    register::<PathTraversalDetector>(),
    register::<SecretDetector>(),
    register::<InsecureCryptoDetector>(),
    register::<XxeDetector>(),
    register::<PrototypePollutionDetector>(),
    register::<InsecureTlsDetector>(),
    register::<CleartextCredentialsDetector>(),
    register::<NosqlInjectionDetector>(),
    register::<LogInjectionDetector>(),
    register::<InsecureDeserializeDetector>(),
    register::<CorsMisconfigDetector>(),
    register::<JwtWeakDetector>(),
    register::<DjangoSecurityDetector>(),
    register::<ExpressSecurityDetector>(),
    register::<GHActionsInjectionDetector>(),
    register::<EvalDetector>(),
    register::<PickleDeserializationDetector>(),
    register::<UnsafeTemplateDetector>(),
    register::<InsecureCookieDetector>(),
    register::<InsecureRandomDetector>(),
    register::<RegexDosDetector>(),
    register::<HardcodedIpsDetector>(),
    // Bug patterns
    register::<EmptyCatchDetector>(),
    register::<BroadExceptionDetector>(),
    register::<MutableDefaultArgsDetector>(),
    register::<UnreachableCodeDetector>(),
    register::<CallbackHellDetector>(),
    register::<GeneratorMisuseDetector>(),
    register::<InfiniteLoopDetector>(),
    register::<ImplicitCoercionDetector>(),
    register::<WildcardImportsDetector>(),
    register::<GlobalVariablesDetector>(),
    register::<StringConcatLoopDetector>(),
    // Performance
    register::<NPlusOneDetector>(),
    register::<RegexInLoopDetector>(),
    register::<SyncInAsyncDetector>(),
    // Refactoring (strict thresholds)
    register::<GodClassDetector>(),
    register::<LongMethodsDetector>(),
    register::<DeepNestingDetector>(),
    register::<AIComplexitySpikeDetector>(),
    // Architecture
    register::<ShotgunSurgeryDetector>(),
    register::<SinglePointOfFailureDetector>(),
    register::<StructuralBridgeRiskDetector>(),
    register::<MutualRecursionDetector>(),
    register::<HiddenCouplingDetector>(),
    register::<CommunityMisplacementDetector>(),
    register::<PageRankDriftDetector>(),
    register::<TemporalBottleneckDetector>(),
    register::<ArchitecturalBottleneckDetector>(),
    register::<DegreeCentralityDetector>(),
    register::<SingleOwnerModuleDetector>(),
    register::<KnowledgeSiloDetector>(),
    register::<OrphanedKnowledgeDetector>(),
    register::<CriticalPathSingleOwnerDetector>(),
    // Rust-specific (bugs and safety)
    register::<UnwrapWithoutContextDetector>(),
    register::<UnsafeWithoutSafetyCommentDetector>(),
    register::<MutexPoisoningRiskDetector>(),
    register::<PanicDensityDetector>(),
    // Testing
    register::<TestInProductionDetector>(),
    // Dependencies
    register::<DepAuditDetector>(),
    // ML/Data Science (all — these are real bug catchers)
    register::<TorchLoadUnsafeDetector>(),
    register::<NanEqualityDetector>(),
    register::<MissingZeroGradDetector>(),
    register::<ForwardMethodDetector>(),
    register::<MissingRandomSeedDetector>(),
    register::<ChainIndexingDetector>(),
    register::<RequireGradTypoDetector>(),
    register::<DeprecatedTorchApiDetector>(),
    // Other keepers
    register::<HardcodedTimeoutDetector>(),
];

/// Deep-scan-only detectors — code smells, style, dead code, and speculative detectors.
/// These run only with `--all-detectors`.
pub const DEEP_ONLY_DETECTOR_FACTORIES: &[DetectorFactory] = &[
    // Demoted from default (0.8.1): high false-positive rate on real JS/TS code from
    // line-based heuristic matching that doesn't consult the AST or graph. The detectors
    // remain runnable with `--all-detectors`. Slated for an AST+graph-aware rewrite —
    // until then, default-running them eroded trust faster than they caught real bugs.
    register::<MissingAwaitDetector>(),
    register::<UnhandledPromiseDetector>(),
    register::<ReactHooksDetector>(),
    // Rust style preferences (not bugs)
    register::<CloneInHotPathDetector>(),
    register::<MissingMustUseDetector>(),
    // Unused imports (linter-level, 573 findings on next.js alone)
    register::<UnusedImportsDetector>(),
    // Code smells (0% evidence from PRs)
    register::<LongParameterListDetector>(),
    register::<DataClumpsDetector>(),
    register::<LazyClassDetector>(),
    register::<FeatureEnvyDetector>(),
    register::<InappropriateIntimacyDetector>(),
    register::<MessageChainDetector>(),
    register::<MiddleManDetector>(),
    register::<RefusedBequestDetector>(),
    register::<ModuleCohesionDetector>(),
    // Dead code (0.03% of PRs)
    register::<DeadCodeDetector>(),
    register::<DeadStoreDetector>(),
    // Duplicate code (0% of PRs fix this)
    register::<DuplicateCodeDetector>(),
    register::<AIDuplicateBlockDetector>(),
    // AI detectors (speculative)
    register::<AIMissingTestsDetector>(),
    register::<AIBoilerplateDetector>(),
    register::<AIChurnDetector>(),
    register::<AINamingPatternDetector>(),
    // Style/lint (formatters do this)
    register::<TodoScanner>(),
    register::<CommentedCodeDetector>(),
    register::<SingleCharNamesDetector>(),
    register::<DebugCodeDetector>(),
    register::<MagicNumbersDetector>(),
    register::<BooleanTrapDetector>(),
    register::<InconsistentReturnsDetector>(),
    register::<MissingDocstringsDetector>(),
    // Informational (not actionable)
    register::<LargeFilesDetector>(),
    register::<InfluentialCodeDetector>(),
    // Predictive (experimental)
    register::<SurprisalDetector>(),
    register::<HierarchicalSurprisalDetector>(),
    // Rust style (not bugs)
    register::<BoxDynTraitDetector>(),
];

/// Create default detectors (high-value: security, bugs, performance, architecture).
/// Respects `[detectors.X] enabled = false` in repotoire.toml.
pub fn create_default_detectors(init: &DetectorInit) -> Vec<Arc<dyn Detector>> {
    DEFAULT_DETECTOR_FACTORIES
        .iter()
        .map(|f| f(init))
        .filter(|d| init.project_config.is_detector_enabled(d.name()))
        .collect()
}

/// Create ALL detectors including deep-scan detectors (code smells, style, dead code).
/// Respects `[detectors.X] enabled = false` in repotoire.toml.
pub fn create_all_detectors(init: &DetectorInit) -> Vec<Arc<dyn Detector>> {
    DEFAULT_DETECTOR_FACTORIES
        .iter()
        .chain(DEEP_ONLY_DETECTOR_FACTORIES.iter())
        .map(|f| f(init))
        .filter(|d| init.project_config.is_detector_enabled(d.name()))
        .collect()
}

// ── Category modules (detectors grouped by concern) ───────────────────────

pub mod ai;
pub mod architecture;
pub mod bugs;
pub mod performance;
pub mod quality;
pub mod security;

// ── Infra modules (shared machinery, not detectors) ───────────────────────

pub mod analysis_context;
pub mod api_surface;
pub mod ast_fingerprint;
pub(crate) mod ast_walk;
pub mod base;
pub mod class_context;
pub mod confidence_enrichment;
pub mod content_classifier;
pub mod context_hmm;
pub mod detector_context;
mod engine;
pub mod file_cache;
pub mod file_index;
pub mod file_provider;
pub mod framework_detection;
pub mod function_context;
pub mod graph_enrichment;
pub mod module_metrics;
pub mod reachability;
pub mod runner;
pub mod text_utils;
pub mod user_input;

// ML/Data Science and Rust-specific detectors (existing subdirectories)
mod ml_smells;
mod rust_smells;

// SIMD-accelerated string searching for hot detector loops
pub(crate) mod fast_search;

// Cross-detector analysis
mod core_utility;
mod health_delta;
mod hierarchical_surprisal;
mod incremental_cache;
mod risk_analyzer;
mod root_cause_analyzer;
mod surprisal;
mod voting_engine;

// ── Re-exports (backward-compatible public API) ───────────────────────────

// Base types
pub use analysis_context::AnalysisContext;
pub use base::{
    DetectionSummary, Detector, DetectorConfig, DetectorResult, DetectorScope, ProgressCallback,
};
pub use detector_context::{ContentFlags, DetectorContext};
pub use engine::{precompute_gd_startup, PrecomputedAnalysis, SerializablePrecomputed};
pub use file_cache::FileContentCache;
pub use file_index::{FileEntry, FileIndex};
pub use file_provider::{FileProvider, SourceFiles};
pub use function_context::{
    FunctionContext, FunctionContextBuilder, FunctionContextMap, FunctionRole,
};
pub use runner::{
    apply_hmm_context_filter, filter_test_file_findings, inject_taint_precomputed, run_detectors,
    sort_findings_deterministic,
};

// Taint analysis — re-exported at top level for backward compat
// (used extensively from engine/, predictive/, etc.)
pub use security::taint;

// Security detectors
pub use security::{
    CleartextCredentialsDetector, CommandInjectionDetector, CorsMisconfigDetector,
    DepAuditDetector, DjangoSecurityDetector, EvalDetector, ExpressSecurityDetector,
    GHActionsInjectionDetector, HardcodedIpsDetector, InsecureCookieDetector,
    InsecureCryptoDetector, InsecureDeserializeDetector, InsecureRandomDetector,
    InsecureTlsDetector, JwtWeakDetector, LogInjectionDetector, NosqlInjectionDetector,
    PathTraversalDetector, PickleDeserializationDetector, PrototypePollutionDetector,
    ReactHooksDetector, RegexDosDetector, SQLInjectionDetector, SecretDetector, SsrfDetector,
    UnsafeTemplateDetector, XssDetector, XxeDetector,
};

// Bug detectors
pub use bugs::{
    BroadExceptionDetector, CallbackHellDetector, EmptyCatchDetector, GeneratorMisuseDetector,
    GlobalVariablesDetector, ImplicitCoercionDetector, InfiniteLoopDetector, MissingAwaitDetector,
    MutableDefaultArgsDetector, StringConcatLoopDetector, UnhandledPromiseDetector,
    UnreachableCodeDetector, WildcardImportsDetector,
};

// Architecture detectors
pub use architecture::{
    ArchitecturalBottleneckDetector, CircularDependencyDetector, CommunityMisplacementDetector,
    CriticalPathSingleOwnerDetector, DegreeCentralityDetector, HiddenCouplingDetector,
    KnowledgeSiloDetector, ModuleCohesionDetector, MutualRecursionDetector,
    OrphanedKnowledgeDetector, PageRankDriftDetector, ShotgunSurgeryDetector,
    SingleOwnerModuleDetector, SinglePointOfFailureDetector, StructuralBridgeRiskDetector,
    TemporalBottleneckDetector,
};

// Performance detectors
pub use performance::{NPlusOneDetector, RegexInLoopDetector, SyncInAsyncDetector};

// Quality detectors
pub use quality::{
    BooleanTrapDetector, CommentedCodeDetector, DataClumpsDetector, DeadCodeDetector,
    DeadStoreDetector, DebugCodeDetector, DeepNestingDetector, DuplicateCodeDetector,
    FeatureEnvyDetector, GodClassDetector, GodClassThresholds, HardcodedTimeoutDetector,
    InappropriateIntimacyDetector, InconsistentReturnsDetector, InfluentialCodeDetector,
    LargeFilesDetector, LazyClassDetector, LongMethodsDetector, LongParameterListDetector,
    LongParameterThresholds, MagicNumbersDetector, MessageChainDetector, MiddleManDetector,
    MissingDocstringsDetector, RefusedBequestDetector, SingleCharNamesDetector,
    TestInProductionDetector, TodoScanner, UnusedImportsDetector,
};

// AI detectors
pub use ai::{
    AIBoilerplateDetector, AIChurnDetector, AIComplexitySpikeDetector, AIDuplicateBlockDetector,
    AIMissingTestsDetector, AINamingPatternDetector, BoilerplatePattern,
};

// ML/Data Science detectors
pub use ml_smells::{
    ChainIndexingDetector, DeprecatedTorchApiDetector, ForwardMethodDetector,
    MissingRandomSeedDetector, MissingZeroGradDetector, NanEqualityDetector,
    RequireGradTypoDetector, TorchLoadUnsafeDetector,
};

// Rust-specific detectors
pub use rust_smells::{
    BoxDynTraitDetector, CloneInHotPathDetector, MissingMustUseDetector,
    MutexPoisoningRiskDetector, PanicDensityDetector, UnsafeWithoutSafetyCommentDetector,
    UnwrapWithoutContextDetector,
};

// Cross-detector analysis
pub use health_delta::{
    estimate_batch_fix_impact, estimate_fix_impact, BatchHealthScoreDelta, HealthScoreDelta,
    HealthScoreDeltaCalculator, ImpactLevel, MetricsBreakdown,
};
pub use incremental_cache::{
    binary_file_hash, compute_fingerprint, prune_stale_caches, CacheStats, CachedScoreResult,
    ConcurrentCacheView, IncrementalCache,
};
pub use risk_analyzer::{analyze_compound_risks, RiskAnalyzer, RiskAssessment, RiskFactor};
pub use root_cause_analyzer::{RootCauseAnalysis, RootCauseAnalyzer, RootCauseSummary};
pub use voting_engine::{
    ConfidenceMethod, ConsensusResult, DetectorWeight, SeverityResolution, VotingEngine,
    VotingStats, VotingStrategy,
};

// Predictive detectors
pub use hierarchical_surprisal::HierarchicalSurprisalDetector;
pub use surprisal::SurprisalDetector;

use std::path::Path;
use std::sync::Arc;

/// Build an adaptive `ThresholdResolver` from an optional style profile.
///
/// Callers pass this to `PrecomputedAnalysis::to_context()` for
/// propagation into `AnalysisContext`.
pub fn build_threshold_resolver(
    style_profile: Option<&crate::calibrate::StyleProfile>,
) -> crate::calibrate::ThresholdResolver {
    crate::calibrate::ThresholdResolver::new(style_profile.cloned())
}

/// Create a file walker that respects .gitignore and .repotoireignore
pub fn walk_source_files<'a>(
    repository_path: &'a Path,
    extensions: Option<&'a [&'a str]>,
) -> impl Iterator<Item = std::path::PathBuf> + 'a {
    use ignore::WalkBuilder;

    let mut builder = WalkBuilder::new(repository_path);
    builder
        .hidden(true)
        .git_ignore(true)
        .git_global(true)
        .git_exclude(true)
        .require_git(false)
        .add_custom_ignore_filename(".repotoireignore");

    builder.build().filter_map(move |entry| {
        let entry = entry.ok()?;
        let path = entry.path();

        if !path.is_file() {
            return None;
        }

        if let Some(exts) = extensions {
            let ext = path.extension()?.to_str()?;
            if !exts.contains(&ext) {
                return None;
            }
        }

        Some(path.to_path_buf())
    })
}

/// Check if a line has a repotoire suppression comment
pub fn is_line_suppressed(line: &str, prev_line: Option<&str>) -> bool {
    let suppression_pattern = "repotoire: ignore";
    let suppression_pattern_alt = "repotoire:ignore";

    let line_lower = line.to_lowercase();
    if line_lower.contains(suppression_pattern) || line_lower.contains(suppression_pattern_alt) {
        return true;
    }

    if let Some(prev) = prev_line {
        let prev_lower = prev.trim().to_lowercase();
        if (prev_lower.starts_with('#')
            || prev_lower.starts_with("//")
            || prev_lower.starts_with("--")
            || prev_lower.starts_with("/*"))
            && (prev_lower.contains(suppression_pattern)
                || prev_lower.contains(suppression_pattern_alt))
        {
            return true;
        }
    }

    false
}

/// Check if a line has a repotoire suppression comment targeting a specific detector.
#[allow(dead_code)]
pub fn is_line_suppressed_for(line: &str, prev_line: Option<&str>, detector_name: &str) -> bool {
    fn check_suppression(text: &str, detector_name: &str) -> bool {
        let lower = text.to_lowercase();
        let det_norm = normalize_detector_id(detector_name);

        for prefix in &["repotoire:ignore", "repotoire: ignore"] {
            if let Some(idx) = lower.find(prefix) {
                let after = idx + prefix.len();
                let rest = &lower[after..];
                if rest.starts_with('[') {
                    if let Some(end) = rest.find(']') {
                        let target = &rest[1..end];
                        if normalize_detector_id(target.trim()) == det_norm {
                            return true;
                        }
                    }
                } else {
                    return true;
                }
            }
        }
        false
    }

    if check_suppression(line, detector_name) {
        return true;
    }

    if let Some(prev) = prev_line {
        let trimmed = prev.trim();
        let trimmed_lower = trimmed.to_lowercase();
        if (trimmed_lower.starts_with('#')
            || trimmed_lower.starts_with("//")
            || trimmed_lower.starts_with("--")
            || trimmed_lower.starts_with("/*"))
            && check_suppression(prev, detector_name)
        {
            return true;
        }
    }

    false
}

/// Check if a file has a file-level suppression directive in the first 10 lines.
pub fn is_file_suppressed(content: &str) -> bool {
    is_file_suppressed_for(content, None)
}

/// Check if a file has a file-level suppression directive targeting a specific detector.
///
/// Behavior:
/// - `repotoire:ignore-file` (no bracket) -> always returns true (file fully suppressed).
/// - `repotoire:ignore-file[<target>]` with `detector_name = Some(name)` -> returns
///   true only when `target` and `name` normalize to the same identifier (case- and
///   separator-insensitive, with optional `Detector` suffix stripping).
/// - `repotoire:ignore-file[<target>]` with `detector_name = None` -> returns false
///   (a targeted directive shouldn't blanket-suppress the file when no detector
///   context is available).
pub fn is_file_suppressed_for(content: &str, detector_name: Option<&str>) -> bool {
    let pattern = "repotoire:ignore-file";
    let pattern_alt = "repotoire: ignore-file";
    let det_norm = detector_name.map(normalize_detector_id);

    for line in content.lines().take(10) {
        let lower = line.to_lowercase();
        let trimmed = lower.trim();
        let is_comment = trimmed.starts_with('#')
            || trimmed.starts_with("//")
            || trimmed.starts_with("/*")
            || trimmed.starts_with("--")
            || trimmed.starts_with('*');

        if !is_comment {
            continue;
        }

        for pat in &[pattern, pattern_alt] {
            if let Some(idx) = lower.find(pat) {
                let after = idx + pat.len();
                let rest = &lower[after..];

                if rest.starts_with('[') {
                    if let Some(end) = rest.find(']') {
                        let target = rest[1..end].trim();
                        if let Some(ref det) = det_norm {
                            if normalize_detector_id(target) == *det {
                                return true;
                            }
                        }
                    }
                } else {
                    return true;
                }
            }
        }
    }

    false
}

/// Normalize a detector identifier so that struct names, kebab-case IDs, snake_case
/// IDs, and human-readable variants all compare equal.
///
/// Examples:
/// - `"InsecureCryptoDetector"` -> `"insecurecrypto"`
/// - `"insecure-crypto"`        -> `"insecurecrypto"`
/// - `"insecure_crypto"`        -> `"insecurecrypto"`
/// - `"InsecureCrypto"`         -> `"insecurecrypto"`
///
/// This handles the inconsistency between `Finding.detector` (typically the struct
/// name like "InsecureCryptoDetector") and the `Detector::name()` method (typically
/// kebab-case like "insecure-crypto"), as well as user-written suppression brackets.
pub fn normalize_detector_id(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
        }
        // drop '-', '_', whitespace, and any other separator
    }
    // Strip a trailing "detector" if present so "FooDetector" == "foo".
    if out.ends_with("detector") && out.len() > "detector".len() {
        out.truncate(out.len() - "detector".len());
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_inline_suppression() {
        assert!(is_line_suppressed("x = 1  // repotoire:ignore", None));
        assert!(is_line_suppressed("x = 1  // repotoire: ignore", None));
    }

    #[test]
    fn test_prev_line_suppression() {
        assert!(is_line_suppressed("x = 1", Some("// repotoire:ignore")));
    }

    #[test]
    fn test_no_suppression() {
        assert!(!is_line_suppressed("x = 1", None));
        assert!(!is_line_suppressed("x = 1", Some("// normal comment")));
    }

    #[test]
    fn test_targeted_suppression() {
        assert!(is_line_suppressed_for(
            "x = 1  // repotoire:ignore[sql-injection]",
            None,
            "sql-injection"
        ));
        assert!(!is_line_suppressed_for(
            "x = 1  // repotoire:ignore[sql-injection]",
            None,
            "xss"
        ));
        assert!(is_line_suppressed_for(
            "x = 1  // repotoire:ignore",
            None,
            "xss"
        ));
        assert!(is_line_suppressed_for(
            "x = 1",
            Some("// repotoire:ignore[xss]"),
            "xss"
        ));
        assert!(!is_line_suppressed_for(
            "x = 1",
            Some("// repotoire:ignore[xss]"),
            "sql-injection"
        ));
    }

    #[test]
    fn test_targeted_suppression_with_space() {
        assert!(is_line_suppressed_for(
            "x = 1  // repotoire: ignore[sql-injection]",
            None,
            "sql-injection"
        ));
        assert!(!is_line_suppressed_for(
            "x = 1  // repotoire: ignore[sql-injection]",
            None,
            "xss"
        ));
    }

    #[test]
    fn test_targeted_suppression_case_insensitive() {
        assert!(is_line_suppressed_for(
            "x = 1  // Repotoire:Ignore[SQL-Injection]",
            None,
            "sql-injection"
        ));
    }

    #[test]
    fn test_targeted_suppression_bare_prev_line() {
        assert!(is_line_suppressed_for(
            "x = 1",
            Some("// repotoire:ignore"),
            "any-detector"
        ));
    }

    #[test]
    fn test_normalize_detector_id() {
        // Struct name with Detector suffix
        assert_eq!(
            normalize_detector_id("InsecureCryptoDetector"),
            "insecurecrypto"
        );
        // Kebab-case ID (Detector::name() convention)
        assert_eq!(normalize_detector_id("insecure-crypto"), "insecurecrypto");
        // Snake_case
        assert_eq!(normalize_detector_id("insecure_crypto"), "insecurecrypto");
        // No-suffix struct name
        assert_eq!(normalize_detector_id("InsecureCrypto"), "insecurecrypto");
        // Already normalized
        assert_eq!(normalize_detector_id("insecurecrypto"), "insecurecrypto");
        // Whitespace and mixed separators
        assert_eq!(
            normalize_detector_id(" Insecure-Crypto Detector "),
            "insecurecrypto"
        );
        // The bare word "detector" should NOT be stripped to empty.
        assert_eq!(normalize_detector_id("Detector"), "detector");
        // Empty string is fine
        assert_eq!(normalize_detector_id(""), "");
    }

    #[test]
    fn test_targeted_suppression_matches_struct_name_against_kebab_id() {
        // Finding.detector is typically the struct name "InsecureCryptoDetector"
        // while users write "insecure-crypto" in suppression brackets.
        assert!(is_line_suppressed_for(
            "let h = sha1(data);  // repotoire:ignore[insecure-crypto]",
            None,
            "InsecureCryptoDetector"
        ));
        // Reverse direction also works: bracket "InsecureCryptoDetector",
        // detector name "insecure-crypto".
        assert!(is_line_suppressed_for(
            "let h = sha1(data);  // repotoire:ignore[InsecureCryptoDetector]",
            None,
            "insecure-crypto"
        ));
        // But unrelated detectors are NOT suppressed.
        assert!(!is_line_suppressed_for(
            "let h = sha1(data);  // repotoire:ignore[insecure-crypto]",
            None,
            "SqlInjectionDetector"
        ));
    }

    #[test]
    fn test_file_suppression_untargeted() {
        let content =
            "//! Pure-Rust SHA1 implementation.\n//! repotoire:ignore-file\nfn sha1() {}\n";
        // No bracket -> blanket suppress regardless of detector.
        assert!(is_file_suppressed(content));
        assert!(is_file_suppressed_for(
            content,
            Some("InsecureCryptoDetector")
        ));
        assert!(is_file_suppressed_for(content, Some("AnyOtherDetector")));
    }

    #[test]
    fn test_file_suppression_targeted() {
        let content = "//! repotoire:ignore-file[insecure-crypto]\nfn sha1() {}\n";
        // Targeted bracket: only matches when detector_name normalizes to "insecurecrypto".
        assert!(is_file_suppressed_for(
            content,
            Some("InsecureCryptoDetector")
        ));
        assert!(is_file_suppressed_for(content, Some("insecure-crypto")));
        assert!(is_file_suppressed_for(content, Some("Insecure_Crypto")));
        // Unrelated detector is NOT suppressed.
        assert!(!is_file_suppressed_for(
            content,
            Some("SqlInjectionDetector")
        ));
        // No detector context with a targeted bracket -> not suppressed (caller intent
        // is unclear; better to keep findings than blanket-suppress).
        assert!(!is_file_suppressed_for(content, None));
        // Untargeted helper agrees.
        assert!(!is_file_suppressed(content));
    }

    #[test]
    fn test_file_suppression_after_other_comments() {
        // Directive can appear anywhere in the first 10 lines, including after
        // other doc comments — common pattern for explanatory paragraphs.
        let content = r#"//! RFC 3174 SHA-1 implementation (hash-only, not for cryptographic use).
//! Used exclusively for git object ID computation.
//!
//! repotoire:ignore-file[insecure-crypto]
//! SHA-1 is mandated by the Git protocol.

const H0: u32 = 0x67452301;
"#;
        assert!(is_file_suppressed_for(
            content,
            Some("InsecureCryptoDetector")
        ));
        assert!(!is_file_suppressed_for(content, Some("DebugCodeDetector")));
    }

    #[test]
    fn test_targeted_suppression_prev_line_non_comment() {
        assert!(!is_line_suppressed_for(
            "x = 1",
            Some("x = 1 repotoire:ignore[xss]"),
            "xss"
        ));
    }

    #[test]
    fn test_targeted_suppression_python_comment() {
        assert!(is_line_suppressed_for(
            "x = 1  # repotoire:ignore[magic-numbers]",
            None,
            "magic-numbers"
        ));
    }

    #[test]
    fn test_targeted_suppression_no_match_no_suppress() {
        assert!(!is_line_suppressed_for("x = 1", None, "sql-injection"));
        assert!(!is_line_suppressed_for(
            "x = 1",
            Some("// normal comment"),
            "sql-injection"
        ));
    }

    #[test]
    fn all_detectors_have_scope() {
        let init = DetectorInit::test_default();
        let detectors = create_all_detectors(&init);
        for d in &detectors {
            let scope = d.detector_scope();
            match scope {
                DetectorScope::FileLocal
                | DetectorScope::FileScopedGraph
                | DetectorScope::GraphWide => {}
            }
        }
        let file_local = detectors
            .iter()
            .filter(|d| d.detector_scope() == DetectorScope::FileLocal)
            .count();
        let graph_wide = detectors
            .iter()
            .filter(|d| d.detector_scope() == DetectorScope::GraphWide)
            .count();
        assert!(
            file_local > 20,
            "Expected 20+ FileLocal detectors, got {}",
            file_local
        );
        assert!(
            graph_wide >= 2,
            "Expected 2+ GraphWide detectors, got {}",
            graph_wide
        );
    }

    #[test]
    fn test_file_suppressed_rust_comment() {
        assert!(is_file_suppressed("// repotoire:ignore-file\nfn main() {}"));
    }

    #[test]
    fn test_file_suppressed_rust_comment_with_space() {
        assert!(is_file_suppressed(
            "// repotoire: ignore-file\nfn main() {}"
        ));
    }

    #[test]
    fn test_file_suppressed_python_comment() {
        assert!(is_file_suppressed("# repotoire:ignore-file\nimport os"));
    }

    #[test]
    fn test_file_suppressed_c_style_comment() {
        assert!(is_file_suppressed(
            "/* repotoire:ignore-file */\nint main() {}"
        ));
    }

    #[test]
    fn test_file_suppressed_sql_comment() {
        assert!(is_file_suppressed("-- repotoire:ignore-file\nSELECT 1;"));
    }

    #[test]
    fn test_file_suppressed_block_comment_continuation() {
        assert!(is_file_suppressed(
            "/*\n * repotoire:ignore-file\n */\nfn main() {}"
        ));
    }

    #[test]
    fn test_file_suppressed_only_first_10_lines() {
        let mut lines: Vec<&str> = vec!["// normal comment"; 10];
        lines.push("// repotoire:ignore-file");
        assert!(!is_file_suppressed(&lines.join("\n")));
    }

    #[test]
    fn test_file_suppressed_within_10_lines() {
        let mut lines: Vec<&str> = vec!["// normal comment"; 9];
        lines.push("// repotoire:ignore-file");
        assert!(is_file_suppressed(&lines.join("\n")));
    }

    #[test]
    fn test_file_not_suppressed_plain_code() {
        assert!(!is_file_suppressed(
            "fn main() {\n    println!(\"hello\");\n}"
        ));
    }

    #[test]
    fn test_file_not_suppressed_in_code_line() {
        assert!(!is_file_suppressed(
            "let x = \"repotoire:ignore-file\";\nfn main() {}"
        ));
    }

    #[test]
    fn test_file_suppressed_case_insensitive() {
        assert!(is_file_suppressed("// Repotoire:Ignore-File\nfn main() {}"));
    }

    #[test]
    fn test_file_suppressed_for_targeted() {
        assert!(is_file_suppressed_for(
            "// repotoire:ignore-file[sql-injection]\nfn main() {}",
            Some("sql-injection")
        ));
    }

    #[test]
    fn test_file_suppressed_for_targeted_no_match() {
        assert!(!is_file_suppressed_for(
            "// repotoire:ignore-file[sql-injection]\nfn main() {}",
            Some("xss")
        ));
    }

    #[test]
    fn test_file_suppressed_for_blanket() {
        assert!(is_file_suppressed_for(
            "// repotoire:ignore-file\nfn main() {}",
            Some("any-detector")
        ));
    }

    #[test]
    fn test_file_suppressed_for_targeted_does_not_match_blanket_check() {
        assert!(!is_file_suppressed_for(
            "// repotoire:ignore-file[sql-injection]\nfn main() {}",
            None
        ));
    }

    #[test]
    fn test_create_all_detectors_registry() {
        let init = DetectorInit::test_default();
        let default = create_default_detectors(&init);
        let all = create_all_detectors(&init);
        assert!(default.len() > 50, "default detectors: {}", default.len());
        assert!(
            all.len() > default.len(),
            "all ({}) should exceed default ({})",
            all.len(),
            default.len()
        );
        assert_eq!(all.len(), 110);
    }

    #[test]
    fn test_detector_init_config_for() {
        let init = DetectorInit::test_default();
        let config = init.config_for("GodClassDetector");
        assert!(config.coupling_multiplier > 0.0);
    }
}