feat: execute configured text matchers

This commit is contained in:
Dandaedre 2026-09-29 15:17:41 +02:00
parent 10d607d423
commit 90f64fd8ac
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
2 changed files with 79 additions and 21 deletions

View File

@ -79,29 +79,12 @@ impl Detector {
}
/// Analyze text with the compiled registry.
///
/// Exact and regex execution is introduced in the next engine task. This
/// method initially preserves the replacement-backed detector behavior.
pub fn analyze(&self, source: &str) -> Analysis {
let Some(rule) = self
let findings = self
.rules
.iter()
.find(|rule| rule.is_enabled() && matches!(rule.matcher, CompiledMatcher::Replacement))
else {
return Analysis::default();
};
let findings = replacement::plan(&self.config, source)
.into_iter()
.map(|edit| Finding {
rule_id: RuleId::new(rule.id()),
category: rule.category(),
message: rule.definition.message.clone(),
help: Some(rule.definition.help.clone()),
byte_span: edit.byte_span.clone(),
matched_text: source[edit.byte_span.clone()].to_owned(),
weight: rule.definition.weight,
fix: Some(edit),
})
.filter(|rule| rule.is_enabled())
.flat_map(|rule| rule.findings(&self.config, source))
.collect::<Vec<_>>();
let score = u8::try_from(findings.len().saturating_mul(10)).unwrap_or(u8::MAX);
@ -132,6 +115,41 @@ impl Rule {
matcher,
})
}
fn findings(&self, config: &Config, source: &str) -> Vec<Finding> {
match &self.matcher {
CompiledMatcher::ExactPhrase(pattern) => source
.match_indices(pattern)
.map(|(start, matched)| self.finding(source, start..start + matched.len(), None))
.collect(),
CompiledMatcher::Regex(regex) => regex
.find_iter(source)
.map(|matched| self.finding(source, matched.range(), None))
.collect(),
CompiledMatcher::Replacement => replacement::plan(config, source)
.into_iter()
.map(|edit| self.finding(source, edit.byte_span.clone(), Some(edit)))
.collect(),
}
}
fn finding(
&self,
source: &str,
byte_span: std::ops::Range<usize>,
fix: Option<crate::TextEdit>,
) -> Finding {
Finding {
rule_id: RuleId::new(self.id()),
category: self.category(),
message: self.definition.message.clone(),
help: Some(self.definition.help.clone()),
matched_text: source[byte_span.clone()].to_owned(),
byte_span,
weight: self.definition.weight,
fix,
}
}
}
/// Failure while constructing a reusable detector registry.
@ -195,4 +213,44 @@ mod tests {
assert_eq!(matched.range(), 1..5);
}
#[test]
fn exact_phrase_findings_use_configured_metadata_and_byte_spans() {
let detector = Detector::new(&Config::embedded()).unwrap();
let source = "préface: As an AI language model, I cannot verify this.";
let finding = detector
.analyze(source)
.findings
.into_iter()
.find(|finding| finding.rule_id.as_str() == "assistant-self-identification")
.unwrap();
let start = source.find("As an AI language model").unwrap();
assert_eq!(finding.byte_span, start..start + finding.matched_text.len());
assert_eq!(finding.matched_text, "As an AI language model");
assert_eq!(finding.category, Category::PromptLeakage);
assert_eq!(finding.weight, 30.0);
assert!(finding.message.contains("self-identification"));
assert!(finding.help.unwrap().contains("copied"));
assert!(finding.fix.is_none());
}
#[test]
fn regex_findings_cover_the_exact_utf8_source_slice() {
let detector = Detector::new(&Config::embedded()).unwrap();
let source = "préface\nAssistant: generated response";
let finding = detector
.analyze(source)
.findings
.into_iter()
.find(|finding| finding.rule_id.as_str() == "prompt-response-scaffolding")
.unwrap();
assert_eq!(&source[finding.byte_span.clone()], finding.matched_text);
assert_eq!(finding.matched_text, "Assistant: ");
assert_eq!(finding.category, Category::PromptLeakage);
assert_eq!(finding.weight, 25.0);
}
}

View File

@ -109,7 +109,7 @@ configuration is explainable, and all precedence/validation tests pass.
- [x] Define a `Rule`/`Detector` interface and a registry built entirely from the
validated heuristic config. Compile reusable matchers once.
- [ ] Implement exact phrase and regex rules with precise byte spans, match text,
- [x] Implement exact phrase and regex rules with precise byte spans, match text,
category, weight, message, help, and stable rule ID.
- [ ] Add conservative first-party rules for copied assistant disclaimers,
knowledge-cutoff language, prompt/response leakage, templated filler, repetitive