xynthe 0.1.0

A unified orchestration framework for autonomous intelligence with temporal continuity
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Execution Engine - Temporal cognitive loop orchestration
//!
//! The execution engine orchestrates the GIAM-Aligned Temporal Execution Loop (G-TEL):
//! 1. Perceive / Intent Ingestion
//! 2. Reason / Goal Decomposition
//! 3. Layer Assignment
//! 4. Act / Execution
//! 5. Reflect / Evaluation
//! 6. Adaptation & Optimization
//! 7. Continuation
//!
//! This enables long-horizon, state-preserving execution graphs that evolve
//! and persist across sessions.

use crate::capability_binding::{CapabilityRegistry, CapabilityResult};
use crate::context_fabric::{ContextFabric, ContextQuery, TimeWindow};
use crate::thought_stream::{ThoughtEvent, ThoughtEventType};
use crate::trace::{TraceEvent, TraceRecorder, ExecutionTrace};
use crate::types::{ProvenanceChain, StructuredContent, Timestamp};
use crate::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;

/// Current execution state
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionState {
    /// Initial state
    Initialized,

    /// Perceiving input
    Perceiving,

    /// Reasoning about goals
    Reasoning,

    /// Assigning to execution layers
    Assigning,

    /// Executing capabilities
    Executing,

    /// Reflecting on results
    Reflecting,

    /// Completed successfully
    Completed,

    /// Failed execution
    Failed,

    /// Paused for intervention
    Paused,
}

impl ExecutionState {
    /// Get the state as a string
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Initialized => "initialized",
            Self::Perceiving => "perceiving",
            Self::Reasoning => "reasoning",
            Self::Assigning => "assigning",
            Self::Executing => "executing",
            Self::Reflecting => "reflecting",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Paused => "paused",
        }
    }
}

/// Execution configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionConfig {
    /// Enable tracing
    pub tracing_enabled: bool,

    /// Auto-finalize traces
    pub auto_finalize: bool,

    /// Pause on failure
    pub pause_on_failure: bool,

    /// Require approval for high-impact actions
    pub require_approval: bool,

    /// Maximum execution time (seconds)
    pub max_execution_time: Option<u64>,

    /// Reflection frequency (every n steps)
    pub reflection_frequency: usize,
}

impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            tracing_enabled: true,
            auto_finalize: true,
            pause_on_failure: false,
            require_approval: false,
            max_execution_time: Some(3600), // 1 hour
            reflection_frequency: 10,
        }
    }
}

/// Intent to be executed
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionIntent {
    /// Intent identifier
    pub id: Uuid,

    /// Intent description
    pub description: String,

    /// Priority (higher = more important)
    pub priority: u32,

    /// Creation timestamp
    pub created_at: Timestamp,

    /// Optional deadline
    pub deadline: Option<Timestamp>,

    /// Context and parameters
    pub context: StructuredContent,
}

impl ExecutionIntent {
    /// Create a new intent
    pub fn new(description: impl Into<String>, context: StructuredContent) -> Self {
        Self {
            id: Uuid::new_v4(),
            description: description.into(),
            priority: 50, // Default medium priority
            created_at: Timestamp::now(),
            deadline: None,
            context,
        }
    }

    /// Set the priority
    pub fn with_priority(mut self, priority: u32) -> Self {
        self.priority = priority.clamp(0, 100);
        self
    }

    /// Set the deadline
    pub fn with_deadline(mut self, deadline: Timestamp) -> Self {
        self.deadline = Some(deadline);
        self
    }
}

/// Decomposed subgoal from an intent
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Subgoal {
    /// Subgoal identifier
    pub id: Uuid,

    /// Parent intent ID
    pub parent_id: Uuid,

    /// Description
    pub description: String,

    /// Required capabilities
    pub required_capabilities: Vec<String>,

    /// Preconditions to check
    pub preconditions: Vec<String>,

    /// Assigned execution layer
    pub assigned_layer: Option<String>,

    /// Current status
    pub status: SubgoalStatus,
}

impl Subgoal {
    /// Create a new subgoal
    pub fn new(parent_id: Uuid, description: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4(),
            parent_id,
            description: description.into(),
            required_capabilities: Vec::new(),
            preconditions: Vec::new(),
            assigned_layer: None,
            status: SubgoalStatus::Pending,
        }
    }

    /// Add a required capability
    pub fn requires(mut self, capability: impl Into<String>) -> Self {
        self.required_capabilities.push(capability.into());
        self
    }

    /// Add a precondition
    pub fn with_precondition(mut self, precondition: impl Into<String>) -> Self {
        self.preconditions.push(precondition.into());
        self
    }
}

/// Status of a subgoal
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubgoalStatus {
    /// Waiting to start
    Pending,

    /// Currently executing
    InProgress,

    /// Completed successfully
    Completed,

    /// Failed
    Failed,

    /// Blocked by dependencies
    Blocked,

    /// Requires approval
    RequiresApproval,
}

/// Result of execution
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionResult {
    /// Whether execution succeeded
    pub success: bool,

    /// Result data
    pub data: StructuredContent,

    /// Number of steps executed
    pub steps_executed: usize,

    /// Trace ID
    pub trace_id: Uuid,

    /// Error if execution failed
    pub error: Option<String>,
}

impl ExecutionResult {
    /// Create a successful result
    pub fn success(data: StructuredContent, steps: usize, trace_id: Uuid) -> Self {
        Self {
            success: true,
            data,
            steps_executed: steps,
            trace_id,
            error: None,
        }
    }

    /// Create a failed result
    pub fn failure(error: String, steps: usize, trace_id: Uuid) -> Self {
        Self {
            success: false,
            data: StructuredContent::text(""),
            steps_executed: steps,
            trace_id,
            error: Some(error),
        }
    }
}

/// Execution statistics
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ExecutionStats {
    /// Total steps
    pub total_steps: usize,

    /// Steps successfully completed
    pub completed_steps: usize,

    /// Steps failed
    pub failed_steps: usize,

    /// Average step duration in ms
    pub avg_step_duration_ms: u64,

    /// Total execution time in ms
    pub total_duration_ms: u64,

    /// Number of human interventions
    pub interventions: usize,
}

/// The main execution engine
pub struct ExecutionEngine {
    /// Stream for cognitive events
    thought_stream: Arc<crate::thought_stream::ThoughtStream>,

    /// Capability registry
    capability_registry: Arc<crate::capability_binding::CapabilityRegistry>,

    /// Context fabric
    context_fabric: Arc<crate::context_fabric::ContextFabric>,

    /// Trace recorder
    trace_recorder: Arc<TraceRecorder>,

    /// Current execution state
    state: Arc<RwLock<ExecutionState>>,

    /// Active intents
    intents: Arc<RwLock<Vec<ExecutionIntent>>>,

    /// Active subgoals
    subgoals: Arc<RwLock<Vec<Subgoal>>>,

    /// Configuration
    config: Arc<RwLock<ExecutionConfig>>,

    /// Execution statistics
    stats: Arc<RwLock<ExecutionStats>>,
}

impl ExecutionEngine {
    /// Create a new execution engine
    pub fn new(
        thought_stream: Arc<crate::thought_stream::ThoughtStream>,
        capability_registry: Arc<crate::capability_binding::CapabilityRegistry>,
        context_fabric: Arc<crate::context_fabric::ContextFabric>,
    ) -> Self {
        let trace_recorder = Arc::new(TraceRecorder::new("execution_engine"));

        Self {
            thought_stream: thought_stream.clone(),
            capability_registry,
            context_fabric,
            trace_recorder,
            state: Arc::new(RwLock::new(ExecutionState::Initialized)),
            intents: Arc::new(RwLock::new(Vec::new())),
            subgoals: Arc::new(RwLock::new(Vec::new())),
            config: Arc::new(RwLock::new(ExecutionConfig::default())),
            stats: Arc::new(RwLock::new(ExecutionStats::default())),
        }
    }

    /// Execute an intent through the full temporal cognitive loop
    pub async fn execute(&self, intent: ExecutionIntent) -> Result<ExecutionResult> {
        // Update state
    let start_time = std::time::Instant::now();
        *self.state.write().await = ExecutionState::Perceiving;

        // 1. Perceive / Intent Ingestion
        self.ingest_intent(&intent).await?;

        // 2. Reason / Goal Decomposition
        *self.state.write().await = ExecutionState::Reasoning;
        let subgoals = self.decompose_intent(&intent).await?;

        // 3. Layer Assignment
        *self.state.write().await = ExecutionState::Assigning;
        self.assign_layers(&subgoals).await?;

        // 4. Act / Execution
        *self.state.write().await = ExecutionState::Executing;
        let mut steps = 0;
        let mut final_result = StructuredContent::text("");

        for subgoal in subgoals {
            match self.execute_subgoal(subgoal).await {
                Ok(result) => {
                    steps += 1;
                    final_result = result;
                }
                Err(e) => {
                    *self.state.write().await = ExecutionState::Failed;
                let elapsed_ms = start_time.elapsed().as_millis() as u64;
                self.update_stats(|s| s.total_duration_ms = elapsed_ms).await;
                            return Err(e);
                        }
                    }
                }

        // 5. Reflection
        *self.state.write().await = ExecutionState::Reflecting;
        self.reflect_on_execution(&intent, steps).await?;

        // 6. & 7. Adaptation and continuation handled implicitly
        *self.state.write().await = ExecutionState::Completed;

        // Finalize trace
        let trace = self.trace_recorder.finalize().await;
        let trace_id = trace.id;

        Ok(ExecutionResult::success(final_result, steps, trace_id))
    }

    /// Ingest an intent and emit observation event
    pub async fn ingest_intent(&self, intent: &ExecutionIntent) -> Result<()> {
        self.update_stats(|s| s.total_steps += 1).await;

        let event = ThoughtEvent::observation(
            StructuredContent::json(serde_json::json!({
                "intent_id": intent.id,
                "description": &intent.description,
                "priority": intent.priority,
            })),
            ProvenanceChain::new(),
        );

        self.thought_stream.emit(event.clone()).unwrap();
        self.trace_recorder.record_thought(event).await;

        Ok(())
    }

    /// Decompose an intent into subgoals
    pub async fn decompose_intent(&self, intent: &ExecutionIntent) -> Result<Vec<Subgoal>> {
        self.update_stats(|s| s.total_steps += 1).await;

        // In a real implementation, this would use planning algorithms
        // For now, create a simple decomposition
        let mut subgoals = Vec::new();

        let subgoal = Subgoal::new(intent.id, "Execute main goal")
            .requires("execute")
            .with_precondition("intent_validated");

        subgoals.push(subgoal);

        // Store subgoals
        let mut stored_subgoals = self.subgoals.write().await;
        stored_subgoals.extend(subgoals.clone());

        // Emit intention event
        let event = ThoughtEvent::intention(
            StructuredContent::json(serde_json::json!({
                "intent_id": intent.id,
                "subgoals_count": subgoals.len(),
            })),
            ProvenanceChain::new(),
        );

        self.thought_stream.emit(event.clone()).unwrap();
        self.trace_recorder.record_thought(event).await;

        Ok(subgoals)
    }

    /// Assign execution layers to subgoals
    pub async fn assign_layers(&self, subgoals: &[Subgoal]) -> Result<()> {
        self.update_stats(|s| s.total_steps += 1).await;

        // Simple assignment - all to SI layer for now
        for subgoal in subgoals {
            let event = ThoughtEvent::reflection(
                StructuredContent::json(serde_json::json!({
                    "subgoal_id": subgoal.id,
                    "assigned_layer": "SI",
                })),
                ProvenanceChain::new(),
            );

            self.thought_stream.emit(event.clone()).unwrap();
            self.trace_recorder.record_thought(event).await;
        }

        Ok(())
    }

    /// Execute a single subgoal
    pub async fn execute_subgoal(&self, mut subgoal: Subgoal) -> Result<StructuredContent> {
        self.update_stats(|s| s.completed_steps += 1).await;

        subgoal.status = SubgoalStatus::InProgress;

        // Execute required capability
        if let Some(cap_name) = subgoal.required_capabilities.first() {
            let input = StructuredContent::json(serde_json::json!({
                "subgoal_id": subgoal.id,
                "description": subgoal.description,
            }));

            match self.capability_registry.invoke(cap_name, input).await {
                Ok(result) => {
                    subgoal.status = SubgoalStatus::Completed;

                    // Emit success event
                    let event = ThoughtEvent::new(
                        ThoughtEventType::Success,
                        StructuredContent::json(serde_json::json!({
                            "subgoal_id": subgoal.id,
                            "result": "completed",
                        })),
                        ProvenanceChain::new(),
                        1.0,
                    );

                    self.thought_stream.emit(event.clone()).unwrap();
                    self.trace_recorder.record_thought(event).await;

                    Ok(result.data)
                }
                Err(e) => {
                    subgoal.status = SubgoalStatus::Failed;

                    let event = ThoughtEvent::new(
                        ThoughtEventType::Warning,
                        StructuredContent::json(serde_json::json!({
                            "subgoal_id": subgoal.id,
                            "error": e.to_string(),
                        })),
                        ProvenanceChain::new(),
                        1.0,
                    );

                    self.thought_stream.emit(event.clone()).unwrap();
                    self.trace_recorder.record_thought(event).await;

                    Err(e)
                }
            }
        } else {
            Ok(StructuredContent::text("No capabilities required"))
        }
    }

    /// Reflect on execution and update state
    pub async fn reflect_on_execution(&self, intent: &ExecutionIntent, steps: usize) -> Result<()> {
        self.update_stats(|s| {
            s.total_duration_ms = 0; // Will be updated at completion
        }).await;

        // Retrieve thought events from execution
        let window = TimeWindow::new(intent.created_at, Timestamp::now());
        let query = ContextQuery::recall("execution.", window); // Use prefix search

        if let Ok(result) = self.context_fabric.query(query).await {
            let reflection = serde_json::json!({
                "intent_id": intent.id,
                "steps_executed": steps,
                "thoughts_count": result.events.len(),
                "success": true,
            });

            let event = ThoughtEvent::reflection(
                StructuredContent::json(reflection),
                ProvenanceChain::new(),
            );

            self.thought_stream.emit(event.clone()).unwrap();
            self.trace_recorder.record_thought(event).await;
        }

        Ok(())
    }

    /// Get the current execution state
    pub async fn state(&self) -> ExecutionState {
        *self.state.read().await
    }

    /// Get execution statistics
    pub async fn stats(&self) -> ExecutionStats {
        self.stats.read().await.clone()
    }

    /// Update statistics
    async fn update_stats<F>(&self, updater: F)
    where
        F: FnOnce(&mut ExecutionStats),
    {
        let mut stats = self.stats.write().await;
        updater(&mut stats);
    }

    /// Get the trace recorder
    pub fn trace_recorder(&self) -> Arc<TraceRecorder> {
        self.trace_recorder.clone()
    }

    /// Get all intents
    pub async fn intents(&self) -> Vec<ExecutionIntent> {
        self.intents.read().await.clone()
    }

    /// Get all subgoals
    pub async fn subgoals(&self) -> Vec<Subgoal> {
        self.subgoals.read().await.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_execution_intent_creation() {
        let context = StructuredContent::text("test context");
        let intent = ExecutionIntent::new("test intent", context);

        assert_eq!(intent.description, "test intent");
        assert!(intent.deadline.is_none());
    }

    #[test]
    fn test_execution_state() {
        assert_eq!(ExecutionState::Initialized.as_str(), "initialized");
        assert_eq!(ExecutionState::Executing.as_str(), "executing");
    }

    #[test]
    fn test_subgoal_creation() {
        let parent_id = Uuid::new_v4();
        let subgoal = Subgoal::new(parent_id, "test subgoal");

        assert_eq!(subgoal.description, "test subgoal");
        assert_eq!(subgoal.status, SubgoalStatus::Pending);
    }

    #[test]
    fn test_execution_result() {
        let result = ExecutionResult::success(
            StructuredContent::text("success"),
            5,
            Uuid::new_v4(),
        );

        assert!(result.success);
        assert_eq!(result.steps_executed, 5);
    }
}