Skip to main content

qualia_client_core/
chat_ontology.rs

1//! Chat discourse ontology — branch types grounded in WordNet when `wordnet.q42` is present.
2
3use std::path::{Path, PathBuf};
4use std::sync::OnceLock;
5
6use qualia_core_db::q_hash;
7use serde::{Deserialize, Serialize};
8
9use crate::resource_import;
10
11static WORDNET_LEX: OnceLock<Option<qualia_core_db::q42_lex::Q42Lexicon>> = OnceLock::new();
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct ChatBranchType {
15    pub id: String,
16    pub label: String,
17    pub emoji: String,
18    pub description: String,
19    pub wordnet_lemmas: Vec<String>,
20    pub keywords: Vec<String>,
21    #[serde(default)]
22    pub wordnet_grounding_hash: Option<String>,
23    #[serde(default)]
24    pub wordnet_gloss: Option<String>,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct BranchClassification {
29    pub branch_type_id: String,
30    pub label: String,
31    pub emoji: String,
32    pub confidence: f32,
33    pub wordnet_grounding_hash: Option<String>,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct ChatReaction {
38    pub message_lamport: u64,
39    pub emoji: String,
40    pub author_did: String,
41    pub author_name: Option<String>,
42    pub created_at: u64,
43}
44
45const DISCOURSE_TYPES: &[(&str, &str, &str, &str, &[&str], &[&str])] = &[
46    (
47        "comment",
48        "Comment",
49        "💬",
50        "General remark or observation",
51        &["comment", "remark", "note", "statement"],
52        &["note", "fwiw", "interesting"],
53    ),
54    (
55        "correction",
56        "Correction",
57        "✏️",
58        "Fixes or amends prior content",
59        &["correction", "amendment", "rectification"],
60        &[
61            "actually",
62            "incorrect",
63            "mistake",
64            "fix",
65            "wrong",
66            "should be",
67        ],
68    ),
69    (
70        "inquiry",
71        "Inquiry",
72        "❓",
73        "Question or request for information",
74        &["question", "inquiry", "query"],
75        &[
76            "?",
77            "how",
78            "why",
79            "what",
80            "when",
81            "where",
82            "could you",
83            "can you",
84        ],
85    ),
86    (
87        "agreement",
88        "Agreement",
89        "✅",
90        "Endorses or confirms prior content",
91        &["agreement", "assent", "concurrence"],
92        &["yes", "agree", "correct", "exactly", "right", "+1"],
93    ),
94    (
95        "objection",
96        "Objection",
97        "⚠️",
98        "Disagrees or challenges prior content",
99        &["objection", "disagreement", "dissent"],
100        &["disagree", "no", "however", "but", "not quite", "object"],
101    ),
102    (
103        "clarification",
104        "Clarification",
105        "🔍",
106        "Explains or disambiguates",
107        &["clarification", "explanation", "elucidation"],
108        &["clarify", "mean", "to be clear", "in other words", "i.e."],
109    ),
110    (
111        "evidence",
112        "Evidence",
113        "📎",
114        "Cites sources or supporting facts",
115        &["evidence", "proof", "citation"],
116        &[
117            "source",
118            "cite",
119            "according to",
120            "study",
121            "data shows",
122            "provenance",
123        ],
124    ),
125    (
126        "suggestion",
127        "Suggestion",
128        "💡",
129        "Proposes an idea or next step",
130        &["suggestion", "proposal", "recommendation"],
131        &["suggest", "could", "might", "recommend", "try", "idea"],
132    ),
133    (
134        "summary",
135        "Summary",
136        "📋",
137        "Synthesizes or restates thread content",
138        &["summary", "synopsis", "recap"],
139        &["summary", "in short", "tl;dr", "to summarize", "overall"],
140    ),
141    (
142        "humor",
143        "Humor",
144        "😄",
145        "Light or playful response",
146        &["humor", "joke", "wit"],
147        &["lol", "haha", "😄", "😂", "jk"],
148    ),
149];
150
151/// Local wordnet-dir.
152pub fn local_wordnet_dir() -> PathBuf {
153    if let Ok(dir) = std::env::var("QUALIA_WORDNET_DIR") {
154        let trimmed = dir.trim();
155        if !trimmed.is_empty() {
156            return PathBuf::from(trimmed);
157        }
158    }
159    PathBuf::from("Local_LIbraries/wordnet")
160}
161
162/// Resolves a WordNet entry to q42.
163pub fn resolve_wordnet_q42(storage: &Path) -> Option<PathBuf> {
164    let index = resource_import::index_dir(storage);
165    let local = local_wordnet_dir();
166    let candidates = [
167        index.join("wordnet.q42"),
168        index.join("princeton.q42"),
169        index.join("wordnet-rdf.q42"),
170        index.join("english-wordnet.q42"),
171        local.join("wordnet.q42"),
172        local.join("princeton.q42"),
173        PathBuf::from("docs/data/wordnet/princeton.q42"),
174        PathBuf::from("docs/playground/wordnet.q42"),
175        PathBuf::from("wordnet.q42"),
176    ];
177    candidates.into_iter().find(|p| p.is_file())
178}
179
180/// Resolves a WordNet lex entry.
181pub fn resolve_wordnet_lex(q42_path: &Path) -> Option<PathBuf> {
182    if qualia_core_db::q42_volume::is_unified_volume(q42_path).ok() == Some(true) {
183        return Some(q42_path.to_path_buf());
184    }
185    let lex = q42_path.with_extension("q42.lex");
186    if lex.is_file() {
187        return Some(lex);
188    }
189    let alt = PathBuf::from(format!("{}.lex", q42_path.display()));
190    if alt.is_file() {
191        return Some(alt);
192    }
193    let sibling = q42_path.with_file_name(format!(
194        "{}.q42.lex",
195        q42_path.file_stem()?.to_string_lossy()
196    ));
197    if sibling.is_file() {
198        return Some(sibling);
199    }
200    None
201}
202
203fn wordnet_lexicon() -> Option<&'static qualia_core_db::q42_lex::Q42Lexicon> {
204    WORDNET_LEX
205        .get_or_init(|| {
206            let state = crate::state::APP_STATE.get()?;
207            let storage = state.config.lock().ok()?.storage_path.clone();
208            let q42 = resolve_wordnet_q42(Path::new(&storage))?;
209            qualia_core_db::q42_lex::Q42Lexicon::load_for_q42(&q42)
210                .ok()
211                .or_else(|| {
212                    resolve_wordnet_lex(&q42).and_then(|lex_path| {
213                        qualia_core_db::q42_lex::Q42Lexicon::load(&lex_path).ok()
214                    })
215                })
216        })
217        .as_ref()
218}
219
220/// `true` when WordNet data is available.
221pub fn wordnet_available(storage: &Path) -> bool {
222    resolve_wordnet_q42(storage).is_some()
223}
224
225/// Lists branch types.
226pub fn list_branch_types(storage: &Path) -> Vec<ChatBranchType> {
227    let lex = wordnet_lexicon();
228    DISCOURSE_TYPES
229        .iter()
230        .map(|(id, label, emoji, desc, lemmas, keywords)| {
231            let mut branch = ChatBranchType {
232                id: (*id).to_string(),
233                label: (*label).to_string(),
234                emoji: (*emoji).to_string(),
235                description: (*desc).to_string(),
236                wordnet_lemmas: lemmas.iter().map(|s| (*s).to_string()).collect(),
237                keywords: keywords.iter().map(|s| (*s).to_string()).collect(),
238                wordnet_grounding_hash: None,
239                wordnet_gloss: None,
240            };
241            if let Some(lex) = lex {
242                for lemma in *lemmas {
243                    if let Some(hash) = lex.find_literal(lemma) {
244                        branch.wordnet_grounding_hash = Some(format!("0x{hash:016x}"));
245                        branch.wordnet_gloss = lex.lookup(hash).map(|s| s.to_string());
246                        break;
247                    }
248                }
249            }
250            let _ = storage;
251            branch
252        })
253        .collect()
254}
255
256/// Classifies a branch.
257pub fn classify_branch(
258    storage: &Path,
259    anchor_text: &str,
260    reply_text: &str,
261) -> BranchClassification {
262    let types = list_branch_types(storage);
263    let combined = format!("{anchor_text}\n{reply_text}").to_lowercase();
264    let lex = wordnet_lexicon();
265
266    let mut best_id = "comment";
267    let mut best_score = 0f32;
268
269    for t in &types {
270        let mut score = 0f32;
271        for kw in &t.keywords {
272            if combined.contains(&kw.to_lowercase()) {
273                score += 1.5;
274            }
275        }
276        for lemma in &t.wordnet_lemmas {
277            if combined.contains(lemma) {
278                score += 1.0;
279            }
280            if let Some(lex) = lex {
281                for (_, gloss) in lex.search_contains(lemma, 3) {
282                    if combined.contains(&gloss.to_lowercase()) {
283                        score += 0.5;
284                    }
285                }
286            }
287        }
288        if score > best_score {
289            best_score = score;
290            best_id = &t.id;
291        }
292    }
293
294    let chosen = types
295        .iter()
296        .find(|t| t.id == best_id)
297        .or_else(|| types.first());
298
299    if let Some(t) = chosen {
300        BranchClassification {
301            branch_type_id: t.id.clone(),
302            label: t.label.clone(),
303            emoji: t.emoji.clone(),
304            confidence: (best_score / 3.0).min(1.0),
305            wordnet_grounding_hash: t.wordnet_grounding_hash.clone(),
306        }
307    } else {
308        BranchClassification {
309            branch_type_id: "comment".to_string(),
310            label: "Comment".to_string(),
311            emoji: "💬".to_string(),
312            confidence: 0.1,
313            wordnet_grounding_hash: None,
314        }
315    }
316}
317
318/// Builds chat-ontology-briefing.
319pub fn build_chat_ontology_briefing(storage: &Path) -> String {
320    let q42 = resolve_wordnet_q42(storage);
321    let types = list_branch_types(storage);
322    let mut lines = vec!["[Chat discourse ontology]".to_string()];
323    if let Some(path) = q42 {
324        lines.push(format!(
325            "wordnet_grounding: {} (lexicon-backed branch labels)",
326            path.display()
327        ));
328    } else {
329        lines.push(
330            "wordnet_grounding: not installed — place artefacts under Local_LIbraries/wordnet/, import via Ontology Hub, or run scripts/fetch_wordnet.sh"
331                .to_string(),
332        );
333    }
334    lines.push("branch_types:".to_string());
335    for t in types {
336        let wn = t.wordnet_grounding_hash.as_deref().unwrap_or("builtin");
337        lines.push(format!(
338            "  - {} {} ({}) wordnet={}",
339            t.emoji, t.label, t.id, wn
340        ));
341    }
342    lines.push(
343        "instructions: Label each graph branch with the best-matching branch_type when replying to a fragment."
344            .to_string(),
345    );
346    lines.join("\n")
347}
348
349fn reactions_path(storage_root: &Path, session_id: &str) -> PathBuf {
350    storage_root
351        .join("Chats")
352        .join(session_id)
353        .join("reactions.jsonl")
354}
355
356fn unix_now() -> u64 {
357    std::time::SystemTime::now()
358        .duration_since(std::time::UNIX_EPOCH)
359        .unwrap_or_default()
360        .as_secs()
361}
362
363/// Adds reaction.
364pub fn add_reaction(
365    storage_root: &Path,
366    session_id: &str,
367    message_lamport: u64,
368    emoji: &str,
369) -> Result<Vec<ChatReaction>, String> {
370    if emoji.is_empty() {
371        return Err("Emoji required".to_string());
372    }
373    // Basic validation: allow printable unicode including emoji sequences
374    if emoji.chars().count() > 8 {
375        return Err("Emoji reaction too long".to_string());
376    }
377
378    let profile = crate::user_profile::load_profile();
379    let path = reactions_path(storage_root, session_id);
380    if let Some(parent) = path.parent() {
381        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
382    }
383
384    let mut reactions = list_reactions(storage_root, session_id)?;
385    if reactions.iter().any(|r| {
386        r.message_lamport == message_lamport
387            && r.author_did == profile.public_did
388            && r.emoji == emoji
389    }) {
390        return Ok(reactions);
391    }
392
393    let reaction = ChatReaction {
394        message_lamport,
395        emoji: emoji.to_string(),
396        author_did: profile.public_did.clone(),
397        author_name: profile
398            .sharing
399            .share_display_name
400            .then(|| profile.display_name.clone()),
401        created_at: unix_now(),
402    };
403    reactions.push(reaction);
404
405    let mut file = std::fs::OpenOptions::new()
406        .create(true)
407        .write(true)
408        .truncate(true)
409        .open(&path)
410        .map_err(|e| e.to_string())?;
411    for r in &reactions {
412        use std::io::Write;
413        writeln!(
414            file,
415            "{}",
416            serde_json::to_string(r).map_err(|e| e.to_string())?
417        )
418        .map_err(|e| e.to_string())?;
419    }
420
421    // WAL quin: chat:hasReaction
422    let wal_path = storage_root.join("Chats").join(session_id).join("chat.wal");
423    if wal_path.is_file() {
424        let subject = q_hash(&format!("chat:session:{session_id}"));
425        let predicate = q_hash("chat:hasReaction");
426        let object = q_hash(&format!("react:{message_lamport}:{emoji}")) & 0x0FFF_FFFF_FFFF_FFFF;
427        let context = q_hash(&profile.public_did);
428        let metadata = (message_lamport & 0x1FFF_FFFF) << 32;
429        let parity = subject ^ predicate ^ object ^ context ^ metadata;
430        let quin = qualia_core_db::NQuin {
431            subject,
432            predicate,
433            object,
434            context,
435            metadata,
436            parity,
437        };
438        if let Ok(mut wal) = qualia_core_db::wal::WriteAheadLog::open(&wal_path) {
439            let _ = wal.append_mutation(&quin);
440        }
441    }
442
443    Ok(reactions)
444}
445
446/// Toggles reaction.
447pub fn toggle_reaction(
448    storage_root: &Path,
449    session_id: &str,
450    message_lamport: u64,
451    emoji: &str,
452) -> Result<Vec<ChatReaction>, String> {
453    let profile = crate::user_profile::load_profile();
454    let existing: Vec<_> = list_reactions_for_message(storage_root, session_id, message_lamport)?;
455    let already = existing
456        .iter()
457        .any(|r| r.author_did == profile.public_did && r.emoji == emoji);
458    if already {
459        remove_reaction(storage_root, session_id, message_lamport, emoji)
460    } else {
461        add_reaction(storage_root, session_id, message_lamport, emoji)
462    }
463}
464
465fn remove_reaction(
466    storage_root: &Path,
467    session_id: &str,
468    message_lamport: u64,
469    emoji: &str,
470) -> Result<Vec<ChatReaction>, String> {
471    let profile = crate::user_profile::load_profile();
472    let mut reactions = list_reactions(storage_root, session_id)?;
473    reactions.retain(|r| {
474        !(r.message_lamport == message_lamport
475            && r.author_did == profile.public_did
476            && r.emoji == emoji)
477    });
478    let path = reactions_path(storage_root, session_id);
479    let mut file = std::fs::OpenOptions::new()
480        .create(true)
481        .write(true)
482        .truncate(true)
483        .open(&path)
484        .map_err(|e| e.to_string())?;
485    for r in &reactions {
486        use std::io::Write;
487        writeln!(
488            file,
489            "{}",
490            serde_json::to_string(r).map_err(|e| e.to_string())?
491        )
492        .map_err(|e| e.to_string())?;
493    }
494    Ok(reactions)
495}
496
497/// Lists reactions.
498pub fn list_reactions(storage_root: &Path, session_id: &str) -> Result<Vec<ChatReaction>, String> {
499    let path = reactions_path(storage_root, session_id);
500    if !path.is_file() {
501        return Ok(Vec::new());
502    }
503    let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
504    let mut out = Vec::new();
505    for line in text.lines() {
506        if line.trim().is_empty() {
507            continue;
508        }
509        if let Ok(r) = serde_json::from_str::<ChatReaction>(line) {
510            out.push(r);
511        }
512    }
513    Ok(out)
514}
515
516/// Lists reactions for a message.
517pub fn list_reactions_for_message(
518    storage_root: &Path,
519    session_id: &str,
520    message_lamport: u64,
521) -> Result<Vec<ChatReaction>, String> {
522    Ok(list_reactions(storage_root, session_id)?
523        .into_iter()
524        .filter(|r| r.message_lamport == message_lamport)
525        .collect())
526}