-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.rs
More file actions
5512 lines (5192 loc) · 210 KB
/
Copy pathmain.rs
File metadata and controls
5512 lines (5192 loc) · 210 KB
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::io;
use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, Subcommand};
use crossterm::{
event::{
self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyModifiers,
},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::Line,
widgets::{Block, Borders, List, ListItem, Paragraph},
};
use serde::Serialize;
use terraphim_persistence::Persistable;
use tokio::runtime::Runtime;
#[cfg(feature = "server")]
mod client;
mod tui_backend;
mod guard_patterns;
mod listener;
mod onboarding;
mod service;
#[allow(dead_code)]
mod shell_dispatch;
// Robot mode and forgiving CLI - always available
mod forgiving;
mod robot;
// Learning capture for failed commands
mod learnings;
// KG-based command validation for PreToolUse hook pipeline
mod kg_validation;
#[cfg(feature = "repl")]
mod repl;
#[cfg(feature = "server")]
use client::{ApiClient, SearchResponse};
use service::TuiService;
use terraphim_types::{
Document, Layer, LogicalOperator, NormalizedTermValue, RoleName, SearchQuery,
};
use terraphim_update::{TerraphimUpdater, UpdaterConfig};
#[derive(clap::ValueEnum, Debug, Clone)]
enum LogicalOperatorCli {
And,
Or,
}
/// Truncate a snippet at a UTF-8 char boundary, appending "..." when truncated.
///
/// Naive `&s[..max]` panics when `max` lands inside a multi-byte char (e.g. typographic
/// quotes from email subjects). This walks char boundaries and stops at the last one
/// whose byte index is ≤ max.
fn truncate_snippet(s: &str, max_bytes: usize) -> String {
if s.len() <= max_bytes {
return s.to_string();
}
let cutoff = s
.char_indices()
.map(|(i, _)| i)
.take_while(|&i| i <= max_bytes)
.last()
.unwrap_or(0);
format!("{}...", &s[..cutoff])
}
#[cfg(test)]
mod truncate_snippet_tests {
use super::truncate_snippet;
#[test]
fn short_string_unchanged() {
assert_eq!(truncate_snippet("hello", 120), "hello");
}
#[test]
fn ascii_truncated() {
let s = "a".repeat(200);
let out = truncate_snippet(&s, 120);
assert!(out.ends_with("..."));
assert_eq!(out.len(), 123);
}
#[test]
fn multibyte_does_not_panic() {
// Reproduces crates/terraphim_agent/src/main.rs:1414 panic where
// `&s[..120]` landed inside a typographic quote (3 bytes: e2 80 9c).
let s = "Includes dependencies for llama.cpp, integration with retreival, and CLI/GUI flows; the project positions itself as \u{201C}ultimate open-source RAG app\u{201D} with curated features.";
let out = truncate_snippet(s, 120);
// Must not panic and must be a valid UTF-8 string ending in "..."
assert!(out.ends_with("..."));
assert!(out.is_char_boundary(out.len()));
}
#[test]
fn cyrillic_safe() {
let s = "консенсус ".repeat(20);
let out = truncate_snippet(&s, 120);
assert!(out.ends_with("..."));
}
}
/// Format the one-line stderr explainability message emitted when the search
/// command auto-routes (i.e. the user did not pass `--role`).
///
/// Exact format pinned by the design (section 5):
/// `[auto-route] picked role "<name>" (score=<n>, candidates=<m>); to override, pass --role`
fn format_auto_route_line(result: &terraphim_service::auto_route::AutoRouteResult) -> String {
format!(
"[auto-route] picked role \"{}\" (score={}, candidates={}); to override, pass --role",
result.role.as_str(),
result.score,
result.candidates.len(),
)
}
#[cfg(test)]
mod format_auto_route_line_tests {
use super::format_auto_route_line;
use terraphim_service::auto_route::{AutoRouteReason, AutoRouteResult};
use terraphim_types::RoleName;
#[test]
fn pinned_exact_format() {
let r = AutoRouteResult {
role: RoleName::new("Personal Assistant"),
score: 42,
candidates: vec![
(RoleName::new("Personal Assistant"), 42),
(RoleName::new("Default"), 0),
],
reason: AutoRouteReason::ScoredWinner,
};
assert_eq!(
format_auto_route_line(&r),
"[auto-route] picked role \"Personal Assistant\" (score=42, candidates=2); to override, pass --role"
);
}
}
/// Show helpful usage information when run without a TTY
fn show_usage_info() {
println!("Terraphim AI Agent v{}", env!("CARGO_PKG_VERSION"));
println!();
println!("Interactive Modes (requires TTY):");
println!(" terraphim-agent # Start fullscreen TUI (requires running server)");
println!(" terraphim-agent repl # Start REPL (offline-capable by default)");
println!(" terraphim-agent repl --server # Start REPL in server mode");
println!();
println!("Common Commands:");
println!(" search <query> # Search documents (offline-capable by default)");
println!(" roles list # List available roles");
println!(" config show # Show configuration");
println!(" replace <text> # Replace terms using thesaurus");
println!(" validate <text> # Validate against knowledge graph");
println!();
println!("For more information:");
println!(" terraphim-agent --help # Show full help");
println!(" terraphim-agent help # Show command-specific help");
}
#[cfg(feature = "server")]
fn resolve_tui_server_url(explicit: Option<&str>) -> String {
let env_server = std::env::var("TERRAPHIM_SERVER").ok();
resolve_tui_server_url_with_env(explicit, env_server.as_deref())
}
#[cfg(feature = "server")]
fn resolve_tui_server_url_with_env(explicit: Option<&str>, env_server: Option<&str>) -> String {
explicit
.map(ToOwned::to_owned)
.or_else(|| env_server.map(ToOwned::to_owned))
.unwrap_or_else(|| "http://localhost:8000".to_string())
}
#[cfg(feature = "server")]
fn tui_server_requirement_error(url: &str, cause: &anyhow::Error) -> anyhow::Error {
anyhow::anyhow!(
"Fullscreen TUI requires a running Terraphim server at {}. \
Start terraphim_server or use offline mode with `terraphim-agent repl`. \
Connection error: {}",
url,
cause
)
}
#[cfg(feature = "server")]
fn ensure_tui_server_reachable(
runtime: &tokio::runtime::Runtime,
api: &ApiClient,
url: &str,
) -> Result<()> {
runtime
.block_on(api.health())
.map_err(|err| tui_server_requirement_error(url, &err))
}
impl From<LogicalOperatorCli> for LogicalOperator {
fn from(op: LogicalOperatorCli) -> Self {
match op {
LogicalOperatorCli::And => LogicalOperator::And,
LogicalOperatorCli::Or => LogicalOperator::Or,
}
}
}
/// Hook types for Claude Code integration
#[derive(clap::ValueEnum, Debug, Clone)]
pub enum HookType {
/// Pre-tool-use hook (intercepts tool calls)
PreToolUse,
/// Post-tool-use hook (processes tool results)
PostToolUse,
/// Pre-commit hook (validate before commit)
PreCommit,
/// Prepare-commit-msg hook (enhance commit message)
PrepareCommitMsg,
}
/// Boundary mode for text replacement
#[derive(clap::ValueEnum, Debug, Clone, Default)]
pub enum BoundaryMode {
/// Match anywhere (default, current behavior)
#[default]
None,
/// Only match at word boundaries
Word,
}
/// Check if a character is a word boundary character (not alphanumeric).
fn is_word_boundary_char(c: char) -> bool {
!c.is_alphanumeric() && c != '_'
}
/// Check if a match position is at word boundaries in the text.
/// Returns true if the character before start (or start of string) and
/// the character after end (or end of string) are word boundary characters.
fn is_at_word_boundary(text: &str, start: usize, end: usize) -> bool {
// Check character before start
let before_ok = if start == 0 {
true
} else {
text[..start]
.chars()
.last()
.map(is_word_boundary_char)
.unwrap_or(true)
};
// Check character after end
let after_ok = if end >= text.len() {
true
} else {
text[end..]
.chars()
.next()
.map(is_word_boundary_char)
.unwrap_or(true)
};
before_ok && after_ok
}
/// Format a replacement link from a NormalizedTerm and LinkType.
fn format_replacement_link(
term: &terraphim_types::NormalizedTerm,
link_type: terraphim_hooks::LinkType,
) -> String {
let display_text = term.display();
match link_type {
terraphim_hooks::LinkType::WikiLinks => format!("[[{}]]", display_text),
terraphim_hooks::LinkType::HTMLLinks => format!(
"<a href=\"{}\">{}</a>",
term.url.as_deref().unwrap_or_default(),
display_text
),
terraphim_hooks::LinkType::MarkdownLinks => format!(
"[{}]({})",
display_text,
term.url.as_deref().unwrap_or_default()
),
terraphim_hooks::LinkType::PlainText => display_text.to_string(),
}
}
/// Create a transparent style for UI elements
fn transparent_style() -> Style {
Style::default().bg(Color::Reset)
}
/// Create a block with optional transparent background
fn create_block(title: &str, transparent: bool) -> Block<'_> {
let block = Block::default().title(title).borders(Borders::ALL);
if transparent {
block.style(transparent_style())
} else {
block
}
}
#[derive(Debug, Clone, PartialEq)]
enum ViewMode {
Search,
ResultDetail,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TuiAction {
None,
Quit,
SearchOrOpen,
MoveUp,
MoveDown,
Autocomplete,
SwitchRole,
SummarizeSelection,
SummarizeDetail,
Backspace,
InsertChar(char),
BackToSearch,
}
#[cfg(test)]
fn key_event(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
KeyEvent::new(code, modifiers)
}
fn map_search_key_event(event: KeyEvent) -> TuiAction {
match (event.code, event.modifiers) {
(KeyCode::Char('q'), KeyModifiers::CONTROL) => TuiAction::Quit,
(KeyCode::Esc, KeyModifiers::NONE) => TuiAction::Quit,
(KeyCode::Enter, KeyModifiers::NONE) => TuiAction::SearchOrOpen,
(KeyCode::Up, KeyModifiers::NONE) => TuiAction::MoveUp,
(KeyCode::Down, KeyModifiers::NONE) => TuiAction::MoveDown,
(KeyCode::Tab, KeyModifiers::NONE) => TuiAction::Autocomplete,
(KeyCode::Char('r'), KeyModifiers::CONTROL) => TuiAction::SwitchRole,
(KeyCode::Char('s'), KeyModifiers::CONTROL) => TuiAction::SummarizeSelection,
(KeyCode::Backspace, KeyModifiers::NONE) => TuiAction::Backspace,
(KeyCode::Char(c), KeyModifiers::NONE) => TuiAction::InsertChar(c),
_ => TuiAction::None,
}
}
fn map_detail_key_event(event: KeyEvent) -> TuiAction {
match (event.code, event.modifiers) {
(KeyCode::Esc, KeyModifiers::NONE) => TuiAction::BackToSearch,
(KeyCode::Char('q'), KeyModifiers::CONTROL) => TuiAction::Quit,
(KeyCode::Char('s'), KeyModifiers::CONTROL) => TuiAction::SummarizeDetail,
_ => TuiAction::None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn map_search_key_event_allows_plain_letters() {
assert_eq!(
map_search_key_event(key_event(KeyCode::Char('s'), KeyModifiers::NONE)),
TuiAction::InsertChar('s')
);
assert_eq!(
map_search_key_event(key_event(KeyCode::Char('r'), KeyModifiers::NONE)),
TuiAction::InsertChar('r')
);
// 'q' should also be typeable now
assert_eq!(
map_search_key_event(key_event(KeyCode::Char('q'), KeyModifiers::NONE)),
TuiAction::InsertChar('q')
);
}
#[test]
fn map_search_key_event_ctrl_shortcuts() {
assert_eq!(
map_search_key_event(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL)),
TuiAction::SummarizeSelection
);
assert_eq!(
map_search_key_event(key_event(KeyCode::Char('r'), KeyModifiers::CONTROL)),
TuiAction::SwitchRole
);
// Ctrl+q quits
assert_eq!(
map_search_key_event(key_event(KeyCode::Char('q'), KeyModifiers::CONTROL)),
TuiAction::Quit
);
// Esc also quits in search mode
assert_eq!(
map_search_key_event(key_event(KeyCode::Esc, KeyModifiers::NONE)),
TuiAction::Quit
);
}
#[test]
fn map_detail_key_event_ctrl_s_summarizes() {
assert_eq!(
map_detail_key_event(key_event(KeyCode::Char('s'), KeyModifiers::CONTROL)),
TuiAction::SummarizeDetail
);
assert_eq!(
map_detail_key_event(key_event(KeyCode::Char('s'), KeyModifiers::NONE)),
TuiAction::None
);
}
#[test]
fn map_detail_key_event_ctrl_q_quits() {
// Ctrl+q quits in detail mode
assert_eq!(
map_detail_key_event(key_event(KeyCode::Char('q'), KeyModifiers::CONTROL)),
TuiAction::Quit
);
// Plain 'q' does nothing (no typing in detail mode)
assert_eq!(
map_detail_key_event(key_event(KeyCode::Char('q'), KeyModifiers::NONE)),
TuiAction::None
);
// Esc goes back to search, not quit
assert_eq!(
map_detail_key_event(key_event(KeyCode::Esc, KeyModifiers::NONE)),
TuiAction::BackToSearch
);
}
#[test]
fn test_is_word_boundary_char() {
// Non-alphanumeric chars are boundaries
assert!(is_word_boundary_char(' '));
assert!(is_word_boundary_char('\t'));
assert!(is_word_boundary_char('\n'));
assert!(is_word_boundary_char('.'));
assert!(is_word_boundary_char(','));
assert!(is_word_boundary_char('('));
assert!(is_word_boundary_char(')'));
assert!(is_word_boundary_char('"'));
// Alphanumeric chars are NOT boundaries
assert!(!is_word_boundary_char('a'));
assert!(!is_word_boundary_char('Z'));
assert!(!is_word_boundary_char('0'));
assert!(!is_word_boundary_char('9'));
// Underscore is NOT a boundary (word char in most regex)
assert!(!is_word_boundary_char('_'));
}
#[test]
fn test_is_at_word_boundary_start_of_string() {
// At start of string, "npm" should be at boundary
let text = "npm install";
assert!(is_at_word_boundary(text, 0, 3)); // "npm" at start
}
#[test]
fn test_is_at_word_boundary_end_of_string() {
// At end of string, "npm" should be at boundary
let text = "install npm";
assert!(is_at_word_boundary(text, 8, 11)); // "npm" at end
}
#[test]
fn test_is_at_word_boundary_middle_with_spaces() {
// In middle with spaces, "npm" should be at boundary
let text = "run npm install";
assert!(is_at_word_boundary(text, 4, 7)); // "npm" surrounded by spaces
}
#[test]
fn test_is_at_word_boundary_not_at_boundary() {
// "npm" embedded in "anpmb" should NOT be at boundary
let text = "anpmb";
assert!(!is_at_word_boundary(text, 1, 4)); // "npm" embedded
}
#[test]
fn test_is_at_word_boundary_partial_boundary() {
// "npm" at start but not end: "npma"
let text = "npma";
assert!(!is_at_word_boundary(text, 0, 3)); // "npm" no boundary after
// "npm" at end but not start: "anpm"
let text2 = "anpm";
assert!(!is_at_word_boundary(text2, 1, 4)); // "npm" no boundary before
}
#[test]
fn test_is_at_word_boundary_with_punctuation() {
// Punctuation counts as boundary
let text = "(npm)";
assert!(is_at_word_boundary(text, 1, 4)); // "npm" between parens
let text2 = "use npm, please";
assert!(is_at_word_boundary(text2, 4, 7)); // "npm" followed by comma
}
#[test]
fn resolve_tui_server_url_uses_explicit_then_env_then_default() {
let explicit = resolve_tui_server_url_with_env(Some("http://explicit:9000"), None);
assert_eq!(explicit, "http://explicit:9000");
let from_env = resolve_tui_server_url_with_env(None, Some("http://env:7000"));
assert_eq!(from_env, "http://env:7000");
let defaulted = resolve_tui_server_url_with_env(None, None);
assert_eq!(defaulted, "http://localhost:8000");
}
#[test]
fn tui_server_requirement_error_mentions_repl_fallback() {
let cause = anyhow::anyhow!("connect error");
let err = tui_server_requirement_error("http://localhost:8000", &cause);
let msg = err.to_string();
assert!(msg.contains("Fullscreen TUI requires a running Terraphim server"));
assert!(msg.contains("terraphim-agent repl"));
assert!(msg.contains("http://localhost:8000"));
}
}
#[derive(clap::ValueEnum, Debug, Clone, Default)]
pub enum OutputFormat {
/// Human-readable output (default)
#[default]
Human,
/// Machine-readable JSON output
Json,
/// Compact JSON for piping
JsonCompact,
}
#[derive(clap::ValueEnum, Debug, Clone, Default)]
enum RobotFormat {
#[default]
Json,
Table,
Minimal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CommandOutputMode {
Human,
Json,
JsonCompact,
}
#[derive(Debug, Clone, Copy)]
struct CommandOutputConfig {
mode: CommandOutputMode,
robot: bool,
}
impl CommandOutputConfig {
fn is_machine_readable(self) -> bool {
self.robot || !matches!(self.mode, CommandOutputMode::Human)
}
}
fn resolve_output_config(robot: bool, format: OutputFormat) -> CommandOutputConfig {
let mode = match format {
OutputFormat::Human => {
if robot {
CommandOutputMode::Json
} else {
CommandOutputMode::Human
}
}
OutputFormat::Json => CommandOutputMode::Json,
OutputFormat::JsonCompact => CommandOutputMode::JsonCompact,
};
CommandOutputConfig { mode, robot }
}
#[cfg(feature = "repl-sessions")]
mod session_output {
use serde::Serialize;
#[derive(Debug, Serialize)]
pub struct SourcesOutput {
pub count: usize,
pub sources: Vec<SourceEntry>,
}
#[derive(Debug, Serialize)]
pub struct SourceEntry {
pub id: String,
pub name: Option<String>,
pub available: bool,
}
#[derive(Debug, Serialize)]
pub struct SessionListOutput {
pub total: usize,
pub shown: usize,
pub sessions: Vec<SessionEntry>,
}
#[derive(Debug, Serialize)]
pub struct SessionEntry {
pub id: String,
pub title: Option<String>,
pub message_count: usize,
pub source: String,
}
#[derive(Debug, Serialize)]
pub struct SessionSearchOutput {
pub query: String,
pub total: usize,
pub shown: usize,
pub sessions: Vec<SessionSearchEntry>,
}
#[derive(Debug, Serialize)]
pub struct SessionSearchEntry {
pub id: String,
pub title: Option<String>,
pub message_count: usize,
pub preview: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct SessionStatsOutput {
pub total_sessions: usize,
pub total_messages: usize,
pub total_user_messages: usize,
pub total_assistant_messages: usize,
pub by_source: std::collections::HashMap<String, usize>,
}
}
#[allow(dead_code)]
fn print_json_output<T: Serialize>(value: &T, mode: CommandOutputMode) -> Result<()> {
let out = match mode {
CommandOutputMode::Human => serde_json::to_string_pretty(value)?,
CommandOutputMode::Json => serde_json::to_string_pretty(value)?,
CommandOutputMode::JsonCompact => serde_json::to_string(value)?,
};
println!("{}", out);
Ok(())
}
#[derive(Parser, Debug)]
#[command(
name = "terraphim-agent",
version,
about = "Terraphim Agent: server-backed fullscreen TUI with offline-capable REPL and CLI commands",
after_long_help = "EXIT CODES (F1.2 contract)\n\
\n\
\x20 0 SUCCESS Operation completed successfully\n\
\x20 1 ERROR_GENERAL Unspecified or unexpected error\n\
\x20 2 ERROR_USAGE Invalid arguments or unknown command\n\
\x20 3 ERROR_INDEX_MISSING Required index not initialised\n\
\x20 4 ERROR_NOT_FOUND No results (only with --fail-on-empty)\n\
\x20 5 ERROR_AUTH Authentication required or failed\n\
\x20 6 ERROR_NETWORK Transport-level network error\n\
\x20 7 ERROR_TIMEOUT Operation exceeded configured timeout\n"
)]
struct Cli {
/// Use server API mode instead of self-contained offline mode
#[arg(long, default_value_t = false)]
server: bool,
/// Server URL for API mode
#[arg(long, default_value = "http://localhost:8000")]
server_url: String,
/// Enable transparent background mode
#[arg(long, default_value_t = false)]
transparent: bool,
/// Enable robot mode for AI agent integration (JSON output, exit codes)
#[arg(long, default_value_t = false)]
robot: bool,
/// Output format (human, json, json-compact)
#[arg(long, value_enum, default_value_t = OutputFormat::Human)]
format: OutputFormat,
/// Path to a JSON config file (overrides settings.toml and persistence)
#[arg(long)]
config: Option<String>,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Subcommand, Debug)]
enum Command {
/// Search documents using the knowledge graph
Search {
/// Primary search query
query: String,
/// Additional search terms for multi-term queries
#[arg(long, num_args = 1.., value_delimiter = ',')]
terms: Option<Vec<String>>,
/// Logical operator for combining multiple search terms (and/or)
#[arg(long, value_enum)]
operator: Option<LogicalOperatorCli>,
#[arg(long)]
role: Option<String>,
#[arg(long, default_value_t = 10)]
limit: usize,
#[arg(long, default_value_t = false)]
fail_on_empty: bool,
/// Include pinned KG entries in results
#[arg(long, default_value_t = false)]
include_pinned: bool,
/// Minimum composite quality score (0.0-1.0). Excludes documents below this threshold.
#[arg(long)]
min_quality: Option<f64>,
/// Maximum estimated tokens in robot-mode output (4 chars ≈ 1 token)
#[arg(long)]
max_tokens: Option<usize>,
/// Maximum characters per content/preview field before truncation
#[arg(long)]
max_content_length: Option<usize>,
/// Output field set: full, summary, minimal, or custom:<f1>,<f2>
#[arg(long)]
fields: Option<robot::output::FieldMode>,
},
/// Manage roles (list, select)
Roles {
#[command(subcommand)]
sub: RolesSub,
},
/// Manage configuration (show, set, validate, reload)
Config {
#[command(subcommand)]
sub: ConfigSub,
},
/// Display the knowledge graph for a role
Graph {
#[arg(long)]
role: Option<String>,
#[arg(long, default_value_t = 50)]
top_k: usize,
/// Show only pinned entries
#[arg(long, default_value_t = false)]
pinned: bool,
},
/// Manage knowledge graph entries
Kg {
#[command(subcommand)]
sub: KgSub,
},
/// Chat with the AI using a specific role
#[cfg(feature = "llm")]
Chat {
#[arg(long)]
role: Option<String>,
prompt: String,
#[arg(long)]
model: Option<String>,
},
/// Extract paragraphs matching knowledge graph terms from text
Extract {
text: String,
#[arg(long)]
role: Option<String>,
#[arg(long, default_value_t = false)]
exclude_term: bool,
},
/// Replace terms in text using the knowledge graph thesaurus
Replace {
/// Text to replace (reads from stdin if not provided)
text: Option<String>,
#[arg(long)]
role: Option<String>,
/// Output format: plain (default), markdown, wiki, html
#[arg(long)]
format: Option<String>,
/// Boundary mode: none (match anywhere) or word (only at word boundaries)
#[arg(long, default_value = "none")]
boundary: BoundaryMode,
/// Output as JSON with metadata (for hook integration)
#[arg(long, default_value_t = false)]
json: bool,
/// Suppress errors and pass through unchanged on failure
#[arg(long, default_value_t = false)]
fail_open: bool,
},
/// Validate text against knowledge graph
Validate {
/// Text to validate (reads from stdin if not provided)
text: Option<String>,
/// Role to use for validation
#[arg(long)]
role: Option<String>,
/// Check if all matched terms are connected by a single path
#[arg(long, default_value_t = false)]
connectivity: bool,
/// Validate against a named checklist (e.g., "code_review", "security")
#[arg(long)]
checklist: Option<String>,
/// Output as JSON
#[arg(long, default_value_t = false)]
json: bool,
},
/// Suggest similar terms using fuzzy matching
Suggest {
/// Query to search for (reads from stdin if not provided)
query: Option<String>,
/// Role to use for suggestions
#[arg(long)]
role: Option<String>,
/// Enable fuzzy matching
#[arg(long, default_value_t = true)]
fuzzy: bool,
/// Minimum similarity threshold (0.0-1.0)
#[arg(long, default_value_t = 0.6)]
threshold: f64,
/// Maximum number of suggestions
#[arg(long, default_value_t = 10)]
limit: usize,
/// Output as JSON
#[arg(long, default_value_t = false)]
json: bool,
},
/// Unified hook handler for Claude Code integration
Hook {
/// Hook type (pre-tool-use, post-tool-use, pre-commit, etc.)
#[arg(long, value_enum)]
hook_type: HookType,
/// JSON input from Claude Code (reads from stdin if not provided)
#[arg(long)]
input: Option<String>,
/// Role to use for processing
#[arg(long)]
role: Option<String>,
/// Output as JSON (always true for hooks, but explicit)
#[arg(long, default_value_t = true)]
json: bool,
/// Include guard check for destructive commands (git reset --hard, rm -rf, etc.)
#[arg(long, default_value_t = false)]
with_guard: bool,
},
/// Check command against safety guard patterns (blocks destructive git/fs commands)
Guard {
/// Command to check (reads from stdin if not provided)
command: Option<String>,
/// Output as JSON
#[arg(long, default_value_t = false)]
json: bool,
/// Suppress errors and pass through unchanged on failure
#[arg(long, default_value_t = false)]
fail_open: bool,
/// Path to custom destructive patterns thesaurus JSON file
#[arg(long)]
guard_thesaurus: Option<String>,
/// Path to custom allowlist thesaurus JSON file
#[arg(long)]
guard_allowlist: Option<String>,
},
/// Start fullscreen interactive TUI mode (requires running server)
Interactive,
/// Start REPL (Read-Eval-Print-Loop) interface
#[cfg(feature = "repl")]
Repl {
/// Start in server mode
#[arg(long)]
server: bool,
/// Server URL for API mode
#[arg(long, default_value = "http://localhost:8000")]
server_url: String,
},
/// Interactive setup wizard for first-time configuration
Setup {
/// Apply a specific template directly (skip interactive wizard)
#[arg(long)]
template: Option<String>,
/// Path to use with the template (required for some templates like local-notes)
#[arg(long)]
path: Option<String>,
/// Add a new role to existing configuration (instead of replacing)
#[arg(long, default_value_t = false)]
add_role: bool,
/// List available templates and exit
#[arg(long, default_value_t = false)]
list_templates: bool,
},
/// Check for updates without installing
CheckUpdate,
/// Update to latest version if available
Update,
/// Learning capture for failed commands
Learn {
#[command(subcommand)]
sub: LearnSub,
},
/// Session management for AI coding assistant history
#[cfg(feature = "repl-sessions")]
Sessions {
#[command(subcommand)]
sub: SessionsSub,
},
/// Start listener mode for AI agent communication (offline-only)
Listen {
/// Agent identity/name for this listener instance
#[arg(long)]
identity: Option<String>,
/// Optional listener configuration JSON file
#[arg(long)]
config: Option<String>,
/// Start in server mode (rejected -- listen is offline-only)
#[arg(long)]
server: bool,
},
/// Manage the compiled thesaurus cache
Cache {
#[command(subcommand)]
sub: CacheSub,
},
/// Robot mode self-documentation commands
Robot {
#[command(subcommand)]
sub: RobotSub,
},
}
#[derive(Subcommand, Debug)]
enum CacheSub {
/// Flush (delete) compiled thesaurus cache entries
Flush {
/// Specific role to flush (if omitted, flushes all cached thesauri)
#[arg(long)]
role: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum LearnSub {
/// Capture a failed command as a learning
Capture {
/// The command that failed
command: String,
/// The error output (stderr)
#[arg(long)]
error: String,
/// The exit code
#[arg(long, default_value_t = 1)]
exit_code: i32,
/// Enable debug output
#[arg(long, default_value_t = false)]
debug: bool,
},
/// List recent learnings
List {
/// Number of recent learnings to show
#[arg(long, default_value_t = 10)]
recent: usize,
/// Show global learnings instead of project
#[arg(long, default_value_t = false)]
global: bool,
},
/// Query learnings by pattern
Query {
/// Search pattern
pattern: String,
/// Use exact match instead of substring
#[arg(long, default_value_t = false)]
exact: bool,
/// Show global learnings instead of project
#[arg(long, default_value_t = false)]
global: bool,
/// Enable semantic matching via KG entities
#[arg(long, default_value_t = false)]
semantic: bool,
},
/// Add correction to an existing learning
Correct {
/// Learning ID
id: String,
/// The correction to add
#[arg(long)]
correction: String,
},
/// Record a user correction (tool preference, naming, workflow, etc.)
Correction {
/// What the agent said/did originally
#[arg(long)]