1use std::collections::HashSet;
8
9use qualia_core_db::q_hash;
10
11use crate::chat_session::{ChatEnvironment, OntologyScopeSummary};
12
13#[derive(Debug, Clone, Default)]
14pub struct OntologyRoutingDecision {
15 pub ontology_ids: Vec<String>,
16 pub context_namespaces: Vec<u64>,
17 pub matched_terms: Vec<String>,
18 pub routing_brief: String,
19}
20
21pub fn route_prompt_to_ontologies(env: &ChatEnvironment, prompt: &str) -> OntologyRoutingDecision {
23 route_prompt_with_focus(env, prompt, &[])
24}
25
26pub fn route_prompt_with_focus(
30 env: &ChatEnvironment,
31 prompt: &str,
32 focus_terms: &[String],
33) -> OntologyRoutingDecision {
34 route_prompt_with_focus_and_allowlist(env, prompt, focus_terms, &[])
35}
36
37pub fn route_prompt_with_focus_and_allowlist(
41 env: &ChatEnvironment,
42 prompt: &str,
43 focus_terms: &[String],
44 allowed_ontology_ids: &[String],
45) -> OntologyRoutingDecision {
46 let allowed = |id: &str| {
47 allowed_ontology_ids.is_empty()
48 || allowed_ontology_ids
49 .iter()
50 .any(|configured| configured == id)
51 };
52 let in_scope: Vec<&OntologyScopeSummary> = env
53 .ontology_summaries
54 .iter()
55 .filter(|summary| allowed(&summary.id))
56 .collect();
57 if in_scope.is_empty() {
58 return OntologyRoutingDecision::default();
59 }
60
61 let mut keywords = extract_keywords(prompt);
62 for term in focus_terms {
63 for keyword in extract_keywords(term) {
64 if !keywords.iter().any(|known| known == &keyword) {
65 keywords.push(keyword);
66 }
67 }
68 }
69 keywords.truncate(32);
70 let mut scored: Vec<(i32, &OntologyScopeSummary)> = in_scope
71 .iter()
72 .copied()
73 .map(|summary| (score_summary(summary, &keywords), summary))
74 .collect();
75
76 scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.id.cmp(&b.1.id)));
77
78 let mut ontology_ids = Vec::new();
79 let mut context_namespaces = Vec::new();
80 let mut matched_terms = Vec::new();
81 let mut seen_terms = HashSet::new();
82
83 for (score, summary) in &scored {
84 if *score <= 0 {
85 break;
86 }
87 ontology_ids.push(summary.id.clone());
88 extend_namespaces(&mut context_namespaces, summary);
89 for keyword in &keywords {
90 if summary_matches_keyword(summary, keyword) && seen_terms.insert(keyword.clone()) {
91 matched_terms.push(keyword.clone());
92 }
93 }
94 }
95
96 if ontology_ids.is_empty() {
97 for summary in &in_scope {
98 ontology_ids.push(summary.id.clone());
99 extend_namespaces(&mut context_namespaces, summary);
100 }
101 }
102
103 if ontology_ids.iter().all(|id| !id.contains("wordnet")) {
104 if let Some(wordnet) = in_scope.iter().copied().find(|o| o.id.contains("wordnet")) {
105 ontology_ids.push(wordnet.id.clone());
106 extend_namespaces(&mut context_namespaces, wordnet);
107 }
108 }
109
110 context_namespaces.sort_unstable();
111 context_namespaces.dedup();
112
113 let routing_brief = if ontology_ids.is_empty() {
114 "[Ontology routing: no installed ontologies selected]".to_string()
115 } else if matched_terms.is_empty() {
116 format!(
117 "[Ontology routing: {} selected for general grounding]",
118 ontology_ids.join(", ")
119 )
120 } else {
121 format!(
122 "[Ontology routing: {} selected from prompt terms: {}]",
123 ontology_ids.join(", "),
124 matched_terms.join(", ")
125 )
126 };
127
128 OntologyRoutingDecision {
129 ontology_ids,
130 context_namespaces,
131 matched_terms,
132 routing_brief,
133 }
134}
135
136fn extract_keywords(prompt: &str) -> Vec<String> {
137 prompt
138 .split(|c: char| !c.is_alphanumeric())
139 .filter(|w| w.len() >= 3)
140 .map(|w| w.to_ascii_lowercase())
141 .take(24)
142 .collect()
143}
144
145fn score_summary(summary: &OntologyScopeSummary, keywords: &[String]) -> i32 {
146 if keywords.is_empty() {
147 return 1;
148 }
149
150 let mut score = 0;
151 for keyword in keywords {
152 if summary_matches_keyword(summary, keyword) {
153 score += 4;
154 }
155 score += domain_bonus(summary, keyword);
156 }
157 if summary.id.contains("wordnet") {
158 score += 1;
159 }
160 score
161}
162
163fn summary_matches_keyword(summary: &OntologyScopeSummary, keyword: &str) -> bool {
164 contains_term(&summary.id, keyword)
165 || contains_term(&summary.name, keyword)
166 || summary
167 .domain
168 .as_deref()
169 .map(|d| contains_term(d, keyword))
170 .unwrap_or(false)
171 || summary
172 .tags
173 .iter()
174 .flatten()
175 .any(|tag| contains_term(tag, keyword))
176}
177
178fn contains_term(text: &str, keyword: &str) -> bool {
179 let lower = text.to_ascii_lowercase();
180 lower.contains(keyword)
181}
182
183fn domain_bonus(summary: &OntologyScopeSummary, keyword: &str) -> i32 {
184 let health = [
185 "health", "medical", "medicine", "clinical", "patient", "drug", "fhir", "loinc", "snomed",
186 "anatomy", "body", "heart", "fever", "symptom",
187 ];
188 let legal = [
189 "legal",
190 "law",
191 "contract",
192 "rights",
193 "guardian",
194 "guardianship",
195 "consent",
196 "policy",
197 "agreement",
198 "duty",
199 ];
200 let civic = ["commons", "community", "governance", "public", "care"];
201
202 let domain = summary
203 .domain
204 .as_deref()
205 .unwrap_or_default()
206 .to_ascii_lowercase();
207 let tags = summary
208 .tags
209 .as_ref()
210 .map(|v| v.join(" ").to_ascii_lowercase())
211 .unwrap_or_default();
212 let haystack = format!("{} {}", domain, tags);
213
214 if health.contains(&keyword) && haystack.contains("health") {
215 return 6;
216 }
217 if legal.contains(&keyword)
218 && (haystack.contains("legal") || haystack.contains("rights") || haystack.contains("guard"))
219 {
220 return 6;
221 }
222 if civic.contains(&keyword) && haystack.contains("commons") {
223 return 4;
224 }
225 0
226}
227
228fn extend_namespaces(out: &mut Vec<u64>, summary: &OntologyScopeSummary) {
229 out.push(q_hash(&summary.id));
230 out.push(q_hash(&format!("ont:{}", summary.id)));
231 out.push(q_hash(&summary.name));
232 if let Some(domain) = &summary.domain {
233 out.push(q_hash(domain));
234 out.push(q_hash(&format!("domain:{domain}")));
235 }
236 if let Some(tags) = &summary.tags {
237 for tag in tags.iter().take(4) {
238 out.push(q_hash(tag));
239 }
240 }
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246 use crate::chat_session::{ChatEnvironment, OntologyScopeSummary};
247
248 fn env() -> ChatEnvironment {
249 ChatEnvironment {
250 session_id: "s".into(),
251 active_model_profile_id: 0,
252 ontology_ids: vec!["snomed".into(), "legal-commons".into(), "wordnet".into()],
253 prior_session_ids: vec![],
254 graph_scope_hashes: vec![],
255 lexicon_prefixes: vec![],
256 capability_briefing: String::new(),
257 model_id: None,
258 model_modality: "text".into(),
259 context_window: 4096,
260 engine_capabilities: vec![],
261 installed_qapps: vec![],
262 ontology_summaries: vec![
263 OntologyScopeSummary {
264 id: "snomed".into(),
265 name: "SNOMED Clinical Terms".into(),
266 quin_count: 10,
267 q42_path: "snomed.q42".into(),
268 domain: Some("health".into()),
269 tags: Some(vec!["medical".into(), "clinical".into()]),
270 source: None,
271 },
272 OntologyScopeSummary {
273 id: "legal-commons".into(),
274 name: "Legal Commons".into(),
275 quin_count: 10,
276 q42_path: "legal.q42".into(),
277 domain: Some("legal".into()),
278 tags: Some(vec!["contract".into(), "rights".into()]),
279 source: None,
280 },
281 OntologyScopeSummary {
282 id: "wordnet".into(),
283 name: "WordNet".into(),
284 quin_count: 10,
285 q42_path: "wordnet.q42".into(),
286 domain: Some("lexical".into()),
287 tags: Some(vec!["language".into()]),
288 source: None,
289 },
290 ],
291 daemon_reachable: false,
292 session_kind: crate::chat_session::SessionKind::Solo,
293 participants: vec![],
294 graph_mutation: false,
295 axiom_bounds: crate::context_binding::AxiomBounds::default(),
296 }
297 }
298
299 #[test]
300 fn routes_medical_prompt_to_health_ontology() {
301 let decision = route_prompt_to_ontologies(&env(), "What does this patient fever indicate?");
302 assert!(decision.ontology_ids.iter().any(|id| id == "snomed"));
303 assert!(decision.context_namespaces.contains(&q_hash("health")));
304 }
305
306 #[test]
307 fn routes_guardianship_prompt_to_legal_ontology() {
308 let decision =
309 route_prompt_to_ontologies(&env(), "Draft a guardianship consent agreement.");
310 assert!(decision.ontology_ids.iter().any(|id| id == "legal-commons"));
311 assert!(decision.context_namespaces.contains(&q_hash("legal")));
312 }
313
314 #[test]
315 fn semantic_focus_can_narrow_routing_without_prompt_keywords() {
316 let decision = route_prompt_with_focus(
317 &env(),
318 "Please prepare a concise source note.",
319 &["clinical evidence".to_string(), "health".to_string()],
320 );
321 assert!(decision.ontology_ids.iter().any(|id| id == "snomed"));
322 assert!(decision.matched_terms.iter().any(|term| term == "clinical"));
323 }
324
325 #[test]
326 fn agent_allowlist_intersects_the_session_scope() {
327 let decision = route_prompt_with_focus_and_allowlist(
328 &env(),
329 "What does this patient fever indicate?",
330 &[],
331 &["legal-commons".to_string()],
332 );
333 assert_eq!(decision.ontology_ids, vec!["legal-commons".to_string()]);
334 assert!(!decision.context_namespaces.contains(&q_hash("health")));
335 }
336
337 #[test]
338 fn routing_keeps_all_matching_ontologies_and_namespaces() {
339 let mut env = env();
340 for index in 0..5 {
341 env.ontology_summaries.push(OntologyScopeSummary {
342 id: format!("legal-{index}"),
343 name: format!("Legal Domain {index}"),
344 quin_count: 10,
345 q42_path: format!("legal-{index}.q42"),
346 domain: Some("legal".into()),
347 tags: Some(vec!["agreement".into()]),
348 source: None,
349 });
350 }
351
352 let decision = route_prompt_to_ontologies(&env, "Draft a legal agreement.");
353 for index in 0..5 {
354 assert!(decision.ontology_ids.contains(&format!("legal-{index}")));
355 }
356 assert!(decision.context_namespaces.len() > 16);
357 }
358
359 #[test]
360 fn routing_keeps_full_scope_when_no_ontology_matches() {
361 let mut env = env();
362 env.ontology_summaries
363 .retain(|summary| !summary.id.contains("wordnet"));
364
365 let decision = route_prompt_to_ontologies(&env, "Investigate xylophones.");
366 assert_eq!(decision.ontology_ids.len(), env.ontology_summaries.len());
367 for summary in &env.ontology_summaries {
368 assert!(decision.ontology_ids.contains(&summary.id));
369 }
370 }
371}