Skip to main content

qualia_client_core/
chat_retrieval.rs

1//! Scoped graph retrieval for chat — local `.q42` scan + optional daemon query.
2
3use std::collections::HashSet;
4use std::path::Path;
5
6use qualia_core_db::{q42_reader::read_q42_quins, q_hash, NQuin};
7use serde::{Deserialize, Serialize};
8
9use crate::chat_session::ChatEnvironment;
10use crate::resource_import;
11
12const MAX_RETRIEVAL_TRIPLES: usize = 48;
13const OBJECT_HASH_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct GraphCitation {
17    pub ontology_id: String,
18    pub subject_hash: String,
19    pub predicate_hash: String,
20    pub object_hash: String,
21    pub label: String,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct RetrievalBundle {
26    pub triple_count: usize,
27    pub citations: Vec<GraphCitation>,
28    pub provenance_hashes: Vec<u64>,
29    pub context_block: String,
30    pub daemon_queried: bool,
31    pub daemon_match_count: u64,
32}
33
34/// Retrieves graph context for a prompt.
35pub fn retrieve_graph_context(
36    storage: &Path,
37    env: &ChatEnvironment,
38    user_prompt: &str,
39    routed_ontology_ids: &[String],
40) -> RetrievalBundle {
41    let keywords = extract_keywords(user_prompt);
42    let mut citations = Vec::new();
43    let mut provenance_hashes = Vec::new();
44    let mut seen: HashSet<(u64, u64, u64)> = HashSet::new();
45
46    let ontology_ids = if routed_ontology_ids.is_empty() {
47        &env.ontology_ids
48    } else {
49        routed_ontology_ids
50    };
51
52    for ont_id in ontology_ids {
53        let q42_path = resource_import::index_dir(storage).join(format!("{ont_id}.q42"));
54        if !q42_path.is_file() {
55            continue;
56        }
57        let Ok(quins) = read_q42_quins(&q42_path) else {
58            continue;
59        };
60
61        for quin in &quins {
62            if citations.len() >= MAX_RETRIEVAL_TRIPLES {
63                break;
64            }
65            if !matches_keywords(quin, &keywords) && !keywords.is_empty() {
66                continue;
67            }
68            let key = (quin.subject, quin.predicate, quin.object);
69            if !seen.insert(key) {
70                continue;
71            }
72            let citation_hash = quin.subject ^ quin.predicate ^ quin.object;
73            provenance_hashes.push(citation_hash);
74            citations.push(GraphCitation {
75                ontology_id: ont_id.clone(),
76                subject_hash: format!("0x{:016x}", quin.subject),
77                predicate_hash: format!("0x{:016x}", quin.predicate),
78                object_hash: format!("0x{:016x}", quin.object & OBJECT_HASH_MASK),
79                label: format!(
80                    "{} → {} → {}",
81                    short_hash(quin.subject),
82                    short_hash(quin.predicate),
83                    short_hash(quin.object)
84                ),
85            });
86        }
87    }
88
89    let (daemon_queried, daemon_match_count, daemon_extra) =
90        query_daemon_for_prompt(user_prompt, &keywords);
91
92    if daemon_queried && daemon_match_count > 0 {
93        provenance_hashes.push(q_hash("qualia:daemon_graph"));
94        if citations.is_empty() && !daemon_extra.is_empty() {
95            citations.push(GraphCitation {
96                ontology_id: "daemon".to_string(),
97                subject_hash: "live".to_string(),
98                predicate_hash: "graph".to_string(),
99                object_hash: format!("{daemon_match_count}"),
100                label: daemon_extra,
101            });
102        }
103    }
104
105    provenance_hashes.sort_unstable();
106    provenance_hashes.dedup();
107
108    let context_block = format_retrieval_block(&citations, daemon_match_count);
109
110    RetrievalBundle {
111        triple_count: citations.len(),
112        citations,
113        provenance_hashes,
114        context_block,
115        daemon_queried,
116        daemon_match_count,
117    }
118}
119
120fn extract_keywords(prompt: &str) -> Vec<String> {
121    prompt
122        .split(|c: char| !c.is_alphanumeric())
123        .filter(|w| w.len() >= 4)
124        .map(|w| w.to_lowercase())
125        .take(16)
126        .collect()
127}
128
129fn matches_keywords(quin: &NQuin, keywords: &[String]) -> bool {
130    if keywords.is_empty() {
131        return true;
132    }
133    let sub = format!("{:016x}", quin.subject);
134    let pred = format!("{:016x}", quin.predicate);
135    let obj = format!("{:016x}", quin.object);
136    keywords
137        .iter()
138        .any(|kw| sub.contains(kw) || pred.contains(kw) || obj.contains(kw))
139}
140
141fn short_hash(h: u64) -> String {
142    format!("{:08x}", (h & 0xFFFF_FFFF) as u32)
143}
144
145fn format_retrieval_block(citations: &[GraphCitation], daemon_matches: u64) -> String {
146    if citations.is_empty() && daemon_matches == 0 {
147        return "[Graph retrieval: no scoped triples matched — rely on environment capabilities only]"
148            .to_string();
149    }
150
151    let mut lines = vec![format!(
152        "[Graph retrieval: {} scoped citation(s), daemon matches: {daemon_matches}]",
153        citations.len()
154    )];
155    for (i, c) in citations.iter().take(24).enumerate() {
156        lines.push(format!("  {}. [{}] {}", i + 1, c.ontology_id, c.label));
157    }
158    lines.join("\n")
159}
160
161fn query_daemon_for_prompt(prompt: &str, keywords: &[String]) -> (bool, u64, String) {
162    if crate::daemon_status() != "running" {
163        return (false, 0, String::new());
164    }
165    let port = crate::get_active_daemon_port();
166    if port == 0 {
167        return (false, 0, String::new());
168    }
169
170    let client = match reqwest::blocking::Client::builder()
171        .timeout(std::time::Duration::from_secs(4))
172        .build()
173    {
174        Ok(c) => c,
175        Err(_) => return (false, 0, String::new()),
176    };
177
178    let token = crate::issue_qapp_session_token("Chat").unwrap_or_default();
179    let url = format!("http://127.0.0.1:{port}/query");
180
181    let query = if keywords.is_empty() {
182        "?subject ?predicate ?object .".to_string()
183    } else {
184        format!("# Scoped chat retrieval for: {}", keywords.join(", "))
185    };
186
187    let response = client
188        .post(&url)
189        .header("X-Qualia-Token", token)
190        .header("Accept", "application/ld+json")
191        .json(&serde_json::json!({
192            "query": query,
193            "format": "json-ld",
194            "prompt_hint": prompt.chars().take(120).collect::<String>()
195        }))
196        .send();
197
198    let Ok(resp) = response else {
199        return (true, 0, String::new());
200    };
201    if !resp.status().is_success() {
202        return (true, 0, String::new());
203    }
204
205    let Ok(body) = resp.json::<serde_json::Value>() else {
206        return (true, 0, String::new());
207    };
208
209    let match_count = body
210        .get("match_count")
211        .and_then(|v| v.as_u64())
212        .unwrap_or(0);
213
214    let summary = if match_count > 0 {
215        format!("Daemon graph returned {match_count} quin(s) for scoped query")
216    } else {
217        String::new()
218    };
219
220    (true, match_count, summary)
221}