oxo-flow-cli 0.29.0

CLI for the oxo-flow bioinformatics pipeline engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! `oxo-flow knowledge` — read-only access to the embedded knowledge base.
//!
//! Exposes the same data surfaces the AI agent tools use (Bioconda tools,
//! nf-core modules, bio.tools/commercial registry, pipeline skills, full
//! skill docs, pipeline graph, freshness meta) through a deterministic CLI:
//!
//! - `knowledge search <query>` — cross-source unified search
//! - `knowledge get <tool|module|skill|doc> <name>` — exact fetch
//! - `knowledge list docs|domains` — embedded indexes
//! - `knowledge stats` — per-source record counts + freshness
//!
//! JSON output goes to stdout; text output reuses the formatters the AI
//! tool layer uses, so what the model sees is what the CLI prints.

use anyhow::{Result, anyhow, bail};
use chrono::Utc;
use clap::Subcommand;
use oxo_flow_ai::knowledge::bioconda::{format_search_results, get_tool, search_tools, tool_count};
use oxo_flow_ai::knowledge::meta::{embedded_meta, format_source_row};
use oxo_flow_ai::knowledge::pipeline_graph::graph_stats;
use oxo_flow_ai::knowledge::registry::{
    format_registry_hit, format_registry_results, get_registry_tool, registry_count,
};
use oxo_flow_ai::knowledge::skillgraph_docs::{doc_count, doc_ids, format_doc, get_doc, list_docs};
use oxo_flow_ai::knowledge::skills::{
    format_skills, get_skill, list_domains, search_skills, skill_count,
};
use serde_json::json;

/// Maximum rows returned by search/list operations (keeps text output
/// readable and JSON payloads bounded).
const SEARCH_LIMIT: usize = 10;

#[derive(Subcommand, Debug)]
pub enum KnowledgeAction {
    /// Cross-source unified search (Bioconda tools + registry + skills).
    Search {
        #[arg(
            value_name = "QUERY",
            help = "Search keywords, e.g. 'variant calling' or 'samtools'"
        )]
        query: String,
    },
    /// Exact-fetch one record by kind.
    Get {
        #[arg(
            value_name = "KIND",
            help = "Record kind: tool (bioconda), module (nf-core), skill, doc"
        )]
        kind: String,
        #[arg(value_name = "NAME", help = "Record name/id (case-insensitive)")]
        name: String,
    },
    /// List an embedded index.
    List {
        #[arg(
            value_name = "WHAT",
            help = "Index to list: docs (skill documents) or domains (skill domains)"
        )]
        what: String,
    },
    /// Show per-source record counts and freshness.
    Stats,
}

fn meta_or_bail() -> Result<&'static oxo_flow_ai::knowledge::meta::KnowledgeMeta> {
    embedded_meta().ok_or_else(|| {
        anyhow!(
            "knowledge metadata is not embedded in this build (knowledge_meta_embedded cfg missing)"
        )
    })
}

fn registry_hit_json(hit: &oxo_flow_ai::knowledge::registry::RegistryHit) -> serde_json::Value {
    use oxo_flow_ai::knowledge::registry::RegistryHit;
    match hit {
        RegistryHit::NfCore(m) => json!({
            "source": "nf-core",
            "name": m.name,
            "versions": m.versions,
            "summary": m.summary,
            "license": m.license,
            "biotools_id": m.biotools_id,
            "doi": m.doi,
        }),
        RegistryHit::Commercial(t) => json!({
            "source": "commercial",
            "name": t.name,
            "version": t.version,
            "summary": t.summary,
            "url": t.url,
            "note": t.note,
        }),
        RegistryHit::BioTools(b) => json!({
            "source": "bio.tools",
            "name": b.name,
            "description": b.description,
            "license": b.license,
            "homepage": b.homepage,
            "topics": b.topics,
            "operations": b.operations,
            "dois": b.dois,
        }),
    }
}

fn skill_json(skill: &oxo_flow_ai::knowledge::skills::SkillRecord) -> serde_json::Value {
    json!({
        "name": skill.name,
        "domain": skill.domain,
        "description": skill.description,
        "tool_type": skill.tool_type,
        "primary_tool": skill.primary_tool,
        "preview": skill.preview,
    })
}

// ── Kind dispatch (single source for JSON + text emitters) ──────────────────

/// One resolved `knowledge get` record. Both output modes consume this, so
/// the kind matching — and its error strings — exist exactly once (reuse,
/// never retype: hand-twinning the JSON and text dispatches lets the two
/// surfaces drift, e.g. one gaining a new kind or an improved hint).
enum KnowledgeRecord {
    Tool(&'static oxo_flow_ai::knowledge::bioconda::BiocondaTool),
    Module(oxo_flow_ai::knowledge::registry::RegistryHit),
    Skill(&'static oxo_flow_ai::knowledge::skills::SkillRecord),
    Doc(&'static oxo_flow_ai::knowledge::skillgraph_docs::SkillDoc),
}

fn resolve_kind(kind: &str, name: &str) -> Result<KnowledgeRecord> {
    match kind {
        "tool" => get_tool(name)
            .map(KnowledgeRecord::Tool)
            .ok_or_else(|| anyhow!("no bioconda tool named '{name}'")),
        "module" => get_registry_tool(name)
            .map(KnowledgeRecord::Module)
            .ok_or_else(|| {
                anyhow!("no registry record named '{name}' (nf-core, commercial, or bio.tools)")
            }),
        "skill" => get_skill(name)
            .map(KnowledgeRecord::Skill)
            .ok_or_else(|| anyhow!("no skill named '{name}' (names carry a bio- prefix; see `oxo-flow knowledge search '{name}'`)")),
        "doc" => get_doc(name)
            .map(KnowledgeRecord::Doc)
            .ok_or_else(|| anyhow!("no skill doc for '{name}' (see `oxo-flow knowledge list docs`)")),
        _ => bail!("unknown kind '{kind}' (expected 'tool', 'module', 'skill', or 'doc')"),
    }
}

/// Which embedded index `knowledge list` should dump.
enum KnowledgeIndex {
    Docs,
    Domains,
}

fn resolve_index(what: &str) -> Result<KnowledgeIndex> {
    match what {
        "docs" => Ok(KnowledgeIndex::Docs),
        "domains" => Ok(KnowledgeIndex::Domains),
        _ => bail!("unknown index '{what}' (expected 'docs' or 'domains')"),
    }
}

// ── JSON emitters ───────────────────────────────────────────────────────────

fn search_json(query: &str) -> serde_json::Value {
    let tools = search_tools(query, SEARCH_LIMIT);
    let registry = oxo_flow_ai::knowledge::registry::search_registry(query, SEARCH_LIMIT);
    let skills = search_skills(query, SEARCH_LIMIT);
    json!({
        "command": "knowledge",
        "action": "search",
        "query": query,
        "tools": tools
            .iter()
            .map(|t| json!({
                "name": t.name, "version": t.version,
                "summary": t.summary, "platforms": t.platforms,
            }))
            .collect::<Vec<_>>(),
        "registry": registry.iter().map(registry_hit_json).collect::<Vec<_>>(),
        "skills": skills.iter().map(|s| skill_json(s)).collect::<Vec<_>>(),
    })
}

fn get_json(kind: &str, name: &str) -> Result<serde_json::Value> {
    match resolve_kind(kind, name)? {
        KnowledgeRecord::Tool(t) => Ok(json!({
            "command": "knowledge", "action": "get", "kind": kind,
            "found": true,
            "record": {
                "name": t.name, "version": t.version,
                "summary": t.summary, "platforms": t.platforms,
            },
        })),
        KnowledgeRecord::Module(hit) => Ok(json!({
            "command": "knowledge", "action": "get", "kind": kind,
            "found": true,
            "record": registry_hit_json(&hit),
        })),
        KnowledgeRecord::Skill(s) => Ok(json!({
            "command": "knowledge", "action": "get", "kind": kind,
            "found": true,
            "record": skill_json(s),
        })),
        KnowledgeRecord::Doc(d) => Ok(json!({
            "command": "knowledge", "action": "get", "kind": kind,
            "found": true,
            "record": { "id": d.id, "doc": d.doc },
        })),
    }
}

fn list_json(what: &str) -> Result<serde_json::Value> {
    match resolve_index(what)? {
        KnowledgeIndex::Docs => {
            let ids = doc_ids();
            let count = ids.len();
            Ok(json!({
                "command": "knowledge", "action": "list", "what": what,
                "count": count,
                "docs": ids,
            }))
        }
        KnowledgeIndex::Domains => {
            let domains = list_domains();
            Ok(json!({
                "command": "knowledge", "action": "list", "what": what,
                "count": domains.len(),
                "domains": domains
                    .iter()
                    .map(|(name, n)| json!({ "name": name, "skills": n }))
                    .collect::<Vec<_>>(),
            }))
        }
    }
}

fn stats_json() -> Result<serde_json::Value> {
    let meta = meta_or_bail()?;
    let now = Utc::now();
    let (graph_nodes, graph_edges) = graph_stats();
    let sources: Vec<serde_json::Value> = meta
        .sources
        .iter()
        .map(|src| {
            json!({
                "name": src.name,
                "count": src.count,
                "generated_at": src.generated_at,
                "auto": src.auto,
                "stale": src.is_stale(now),
            })
        })
        .collect();
    Ok(json!({
        "command": "knowledge", "action": "stats",
        "sources": sources,
        "live_counts": {
            "bioconda_tools": tool_count(),
            "registry": registry_count(),
            "skills": skill_count(),
            "skill_docs": doc_count(),
            "graph_nodes": graph_nodes,
            "graph_edges": graph_edges,
        },
    }))
}

// ── Text emitters ───────────────────────────────────────────────────────────

fn search_text(query: &str) {
    // format_search_results self-covers the empty case ("No Bioconda CLI
    // tools matched …"), so no is_empty fallback is needed here.
    let bioconda = format_search_results(query, SEARCH_LIMIT);
    println!("{bioconda}");
    let registry = format_registry_results(query, SEARCH_LIMIT);
    if !registry.is_empty() {
        println!("\n{registry}");
    }
    let skills = format_skills(query, SEARCH_LIMIT);
    println!("\n{skills}");
}

fn get_text(kind: &str, name: &str) -> Result<()> {
    match resolve_kind(kind, name)? {
        KnowledgeRecord::Tool(t) => {
            println!("{} {} — {}", t.name, t.version, t.summary);
            if !t.platforms.is_empty() {
                println!("platforms: {}", t.platforms.join(", "));
            }
        }
        KnowledgeRecord::Module(hit) => println!("{}", format_registry_hit(&hit)),
        KnowledgeRecord::Skill(s) => {
            println!("[{}] {} — {}", s.domain, s.name, s.description);
            if !s.primary_tool.is_empty() {
                println!("primary_tool: {}", s.primary_tool);
            }
            if !s.preview.is_empty() {
                println!("\n{}", s.preview);
            }
        }
        KnowledgeRecord::Doc(d) => println!("{}", format_doc(d)),
    }
    Ok(())
}

fn list_text(what: &str) -> Result<()> {
    match resolve_index(what)? {
        KnowledgeIndex::Docs => println!("{}", list_docs()),
        KnowledgeIndex::Domains => {
            let domains = list_domains();
            println!(
                "{} skill domains ({} embedded skills):",
                domains.len(),
                skill_count()
            );
            for (name, n) in domains {
                println!("- {name}: {n} skills");
            }
        }
    }
    Ok(())
}

fn stats_text() -> Result<()> {
    let meta = meta_or_bail()?;
    let now = Utc::now();
    println!("Embedded knowledge sources:");
    for src in &meta.sources {
        let mut row = format_source_row(src, now);
        if src.is_stale(now) {
            row.push_str("  [STALE]");
        }
        println!("- {row}");
    }
    let (nodes, edges) = graph_stats();
    println!(
        "\nLive record counts: {} bioconda tools, {} registry records, {} skills, {} skill docs, {} graph nodes / {} transitions",
        tool_count(),
        registry_count(),
        skill_count(),
        doc_count(),
        nodes,
        edges
    );
    Ok(())
}

// ── Entry point ─────────────────────────────────────────────────────────────

/// Execute the `knowledge` subcommand.
pub fn knowledge_command(action: KnowledgeAction, format: Option<String>) -> Result<()> {
    let text = match format.as_deref() {
        Some("text") => true,
        Some("json") | None => false,
        Some(other) => bail!("unknown format '{other}' (expected 'json' or 'text')"),
    };

    match action {
        KnowledgeAction::Search { query } => {
            if text {
                search_text(&query);
            } else {
                println!("{}", serde_json::to_string_pretty(&search_json(&query))?);
            }
        }
        KnowledgeAction::Get { kind, name } => {
            if text {
                get_text(&kind, &name)?;
            } else {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&get_json(&kind, &name)?)?
                );
            }
        }
        KnowledgeAction::List { what } => {
            if text {
                list_text(&what)?;
            } else {
                println!("{}", serde_json::to_string_pretty(&list_json(&what)?)?);
            }
        }
        KnowledgeAction::Stats => {
            if text {
                stats_text()?;
            } else {
                println!("{}", serde_json::to_string_pretty(&stats_json()?)?);
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn get_json_tool_exact() {
        let v = get_json("tool", "samtools").expect("samtools is embedded");
        assert_eq!(v["record"]["name"], "samtools");
        assert_eq!(v["found"], true);
    }

    #[test]
    fn get_json_tool_unknown_is_err() {
        assert!(get_json("tool", "no-such-tool-xyz").is_err());
    }

    #[test]
    fn get_json_module_exact() {
        let v = get_json("module", "fastqc").expect("fastqc module is embedded");
        assert_eq!(v["record"]["source"], "nf-core");
        assert_eq!(v["record"]["name"], "fastqc");
    }

    #[test]
    fn get_json_unknown_kind_bails() {
        assert!(get_json("recipe", "x").is_err());
    }

    #[test]
    fn get_json_skill_top_hit() {
        let v = get_json("skill", "bio-gatk-variant-calling").expect("skill is embedded");
        assert_eq!(v["record"]["domain"], "variant-calling");
    }

    #[test]
    fn get_json_skill_unknown_is_err() {
        // get skill is an exact fetch: a fuzzy-only match must not succeed.
        assert!(get_json("skill", "variant-calling").is_err());
    }

    #[test]
    fn get_json_doc_resolves_display_name() {
        // pipeline-graph display names bridge to doc ids; fall back to a
        // doc id that is verified to exist in the embedded data.
        let v = get_json("doc", "variant-calling").or_else(|_| get_json("doc", "clinical-variant"));
        assert!(v.is_ok(), "at least one canonical doc id must resolve");
        let v = v.unwrap();
        assert!(v["record"]["doc"].as_str().unwrap().len() > 100);
    }

    #[test]
    fn list_json_domains_sorted_and_counted() {
        let v = list_json("domains").expect("domains list");
        let domains = v["domains"].as_array().expect("array");
        assert!(!domains.is_empty());
        let names: Vec<&str> = domains
            .iter()
            .map(|d| d["name"].as_str().expect("name"))
            .collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted, "domains must be BTreeMap-ordered");
    }

    #[test]
    fn list_json_unknown_index_bails() {
        assert!(list_json("tools").is_err());
    }

    #[test]
    fn stats_json_has_sources_and_live_counts() {
        let v = stats_json().expect("meta embedded");
        assert!(v["sources"].as_array().expect("sources").len() >= 8);
        assert!(v["live_counts"]["bioconda_tools"].as_u64().unwrap() > 6000);
        assert!(v["live_counts"]["skill_docs"].as_u64().unwrap() >= 70);
    }

    #[test]
    fn search_json_groups_three_sources() {
        let v = search_json("alignment");
        assert!(v["tools"].as_array().unwrap().iter().count() <= SEARCH_LIMIT);
        assert!(v["registry"].is_array());
        assert!(v["skills"].is_array());
    }

    #[test]
    fn format_flag_rejects_unknown() {
        let err = knowledge_command(KnowledgeAction::Stats, Some("yaml".into()))
            .expect_err("unknown format must fail");
        assert!(err.to_string().contains("unknown format 'yaml'"));
    }

    #[test]
    fn text_stats_prints_sources() {
        // stats_text must not panic with real embedded meta.
        stats_text().expect("stats_text");
    }

    #[test]
    fn text_list_domains_prints() {
        list_text("domains").expect("list_text domains");
        list_text("docs").expect("list_text docs");
    }

    #[test]
    fn text_get_tool_exact() {
        get_text("tool", "bwa").expect("bwa is embedded");
        assert!(get_text("tool", "no-such-tool-xyz").is_err());
    }
}