# DX Forge API Reference
Complete API documentation for the dx-forge crate.
## Core API
### Forge - Main Entry Point
```rust
use dx_forge::{Forge, ForgeConfig};
// Create with defaults
let forge = Forge::new(".")?;
// Or with custom configuration
let config = ForgeConfig::new(".")
.without_auto_watch()
.without_lsp()
.with_forge_dir(".custom/forge");
let forge = Forge::with_config(config)?;
```
#### Methods
- `new(path)` - Create a new Forge instance
- `with_config(config)` - Create with custom configuration
- `project_root()` - Get project root directory
- `forge_dir()` - Get Forge data directory
- `watch_directory(path)` - Start watching a directory
- `subscribe_changes()` - Subscribe to file changes
- `stop_watching()` - Stop file watching
- `track_generated_file(file, tool, metadata)` - Track generated file
- `get_generated_files(tool)` - Get files generated by tool
- `cleanup_generated(tool)` - Remove all files from tool
- `get_tool_status(id)` - Get tool execution status
- `subscribe_lifecycle_events()` - Subscribe to lifecycle events
## Orchestration
### DxTool Trait
All DX tools must implement this trait:
```rust
use dx_forge::{DxTool, ExecutionContext, ToolOutput};
use anyhow::Result;
struct MyTool;
impl DxTool for MyTool {
fn name(&self) -> &str { "my-tool" }
fn version(&self) -> &str { "1.0.0" }
fn priority(&self) -> u32 { 50 }
fn execute(&mut self, ctx: &ExecutionContext) -> Result<ToolOutput> {
// Your logic here
Ok(ToolOutput::success())
}
// Optional overrides
fn should_run(&self, ctx: &ExecutionContext) -> bool { true }
fn dependencies(&self) -> Vec<String> { vec![] }
fn before_execute(&mut self, ctx: &ExecutionContext) -> Result<()> { Ok(()) }
fn after_execute(&mut self, ctx: &ExecutionContext, output: &ToolOutput) -> Result<()> { Ok(()) }
fn on_error(&mut self, ctx: &ExecutionContext, error: &anyhow::Error) -> Result<()> { Ok(()) }
fn timeout_seconds(&self) -> u64 { 60 }
}
```
### Orchestrator
Coordinates tool execution:
```rust
use dx_forge::{Orchestrator, OrchestratorConfig};
let mut orch = Orchestrator::new(".")?;
// Or with custom config
let config = OrchestratorConfig {
parallel: true,
fail_fast: false,
max_concurrent: 4,
traffic_branch_enabled: true,
};
let mut orch = Orchestrator::with_config(".", config)?;
// Register tools
orch.register_tool(Box::new(MyTool))?;
// Execute all
let results = orch.execute_all()?;
```
## File Watching
### DualWatcher
Two-tier file change detection (LSP + File System):
```rust
use dx_forge::DualWatcher;
let mut watcher = DualWatcher::new()?;
let mut rx = watcher.receiver();
watcher.start(".").await?;
while let Ok(change) = rx.recv().await {
println!("Changed: {:?} via {:?}", change.path, change.source);
}
```
## Version Control
### SnapshotManager
Git-like versioning for tool state:
```rust
use dx_forge::{SnapshotManager, ToolState, Version};
use std::collections::HashMap;
let mut manager = SnapshotManager::new(".dx/forge")?;
// Create snapshot
let mut tool_states = HashMap::new();
tool_states.insert("my-tool".to_string(), ToolState {
tool_name: "my-tool".to_string(),
version: Version::new(1, 0, 0),
config: HashMap::new(),
output_files: vec![],
});
let snapshot_id = manager.create_snapshot(
"My commit message",
tool_states,
vec![/* files */]
)?;
// Branching
manager.create_branch("feature")?;
manager.checkout_branch("feature")?;
// History
let history = manager.history(10)?;
// Merging
manager.checkout_branch("main")?;
manager.merge("feature", "Merge feature into main")?;
// Diff
let diff = manager.diff(&snapshot1, &snapshot2)?;
println!("Changed {} files", diff.total_changes());
```
## Traffic Branch System
Analyze file changes for merge safety:
```rust
use dx_forge::{TrafficAnalyzer, TrafficBranch, DefaultTrafficAnalyzer};
let analyzer = DefaultTrafficAnalyzer;
let result = analyzer.analyze(Path::new("src/api/types.ts"))?;
match result {
TrafficBranch::Green => {
println!("🟢 Safe to auto-merge");
}
TrafficBranch::Yellow { conflicts } => {
println!("🟡 Review {} conflicts", conflicts.len());
}
TrafficBranch::Red { conflicts } => {
println!("🔴 Manual resolution required");
for conflict in conflicts {
println!(" - {}: {}", conflict.path.display(), conflict.reason);
}
}
}
```
## Tool Registry
Manage installed tools with semantic versioning:
```rust
use dx_forge::{ToolRegistry, ToolSource, Version};
use std::collections::HashMap;
let mut registry = ToolRegistry::new(".dx/forge")?;
// Register a tool
registry.register(
"my-tool".to_string(),
Version::new(1, 0, 0),
ToolSource::Local(PathBuf::from("./tools/my-tool")),
HashMap::new(), // dependencies
)?;
// Check registration
if registry.is_registered("my-tool") {
let version = registry.version("my-tool").unwrap();
println!("Installed: {}", version);
}
// Check dependencies
let missing = registry.check_dependencies("my-tool")?;
for msg in missing {
println!("Missing: {}", msg);
}
// List all tools
for tool in registry.list() {
println!("{} v{}", tool.name, tool.version);
}
```
## Pattern Detection
Detect DX tool patterns in code:
```rust
use dx_forge::{PatternDetector, DxToolType};
let detector = PatternDetector::new();
let content = r#"
<dxButton variant="primary">Click me</dxButton>
<dxiUser size={24} />
"#;
let matches = detector.detect_in_content(content, "component.tsx")?;
for m in matches {
println!("Found {} at line {}", m.tool_type, m.line);
match m.tool_type {
DxToolType::UI => println!(" Component: {}", m.component_name),
DxToolType::Icon => println!(" Icon: {}", m.component_name),
_ => {}
}
}
```
## Component Injection
Fetch and cache components from R2:
```rust
use dx_forge::InjectionManager;
let mut manager = InjectionManager::new(".dx/forge")?;
// Inject a component
let code = manager.inject_component("dxButton", "1.0.0").await?;
println!("Injected:\n{}", code);
// Get cache stats
let stats = manager.cache_stats()?;
println!("Cached {} components ({} bytes)", stats.component_count, stats.total_size);
// Clear cache
manager.clear_cache()?;
```
## Error Handling
Enhanced error handling with retry logic:
```rust
use dx_forge::{with_retry, RetryPolicy, EnhancedError, ToEnhanced};
// Use retry wrapper
let result = with_retry(
RetryPolicy::default(),
|| {
// Operation that might fail
some_network_call()
}
).await?;
// Enhanced errors
let result = some_operation()
.to_enhanced("Failed to perform operation")?;
// Error categorization
match result {
Err(e) => {
let category = dx_forge::categorize_error(&e);
println!("Error category: {:?}", category);
}
Ok(val) => { /* ... */ }
}
```
## Lifecycle Events
Monitor tool lifecycle:
```rust
use dx_forge::{Forge, LifecycleEvent};
let forge = Forge::new(".")?;
let mut rx = forge.subscribe_lifecycle_events();
tokio::spawn(async move {
while let Ok(event) = rx.recv().await {
match event {
LifecycleEvent::ToolStarting { name, .. } => {
println!("Starting: {}", name);
}
LifecycleEvent::ToolCompleted { name, .. } => {
println!("Completed: {}", name);
}
LifecycleEvent::ToolFailed { name, error, .. } => {
eprintln!("Failed: {} - {}", name, error);
}
_ => {}
}
}
});
```
## Generated Code Tracking
Track files generated by tools:
```rust
use dx_forge::Forge;
use std::collections::HashMap;
let mut forge = Forge::new(".")?;
// Track a generated file
let mut metadata = HashMap::new();
metadata.insert("version".to_string(), "1.0.0".to_string());
metadata.insert("template".to_string(), "component".to_string());
forge.track_generated_file(
PathBuf::from("src/components/Button.tsx"),
"dx-codegen",
metadata
)?;
// Query generated files
let files = forge.get_generated_files("dx-codegen");
println!("Generated {} files", files.len());
// Cleanup
let removed = forge.cleanup_generated("dx-codegen").await?;
println!("Removed {} files", removed.len());
```
## Configuration
### ForgeConfig
```rust
pub struct ForgeConfig {
pub project_root: PathBuf,
pub forge_dir: PathBuf,
pub auto_watch: bool,
pub enable_lsp: bool,
pub enable_versioning: bool,
pub worker_threads: usize,
}
impl ForgeConfig {
pub fn new(project_root: impl AsRef<Path>) -> Self;
pub fn without_auto_watch(self) -> Self;
pub fn without_lsp(self) -> Self;
pub fn with_forge_dir(self, dir: impl AsRef<Path>) -> Self;
}
```
### OrchestratorConfig
```rust
pub struct OrchestratorConfig {
pub parallel: bool,
pub fail_fast: bool,
pub max_concurrent: usize,
pub traffic_branch_enabled: bool,
}
```
## Type Reference
### Version
```rust
pub struct Version {
pub major: u64,
pub minor: u64,
pub patch: u64,
pub pre_release: Option<String>,
pub build: Option<String>,
}
impl Version {
pub fn new(major: u64, minor: u64, patch: u64) -> Self;
pub fn is_compatible_with(&self, other: &Version) -> bool;
pub fn satisfies(&self, req: &VersionReq) -> bool;
pub fn is_prerelease(&self) -> bool;
pub fn is_stable(&self) -> bool;
}
```
### ToolOutput
```rust
pub struct ToolOutput {
pub success: bool,
pub files_modified: Vec<PathBuf>,
pub files_created: Vec<PathBuf>,
pub files_deleted: Vec<PathBuf>,
pub message: String,
pub duration_ms: u64,
}
impl ToolOutput {
pub fn success() -> Self;
pub fn failure(message: impl Into<String>) -> Self;
}
```
### ExecutionContext
```rust
pub struct ExecutionContext {
pub repo_root: PathBuf,
pub forge_path: PathBuf,
pub current_branch: Option<String>,
pub changed_files: Vec<PathBuf>,
pub shared_state: Arc<RwLock<HashMap<String, serde_json::Value>>>,
pub traffic_analyzer: Arc<dyn TrafficAnalyzer + Send + Sync>,
pub component_manager: Option<Arc<RwLock<ComponentStateManager>>>,
}
impl ExecutionContext {
pub fn new(repo_root: PathBuf, forge_path: PathBuf) -> Self;
pub fn set<T: Serialize>(&self, key: impl Into<String>, value: T) -> Result<()>;
pub fn get<T: for<'de> Deserialize<'de>>(&self, key: &str) -> Result<Option<T>>;
}
```
## Best Practices
### Tool Development
1. **Set appropriate priority**: Infrastructure tools (0-20), component tools (21-50), post-processing (51-100)
2. **Declare dependencies**: Use `dependencies()` for tools that must run first
3. **Implement should_run()**: Skip unnecessary execution
4. **Use lifecycle hooks**: Validate in `before_execute()`, cleanup in `after_execute()`
5. **Handle errors gracefully**: Implement `on_error()` for rollback logic
### Error Handling
1. Use `ToEnhanced` trait for better error messages
2. Leverage `with_retry()` for transient failures
3. Categorize errors for appropriate handling
4. Log errors with context
### Version Control
1. Create snapshots after significant changes
2. Use branches for experimental features
3. Review diffs before merging
4. Tag important snapshots
### Performance
1. Enable parallel execution for independent tools
2. Use file watching instead of polling
3. Leverage caching for components
4. Implement proper cleanup
## Examples
See the `examples/` directory for complete working examples:
- `simple.rs` - Basic tool registration and execution
- `traffic_branch_and_lsp.rs` - Traffic branch analysis
- `complete_dx_workflow.rs` - Full DX tools workflow
- `test_all_features.rs` - Feature demonstration