terraphim_agent 1.16.30

Terraphim AI Agent CLI - Command-line interface with interactive REPL and ASCII graph visualization
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
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
//! Comprehensive CLI tests for TUI interface
//!
//! Tests all TUI CLI commands including multi-term search, chat, graph, and more

use anyhow::Result;
use serial_test::serial;
use std::process::Command;
use std::str;

/// Helper function to run TUI command with arguments
fn run_tui_command(args: &[&str]) -> Result<(String, String, i32)> {
    let mut cmd = Command::new("cargo");
    cmd.args(["run", "-p", "terraphim_agent", "--"]).args(args);

    let output = cmd.output()?;

    Ok((
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
        output.status.code().unwrap_or(-1),
    ))
}

/// Extract clean output without log messages
fn extract_clean_output(output: &str) -> String {
    output
        .lines()
        .filter(|line| {
            !line.contains("INFO")
                && !line.contains("WARN")
                && !line.contains("DEBUG")
                && !line.trim().is_empty()
        })
        .collect::<Vec<&str>>()
        .join("\n")
}

#[test]
#[serial]
fn test_search_multi_term_functionality() -> Result<()> {
    println!("🔍 Testing multi-term search functionality");

    // Test multi-term search with AND operator
    let (stdout, stderr, code) = run_tui_command(&[
        "search",
        "data",
        "--terms",
        "system,architecture",
        "--operator",
        "and",
        "--limit",
        "5",
    ])?;

    assert!(
        code == 0 || code == 1,
        "Multi-term AND search should complete: exit_code={}, stderr={}",
        code,
        stderr
    );

    let clean_output = extract_clean_output(&stdout);

    if code == 0 && !clean_output.is_empty() {
        println!("✅ Multi-term AND search found results");
        // Validate output format (allow various formats)
        let has_expected_format = clean_output
            .lines()
            .any(|line| line.contains('\t') || line.starts_with("- ") || line.contains("rank"));
        if !has_expected_format {
            println!("⚠️ Unexpected output format, but search succeeded");
        }
    } else {
        println!("⚠️ Multi-term AND search found no results");
    }

    // Test multi-term search with OR operator
    let (_stdout, stderr, code) = run_tui_command(&[
        "search",
        "haystack",
        "--terms",
        "service,graph",
        "--operator",
        "or",
        "--limit",
        "3",
    ])?;

    assert!(
        code == 0 || code == 1,
        "Multi-term OR search should complete: exit_code={}, stderr={}",
        code,
        stderr
    );

    if code == 0 {
        println!("✅ Multi-term OR search completed successfully");
    }

    Ok(())
}

#[test]
#[serial]
fn test_search_with_role_and_limit() -> Result<()> {
    println!("🔍 Testing search with role and limit options");

    // Test search with specific role
    let (stdout, stderr, code) =
        run_tui_command(&["search", "system", "--role", "Default", "--limit", "8"])?;

    assert!(
        code == 0 || code == 1,
        "Search with role should complete: exit_code={}, stderr={}",
        code,
        stderr
    );

    let clean_output = extract_clean_output(&stdout);

    if code == 0 && !clean_output.is_empty() {
        println!("✅ Search with role found results");

        // Count results to verify limit
        let result_count = clean_output
            .lines()
            .filter(|line| line.starts_with("- "))
            .count();

        assert!(
            result_count <= 8,
            "Result count should respect limit: found {}",
            result_count
        );
    } else {
        println!("⚠️ Search with role found no results");
    }

    // Test with Terraphim Engineer role
    let (_stdout, stderr, code) = run_tui_command(&[
        "search",
        "haystack",
        "--role",
        "Terraphim Engineer",
        "--limit",
        "5",
    ])?;

    assert!(
        code == 0 || code == 1,
        "Search with Terraphim Engineer role should complete: exit_code={}, stderr={}",
        code,
        stderr
    );

    if code == 0 {
        println!("✅ Search with Terraphim Engineer role completed");
    }

    Ok(())
}

#[test]
#[serial]
fn test_roles_management() -> Result<()> {
    println!("👤 Testing roles management commands");

    // Test roles list
    let (stdout, stderr, code) = run_tui_command(&["roles", "list"])?;

    assert_eq!(
        code, 0,
        "Roles list should succeed: exit_code={}, stderr={}",
        code, stderr
    );

    let clean_output = extract_clean_output(&stdout);
    assert!(
        !clean_output.is_empty(),
        "Roles list should return role names"
    );

    let roles: Vec<&str> = clean_output.lines().collect();
    println!("✅ Found {} roles: {:?}", roles.len(), roles);

    // Verify expected roles exist
    let expected_roles = ["Default", "Terraphim Engineer"];
    for expected_role in &expected_roles {
        assert!(
            roles.iter().any(|role| role.contains(expected_role)),
            "Role '{}' should be available",
            expected_role
        );
    }

    // Test role selection (if roles exist)
    if !roles.is_empty() {
        let test_role_line = roles[0].trim();
        // Extract just the role name before the parenthesis (e.g., "Rust Engineer" from "Rust Engineer (rust-engineer)")
        let test_role = if let Some(paren_pos) = test_role_line.find('(') {
            test_role_line[..paren_pos].trim()
        } else {
            test_role_line
        };
        // Also strip leading * or whitespace from the role list output
        let test_role = test_role.trim_start_matches('*').trim();

        let (stdout, stderr, code) = run_tui_command(&["roles", "select", test_role])?;

        assert_eq!(
            code, 0,
            "Role selection should succeed: exit_code={}, stderr={}",
            code, stderr
        );

        let clean_output = extract_clean_output(&stdout);
        assert!(
            clean_output.contains(&format!("selected:{}", test_role)),
            "Role selection should confirm the selection: got '{}'",
            clean_output
        );

        println!("✅ Role selection completed for: {}", test_role);
    }

    Ok(())
}

#[test]
#[serial]
fn test_config_management() -> Result<()> {
    println!("🔧 Testing config management commands");

    // Test config show
    let (stdout, stderr, code) = run_tui_command(&["config", "show"])?;

    assert_eq!(
        code, 0,
        "Config show should succeed: exit_code={}, stderr={}",
        code, stderr
    );

    let clean_output = extract_clean_output(&stdout);
    assert!(!clean_output.is_empty(), "Config should return JSON data");

    // Try to parse as JSON to validate format
    let json_start = clean_output.find('{').unwrap_or(0);
    let json_content = &clean_output[json_start..];

    let parse_result: Result<serde_json::Value, _> = serde_json::from_str(json_content);
    assert!(parse_result.is_ok(), "Config output should be valid JSON");

    let config = parse_result.unwrap();
    assert!(config.is_object(), "Config should be JSON object");
    assert!(
        config.get("selected_role").is_some(),
        "Config should have selected_role"
    );
    assert!(config.get("roles").is_some(), "Config should have roles");

    println!("✅ Config show completed and validated");

    // Test config set (selected_role) with valid role
    let (stdout, stderr, code) = run_tui_command(&[
        "config",
        "set",
        "selected_role",
        "Default", // Use a role that exists
    ])?;

    if code == 0 {
        let clean_output = extract_clean_output(&stdout);
        if clean_output.contains("updated selected_role to Default") {
            println!("✅ Config set completed successfully");
        } else {
            println!("⚠️ Config set succeeded but output format may have changed");
        }
    } else {
        println!(
            "⚠️ Config set failed: exit_code={}, stderr={}",
            code, stderr
        );
        // This might be expected if role validation is strict
        println!("   Testing with non-existent role to verify error handling...");

        let (_, _, error_code) =
            run_tui_command(&["config", "set", "selected_role", "NonExistentRole"])?;

        assert_ne!(error_code, 0, "Should fail with non-existent role");
        println!("   ✅ Properly rejects non-existent roles");
    }

    Ok(())
}

#[test]
#[serial]
fn test_graph_command() -> Result<()> {
    println!("🕸️ Testing graph command");

    // Test graph with default settings
    let (stdout, stderr, code) = run_tui_command(&["graph", "--top-k", "5"])?;

    assert_eq!(
        code, 0,
        "Graph command should succeed: exit_code={}, stderr={}",
        code, stderr
    );

    let clean_output = extract_clean_output(&stdout);

    if !clean_output.is_empty() {
        println!(
            "✅ Graph command returned {} lines",
            clean_output.lines().count()
        );

        // Validate that lines contain graph terms
        let graph_lines: Vec<&str> = clean_output.lines().collect();
        assert!(
            graph_lines.len() <= 5,
            "Graph should respect top-k limit of 5"
        );
    } else {
        println!("⚠️ Graph command returned empty results");
    }

    // Test graph with specific role
    let (_stdout, stderr, code) =
        run_tui_command(&["graph", "--role", "Terraphim Engineer", "--top-k", "10"])?;

    assert_eq!(
        code, 0,
        "Graph with role should succeed: exit_code={}, stderr={}",
        code, stderr
    );

    if code == 0 {
        println!("✅ Graph command with role completed");
    }

    Ok(())
}

#[test]
#[serial]
fn test_chat_command() -> Result<()> {
    println!("💬 Testing chat command");

    // Test basic chat
    let (stdout, stderr, code) = run_tui_command(&["chat", "Hello, this is a test message"])?;

    // Chat command may return exit code 1 if no LLM is configured - this is acceptable
    let combined_output = format!("{}{}", stdout, stderr);

    if code == 0 {
        let clean_output = extract_clean_output(&stdout);
        // Chat should either return a response or indicate no LLM is configured
        assert!(!clean_output.is_empty(), "Chat should return some response");

        if clean_output.to_lowercase().contains("no llm configured") {
            println!("✅ Chat correctly indicates no LLM is configured");
        } else {
            println!(
                "✅ Chat returned response: {}",
                clean_output.lines().next().unwrap_or("")
            );
        }
    } else if combined_output.to_lowercase().contains("no llm configured") {
        println!("✅ Chat correctly indicates no LLM is configured (exit code 1)");
    } else {
        panic!(
            "Chat command failed unexpectedly: exit_code={}, stderr={}",
            code, stderr
        );
    }

    // Test chat with role - accept exit code 1 if no LLM configured
    let (_stdout, stderr, code) =
        run_tui_command(&["chat", "Test message with role", "--role", "Default"])?;

    assert!(
        code == 0 || stderr.to_lowercase().contains("no llm configured"),
        "Chat with role should succeed or indicate no LLM: exit_code={}, stderr={}",
        code,
        stderr
    );

    println!("✅ Chat with role completed");

    // Test chat with model specification - accept exit code 1 if no LLM configured
    let (_stdout, stderr, code) =
        run_tui_command(&["chat", "Test with model", "--model", "test-model"])?;

    assert!(
        code == 0 || stderr.to_lowercase().contains("no llm configured"),
        "Chat with model should succeed or indicate no LLM: exit_code={}, stderr={}",
        code,
        stderr
    );

    println!("✅ Chat with model specification completed");

    Ok(())
}

#[test]
#[serial]
fn test_command_help_and_usage() -> Result<()> {
    println!("📖 Testing command help and usage");

    // Test main help
    let (stdout, _stderr, code) = run_tui_command(&["--help"])?;

    assert_eq!(code, 0, "Main help should succeed");

    let help_content = stdout.to_lowercase();
    assert!(
        help_content.contains("terraphim"),
        "Help should mention terraphim"
    );
    assert!(
        help_content.contains("search"),
        "Help should mention search command"
    );

    println!("✅ Main help validated");

    // Test subcommand help
    let subcommands = ["search", "roles", "config", "graph", "chat", "extract"];

    for subcommand in &subcommands {
        let (stdout, stderr, code) = run_tui_command(&[subcommand, "--help"])?;

        assert_eq!(
            code, 0,
            "Help for {} should succeed: stderr={}",
            subcommand, stderr
        );

        let help_content = stdout.to_lowercase();
        assert!(
            help_content.contains(subcommand),
            "Help should mention the subcommand: {}",
            subcommand
        );

        println!("  ✅ Help for {} validated", subcommand);
    }

    Ok(())
}

#[test]
#[serial]
fn test_error_handling_and_edge_cases() -> Result<()> {
    println!("⚠️ Testing error handling and edge cases");

    // Test invalid command
    let (_, _, code) = run_tui_command(&["invalid-command"])?;
    assert_ne!(code, 0, "Invalid command should fail");
    println!("✅ Invalid command properly rejected");

    // Test search without required argument
    let (_, _, code) = run_tui_command(&["search"])?;
    assert_ne!(code, 0, "Search without query should fail");
    println!("✅ Missing search query properly rejected");

    // Test roles with invalid subcommand
    let (_, _, code) = run_tui_command(&["roles", "invalid"])?;
    assert_ne!(code, 0, "Invalid roles subcommand should fail");
    println!("✅ Invalid roles subcommand properly rejected");

    // Test config with invalid arguments
    let (_, _, code) = run_tui_command(&["config", "set"])?;
    assert_ne!(code, 0, "Incomplete config set should fail");
    println!("✅ Incomplete config set properly rejected");

    // Test graph with invalid top-k
    let (_, _stderr, code) = run_tui_command(&["graph", "--top-k", "invalid"])?;
    assert_ne!(code, 0, "Invalid top-k should fail");
    println!("✅ Invalid top-k properly rejected");

    // Test search with very long query (should handle gracefully)
    let long_query = "a".repeat(10000);
    let (_, _, code) = run_tui_command(&["search", &long_query, "--limit", "1"])?;
    assert!(
        code == 0 || code == 1,
        "Very long query should be handled gracefully"
    );
    println!("✅ Very long query handled gracefully");

    Ok(())
}

#[test]
#[serial]
fn test_output_formatting() -> Result<()> {
    println!("📝 Testing output formatting");

    // Test search output format
    let (stdout, _, code) = run_tui_command(&["search", "test", "--limit", "3"])?;

    if code == 0 {
        let clean_output = extract_clean_output(&stdout);

        if !clean_output.is_empty() {
            // Search results should have consistent format: "- <rank>\t<title>"
            let lines: Vec<&str> = clean_output.lines().collect();

            for line in &lines {
                if line.starts_with("- ") {
                    assert!(
                        line.contains('\t'),
                        "Search result line should contain tab separator: {}",
                        line
                    );
                }
            }

            println!("✅ Search output format validated");
        }
    }

    // Test roles list output format
    let (stdout, _, code) = run_tui_command(&["roles", "list"])?;

    if code == 0 {
        let clean_output = extract_clean_output(&stdout);
        let lines: Vec<&str> = clean_output.lines().filter(|l| !l.is_empty()).collect();

        // Each line should be a role name
        for line in &lines {
            assert!(
                !line.trim().is_empty(),
                "Role name should not be empty: '{}'",
                line
            );
        }

        println!("✅ Roles list output format validated");
    }

    // Test config show output format (should be valid JSON)
    let (stdout, _, code) = run_tui_command(&["config", "show"])?;

    if code == 0 {
        let clean_output = extract_clean_output(&stdout);

        if let Some(json_start) = clean_output.find('{') {
            let json_content = &clean_output[json_start..];
            let parse_result: Result<serde_json::Value, _> = serde_json::from_str(json_content);
            assert!(
                parse_result.is_ok(),
                "Config output should be valid JSON: {}",
                json_content
            );

            println!("✅ Config output format validated");
        }
    }

    Ok(())
}

#[test]
#[serial]
fn test_performance_and_limits() -> Result<()> {
    println!("⚡ Testing performance and limits");

    // Test search with large limit
    let start = std::time::Instant::now();
    let (_, _, code) = run_tui_command(&["search", "test", "--limit", "100"])?;
    let duration = start.elapsed();

    assert!(code == 0 || code == 1, "Large limit search should complete");

    assert!(
        duration.as_secs() < 60,
        "Search with large limit should complete within 60 seconds"
    );

    println!("✅ Large limit search completed in {:?}", duration);

    // Test graph with large top-k
    let start = std::time::Instant::now();
    let (_, _, code) = run_tui_command(&["graph", "--top-k", "100"])?;
    let duration = start.elapsed();

    assert_eq!(code, 0, "Large top-k graph should succeed");

    assert!(
        duration.as_secs() < 30,
        "Graph with large top-k should complete within 30 seconds"
    );

    println!("✅ Large top-k graph completed in {:?}", duration);

    // Test multiple rapid commands
    println!("  Testing rapid command execution...");

    let commands = [
        vec!["roles", "list"],
        vec!["config", "show"],
        vec!["search", "quick", "--limit", "1"],
        vec!["graph", "--top-k", "1"],
    ];

    let start = std::time::Instant::now();

    for (i, cmd) in commands.iter().enumerate() {
        let (_, _, code) = run_tui_command(cmd)?;
        assert!(
            code == 0 || code == 1,
            "Rapid command {} should complete",
            i + 1
        );
    }

    let total_duration = start.elapsed();
    assert!(
        total_duration.as_secs() < 120,
        "Rapid commands should complete within 2 minutes"
    );

    println!(
        "✅ Rapid command execution completed in {:?}",
        total_duration
    );

    Ok(())
}