From 536009d32d052ba46819b1d9e482a9c92e92247a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 29 Sep 2026 15:26:29 +0200 Subject: [PATCH] feat: scope heuristics by content and path --- Cargo.lock | 23 +++ Cargo.toml | 1 + docs/architecture.md | 6 +- docs/configuration.md | 13 +- src/bin/john-slop.rs | 3 +- src/config.rs | 57 ++++++++ src/detector.rs | 326 +++++++++++++++++++++++++++++++++++++++++- src/lib.rs | 2 +- tasks.md | 2 +- 9 files changed, 421 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d887a0..9763d68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -92,6 +92,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -390,6 +400,18 @@ version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "hashbrown" version = "0.17.1" @@ -560,6 +582,7 @@ dependencies = [ "clap", "directories", "figment", + "globset", "insta", "miette", "regex", diff --git a/Cargo.toml b/Cargo.toml index 347d1b9..b34053d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ fancy-diagnostics = ["miette/fancy"] clap = { version = "4.6.7", default-features = false, features = ["derive", "error-context", "help", "std", "suggestions", "usage"] } directories = "6.0.0" figment = { version = "0.10.19", default-features = false, features = ["toml"] } +globset = { version = "0.4.20", default-features = false } miette = { version = "7.6.0", default-features = false, features = ["derive"] } regex = "1.13.1" serde = { version = "1.0.229", features = ["derive"] } diff --git a/docs/architecture.md b/docs/architecture.md index 2f9669e..c8816a2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -15,7 +15,8 @@ The main modules have deliberately narrow responsibilities: - `config` owns the validated embedded replacement catalog and input limits; - `input` streams files, directory entries, and archive members as documents; -- `detector` produces explainable findings and bounded confidence; +- `detector` compiles configured matchers and path scopes once, then produces + explainable findings and bounded confidence; - `replacement` produces non-overlapping edits without performing I/O; - `model` contains presentation-neutral domain values; - `error` exposes typed input failures for library consumers; @@ -24,7 +25,8 @@ The main modules have deliberately narrow responsibilities: All source spans are zero-based UTF-8 byte ranges into the exact analyzed source snapshot. Presentation layers will convert those canonical spans to terminal or UTF-16 LSP coordinates at their boundaries. Archive sources retain both their -outer path and inner member identity. +outer path and inner member identity. Rule applicability uses the member path +so language and path filters behave the same inside and outside archives. ## Public facade diff --git a/docs/configuration.md b/docs/configuration.md index c5e0b92..d260372 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -46,10 +46,15 @@ id = "templated-conclusion" weight = 2.5 ``` -A new ID must provide every field. Scope extension arrays replace the prior -array as a whole. Unknown keys, malformed TOML, duplicate IDs within one layer, -invalid regular expressions, unsafe matchers, non-ASCII replacement targets, -and invalid thresholds are fatal configuration diagnostics. +A new ID must provide every field. Scope arrays replace the prior array as a +whole. A rule scope can select `prose` or `source-code`, restrict lowercase +extensions, and use `include`/`exclude` path globs. The `skip_generated`, +`skip_vendor`, and `skip_minified` switches default to `true`; set one to +`false` only when those paths are intentionally in scope. Archive rules match +the inner member path. Unknown keys, malformed TOML, duplicate IDs within one +layer, invalid regular expressions or globs, unsafe matchers, non-ASCII +replacement targets, and invalid thresholds are fatal configuration +diagnostics. ## Inspection diff --git a/src/bin/john-slop.rs b/src/bin/john-slop.rs index 5a3c9c9..dbd0800 100644 --- a/src/bin/john-slop.rs +++ b/src/bin/john-slop.rs @@ -107,7 +107,8 @@ fn run(cli: &Cli) -> Result { let document = document .into_diagnostic() .wrap_err("failed to read an input document")?; - let analysis = detector.analyze(&document.content); + let context = john_slop::AnalysisContext::for_source(&document.source); + let analysis = detector.analyze_with(&document.content, &context); println!( "{}: confidence {}, {} finding(s)", document.source, diff --git a/src/config.rs b/src/config.rs index cc9f8cc..ba8c78a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -356,6 +356,19 @@ pub enum ConfigValidationError { /// Invalid extension value. extension: String, }, + /// A path applicability glob could not be compiled. + #[error("rule `{id}` has invalid {field} glob `{pattern}`")] + InvalidGlob { + /// Heuristic rule ID. + id: String, + /// Scope field containing the invalid glob. + field: &'static str, + /// Invalid glob pattern. + pattern: String, + /// Glob compiler failure. + #[source] + source: globset::Error, + }, /// Confidence thresholds are not strictly increasing. #[error("confidence thresholds must satisfy low < medium < high <= 100")] InvalidThresholds, @@ -764,6 +777,25 @@ pub struct RuleScope { pub content: Vec, /// Lowercase extensions without a leading dot; empty means unrestricted. pub extensions: Vec, + /// Path globs that opt inputs into this rule; empty means unrestricted. + #[serde(default)] + pub include: Vec, + /// Path globs that opt inputs out of this rule. + #[serde(default)] + pub exclude: Vec, + /// Ignore conventional generated-output paths. + #[serde(default = "default_true")] + pub skip_generated: bool, + /// Ignore conventional vendored-dependency paths. + #[serde(default = "default_true")] + pub skip_vendor: bool, + /// Ignore conventionally minified filenames. + #[serde(default = "default_true")] + pub skip_minified: bool, +} + +const fn default_true() -> bool { + true } /// Broad input kind used for heuristic applicability. @@ -960,6 +992,21 @@ fn validate_rules(rules: &[HeuristicRule]) -> Result<(), ConfigValidationError> }); } } + for (field, patterns) in [ + ("include", &rule.scope.include), + ("exclude", &rule.scope.exclude), + ] { + for pattern in patterns { + globset::Glob::new(pattern).map_err(|source| { + ConfigValidationError::InvalidGlob { + id: rule.id.clone(), + field, + pattern: pattern.clone(), + source, + } + })?; + } + } } Ok(()) } @@ -1243,6 +1290,16 @@ weight = 9.5 config.validate(), Err(ConfigValidationError::InvalidRegex { .. }) )); + + let mut config = Config::embedded(); + config.rules[0].scope.include.push("[".to_owned()); + assert!(matches!( + config.validate(), + Err(ConfigValidationError::InvalidGlob { + field: "include", + .. + }) + )); } #[test] diff --git a/src/detector.rs b/src/detector.rs index 738d7f6..3fa78a2 100644 --- a/src/detector.rs +++ b/src/detector.rs @@ -1,10 +1,13 @@ //! Compiled, reusable registry of configured detection rules. +use std::path::{Path, PathBuf}; + +use globset::{Glob, GlobSet, GlobSetBuilder}; use regex::Regex; use crate::{ - Analysis, Category, Confidence, Config, ConfigValidationError, Finding, HeuristicRule, - MatcherType, RuleId, replacement, + Analysis, Category, Confidence, Config, ConfigValidationError, ContentKind, Finding, + HeuristicRule, MatcherType, RuleId, SourceId, replacement, }; /// A validated heuristic definition paired with its reusable matcher. @@ -12,6 +15,7 @@ use crate::{ pub struct Rule { definition: HeuristicRule, matcher: CompiledMatcher, + scope: CompiledScope, } impl Rule { @@ -41,6 +45,66 @@ impl Rule { } } +/// Input metadata used to select applicable rules without reading the source twice. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnalysisContext { + path: Option, + content_kind: ContentKind, +} + +impl AnalysisContext { + /// Describe prose without a known filesystem path, such as standard input. + pub const fn prose() -> Self { + Self { + path: None, + content_kind: ContentKind::Prose, + } + } + + /// Describe source code without a known filesystem path. + pub const fn source_code() -> Self { + Self { + path: None, + content_kind: ContentKind::SourceCode, + } + } + + /// Infer the broad content kind from a path's extension. + pub fn for_path(path: impl Into) -> Self { + let path = path.into(); + let content_kind = infer_content_kind(&path); + Self { + path: Some(path), + content_kind, + } + } + + /// Describe a loaded document using its exact source identity. + pub fn for_source(source: &SourceId) -> Self { + match source { + SourceId::Stdin => Self::prose(), + SourceId::File(path) => Self::for_path(path), + SourceId::ArchiveMember { member, .. } => Self::for_path(member), + } + } + + /// Return the path used by extension and glob filters, when known. + pub fn path(&self) -> Option<&Path> { + self.path.as_deref() + } + + /// Return the broad content kind selected for this input. + pub const fn content_kind(&self) -> ContentKind { + self.content_kind + } +} + +impl Default for AnalysisContext { + fn default() -> Self { + Self::prose() + } +} + /// Matcher compiled once when the detector registry is built. #[derive(Debug, Clone)] enum CompiledMatcher { @@ -50,6 +114,12 @@ enum CompiledMatcher { Replacement, } +#[derive(Debug, Clone)] +struct CompiledScope { + include: Option, + exclude: GlobSet, +} + /// Reusable detection engine built from one resolved configuration snapshot. #[derive(Debug, Clone)] pub struct Detector { @@ -82,10 +152,15 @@ impl Detector { /// Analyze text with the compiled registry. pub fn analyze(&self, source: &str) -> Analysis { + self.analyze_with(source, &AnalysisContext::default()) + } + + /// Analyze text with explicit content and path applicability metadata. + pub fn analyze_with(&self, source: &str, context: &AnalysisContext) -> Analysis { let findings = self .rules .iter() - .filter(|rule| rule.is_enabled()) + .filter(|rule| rule.is_enabled() && rule.applies(context)) .flat_map(|rule| rule.findings(&self.config, source)) .collect::>(); let score = u8::try_from(findings.len().saturating_mul(10)).unwrap_or(u8::MAX); @@ -121,12 +196,56 @@ impl Rule { } MatcherType::Replacement => CompiledMatcher::Replacement, }; + let scope = CompiledScope::compile(&definition)?; Ok(Self { definition, matcher, + scope, }) } + fn applies(&self, context: &AnalysisContext) -> bool { + if !self + .definition + .scope + .content + .contains(&context.content_kind) + { + return false; + } + + let Some(path) = context.path() else { + return self.scope.include.is_none(); + }; + if !self.definition.scope.extensions.is_empty() + && !path + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + self.definition + .scope + .extensions + .iter() + .any(|allowed| extension.eq_ignore_ascii_case(allowed)) + }) + { + return false; + } + if self + .scope + .include + .as_ref() + .is_some_and(|include| !include.is_match(path)) + || self.scope.exclude.is_match(path) + { + return false; + } + + !(self.definition.scope.skip_generated && is_generated(path) + || self.definition.scope.skip_vendor && is_vendor(path) + || self.definition.scope.skip_minified && is_minified(path)) + } + fn findings(&self, config: &Config, source: &str) -> Vec { match &self.matcher { CompiledMatcher::ExactPhrase(pattern) => source @@ -174,6 +293,101 @@ impl Rule { } } +impl CompiledScope { + fn compile(rule: &HeuristicRule) -> Result { + Ok(Self { + include: if rule.scope.include.is_empty() { + None + } else { + Some(compile_globs(rule, "include", &rule.scope.include)?) + }, + exclude: compile_globs(rule, "exclude", &rule.scope.exclude)?, + }) + } +} + +fn compile_globs( + rule: &HeuristicRule, + field: &'static str, + patterns: &[String], +) -> Result { + let mut builder = GlobSetBuilder::new(); + for pattern in patterns { + builder.add( + Glob::new(pattern).map_err(|source| DetectorBuildError::InvalidGlob { + id: rule.id.clone(), + field, + pattern: pattern.clone(), + source, + })?, + ); + } + builder + .build() + .map_err(|source| DetectorBuildError::InvalidGlob { + id: rule.id.clone(), + field, + pattern: patterns.join(", "), + source, + }) +} + +fn infer_content_kind(path: &Path) -> ContentKind { + const SOURCE_EXTENSIONS: &[&str] = &[ + "c", "cc", "cpp", "cs", "go", "h", "hpp", "java", "js", "jsx", "kt", "php", "py", "rb", + "rs", "swift", "ts", "tsx", + ]; + if path + .extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + SOURCE_EXTENSIONS + .iter() + .any(|candidate| extension.eq_ignore_ascii_case(candidate)) + }) + { + ContentKind::SourceCode + } else { + ContentKind::Prose + } +} + +fn has_component(path: &Path, candidates: &[&str]) -> bool { + path.components().any(|component| { + component.as_os_str().to_str().is_some_and(|value| { + candidates + .iter() + .any(|candidate| value.eq_ignore_ascii_case(candidate)) + }) + }) +} + +fn is_generated(path: &Path) -> bool { + has_component(path, &["generated", "gen", "dist", "build", "target"]) +} + +fn is_vendor(path: &Path) -> bool { + has_component( + path, + &[ + "vendor", + "vendors", + "node_modules", + "third_party", + "third-party", + ], + ) +} + +fn is_minified(path: &Path) -> bool { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + let name = name.to_ascii_lowercase(); + name.contains(".min.") || name.ends_with("-min.js") || name.ends_with("-min.css") + }) +} + /// Failure while constructing a reusable detector registry. #[derive(Debug, thiserror::Error)] pub enum DetectorBuildError { @@ -189,6 +403,19 @@ pub enum DetectorBuildError { #[source] source: regex::Error, }, + /// A configured path applicability glob could not be compiled. + #[error("failed to compile {field} glob `{pattern}` for rule `{id}`")] + InvalidGlob { + /// Stable rule identifier. + id: String, + /// Scope field containing the glob. + field: &'static str, + /// Invalid glob source. + pattern: String, + /// Glob compiler failure. + #[source] + source: globset::Error, + }, } #[cfg(test)] @@ -323,4 +550,97 @@ mod tests { 2 ); } + + #[test] + fn content_and_extension_scopes_select_the_expected_rules() { + let detector = Detector::new(&Config::embedded()).unwrap(); + let text = "TODO: implement the parser"; + + assert!( + detector + .analyze_with(text, &AnalysisContext::prose()) + .findings + .is_empty() + ); + assert_eq!( + detector + .analyze_with(text, &AnalysisContext::for_path("src/parser.rs")) + .findings + .len(), + 1 + ); + assert!( + detector + .analyze_with(text, &AnalysisContext::for_path("src/parser.md")) + .findings + .is_empty() + ); + } + + #[test] + fn include_and_exclude_globs_are_compiled_and_applied() { + let mut config = Config::embedded(); + let rule = config + .rules + .iter_mut() + .find(|rule| rule.id == "assistant-self-identification") + .unwrap(); + rule.scope.include = vec!["docs/**".to_owned()]; + rule.scope.exclude = vec!["docs/archive/**".to_owned()]; + let detector = Detector::new(&config).unwrap(); + let text = "As an AI language model, I can help."; + + assert_eq!( + detector + .analyze_with(text, &AnalysisContext::for_path("docs/guide.md")) + .findings + .len(), + 1 + ); + assert!( + detector + .analyze_with(text, &AnalysisContext::for_path("notes/guide.md")) + .findings + .is_empty() + ); + assert!( + detector + .analyze_with(text, &AnalysisContext::for_path("docs/archive/guide.md")) + .findings + .is_empty() + ); + assert!(detector.analyze(text).findings.is_empty()); + } + + #[test] + fn generated_vendor_and_minified_paths_are_skipped_by_default() { + let detector = Detector::new(&Config::embedded()).unwrap(); + let text = "TODO: implement the parser"; + + for path in [ + "generated/parser.rs", + "vendor/parser.rs", + "node_modules/parser.js", + "src/parser.min.js", + ] { + assert!( + detector + .analyze_with(text, &AnalysisContext::for_path(path)) + .findings + .is_empty(), + "unexpected finding for {path}" + ); + } + } + + #[test] + fn archive_members_use_the_inner_path_for_applicability() { + let context = AnalysisContext::for_source(&SourceId::ArchiveMember { + archive: PathBuf::from("bundle.zip"), + member: PathBuf::from("src/lib.rs"), + }); + + assert_eq!(context.path(), Some(Path::new("src/lib.rs"))); + assert_eq!(context.content_kind(), ContentKind::SourceCode); + } } diff --git a/src/lib.rs b/src/lib.rs index 545a4ab..a5778e0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,7 +18,7 @@ pub use config::{ HeuristicRule, InputLimits, InputOverrides, MatcherType, ReplacementRule, RuleScope, ThresholdOverrides, }; -pub use detector::{Detector, DetectorBuildError, Rule}; +pub use detector::{AnalysisContext, Detector, DetectorBuildError, Rule}; pub use error::{InputError, InputResult}; pub use input::{Document, Documents}; pub use model::{Analysis, Category, Confidence, Finding, RuleId, SourceId, TextEdit}; diff --git a/tasks.md b/tasks.md index 5bbad2c..e9253ab 100644 --- a/tasks.md +++ b/tasks.md @@ -115,7 +115,7 @@ configuration is explainable, and all precedence/validation tests pass. knowledge-cutoff language, prompt/response leakage, templated filler, repetitive transitions/conclusions, suspicious Unicode, and code-specific placeholder or tutorial residue. -- [ ] Add applicability filters for prose versus source code, extension/language, +- [x] Add applicability filters for prose versus source code, extension/language, include/exclude globs, and generated/vendor/minified paths. - [ ] Design the confidence formula: bounded weighted evidence, per-rule caps, correlated-family damping, normalization to `0..=100`, and configurable