ironflow-engine 2.55.0

Workflow orchestration engine for ironflow with FSM-based run lifecycle
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
//! Integration tests for agent steps with a typed answer and typed tools.
//!
//! `ctx.agent` with `.output::<T>()` returns the `T` itself, with or without
//! tools on the step. The agent provider is the harness mock: it plays the
//! model, the engine code path is real.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use chrono::Utc;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use tokio::time::timeout;
use uuid::Uuid;

use ironflow_core::provider::{AgentConfig, AgentOutput, AgentProvider, InvokeFuture, Tool};
use ironflow_engine::config::{AgentStepConfig, HumanInputConfig, ShellConfig};
use ironflow_engine::context::{AgentReply, WorkflowContext};
use ironflow_engine::engine::{Engine, EnqueueOptions};
use ironflow_engine::executor::StepOutput;
use ironflow_engine::handler::{HandlerFuture, WorkflowHandler};
use ironflow_engine::testing::{MockShellOutput, TestEngine};
use ironflow_store::memory::InMemoryStore;
use ironflow_store::models::{RunStatus, StepStatus, StepUpdate, TriggerKind};
use ironflow_store::store::{RunStore, Store};

/// Prompt and environment id of each resumed agent call, in order.
type ResumeLog = Vec<(String, Option<String>)>;

/// What the reviewer agent answers.
#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
struct Verdict {
    approved: bool,
    score: u8,
}

/// Asks for a [`Verdict`] and ships when it is approved.
struct Reviewer {
    seen: Arc<Mutex<Option<Verdict>>>,
}

impl WorkflowHandler for Reviewer {
    fn name(&self) -> &str {
        "reviewer"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let verdict = ctx
                .agent(
                    "review",
                    AgentStepConfig::new("Review the release")
                        .max_turns(2)
                        .max_budget_usd(0.10)
                        .output::<Verdict>(),
                )
                .await?;
            if verdict.approved {
                ctx.shell("ship", ShellConfig::new("./ship")).await?;
            }
            *self.seen.lock().expect("lock") = Some(verdict);
            Ok(())
        })
    }
}

/// Explores with tools; its answer stays a plain step output.
struct Explorer;

impl WorkflowHandler for Explorer {
    fn name(&self) -> &str {
        "explorer"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let found = ctx
                .agent(
                    "explore",
                    AgentStepConfig::new("List the crates")
                        .max_budget_usd(0.10)
                        .allow_tool(Tool::Bash)
                        .allow_tool(Tool::Custom("mcp__repo__tree".to_string())),
                )
                .await?;
            ctx.shell(
                "echo",
                ShellConfig::new("echo \"$FOUND\"").env("FOUND", &found.output.to_string()),
            )
            .await?;
            Ok(())
        })
    }
}

#[tokio::test]
async fn a_typed_agent_step_returns_its_answer() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(Reviewer { seen: seen.clone() })
        .with_mock_agent(|cfg| {
            assert!(
                cfg.json_schema
                    .as_deref()
                    .is_some_and(|schema| schema.contains("approved")),
                "the schema of Verdict is sent to the provider"
            );
            Ok(AgentOutput::new(json!({"approved": true, "score": 9})))
        })
        .with_mock_shell(|_cfg| Ok(MockShellOutput::ok("shipped")))
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    assert_eq!(result.step_names(), vec!["review", "ship"]);
    assert_eq!(
        *seen.lock().expect("lock"),
        Some(Verdict {
            approved: true,
            score: 9
        })
    );
}

#[tokio::test]
async fn a_rejected_typed_answer_skips_the_next_step() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(Reviewer { seen: seen.clone() })
        .with_mock_agent(|_cfg| Ok(AgentOutput::new(json!({"approved": false, "score": 2}))))
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    assert_eq!(result.step_names(), vec!["review"]);
    assert_eq!(
        seen.lock().expect("lock").as_ref().map(|v| v.score),
        Some(2)
    );
}

#[tokio::test]
async fn an_answer_that_does_not_match_the_type_fails_the_run() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(Reviewer { seen: seen.clone() })
        .with_mock_agent(|_cfg| Ok(AgentOutput::new(json!({"approved": "yes"}))))
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Failed);
    let error = result.error().expect("the run records why it failed");
    assert!(error.starts_with("serialization error"), "got: {error}");
    assert!(error.contains("expected a boolean"), "got: {error}");
    assert!(seen.lock().expect("lock").is_none());
}

#[tokio::test]
async fn typed_tools_reach_the_provider_under_their_names() {
    let result = TestEngine::new()
        .with_handler(Explorer)
        .with_mock_agent(|cfg| {
            assert_eq!(cfg.allowed_tools, vec!["Bash", "mcp__repo__tree"]);
            Ok(AgentOutput::new(json!("ironflow-core")))
        })
        .with_mock_shell(|_cfg| Ok(MockShellOutput::ok("ironflow-core")))
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    assert_eq!(result.step_names(), vec!["explore", "echo"]);
}

/// Reads the code with a tool, then answers with a [`Verdict`].
struct ToolReviewer {
    seen: Arc<Mutex<Option<Verdict>>>,
}

impl WorkflowHandler for ToolReviewer {
    fn name(&self) -> &str {
        "tool-reviewer"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let verdict: Verdict = ctx
                .agent(
                    "review",
                    AgentStepConfig::new("Read the diff, then review the release")
                        .max_turns(4)
                        .max_budget_usd(0.10)
                        .allow_tool(Tool::Read)
                        .output::<Verdict>(),
                )
                .await?;
            *self.seen.lock().expect("lock") = Some(verdict);
            Ok(())
        })
    }
}

/// Greps with a tool and asks for a raw schema: the answer stays untyped.
struct RawToolReviewer {
    seen: Arc<Mutex<Option<StepOutput>>>,
}

impl WorkflowHandler for RawToolReviewer {
    fn name(&self) -> &str {
        "raw-tool-reviewer"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let output: StepOutput = ctx
                .agent(
                    "review",
                    AgentStepConfig::new("Grep the TODOs, then review the release")
                        .max_budget_usd(0.10)
                        .output_schema_raw(r#"{"type":"object"}"#)
                        .allow_tool(Tool::Grep),
                )
                .await?;
            *self.seen.lock().expect("lock") = Some(output);
            Ok(())
        })
    }
}

#[tokio::test]
async fn a_step_with_tools_and_a_typed_output_returns_its_answer() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(ToolReviewer { seen: seen.clone() })
        .with_mock_agent(|cfg| {
            assert_eq!(cfg.allowed_tools, vec!["Read"]);
            assert!(
                cfg.json_schema
                    .as_deref()
                    .is_some_and(|schema| schema.contains("approved")),
                "the schema of Verdict is sent next to the tools"
            );
            Ok(AgentOutput::new(json!({"approved": true, "score": 8})))
        })
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    assert_eq!(result.step_names(), vec!["review"]);
    assert_eq!(
        *seen.lock().expect("lock"),
        Some(Verdict {
            approved: true,
            score: 8
        })
    );
}

#[tokio::test]
async fn a_step_with_tools_and_a_raw_schema_returns_the_step_output() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(RawToolReviewer { seen: seen.clone() })
        .with_mock_agent(|cfg| {
            assert_eq!(cfg.allowed_tools, vec!["Grep"]);
            assert_eq!(cfg.json_schema.as_deref(), Some(r#"{"type":"object"}"#));
            Ok(AgentOutput::new(json!({"todos": 3})))
        })
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    let output = seen.lock().expect("lock").clone().expect("a step output");
    assert_eq!(output.output, json!({"todos": 3}));
}

#[tokio::test]
async fn a_tool_step_answer_that_does_not_match_the_type_fails_the_run() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(ToolReviewer { seen: seen.clone() })
        .with_mock_agent(|_cfg| Ok(AgentOutput::new(json!({"approved": "yes"}))))
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Failed);
    let error = result.error().expect("the run records why it failed");
    assert!(error.starts_with("serialization error"), "got: {error}");
    assert!(error.contains("expected a boolean"), "got: {error}");
    assert!(seen.lock().expect("lock").is_none());
}

/// Clones in a typed step and keeps the metadata next to the answer.
struct Cloner {
    seen: Arc<Mutex<Option<AgentReply<Verdict>>>>,
}

impl WorkflowHandler for Cloner {
    fn name(&self) -> &str {
        "cloner"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let reply = ctx
                .agent_with_meta(
                    "clone",
                    AgentStepConfig::new("Clone the repository")
                        .max_budget_usd(0.10)
                        .output::<Verdict>(),
                )
                .await?;
            *self.seen.lock().expect("lock") = Some(reply);
            Ok(())
        })
    }
}

#[tokio::test]
async fn a_typed_agent_step_exposes_its_environment_id() {
    let seen = Arc::new(Mutex::new(None));
    let account = Uuid::now_v7();
    let result = TestEngine::new()
        .with_handler(Cloner { seen: seen.clone() })
        .with_mock_agent(move |_cfg| {
            let mut output = AgentOutput::new(json!({"approved": true, "score": 7}));
            output.environment_id = Some("ironflow-env-0a1b2c".to_string());
            output.account_id = Some(account.to_string());
            Ok(output)
        })
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    assert_eq!(
        *seen.lock().expect("lock"),
        Some(AgentReply {
            answer: Verdict {
                approved: true,
                score: 7
            },
            environment_id: Some("ironflow-env-0a1b2c".to_string()),
            account_id: Some(account),
        })
    );
}

#[tokio::test]
async fn a_typed_agent_step_without_environment_has_no_ids() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(Cloner { seen: seen.clone() })
        .with_mock_agent(|_cfg| Ok(AgentOutput::new(json!({"approved": false, "score": 1}))))
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    let reply = seen.lock().expect("lock").clone().expect("a reply");
    assert_eq!(reply.answer.score, 1);
    assert_eq!(reply.environment_id, None);
    assert_eq!(reply.account_id, None);
}

#[tokio::test]
async fn a_mismatched_answer_fails_agent_with_meta_without_a_reply() {
    let seen = Arc::new(Mutex::new(None));
    let result = TestEngine::new()
        .with_handler(Cloner { seen: seen.clone() })
        .with_mock_agent(|_cfg| {
            let mut output = AgentOutput::new(json!({"approved": "yes"}));
            output.environment_id = Some("ironflow-env-0a1b2c".to_string());
            Ok(output)
        })
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Failed);
    let error = result.error().expect("the run records why it failed");
    assert!(error.starts_with("serialization error"), "got: {error}");
    assert!(seen.lock().expect("lock").is_none());
}

/// Clones in a typed step, then resumes the environment it handed out.
struct CloneThenFix;

impl WorkflowHandler for CloneThenFix {
    fn name(&self) -> &str {
        "clone-then-fix"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let reply = ctx
                .agent_with_meta(
                    "clone",
                    AgentStepConfig::new("Clone the repository")
                        .max_budget_usd(0.10)
                        .output::<Verdict>(),
                )
                .await?;
            let environment = reply
                .environment_id
                .expect("the clone step hands out an environment id");
            ctx.agent(
                "fix",
                AgentStepConfig::new("Fix the test")
                    .max_budget_usd(0.10)
                    .resume_environment(&environment),
            )
            .await?;
            Ok(())
        })
    }
}

#[tokio::test]
async fn the_environment_id_of_a_typed_step_reaches_the_next_step() {
    let resumed: Arc<Mutex<ResumeLog>> = Arc::new(Mutex::new(Vec::new()));
    let recorder = resumed.clone();
    let result = TestEngine::new()
        .with_handler(CloneThenFix)
        .with_mock_agent(move |cfg| {
            recorder
                .lock()
                .expect("lock")
                .push((cfg.prompt.clone(), cfg.resume_environment_id.clone()));
            let mut output = AgentOutput::new(json!({"approved": true, "score": 3}));
            output.environment_id = Some("ironflow-env-0a1b2c".to_string());
            Ok(output)
        })
        .run(json!({}))
        .await
        .expect("the harness ran the handler");

    assert_eq!(result.status(), RunStatus::Completed);
    assert_eq!(result.step_names(), vec!["clone", "fix"]);
    assert_eq!(
        *resumed.lock().expect("lock"),
        vec![
            ("Clone the repository".to_string(), None),
            (
                "Fix the test".to_string(),
                Some("ironflow-env-0a1b2c".to_string())
            ),
        ]
    );
}

/// Provider handing out a fixed environment id and counting invocations.
#[derive(Default)]
struct CountingProvider {
    calls: AtomicUsize,
}

impl AgentProvider for CountingProvider {
    fn invoke<'a>(&'a self, _config: &'a AgentConfig) -> InvokeFuture<'a> {
        Box::pin(async move {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let mut output = AgentOutput::new(json!({"approved": true, "score": 9}));
            output.environment_id = Some("ironflow-env-1".to_string());
            Ok(output)
        })
    }
}

/// Clones in a typed step, suspends on a human input and records the reply of
/// the clone step each time the handler runs.
struct CloneThenAsk {
    replies: Arc<Mutex<Vec<AgentReply<Verdict>>>>,
}

impl WorkflowHandler for CloneThenAsk {
    fn name(&self) -> &str {
        "clone-then-ask"
    }

    fn execute<'a>(&'a self, ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
        Box::pin(async move {
            let reply = ctx
                .agent_with_meta(
                    "clone",
                    AgentStepConfig::new("Clone the repository")
                        .max_budget_usd(0.10)
                        .output::<Verdict>(),
                )
                .await?;
            self.replies.lock().expect("lock").push(reply);
            ctx.human_input::<Verdict>("clarify", HumanInputConfig::new("Approve?"))
                .await?;
            Ok(())
        })
    }
}

#[tokio::test]
async fn a_replayed_typed_step_returns_the_same_environment_id() {
    timeout(Duration::from_secs(10), async {
        let store = Arc::new(InMemoryStore::new());
        let provider = Arc::new(CountingProvider::default());
        let replies = Arc::new(Mutex::new(Vec::new()));
        let dyn_store: Arc<dyn Store> = store.clone();
        let dyn_provider: Arc<dyn AgentProvider> = provider.clone();
        let mut engine = Engine::new(dyn_store, dyn_provider);
        engine
            .register(CloneThenAsk {
                replies: replies.clone(),
            })
            .expect("register handler");

        let run = engine
            .enqueue_handler_with_options(
                "clone-then-ask",
                TriggerKind::Api,
                json!({}),
                EnqueueOptions::default(),
            )
            .await
            .expect("enqueue")
            .into_run();
        store
            .update_run_status(run.id, RunStatus::Running)
            .await
            .expect("mark running");
        engine
            .execute_handler_run(run.id)
            .await
            .expect("handler suspends on the input");

        let steps = store.list_steps(run.id).await.expect("list steps");
        let input_step = steps
            .iter()
            .find(|s| s.status.state == StepStatus::AwaitingApproval)
            .expect("human input step suspended the run");
        store
            .update_step(
                input_step.id,
                StepUpdate {
                    status: Some(StepStatus::Completed),
                    output: Some(json!({"approved": true, "score": 1})),
                    completed_at: Some(Utc::now()),
                    clear_approval_deadline: true,
                    ..StepUpdate::default()
                },
            )
            .await
            .expect("store the answer");
        store
            .update_run_status(run.id, RunStatus::Running)
            .await
            .expect("mark running");
        engine
            .execute_handler_run(run.id)
            .await
            .expect("the run completes once resumed");

        assert_eq!(
            provider.calls.load(Ordering::SeqCst),
            1,
            "clone is replayed"
        );
        let replies = replies.lock().expect("lock");
        assert_eq!(replies.len(), 2);
        assert_eq!(replies[0].environment_id.as_deref(), Some("ironflow-env-1"));
        assert_eq!(replies[0], replies[1]);
    })
    .await
    .expect("test timed out");
}