use chrono::Datelike;
use std::collections::HashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SemanticCategory {
ProductOrg,
LiveNews,
HistoryStatic,
GeneralEveryday,
}
impl SemanticCategory {
pub fn from_label(label: &str) -> Option<Self> {
let norm: String = label
.trim()
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
match norm.as_str() {
"productorg" | "product" | "organization" | "org" => Some(Self::ProductOrg),
"livenews" | "news" | "live" | "breakingnews" => Some(Self::LiveNews),
"historystatic" | "history" | "static" | "biography" | "encyclopedic" => {
Some(Self::HistoryStatic)
}
"generaleveryday" | "general" | "everyday" => Some(Self::GeneralEveryday),
_ => None,
}
}
pub fn default_for_intent(intent: &QueryIntent, is_time_sensitive: bool) -> Self {
if is_time_sensitive || *intent == QueryIntent::Temporal {
Self::LiveNews
} else {
match intent {
QueryIntent::Navigational => Self::ProductOrg,
QueryIntent::Person | QueryIntent::Factual => Self::HistoryStatic,
QueryIntent::Comparison | QueryIntent::HowTo | QueryIntent::Research => {
Self::GeneralEveryday
}
QueryIntent::Temporal => Self::LiveNews,
}
}
}
}
impl std::fmt::Display for SemanticCategory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SemanticCategory::ProductOrg => write!(f, "Product/Org"),
SemanticCategory::LiveNews => write!(f, "Live News"),
SemanticCategory::HistoryStatic => write!(f, "History/Static"),
SemanticCategory::GeneralEveryday => write!(f, "General Everyday"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum QueryIntent {
Factual,
Temporal,
Person,
Comparison,
HowTo,
Navigational,
Research,
}
#[derive(Debug, Clone, PartialEq)]
pub enum QueryComplexity {
Simple,
Medium,
Complex,
}
#[derive(Debug, Clone)]
pub struct QueryIntelligence {
pub intent: QueryIntent,
pub semantic_category: SemanticCategory,
pub is_time_sensitive: bool,
pub temporal_hint: Option<String>,
pub key_entities: Vec<String>,
pub complexity: QueryComplexity,
pub optimal_source_count: usize,
pub boost_news_engines: bool,
pub corrective_query: Option<String>,
}
pub fn analyze_query(query: &str) -> QueryIntelligence {
let q = query.trim();
let q_lower = q.to_lowercase();
let words: Vec<&str> = q_lower.split_whitespace().collect();
let word_count = words.len();
let intent = detect_intent(&q_lower, &words);
let (is_time_sensitive, temporal_hint) = detect_temporal(&q_lower, &intent);
let key_entities = extract_entities(q);
let complexity = if word_count <= 3 {
QueryComplexity::Simple
} else if word_count <= 8 {
QueryComplexity::Medium
} else {
QueryComplexity::Complex
};
let optimal_source_count = match (&intent, &complexity) {
(QueryIntent::Factual, QueryComplexity::Simple) => 15,
(QueryIntent::Factual, _) => 20,
(QueryIntent::Temporal, _) => 25,
(QueryIntent::Person, _) => 25,
(QueryIntent::Comparison, _) => 30,
(QueryIntent::HowTo, _) => 25,
(QueryIntent::Navigational, _) => 10,
(QueryIntent::Research, _) => 40,
};
let boost_news_engines = is_time_sensitive
|| intent == QueryIntent::Temporal
|| q_lower.contains("news")
|| q_lower.contains("breaking")
|| q_lower.contains("announced");
let semantic_category = SemanticCategory::default_for_intent(&intent, is_time_sensitive);
QueryIntelligence {
intent,
semantic_category,
is_time_sensitive,
temporal_hint,
key_entities,
complexity,
optimal_source_count,
boost_news_engines,
corrective_query: None,
}
}
fn is_structural_site_leader(word: &str) -> bool {
let clean = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '.');
if clean.len() < 2 {
return false;
}
if clean.contains('.') && !clean.starts_with('.') && !clean.ends_with('.') {
return true;
}
!matches!(
clean,
"what"
| "how"
| "why"
| "who"
| "when"
| "where"
| "which"
| "is"
| "are"
| "was"
| "were"
| "can"
| "could"
| "should"
| "does"
| "do"
| "did"
| "will"
| "would"
| "explain"
| "compare"
| "define"
| "tell"
| "show"
| "list"
| "give"
| "the"
| "a"
| "an"
| "best"
| "top"
| "latest"
| "current"
| "recent"
| "upcoming"
| "history"
| "biography"
| "overview"
| "impact"
| "future"
)
}
const NAV_INTENTS: &[&str] = &[
"login",
"log",
"signin",
"sign",
"website",
"site",
"homepage",
"home",
"dashboard",
"account",
"settings",
"tracking",
"orders",
"order",
"trending",
"search",
"docs",
"documentation",
"repository",
"repo",
"questions",
"profile",
"inbox",
"download",
"pricing",
"checkout",
];
const BIOGRAPHICAL: &[&str] = &[
"achievements",
"contributions",
"biography",
"career",
"net worth",
"early life",
"born",
"childhood",
"awards",
"legacy",
"inventions",
"discoveries",
"known for",
"life of",
"education",
"family",
];
fn detect_intent(q_lower: &str, words: &[&str]) -> QueryIntent {
if q_lower.contains(" vs ")
|| q_lower.contains(" vs. ")
|| q_lower.contains(" versus ")
|| q_lower.contains("difference between")
|| q_lower.contains("differences")
|| q_lower.contains("compared to")
|| q_lower.contains("comparison of")
|| q_lower.contains("comparison")
|| (q_lower.contains(" or ") && (q_lower.contains("which") || q_lower.contains("better")))
{
return QueryIntent::Comparison;
}
if words.len() <= 5 {
let leads_with_site = words
.first()
.map(|w| is_structural_site_leader(w))
.unwrap_or(false);
let has_domain_token = words
.iter()
.any(|w| w.contains('.') && w.len() >= 4 && !w.ends_with('.'));
let has_nav_word = words.iter().any(|w| NAV_INTENTS.contains(w));
if (leads_with_site && has_nav_word) || (has_domain_token && words.len() <= 4) {
return QueryIntent::Navigational;
}
}
let explanatory = q_lower.starts_with("how does")
|| q_lower.starts_with("how do ")
|| q_lower.starts_with("how is")
|| q_lower.starts_with("how are")
|| q_lower.starts_with("why ")
|| q_lower.starts_with("what happens when");
let wants_depth = q_lower.contains("in detail")
|| q_lower.contains("step by step")
|| q_lower.contains("under the hood")
|| q_lower.contains("internals")
|| q_lower.contains("use cases")
|| q_lower.contains("implications")
|| q_lower.contains("and what are");
const RESEARCH_MARKERS: &[&str] = &[
"explain",
"analyze",
"analyse",
"research",
"comprehensive",
"in depth",
"in-depth",
"deep dive",
"overview of",
"implications of",
"impact of",
"future of",
"trade-offs",
"tradeoffs",
"architecture of",
];
if RESEARCH_MARKERS.iter().any(|m| q_lower.contains(m))
|| (explanatory && (wants_depth || q_lower.contains("work")))
{
return QueryIntent::Research;
}
const PERSON_PREFIXES: &[&str] = &[
"who is",
"who was",
"who are",
"tell me about",
"biography of",
"bio of",
"life of",
"about the person",
];
if PERSON_PREFIXES.iter().any(|p| q_lower.contains(p)) {
return QueryIntent::Person;
}
if BIOGRAPHICAL.iter().any(|b| q_lower.contains(b)) && words.len() >= 2 {
return QueryIntent::Person;
}
const HOWTO_MARKERS: &[&str] = &[
"how to",
"how can i",
"steps to",
"guide to",
"tutorial",
"instructions for",
"ways to",
"tips for",
"best way to",
"learn to",
"teach me",
"set up",
"setup",
"install",
"configure",
"deploy",
"create a",
"build a",
];
if HOWTO_MARKERS.iter().any(|m| q_lower.contains(m)) {
return QueryIntent::HowTo;
}
const TEMPORAL_WORDS: &[&str] = &[
"latest",
"current",
"newest",
"recent",
"today",
"breaking",
"live",
"upcoming",
"now",
"tonight",
"yesterday",
"tomorrow",
];
const TEMPORAL_PHRASES: &[&str] = &[
"right now",
"as of",
"just announced",
"this year",
"this week",
"this month",
"what is the price",
"stock price",
"market cap",
"score of",
"results of",
"who won",
"schedule",
];
if TEMPORAL_WORDS.iter().any(|w| words.iter().any(|t| t == w))
|| TEMPORAL_PHRASES.iter().any(|p| q_lower.contains(p))
{
return QueryIntent::Temporal;
}
{
let this_year = chrono::Utc::now().year();
if words.iter().any(|w| {
w.parse::<i32>()
.map(|y| (this_year - 3..=this_year + 5).contains(&y))
.unwrap_or(false)
}) {
return QueryIntent::Temporal;
}
}
const ROLE_PATTERNS: &[&str] = &[
"ceo of",
"president of",
"prime minister of",
"leader of",
"founder of",
"chairman of",
"director of",
"head of",
"net worth",
"salary of",
];
if ROLE_PATTERNS.iter().any(|p| q_lower.contains(p)) {
return QueryIntent::Temporal;
}
if words.len() >= 9 {
return QueryIntent::Research;
}
QueryIntent::Factual
}
fn word_tokens(q: &str) -> Vec<&str> {
q.split(|c: char| !crate::util::is_word_char(c))
.filter(|t| !t.is_empty())
.collect()
}
fn detect_temporal(q_lower: &str, intent: &QueryIntent) -> (bool, Option<String>) {
const RECENCY_WORDS: &[&str] = &[
"latest",
"current",
"currently",
"newest",
"recent",
"recently",
"today",
"now",
"updated",
"breaking",
"upcoming",
"live",
"ongoing",
"tonight",
"yesterday",
"tomorrow",
];
const RECENCY_PHRASES: &[&str] = &[
"this year",
"this week",
"this month",
"this quarter",
"right now",
"as of",
"last week",
"last month",
"last year",
"so far",
"up to date",
"at the moment",
"these days",
];
let toks = word_tokens(q_lower);
if let Some(w) = RECENCY_WORDS.iter().find(|w| toks.iter().any(|t| t == *w)) {
return (true, Some((*w).to_string()));
}
if let Some(p) = RECENCY_PHRASES.iter().find(|p| q_lower.contains(*p)) {
return (true, Some((*p).to_string()));
}
const DYNAMIC_FACTS: &[&str] = &[
"ceo of",
"president of",
"prime minister of",
"leader of",
"founder of",
"chairman of",
"director of",
"head of",
"owner of",
"net worth",
"worth of",
"stock price",
"share price",
"market cap",
"population of",
"exchange rate",
"weather in",
"score of",
"who is the",
"how much is",
"what is the price",
];
if let Some(p) = DYNAMIC_FACTS.iter().find(|p| q_lower.contains(*p)) {
return (true, Some((*p).to_string()));
}
if *intent == QueryIntent::Temporal {
return (true, Some("current".to_string()));
}
let this_year = chrono::Utc::now().year();
for year in (this_year - 10)..=(this_year + 10) {
let y = year.to_string();
if toks.iter().any(|t| *t == y) {
return (true, Some(y));
}
}
(false, None)
}
fn is_contraction_token(raw_word: &str) -> bool {
let trimmed =
raw_word.trim_matches(|c: char| !crate::util::is_word_char(c) && c != '\'' && c != '’');
if let Some(rest) = trimmed
.strip_suffix("'s")
.or_else(|| trimmed.strip_suffix("’s"))
{
return rest.contains('\'') || rest.contains('’');
}
trimmed.contains('\'') || trimmed.contains('’')
}
fn strip_possessive(word: &str) -> &str {
word.strip_suffix("'s")
.or_else(|| word.strip_suffix("’s"))
.unwrap_or(word)
}
fn has_internal_caps_or_digits(word: &str) -> bool {
word.chars()
.skip(1)
.any(|c| c.is_uppercase() || c.is_ascii_digit())
}
fn extract_entities(query: &str) -> Vec<String> {
let stop_words: HashSet<&str> = [
"what", "is", "the", "a", "an", "of", "in", "to", "for", "and", "or", "how", "does", "do",
"can", "about", "with", "from", "that", "this", "are", "was", "were", "be", "been",
"being", "have", "has", "had", "will", "would", "it", "its", "on", "at", "by", "but",
"not", "so", "if", "than", "then", "my", "me", "we", "you", "your", "who", "which", "when",
"where", "why", "all", "each", "tell", "give", "show", "find", "between", "vs", "versus",
"compared", "latest", "current", "recent", "new", "best", "top", "most", "many", "much",
"very", "just", "also", "now", "today", "explain", "describe", "analyze",
]
.iter()
.cloned()
.collect();
let total_words = query.split_whitespace().count();
let mut entities = Vec::new();
let clauses = query.split(|c: char| {
matches!(
c,
'.' | '?'
| '!'
| ','
| ';'
| ':'
| '\n'
| '—'
| '–'
| '('
| ')'
| '['
| ']'
| '"'
| '“'
| '”'
)
});
for clause in clauses {
let mut current_entity: Vec<(String, bool, bool)> = Vec::new(); let mut seen_any_token_in_clause = false;
for raw_word in clause.split_whitespace() {
let is_clause_start = !seen_any_token_in_clause;
seen_any_token_in_clause = true;
if is_contraction_token(raw_word) {
if !current_entity.is_empty() {
if current_entity.len() >= 2
|| !current_entity[0].1
|| current_entity[0].2
|| total_words <= 4
{
entities.push(
current_entity
.iter()
.map(|(w, _, _)| w.as_str())
.collect::<Vec<_>>()
.join(" "),
);
}
current_entity.clear();
}
continue;
}
let without_possessive = strip_possessive(raw_word);
let clean = without_possessive.trim_matches(|c: char| !crate::util::is_word_char(c));
if clean.is_empty() {
continue;
}
let first_char = clean.chars().next().unwrap_or(' ');
let lower = clean.to_lowercase();
if first_char.is_uppercase()
&& !stop_words.contains(lower.as_str())
&& clean.chars().count() > 1
{
current_entity.push((
clean.to_string(),
is_clause_start,
has_internal_caps_or_digits(clean),
));
} else if !current_entity.is_empty() {
if current_entity.len() >= 2
|| !current_entity[0].1
|| current_entity[0].2
|| total_words <= 4
{
entities.push(
current_entity
.iter()
.map(|(w, _, _)| w.as_str())
.collect::<Vec<_>>()
.join(" "),
);
}
current_entity.clear();
}
}
if !current_entity.is_empty() {
if current_entity.len() >= 2
|| !current_entity[0].1
|| current_entity[0].2
|| total_words <= 4
{
entities.push(
current_entity
.iter()
.map(|(w, _, _)| w.as_str())
.collect::<Vec<_>>()
.join(" "),
);
}
current_entity.clear();
}
}
if entities.is_empty() {
let has_non_ascii_alpha = query.chars().any(|c| !c.is_ascii() && c.is_alphabetic());
let has_any_uppercase = query.chars().any(|c| c.is_uppercase());
if has_non_ascii_alpha {
let non_ascii_tokens: Vec<String> = query
.split_whitespace()
.map(|w| w.trim_matches(|c: char| !crate::util::is_word_char(c)))
.filter(|w| {
w.chars().any(|c| !c.is_ascii() && c.is_alphabetic()) && w.chars().count() >= 3
})
.take(4)
.map(|w| w.to_string())
.collect();
if !non_ascii_tokens.is_empty() {
entities.push(non_ascii_tokens.join(" "));
}
} else if !has_any_uppercase {
let mut phrase = Vec::new();
for raw_word in query.split_whitespace() {
if is_contraction_token(raw_word) {
continue;
}
let clean = strip_possessive(raw_word)
.trim_matches(|c: char| !crate::util::is_word_char(c));
let lower = clean.to_lowercase();
if clean.chars().count() >= 3
&& !stop_words.contains(lower.as_str())
&& !clean.chars().all(|c| c.is_ascii_digit())
{
phrase.push(clean.to_string());
if phrase.len() >= 3 {
break;
}
} else if !phrase.is_empty() {
break;
}
}
if !phrase.is_empty() {
entities.push(phrase.join(" "));
}
}
}
let mut seen = HashSet::new();
entities.retain(|e| seen.insert(e.to_lowercase()));
entities
}
impl std::fmt::Display for QueryIntent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
QueryIntent::Factual => write!(f, "factual"),
QueryIntent::Temporal => write!(f, "temporal"),
QueryIntent::Person => write!(f, "person"),
QueryIntent::Comparison => write!(f, "comparison"),
QueryIntent::HowTo => write!(f, "howto"),
QueryIntent::Navigational => write!(f, "navigational"),
QueryIntent::Research => write!(f, "research"),
}
}
}
impl std::fmt::Display for QueryComplexity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
QueryComplexity::Simple => write!(f, "simple"),
QueryComplexity::Medium => write!(f, "medium"),
QueryComplexity::Complex => write!(f, "complex"),
}
}
}
pub fn multi_query_enabled() -> bool {
std::env::var("MULTI_QUERY")
.unwrap_or_else(|_| "true".to_string())
.to_lowercase()
== "true"
}
pub fn max_sub_queries() -> usize {
std::env::var("MAX_SUB_QUERIES")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(5)
.clamp(1, 8)
}
pub fn decompose_query(query: &str, intel: &QueryIntelligence) -> Vec<String> {
let q = query.trim();
if q.is_empty() {
return Vec::new();
}
if intel.intent == QueryIntent::Navigational || intel.complexity == QueryComplexity::Simple {
return vec![q.to_string()];
}
let mut out = vec![q.to_string()];
if intel.intent == QueryIntent::Comparison {
for sep in [" vs ", " vs. ", " versus ", " compared to ", " or "] {
if let Some((a, b)) = q.split_once(sep) {
let (a, b) = (a.trim(), b.trim());
if crate::util::char_len(a) >= 3 && crate::util::char_len(b) >= 3 {
out.push(a.to_string());
out.push(b.to_string());
}
break;
}
}
}
if intel.is_time_sensitive && out.len() < max_sub_queries() {
let year = chrono::Utc::now().format("%Y").to_string();
if !q.contains(&year) {
out.push(format!("{q} {year}"));
}
}
for e in intel
.key_entities
.iter()
.filter(|e| e.split_whitespace().count() >= 2)
{
if out.len() >= max_sub_queries() {
break;
}
out.push(e.clone());
}
let mut seen = std::collections::HashSet::new();
out.retain(|s| seen.insert(s.to_lowercase()));
out.truncate(max_sub_queries().min(3));
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_york_is_not_time_sensitive() {
let i = analyze_query("New York population");
assert!(
!i.is_time_sensitive || i.temporal_hint.as_deref() != Some("new"),
"matched on 'new' inside 'New York': {:?}",
i.temporal_hint
);
}
#[test]
fn know_renewable_and_justice_are_not_time_sensitive() {
for q in [
"how do I know if my code compiles",
"renewable energy sources explained",
"justice system reform history",
"newton laws of motion",
"snowfall in the alps",
] {
let i = analyze_query(q);
assert!(
!i.is_time_sensitive,
"{q:?} wrongly time-sensitive (hint={:?}) — substring match regression",
i.temporal_hint
);
}
}
#[test]
fn genuinely_recent_queries_are_still_detected() {
for q in [
"latest iphone release",
"current ceo of google",
"what happened today in markets",
"breaking news ukraine",
"openai announcement this week",
"who is the prime minister of india",
"bitcoin stock price",
] {
assert!(
analyze_query(q).is_time_sensitive,
"{q:?} should be time-sensitive"
);
}
}
#[test]
fn explicit_year_is_a_temporal_signal() {
assert!(analyze_query("cricket world cup 2027 schedule").is_time_sensitive);
assert!(!analyze_query("model 2020x specifications").is_time_sensitive);
}
#[test]
fn simple_and_navigational_queries_are_not_decomposed() {
let simple = analyze_query("rust lifetimes");
assert_eq!(decompose_query("rust lifetimes", &simple).len(), 1);
let nav = analyze_query("youtube login");
assert_eq!(decompose_query("youtube login", &nav).len(), 1);
}
#[test]
fn no_midpoint_fragments_or_bare_entities() {
let q = "what are the long term implications of quantum computing for modern cryptography";
let intel = analyze_query(q);
let subs = decompose_query(q, &intel);
for s in &subs {
assert!(
s == q || s.split_whitespace().count() >= 2,
"bare/fragment sub-query emitted: {s:?}"
);
assert!(
!s.ends_with(" of") && !s.ends_with(" the") && !s.ends_with(" for"),
"dangling-preposition fragment: {s:?}"
);
}
}
#[test]
fn decomposition_is_capped_at_three() {
let q = "compare Apple Vision Pro versus Meta Quest Three for enterprise training in 2027";
let intel = analyze_query(q);
let subs = decompose_query(q, &intel);
assert!(subs.len() <= 3, "got {} sub-queries: {subs:?}", subs.len());
assert_eq!(subs[0], q, "the original query must come first");
}
#[test]
fn comparison_queries_split_into_both_sides() {
let q = "postgres vs mysql for analytics";
let intel = analyze_query(q);
let subs = decompose_query(q, &intel);
assert!(subs.len() >= 2, "comparison should split: {subs:?}");
assert!(subs.iter().any(|s| s.contains("postgres")));
}
#[test]
fn decomposition_never_returns_duplicates() {
let q = "latest ai news 2026";
let intel = analyze_query(q);
let subs = decompose_query(q, &intel);
let mut lower: Vec<String> = subs.iter().map(|s| s.to_lowercase()).collect();
lower.sort();
let before = lower.len();
lower.dedup();
assert_eq!(before, lower.len(), "duplicates in {subs:?}");
}
#[test]
fn navigational_recognises_site_led_queries() {
for q in [
"github new repository",
"amazon order tracking",
"youtube trending",
"stackoverflow rust questions",
"MDN CSS flexbox documentation",
"gmail login",
] {
assert_eq!(
analyze_query(q).intent,
QueryIntent::Navigational,
"{q:?} should be navigational"
);
}
}
#[test]
fn comparison_beats_navigational_when_both_match() {
assert_eq!(
analyze_query("Docker vs Kubernetes differences").intent,
QueryIntent::Comparison
);
assert_eq!(
analyze_query("github vs gitlab for private repos").intent,
QueryIntent::Comparison
);
}
#[test]
fn explanatory_how_does_is_research_not_howto() {
for q in [
"how does the TCP three-way handshake work in detail",
"how does HTTPS TLS encryption work step by step",
"how do bloom filters work and what are their use cases",
] {
assert_eq!(analyze_query(q).intent, QueryIntent::Research, "{q:?}");
}
for q in [
"how to set up SSH keys on Linux",
"how to center a div in CSS",
"how to deploy a Docker container to AWS",
] {
assert_eq!(analyze_query(q).intent, QueryIntent::HowTo, "{q:?}");
}
}
#[test]
fn biographical_framing_without_who_is_is_person() {
for q in [
"Linus Torvalds contributions to open source",
"Alan Turing achievements",
"biography of Marie Curie",
"who is Jensen Huang",
] {
assert_eq!(analyze_query(q).intent, QueryIntent::Person, "{q:?}");
}
}
#[test]
fn year_anchored_queries_are_temporal() {
for q in [
"2026 FIFA World Cup schedule",
"upcoming solar eclipse 2026",
"who won the 2025 NBA Finals",
] {
assert_eq!(analyze_query(q).intent, QueryIntent::Temporal, "{q:?}");
}
}
#[test]
fn stable_reference_facts_stay_factual() {
for q in [
"population of Japan",
"capital of France",
"boiling point of water",
] {
assert_eq!(analyze_query(q).intent, QueryIntent::Factual, "{q:?}");
}
}
#[test]
fn empty_query_yields_nothing() {
let intel = analyze_query("");
assert!(decompose_query("", &intel).is_empty());
assert!(decompose_query(" ", &intel).is_empty());
}
#[test]
fn clause_boundaries_and_contractions_never_form_fake_entities() {
let q = "Wait, what is the latest update on Claude Cowork? Specifically, I’m asking about features.";
let intel = analyze_query(q);
assert!(
intel.key_entities.iter().any(|e| e == "Claude Cowork"),
"expected 'Claude Cowork' in {:?}",
intel.key_entities
);
assert!(
!intel
.key_entities
.iter()
.any(|e| e.contains("Specifically") || e.contains("Wait")),
"conversational clause starters leaked into entities: {:?}",
intel.key_entities
);
}
#[test]
fn lowercase_and_non_latin_queries_extract_subject_entities() {
let lower_intel = analyze_query("what is the dhruv rathi latest video");
assert!(
!lower_intel.key_entities.is_empty() && lower_intel.key_entities[0].contains("dhruv"),
"lowercase query should still extract subject entity: {:?}",
lower_intel.key_entities
);
let hindi_intel = analyze_query("केप्लर टेलिस्कोप की प्रमुख खोजें");
assert!(
!hindi_intel.key_entities.is_empty(),
"non-Latin script query should extract script entities: {:?}",
hindi_intel.key_entities
);
}
}