cmdhub-cli 0.1.0

cmdh — the CmdHub CLI client for offline command search and execution
Documentation
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
use cmdhub_cli::config::OFFICIAL_PUBLIC_KEY;
use cmdhub_cli::config::{load_or_create_config, resolve_config_path};
use cmdhub_cli::db::{init_db, open_db, search_commands};
use cmdhub_cli::runner::{get_command_by_path, run_command};
use cmdhub_shared::RiskLevel;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use ed25519_dalek::{Signer, SigningKey};
use sha2::{Digest, Sha256};
use std::sync::Mutex;
use tempfile::TempDir;

static ENV_MUTEX: Mutex<()> = Mutex::new(());

#[test]
fn test_config_resolution() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let config_dir = tmp.path().to_path_buf();

    // Set XDG_CONFIG_HOME to the temp directory
    std::env::set_var("XDG_CONFIG_HOME", &config_dir);

    // Load or create config (should create it)
    let config = load_or_create_config(None).unwrap();
    assert_eq!(config.api_url, "https://api.cmdhub.io/v1");
    assert_eq!(config.timeout_seconds, 30);

    // Verify it exists in config path
    let expected_path = resolve_config_path(None);
    assert!(expected_path.exists());
}

#[test]
fn test_config_env_override() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let env_config_path = tmp.path().join("env_config.toml");

    // Set CMDH_CONFIG env var
    std::env::set_var("CMDH_CONFIG", &env_config_path);

    // Loading should fail because the override file does not exist
    let result = load_or_create_config(None);
    assert!(result.is_err());

    // Create the file
    let default_config = cmdhub_cli::config::Config::default();
    let toml_str = toml::to_string_pretty(&default_config).unwrap();
    std::fs::write(&env_config_path, toml_str).unwrap();

    // Now loading should succeed
    let config = load_or_create_config(None).unwrap();
    assert_eq!(config.api_url, "https://api.cmdhub.io/v1");

    // Verify it exists at the exact CMDH_CONFIG path
    let expected_path = resolve_config_path(None);
    assert_eq!(expected_path, env_config_path);
    assert!(expected_path.exists());

    // Clean up env var so it doesn't affect other tests
    std::env::remove_var("CMDH_CONFIG");
}

#[test]
fn test_config_custom_path_override() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let custom_path = tmp.path().join("custom_config.toml");

    // Loading should fail because the custom path does not exist
    let result = load_or_create_config(Some(custom_path.clone()));
    assert!(result.is_err());

    // Create the file
    let default_config = cmdhub_cli::config::Config::default();
    let toml_str = toml::to_string_pretty(&default_config).unwrap();
    std::fs::write(&custom_path, toml_str).unwrap();

    // Now loading with custom path should succeed
    let config = load_or_create_config(Some(custom_path.clone())).unwrap();
    assert_eq!(config.api_url, "https://api.cmdhub.io/v1");

    // Verify it exists at the exact custom path
    let expected_path = resolve_config_path(Some(custom_path.clone()));
    assert_eq!(expected_path, custom_path);
    assert!(expected_path.exists());
}

#[test]
fn test_search_fallback_and_db() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let data_dir = tmp.path().to_path_buf();

    // Set XDG_DATA_HOME to temp dir
    std::env::set_var("XDG_DATA_HOME", &data_dir);

    let conn = open_db().unwrap();
    init_db(&conn).unwrap();

    // Insert dummy records for app and argument
    conn.execute(
        "INSERT INTO apps (app_id, name, install_instructions) VALUES (?1, ?2, ?3)",
        ("org.github.sl", "sl", "{\"brew\": \"brew install sl\"}"),
    )
    .unwrap();

    conn.execute(
        "INSERT INTO arguments (cmd_path, app_id, node_name, node_type, description, risk_level, example_template) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        (
            "sl.-l",
            "org.github.sl",
            "-l",
            "arg",
            "Display a train moving from left to right",
            "safe",
            "sl -l",
        ),
    ).unwrap();

    // Insert into FTS5 virtual table
    conn.execute(
        "INSERT INTO apps_fts (cmd_path, name, capabilities) VALUES (?1, ?2, ?3)",
        ("sl.-l", "sl", "Display a train moving from left to right"),
    )
    .unwrap();

    // Search and verify fallback to pure FTS5 works
    let results = search_commands(&conn, "train", None, 5).unwrap();
    assert_eq!(results.len(), 1);

    let command = &results[0];
    assert_eq!(command.cmd_path, "sl.-l");
    assert_eq!(command.app_id, "org.github.sl");
    assert_eq!(command.name, "sl");
    assert_eq!(command.risk_level, RiskLevel::Safe);
    assert_eq!(command.example_template, Some("sl -l".to_string()));
    assert_eq!(
        command.install_instructions.as_ref().unwrap().brew,
        Some("brew install sl".to_string())
    );
}

#[test]
fn test_safety_gating() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let data_dir = tmp.path().to_path_buf();

    // Set XDG_DATA_HOME to temp dir
    std::env::set_var("XDG_DATA_HOME", &data_dir);
    std::env::set_var("CMD_TEST", "1");

    let conn = open_db().unwrap();
    init_db(&conn).unwrap();

    // Insert a dangerous command (we mock it as "echo" for child process testing)
    conn.execute(
        "INSERT INTO apps (app_id, name, install_instructions) VALUES (?1, ?2, ?3)",
        ("org.test.echo", "echo", None::<String>),
    )
    .unwrap();

    conn.execute(
        "INSERT INTO arguments (cmd_path, app_id, node_name, node_type, description, risk_level, example_template) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        (
            "echo.danger",
            "org.test.echo",
            "danger",
            "arg",
            "Dangerous echo",
            "dangerous",
            "echo danger",
        ),
    ).unwrap();

    // Retrieve from DB
    let cmd = get_command_by_path(&conn, "echo.danger").unwrap();
    assert_eq!(cmd.risk_level, RiskLevel::Dangerous);

    // Test bypass gate
    let result = run_command(&conn, "echo.danger", &["hello".to_string()], true);
    assert!(result.is_ok());

    // Test dangerous blocked when skip_gating is false and stdin is not interactive (fails read_line)
    let result = run_command(&conn, "echo.danger", &["hello".to_string()], false);
    assert!(result.is_err());
    let err_str = format!("{}", result.unwrap_err());
    assert!(
        err_str.contains("blocked")
            || err_str.contains("read_line")
            || err_str.contains("standard input")
    );
}

#[test]
fn test_signature_verification_and_zstd() {
    // Generate deterministic key pair using [42; 32] seed
    let seed = [42u8; 32];
    let signing_key = SigningKey::from_bytes(&seed);
    let verifying_key = signing_key.verifying_key();
    let pub_key_bytes = verifying_key.to_bytes();

    // Ensure the deterministic key matches the OFFICIAL_PUBLIC_KEY constant
    assert_eq!(pub_key_bytes, OFFICIAL_PUBLIC_KEY);

    // Dummy DB content
    let db_payload = b"SQLite dummy content";

    // Decompress/compress zstd
    let compressed = zstd::encode_all(&db_payload[..], 3).unwrap();

    // Compute SHA-256
    let mut hasher = Sha256::new();
    hasher.update(&compressed);
    let hash_result: [u8; 32] = hasher.finalize().into();

    // Sign using private key
    let signature = signing_key.sign(&hash_result);
    let sig_bytes = signature.to_bytes();

    // Verify signature using pubkey
    let verifying_key_dec = VerifyingKey::from_bytes(&pub_key_bytes).unwrap();
    let sig_dec = Signature::from_slice(&sig_bytes).unwrap();
    let verify_res = verifying_key_dec.verify(&hash_result, &sig_dec);
    assert!(verify_res.is_ok());

    // Decompress payload
    let decompressed = zstd::decode_all(&compressed[..]).unwrap();
    assert_eq!(decompressed, db_payload);
}

#[test]
fn test_skills_integration() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let config_dir = tmp.path().to_path_buf();

    // Set XDG_CONFIG_HOME and XDG_DATA_HOME to temp dirs
    std::env::set_var("XDG_CONFIG_HOME", &config_dir);
    std::env::set_var("XDG_DATA_HOME", &config_dir);

    // Load db and init
    let conn = open_db().unwrap();
    init_db(&conn).unwrap();

    // Create a mock skills JSON file inside skills_dir
    let skills_dir = config_dir.join("cmdhub").join("skills");
    std::fs::create_dir_all(&skills_dir).unwrap();

    let contract_custom = cmdhub_shared::AciCommandContract {
        app_id: "org.test.custom".to_string(),
        name: "custom_cmd".to_string(),
        cmd_path: "custom.run".to_string(),
        node_type: cmdhub_shared::NodeType::Root,
        description: "A completely custom command shortcut loaded from skills".to_string(),
        risk_level: RiskLevel::Safe,
        example_template: Some("custom_cmd --do-something".to_string()),
        install_instructions: None,
        docker_image: None,
        script_url: None,
        source_url: None,
    };

    let json_content = serde_json::to_string(&contract_custom).unwrap();
    std::fs::write(skills_dir.join("custom.json"), json_content).unwrap();

    // Search query using search_all and verify it successfully recalls the skill command!
    let results = search_commands(&conn, "completely", None, 5).unwrap();
    assert!(results.is_empty()); // Should be empty in pure DB search

    let results_all = cmdhub_cli::db::search_all(&conn, "completely", None, 5).unwrap();
    assert_eq!(results_all.len(), 1);
    assert_eq!(results_all[0].name, "custom_cmd");
    assert_eq!(results_all[0].cmd_path, "custom.run");
}

#[test]
fn test_config_override_strict_validation() {
    use assert_cmd::Command;
    let mut cmd = Command::cargo_bin("cmdh").unwrap();
    cmd.arg("--config")
        .arg("non_existent_config_abc_123.toml")
        .arg("search")
        .arg("test");
    cmd.assert()
        .failure()
        .stderr(predicates::str::contains("does not exist"));
}

#[test]
fn test_output_preset_formatting() {
    let _guard = ENV_MUTEX.lock().unwrap();
    use assert_cmd::Command;
    let tmp = tempfile::TempDir::new().unwrap();
    let data_dir = tmp.path().to_path_buf();

    // Set XDG_DATA_HOME to temp dir
    std::env::set_var("XDG_DATA_HOME", &data_dir);

    let conn = open_db().unwrap();
    init_db(&conn).unwrap();

    conn.execute(
        "INSERT INTO apps (app_id, name, install_instructions) VALUES (?1, ?2, ?3)",
        ("org.github.git", "git", "{\"brew\": \"brew install git\"}"),
    )
    .unwrap();

    conn.execute(
        "INSERT INTO arguments (cmd_path, app_id, node_name, node_type, description, risk_level, example_template) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        (
            "git",
            "org.github.git",
            "git",
            "root",
            "git version control",
            "safe",
            "example_template",
        ),
    ).unwrap();

    conn.execute(
        "INSERT INTO apps_fts (cmd_path, name, capabilities) VALUES (?1, ?2, ?3)",
        ("git", "git", "git version control"),
    )
    .unwrap();

    drop(conn);

    let mut cmd = Command::cargo_bin("cmdh").unwrap();
    cmd.env("XDG_DATA_HOME", &data_dir)
        .arg("search")
        .arg("git")
        .arg("--usage-only");
    let assert = cmd.assert().success();
    let output = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(output.contains("cmd_path"));
    assert!(output.contains("example_template"));
    assert!(!output.contains("risk_level"));
}

#[test]
fn test_init_command_safety_guards() {
    use assert_cmd::Command;
    let tmp = tempfile::TempDir::new().unwrap();
    let config_path = tmp.path().join("cmdhub/config.toml");

    // Seed file
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(&config_path, "dummy").unwrap();

    // Test guard warning exits gracefully (exit code 0)
    let mut cmd = Command::cargo_bin("cmdh").unwrap();
    cmd.env("XDG_CONFIG_HOME", tmp.path()).arg("init");
    cmd.assert().success();

    let val = std::fs::read_to_string(&config_path).unwrap();
    assert_eq!(val, "dummy"); // Should not have changed

    // Overwrite with force
    let mut cmd_force = Command::cargo_bin("cmdh").unwrap();
    cmd_force
        .env("XDG_CONFIG_HOME", tmp.path())
        .arg("init")
        .arg("--force");
    cmd_force.assert().success();

    let val_overwritten = std::fs::read_to_string(&config_path).unwrap();
    assert!(val_overwritten.contains("CmdHub configuration file"));
}

#[test]
fn test_completions_generation() {
    use assert_cmd::Command;
    let mut cmd = Command::cargo_bin("cmdh").unwrap();
    cmd.arg("completions").arg("zsh");
    let assert = cmd.assert().success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(stdout.contains("compdef") || stdout.contains("#defzsh"));
}

#[test]
fn test_expanded_aci_fields_roundtrip() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = tempfile::TempDir::new().unwrap();
    let data_dir = tmp.path().to_path_buf();
    std::env::set_var("XDG_DATA_HOME", &data_dir);

    let conn = open_db().unwrap();
    init_db(&conn).unwrap();

    conn.execute(
        "INSERT INTO apps (app_id, name, install_instructions) VALUES (?1, ?2, ?3)",
        (
            "org.test.extended",
            "ext",
            "{\"brew\": \"brew install ext\", \"scoop\": \"scoop install ext\"}",
        ),
    )
    .unwrap();

    conn.execute(
        "INSERT INTO arguments (cmd_path, app_id, node_name, node_type, description, risk_level, example_template, docker_image, script_url, source_url) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
        (
            "ext",
            "org.test.extended",
            "ext",
            "root",
            "extended commands",
            "safe",
            "ext --test",
            Some("docker.io/test/ext:latest"),
            Some("https://raw.githubusercontent.com/test/ext/main/install.sh"),
            Some("https://github.com/test/ext"),
        ),
    ).unwrap();

    conn.execute(
        "INSERT INTO apps_fts (cmd_path, name, capabilities) VALUES (?1, ?2, ?3)",
        ("ext", "ext", "extended commands"),
    )
    .unwrap();

    drop(conn);

    use assert_cmd::Command;
    let mut cmd = Command::cargo_bin("cmdh").unwrap();
    cmd.env("XDG_DATA_HOME", &data_dir)
        .arg("search")
        .arg("ext")
        .arg("--full");

    let assert = cmd.assert().success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(stdout.contains("\"docker_image\":\"docker.io/test/ext:latest\""));
    assert!(stdout
        .contains("\"script_url\":\"https://raw.githubusercontent.com/test/ext/main/install.sh\""));
    assert!(stdout.contains("\"source_url\":\"https://github.com/test/ext\""));
}

#[test]
fn test_windows_scoop_install_suggestions() {
    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = tempfile::TempDir::new().unwrap();
    let data_dir = tmp.path().to_path_buf();
    std::env::set_var("XDG_DATA_HOME", &data_dir);
    std::env::set_var("XDG_CONFIG_HOME", &data_dir);

    // Write a config overrides stating OS is windows
    let config_path = data_dir.join("cmdhub/config.toml");
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();

    let mut config = cmdhub_cli::config::Config::default();
    config.install.os = Some("windows".to_string());
    config.install.package_managers = vec!["scoop".to_string(), "cargo".to_string()];
    let toml_str = toml::to_string_pretty(&config).unwrap();
    std::fs::write(&config_path, toml_str).unwrap();

    let conn = open_db().unwrap();
    init_db(&conn).unwrap();

    conn.execute(
        "INSERT INTO apps (app_id, name, install_instructions) VALUES (?1, ?2, ?3)",
        (
            "org.test.win",
            "win",
            "{\"scoop\": \"scoop install win\", \"brew\": \"brew install win\"}",
        ),
    )
    .unwrap();

    conn.execute(
        "INSERT INTO arguments (cmd_path, app_id, node_name, node_type, description, risk_level, example_template, docker_image, script_url, source_url) \
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
        (
            "win",
            "org.test.win",
            "win",
            "root",
            "windows commands",
            "safe",
            "win --test",
            None::<String>,
            None::<String>,
            None::<String>,
        ),
    ).unwrap();

    conn.execute(
        "INSERT INTO apps_fts (cmd_path, name, capabilities) VALUES (?1, ?2, ?3)",
        ("win", "win", "windows commands"),
    )
    .unwrap();

    drop(conn);

    use assert_cmd::Command;
    let mut cmd = Command::cargo_bin("cmdh").unwrap();
    cmd.env("XDG_DATA_HOME", &data_dir)
        .env("XDG_CONFIG_HOME", &data_dir)
        .arg("search")
        .arg("win")
        .arg("--full");

    let assert = cmd.assert().success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(stdout.contains("\"install_command\":\"scoop install win\""));
}

#[tokio::test]
async fn test_auto_model_download() {
    use sha2::{Digest, Sha256};
    use std::io::{Read, Write};
    use std::net::TcpListener;
    use std::thread;

    let _guard = ENV_MUTEX.lock().unwrap();
    let tmp = TempDir::new().unwrap();
    let cache_dir = tmp.path().to_path_buf();

    // Prepare mock data
    let mock_data = b"mock onnx model content".to_vec();
    let mut hasher = Sha256::new();
    hasher.update(&mock_data);
    let mock_sha256 = format!("{:x}", hasher.finalize());

    // Start ephemeral mock server
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let server_url = format!("http://127.0.0.1:{}", port);

    let mock_data_clone = mock_data.clone();
    let _server_thread = thread::spawn(move || {
        if let Ok((mut stream, _)) = listener.accept() {
            let mut buffer = [0; 1024];
            let _ = stream.read(&mut buffer);

            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                mock_data_clone.len()
            );
            let _ = stream.write_all(response.as_bytes());
            let _ = stream.write_all(&mock_data_clone);
            let _ = stream.flush();
        }
    });

    // Set configuration variables
    let config_path = cache_dir.join("cmdhub/config.toml");
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();

    let temp_model_path = cache_dir.join("cmdhub/models/bge-micro-v2.onnx");

    let mut config = cmdhub_cli::config::Config::default();
    config.vector.model_url = Some(server_url);
    config.vector.model_sha256 = Some(mock_sha256);
    config.vector.model_path = Some(temp_model_path.to_string_lossy().to_string());

    drop(_guard);

    // Trigger ensure_model_installed
    let path = cmdhub_cli::installer::ensure_model_installed(&config)
        .await
        .unwrap();
    assert_eq!(path, temp_model_path);
    assert!(temp_model_path.exists());

    let downloaded_content = std::fs::read(&temp_model_path).unwrap();
    assert_eq!(downloaded_content, mock_data);
}