1use std::collections::HashMap;
6use std::fs;
7use std::path::Path;
8
9use serde::{Deserialize, Serialize};
10
11use qualia_core_db::{
12 profiles::CapabilityProfile,
13 q_hash,
14 resource_catalog::{OntologyResource, ResourceCatalog},
15 NQuin, CAPABILITY_DESCRIPTORS,
16};
17
18use crate::chat_session::{ChatEnvironment, OntologyScopeSummary};
19use crate::model_lifecycle;
20use crate::resource_import;
21
22const MAX_LEXICON_PER_ONTOLOGY: usize = 256;
23const MAX_MANIFEST_QUINS: usize = 16;
24const OBJECT_HASH_MASK: u64 = 0x0FFF_FFFF_FFFF_FFFF;
25
26#[derive(Debug)]
27pub enum BindError {
28 Io(std::io::Error),
29 Json(serde_json::Error),
30 NotFound(String),
31 Compile(String),
32}
33
34impl std::fmt::Display for BindError {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 match self {
37 BindError::Io(e) => write!(f, "IO error: {e}"),
38 BindError::Json(e) => write!(f, "JSON error: {e}"),
39 BindError::NotFound(id) => write!(f, "Not found: {id}"),
40 BindError::Compile(msg) => write!(f, "Compile error: {msg}"),
41 }
42 }
43}
44
45impl From<std::io::Error> for BindError {
46 fn from(e: std::io::Error) -> Self {
47 BindError::Io(e)
48 }
49}
50
51impl From<serde_json::Error> for BindError {
52 fn from(e: serde_json::Error) -> Self {
53 BindError::Json(e)
54 }
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59pub struct AxiomBounds {
60 pub start_year: u16,
61 pub end_year: u16,
62 pub spatial_context_hash: u64,
64 #[serde(default)]
65 pub spatial_context_label: String,
66}
67
68impl Default for AxiomBounds {
69 fn default() -> Self {
70 Self {
71 start_year: 1800,
72 end_year: 2100,
73 spatial_context_hash: 0,
74 spatial_context_label: String::new(),
75 }
76 }
77}
78
79impl AxiomBounds {
80 pub fn label(&self) -> String {
82 format!("[{}–{}]", self.start_year, self.end_year)
83 }
84
85 pub fn with_spatial_label(mut self, label: &str) -> Self {
87 self.spatial_context_label = label.trim().to_string();
88 self.spatial_context_hash = if self.spatial_context_label.is_empty() {
89 0
90 } else {
91 q_hash(&self.spatial_context_label)
92 };
93 self
94 }
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct ChatEnvironmentConfig {
99 pub session_id: String,
100 pub ontology_ids: Vec<String>,
101 pub prior_session_ids: Vec<String>,
102 #[serde(default)]
103 pub session_kind: crate::chat_session::SessionKind,
104 #[serde(default)]
105 pub participants: Vec<crate::chat_session::ChatParticipant>,
106 #[serde(default)]
107 pub graph_mutation: bool,
108 #[serde(default)]
109 pub axiom_bounds: AxiomBounds,
110}
111
112#[derive(Debug, Clone, Deserialize)]
113struct OntologyMetaSidecar {
114 ontology_id: String,
115 quin_count: u64,
116 #[allow(dead_code)]
117 q42_path: String,
118}
119
120#[derive(Debug, Clone)]
122pub struct InferenceContextPacket {
123 pub augmented_prompt: String,
124 pub graph_context_json: String,
125 pub graph_scope_hashes: Vec<u64>,
126 pub context_namespaces: Vec<u64>,
127 pub routed_ontology_ids: Vec<String>,
128 pub routing_brief: String,
129 pub active_profile: Option<CapabilityProfile>,
130 pub model_path: String,
131 pub axiom_bounds: AxiomBounds,
132}
133
134pub fn compile_chat_environment(
136 storage: &Path,
137 catalog: &ResourceCatalog,
138 config: &ChatEnvironmentConfig,
139) -> Result<ChatEnvironment, BindError> {
140 let active = load_active_model_record();
141 let profile_id = active.as_ref().map(|r| r.profile_id).unwrap_or(0);
142
143 let installed = list_installed_ontology_ids(storage);
144 let mut ontology_ids: Vec<String> = if config.ontology_ids.is_empty() {
145 installed.clone()
146 } else {
147 config
148 .ontology_ids
149 .iter()
150 .filter(|id| installed.contains(id))
151 .cloned()
152 .collect()
153 };
154
155 if crate::chat_ontology::wordnet_available(storage) {
156 for id in ["wordnet", "wordnet-rdf", "english-wordnet"] {
157 if installed.iter().any(|i| i == id) && !ontology_ids.contains(&id.to_string()) {
158 ontology_ids.push(id.to_string());
159 }
160 }
161 if ontology_ids.iter().all(|id| !id.contains("wordnet"))
162 && installed.iter().any(|i| i.starts_with("wordnet"))
163 {
164 if let Some(w) = installed.iter().find(|i| i.contains("wordnet")).cloned() {
165 ontology_ids.push(w);
166 }
167 }
168 }
169
170 let mut graph_scope_hashes = vec![q_hash(&format!("chat:session:{}", config.session_id))];
171 let mut lexicon_prefixes: Vec<u64> = Vec::new();
172 let mut ontology_summaries = Vec::new();
173
174 for ont_id in &ontology_ids {
175 graph_scope_hashes.push(q_hash(&format!("ont:{ont_id}")));
176 if let Some(summary) =
177 compile_ontology_scope(storage, catalog, ont_id, &mut lexicon_prefixes)?
178 {
179 ontology_summaries.push(summary);
180 }
181 }
182
183 for prior in &config.prior_session_ids {
184 graph_scope_hashes.push(q_hash(&format!("chat:session:{prior}")));
185 }
186
187 lexicon_prefixes.sort_unstable();
188 lexicon_prefixes.dedup();
189 if lexicon_prefixes.len() > MAX_LEXICON_PER_ONTOLOGY * 4 {
190 lexicon_prefixes.truncate(MAX_LEXICON_PER_ONTOLOGY * 4);
191 }
192
193 graph_scope_hashes.sort_unstable();
194 graph_scope_hashes.dedup();
195
196 let installed_qapps = list_qapp_names(storage);
197 let daemon_reachable = daemon_is_running();
198 let engine_capabilities: Vec<String> = CAPABILITY_DESCRIPTORS
199 .iter()
200 .map(|capability| capability.name.to_string())
201 .collect();
202
203 let model_id = active.as_ref().map(|r| r.model_id.clone());
204 let model_modality = active
205 .as_ref()
206 .map(|r| r.modality.clone())
207 .unwrap_or_else(|| "text".to_string());
208 let context_window = active.as_ref().map(|r| r.context_window).unwrap_or(4096);
209
210 let profile = crate::user_profile::load_profile();
211 let capability_briefing = build_capability_briefing(
212 storage,
213 &config.session_id,
214 config.session_kind,
215 &config.participants,
216 &profile,
217 active.as_ref(),
218 &ontology_summaries,
219 &installed_qapps,
220 &engine_capabilities,
221 daemon_reachable,
222 &config.prior_session_ids,
223 lexicon_prefixes.len(),
224 );
225
226 let env = ChatEnvironment {
227 session_id: config.session_id.clone(),
228 active_model_profile_id: profile_id,
229 ontology_ids,
230 prior_session_ids: config.prior_session_ids.clone(),
231 graph_scope_hashes: graph_scope_hashes.clone(),
232 lexicon_prefixes,
233 capability_briefing,
234 model_id,
235 model_modality,
236 context_window,
237 engine_capabilities,
238 installed_qapps,
239 ontology_summaries,
240 daemon_reachable,
241 session_kind: config.session_kind,
242 participants: config.participants.clone(),
243 graph_mutation: config.graph_mutation,
244 axiom_bounds: config.axiom_bounds.clone(),
245 };
246
247 write_environment_manifest_q42(storage, &config.session_id, &graph_scope_hashes)?;
248 Ok(env)
249}
250
251pub fn refresh_session_environment(
253 storage: &Path,
254 catalog: &ResourceCatalog,
255 session_id: &str,
256) -> Result<ChatEnvironment, BindError> {
257 let existing = crate::chat_session::load_session(storage, session_id).map_err(|e| match e {
258 crate::chat_session::ChatError::NotFound(id) => BindError::NotFound(id),
259 crate::chat_session::ChatError::Io(err) => BindError::Io(err),
260 crate::chat_session::ChatError::Json(err) => BindError::Json(err),
261 other => BindError::Compile(other.to_string()),
262 })?;
263
264 let config = ChatEnvironmentConfig {
265 session_id: session_id.to_string(),
266 ontology_ids: existing.environment.ontology_ids,
267 prior_session_ids: existing.environment.prior_session_ids,
268 session_kind: existing.meta.session_kind,
269 participants: existing.meta.participants.clone(),
270 graph_mutation: existing.environment.graph_mutation,
271 axiom_bounds: existing.environment.axiom_bounds,
272 };
273
274 let env = compile_chat_environment(storage, catalog, &config)?;
275 env.save_to_session_dir(storage)
276 .map_err(|e| BindError::Compile(e.to_string()))?;
277 Ok(env)
278}
279
280pub fn build_inference_packet(
282 env: &ChatEnvironment,
283 user_prompt: &str,
284 catalog: &ResourceCatalog,
285) -> Result<InferenceContextPacket, BindError> {
286 let use_ollama = crate::inference_backend::use_ollama_harness();
287 let active = load_active_model_record();
288
289 let (active_profile, model_path) = if use_ollama {
290 let ib = crate::inference_backend::load_inference_backend_settings();
292 let label = format!("ollama:{}", ib.ollama_model);
293 (None, label)
294 } else {
295 let active = active.ok_or_else(|| {
296 BindError::Compile(
297 "No active model — activate one in LLM Hub, or set Inference Backend to Ollama in Settings"
298 .to_string(),
299 )
300 })?;
301 if !std::path::Path::new(&active.gguf_path).is_file() {
302 return Err(BindError::Compile(format!(
303 "GGUF missing at {}",
304 active.gguf_path
305 )));
306 }
307 let llm = catalog.find_llm(&active.model_id);
308 let active_profile = llm.map(|m| {
309 m.to_capability_profile_with_projector(&active.gguf_path, active.mmproj_path.as_deref())
310 });
311 (active_profile, active.gguf_path.clone())
312 };
313
314 let graph_context_json = serde_json::to_string(env)?;
315 let backend_note = if use_ollama {
316 "\n[inference_backend: ollama — optional HTTP harness; Qualia retrieval/routing still apply]\n"
317 } else {
318 ""
319 };
320 let augmented_prompt = format!(
321 "{}\n{}---\nUser: {}\n---",
322 env.capability_briefing, backend_note, user_prompt
323 );
324
325 Ok(InferenceContextPacket {
326 augmented_prompt,
327 graph_context_json,
328 graph_scope_hashes: env.graph_scope_hashes.clone(),
329 context_namespaces: Vec::new(),
330 routed_ontology_ids: Vec::new(),
331 routing_brief: String::new(),
332 active_profile,
333 model_path,
334 axiom_bounds: env.axiom_bounds.clone(),
335 })
336}
337
338pub fn load_active_model_record() -> Option<model_lifecycle::ActiveModelRecord> {
340 let path = crate::state::app_meta_dir().join("active_model.json");
341 let text = fs::read_to_string(path).ok()?;
342 serde_json::from_str(&text).ok()
343}
344
345fn daemon_is_running() -> bool {
346 let state = match crate::state::APP_STATE.get() {
347 Some(s) => s,
348 None => return false,
349 };
350 *state.daemon_running.lock().unwrap()
351}
352
353fn list_qapp_names(storage: &Path) -> Vec<String> {
354 let dir = crate::qapp_paths::qapps_dir(storage);
355 let mut names = Vec::new();
356 if let Ok(entries) = fs::read_dir(dir) {
357 for entry in entries.filter_map(Result::ok) {
358 if entry.path().is_dir() {
359 names.push(entry.file_name().to_string_lossy().into_owned());
360 }
361 }
362 }
363 names.sort();
364 names
365}
366
367pub fn list_installed_ontology_ids(storage: &Path) -> Vec<String> {
369 let index = resource_import::index_dir(storage);
370 let mut ids = Vec::new();
371
372 if let Ok(entries) = fs::read_dir(&index) {
373 for entry in entries.filter_map(Result::ok) {
374 let path = entry.path();
375 let name = entry.file_name().to_string_lossy().into_owned();
376 if name.ends_with(".q42.meta.json") {
377 if let Ok(text) = fs::read_to_string(&path) {
378 if let Ok(meta) = serde_json::from_str::<OntologyMetaSidecar>(&text) {
379 ids.push(meta.ontology_id);
380 continue;
381 }
382 }
383 }
384 if name.ends_with(".q42") && !name.contains(".meta.") {
385 let id = name.trim_end_matches(".q42").to_string();
386 if !id.is_empty() {
387 ids.push(id);
388 }
389 }
390 }
391 }
392
393 ids.sort();
394 ids.dedup();
395 ids
396}
397
398fn compile_ontology_scope(
399 storage: &Path,
400 catalog: &ResourceCatalog,
401 ont_id: &str,
402 lexicon_out: &mut Vec<u64>,
403) -> Result<Option<OntologyScopeSummary>, BindError> {
404 let q42_path = resource_import::index_dir(storage).join(format!("{ont_id}.q42"));
405 if !q42_path.is_file() {
406 return Ok(None);
407 }
408
409 let meta = read_ontology_meta(storage, ont_id);
410 let quin_count = meta
411 .as_ref()
412 .map(|m| m.quin_count)
413 .unwrap_or_else(|| count_q42_quins(&q42_path).unwrap_or(0));
414
415 if let Ok(quins) = qualia_core_db::q42_reader::read_q42_quins(&q42_path) {
416 collect_lexicon_prefixes(&quins, lexicon_out);
417 }
418
419 let entry = catalog.find_ontology(ont_id);
420 let name = entry
421 .map(|o: &OntologyResource| o.name.clone())
422 .unwrap_or_else(|| ont_id.to_string());
423
424 Ok(Some(OntologyScopeSummary {
425 id: ont_id.to_string(),
426 name,
427 quin_count,
428 q42_path: q42_path.to_string_lossy().into_owned(),
429 domain: entry.and_then(|o| o.domain.clone()),
430 tags: entry.and_then(|o| o.tags.clone()),
431 source: entry.and_then(|o| o.source.clone()),
432 }))
433}
434
435fn read_ontology_meta(storage: &Path, ont_id: &str) -> Option<OntologyMetaSidecar> {
436 let path = resource_import::index_dir(storage).join(format!("{ont_id}.q42.meta.json"));
437 let text = fs::read_to_string(path).ok()?;
438 serde_json::from_str(&text).ok()
439}
440
441fn collect_lexicon_prefixes(quins: &[NQuin], out: &mut Vec<u64>) {
442 let mut freq: HashMap<u64, u32> = HashMap::new();
443 for q in quins {
444 *freq.entry(q.subject & OBJECT_HASH_MASK).or_insert(0) += 1;
445 *freq.entry(q.predicate & OBJECT_HASH_MASK).or_insert(0) += 1;
446 }
447
448 let mut ranked: Vec<(u64, u32)> = freq.into_iter().collect();
449 ranked.sort_by(|a, b| b.1.cmp(&a.1));
450 for (hash, _) in ranked.into_iter().take(MAX_LEXICON_PER_ONTOLOGY) {
451 out.push(hash);
452 }
453}
454
455fn count_q42_quins(path: &Path) -> Result<u64, BindError> {
456 Ok(qualia_core_db::q42_reader::read_q42_quins(path)
457 .map_err(|e| BindError::Compile(e.to_string()))?
458 .len() as u64)
459}
460
461fn write_environment_manifest_q42(
462 storage: &Path,
463 session_id: &str,
464 scopes: &[u64],
465) -> Result<(), BindError> {
466 let dir = crate::chat_session::chats_dir(storage).join(session_id);
467 fs::create_dir_all(&dir)?;
468 let out_path = dir.join("environment.q42");
469
470 let mut quins = Vec::new();
471 let subject = q_hash(&format!("chat:session:{session_id}"));
472 let predicate = q_hash("q42:hasGraphScope");
473
474 for (i, scope) in scopes.iter().take(MAX_MANIFEST_QUINS).enumerate() {
475 let object = *scope & OBJECT_HASH_MASK;
476 let metadata = i as u64;
477 let context = q_hash("chat:environment");
478 let parity = subject ^ predicate ^ object ^ context ^ metadata;
479 quins.push(NQuin {
480 subject,
481 predicate,
482 object,
483 context,
484 metadata,
485 parity,
486 });
487 }
488
489 if quins.is_empty() {
490 return Ok(());
491 }
492
493 write_quins_to_q42(&quins, &out_path)?;
494 Ok(())
495}
496
497fn write_quins_to_q42(quins: &[NQuin], out_path: &Path) -> Result<(), BindError> {
498 qualia_core_db::q42_volume::write_sorted_quins_volume(out_path, quins)?;
499 Ok(())
500}
501
502fn build_capability_briefing(
503 storage: &Path,
504 session_id: &str,
505 session_kind: crate::chat_session::SessionKind,
506 participants: &[crate::chat_session::ChatParticipant],
507 profile: &crate::user_profile::UserProfile,
508 model: Option<&model_lifecycle::ActiveModelRecord>,
509 ontologies: &[OntologyScopeSummary],
510 qapps: &[String],
511 engines: &[String],
512 daemon_reachable: bool,
513 prior_sessions: &[String],
514 lexicon_count: usize,
515) -> String {
516 let mut lines = vec![
517 "[Qualia Chat Environment]".to_string(),
518 format!("session_id: {session_id}"),
519 format!(
520 "session_kind: {}",
521 match session_kind {
522 crate::chat_session::SessionKind::Solo => "solo",
523 crate::chat_session::SessionKind::Group => "group",
524 }
525 ),
526 ];
527
528 if session_kind == crate::chat_session::SessionKind::Group && !participants.is_empty() {
529 lines.push("participants:".to_string());
530 for p in participants {
531 lines.push(format!(
532 " - {} ({}) role={}",
533 p.display_name, p.did, p.role
534 ));
535 }
536 if profile.sharing.share_display_name {
537 lines.push(format!("local_user: {}", profile.display_name));
538 }
539 if profile.sharing.share_public_did {
540 lines.push(format!("local_did: {}", profile.public_did));
541 }
542 lines.push(
543 "instructions: This is a group chat. Attribute user messages to participants when author metadata is present. Respect each participant's shared scope only.".to_string(),
544 );
545 lines.push(
546 "agent_hierarchy: LLM/Webizen agents are sub-agents of their human principal (sub_agent_of), not independent participants. Only use peer agent outcomes when cooperative_agents metadata marks them shareable.".to_string(),
547 );
548 }
549
550 if let Some(m) = model {
551 if profile.sharing.share_active_model {
552 lines.push(format!(
553 "active_model: {} (profile_id=0x{:016x}, modality={}, quantization={}, context_window={})",
554 m.model_id, m.profile_id, m.modality, m.quantization, m.context_window
555 ));
556 if m.modality == "multimodal" {
557 lines.push(
558 "vision: multimodal model with mmproj projector — image ingest available via native vision_ingest"
559 .to_string(),
560 );
561 }
562 } else {
563 lines.push("active_model: [hidden by sharing policy]".to_string());
564 }
565 } else if profile.sharing.share_active_model {
566 lines.push("active_model: none (inference blocked until LLM Hub activation)".to_string());
567 }
568
569 if profile.sharing.share_daemon_status {
570 lines.push(format!(
571 "graph_daemon: {} (localhost SPARQL-style /query over installed .q42 indexes)",
572 if daemon_reachable {
573 "reachable"
574 } else {
575 "not running"
576 }
577 ));
578 }
579
580 if profile.sharing.share_ontology_scope {
581 if ontologies.is_empty() {
582 lines.push("installed_ontologies: none — import ontologies in Ontology Hub for grounded citations".to_string());
583 } else {
584 lines.push("installed_ontologies:".to_string());
585 for o in ontologies {
586 lines.push(format!(
587 " - {} ({}) — {} quins at {}",
588 o.name, o.id, o.quin_count, o.q42_path
589 ));
590 }
591 lines.push(format!(
592 "lexicon_prefixes_sampled: {lexicon_count} predicate/subject hashes"
593 ));
594 }
595 } else {
596 lines.push("installed_ontologies: [hidden by sharing policy]".to_string());
597 }
598
599 if !prior_sessions.is_empty() {
600 lines.push(format!("prior_sessions: {}", prior_sessions.join(", ")));
601 }
602
603 if profile.sharing.share_installed_qapps {
604 if qapps.is_empty() {
605 lines.push("installed_qapps: none".to_string());
606 } else {
607 lines.push(format!("installed_qapps: {}", qapps.join(", ")));
608 }
609 }
610
611 lines.push(format!("native_engines: {}", engines.join(", ")));
612 lines.push("native_tool_routing:".to_string());
613 for capability in CAPABILITY_DESCRIPTORS {
614 lines.push(format!(
615 " - {} [{}] -> {}",
616 capability.name,
617 capability.domain,
618 capability.mcp_tools.join(", ")
619 ));
620 }
621
622 lines.push(
623 "instructions: Ground factual claims in installed ontology quins. Route exact STEM calculations through the listed native MCP tools; do not imitate those solvers in generated prose. Cite graph scope hashes when asserting domain facts. Use Anatomy qapp handoff for spatial/clinical visualization. Refuse ungrounded speculation when ontologies are available.".to_string(),
624 );
625
626 lines.push(crate::chat_ontology::build_chat_ontology_briefing(storage));
627
628 lines.join("\n")
629}
630
631#[cfg(test)]
632mod tests {
633 use super::*;
634 use std::env;
635
636 #[test]
637 fn compile_environment_deterministic_scopes() {
638 let mut storage = env::temp_dir();
639 storage.push(format!("qualia-bind-{}", rand::random::<u32>()));
640 let catalog = ResourceCatalog::empty();
641 let config = ChatEnvironmentConfig {
642 session_id: "test-session".to_string(),
643 ontology_ids: vec![],
644 prior_session_ids: vec![],
645 session_kind: crate::chat_session::SessionKind::Solo,
646 participants: vec![],
647 graph_mutation: false,
648 axiom_bounds: AxiomBounds::default(),
649 };
650 let env = compile_chat_environment(&storage, &catalog, &config).unwrap();
651 assert!(env.capability_briefing.contains("test-session"));
652 assert!(!env.graph_scope_hashes.is_empty());
653 let _ = fs::remove_dir_all(&storage);
654 }
655}