ironflow-engine 2.31.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
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! Step executor — reconstructs operations from configs and runs them.
//!
//! Each step type (shell, HTTP, agent) has its own executor implementing
//! the [`StepExecutor`] trait. The [`execute_step_config`] function dispatches
//! to the appropriate executor based on the [`StepConfig`] variant.

mod agent;
mod http;
mod shell;

use std::future::Future;
use std::sync::Arc;

use rust_decimal::Decimal;
use serde::de::DeserializeOwned;
use serde_json::{Value, from_value};
use uuid::Uuid;

use ironflow_core::provider::{AgentProvider, DebugMessage};
use ironflow_store::entities::StepStatus;

use crate::config::StepConfig;
use crate::error::EngineError;
use crate::log_sender::StepLogSender;

pub use agent::AgentExecutor;
pub use http::HttpExecutor;
pub use shell::ShellExecutor;

/// Result of executing a single step.
#[derive(Debug, Clone)]
pub struct StepOutput {
    /// Serialized output (stdout for shell, body for http, value for agent).
    ///
    /// For agent steps with a JSON schema, the value may not strictly conform
    /// to the schema: Claude CLI can flatten wrapper objects with a single
    /// array field, returning a bare array instead of `{"items": [...]}`.
    /// Callers should handle both the expected wrapper and a bare value.
    pub output: Value,
    /// Wall-clock duration in milliseconds.
    pub duration_ms: u64,
    /// Cost in USD (agent steps only).
    pub cost_usd: Decimal,
    /// Input token count (agent steps only).
    pub input_tokens: Option<u64>,
    /// Output token count (agent steps only).
    pub output_tokens: Option<u64>,
    /// Model identifier used for agent steps (e.g. `"claude-sonnet-4-20250514"`).
    pub model: Option<String>,
    /// Conversation trace from verbose agent invocations.
    pub debug_messages: Option<Vec<DebugMessage>>,
}

impl StepOutput {
    /// Serialize debug messages to a JSON [`Value`] for store persistence.
    ///
    /// Returns `None` when verbose mode was off (no messages captured).
    pub fn debug_messages_json(&self) -> Option<Value> {
        self.debug_messages
            .as_ref()
            .and_then(|msgs| serde_json::to_value(msgs).ok())
    }

    /// Exit code of a shell step.
    ///
    /// Returns `None` for non-shell steps or when the field is absent.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    ///
    /// let output = StepOutput {
    ///     output: json!({"stdout": "ok\n", "stderr": "", "exit_code": 0}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// assert_eq!(output.exit_code(), Some(0));
    /// ```
    pub fn exit_code(&self) -> Option<i64> {
        self.output.get("exit_code").and_then(Value::as_i64)
    }

    /// Standard output of a shell step, or an empty string for other kinds.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    ///
    /// let output = StepOutput {
    ///     output: json!({"stdout": "42 tests passed\n", "stderr": "", "exit_code": 0}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// assert!(output.stdout().contains("42 tests"));
    /// ```
    pub fn stdout(&self) -> &str {
        self.output
            .get("stdout")
            .and_then(Value::as_str)
            .unwrap_or_default()
    }

    /// Standard error of a shell step, or an empty string for other kinds.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    ///
    /// let output = StepOutput {
    ///     output: json!({"stdout": "", "stderr": "warning: unused", "exit_code": 0}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// assert_eq!(output.stderr(), "warning: unused");
    /// ```
    pub fn stderr(&self) -> &str {
        self.output
            .get("stderr")
            .and_then(Value::as_str)
            .unwrap_or_default()
    }

    /// HTTP status code of an HTTP step.
    ///
    /// Returns `None` for non-HTTP steps or when the field is absent.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    ///
    /// let output = StepOutput {
    ///     output: json!({"status": 204, "body": ""}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// assert_eq!(output.status(), Some(204));
    /// ```
    pub fn status(&self) -> Option<u16> {
        self.output
            .get("status")
            .and_then(Value::as_u64)
            .and_then(|s| u16::try_from(s).ok())
    }

    /// Response body of an HTTP step, or an empty string for other kinds.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    ///
    /// let output = StepOutput {
    ///     output: json!({"status": 200, "body": "{\"ok\":true}"}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// assert_eq!(output.body(), "{\"ok\":true}");
    /// ```
    pub fn body(&self) -> &str {
        self.output
            .get("body")
            .and_then(Value::as_str)
            .unwrap_or_default()
    }

    /// Whether the step succeeded from the point of view of its own kind.
    ///
    /// - Shell step: the exit code is `0`.
    /// - HTTP step: the status is in the `2xx` range.
    /// - Any other kind: `false`, since no success marker is recorded.
    ///
    /// Mostly useful after a step configured with `allow_failure()`, since a
    /// failing step otherwise returns an error from the context method.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    ///
    /// let shell = StepOutput {
    ///     output: json!({"stdout": "", "stderr": "", "exit_code": 1}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// assert!(!shell.is_success());
    ///
    /// let http = StepOutput { output: json!({"status": 201, "body": ""}), ..shell.clone() };
    /// assert!(http.is_success());
    /// ```
    pub fn is_success(&self) -> bool {
        if let Some(code) = self.exit_code() {
            return code == 0;
        }
        if let Some(status) = self.status() {
            return (200..300).contains(&status);
        }
        false
    }

    /// Deserialize the step output into `T`.
    ///
    /// Intended for agent steps constrained by a JSON schema, and for custom
    /// operations that return structured JSON.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Serialization`] when the output does not match `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::StepOutput;
    /// use rust_decimal::Decimal;
    /// use serde::Deserialize;
    /// use serde_json::json;
    ///
    /// #[derive(Deserialize)]
    /// struct Review {
    ///     score: u8,
    /// }
    ///
    /// let output = StepOutput {
    ///     output: json!({"score": 8}),
    ///     duration_ms: 3,
    ///     cost_usd: Decimal::ZERO,
    ///     input_tokens: None,
    ///     output_tokens: None,
    ///     model: None,
    ///     debug_messages: None,
    /// };
    /// let review: Review = output.json()?;
    /// assert_eq!(review.score, 8);
    /// # Ok::<(), ironflow_engine::error::EngineError>(())
    /// ```
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, EngineError> {
        from_value(self.output.clone()).map_err(EngineError::Serialization)
    }
}

/// Result of a single step within a [`parallel`](crate::context::WorkflowContext::parallel) batch.
#[derive(Debug, Clone)]
pub struct ParallelStepResult {
    /// The step name (same as provided to `parallel()`).
    pub name: String,
    /// The step execution output.
    pub output: StepOutput,
    /// The step ID in the store (for dependency tracking).
    pub step_id: Uuid,
}

/// Enriched result of a completed step, for post-execution inspection.
///
/// Collects the step's trace ID, status, metrics, and a truncated output
/// summary into a single struct that the [`WorkflowContext`](crate::context::WorkflowContext)
/// accumulates over the run.
///
/// # Examples
///
/// ```
/// use ironflow_engine::executor::StepResult;
/// use ironflow_store::entities::StepStatus;
/// use rust_decimal::Decimal;
/// use uuid::Uuid;
///
/// let result = StepResult {
///     trace_id: Uuid::nil(),
///     name: "build".to_string(),
///     status: StepStatus::Completed,
///     duration_ms: 1200,
///     cost_usd: Decimal::ZERO,
///     input_tokens: None,
///     output_tokens: None,
///     error: None,
///     output_summary: Some("ok".to_string()),
/// };
/// assert_eq!(result.status, StepStatus::Completed);
/// ```
#[derive(Debug, Clone, serde::Serialize)]
pub struct StepResult {
    /// Deterministic trace ID for log correlation.
    pub trace_id: Uuid,
    /// Step name.
    pub name: String,
    /// Terminal status.
    pub status: StepStatus,
    /// Wall-clock duration in milliseconds.
    pub duration_ms: u64,
    /// Cost in USD.
    pub cost_usd: Decimal,
    /// Input token count (agent steps only).
    pub input_tokens: Option<u64>,
    /// Output token count (agent steps only).
    pub output_tokens: Option<u64>,
    /// Error message if the step failed.
    pub error: Option<String>,
    /// First 500 characters of the serialized output.
    pub output_summary: Option<String>,
}

/// Maximum length of [`StepResult::output_summary`].
const OUTPUT_SUMMARY_MAX_LEN: usize = 500;

impl StepResult {
    /// Build from a completed step's output.
    pub fn from_success(trace_id: Uuid, name: &str, output: &StepOutput) -> Self {
        Self {
            trace_id,
            name: name.to_string(),
            status: StepStatus::Completed,
            duration_ms: output.duration_ms,
            cost_usd: output.cost_usd,
            input_tokens: output.input_tokens,
            output_tokens: output.output_tokens,
            error: None,
            output_summary: summarize_output(&output.output),
        }
    }

    /// Build from a failed step.
    pub fn from_failure(
        trace_id: Uuid,
        name: &str,
        error: &str,
        duration_ms: u64,
        cost_usd: Decimal,
    ) -> Self {
        Self {
            trace_id,
            name: name.to_string(),
            status: StepStatus::Failed,
            duration_ms,
            cost_usd,
            input_tokens: None,
            output_tokens: None,
            error: Some(error.to_string()),
            output_summary: None,
        }
    }
}

fn summarize_output(value: &Value) -> Option<String> {
    let raw = value.to_string();
    match raw.char_indices().nth(OUTPUT_SUMMARY_MAX_LEN) {
        None => Some(raw),
        Some((byte_idx, _)) => Some(raw[..byte_idx].to_string()),
    }
}

/// Trait for step executors.
///
/// Each step type implements this trait to execute its specific operation
/// and return a [`StepOutput`].
pub trait StepExecutor: Send + Sync {
    /// Execute the step and return structured output.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError`] if the operation fails.
    fn execute(
        &self,
        provider: &Arc<dyn AgentProvider>,
    ) -> impl Future<Output = Result<StepOutput, EngineError>> + Send;
}

/// Execute a [`StepConfig`] and return structured output.
///
/// When a [`StepLogSender`] is provided, executors that support streaming
/// will emit log lines in real time (e.g. shell stdout/stderr).
///
/// # Errors
///
/// Returns [`EngineError::Operation`] if the operation fails.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::config::{StepConfig, ShellConfig};
/// use ironflow_engine::executor::execute_step_config;
/// use ironflow_core::provider::AgentProvider;
/// use ironflow_core::providers::claude::ClaudeCodeProvider;
/// use std::sync::Arc;
///
/// # async fn example() -> Result<(), ironflow_engine::error::EngineError> {
/// let provider: Arc<dyn AgentProvider> = Arc::new(ClaudeCodeProvider::new());
/// let config = StepConfig::Shell(ShellConfig::new("echo hello"));
/// let output = execute_step_config(&config, &provider, None).await?;
/// # Ok(())
/// # }
/// ```
#[tracing::instrument(name = "executor.execute_step", skip_all, fields(step.kind))]
pub async fn execute_step_config(
    config: &StepConfig,
    provider: &Arc<dyn AgentProvider>,
    log_sender: Option<StepLogSender>,
) -> Result<StepOutput, EngineError> {
    let kind = match config {
        StepConfig::Shell(_) => "shell",
        StepConfig::Http(_) => "http",
        StepConfig::Agent(_) => "agent",
        StepConfig::Workflow(_) => "workflow",
        StepConfig::Approval(_) => "approval",
    };
    tracing::Span::current().record("step.kind", kind);

    let result = match config {
        StepConfig::Shell(cfg) => {
            let mut executor = ShellExecutor::new(cfg);
            if let Some(sender) = log_sender {
                executor = executor.with_log_sender(sender);
            }
            executor.execute(provider).await
        }
        StepConfig::Http(cfg) => HttpExecutor::new(cfg).execute(provider).await,
        StepConfig::Agent(cfg) => {
            let mut executor = AgentExecutor::new(cfg);
            if let Some(sender) = log_sender {
                executor = executor.with_log_sender(sender);
            }
            executor.execute(provider).await
        }
        StepConfig::Workflow(_) => Err(EngineError::StepConfig(
            "workflow steps are executed by WorkflowContext, not the executor".to_string(),
        )),
        StepConfig::Approval(_) => Err(EngineError::StepConfig(
            "approval steps are executed by WorkflowContext, not the executor".to_string(),
        )),
    };

    #[cfg(feature = "prometheus")]
    {
        use ironflow_core::metric_names::{
            STATUS_ERROR, STATUS_SUCCESS, STEP_DURATION_SECONDS, STEPS_TOTAL,
        };
        use metrics::{counter, histogram};
        let status = if result.is_ok() {
            STATUS_SUCCESS
        } else {
            STATUS_ERROR
        };
        counter!(STEPS_TOTAL, "kind" => kind, "status" => status).increment(1);
        if let Ok(ref output) = result {
            histogram!(STEP_DURATION_SECONDS, "kind" => kind)
                .record(output.duration_ms as f64 / 1000.0);
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use ironflow_core::provider::DebugMessage;
    use serde_json::json;

    #[test]
    fn step_output_with_no_debug_messages_returns_none() {
        let output = StepOutput {
            output: json!({"result": "ok"}),
            duration_ms: 100,
            cost_usd: rust_decimal::Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: None,
        };

        assert_eq!(output.debug_messages_json(), None);
    }

    #[test]
    fn step_output_with_empty_debug_messages_returns_some_empty_array() {
        let output = StepOutput {
            output: json!({"result": "ok"}),
            duration_ms: 100,
            cost_usd: rust_decimal::Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: Some(Vec::new()),
        };

        let json_val = output.debug_messages_json();
        assert!(json_val.is_some());
        let arr = json_val.unwrap();
        assert!(arr.is_array());
        assert_eq!(arr.as_array().unwrap().len(), 0);
    }

    #[test]
    fn step_output_debug_messages_json_serializes_messages() {
        let json_msgs = json!([
            {
                "text": "Hello",
                "thinking": null,
                "thinking_redacted": false,
                "tool_calls": [],
                "tool_results": [],
                "stop_reason": "end_turn",
                "input_tokens": 10,
                "output_tokens": 20
            },
            {
                "text": "Hi there",
                "thinking": null,
                "thinking_redacted": false,
                "tool_calls": [],
                "tool_results": [],
                "stop_reason": "end_turn",
                "input_tokens": 15,
                "output_tokens": 25
            }
        ]);

        let messages: Vec<DebugMessage> =
            serde_json::from_value(json_msgs.clone()).expect("deserialize debug messages");

        let output = StepOutput {
            output: json!({"result": "ok"}),
            duration_ms: 100,
            cost_usd: rust_decimal::Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: Some(messages),
        };

        let json_val = output.debug_messages_json();
        assert!(json_val.is_some());

        let arr = json_val.unwrap();
        assert!(arr.is_array());
        let messages_array = arr.as_array().unwrap();
        assert_eq!(messages_array.len(), 2);
        assert_eq!(messages_array[0]["text"], "Hello");
        assert_eq!(messages_array[1]["text"], "Hi there");
    }

    #[test]
    fn step_output_contains_all_metrics() {
        let output = StepOutput {
            output: json!({"data": "test"}),
            duration_ms: 5000,
            cost_usd: rust_decimal::Decimal::new(123, 2),
            input_tokens: Some(100),
            output_tokens: Some(200),
            model: Some("claude-sonnet".to_string()),
            debug_messages: None,
        };

        assert_eq!(output.duration_ms, 5000);
        assert_eq!(output.cost_usd, rust_decimal::Decimal::new(123, 2));
        assert_eq!(output.input_tokens, Some(100));
        assert_eq!(output.output_tokens, Some(200));
        assert_eq!(output.model, Some("claude-sonnet".to_string()));
    }

    #[test]
    fn step_output_default_tokens_and_model_are_none() {
        let output = StepOutput {
            output: json!({}),
            duration_ms: 0,
            cost_usd: rust_decimal::Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: None,
        };

        assert!(output.input_tokens.is_none());
        assert!(output.output_tokens.is_none());
        assert!(output.model.is_none());
    }

    #[test]
    fn parallel_step_result_contains_step_metadata() {
        let step_id = uuid::Uuid::now_v7();
        let output = StepOutput {
            output: json!({"done": true}),
            duration_ms: 1000,
            cost_usd: rust_decimal::Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: None,
        };

        let result = ParallelStepResult {
            name: "build".to_string(),
            output,
            step_id,
        };

        assert_eq!(result.name, "build");
        assert_eq!(result.step_id, step_id);
        assert_eq!(result.output.duration_ms, 1000);
    }

    #[test]
    fn step_output_serializes_complex_json_output() {
        let complex_output = json!({
            "status": "success",
            "data": {
                "items": [1, 2, 3],
                "nested": {
                    "key": "value"
                }
            }
        });

        let output = StepOutput {
            output: complex_output.clone(),
            duration_ms: 100,
            cost_usd: rust_decimal::Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: None,
        };

        assert_eq!(output.output, complex_output);
        assert_eq!(output.output["status"], "success");
        assert_eq!(output.output["data"]["items"][0], 1);
        assert_eq!(output.output["data"]["nested"]["key"], "value");
    }

    #[test]
    fn step_result_from_success_captures_all_fields() {
        let trace_id = Uuid::nil();
        let output = StepOutput {
            output: json!({"stdout": "ok"}),
            duration_ms: 1500,
            cost_usd: Decimal::new(42, 2),
            input_tokens: Some(100),
            output_tokens: Some(200),
            model: Some("claude-sonnet".to_string()),
            debug_messages: None,
        };

        let result = StepResult::from_success(trace_id, "build", &output);

        assert_eq!(result.trace_id, trace_id);
        assert_eq!(result.name, "build");
        assert_eq!(result.status, StepStatus::Completed);
        assert_eq!(result.duration_ms, 1500);
        assert_eq!(result.cost_usd, Decimal::new(42, 2));
        assert_eq!(result.input_tokens, Some(100));
        assert_eq!(result.output_tokens, Some(200));
        assert!(result.error.is_none());
        assert!(result.output_summary.is_some());
        assert!(result.output_summary.unwrap().contains("stdout"));
    }

    #[test]
    fn step_result_from_failure_captures_error() {
        let trace_id = Uuid::nil();
        let result =
            StepResult::from_failure(trace_id, "deploy", "connection refused", 500, Decimal::ZERO);

        assert_eq!(result.trace_id, trace_id);
        assert_eq!(result.name, "deploy");
        assert_eq!(result.status, StepStatus::Failed);
        assert_eq!(result.duration_ms, 500);
        assert_eq!(result.error, Some("connection refused".to_string()));
        assert!(result.output_summary.is_none());
    }

    #[test]
    fn step_result_output_summary_truncates_long_output() {
        let long_value = json!({"data": "x".repeat(1000)});
        let output = StepOutput {
            output: long_value,
            duration_ms: 0,
            cost_usd: Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: None,
        };

        let result = StepResult::from_success(Uuid::nil(), "test", &output);
        let summary = result.output_summary.unwrap();
        assert_eq!(summary.len(), 500);
    }
}

#[cfg(test)]
mod output_helper_tests {
    use super::*;
    use serde::Deserialize;
    use serde_json::json;

    fn output(value: Value) -> StepOutput {
        StepOutput {
            output: value,
            duration_ms: 1,
            cost_usd: Decimal::ZERO,
            input_tokens: None,
            output_tokens: None,
            model: None,
            debug_messages: None,
        }
    }

    #[test]
    fn shell_helpers_read_shell_fields() {
        let out = output(json!({"stdout": "hi\n", "stderr": "warn", "exit_code": 0}));
        assert_eq!(out.exit_code(), Some(0));
        assert_eq!(out.stdout(), "hi\n");
        assert_eq!(out.stderr(), "warn");
        assert!(out.is_success());
        assert_eq!(out.status(), None);
        assert_eq!(out.body(), "");
    }

    #[test]
    fn shell_non_zero_exit_is_not_success() {
        let out = output(json!({"stdout": "", "stderr": "", "exit_code": 127}));
        assert_eq!(out.exit_code(), Some(127));
        assert!(!out.is_success());
    }

    #[test]
    fn http_helpers_read_http_fields() {
        let out = output(json!({"status": 200, "body": "{\"ok\":true}"}));
        assert_eq!(out.status(), Some(200));
        assert_eq!(out.body(), "{\"ok\":true}");
        assert!(out.is_success());
        assert_eq!(out.exit_code(), None);
        assert_eq!(out.stdout(), "");
    }

    #[test]
    fn http_error_status_is_not_success() {
        assert!(!output(json!({"status": 500, "body": ""})).is_success());
        assert!(!output(json!({"status": 199, "body": ""})).is_success());
        assert!(output(json!({"status": 299, "body": ""})).is_success());
    }

    #[test]
    fn status_out_of_u16_range_is_none() {
        assert_eq!(output(json!({"status": 70000})).status(), None);
        assert_eq!(output(json!({"status": "200"})).status(), None);
    }

    #[test]
    fn agent_output_without_markers_is_not_success() {
        let out = output(json!({"summary": "fine"}));
        assert!(!out.is_success());
        assert_eq!(out.exit_code(), None);
        assert_eq!(out.stdout(), "");
        assert_eq!(out.body(), "");
    }

    #[test]
    fn json_deserializes_structured_output() {
        #[derive(Deserialize, Debug, PartialEq)]
        struct Review {
            score: u8,
            summary: String,
        }
        let out = output(json!({"score": 9, "summary": "good"}));
        let review: Review = out.json().expect("matches schema");
        assert_eq!(
            review,
            Review {
                score: 9,
                summary: "good".to_string()
            }
        );
    }

    #[test]
    fn json_reports_mismatch_as_serialization_error() {
        #[derive(Deserialize, Debug)]
        struct Review {
            #[allow(dead_code)]
            score: u8,
        }
        let out = output(json!({"score": "nine"}));
        let err = out.json::<Review>().expect_err("type mismatch");
        assert!(matches!(err, EngineError::Serialization(_)));
    }

    #[test]
    fn helpers_tolerate_non_object_output() {
        let out = output(json!("plain text"));
        assert_eq!(out.exit_code(), None);
        assert_eq!(out.status(), None);
        assert_eq!(out.stdout(), "");
        assert!(!out.is_success());
    }
}