dx-forge 0.1.3

Production-ready VCS and orchestration engine for DX tools with Git-like versioning, dual-watcher architecture, traffic branch system, and component injection
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
# 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