ruvswarm-core 1.1.0

Core orchestration and agent traits for RUV Swarm
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
# ruvswarm-core 🧠🐝

[![Crates.io](https://img.shields.io/crates/v/ruvswarm-core.svg)](https://crates.io/crates/ruvswarm-core)
[![Documentation](https://docs.rs/ruvswarm-core/badge.svg)](https://docs.rs/ruvswarm-core)
[![License](https://img.shields.io/crates/l/ruvswarm-core.svg)](https://github.com/ruvnet/ruv-FANN/blob/main/LICENSE)

**Core orchestration and agent traits for RUV Swarm - the foundational building blocks for creating distributed AI agent swarms with cognitive diversity patterns.**

## 🎯 What is ruvswarm-core?

ruvswarm-core is the foundational orchestration crate that powers the RUV Swarm ecosystem. It provides the core traits, abstractions, and coordination primitives needed to build distributed AI agent systems with cognitive diversity patterns and advanced swarm behaviors.

This crate serves as the bedrock for all swarm operations, defining how agents communicate, coordinate, and execute tasks across different topologies and distribution strategies.

## ✨ Key Features

### 🤖 **Agent Management**
- **Agent Trait**: Core abstraction for all swarm agents with async processing
- **Cognitive Patterns**: Support for diverse thinking patterns (convergent, divergent, lateral, etc.)
- **Health Monitoring**: Real-time agent status tracking and health checks
- **Resource Management**: Configurable resource limits and requirements
- **Capability Discovery**: Dynamic agent capability registration and matching

### 🌐 **Swarm Coordination**
- **Multiple Topologies**: Mesh, hierarchical, ring, and star network topologies
- **Distribution Strategies**: Balanced, specialized, and adaptive task distribution
- **Task Orchestration**: Priority-based task queue with sophisticated scheduling
- **Message Passing**: Efficient inter-agent communication primitives
- **Fault Tolerance**: Graceful degradation and error recovery mechanisms

### 🧠 **Cognitive Architecture**
- **Pattern Diversity**: 7 distinct cognitive patterns for varied problem-solving approaches
- **Adaptive Behavior**: Agents can switch cognitive patterns based on task requirements
- **Collective Intelligence**: Emergent behaviors from agent interactions
- **Learning Coordination**: Support for distributed learning and knowledge sharing

### 🔧 **Platform Support**
- **No-std Compatible**: Runs in embedded and resource-constrained environments
- **WASM Ready**: Full WebAssembly support for browser and edge deployment
- **Async/Await**: Modern Rust asynchronous programming throughout
- **Type Safety**: Comprehensive error handling with detailed error types

## 📦 Installation

Add ruvswarm-core to your `Cargo.toml`:

```toml
[dependencies]
ruvswarm-core = "0.1.0"
```

### Feature Flags

Enable optional features based on your deployment needs:

```toml
[dependencies]
ruvswarm-core = { version = "0.1.0", features = ["std", "wasm"] }
```

Available features:
- `std` (default) - Standard library support with full functionality
- `no_std` - No standard library support for embedded environments
- `wasm` - WebAssembly support with JavaScript interop
- `minimal` - Minimal feature set for size optimization

## 🚀 Basic Usage Examples

### Simple Agent Implementation

```rust
use ruvswarm_core::prelude::*;
use async_trait::async_trait;

// Define a compute agent
struct ComputeAgent {
    id: String,
    capabilities: Vec<String>,
}

#[async_trait]
impl Agent for ComputeAgent {
    type Input = f64;
    type Output = f64;
    type Error = std::io::Error;

    async fn process(&mut self, input: Self::Input) -> Result<Self::Output, Self::Error> {
        // Simulate computational work
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        Ok(input * 2.0)
    }

    fn capabilities(&self) -> &[String] {
        &self.capabilities
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn cognitive_pattern(&self) -> CognitivePattern {
        CognitivePattern::Convergent
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create an agent
    let agent = ComputeAgent {
        id: "compute-001".to_string(),
        capabilities: vec!["mathematics".to_string(), "computation".to_string()],
    };

    // Process input
    let mut agent = agent;
    let result = agent.process(42.0).await?;
    println!("Agent processed 42.0 -> {}", result);

    Ok(())
}
```

### Swarm Creation and Task Distribution

```rust
use ruvswarm_core::{Swarm, SwarmConfig, Task, Priority, TopologyType};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Configure swarm with mesh topology
    let config = SwarmConfig {
        max_agents: 10,
        topology: TopologyType::Mesh,
        distribution_strategy: DistributionStrategy::Balanced,
        enable_monitoring: true,
        ..Default::default()
    };

    // Create swarm
    let mut swarm = Swarm::new(config).await?;

    // Add agents to swarm
    for i in 0..5 {
        let agent = ComputeAgent {
            id: format!("agent-{:03}", i),
            capabilities: vec!["computation".to_string()],
        };
        swarm.add_agent(Box::new(agent)).await?;
    }

    // Create and submit tasks
    for i in 0..20 {
        let task = Task::new(
            format!("task-{}", i),
            Priority::Medium,
            i as f64,
        );
        swarm.submit_task(task).await?;
    }

    // Process tasks
    swarm.start().await?;

    // Wait for completion
    while swarm.has_pending_tasks().await {
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    }

    println!("All tasks completed!");
    Ok(())
}
```

### Cognitive Pattern Switching

```rust
use ruvswarm_core::{Agent, CognitivePattern};

struct AdaptiveAgent {
    id: String,
    current_pattern: CognitivePattern,
}

impl AdaptiveAgent {
    fn switch_pattern(&mut self, task_type: &str) {
        self.current_pattern = match task_type {
            "creative" => CognitivePattern::Divergent,
            "analytical" => CognitivePattern::Convergent,
            "innovative" => CognitivePattern::Lateral,
            "systematic" => CognitivePattern::Systems,
            _ => CognitivePattern::Critical,
        };
    }
}

#[async_trait]
impl Agent for AdaptiveAgent {
    type Input = (String, f64); // (task_type, data)
    type Output = f64;
    type Error = std::io::Error;

    async fn process(&mut self, input: Self::Input) -> Result<Self::Output, Self::Error> {
        let (task_type, data) = input;
        
        // Switch cognitive pattern based on task
        self.switch_pattern(&task_type);
        
        // Process differently based on cognitive pattern
        let result = match self.current_pattern {
            CognitivePattern::Convergent => data * 1.1,
            CognitivePattern::Divergent => data * 1.5,
            CognitivePattern::Lateral => data.sqrt() * 2.0,
            CognitivePattern::Systems => data.ln() + 1.0,
            _ => data,
        };

        Ok(result)
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn cognitive_pattern(&self) -> CognitivePattern {
        self.current_pattern
    }

    fn capabilities(&self) -> &[String] {
        static CAPS: &[String] = &[];
        CAPS
    }
}
```

### Multi-Topology Swarm

```rust
use ruvswarm_core::{Topology, TopologyType};

async fn create_hierarchical_swarm() -> Result<(), Box<dyn std::error::Error>> {
    // Create hierarchical topology with coordinators and workers
    let topology = Topology::new(TopologyType::Hierarchical);
    
    let config = SwarmConfig {
        topology_type: TopologyType::Hierarchical,
        coordinator_count: 2,
        worker_count: 8,
        enable_fault_tolerance: true,
        ..Default::default()
    };

    let mut swarm = Swarm::with_topology(config, topology).await?;

    // Add coordinator agents
    for i in 0..2 {
        let coordinator = CoordinatorAgent::new(format!("coord-{}", i));
        swarm.add_coordinator(Box::new(coordinator)).await?;
    }

    // Add worker agents
    for i in 0..8 {
        let worker = WorkerAgent::new(format!("worker-{}", i));
        swarm.add_worker(Box::new(worker)).await?;
    }

    // Start coordinated processing
    swarm.start_coordinated().await?;

    Ok(())
}
```

## 🔗 Core API Documentation

### Agent Trait
The foundational trait that all swarm agents must implement:

```rust
#[async_trait]
pub trait Agent: Send + Sync {
    type Input: Send;
    type Output: Send;
    type Error: Send;

    async fn process(&mut self, input: Self::Input) -> Result<Self::Output, Self::Error>;
    fn id(&self) -> &str;
    fn capabilities(&self) -> &[String];
    fn cognitive_pattern(&self) -> CognitivePattern;
    fn health_status(&self) -> HealthStatus;
}
```

### Cognitive Patterns
Seven distinct patterns for diverse problem-solving approaches:

- **Convergent**: Focused, analytical thinking
- **Divergent**: Creative, expansive exploration
- **Lateral**: Innovative, non-linear approaches
- **Systems**: Holistic, interconnected analysis
- **Critical**: Evaluative, skeptical assessment
- **Abstract**: High-level conceptual thinking
- **Concrete**: Practical, detail-oriented processing

### Task Management
Priority-based task orchestration with sophisticated scheduling:

```rust
pub struct Task<T> {
    pub id: TaskId,
    pub priority: Priority,
    pub data: T,
    pub requirements: Vec<String>,
    pub timeout: Option<Duration>,
}

pub enum Priority {
    Low = 1,
    Medium = 2,
    High = 3,
    Critical = 4,
}
```

## 🌐 Topology Support

### Mesh Topology
Full connectivity between all agents for maximum redundancy:
- **Advantages**: High fault tolerance, optimal load distribution
- **Use Cases**: Critical systems, real-time processing

### Hierarchical Topology
Coordinator-worker structure for organized task flow:
- **Advantages**: Clear command structure, efficient resource management
- **Use Cases**: Large-scale processing, enterprise applications

### Ring Topology
Agents connected in a circular pattern:
- **Advantages**: Predictable communication patterns, lower bandwidth
- **Use Cases**: Sequential processing, token-ring algorithms

### Star Topology
Central hub with spoke connections to all agents:
- **Advantages**: Simple coordination, centralized control
- **Use Cases**: Centralized processing, hub-and-spoke architectures

## 📚 API Documentation

Complete API documentation is available on [docs.rs](https://docs.rs/ruvswarm-core):

- **[Agent Trait Documentation]https://docs.rs/ruvswarm-core/latest/ruvswarm_core/trait.Agent.html**
- **[Swarm Management]https://docs.rs/ruvswarm-core/latest/ruvswarm_core/struct.Swarm.html**  
- **[Task Coordination]https://docs.rs/ruvswarm-core/latest/ruvswarm_core/struct.Task.html**
- **[Topology Types]https://docs.rs/ruvswarm-core/latest/ruvswarm_core/enum.TopologyType.html**
- **[Cognitive Patterns]https://docs.rs/ruvswarm-core/latest/ruvswarm_core/enum.CognitivePattern.html**

## 🔗 Links

- **[Main Repository]https://github.com/ruvnet/ruv-FANN**: Complete RUV-FANN ecosystem
- **[ruvswarm]../../../**: Full swarm implementation using this core
- **[API Documentation]https://docs.rs/ruvswarm-core**: Complete API reference  
- **[Examples]../../examples/**: Practical implementation examples
- **[Benchmarks]../../benchmarks/**: Performance analysis and comparisons

## 🏗️ Architecture Integration

ruvswarm-core integrates seamlessly with the broader RUV ecosystem:

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   ruv-FANN      │    │   ruvswarm      │    │ neuro-divergent │
│ Neural Networks │◄──►│ Agent Swarms     │◄──►│   Forecasting   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                    ┌─────────────────┐
                    │ ruvswarm-core  │
                    │ Core Traits &   │
                    │ Orchestration   │
                    └─────────────────┘
```

## 🤝 Contributing

We welcome contributions to ruvswarm-core! Please see the main repository's [Contributing Guide](https://github.com/ruvnet/ruv-FANN/blob/main/CONTRIBUTING.md) for details.

### Development Setup

```bash
# Clone the main repository
git clone https://github.com/ruvnet/ruv-FANN.git
cd ruv-FANN/ruvswarm/crates/ruvswarm-core

# Run tests
cargo test --all-features

# Run benchmarks
cargo bench

# Check no-std compatibility
cargo check --no-default-features --features no_std

# Test WASM compatibility
cargo check --target wasm32-unknown-unknown --features wasm
```

## 📄 License

Licensed under either of:

- **Apache License, Version 2.0** ([LICENSE-APACHE]https://github.com/ruvnet/ruv-FANN/blob/main/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- **MIT License** ([LICENSE-MIT]https://github.com/ruvnet/ruv-FANN/blob/main/LICENSE-MIT or http://opensource.org/licenses/MIT)

at your option.

---

**Created by rUv** 

*Building the future of distributed AI agent orchestration - one cognitive pattern at a time.*

Part of the **[RUV-FANN](https://github.com/ruvnet/ruv-FANN)** ecosystem for neural networks, agent swarms, and AI forecasting.