oxo-flow-cli 0.23.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
use anyhow::{Context, Result};
use colored::Colorize;
use oxo_flow_core::config::WorkflowConfig;

use crate::commands::print_banner;

use crate::{ConfigAction, EnvAction};

pub async fn env_command(action: EnvAction) -> Result<()> {
    print_banner();
    match action {
        EnvAction::List { workflow } => match workflow {
            Some(wf_path) => {
                let config = WorkflowConfig::from_file(&wf_path)
                    .with_context(|| format!("failed to parse {}", wf_path.display()))?;
                eprintln!(
                    "{} {}",
                    "Environments in".bold(),
                    wf_path.display().to_string().dimmed()
                );
                let mut seen = std::collections::HashSet::new();
                for rule in &config.rules {
                    let kind = rule.environment.kind();
                    let spec = kind.to_string();
                    if seen.insert(format!("{}:{spec}", rule.name)) {
                        eprintln!("  {} {} [{}]", "✓".green(), rule.name, spec);
                    }
                }
                if seen.is_empty() {
                    eprintln!(
                        "  (no environment specifications found — rules will use system environment)"
                    );
                }
            }
            None => {
                let resolver = oxo_flow_core::environment::EnvironmentResolver::new();
                let available = resolver.available_backends();
                eprintln!("{}", "Available environment backends:".bold());
                for backend in available {
                    eprintln!("  {} {}", "✓".green(), backend);
                }
            }
        },
        EnvAction::Check { workflow } => {
            let resolver = oxo_flow_core::environment::EnvironmentResolver::new();

            match workflow {
                Some(wf_path) => {
                    // Validate each rule's declared environment in the workflow.
                    let config = WorkflowConfig::from_file(&wf_path)
                        .with_context(|| format!("failed to parse {}", wf_path.display()))?;

                    // A rule's `pixi = "envs/pixi.toml"` is resolved relative
                    // to the WORKFLOW (that is what the engine's error message
                    // promises), never to wherever the command happens to run.
                    let workflow_dir = wf_path
                        .parent()
                        .filter(|p| !p.as_os_str().is_empty())
                        .unwrap_or_else(|| std::path::Path::new("."));

                    let mut all_ok = true;
                    for rule in &config.rules {
                        let spec = rule.environment.resolve_relative_paths(Some(workflow_dir));
                        match resolver.validate_spec(&spec) {
                            Ok(()) => {
                                eprintln!(
                                    "  {} {} ({})",
                                    "✓".green(),
                                    rule.name,
                                    rule.environment.kind()
                                );
                            }
                            Err(e) => {
                                eprintln!("  {} {} — {}", "✗".red(), rule.name, e);
                                all_ok = false;
                            }
                        }
                    }

                    if !all_ok {
                        std::process::exit(1);
                    }
                }
                None => {
                    // No workflow provided: report global backend availability.
                    eprintln!("{}", "Environment backend availability:".bold());
                    let available = resolver.available_backends();
                    for backend in
                        oxo_flow_core::environment::EnvironmentResolver::all_known_backends()
                    {
                        if available.contains(backend) {
                            // Surface WHICH binary resolves — on boxes with
                            // several conda-family installs, "conda ✓" alone
                            // hides which one a run would pick (issue #433).
                            // `resolved_backend_binary` only annotates the
                            // conda family; other backends (docker, venv,
                            // modules, ...) resolve structurally, so a
                            // missing annotation must NOT print "not found"
                            // for a backend that IS available.
                            match resolver.resolved_backend_binary(backend) {
                                Some(bin) if bin != *backend => {
                                    eprintln!("  {} {} (resolved: {})", "✓".green(), backend, bin);
                                }
                                _ => {
                                    eprintln!("  {} {}", "✓".green(), backend);
                                }
                            }
                        } else {
                            eprintln!("  {} {} (not found)", "✗".red(), backend);
                        }
                    }
                }
            }
        }
        EnvAction::Create {
            spec,
            name,
            ai,
            backend,
        } => {
            // AI mode: SPEC is a natural-language description, not a file path.
            if ai {
                return create_env_from_ai(&spec, name, backend.as_deref().unwrap_or("conda"))
                    .await;
            }
            let name_str = name.clone().unwrap_or_else(|| {
                spec.file_stem()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string()
            });

            // Determine the backend from the spec's extension, then let an
            // explicit --backend win. The flag used to be shadowed by this
            // match, so `env create --backend pixi` always ran conda (audit
            // finding); a mismatch with the spec format warns rather than
            // silently overriding the user's choice.
            let ext = spec.extension().and_then(|e| e.to_str()).unwrap_or("");
            let ext_backend = match ext {
                "yaml" | "yml" => "conda",
                "toml" => "pixi",
                "lock" => "conda",
                _ => {
                    eprintln!(
                        "{} Unknown environment spec format: '{}'",
                        "Warning:".yellow(),
                        spec.display()
                    );
                    eprintln!(
                        "  Supported formats: .yaml/.yml (conda), .toml (pixi), .lock (conda-lock)"
                    );
                    anyhow::bail!("Unsupported environment spec format");
                }
            };
            let backend = match backend {
                Some(requested) => {
                    if !requested.eq_ignore_ascii_case(ext_backend) {
                        eprintln!(
                            "{} --backend {requested} overrides the spec format \
                             ('.{ext}' is a {ext_backend} spec)",
                            "Warning:".yellow()
                        );
                    }
                    requested
                }
                None => ext_backend.to_string(),
            };

            eprintln!(
                "{} Creating {} environment '{}' from '{}'...",
                "Info:".bold().cyan(),
                backend,
                name_str,
                spec.display()
            );

            match backend.as_str() {
                "conda" => {
                    // Use conda/mamba to create environment
                    // Prefer mamba for speed, fall back to conda
                    let tool = {
                        let mamba_exists = std::process::Command::new("mamba")
                            .arg("--version")
                            .stdout(std::process::Stdio::null())
                            .stderr(std::process::Stdio::null())
                            .status()
                            .is_ok();
                        let micromamba_exists = std::process::Command::new("micromamba")
                            .arg("--version")
                            .stdout(std::process::Stdio::null())
                            .stderr(std::process::Stdio::null())
                            .status()
                            .is_ok();
                        if mamba_exists {
                            "mamba"
                        } else if micromamba_exists {
                            "micromamba"
                        } else {
                            "conda"
                        }
                    };

                    let status = std::process::Command::new(tool)
                        .args([
                            "env",
                            "create",
                            "-f",
                            &spec.to_string_lossy(),
                            "-n",
                            &name_str,
                        ])
                        .status()
                        .with_context(|| format!("failed to run {} env create", tool))?;

                    if !status.success() {
                        anyhow::bail!(
                            "{} env create failed with exit code {:?}",
                            tool,
                            status.code()
                        );
                    }
                    eprintln!(
                        "  {} Environment '{}' created successfully.",
                        "✓".green(),
                        name_str
                    );
                    eprintln!("  Activate with: conda activate {}", name_str);
                }
                "pixi" => {
                    // The generated spec is itself a complete pixi project
                    // manifest ([project] + [dependencies]) — install it
                    // directly. `pixi init` would create an empty project
                    // and install nothing.
                    let pixi_toml = std::fs::read_to_string(&spec)
                        .with_context(|| format!("cannot read pixi spec: {}", spec.display()))?;

                    // Staged in a uniquely named temp directory instead of
                    // `temp_dir()/oxo-flow-<name>` — the same shared-machine
                    // hazard as the bundle extraction in `bundle.rs` (a
                    // predictable, user-controlled name another user can
                    // pre-create). The project must outlive this process —
                    // the user is told to `cd` into it and `pixi shell` — so
                    // it is kept only after a successful install; failures
                    // clean up automatically via the TempDir guard.
                    let temp_project =
                        tempfile::Builder::new()
                            .prefix("oxo-flow-env-")
                            .tempdir()
                            .context("failed to create temporary pixi project directory")?;
                    let project_dir = temp_project.path().to_path_buf();
                    std::fs::write(project_dir.join("pixi.toml"), &pixi_toml)
                        .with_context(|| "failed to write pixi.toml")?;

                    let status = std::process::Command::new("pixi")
                        .args(["install"])
                        .current_dir(&project_dir)
                        .status()
                        .with_context(|| "failed to run pixi install")?;

                    if !status.success() {
                        anyhow::bail!("pixi install failed");
                    }

                    // Success: hand the directory over to the user (the
                    // guard would otherwise delete it on drop).
                    let _ = temp_project.keep();

                    eprintln!(
                        "  {} Pixi project created at: {}",
                        "✓".green(),
                        project_dir.display()
                    );
                    eprintln!(
                        "  Activate with: cd {} && pixi shell",
                        project_dir.display()
                    );
                }
                other => {
                    anyhow::bail!(
                        "Environment backend '{}' not supported for env create yet",
                        other
                    );
                }
            }
        }
    }
    Ok(())
}

pub fn handle_config(action: ConfigAction) -> Result<()> {
    print_banner();
    match action {
        ConfigAction::Show { workflow } => {
            let config = WorkflowConfig::from_file(&workflow)
                .with_context(|| format!("failed to parse {}", workflow.display()))?;

            eprintln!("{}", "Workflow Configuration:".bold());
            eprintln!("  Name:    {}", config.workflow.name);
            eprintln!("  Version: {}", config.workflow.version);
            if let Some(ref desc) = config.workflow.description {
                eprintln!("  Desc:    {}", desc);
            }
            if let Some(ref author) = config.workflow.author {
                eprintln!("  Author:  {}", author);
            }

            eprintln!("\n{}", "Config Variables:".bold());
            if config.config.is_empty() {
                eprintln!("  (none)");
            } else {
                for (k, v) in &config.config {
                    eprintln!("  {} = {}", k, v);
                }
            }
        }
        ConfigAction::Stats { workflow } => {
            let config = WorkflowConfig::from_file(&workflow)
                .with_context(|| format!("failed to parse {}", workflow.display()))?;

            let stats = oxo_flow_core::format::workflow_stats(&config);
            eprintln!("{}", "Workflow Statistics:".bold());
            eprintln!("  Workflow:           {}", config.workflow.name);
            eprintln!("  Rules:              {}", stats.rule_count);
            eprintln!("  Shell rules:        {}", stats.shell_rules);
            eprintln!("  Script rules:       {}", stats.script_rules);
            eprintln!("  Dependencies:       {}", stats.dependency_count);
            eprintln!("  Parallel groups:    {}", stats.parallel_groups);
            eprintln!("  Max depth:          {}", stats.max_depth);
            eprintln!("  Total threads:      {}", stats.total_threads);
            eprintln!(
                "  Wildcards:          {} ({:?})",
                stats.wildcard_count, stats.wildcard_names
            );
            if !stats.environments.is_empty() {
                eprintln!("  Environments:       {:?}", stats.environments);
            }
        }
        ConfigAction::Get { workflow, key } => {
            let config = WorkflowConfig::from_file(&workflow)?;
            if let Some(val) = config.config.get(&key) {
                println!("{}", val);
            } else {
                return Err(anyhow::anyhow!("config key '{}' not found", key));
            }
        }
    }
    Ok(())
}

/// Verify a license file, or display the current license status without one.
/// With `json` set, both branches emit a machine-readable object on stdout
/// instead of the human summary (the global `--json` flag was previously a
/// silent no-op for this command).
pub fn handle_license(path: Option<std::path::PathBuf>, json: bool) -> Result<()> {
    let status = oxo_flow_web::check_license();
    if let Some(p) = path {
        match oxo_license::load_and_verify(Some(&p), &oxo_flow_web::OXO_FLOW_CONFIG) {
            Ok(license) => {
                if json {
                    println!(
                        "{}",
                        serde_json::json!({
                            "verified": true,
                            "type": license.payload.license_type,
                            "issued_to": license.payload.issued_to_org,
                            "schema": license.payload.schema,
                            "id": license.payload.license_id,
                        })
                    );
                } else {
                    println!("{} License verified successfully", "✓".green().bold());
                    println!("  Type:    {}", license.payload.license_type);
                    println!("  Issued:  {}", license.payload.issued_to_org);
                    println!("  Schema:  {}", license.payload.schema);
                    println!("  ID:      {}", license.payload.license_id);
                }
            }
            Err(e) => {
                if json {
                    println!(
                        "{}",
                        serde_json::json!({ "verified": false, "error": e.to_string() })
                    );
                }
                anyhow::bail!("License verification failed: {e}");
            }
        }
    } else if json {
        println!(
            "{}",
            serde_json::json!({
                "valid": status.valid,
                "license_type": status.license_type,
                "issued_to": status.issued_to,
                "message": status.message,
            })
        );
    } else {
        println!("License status:");
        if status.valid {
            println!(
                "  Status:  {} ({})",
                "Valid".green().bold(),
                status.license_type.as_deref().unwrap_or("unknown")
            );
            if let Some(org) = &status.issued_to {
                println!("  Issued:  {org}");
            }
        } else {
            println!("  Status:  {}", "Invalid".red().bold());
        }
        println!("  Message: {}", status.message);
    }
    Ok(())
}

// ── AI-powered environment spec generation ────────────────────────────────

/// Generate an environment spec (conda YAML or pixi TOML) from a
/// natural-language description using the AI provider + built-in tool table.
/// Pre-resolve tools mentioned in a natural-language description against
/// the embedded Bioconda database (`env create --ai`).
///
/// Generic stop words and short fragments are filtered before matching,
/// and only NAME-level matches (the tool name contains the word) are
/// injected — summary-only matches are too loose. Returns (name, version,
/// summary) triples, deduplicated.
fn match_description_tools(description: &str) -> Vec<(String, String, String)> {
    const STOP_WORDS: &[&str] = &[
        "and", "the", "for", "with", "using", "into", "from", "your", "pipeline", "workflow",
        "analysis", "data", "files", "output", "input", "all", "new", "this", "that", "via",
        "then", "also", "based", "need", "want", "please",
    ];
    let mut matched = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for word in description
        .split(|c: char| !c.is_alphanumeric() && c != '-' && c != '_')
        .filter(|w| w.len() >= 3 && !STOP_WORDS.contains(&w.to_ascii_lowercase().as_str()))
    {
        let word_lower = word.to_ascii_lowercase();
        for tool in oxo_flow_ai::knowledge::bioconda::search_tools(word, 3) {
            // Keep only matches where the tool name actually contains the
            // word — summary-only matches are too loose to inject.
            if !tool.name.to_ascii_lowercase().contains(&word_lower) {
                continue;
            }
            if seen.insert(tool.name.clone()) {
                let summary = if tool.summary.is_empty() {
                    "(no description)".to_string()
                } else {
                    tool.summary.clone()
                };
                matched.push((tool.name.clone(), tool.version.clone(), summary));
            }
        }
    }
    matched
}

async fn create_env_from_ai(
    description: &std::path::Path,
    name: Option<String>,
    backend: &str,
) -> Result<()> {
    let description = description.to_string_lossy().to_string();
    let provider = crate::commands::ai_template::resolve_ai_provider()?;

    let is_pixi = backend.eq_ignore_ascii_case("pixi");
    if !is_pixi && !backend.eq_ignore_ascii_case("conda") {
        anyhow::bail!("unsupported backend '{}'. Use 'conda' or 'pixi'.", backend);
    }

    println!("{}", "AI Environment Generator".bold().green());
    println!(
        "  Model: {}",
        provider.model().unwrap_or_else(|| "default".into())
    );
    println!("  Backend: {}", if is_pixi { "pixi" } else { "conda" });
    println!("  Description: {description}\n");

    let matched = match_description_tools(&description);
    if !matched.is_empty() {
        eprintln!("{}", "  Matched Bioconda tools:".bold().cyan());
        for (name, version, summary) in &matched {
            eprintln!("    - {name} {version} — {summary}");
        }
    }

    let system = if is_pixi {
        format!(
            r#"## Role
You are a bioinformatics environment specialist. Generate a pixi environment
TOML file from the user's natural-language description.

## Tool Reference
{}

## Matched Bioconda Tools (real names + current versions)
{}

## Output Requirements
Generate ONLY valid pixi.toml inside ```toml code fences:

```toml
[project]
name = "env-name"
channels = ["conda-forge", "bioconda"]
platforms = ["linux-64"]

[dependencies]
tool = "version"
```

Rules:
- Pin every tool version using the Matched Bioconda Tools above when present; otherwise use your knowledge of current stable versions
- Include all tools the user mentions; add common companions if clearly needed
- channels order: conda-forge first, bioconda second (Bioconda's recommended channel setup)
- Do NOT add comments beyond the file header
"#,
            oxo_flow_ai::knowledge::builtin::format_tool_table(),
            if matched.is_empty() {
                "(none matched)".to_string()
            } else {
                matched
                    .iter()
                    .map(|(n, v, s)| format!("- {n} {v} — {s}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            }
        )
    } else {
        format!(
            r#"## Role
You are a bioinformatics environment specialist. Generate a conda environment
YAML file from the user's natural-language description.

## Tool Reference
{}

## Matched Bioconda Tools (real names + current versions)
{}

## Output Requirements
Generate ONLY valid conda environment YAML inside ```yaml code fences:

```yaml
# envs/<name>.yaml
name: <kebab-case-env-name>
channels:
  - conda-forge
  - bioconda
dependencies:
  - <tool>=<pinned-version>
```

Rules:
- Pin every tool version using the Matched Bioconda Tools above when present; otherwise use your knowledge of current stable versions
- Include all tools the user mentions; add common companions if clearly needed
- channels order: conda-forge first, bioconda second (Bioconda's recommended channel setup)
- Do NOT add comments beyond the file header
"#,
            oxo_flow_ai::knowledge::builtin::format_tool_table(),
            if matched.is_empty() {
                "(none matched)".to_string()
            } else {
                matched
                    .iter()
                    .map(|(n, v, s)| format!("- {n} {v} — {s}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            }
        )
    };

    println!("{}", "  Generating...".bold().cyan());
    use oxo_flow_ai::types::Message;
    let messages = vec![Message::system(&system), Message::user(&description)];
    let response = provider.chat_with_tools(&messages, &[]).await?;
    let response_text = response.content.unwrap_or_default();

    // Extract spec from code fence (YAML for conda, TOML for pixi)
    let spec_content = if is_pixi {
        extract_toml(&response_text)
            .ok_or_else(|| anyhow::anyhow!("AI response did not contain valid pixi TOML"))?
    } else {
        extract_yaml(&response_text)
            .ok_or_else(|| anyhow::anyhow!("AI response did not contain valid conda YAML"))?
    };

    // Basic structural validation
    let has_deps = spec_content.contains("dependencies");
    if !has_deps {
        anyhow::bail!("generated spec missing 'dependencies' section");
    }

    // Determine output path: -n <name> → envs/<name>.<ext>
    let ext = if is_pixi { "toml" } else { "yaml" };
    let env_name = name.unwrap_or_else(|| {
        let name_key = if is_pixi {
            spec_content.lines().find_map(|l| l.strip_prefix("name = "))
        } else {
            spec_content.lines().find_map(|l| l.strip_prefix("name:"))
        };
        name_key
            .map(|n| n.trim().trim_matches('"').trim_matches('\'').to_string())
            .filter(|n| !n.is_empty())
            .unwrap_or_else(|| "generated".to_string())
    });
    let out_path = std::path::PathBuf::from("envs").join(format!("{env_name}.{ext}"));
    if let Some(parent) = out_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&out_path, &spec_content)?;

    println!(
        "{} Environment spec written to {}",
        "✓".green(),
        out_path.display()
    );
    println!();
    println!(
        "  Review the spec: {}",
        out_path.display().to_string().dimmed()
    );
    println!(
        "  Then create it with: oxo-flow env create {}",
        out_path.display().to_string().dimmed()
    );
    Ok(())
}

/// Extract YAML content from an AI response (```yaml fence or raw).
fn extract_yaml(response: &str) -> Option<String> {
    if let Some(start) = response.find("```yaml") {
        let start = start + 7;
        if let Some(end) = response[start..].find("```") {
            let content = response[start..start + end].trim().to_string();
            if !content.is_empty() {
                return Some(content);
            }
        }
    }
    if let Some(pos) = response.find("name:") {
        return Some(response[pos..].trim().to_string());
    }
    None
}

/// Extract TOML content from an AI response (```toml fence or raw).
fn extract_toml(response: &str) -> Option<String> {
    if let Some(start) = response.find("```toml") {
        let start = start + 7;
        if let Some(end) = response[start..].find("```") {
            let content = response[start..start + end].trim().to_string();
            if !content.is_empty() {
                return Some(content);
            }
        }
    }
    if let Some(pos) = response.find("[project]") {
        return Some(response[pos..].trim().to_string());
    }
    None
}

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

    /// Stop words and short fragments must not match anything.
    #[test]
    fn description_matching_filters_stop_words_and_short_words() {
        let matched = match_description_tools("please align with using fastp for the data");
        assert!(
            matched.iter().any(|(name, _, _)| name == "fastp"),
            "fastp must be matched: {matched:?}"
        );
        for (name, _, _) in &matched {
            assert_ne!(name, "and");
            assert_ne!(name, "using");
            assert_ne!(name, "the");
        }
    }

    /// Only NAME-level matches are injected: a query word that only
    /// appears in a summary must not pull the tool in.
    #[test]
    fn description_matching_requires_name_level_hit() {
        let matched = match_description_tools("trimming");
        for (name, _, _) in &matched {
            assert!(
                name.to_ascii_lowercase().contains("trim"),
                "name-level match required, got {name}"
            );
        }
    }

    /// The same tool mentioned twice contributes once.
    #[test]
    fn description_matching_deduplicates_tools() {
        let matched = match_description_tools("fastp fastp fastp");
        let fastp_hits: Vec<_> = matched.iter().filter(|(n, _, _)| n == "fastp").collect();
        assert_eq!(fastp_hits.len(), 1, "fastp must appear once: {matched:?}");
    }

    /// A known tool mentioned in the description resolves to a pinned
    /// version from the embedded database.
    #[test]
    fn description_matching_pins_versions_from_knowledge_base() {
        let matched = match_description_tools("trim adapters with fastp and index with samtools");
        let fastp = matched.iter().find(|(n, _, _)| n == "fastp").unwrap();
        assert!(
            !fastp.1.is_empty(),
            "fastp must carry a version: {matched:?}"
        );
        assert!(
            !fastp.2.is_empty(),
            "fastp must carry a summary: {matched:?}"
        );
        assert!(
            matched.iter().any(|(n, _, _)| n == "samtools"),
            "samtools must be matched: {matched:?}"
        );
    }
}