Skip to main content

qualia_cli/
resources.rs

1//! `qualia-cli resources` — discover, inspect, download, and import catalog resources.
2//!
3//! # Pipeline (download)
4//!
5//! ```text
6//! resources/llms.yaml
7//!   └─ LLMResource::download_info.resolved_url()
8//!        └─ reqwest stream → ~/.qualia/models/<filename>
9//!             └─ GGufSharder::generate_bidx_pointer_map()   ← tensor pointer Quins
10//!                  └─ WriteAheadLog::append_mutation()       ← pointer + provenance Quins
11//!                       └─ LLMResource::to_capability_profile() → CapabilityProfile
12//! ```
13//!
14//! # Pipeline (ontology import)
15//!
16//! ```text
17//! resources/ontologies.yaml
18//!   └─ OntologyResource::download_info.resolved_url()
19//!        └─ reqwest stream → /tmp/<filename>
20//!             └─ qualia_core_db::ingest::streaming_import_rdf()   ← builds .q42
21//!                  └─ WriteAheadLog::append_mutation()             ← provenance Quin
22//! ```
23
24use qualia_core_db::resource_catalog::{self, ResourceCatalog};
25use std::path::{Path, PathBuf};
26
27/// Load the full `ResourceCatalog` from the YAML files under `catalog_dir`.
28pub fn load_catalog(catalog_dir: &Path) -> Result<ResourceCatalog, String> {
29    resource_catalog::load_from_dir(catalog_dir).map_err(|e| e.to_string())
30}
31
32// ─── CLI entry point ─────────────────────────────────────────────────────────
33
34/// Handles the subcommand action.
35pub async fn handle(subcommand: &str, arg: Option<&str>) {
36    let catalog_dir = resource_catalog::resolve_resources_dir();
37    let catalog = match load_catalog(&catalog_dir) {
38        Ok(c) => c,
39        Err(e) => {
40            eprintln!("Error loading catalog: {}", e);
41            return;
42        }
43    };
44
45    match subcommand {
46        "list" => cmd_list(&catalog, arg),
47        "show" => cmd_show(&catalog, arg),
48        "download" => {
49            if let Some(id) = arg {
50                cmd_download(&catalog, id).await;
51            } else {
52                eprintln!("Usage: qualia resources download <llm-id>");
53            }
54        }
55        "import-ontology" => {
56            if let Some(id) = arg {
57                cmd_import_ontology(&catalog, id).await;
58            } else {
59                eprintln!("Usage: qualia resources import-ontology <ontology-id>");
60            }
61        }
62        _ => print_help(),
63    }
64}
65
66// ─── list ─────────────────────────────────────────────────────────────────────
67
68fn cmd_list(catalog: &ResourceCatalog, filter: Option<&str>) {
69    match filter.unwrap_or("all") {
70        "llms" | "llm" => list_llms(catalog),
71        "ontologies" | "ont" => list_ontologies(catalog),
72        "sparql" => list_sparql(catalog),
73        _ => {
74            list_llms(catalog);
75            list_ontologies(catalog);
76            list_sparql(catalog);
77        }
78    }
79}
80
81fn list_llms(catalog: &ResourceCatalog) {
82    println!("\nLLMs ({}):", catalog.llms.len());
83    for m in &catalog.llms {
84        println!(
85            "  {:40} {:8}  {:7}  {}MB",
86            m.id,
87            m.format,
88            m.quantization.as_deref().unwrap_or("—"),
89            m.size_mb.unwrap_or(0)
90        );
91    }
92}
93
94fn list_ontologies(catalog: &ResourceCatalog) {
95    println!("\nOntologies ({}):", catalog.ontologies.len());
96    for o in &catalog.ontologies {
97        println!(
98            "  {:40} {:6}  ~{}MB  {}",
99            o.id,
100            o.format,
101            o.size_estimate_mb.unwrap_or(0.0),
102            o.domain.as_deref().unwrap_or("—")
103        );
104    }
105}
106
107fn list_sparql(catalog: &ResourceCatalog) {
108    println!("\nSPARQL endpoints ({}):", catalog.sparql_endpoints.len());
109    for s in &catalog.sparql_endpoints {
110        println!("  {:40} {}", s.id, s.endpoint);
111    }
112}
113
114// ─── show ─────────────────────────────────────────────────────────────────────
115
116fn cmd_show(catalog: &ResourceCatalog, id: Option<&str>) {
117    let id = match id {
118        Some(i) => i,
119        None => {
120            eprintln!("Usage: qualia resources show <id>");
121            return;
122        }
123    };
124
125    if let Some(m) = catalog.find_llm(id) {
126        println!("LLM: {}", m.name);
127        println!("  id           : {}", m.id);
128        println!("  format       : {}", m.format);
129        println!(
130            "  quantization : {}",
131            m.quantization.as_deref().unwrap_or("—")
132        );
133        println!("  size         : {}MB", m.size_mb.unwrap_or(0));
134        println!("  RAM estimate : {}MB", m.ram_estimate_mb.unwrap_or(0));
135        println!("  license      : {}", m.license.as_deref().unwrap_or("—"));
136        if let Some(url) = m.download.resolved_url() {
137            println!("  download url : {}", url);
138        }
139        if let Some(ref notes) = m.notes {
140            println!("  notes        : {}", notes);
141        }
142        println!(
143            "  profile_id   : 0x{:016x}  (q_hash(\"profile:{}\"))",
144            qualia_core_db::q_hash(&format!("profile:{}", m.id)),
145            m.id
146        );
147        return;
148    }
149
150    if let Some(o) = catalog.find_ontology(id) {
151        println!("Ontology: {}", o.name);
152        println!("  id       : {}", o.id);
153        println!("  format   : {}", o.format);
154        println!("  domain   : {}", o.domain.as_deref().unwrap_or("—"));
155        println!("  size     : ~{}MB", o.size_estimate_mb.unwrap_or(0.0));
156        println!("  license  : {}", o.license.as_deref().unwrap_or("—"));
157        if let Some(url) = o.download.resolved_url() {
158            println!("  download : {}", url);
159        }
160        return;
161    }
162
163    if let Some(s) = catalog.find_sparql(id) {
164        println!("SPARQL: {}", s.name);
165        println!("  endpoint     : {}", s.endpoint);
166        println!(
167            "  maintainer   : {}",
168            s.maintainer.as_deref().unwrap_or("—")
169        );
170        println!(
171            "  reliability  : {}",
172            s.reliability.as_deref().unwrap_or("—")
173        );
174        return;
175    }
176
177    eprintln!("Not found: {}", id);
178}
179
180// ─── download ─────────────────────────────────────────────────────────────────
181
182fn default_storage_root() -> PathBuf {
183    std::env::var("QUALIA_STORAGE")
184        .map(PathBuf::from)
185        .unwrap_or_else(|_| {
186            std::env::var("HOME")
187                .or_else(|_| std::env::var("USERPROFILE"))
188                .map(PathBuf::from)
189                .unwrap_or_else(|_| PathBuf::from("."))
190                .join(".qualia")
191        })
192}
193
194async fn cmd_download(catalog: &ResourceCatalog, id: &str) {
195    let storage = default_storage_root();
196
197    match qualia_client_core::model_lifecycle::install_catalog_llm(catalog, id, &storage).await {
198        Ok(result) => {
199            println!("Install complete: {}", result.gguf_path);
200            println!("  profile_id : 0x{:016x}", result.profile_id);
201            println!("  pointers   : {}", result.pointer_quin_count);
202            println!("  WAL        : {}", result.wal_path);
203            println!("  lifecycle  : {}", result.lifecycle_state);
204            println!(
205                "\nActivate in LLM Hub, then chat with profile_id 0x{:016x}",
206                result.profile_id
207            );
208        }
209        Err(e) => eprintln!("Download failed: {e}"),
210    }
211}
212
213// ─── import-ontology ──────────────────────────────────────────────────────────
214
215async fn cmd_import_ontology(catalog: &ResourceCatalog, id: &str) {
216    let storage = default_storage_root();
217
218    match qualia_client_core::resource_import::import_catalog_ontology(catalog, id, &storage).await
219    {
220        Ok(result) => {
221            println!("Import complete: {}", result.q42_path);
222            println!("  Quins: {}", result.quin_count);
223            println!("  WAL:   {}", result.wal_path);
224            println!("  SHA256: {}", result.sha256);
225        }
226        Err(e) => eprintln!("Import failed: {e}"),
227    }
228}
229
230fn print_help() {
231    println!("qualia resources <subcommand> [arg]");
232    println!("  list [llms|ontologies|sparql]    List catalog entries");
233    println!("  show <id>                        Show details for a resource");
234    println!("  download <llm-id>                Download GGUF → WAL + CapabilityProfile");
235    println!("  import-ontology <ont-id>         Download + ingest ontology → .q42 + WAL");
236}