enact-core 0.0.2

Core agent runtime for Enact - Graph-Native AI agents
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
//! Background Executor - Runs callables in background mode
//!
//! The executor handles different background execution modes:
//! - FireAndForget: Don't wait for result, no streaming
//! - Silent: Wait for result, but suppress streaming events
//! - Deferred: Queue for later execution
//!
//! @see packages/enact-schemas/src/execution.schemas.ts

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::kernel::ids::{ExecutionId, SpawnMode, TenantId};
use crate::kernel::ExecutionError;

use super::target_binding::TargetBindingConfig;
use super::trigger::{RetryConfig, TriggerId};

/// BackgroundExecutionMode - How to run a background callable
/// @see packages/enact-schemas/src/execution.schemas.ts - backgroundExecutionModeSchema
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum BackgroundExecutionMode {
    /// Don't wait for result, no streaming
    #[default]
    FireAndForget,
    /// Wait for result, but no streaming
    Silent,
    /// Queue for later execution
    Deferred,
}

/// BackgroundExecutionStatus - Status of a background execution
/// @see packages/enact-schemas/src/execution.schemas.ts - backgroundExecutionStatusSchema
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum BackgroundExecutionStatus {
    /// Waiting to execute
    #[default]
    Queued,
    /// Currently executing
    Running,
    /// Finished successfully
    Completed,
    /// Failed with error
    Failed,
    /// Cancelled before completion
    Cancelled,
    /// Exceeded timeout
    Timeout,
}

/// BackgroundExecutionConfig - Configuration for background execution
/// @see packages/enact-schemas/src/execution.schemas.ts - backgroundExecutionConfigSchema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BackgroundExecutionConfig {
    /// Execution mode
    #[serde(default)]
    pub mode: BackgroundExecutionMode,

    /// Priority (higher = runs sooner)
    #[serde(default = "default_priority")]
    pub priority: u8,

    /// Maximum execution time in milliseconds
    #[serde(default = "default_timeout_ms")]
    pub timeout_ms: u64,

    /// Target binding for result
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_binding: Option<TargetBindingConfig>,

    /// Callback URL (for deferred mode)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callback_url: Option<String>,

    /// Retry configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry: Option<RetryConfig>,
}

fn default_priority() -> u8 {
    50
}

fn default_timeout_ms() -> u64 {
    300000 // 5 minutes
}

impl Default for BackgroundExecutionConfig {
    fn default() -> Self {
        Self {
            mode: BackgroundExecutionMode::FireAndForget,
            priority: default_priority(),
            timeout_ms: default_timeout_ms(),
            target_binding: None,
            callback_url: None,
            retry: None,
        }
    }
}

/// BackgroundExecution - A background execution record
/// @see packages/enact-schemas/src/execution.schemas.ts - backgroundExecutionSchema
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BackgroundExecution {
    /// Execution ID
    pub execution_id: ExecutionId,

    /// Tenant that owns this execution
    pub tenant_id: TenantId,

    /// Callable to invoke
    pub callable_name: String,

    /// Input to pass to the callable
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,

    /// Context to pass
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<HashMap<String, String>>,

    /// Configuration
    pub config: BackgroundExecutionConfig,

    /// Current status
    #[serde(default)]
    pub status: BackgroundExecutionStatus,

    /// When execution was queued
    pub queued_at: DateTime<Utc>,

    /// When execution started
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<DateTime<Utc>>,

    /// When execution completed
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<DateTime<Utc>>,

    /// Output (populated on completion)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<serde_json::Value>,

    /// Error (populated on failure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ExecutionError>,

    /// Whether target binding was applied
    #[serde(default)]
    pub target_binding_applied: bool,

    /// Trigger that spawned this execution (if any)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_id: Option<TriggerId>,

    /// Metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

impl BackgroundExecution {
    /// Create a new background execution
    pub fn new(
        tenant_id: TenantId,
        callable_name: impl Into<String>,
        config: BackgroundExecutionConfig,
    ) -> Self {
        Self {
            execution_id: ExecutionId::new(),
            tenant_id,
            callable_name: callable_name.into(),
            input: None,
            context: None,
            config,
            status: BackgroundExecutionStatus::Queued,
            queued_at: Utc::now(),
            started_at: None,
            completed_at: None,
            output: None,
            error: None,
            target_binding_applied: false,
            trigger_id: None,
            metadata: None,
        }
    }

    /// Create from a trigger
    pub fn from_trigger(
        tenant_id: TenantId,
        trigger_id: TriggerId,
        callable_name: impl Into<String>,
        input: Option<String>,
        context: Option<HashMap<String, String>>,
        target_binding: Option<TargetBindingConfig>,
        retry: Option<RetryConfig>,
    ) -> Self {
        let config = BackgroundExecutionConfig {
            mode: BackgroundExecutionMode::Silent,
            target_binding,
            retry,
            ..Default::default()
        };

        let mut execution = Self::new(tenant_id, callable_name, config);
        execution.trigger_id = Some(trigger_id);
        execution.input = input;
        execution.context = context;
        execution
    }

    /// Create from SpawnMode::Child
    ///
    /// This bridges the gap between SpawnMode::Child { background: true, .. }
    /// and the BackgroundExecution infrastructure.
    ///
    /// @see docs/TECHNICAL/32-SPAWN-MODE.md
    pub fn from_spawn_mode(
        spawn_mode: &SpawnMode,
        tenant_id: TenantId,
        callable_name: impl Into<String>,
        input: Option<String>,
        context: Option<HashMap<String, String>>,
    ) -> Option<Self> {
        match spawn_mode {
            SpawnMode::Child {
                background: true, ..
            } => {
                // Background=true means fire-and-forget execution
                let config = BackgroundExecutionConfig {
                    mode: BackgroundExecutionMode::FireAndForget,
                    ..Default::default()
                };

                let mut execution = Self::new(tenant_id, callable_name, config);
                execution.input = input;
                execution.context = context;
                Some(execution)
            }
            SpawnMode::Child {
                background: false, ..
            } => {
                // Background=false means inline execution - not a background execution
                None
            }
            SpawnMode::Inline => {
                // Inline mode doesn't create a separate execution
                None
            }
        }
    }

    /// Check if a SpawnMode should create a background execution
    pub fn should_run_background(spawn_mode: &SpawnMode) -> bool {
        matches!(
            spawn_mode,
            SpawnMode::Child {
                background: true,
                ..
            }
        )
    }

    /// Mark execution as started
    pub fn start(&mut self) {
        self.status = BackgroundExecutionStatus::Running;
        self.started_at = Some(Utc::now());
    }

    /// Mark execution as completed
    pub fn complete(&mut self, output: serde_json::Value) {
        self.status = BackgroundExecutionStatus::Completed;
        self.completed_at = Some(Utc::now());
        self.output = Some(output);
    }

    /// Mark execution as failed
    pub fn fail(&mut self, error: ExecutionError) {
        self.status = BackgroundExecutionStatus::Failed;
        self.completed_at = Some(Utc::now());
        self.error = Some(error);
    }

    /// Mark execution as cancelled
    pub fn cancel(&mut self) {
        self.status = BackgroundExecutionStatus::Cancelled;
        self.completed_at = Some(Utc::now());
    }

    /// Mark execution as timed out
    pub fn timeout(&mut self) {
        self.status = BackgroundExecutionStatus::Timeout;
        self.completed_at = Some(Utc::now());
    }

    /// Check if execution has completed (successfully or not)
    pub fn is_finished(&self) -> bool {
        matches!(
            self.status,
            BackgroundExecutionStatus::Completed
                | BackgroundExecutionStatus::Failed
                | BackgroundExecutionStatus::Cancelled
                | BackgroundExecutionStatus::Timeout
        )
    }

    /// Check if execution succeeded
    pub fn is_success(&self) -> bool {
        self.status == BackgroundExecutionStatus::Completed
    }

    /// Calculate execution duration
    pub fn duration_ms(&self) -> Option<i64> {
        match (self.started_at, self.completed_at) {
            (Some(start), Some(end)) => Some((end - start).num_milliseconds()),
            _ => None,
        }
    }

    /// Check if execution should suppress streaming events (silent mode)
    pub fn is_silent(&self) -> bool {
        matches!(
            self.config.mode,
            BackgroundExecutionMode::Silent | BackgroundExecutionMode::FireAndForget
        )
    }

    /// Check if execution requires waiting for result
    pub fn requires_result(&self) -> bool {
        matches!(self.config.mode, BackgroundExecutionMode::Silent)
    }
}

/// BackgroundExecutionQueue - Queue for managing background executions
/// This is an in-memory implementation for testing. Production uses Redis/Postgres.
#[derive(Debug, Default)]
pub struct BackgroundExecutionQueue {
    executions: std::collections::VecDeque<BackgroundExecution>,
}

impl BackgroundExecutionQueue {
    /// Create a new empty queue
    pub fn new() -> Self {
        Self::default()
    }

    /// Enqueue a new execution
    pub fn enqueue(&mut self, execution: BackgroundExecution) {
        // Insert based on priority (higher priority first)
        let pos = self
            .executions
            .iter()
            .position(|e| e.config.priority < execution.config.priority)
            .unwrap_or(self.executions.len());
        self.executions.insert(pos, execution);
    }

    /// Dequeue the next execution to run
    pub fn dequeue(&mut self) -> Option<BackgroundExecution> {
        self.executions.pop_front()
    }

    /// Peek at the next execution without removing it
    pub fn peek(&self) -> Option<&BackgroundExecution> {
        self.executions.front()
    }

    /// Get queue length
    pub fn len(&self) -> usize {
        self.executions.len()
    }

    /// Check if queue is empty
    pub fn is_empty(&self) -> bool {
        self.executions.is_empty()
    }

    /// Get all queued execution IDs
    pub fn execution_ids(&self) -> Vec<ExecutionId> {
        self.executions
            .iter()
            .map(|e| e.execution_id.clone())
            .collect()
    }
}

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

    #[test]
    fn test_background_execution_modes() {
        // Test fire and forget
        let config = BackgroundExecutionConfig {
            mode: BackgroundExecutionMode::FireAndForget,
            ..Default::default()
        };
        let exec = BackgroundExecution::new(TenantId::new(), "test", config);
        assert!(exec.is_silent());
        assert!(!exec.requires_result());

        // Test silent
        let config = BackgroundExecutionConfig {
            mode: BackgroundExecutionMode::Silent,
            ..Default::default()
        };
        let exec = BackgroundExecution::new(TenantId::new(), "test", config);
        assert!(exec.is_silent());
        assert!(exec.requires_result());

        // Test deferred
        let config = BackgroundExecutionConfig {
            mode: BackgroundExecutionMode::Deferred,
            ..Default::default()
        };
        let exec = BackgroundExecution::new(TenantId::new(), "test", config);
        assert!(!exec.is_silent());
        assert!(!exec.requires_result());
    }

    #[test]
    fn test_background_execution_lifecycle() {
        let config = BackgroundExecutionConfig::default();
        let mut exec = BackgroundExecution::new(TenantId::new(), "test", config);

        assert_eq!(exec.status, BackgroundExecutionStatus::Queued);
        assert!(!exec.is_finished());

        exec.start();
        assert_eq!(exec.status, BackgroundExecutionStatus::Running);
        assert!(exec.started_at.is_some());

        exec.complete(serde_json::json!({"result": "success"}));
        assert_eq!(exec.status, BackgroundExecutionStatus::Completed);
        assert!(exec.is_finished());
        assert!(exec.is_success());
        assert!(exec.output.is_some());
        assert!(exec.duration_ms().is_some());
    }

    #[test]
    fn test_background_execution_queue() {
        let mut queue = BackgroundExecutionQueue::new();
        assert!(queue.is_empty());

        // Add low priority
        let low = BackgroundExecution::new(
            TenantId::new(),
            "low",
            BackgroundExecutionConfig {
                priority: 10,
                ..Default::default()
            },
        );
        queue.enqueue(low);

        // Add high priority
        let high = BackgroundExecution::new(
            TenantId::new(),
            "high",
            BackgroundExecutionConfig {
                priority: 90,
                ..Default::default()
            },
        );
        queue.enqueue(high);

        assert_eq!(queue.len(), 2);

        // High priority should come first
        let first = queue.dequeue().unwrap();
        assert_eq!(first.callable_name, "high");

        let second = queue.dequeue().unwrap();
        assert_eq!(second.callable_name, "low");

        assert!(queue.is_empty());
    }

    #[test]
    fn test_spawn_mode_integration() {
        let tenant_id = TenantId::new();

        // SpawnMode::Child with background=true creates a background execution
        let spawn_mode = SpawnMode::Child {
            background: true,
            inherit_inbox: false,
            policies: None,
        };
        assert!(BackgroundExecution::should_run_background(&spawn_mode));

        let exec = BackgroundExecution::from_spawn_mode(
            &spawn_mode,
            tenant_id.clone(),
            "background_callable",
            Some("input data".to_string()),
            None,
        );
        assert!(exec.is_some());
        let exec = exec.unwrap();
        assert_eq!(exec.callable_name, "background_callable");
        assert_eq!(exec.config.mode, BackgroundExecutionMode::FireAndForget);
        assert!(exec.is_silent());

        // SpawnMode::Child with background=false does not create a background execution
        let spawn_mode = SpawnMode::Child {
            background: false,
            inherit_inbox: false,
            policies: None,
        };
        assert!(!BackgroundExecution::should_run_background(&spawn_mode));
        let exec = BackgroundExecution::from_spawn_mode(
            &spawn_mode,
            tenant_id.clone(),
            "sync_callable",
            None,
            None,
        );
        assert!(exec.is_none());

        // SpawnMode::Inline does not create a background execution
        let spawn_mode = SpawnMode::Inline;
        assert!(!BackgroundExecution::should_run_background(&spawn_mode));
        let exec = BackgroundExecution::from_spawn_mode(
            &spawn_mode,
            tenant_id,
            "inline_callable",
            None,
            None,
        );
        assert!(exec.is_none());
    }
}