ggen 1.2.0

ggen is a deterministic, language-agnostic code generation framework that treats software artifacts as projections of knowledge graphs.
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
//! Simplified Agent System - Core Team Best Practices Implementation
//!
//! This module provides a maintainable, performant agent system that focuses
//! on the 80/20 principle: 20% of the code handles 80% of the value.
//!
//! # Simplified Architecture
//!
//! - **Agent Registry**: Centralized agent management
//! - **Message Passing**: Simple, reliable inter-agent communication
//! - **Task Coordination**: Lightweight task distribution
//! - **Knowledge Sharing**: Efficient knowledge transfer between agents

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Simplified agent trait - no async complexity
pub trait SimpleAgent: Send + Sync {
    fn id(&self) -> &str;
    fn specialization(&self) -> AgentSpecialization;
    fn execute_sync(&self, context: &AgentContext) -> AgentResult;
    fn coordinate_sync(&self, message: CoordinationMessage) -> AgentResult;
    fn status(&self) -> AgentStatus;
}

/// Agent specialization domains (simplified)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum AgentSpecialization {
    LondonBdd,           // BDD orchestration
    Byzantene,           // Fault tolerance
    MarketIntelligence,  // Marketplace analytics
    SemanticAnalyst,     // Knowledge analysis
    SecuritySentinel,    // Security monitoring
    PerformanceGuardian, // Performance monitoring
}

/// Agent execution context
#[derive(Debug, Clone)]
pub struct AgentContext {
    pub request_id: Uuid,
    pub project_context: ProjectContext,
    pub execution_environment: ExecutionEnvironment,
}

/// Project context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectContext {
    pub project_id: String,
    pub project_type: String,
    pub technology_stack: Vec<String>,
}

/// Execution environment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionEnvironment {
    pub available_resources: ResourceAllocation,
    pub network_status: NetworkStatus,
}

/// Resource allocation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceAllocation {
    pub cpu_cores: u32,
    pub memory_mb: u64,
}

/// Network status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NetworkStatus {
    Online,
    Limited,
    Offline,
}

/// Agent execution results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentResult {
    pub success: bool,
    pub output: serde_json::Value,
    pub confidence: f64,
    pub execution_time_ms: u64,
    pub recommendations: Vec<String>,
}

/// Coordination messages
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationMessage {
    pub from_agent: String,
    pub to_agent: String,
    pub message_type: MessageType,
    pub payload: serde_json::Value,
    pub priority: Priority,
}

/// Message types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MessageType {
    StatusUpdate,
    TaskDelegation,
    KnowledgeShare,
    Coordination,
}

/// Priority levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Priority {
    Low,
    Medium,
    High,
    Critical,
}

/// Agent status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentStatus {
    pub agent_id: String,
    pub specialization: AgentSpecialization,
    pub current_load: f64,
    pub health_score: f64,
    pub last_activity: chrono::DateTime<chrono::Utc>,
    pub active_tasks: Vec<String>,
}

/// Agent registry for managing all agents
pub struct AgentRegistry {
    agents: HashMap<String, Box<dyn SimpleAgent>>,
}

impl Default for AgentRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl AgentRegistry {
    pub fn new() -> Self {
        Self {
            agents: HashMap::new(),
        }
    }

    pub fn register(&mut self, agent: Box<dyn SimpleAgent>) {
        self.agents.insert(agent.id().to_string(), agent);
    }

    pub fn get(&self, id: &str) -> Option<&dyn SimpleAgent> {
        self.agents.get(id).map(|v| &**v)
    }

    pub fn list(&self) -> Vec<&str> {
        self.agents.keys().map(|s| s.as_str()).collect()
    }

    pub fn get_by_specialization(
        &self, specialization: &AgentSpecialization,
    ) -> Vec<&dyn SimpleAgent> {
        self.agents
            .values()
            .filter(|agent| agent.specialization() == *specialization)
            .map(|agent| &**agent)
            .collect()
    }
}

/// Message router for inter-agent communication
pub struct MessageRouter {
    message_queue: Vec<CoordinationMessage>,
}

impl Default for MessageRouter {
    fn default() -> Self {
        Self::new()
    }
}

impl MessageRouter {
    pub fn new() -> Self {
        Self {
            message_queue: Vec::new(),
        }
    }

    pub fn route_message(&mut self, message: CoordinationMessage) -> RoutingResult {
        self.message_queue.push(message.clone());

        RoutingResult {
            message_id: Uuid::new_v4().to_string(),
            delivered_to: vec![message.to_agent.clone()],
            delivery_successful: true,
            response_time_ms: 50,
        }
    }

    pub fn process_messages(&mut self, agents: &AgentRegistry) -> Vec<AgentResult> {
        let mut results = Vec::new();

        while let Some(message) = self.message_queue.pop() {
            if let Some(agent) = agents.get(&message.to_agent) {
                let result = agent.coordinate_sync(message);
                results.push(result);
            }
        }

        results
    }
}

/// Routing result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingResult {
    pub message_id: String,
    pub delivered_to: Vec<String>,
    pub delivery_successful: bool,
    pub response_time_ms: u64,
}

/// Task coordinator for distributing work
pub struct TaskCoordinator {
    tasks: Vec<CoordinationTask>,
    #[allow(dead_code)]
    completed_tasks: Vec<String>,
}

impl Default for TaskCoordinator {
    fn default() -> Self {
        Self::new()
    }
}

impl TaskCoordinator {
    pub fn new() -> Self {
        Self {
            tasks: Vec::new(),
            completed_tasks: Vec::new(),
        }
    }

    pub fn add_task(&mut self, task: CoordinationTask) {
        self.tasks.push(task);
    }

    pub fn coordinate_tasks(&mut self, agents: &AgentRegistry) -> Vec<TaskResult> {
        let mut results = Vec::new();

        for task in &self.tasks {
            if let Some(agent) = self.select_agent_for_task(task, agents) {
                let context = AgentContext {
                    request_id: Uuid::new_v4(),
                    project_context: ProjectContext {
                        project_id: "ggen-marketplace".to_string(),
                        project_type: "library".to_string(),
                        technology_stack: vec!["rust".to_string()],
                    },
                    execution_environment: ExecutionEnvironment {
                        available_resources: ResourceAllocation {
                            cpu_cores: 4,
                            memory_mb: 8192,
                        },
                        network_status: NetworkStatus::Online,
                    },
                };

                let result = agent.execute_sync(&context);
                results.push(TaskResult {
                    task_id: task.id.clone(),
                    success: result.success,
                    execution_time_ms: result.execution_time_ms,
                    agent_used: agent.id().to_string(),
                });
            }
        }

        results
    }

    fn select_agent_for_task<'a>(
        &self, task: &CoordinationTask, agents: &'a AgentRegistry,
    ) -> Option<&'a dyn SimpleAgent> {
        agents
            .get_by_specialization(&task.required_specialization)
            .first()
            .copied()
    }
}

/// Coordination task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationTask {
    pub id: String,
    pub task_type: String,
    pub priority: Priority,
    pub required_specialization: AgentSpecialization,
    pub input_data: serde_json::Value,
}

/// Task result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskResult {
    pub task_id: String,
    pub success: bool,
    pub execution_time_ms: u64,
    pub agent_used: String,
}

/// Agent system status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemStatus {
    pub total_agents: usize,
    pub active_tasks: usize,
    pub system_health: f64,
    pub last_updated: chrono::DateTime<chrono::Utc>,
}

/// Agent system for simplified orchestration
pub struct AgentSystem {
    registry: AgentRegistry,
    message_router: MessageRouter,
    task_coordinator: TaskCoordinator,
}

impl Default for AgentSystem {
    fn default() -> Self {
        Self::new()
    }
}

impl AgentSystem {
    pub fn new() -> Self {
        Self {
            registry: AgentRegistry::new(),
            message_router: MessageRouter::new(),
            task_coordinator: TaskCoordinator::new(),
        }
    }

    pub fn register_agent(&mut self, agent: Box<dyn SimpleAgent>) {
        self.registry.register(agent);
    }

    pub fn get_status(&self) -> SystemStatus {
        SystemStatus {
            total_agents: self.registry.list().len(),
            active_tasks: self.task_coordinator.tasks.len(),
            system_health: 0.95, // Simplified for demo
            last_updated: chrono::Utc::now(),
        }
    }

    pub fn coordinate_task(&mut self, task: CoordinationTask) -> TaskResult {
        self.task_coordinator.add_task(task);
        let results = self.task_coordinator.coordinate_tasks(&self.registry);

        results.into_iter().next().unwrap_or_else(|| TaskResult {
            task_id: "unknown".to_string(),
            success: false,
            execution_time_ms: 0,
            agent_used: "none".to_string(),
        })
    }

    pub fn process_messages(&mut self) -> Vec<AgentResult> {
        self.message_router.process_messages(&self.registry)
    }
}

/// London BDD Agent (simplified implementation)
pub struct LondonBddAgent {
    id: String,
}

impl Default for LondonBddAgent {
    fn default() -> Self {
        Self::new()
    }
}

impl LondonBddAgent {
    pub fn new() -> Self {
        Self {
            id: "london-bdd-001".to_string(),
        }
    }
}

impl SimpleAgent for LondonBddAgent {
    fn id(&self) -> &str {
        &self.id
    }

    fn specialization(&self) -> AgentSpecialization {
        AgentSpecialization::LondonBdd
    }

    fn execute_sync(&self, _context: &AgentContext) -> AgentResult {
        AgentResult {
            success: true,
            output: serde_json::json!({"bdd_analysis": "completed"}),
            confidence: 0.95,
            execution_time_ms: 200,
            recommendations: vec!["Add more BDD scenarios".to_string()],
        }
    }

    fn coordinate_sync(&self, _message: CoordinationMessage) -> AgentResult {
        AgentResult {
            success: true,
            output: serde_json::json!({"coordination_acknowledged": true}),
            confidence: 1.0,
            execution_time_ms: 50,
            recommendations: vec![],
        }
    }

    fn status(&self) -> AgentStatus {
        AgentStatus {
            agent_id: self.id.clone(),
            specialization: AgentSpecialization::LondonBdd,
            current_load: 0.3,
            health_score: 0.95,
            last_activity: chrono::Utc::now(),
            active_tasks: vec!["bdd_orchestration".to_string()],
        }
    }
}

/// Byzantene Agent (simplified implementation)
pub struct ByzanteneAgent {
    id: String,
}

impl Default for ByzanteneAgent {
    fn default() -> Self {
        Self::new()
    }
}

impl ByzanteneAgent {
    pub fn new() -> Self {
        Self {
            id: "byzantene-001".to_string(),
        }
    }
}

impl SimpleAgent for ByzanteneAgent {
    fn id(&self) -> &str {
        &self.id
    }

    fn specialization(&self) -> AgentSpecialization {
        AgentSpecialization::Byzantene
    }

    fn execute_sync(&self, _context: &AgentContext) -> AgentResult {
        AgentResult {
            success: true,
            output: serde_json::json!({"fault_tolerance": "active"}),
            confidence: 0.98,
            execution_time_ms: 100,
            recommendations: vec!["Monitor agent health".to_string()],
        }
    }

    fn coordinate_sync(&self, _message: CoordinationMessage) -> AgentResult {
        AgentResult {
            success: true,
            output: serde_json::json!({"coordination_acknowledged": true}),
            confidence: 1.0,
            execution_time_ms: 50,
            recommendations: vec![],
        }
    }

    fn status(&self) -> AgentStatus {
        AgentStatus {
            agent_id: self.id.clone(),
            specialization: AgentSpecialization::Byzantene,
            current_load: 0.2,
            health_score: 0.98,
            last_activity: chrono::Utc::now(),
            active_tasks: vec!["fault_detection".to_string()],
        }
    }
}