返回 CodeWhale
matcher.rs
根目录 / crates / plugins / src / matcher.rs
1 //! Pure keyword matcher over plugin metadata.
2 //!
3 //! Matches live as data: explicit `keywords`, `domains` (scheme / `www.` /
4 //! path stripped), and the plugin `name`. There is no `regex` dependency —
5 //! matching is substring search guarded by ASCII word boundaries.
6
7 use std::cmp::Reverse;
8
9 /// A plugin to match a draft against.
10 pub struct KeywordCandidate<'a> {
11 pub name: &'a str,
12 pub domains: &'a [String],
13 pub keywords: &'a [String],
14 }
15
16 /// Return the candidate index and exact term that matched `draft`.
17 ///
18 /// Returns `None` when `draft` has fewer than 3 characters or nothing matches.
19 /// Longer keywords take precedence; a keyword matches only when the occurrence
20 /// is flanked by ASCII word boundaries.
21 pub fn match_plugin_keyword(
22 draft: &str,
23 candidates: &[KeywordCandidate<'_>],
24 ) -> Option<(usize, String)> {
25 if draft.trim_start().starts_with('/') || draft.chars().count() < 3 {
26 return None;
27 }
28 let draft_lc = draft.to_ascii_lowercase();
29 let haystack = draft_lc.as_bytes();
30
31 let mut pairs: Vec<(String, usize)> = Vec::new();
32 for (idx, candidate) in candidates.iter().enumerate() {
33 for keyword in effective_keywords(candidate) {
34 pairs.push((keyword, idx));
35 }
36 }
37 pairs.sort_by_key(|(keyword, _)| Reverse(keyword.len()));
38
39 pairs
40 .iter()
41 .find(|(keyword, _)| keyword_matches(haystack, keyword.as_bytes()))
42 .map(|(keyword, idx)| (*idx, keyword.clone()))
43 }
44
45 fn effective_keywords(candidate: &KeywordCandidate<'_>) -> Vec<String> {
46 let mut keywords = Vec::new();
47 for keyword in candidate.keywords {
48 let normalized = keyword.trim().to_ascii_lowercase();
49 if is_matchable_term(&normalized) {
50 keywords.push(normalized);
51 }
52 }
53 for domain in candidate.domains {
54 // A homepage on a code-hosting platform names where the plugin
55 // *lives*, not what it is; matching it would make every github-hosted
56 // plugin fire on any "github" mention. Everything else matches on
57 // declared data, which the host does not second-guess.
58 if let Some(normalized) = normalize_domain(domain)
59 && is_matchable_term(&normalized)
60 && !matches!(
61 normalized.as_str(),
62 "github.com" | "gitlab.com" | "bitbucket.org"
63 )
64 {
65 keywords.push(normalized);
66 }
67 }
68 let name = candidate.name.trim().to_ascii_lowercase();
69 if is_matchable_term(&name) {
70 keywords.push(name);
71 }
72 keywords
73 }
74
75 /// Generic words that never trigger a proactive plugin offer (0.10.1 plugin
76 /// offering policy, rule 6). Everyday requests like "fix the accessibility of
77 /// the login form" or "take a screenshot" are not evidence that the user needs
78 /// an integration.
79 ///
80 /// The marketplace repo's `scripts/check-marketplace.mjs` carries the same
81 /// list as `STOPLIST` and rejects a manifest keyword on it, so a catalog
82 /// author finds out at review time instead of the term silently never
83 /// matching here. Change both together; kept sorted so the two diff cleanly.
84 pub const GENERIC_TERM_STOPLIST: &[&str] = &[
85 "accessibility",
86 "agent",
87 "agents",
88 "automation",
89 "browser",
90 "browsers",
91 "chrome",
92 "code",
93 "codebase",
94 "codes",
95 "data",
96 "docs",
97 "documentation",
98 "extension",
99 "extensions",
100 "mcp",
101 "mcps",
102 "model",
103 "models",
104 "screenshot",
105 "screenshots",
106 "session",
107 "sessions",
108 "tool",
109 "tools",
110 "web",
111 "website",
112 "wiki",
113 ];
114
115 /// Admissibility for a match term: long enough to be a word, free of control
116 /// characters, and not a generic word from [`GENERIC_TERM_STOPLIST`].
117 ///
118 /// The remaining noise controls are the send-time toast's shared tips switch
119 /// and per-session budget, and per-plugin dismissal. There is no score
120 /// threshold on the proactive path (see `recommend.rs`).
121 fn is_matchable_term(term: &str) -> bool {
122 term.chars().count() >= 3
123 && !term.chars().any(char::is_control)
124 && !GENERIC_TERM_STOPLIST.contains(&term)
125 }
126
127 pub fn normalize_domain(domain: &str) -> Option<String> {
128 let trimmed = domain.trim();
129 let after_scheme = match trimmed.find("://") {
130 Some(i) => &trimmed[i + 3..],
131 None => trimmed,
132 };
133 let host = after_scheme
134 .split(['/', '?', '#'])
135 .next()
136 .unwrap_or(after_scheme)
137 .to_ascii_lowercase();
138 let host = host.strip_prefix("www.").unwrap_or(&host);
139 if host.is_empty() {
140 None
141 } else {
142 Some(host.to_string())
143 }
144 }
145
146 fn keyword_matches(haystack: &[u8], keyword: &[u8]) -> bool {
147 if keyword.is_empty() {
148 return false;
149 }
150 let len = haystack.len();
151 haystack
152 .windows(keyword.len())
153 .enumerate()
154 .any(|(start, window)| {
155 if window != keyword {
156 return false;
157 }
158 let end = start + keyword.len();
159 let start_ok = start == 0 || is_word(haystack[start - 1]) != is_word(haystack[start]);
160 let end_ok = end == len || is_word(haystack[end - 1]) != is_word(haystack[end]);
161 start_ok && end_ok
162 })
163 }
164
165 fn is_word(byte: u8) -> bool {
166 byte.is_ascii_alphanumeric() || byte == b'_'
167 }
168
169 #[cfg(test)]
170 mod tests {
171 use super::*;
172
173 // Existing selection tests assert the index; the receipt test below also
174 // checks the matched term carried through to the UI.
175 fn match_plugin_keyword(draft: &str, candidates: &[KeywordCandidate<'_>]) -> Option<usize> {
176 super::match_plugin_keyword(draft, candidates).map(|(index, _)| index)
177 }
178
179 #[test]
180 fn match_receipt_names_the_exact_trigger() {
181 let keywords = vec!["finance".to_string(), "mcp".to_string()];
182 let candidates = [candidate("kimi-datasource", &[], &keywords)];
183 assert_eq!(
184 super::match_plugin_keyword("help with finance", &candidates),
185 Some((0, "finance".into()))
186 );
187 for draft in [
188 "help with mcp",
189 "why did my mcp servers get stuck at connecting",
190 ] {
191 assert_eq!(super::match_plugin_keyword(draft, &candidates), None);
192 }
193 }
194
195 fn candidate<'a>(
196 name: &'a str,
197 domains: &'a [String],
198 keywords: &'a [String],
199 ) -> KeywordCandidate<'a> {
200 KeywordCandidate {
201 name,
202 domains,
203 keywords,
204 }
205 }
206
207 #[test]
208 fn longest_keyword_takes_precedence() {
209 let short = vec!["editor".to_string()];
210 let long = vec!["code editor".to_string()];
211 let candidates = [
212 candidate("plugin-a", &[], &short),
213 candidate("plugin-b", &[], &long),
214 ];
215 assert_eq!(
216 match_plugin_keyword("my code editor rocks", &candidates),
217 Some(1)
218 );
219 }
220
221 #[test]
222 fn word_boundary_required() {
223 let keywords = vec!["box".to_string()];
224 let candidates = [candidate("box", &[], &keywords)];
225 assert_eq!(match_plugin_keyword("i love boxing", &candidates), None);
226 assert_eq!(match_plugin_keyword("i love box", &candidates), Some(0));
227 }
228
229 #[test]
230 fn boxing_does_not_match_box() {
231 let keywords = vec!["box".to_string()];
232 let candidates = [candidate("box", &[], &keywords)];
233 assert_eq!(match_plugin_keyword("try boxing drills", &candidates), None);
234 }
235
236 #[test]
237 fn domains_match_inside_pasted_urls() {
238 let domains = vec!["figma.com".to_string(), "mcp.example.com".to_string()];
239 let none: Vec<String> = Vec::new();
240 let candidates = [candidate("design-app", &domains, &none)];
241 assert_eq!(
242 match_plugin_keyword("open https://www.figma.com/board/x please", &candidates),
243 Some(0)
244 );
245 assert_eq!(
246 match_plugin_keyword("open figma.com please", &candidates),
247 Some(0)
248 );
249 assert_eq!(match_plugin_keyword("open figma please", &candidates), None);
250 assert_eq!(
251 match_plugin_keyword("open https://mcp.example.com/tools", &candidates),
252 Some(0)
253 );
254 }
255
256 #[test]
257 fn name_is_used_as_fallback() {
258 let none: Vec<String> = Vec::new();
259 let candidates = [candidate("obsidian", &[], &none)];
260 assert_eq!(
261 match_plugin_keyword("open obsidian now", &candidates),
262 Some(0)
263 );
264 }
265
266 #[test]
267 fn draft_below_min_length_never_matches() {
268 let keywords = vec!["go".to_string()];
269 let candidates = [candidate("go", &[], &keywords)];
270 assert_eq!(match_plugin_keyword("go", &candidates), None);
271 let git = vec!["git".to_string()];
272 let candidates = [candidate("git", &[], &git)];
273 assert_eq!(match_plugin_keyword("git", &candidates), Some(0));
274 }
275
276 #[test]
277 fn declared_vocabulary_respects_shared_policy_and_mechanical_guards() {
278 let words = ["convex", "supabase", "stripe"];
279 let keywords = words
280 .iter()
281 .map(|word| word.to_string())
282 .collect::<Vec<_>>();
283 let candidates = [candidate("convex", &[], &keywords)];
284 for word in words {
285 assert_eq!(
286 match_plugin_keyword(&format!("please help with {word}"), &candidates),
287 Some(0),
288 "{word}"
289 );
290 }
291 // Two-character terms stay out on the mechanical floor.
292 let short_keywords = vec!["go".to_string()];
293 let short = [candidate("git", &[], &short_keywords)];
294 assert_eq!(match_plugin_keyword("go", &short), None);
295
296 let shared_host = vec!["https://github.com/example/plugin".to_string()];
297 let candidates = [candidate("supabase", &shared_host, &[])];
298 assert_eq!(
299 match_plugin_keyword("open github.com/example/repo", &candidates),
300 None
301 );
302 for command in ["/mcp", " /plugin show supabase", "/skills supabase"] {
303 assert_eq!(match_plugin_keyword(command, &candidates), None);
304 }
305 assert_eq!(
306 match_plugin_keyword("add supabase auth", &candidates),
307 Some(0)
308 );
309 }
310
311 #[test]
312 fn generic_terms_never_match_even_when_declared() {
313 // Policy rule 6: "improve accessibility" and "take a screenshot" are
314 // ordinary requests, not evidence the user wants an integration.
315 let keywords = GENERIC_TERM_STOPLIST
316 .iter()
317 .map(|word| word.to_string())
318 .collect::<Vec<_>>();
319 let candidates = [candidate("computer-use", &[], &keywords)];
320 for draft in [
321 "improve accessibility",
322 "take a screenshot",
323 "fix the accessibility of the login form",
324 "open the browser and check the web page",
325 "update the docs and the wiki",
326 "why did my mcp servers get stuck at connecting",
327 "ask the agent to use tools and models",
328 "read the code and data in these sessions",
329 ] {
330 assert_eq!(match_plugin_keyword(draft, &candidates), None, "{draft}");
331 }
332 // A plugin named with a generic word is not matchable by that name.
333 let none: Vec<String> = Vec::new();
334 for term in GENERIC_TERM_STOPLIST {
335 let draft = format!("help with {term}");
336 assert_eq!(match_plugin_keyword(&draft, &candidates), None, "{term}");
337 let named = [candidate(term, &[], &none)];
338 assert_eq!(match_plugin_keyword(&draft, &named), None, "{term}");
339 }
340 // A specific term on the same plugin still matches.
341 let specific = vec!["accessibility".to_string(), "computer use".to_string()];
342 let candidates = [candidate("computer-use", &[], &specific)];
343 assert_eq!(
344 match_plugin_keyword("let computer use drive the app", &candidates),
345 Some(0)
346 );
347 }
348
349 #[test]
350 fn stoplist_is_sorted_lowercase_and_unique() {
351 let mut sorted = GENERIC_TERM_STOPLIST.to_vec();
352 sorted.sort_unstable();
353 sorted.dedup();
354 assert_eq!(sorted, GENERIC_TERM_STOPLIST);
355 assert!(
356 GENERIC_TERM_STOPLIST
357 .iter()
358 .all(|term| *term == term.to_ascii_lowercase())
359 );
360 }
361 }
362
362 lines RUST