Skip to content

Commit 67bd83a

Browse files
authored
Merge pull request #726 from terraphim/fix/merge-conflicts
fix(terraphim-agent): resolve role shortnames, fix remote thesaurus, add LLM proxy fallback
2 parents e95e061 + 5a78fd2 commit 67bd83a

18 files changed

Lines changed: 462 additions & 275 deletions

File tree

.docs/summary-Cargo.toml.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Cargo.toml Summary
2+
3+
## Purpose
4+
Defines the workspace configuration and dependencies for the Terraphim AI project, managing multiple crates and external dependencies.
5+
6+
## Key Functionality
7+
- Configures a Rust workspace with multiple member crates
8+
- Sets up workspace-level dependencies (tokio, reqwest, serde, etc.)
9+
- Defines profile configurations for different build scenarios (release, ci, etc.)
10+
- Specifies excluded crates (experimental, Python bindings, desktop-specific)
11+
- Applies patches for specific dependencies (genai, self_update)
12+
13+
## Important Details
14+
- Workspace includes crates/, terraphim_server, terraphim_firecracker, terraphim_ai_nodejs
15+
- Excludes experimental crates like terraphim_agent_application, terraphim_truthforge, etc.
16+
- Uses edition 2024 and version 1.14.0
17+
- Configured for async/await with tokio runtime
18+
- Features conditional compilation via cfg attributes
19+
- Manages cross-platform builds with specific exclusions
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# terraphim_agent/src/client.rs Summary
2+
3+
## Purpose
4+
Provides HTTP client functionality for communicating with the Terraphim server API, handling requests for configuration, chat, document summarization, thesaurus access, and VM management.
5+
6+
## Key Functionality
7+
- Creates HTTP client with configurable timeouts and user agent
8+
- Fetches server configuration via GET /config endpoint
9+
- Resolves role strings to RoleName objects using server config (with fallback)
10+
- Handles chat interactions with LLM models via POST /chat
11+
- Summarizes documents via POST /documents/summarize
12+
- Accesses thesaurus data via GET /thesaurus/{role_name}
13+
- Provides autocomplete suggestions via GET /autocomplete/{role_name}/{query}
14+
- Manages VM operations (listing, status, execution, metrics)
15+
- Supports async document summarization and task management
16+
17+
## Important Details
18+
- Role resolution falls back to creating RoleName from raw string if not found in config (line 69)
19+
- Uses async/await pattern with Tokio for non-blocking HTTP requests
20+
- Implements proper error handling with anyhow::Result
21+
- Includes configurable timeout via TERRAPHIM_CLIENT_TIMEOUT environment variable
22+
- Provides both live API methods and dead-code-allowed variants for testing
23+
- Handles URL encoding for query parameters in various endpoints
24+
- Supports VM pool management, execution, and monitoring capabilities
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# terraphim_agent/src/service.rs Summary
2+
3+
## Purpose
4+
Provides the TUI service layer that manages application state, configuration, and business logic for the Terraphim agent's text-based user interface, coordinating between configuration persistence and the core TerraphimService.
5+
6+
## Key Functionality
7+
- Manages configuration loading with priority: CLI flag → settings.toml → persistence → embedded defaults
8+
- Resolves role strings to RoleName objects by searching configuration (name first, then shortname)
9+
- Provides access to thesaurus data for roles via embedded automata
10+
- Handles chat interactions with LLM providers based on role configuration
11+
- Implements document search, extraction, summarization, and connectivity checking
12+
- Manages role graph operations and topological analysis
13+
- Supports configuration persistence and reloading from JSON files
14+
- Provides checklist validation functionality for various domains (code review, security, etc.)
15+
16+
## Important Details
17+
- Role resolution returns error if role not found in config (line 251), unlike client.rs which falls back to raw string
18+
- Uses Arc<Mutex<TerraphimService>> for shared state access across async contexts
19+
- Implements bootstrap-then-persistence pattern for role_config in settings.toml
20+
- Supports multiple search modes: simple term search and complex SearchQuery with operators
21+
- Provides thesaurus-backed text operations: extraction, finding matches, autocomplete, fuzzy suggestions
22+
- Includes connectivity checking for knowledge graph relationships between matched terms
23+
- Handles device settings with fallback to embedded defaults in sandboxed environments
24+
- Manages configuration updates and persistence through save_config() method

.docs/summary.md

Lines changed: 57 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -1,119 +1,59 @@
1-
# Terraphim AI - Project Summary
1+
# Terraphim AI Project Summary
22

33
## Overview
4-
Terraphim AI is a comprehensive AI agent system designed for semantic knowledge graph search, automation, and intelligent workflow management. The system provides tools for developers and engineers to interact with codebases, documentation, and various data sources through natural language interfaces.
5-
6-
## Key Components Analyzed
7-
8-
### 1. MCP Tool Index (terraphim_agent/src/mcp_tool_index.rs)
9-
**Purpose**: Implements the Model Context Protocol Tool Index for discovering and searching available MCP tools from configured servers.
10-
11-
**Key Features**:
12-
- Fast, searchable discovery using Aho-Corasick pattern matching via terraphim_automata
13-
- Tool management (add, save, load, count)
14-
- JSON persistence for tool indices
15-
- Search across tool names, descriptions, and tags
16-
17-
**Performance Characteristics**:
18-
- Originally required search completion in under 50ms for 100 tools
19-
- Increased threshold to 70ms to account for system variability while maintaining performance expectations
20-
- Uses efficient Aho-Corasick automaton for multi-pattern matching
21-
22-
**Recent Fix**:
23-
- Increased search latency benchmark threshold from 50ms to 70ms to fix intermittent test failures due to system load variability
24-
25-
### 2. TinyClaw Skills Benchmarks (terraphim_tinyclaw/tests/skills_benchmarks.rs)
26-
**Purpose**: Contains benchmarks for validating the performance of the Terraphim TinyClaw skills system.
27-
28-
**Key Features**:
29-
- Skill load benchmark (< 100ms NFR)
30-
- Skill save benchmark (< 50ms NFR)
31-
- Skill execution benchmark (< 2000ms NFR, increased from 1000ms)
32-
33-
**Recent Fix**:
34-
- Increased execution time threshold from 1000ms to 2000ms in benchmark_execution_small_skill to fix intermittent test failures due to system load variability while maintaining reasonable performance expectations
35-
36-
## Architecture Analysis
37-
38-
### Strengths
39-
1. **Modular Design**: Clear separation of concerns between different components (agent, automata, persistence, etc.)
40-
2. **Performance-Oriented**: Uses efficient algorithms like Aho-Corasick for pattern matching
41-
3. **Extensible**: Plugin-based architecture for skills and tools
42-
4. **Well-Tested**: Comprehensive test suite covering unit, integration, and benchmark tests
43-
5. **Async/Await**: Proper use of Tokio for asynchronous operations where appropriate
44-
45-
### Areas for Improvement
46-
1. **Benchmark Sensitivity**: Some performance tests are too close to system variability limits
47-
2. **Resource Management**: Could benefit from more explicit resource cleanup in long-running processes
48-
3. **Error Handling**: Some error propagation could be more consistent across layers
49-
50-
## Security Analysis
51-
52-
### Strengths
53-
1. **Input Validation**: Proper validation of inputs in key areas like tool search and skill execution
54-
2. **Sandboxing**: Execution guards prevent dangerous operations (rm -rf, curl | bash, etc.)
55-
3. **Path Safety**: Proper handling of file paths to prevent traversal attacks
56-
4. **Dependency Management**: Uses trusted crates and follows Rust security best practices
57-
58-
### Areas for Improvement
59-
1. **Dependency Scanning**: Regular dependency vulnerability scanning could be enhanced
60-
2. **Secrets Management**: While 1Password integration exists, broader secrets management patterns could be documented
61-
3. **Audit Logging**: More comprehensive audit logging for security-sensitive operations
62-
63-
## Testing Analysis
64-
65-
### Strengths
66-
1. **Comprehensive Coverage**: Unit tests, integration tests, and performance benchmarks
67-
2. **Realistic Scenarios**: Tests simulate real-world usage patterns
68-
3. **Property-Based Testing**: Use of proptest for randomized testing where appropriate
69-
4. **Benchmark Focus**: Performance benchmarks help catch regressions early
70-
5. **Test Organization**: Clear separation of different test types
71-
72-
### Areas for Improvement
73-
1. **Benchmark Flakiness**: Some performance tests are sensitive to system load (addressed by increasing thresholds)
74-
2. **Test Duration**: Some integration tests take considerable time (>60s)
75-
3. **Mock Usage**: Good avoidance of mocks in tests as per project policy
76-
4. **Test Parallelization**: Could benefit from more parallel test execution where safe
77-
78-
## Business Value Analysis
79-
80-
### Key Value Propositions
81-
1. **Developer Productivity**: Reduces context switching by providing intelligent search and automation
82-
2. **Knowledge Discovery**: Enables finding relevant information across large codebases and documentation
83-
3. **Workflow Automation**: Automates repetitive development tasks through skills and agents
84-
4. **Code Quality**: Helps maintain consistency and discover best practices in codebases
85-
5. **Onboarding Acceleration**: Helps new team members quickly understand codebases and workflows
86-
87-
### Competitive Advantages
88-
1. **Semantic Understanding**: Goes beyond keyword search to understand context and intent
89-
2. **Extensibility**: Easy to add new skills, tools, and data sources
90-
3. **Privacy-First**: Can operate entirely locally without sending data to external services
91-
4. **Multi-Modal**: Supports text, code, and potentially other data types
92-
5. **Integration Friendly**: Designed to work with existing developer tools and workflows
93-
94-
### Target Use Cases
95-
1. **Code Navigation**: Finding specific implementations, patterns, or usage examples
96-
2. **Debugging Assistance**: Quickly locating relevant code sections during issue resolution
97-
3. **Learning & Onboarding**: Helping new team members understand codebase structure
98-
4. **Refactoring Support**: Finding all usages of specific patterns or APIs
99-
5. **Automation**: Creating reusable skills for common development tasks
100-
101-
## Recommendations
102-
103-
### Short-Term
104-
1. Monitor the adjusted benchmark thresholds to ensure they remain appropriate
105-
2. Consider adding more performance profiling to identify actual bottlenecks
106-
3. Document the reasoning behind benchmark thresholds for future maintainers
107-
108-
### Medium-Term
109-
1. Develop more sophisticated performance baselines that account for hardware variations
110-
2. Consider implementing adaptive benchmarking that adjusts thresholds based on baseline performance
111-
3. Enhance security audit logging and monitoring capabilities
112-
113-
### Long-Term
114-
1. Investigate more deterministic performance testing approaches for CI/CD
115-
2. Consider benchmarking against hardware profiles to set appropriate thresholds
116-
3. Explore ways to make benchmark tests less sensitive to environmental factors while maintaining their validity
117-
118-
## Conclusion
119-
The Terraphim AI project demonstrates strong architectural foundations with a focus on performance, security, and extensibility. The recent fixes to benchmark thresholds address test flakiness due to system variability while maintaining meaningful performance expectations. The codebase shows good adherence to Rust best practices and project-specific guidelines, resulting in a reliable and maintainable system that delivers significant value to development teams seeking to improve productivity and code quality.
4+
Terraphim AI is a Rust-based AI agent system featuring a modular architecture with multiple crates, providing both online (server-connected) and offline (embedded) capabilities for knowledge work, document processing, and AI-assisted tasks.
5+
6+
## Architecture
7+
- **Workspace Structure**: Cargo workspace with multiple member crates including `terraphim_agent`, `terraphim_server`, `terraphim_firecracker`, and `terraphim_ai_nodejs`
8+
- **Modular Design**: Separation of concerns between client communication, service logic, and core functionality
9+
- **Async Runtime**: Built on Tokio for asynchronous operations throughout the codebase
10+
- **Configuration System**: Multi-layer config loading with priority: CLI flags → settings.toml → persistence → embedded defaults
11+
12+
## Key Components
13+
14+
### Communication Layer (`terraphim_agent/src/client.rs`)
15+
- HTTP client for server API communication
16+
- Features configurable timeouts and user agent
17+
- Role resolution that falls back to creating RoleName from raw string when not found in server config
18+
- Supports chat, document summarization, thesaurus access, autocomplete, and VM management operations
19+
20+
### Service Layer (`terraphim_agent/src/service.rs`)
21+
- TUI service managing application state and business logic
22+
- Coordinates between configuration persistence and core TerraphimService
23+
- Role resolution that returns error when role not found in config (contrasts with client.rs)
24+
- Provides thesaurus-backed text operations, search, extraction, summarization, and connectivity checking
25+
- Implements bootstrap-then-persistence pattern for role configuration
26+
27+
### Dependencies & Tooling
28+
- Core dependencies: tokio, reqwest, serde, thiserror, anyhow, async-trait
29+
- Conditional compilation via cfg attributes for feature flags
30+
- Cross-platform build management with specific exclusions
31+
- Development tooling includes Clippy, Rustfmt, and custom validation scripts
32+
33+
## Notable Patterns & Characteristics
34+
1. **Role Resolution Inconsistency**:
35+
- Online mode (client.rs): Falls back to raw role string when not found in config
36+
- Offline mode (service.rs): Returns error when role not found in config
37+
- This creates different behavior between connected and disconnected states
38+
39+
2. **Configuration Loading**: Sophisticated multi-source configuration system with fallback hierarchy
40+
41+
3. **Error Handling**: Consistent use of `anyhow::Result` and `thiserror` for error propagation
42+
43+
4. **Async/Await**: Extensive use of asynchronous patterns with proper timeout handling
44+
45+
5. **Testing Approach**: Emphasis on integration testing with real services rather than mocks
46+
47+
## Current Focus Areas
48+
Based on recent documentation and code review activities:
49+
- Cross-mode consistency between online and offline operations
50+
- Role resolution and validation improvements
51+
- Test coverage and compilation fixes
52+
- Documentation maintenance and accuracy
53+
- Performance optimization and benchmarking
54+
55+
## Build & Development
56+
- Standard Rust toolchain with cargo workspace
57+
- Features: openrouter, mcp-rust-sdk for conditional compilation
58+
- Profile configurations for release, CI, and LTO-optimized builds
59+
- Pre-commit hooks for code quality assurance

crates/terraphim_agent/Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ readme = "../../README.md"
1313

1414
[features]
1515
default = ["repl-interactive"]
16-
repl = ["dep:rustyline", "dep:colored", "dep:comfy-table", "dep:dirs"]
16+
repl = ["dep:rustyline", "dep:colored", "dep:comfy-table"]
1717
repl-interactive = ["repl"]
1818
# NOTE: repl-sessions re-enabled for local development (path dependency)
1919
repl-full = ["repl", "repl-chat", "repl-mcp", "repl-file", "repl-custom", "repl-web", "repl-interactive", "repl-sessions"]
@@ -62,7 +62,7 @@ dialoguer = "0.12" # Interactive CLI prompts for onboarding wizard
6262
rustyline = { version = "17.0", optional = true }
6363
colored = { version = "3.0", optional = true }
6464
comfy-table = { version = "7.0", optional = true }
65-
dirs = { version = "5.0", optional = true }
65+
dirs = { version = "5.0" }
6666
terraphim_types = { path = "../terraphim_types", version = "1.0.0" }
6767
terraphim_settings = { path = "../terraphim_settings", version = "1.0.0" }
6868
terraphim_persistence = { path = "../terraphim_persistence", version = "1.0.0" }

crates/terraphim_agent/src/client.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,29 @@ impl ApiClient {
4646
Ok(body)
4747
}
4848

49+
/// Resolve a role string (name or shortname) to a RoleName using server config.
50+
/// Falls back to RoleName::new if no match found (server will validate).
51+
pub async fn resolve_role(&self, role: &str) -> Result<terraphim_types::RoleName> {
52+
use terraphim_types::RoleName;
53+
let config_res = self.get_config().await?;
54+
let role_lower = role.to_lowercase();
55+
let selected = &config_res.config.selected_role;
56+
if selected.to_string().to_lowercase() == role_lower {
57+
return Ok(selected.clone());
58+
}
59+
for (name, role_cfg) in &config_res.config.roles {
60+
if name.to_string().to_lowercase() == role_lower {
61+
return Ok(name.clone());
62+
}
63+
if let Some(ref sn) = role_cfg.shortname {
64+
if sn.to_lowercase() == role_lower {
65+
return Ok(name.clone());
66+
}
67+
}
68+
}
69+
Ok(RoleName::new(role))
70+
}
71+
4972
pub async fn update_selected_role(&self, role: &str) -> Result<ConfigResponse> {
5073
let url = format!("{}/config/selected_role", self.base);
5174
#[derive(Serialize)]

crates/terraphim_agent/src/learnings/capture.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -823,13 +823,6 @@ pub enum LearningEntry {
823823
}
824824

825825
impl LearningEntry {
826-
pub fn captured_at(&self) -> DateTime<Utc> {
827-
match self {
828-
LearningEntry::Learning(l) => l.context.captured_at,
829-
LearningEntry::Correction(c) => c.context.captured_at,
830-
}
831-
}
832-
833826
pub fn source(&self) -> &LearningSource {
834827
match self {
835828
LearningEntry::Learning(l) => &l.source,
@@ -845,6 +838,13 @@ impl LearningEntry {
845838
}
846839
}
847840

841+
pub fn captured_at(&self) -> chrono::DateTime<chrono::Utc> {
842+
match self {
843+
LearningEntry::Learning(l) => l.context.captured_at,
844+
LearningEntry::Correction(c) => c.context.captured_at,
845+
}
846+
}
847+
848848
/// Summary line for display.
849849
pub fn summary(&self) -> String {
850850
match self {

crates/terraphim_agent/src/learnings/mod.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ pub use capture::{
3636
capture_correction, capture_failed_command, correct_learning, list_all_entries,
3737
query_all_entries, suggest_learnings,
3838
};
39-
4039
// Re-export for testing - not used by CLI yet
4140
#[allow(unused_imports)]
4241
pub use capture::{CapturedLearning, LearningContext, LearningError};

0 commit comments

Comments
 (0)