Skip to main content

arbor_graph/
lexicon.rs

1//! Identifier tokenization and a code-domain synonym lexicon.
2//!
3//! Substring search cannot answer "where is login?" when the function is called
4//! `get_authenticated` — there is no shared substring. Yet a reviewer asking
5//! about auth means both, and so does anyone asking Arbor about a security
6//! surface.
7//!
8//! This module closes that gap without embeddings: identifiers are split into
9//! their real word tokens, and tokens are mapped onto a small hand-curated set
10//! of concepts. It is deterministic, offline, auditable, and costs nothing to
11//! run — the properties that make the rest of the engine worth trusting.
12//!
13//! Deliberately *not* a semantic model. It resolves vocabulary, not meaning. A
14//! function named `handleThing` will not be found by "auth" no matter what it
15//! does; for that, see structural role inference over the call graph.
16
17use std::collections::{HashMap, HashSet};
18
19/// Splits an identifier into lowercase word tokens.
20///
21/// Handles `snake_case`, `camelCase`, `PascalCase`, `kebab-case`, `SCREAMING_CASE`,
22/// dotted paths, and acronym runs (`parseHTTPResponse` → `parse`, `http`, `response`).
23///
24/// Tokens shorter than two characters are dropped: single letters are loop
25/// variables and type parameters, and indexing them matches everything.
26pub fn tokenize_identifier(identifier: &str) -> Vec<String> {
27    let mut tokens = Vec::new();
28    let mut current = String::new();
29
30    let chars: Vec<char> = identifier.chars().collect();
31
32    for i in 0..chars.len() {
33        let c = chars[i];
34
35        if !c.is_alphanumeric() {
36            // `_`, `-`, `.`, `/`, space — all separators.
37            if !current.is_empty() {
38                tokens.push(std::mem::take(&mut current));
39            }
40            continue;
41        }
42
43        if c.is_uppercase() && !current.is_empty() {
44            let prev = chars[i - 1];
45            let next_is_lower = chars.get(i + 1).is_some_and(|n| n.is_lowercase());
46
47            // Break before a capital that starts a new word: either the
48            // previous char was lowercase (`getUser`), or we are leaving an
49            // acronym run into a new word (`HTTPResponse`).
50            if prev.is_lowercase() || prev.is_numeric() || (prev.is_uppercase() && next_is_lower) {
51                tokens.push(std::mem::take(&mut current));
52            }
53        }
54
55        current.push(c.to_ascii_lowercase());
56    }
57
58    if !current.is_empty() {
59        tokens.push(current);
60    }
61
62    tokens.retain(|t| t.len() >= 2);
63    tokens
64}
65
66/// Reduces a token to a crude stem so `handlers`, `handler`, and `handling`
67/// collapse together.
68///
69/// Intentionally conservative — over-stemming collapses unrelated words and
70/// produces confident nonsense, which is worse than a missed match.
71pub fn stem(token: &str) -> String {
72    let t = token;
73
74    for suffix in ["ing", "ers", "ed"] {
75        if t.len() > suffix.len() + 3 && t.ends_with(suffix) {
76            return t[..t.len() - suffix.len()].to_string();
77        }
78    }
79    for suffix in ["es", "er", "s"] {
80        if t.len() > suffix.len() + 2 && t.ends_with(suffix) {
81            return t[..t.len() - suffix.len()].to_string();
82        }
83    }
84
85    t.to_string()
86}
87
88/// Concept clusters over code vocabulary.
89///
90/// The first entry of each row is the canonical concept name; every entry maps
91/// to it. Queries expand through this table in both directions, so searching
92/// `login` reaches `authenticate`, `session`, and `credential`.
93const CONCEPT_CLUSTERS: &[&[&str]] = &[
94    &[
95        "auth",
96        "authenticate",
97        "authenticated",
98        "authentication",
99        "authorize",
100        "authorization",
101        "login",
102        "logout",
103        "signin",
104        "signout",
105        "signup",
106        "session",
107        "credential",
108        "credentials",
109        "password",
110        "passwd",
111        "token",
112        "jwt",
113        "oauth",
114        "sso",
115        "saml",
116        "identity",
117        "principal",
118        "bearer",
119        "apikey",
120        "mfa",
121        "otp",
122        "2fa",
123    ],
124    &[
125        "crypto",
126        "encrypt",
127        "decrypt",
128        "cipher",
129        "hash",
130        "digest",
131        "sign",
132        "signature",
133        "verify",
134        "hmac",
135        "bcrypt",
136        "scrypt",
137        "argon",
138        "pbkdf",
139        "aes",
140        "rsa",
141        "nonce",
142        "salt",
143        "keypair",
144    ],
145    &[
146        "secret",
147        "secrets",
148        "vault",
149        "keystore",
150        "credentialstore",
151        "env",
152        "environment",
153        "config",
154        "configuration",
155        "settings",
156    ],
157    &[
158        "payment",
159        "pay",
160        "billing",
161        "invoice",
162        "charge",
163        "refund",
164        "checkout",
165        "subscription",
166        "stripe",
167        "paypal",
168        "razorpay",
169        "card",
170        "price",
171        "pricing",
172        "plan",
173        "wallet",
174        "payout",
175        "transaction",
176    ],
177    &[
178        "database",
179        "db",
180        "sql",
181        "query",
182        "repository",
183        "repo",
184        "dao",
185        "orm",
186        "migration",
187        "schema",
188        "table",
189        "insert",
190        "update",
191        "delete",
192        "select",
193        "transaction",
194        "cursor",
195        "connection",
196        "pool",
197    ],
198    &[
199        "network",
200        "http",
201        "https",
202        "request",
203        "response",
204        "fetch",
205        "client",
206        "api",
207        "endpoint",
208        "route",
209        "router",
210        "handler",
211        "controller",
212        "middleware",
213        "webhook",
214        "rpc",
215        "grpc",
216        "socket",
217        "url",
218        "uri",
219    ],
220    &[
221        "validate",
222        "validation",
223        "validator",
224        "sanitize",
225        "sanitizer",
226        "escape",
227        "check",
228        "verify",
229        "assert",
230        "guard",
231        "constraint",
232        "schema",
233    ],
234    &[
235        "user",
236        "users",
237        "account",
238        "accounts",
239        "profile",
240        "member",
241        "customer",
242        "tenant",
243        "organization",
244        "org",
245        "team",
246        "role",
247        "permission",
248        "permissions",
249        "acl",
250        "policy",
251    ],
252    &[
253        "file",
254        "filesystem",
255        "fs",
256        "path",
257        "directory",
258        "dir",
259        "upload",
260        "download",
261        "stream",
262        "blob",
263        "storage",
264        "bucket",
265    ],
266    &[
267        "log",
268        "logger",
269        "logging",
270        "trace",
271        "tracing",
272        "audit",
273        "metric",
274        "metrics",
275        "telemetry",
276        "monitor",
277        "monitoring",
278        "observability",
279    ],
280    &[
281        "cache",
282        "caching",
283        "memo",
284        "memoize",
285        "redis",
286        "memcached",
287        "ttl",
288        "evict",
289        "invalidate",
290    ],
291    &[
292        "queue",
293        "job",
294        "jobs",
295        "worker",
296        "task",
297        "scheduler",
298        "cron",
299        "background",
300        "async",
301        "batch",
302        "consumer",
303        "producer",
304        "publish",
305        "subscribe",
306    ],
307    &[
308        "error",
309        "errors",
310        "exception",
311        "panic",
312        "fail",
313        "failure",
314        "fault",
315        "retry",
316        "fallback",
317        "recover",
318        "handle",
319    ],
320    &[
321        "test",
322        "tests",
323        "spec",
324        "fixture",
325        "mock",
326        "stub",
327        "fake",
328        "assert",
329        "expect",
330        "benchmark",
331    ],
332    &[
333        "parse",
334        "parser",
335        "serialize",
336        "serializer",
337        "deserialize",
338        "decode",
339        "encode",
340        "marshal",
341        "unmarshal",
342        "json",
343        "yaml",
344        "toml",
345        "xml",
346    ],
347    &[
348        "create",
349        "new",
350        "make",
351        "build",
352        "construct",
353        "init",
354        "initialize",
355        "insert",
356        "add",
357        "register",
358    ],
359    &[
360        "delete",
361        "remove",
362        "destroy",
363        "drop",
364        "purge",
365        "erase",
366        "clear",
367        "unregister",
368    ],
369    &[
370        "get", "fetch", "read", "load", "find", "lookup", "retrieve", "query", "list",
371    ],
372    &[
373        "set", "write", "save", "store", "persist", "put", "commit", "flush",
374    ],
375];
376
377/// Bidirectional token↔concept index over [`CONCEPT_CLUSTERS`].
378#[derive(Debug, Clone)]
379pub struct Lexicon {
380    /// Token → the concepts it belongs to.
381    token_to_concepts: HashMap<&'static str, Vec<&'static str>>,
382    /// Concept → every token in it.
383    concept_to_tokens: HashMap<&'static str, &'static [&'static str]>,
384}
385
386impl Default for Lexicon {
387    fn default() -> Self {
388        Self::new()
389    }
390}
391
392impl Lexicon {
393    pub fn new() -> Self {
394        let mut token_to_concepts: HashMap<&'static str, Vec<&'static str>> = HashMap::new();
395        let mut concept_to_tokens = HashMap::new();
396
397        for cluster in CONCEPT_CLUSTERS {
398            let Some(&concept) = cluster.first() else {
399                continue;
400            };
401            concept_to_tokens.insert(concept, *cluster);
402            for token in cluster.iter() {
403                token_to_concepts.entry(*token).or_default().push(concept);
404            }
405        }
406
407        Self {
408            token_to_concepts,
409            concept_to_tokens,
410        }
411    }
412
413    /// Concepts a token belongs to, if any.
414    pub fn concepts_for(&self, token: &str) -> &[&'static str] {
415        self.token_to_concepts
416            .get(token)
417            .map(|v| v.as_slice())
418            .unwrap_or(&[])
419    }
420
421    /// Every token related to the given one, including itself.
422    ///
423    /// `login` → `auth`, `authenticate`, `session`, `token`, …
424    pub fn expand(&self, token: &str) -> HashSet<String> {
425        let mut out = HashSet::new();
426        out.insert(token.to_string());
427
428        for concept in self.concepts_for(token) {
429            if let Some(tokens) = self.concept_to_tokens.get(concept) {
430                for t in tokens.iter() {
431                    out.insert((*t).to_string());
432                }
433            }
434        }
435
436        out
437    }
438
439    /// Whether two tokens share a concept.
440    pub fn related(&self, a: &str, b: &str) -> bool {
441        if a == b {
442            return true;
443        }
444        let a_concepts = self.concepts_for(a);
445        !a_concepts.is_empty() && self.concepts_for(b).iter().any(|c| a_concepts.contains(c))
446    }
447
448    /// Number of concept clusters.
449    pub fn concept_count(&self) -> usize {
450        self.concept_to_tokens.len()
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    #[test]
459    fn splits_snake_case() {
460        assert_eq!(
461            tokenize_identifier("get_authenticated_user"),
462            ["get", "authenticated", "user"]
463        );
464    }
465
466    #[test]
467    fn splits_camel_and_pascal_case() {
468        assert_eq!(
469            tokenize_identifier("getUserProfile"),
470            ["get", "user", "profile"]
471        );
472        assert_eq!(tokenize_identifier("UserService"), ["user", "service"]);
473    }
474
475    #[test]
476    fn splits_acronym_runs() {
477        assert_eq!(
478            tokenize_identifier("parseHTTPResponse"),
479            ["parse", "http", "response"]
480        );
481        assert_eq!(tokenize_identifier("HTTPServer"), ["http", "server"]);
482    }
483
484    #[test]
485    fn splits_mixed_separators() {
486        assert_eq!(
487            tokenize_identifier("auth-service.verify_token"),
488            ["auth", "service", "verify", "token"]
489        );
490        assert_eq!(
491            tokenize_identifier("src/api/authHandler"),
492            ["src", "api", "auth", "handler"]
493        );
494    }
495
496    #[test]
497    fn drops_single_character_tokens() {
498        // Type parameters and loop variables match everything; indexing them
499        // is pure noise.
500        assert_eq!(tokenize_identifier("a_b_cd"), ["cd"]);
501        assert_eq!(tokenize_identifier("mapToT"), ["map", "to"]);
502        assert_eq!(tokenize_identifier("x"), Vec::<String>::new());
503    }
504
505    #[test]
506    fn handles_screaming_case_and_digits() {
507        assert_eq!(
508            tokenize_identifier("MAX_RETRY_COUNT"),
509            ["max", "retry", "count"]
510        );
511        assert_eq!(tokenize_identifier("oauth2Client"), ["oauth2", "client"]);
512    }
513
514    #[test]
515    fn empty_and_degenerate_input() {
516        assert!(tokenize_identifier("").is_empty());
517        assert!(tokenize_identifier("_").is_empty());
518        assert!(tokenize_identifier("___").is_empty());
519    }
520
521    #[test]
522    fn stemming_is_conservative() {
523        assert_eq!(stem("handlers"), "handl");
524        assert_eq!(stem("handler"), "handl");
525        assert_eq!(stem("tokens"), "token");
526        // Too short to strip — refuses rather than mangling.
527        assert_eq!(stem("as"), "as");
528        assert_eq!(stem("api"), "api");
529        assert_eq!(stem("les"), "les");
530    }
531
532    #[test]
533    fn login_and_authenticated_share_a_concept() {
534        // The exact case that motivated this module.
535        let lex = Lexicon::new();
536        assert!(lex.related("login", "authenticated"));
537        assert!(lex.related("login", "session"));
538        assert!(lex.related("signin", "jwt"));
539    }
540
541    #[test]
542    fn expansion_reaches_synonyms() {
543        let lex = Lexicon::new();
544        let expanded = lex.expand("login");
545        assert!(expanded.contains("authenticate"));
546        assert!(expanded.contains("credential"));
547        assert!(expanded.contains("login"));
548    }
549
550    #[test]
551    fn unrelated_tokens_do_not_match() {
552        let lex = Lexicon::new();
553        assert!(!lex.related("login", "invoice"));
554        assert!(!lex.related("cache", "password"));
555        // An unknown token relates only to itself.
556        assert!(!lex.related("wibble", "auth"));
557        assert!(lex.related("wibble", "wibble"));
558    }
559
560    #[test]
561    fn expansion_of_unknown_token_is_just_itself() {
562        let lex = Lexicon::new();
563        let expanded = lex.expand("zzzz");
564        assert_eq!(expanded.len(), 1);
565        assert!(expanded.contains("zzzz"));
566    }
567
568    #[test]
569    fn every_cluster_has_a_canonical_head() {
570        let lex = Lexicon::new();
571        assert_eq!(lex.concept_count(), CONCEPT_CLUSTERS.len());
572    }
573}