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
//! Loop Flow - Iteration with exit condition
//!
//! Repeatedly execute a callable until an exit condition is met.

use crate::callable::Callable;
use std::sync::Arc;

/// Loop exit condition
pub enum LoopCondition {
    /// Fixed number of iterations
    MaxIterations(usize),
    /// Output matches predicate
    OutputMatches(Box<dyn Fn(&str) -> bool + Send + Sync>),
    /// Output contains string
    OutputContains(String),
    /// Combined: max iterations OR output matches
    Either {
        max_iterations: usize,
        predicate: Box<dyn Fn(&str) -> bool + Send + Sync>,
    },
}

impl LoopCondition {
    /// Check if loop should exit
    pub fn should_exit(&self, iteration: usize, output: &str) -> bool {
        match self {
            LoopCondition::MaxIterations(max) => iteration >= *max,
            LoopCondition::OutputMatches(pred) => pred(output),
            LoopCondition::OutputContains(needle) => output.contains(needle),
            LoopCondition::Either {
                max_iterations,
                predicate,
            } => iteration >= *max_iterations || predicate(output),
        }
    }

    /// Create a max iterations condition
    pub fn max(n: usize) -> Self {
        LoopCondition::MaxIterations(n)
    }

    /// Create an output contains condition
    pub fn until_contains(s: impl Into<String>) -> Self {
        LoopCondition::OutputContains(s.into())
    }

    /// Create a predicate condition
    pub fn until(pred: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self {
        LoopCondition::OutputMatches(Box::new(pred))
    }

    /// Create a combined condition
    pub fn max_or_until(max: usize, pred: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self {
        LoopCondition::Either {
            max_iterations: max,
            predicate: Box::new(pred),
        }
    }
}

/// Loop execution flow
pub struct LoopFlow<C: Callable> {
    /// The callable to execute repeatedly
    callable: Arc<C>,
    /// Exit condition
    condition: LoopCondition,
    /// Flow name
    name: String,
    /// Whether to pass previous output as input (feedback loop)
    feedback: bool,
}

impl<C: Callable> LoopFlow<C> {
    /// Create a new loop flow
    pub fn new(name: impl Into<String>, callable: Arc<C>, condition: LoopCondition) -> Self {
        Self {
            callable,
            condition,
            name: name.into(),
            feedback: true, // Default: use output as next input
        }
    }

    /// Create a loop that runs N times
    pub fn times(name: impl Into<String>, n: usize, callable: Arc<C>) -> Self {
        Self::new(name, callable, LoopCondition::MaxIterations(n))
    }

    /// Create a loop that runs until output contains string
    pub fn until_contains(name: impl Into<String>, s: impl Into<String>, callable: Arc<C>) -> Self {
        Self::new(name, callable, LoopCondition::OutputContains(s.into()))
    }

    /// Set whether to use output as next input
    pub fn with_feedback(mut self, feedback: bool) -> Self {
        self.feedback = feedback;
        self
    }

    /// Execute the loop
    pub async fn execute(&self, input: &str) -> anyhow::Result<String> {
        let mut current_input = input.to_string();
        let mut iteration = 0;

        loop {
            let output = self.callable.run(&current_input).await?;

            if self.condition.should_exit(iteration, &output) {
                return Ok(output);
            }

            // Prepare next iteration
            if self.feedback {
                current_input = output;
            }
            iteration += 1;
        }
    }

    /// Execute with iteration tracking
    pub async fn execute_with_history(&self, input: &str) -> anyhow::Result<LoopHistory> {
        let mut current_input = input.to_string();
        let mut iteration = 0;
        let mut outputs = Vec::new();

        loop {
            let output = self.callable.run(&current_input).await?;
            outputs.push(output.clone());

            if self.condition.should_exit(iteration, &output) {
                return Ok(LoopHistory {
                    iterations: iteration + 1,
                    outputs,
                    final_output: output,
                });
            }

            if self.feedback {
                current_input = output;
            }
            iteration += 1;
        }
    }

    /// Get the flow name
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// History of a loop execution
#[derive(Debug)]
pub struct LoopHistory {
    /// Number of iterations executed
    pub iterations: usize,
    /// Output from each iteration
    pub outputs: Vec<String>,
    /// Final output
    pub final_output: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// Mock callable that tracks calls and transforms input
    #[allow(clippy::type_complexity)]
    struct MockCallable {
        name: String,
        call_count: Arc<AtomicUsize>,
        transform: Box<dyn Fn(&str, usize) -> String + Send + Sync>,
    }

    impl MockCallable {
        fn new(
            name: &str,
            transform: impl Fn(&str, usize) -> String + Send + Sync + 'static,
        ) -> Self {
            Self {
                name: name.to_string(),
                call_count: Arc::new(AtomicUsize::new(0)),
                transform: Box::new(transform),
            }
        }

        /// Simple incrementing callable - appends iteration count
        fn incrementing(name: &str) -> Self {
            Self::new(name, |input, n| format!("{}:{}", input, n))
        }

        /// Callable that emits "DONE" on the Nth call
        fn done_on_call(name: &str, n: usize) -> Self {
            Self::new(name, move |input, call| {
                if call >= n - 1 {
                    "DONE".to_string()
                } else {
                    format!("{}:{}", input, call)
                }
            })
        }

        fn get_call_count(&self) -> usize {
            self.call_count.load(Ordering::SeqCst)
        }
    }

    #[async_trait]
    impl Callable for MockCallable {
        fn name(&self) -> &str {
            &self.name
        }

        async fn run(&self, input: &str) -> anyhow::Result<String> {
            let n = self.call_count.fetch_add(1, Ordering::SeqCst);
            Ok((self.transform)(input, n))
        }
    }

    // ============ LoopCondition Tests ============

    #[test]
    fn test_condition_max_iterations() {
        let cond = LoopCondition::MaxIterations(3);
        assert!(!cond.should_exit(0, "any"));
        assert!(!cond.should_exit(1, "any"));
        assert!(!cond.should_exit(2, "any"));
        assert!(cond.should_exit(3, "any")); // Exit at iteration 3
        assert!(cond.should_exit(5, "any")); // Also exit if past
    }

    #[test]
    fn test_condition_output_matches() {
        let cond = LoopCondition::OutputMatches(Box::new(|s| s.len() > 5));
        assert!(!cond.should_exit(0, "hi"));
        assert!(!cond.should_exit(10, "short"));
        assert!(cond.should_exit(0, "longer"));
        assert!(cond.should_exit(0, "this is long enough"));
    }

    #[test]
    fn test_condition_output_contains() {
        let cond = LoopCondition::OutputContains("DONE".to_string());
        assert!(!cond.should_exit(0, "not yet"));
        assert!(!cond.should_exit(5, "still working"));
        assert!(cond.should_exit(0, "DONE"));
        assert!(cond.should_exit(0, "task DONE here"));
    }

    #[test]
    fn test_condition_either() {
        let cond = LoopCondition::Either {
            max_iterations: 5,
            predicate: Box::new(|s| s.contains("STOP")),
        };

        // Not exit before max or predicate
        assert!(!cond.should_exit(0, "working"));
        assert!(!cond.should_exit(4, "still going"));

        // Exit at max iterations
        assert!(cond.should_exit(5, "working"));

        // Exit when predicate matches, even before max
        assert!(cond.should_exit(2, "STOP now"));
    }

    #[test]
    fn test_condition_helpers() {
        // max()
        let cond = LoopCondition::max(2);
        assert!(!cond.should_exit(1, "x"));
        assert!(cond.should_exit(2, "x"));

        // until_contains()
        let cond = LoopCondition::until_contains("END");
        assert!(!cond.should_exit(0, "not"));
        assert!(cond.should_exit(0, "END"));

        // until()
        let cond = LoopCondition::until(|s| s == "target");
        assert!(!cond.should_exit(0, "other"));
        assert!(cond.should_exit(0, "target"));

        // max_or_until()
        let cond = LoopCondition::max_or_until(3, |s| s.starts_with("!"));
        assert!(!cond.should_exit(0, "a"));
        assert!(cond.should_exit(3, "a")); // max hit
        assert!(cond.should_exit(0, "!bang")); // predicate hit
    }

    // ============ LoopFlow Construction Tests ============

    #[tokio::test]
    async fn test_loop_flow_new() {
        let callable = Arc::new(MockCallable::incrementing("inc"));
        let flow = LoopFlow::new("test_loop", callable, LoopCondition::MaxIterations(2));
        assert_eq!(flow.name(), "test_loop");
    }

    #[tokio::test]
    async fn test_loop_flow_times() {
        let callable = Arc::new(MockCallable::incrementing("inc"));
        let flow = LoopFlow::times("timer", 3, callable);
        assert_eq!(flow.name(), "timer");
    }

    #[tokio::test]
    async fn test_loop_flow_until_contains() {
        let callable = Arc::new(MockCallable::done_on_call("done", 2));
        let flow = LoopFlow::until_contains("stopper", "DONE", callable);
        assert_eq!(flow.name(), "stopper");
    }

    // ============ LoopFlow Execute Tests ============

    #[tokio::test]
    async fn test_loop_execute_max_iterations() {
        let callable = Arc::new(MockCallable::incrementing("inc"));
        let flow = LoopFlow::times("loop", 3, callable.clone());

        let result = flow.execute("start").await.unwrap();
        // With MaxIterations(3), exit condition is iteration >= 3
        // iteration 0: run, check 0>=3=false, inc to 1
        // iteration 1: run, check 1>=3=false, inc to 2
        // iteration 2: run, check 2>=3=false, inc to 3
        // iteration 3: run, check 3>=3=true, exit
        // So 4 total calls
        assert_eq!(callable.get_call_count(), 4);
        assert!(result.contains("start"));
    }

    #[tokio::test]
    async fn test_loop_execute_until_contains() {
        let callable = Arc::new(MockCallable::done_on_call("done", 3));
        let flow = LoopFlow::until_contains("wait_done", "DONE", callable.clone());

        let result = flow.execute("input").await.unwrap();
        assert_eq!(result, "DONE");
        assert_eq!(callable.get_call_count(), 3);
    }

    #[tokio::test]
    async fn test_loop_execute_with_predicate() {
        let callable = Arc::new(MockCallable::new("counter", |_, n| format!("count:{}", n)));
        let flow = LoopFlow::new(
            "until_five",
            callable.clone(),
            LoopCondition::until(|s| s == "count:5"),
        );

        let result = flow.execute("x").await.unwrap();
        assert_eq!(result, "count:5");
        assert_eq!(callable.get_call_count(), 6); // 0,1,2,3,4,5
    }

    #[tokio::test]
    async fn test_loop_execute_either_max_first() {
        let callable = Arc::new(MockCallable::new("counter", |_, n| format!("v{}", n)));
        let flow = LoopFlow::new(
            "either",
            callable.clone(),
            LoopCondition::max_or_until(3, |s| s == "never"),
        );

        let result = flow.execute("x").await.unwrap();
        // Exit at iteration >= 3, so 4 calls total
        assert_eq!(callable.get_call_count(), 4);
        assert_eq!(result, "v3");
    }

    #[tokio::test]
    async fn test_loop_execute_either_predicate_first() {
        let callable = Arc::new(MockCallable::done_on_call("done", 2));
        let flow = LoopFlow::new(
            "either",
            callable.clone(),
            LoopCondition::max_or_until(10, |s| s == "DONE"),
        );

        let result = flow.execute("x").await.unwrap();
        assert_eq!(result, "DONE");
        assert_eq!(callable.get_call_count(), 2); // Exit before max
    }

    // ============ Feedback Mode Tests ============

    #[tokio::test]
    async fn test_loop_with_feedback_enabled() {
        // Track inputs to verify feedback
        let inputs: Arc<std::sync::Mutex<Vec<String>>> =
            Arc::new(std::sync::Mutex::new(Vec::new()));
        let inputs_clone = inputs.clone();

        let callable = Arc::new(MockCallable::new("fb", move |input, n| {
            inputs_clone.lock().unwrap().push(input.to_string());
            format!("out{}", n)
        }));

        let flow = LoopFlow::times("feedback_on", 3, callable).with_feedback(true);
        flow.execute("start").await.unwrap();

        let recorded = inputs.lock().unwrap().clone();
        // MaxIterations(3) runs 4 times (exits when iteration >= 3)
        assert_eq!(recorded, vec!["start", "out0", "out1", "out2"]);
    }

    #[tokio::test]
    async fn test_loop_with_feedback_disabled() {
        let inputs: Arc<std::sync::Mutex<Vec<String>>> =
            Arc::new(std::sync::Mutex::new(Vec::new()));
        let inputs_clone = inputs.clone();

        let callable = Arc::new(MockCallable::new("no_fb", move |input, n| {
            inputs_clone.lock().unwrap().push(input.to_string());
            format!("out{}", n)
        }));

        let flow = LoopFlow::times("feedback_off", 3, callable).with_feedback(false);
        flow.execute("same").await.unwrap();

        let recorded = inputs.lock().unwrap().clone();
        // Without feedback, input stays the same; MaxIterations(3) runs 4 times
        assert_eq!(recorded, vec!["same", "same", "same", "same"]);
    }

    // ============ Execute with History Tests ============

    #[tokio::test]
    async fn test_loop_execute_with_history() {
        let callable = Arc::new(MockCallable::new("hist", |_, n| format!("iter{}", n)));
        let flow = LoopFlow::times("history_test", 4, callable);

        let history = flow.execute_with_history("start").await.unwrap();

        // MaxIterations(4) exits when iteration >= 4, so runs 5 times
        assert_eq!(history.iterations, 5);
        assert_eq!(history.outputs.len(), 5);
        assert_eq!(
            history.outputs,
            vec!["iter0", "iter1", "iter2", "iter3", "iter4"]
        );
        assert_eq!(history.final_output, "iter4");
    }

    #[tokio::test]
    async fn test_loop_execute_with_history_early_exit() {
        let callable = Arc::new(MockCallable::done_on_call("early", 2));
        let flow = LoopFlow::until_contains("early_exit", "DONE", callable);

        let history = flow.execute_with_history("x").await.unwrap();

        assert_eq!(history.iterations, 2);
        assert_eq!(history.outputs.len(), 2);
        assert_eq!(history.final_output, "DONE");
    }

    // ============ Error Handling Tests ============

    #[tokio::test]
    async fn test_loop_error_propagation() {
        struct FailingCallable {
            fail_on: usize,
            call_count: Arc<AtomicUsize>,
        }

        #[async_trait]
        impl Callable for FailingCallable {
            fn name(&self) -> &str {
                "failing"
            }

            async fn run(&self, _input: &str) -> anyhow::Result<String> {
                let n = self.call_count.fetch_add(1, Ordering::SeqCst);
                if n >= self.fail_on {
                    anyhow::bail!("Intentional failure at iteration {}", n)
                }
                Ok(format!("ok{}", n))
            }
        }

        let callable = Arc::new(FailingCallable {
            fail_on: 2,
            call_count: Arc::new(AtomicUsize::new(0)),
        });

        let flow = LoopFlow::times("fail_loop", 5, callable);
        let result = flow.execute("start").await;

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Intentional failure"));
    }

    // ============ Edge Cases ============

    #[tokio::test]
    async fn test_loop_zero_iterations() {
        let callable = Arc::new(MockCallable::incrementing("zero"));
        let flow = LoopFlow::times("zero_loop", 0, callable.clone());

        // With max 0, should_exit returns true on iteration 0
        // So we run once and immediately exit
        let result = flow.execute("input").await.unwrap();
        assert_eq!(callable.get_call_count(), 1);
        assert!(result.contains("input"));
    }

    #[tokio::test]
    async fn test_loop_immediate_exit_predicate() {
        let callable = Arc::new(MockCallable::new("imm", |_, _| "STOP".to_string()));
        let flow = LoopFlow::new(
            "immediate",
            callable.clone(),
            LoopCondition::until_contains("STOP"),
        );

        let result = flow.execute("x").await.unwrap();
        assert_eq!(result, "STOP");
        assert_eq!(callable.get_call_count(), 1);
    }

    #[tokio::test]
    async fn test_loop_single_iteration() {
        let callable = Arc::new(MockCallable::incrementing("single"));
        let flow = LoopFlow::times("one", 1, callable.clone());

        let history = flow.execute_with_history("x").await.unwrap();
        // MaxIterations(1) exits when iteration >= 1, so runs 2 times
        assert_eq!(history.iterations, 2);
        assert_eq!(callable.get_call_count(), 2);
    }
}