ironflow-engine 2.41.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
//! Per-workflow broadcast event bus for real-time monitoring.
//!
//! [`WorkflowEventBus`] maintains one [`tokio::sync::broadcast`] channel per
//! workflow run. Consumers (dashboards, SSE routes) subscribe to a specific
//! `run_id` and receive only the events for that run.
//!
//! # Architecture
//!
//! - [`WorkflowEvent`] -- granular step-level events (started, completed,
//!   failed, approval, human input, token usage).
//! - [`WorkflowEventBus`] -- per-run broadcast channels with subscribe /
//!   publish / remove lifecycle.
//!
//! # Examples
//!
//! ```
//! use ironflow_engine::notify::{WorkflowEvent, WorkflowEventBus, WorkflowStepStartedEvent};
//! use uuid::Uuid;
//! use chrono::Utc;
//!
//! let bus = WorkflowEventBus::new();
//! let run_id = Uuid::now_v7();
//!
//! let mut rx = bus.subscribe(run_id);
//!
//! bus.publish(run_id, WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
//!     step_name: "build".to_string(),
//!     step_index: 0,
//!     timestamp: Utc::now(),
//! }));
//! ```

use std::collections::HashMap;
use std::sync::RwLock;

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::broadcast;
use uuid::Uuid;

/// Default broadcast channel buffer size per run.
const DEFAULT_BUFFER_SIZE: usize = 64;

/// Payload of the `WorkflowEvent::StepStarted` workflow event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::WorkflowStepStartedEvent;
///
/// let payload = WorkflowStepStartedEvent {
///     step_name: "build".to_string(),
///     step_index: 0,
///     timestamp: Utc::now(),
/// };
/// assert_eq!(payload.step_index, 0);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct WorkflowStepStartedEvent {
    /// Human-readable step name.
    pub step_name: String,
    /// Zero-based position in the workflow.
    pub step_index: u32,
    /// When the step started.
    pub timestamp: DateTime<Utc>,
}

/// Payload of the `WorkflowEvent::StepCompleted` workflow event.
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::WorkflowStepCompletedEvent;
///
/// let payload = WorkflowStepCompletedEvent {
///     step_name: "deploy".to_string(),
///     step_index: 1,
///     duration_ms: 5000,
///     output_summary: Some("deployed v1.2.3".to_string()),
/// };
/// assert_eq!(payload.duration_ms, 5000);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct WorkflowStepCompletedEvent {
    /// Human-readable step name.
    pub step_name: String,
    /// Zero-based position in the workflow.
    pub step_index: u32,
    /// Step duration in milliseconds.
    pub duration_ms: u64,
    /// Optional summary of the step output.
    pub output_summary: Option<String>,
}

/// Payload of the `WorkflowEvent::StepFailed` workflow event.
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::WorkflowStepFailedEvent;
///
/// let payload = WorkflowStepFailedEvent {
///     step_name: "test".to_string(),
///     step_index: 2,
///     error: "exit code 1".to_string(),
///     duration_ms: 3000,
/// };
/// assert_eq!(payload.error, "exit code 1");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct WorkflowStepFailedEvent {
    /// Human-readable step name.
    pub step_name: String,
    /// Zero-based position in the workflow.
    pub step_index: u32,
    /// Error description.
    pub error: String,
    /// Step duration in milliseconds.
    pub duration_ms: u64,
}

/// Payload of the `WorkflowEvent::ApprovalRequired` workflow event.
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::WorkflowApprovalRequiredEvent;
/// use uuid::Uuid;
///
/// let payload = WorkflowApprovalRequiredEvent {
///     step_name: "prod-gate".to_string(),
///     step_index: 3,
///     approval_id: Uuid::now_v7(),
/// };
/// assert_eq!(payload.step_name, "prod-gate");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct WorkflowApprovalRequiredEvent {
    /// Human-readable step name.
    pub step_name: String,
    /// Zero-based position in the workflow.
    pub step_index: u32,
    /// Identifier of the approval gate.
    pub approval_id: Uuid,
}

/// Payload of the `WorkflowEvent::InputRequired` workflow event.
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::WorkflowInputRequiredEvent;
/// use serde_json::json;
/// use uuid::Uuid;
///
/// let payload = WorkflowInputRequiredEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Uuid::now_v7(),
///     step_name: "clarify".to_string(),
///     step_index: 2,
///     message: "Answer the questions".to_string(),
///     schema: json!({"type": "object"}),
/// };
/// assert_eq!(payload.step_name, "clarify");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct WorkflowInputRequiredEvent {
    /// The run waiting for the input.
    pub run_id: Uuid,
    /// Identifier of the human input step; the answer is posted to it.
    pub step_id: Uuid,
    /// Human-readable step name.
    pub step_name: String,
    /// Zero-based position in the workflow.
    pub step_index: u32,
    /// Message displayed to the person answering.
    pub message: String,
    /// JSON schema the answer must match.
    #[cfg_attr(feature = "openapi", schema(value_type = Object))]
    pub schema: Value,
}

/// Payload of the `WorkflowEvent::AgentStepTokensUsed` workflow event.
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::WorkflowAgentStepTokensUsedEvent;
/// use rust_decimal::Decimal;
///
/// let payload = WorkflowAgentStepTokensUsedEvent {
///     step_name: "review".to_string(),
///     tokens: 15_000,
///     cost_usd: Decimal::new(42, 4),
/// };
/// assert_eq!(payload.tokens, 15_000);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct WorkflowAgentStepTokensUsedEvent {
    /// Human-readable step name.
    pub step_name: String,
    /// Total tokens consumed.
    pub tokens: u64,
    /// Estimated cost in USD.
    pub cost_usd: Decimal,
}

/// A granular step-level event for real-time workflow monitoring.
///
/// Unlike [`Event`](super::Event) which covers the full system lifecycle
/// (runs, auth, audit), `WorkflowEvent` tracks individual step transitions
/// within a single run. Serialized with a `type` discriminant for UI
/// consumption.
///
/// Each variant wraps a dedicated payload struct; the serialized form stays
/// flat, with `type` sitting next to the payload fields.
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::{WorkflowEvent, WorkflowStepStartedEvent};
/// use chrono::Utc;
///
/// let event = WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
///     step_name: "deploy".to_string(),
///     step_index: 0,
///     timestamp: Utc::now(),
/// });
/// assert_eq!(event.event_type(), "step_started");
///
/// let json = serde_json::to_string(&event)?;
/// assert!(json.contains("\"type\":\"step_started\""));
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum WorkflowEvent {
    /// A step began execution.
    StepStarted(WorkflowStepStartedEvent),

    /// A step completed successfully.
    StepCompleted(WorkflowStepCompletedEvent),

    /// A step failed.
    StepFailed(WorkflowStepFailedEvent),

    /// A step requires human approval before the run can continue.
    ApprovalRequired(WorkflowApprovalRequiredEvent),

    /// A step waits for a typed human input before the run can continue.
    InputRequired(WorkflowInputRequiredEvent),

    /// Token usage report for an agent step.
    AgentStepTokensUsed(WorkflowAgentStepTokensUsedEvent),
}

impl WorkflowEvent {
    /// Event type constant for [`StepStarted`](WorkflowEvent::StepStarted).
    pub const STEP_STARTED: &'static str = "step_started";
    /// Event type constant for [`StepCompleted`](WorkflowEvent::StepCompleted).
    pub const STEP_COMPLETED: &'static str = "step_completed";
    /// Event type constant for [`StepFailed`](WorkflowEvent::StepFailed).
    pub const STEP_FAILED: &'static str = "step_failed";
    /// Event type constant for [`ApprovalRequired`](WorkflowEvent::ApprovalRequired).
    pub const APPROVAL_REQUIRED: &'static str = "approval_required";
    /// Event type constant for [`InputRequired`](WorkflowEvent::InputRequired).
    pub const INPUT_REQUIRED: &'static str = "input_required";
    /// Event type constant for [`AgentStepTokensUsed`](WorkflowEvent::AgentStepTokensUsed).
    pub const AGENT_STEP_TOKENS_USED: &'static str = "agent_step_tokens_used";

    /// Returns the event type as a static string (e.g. `"step_started"`).
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::{WorkflowEvent, WorkflowStepStartedEvent};
    /// use chrono::Utc;
    ///
    /// let event = WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
    ///     step_name: "build".to_string(),
    ///     step_index: 0,
    ///     timestamp: Utc::now(),
    /// });
    /// assert_eq!(event.event_type(), "step_started");
    /// ```
    #[deny(unreachable_patterns)]
    pub fn event_type(&self) -> &'static str {
        match self {
            WorkflowEvent::StepStarted(_) => Self::STEP_STARTED,
            WorkflowEvent::StepCompleted(_) => Self::STEP_COMPLETED,
            WorkflowEvent::StepFailed(_) => Self::STEP_FAILED,
            WorkflowEvent::ApprovalRequired(_) => Self::APPROVAL_REQUIRED,
            WorkflowEvent::InputRequired(_) => Self::INPUT_REQUIRED,
            WorkflowEvent::AgentStepTokensUsed(_) => Self::AGENT_STEP_TOKENS_USED,
        }
    }
}

/// Per-workflow broadcast event bus for real-time monitoring.
///
/// Maintains one [`tokio::sync::broadcast`] channel per workflow run.
/// Consumers call [`subscribe`](Self::subscribe) to receive events for a
/// specific run; producers call [`publish`](Self::publish) to broadcast
/// an event to all subscribers of that run.
///
/// Thread-safe and cheaply cloneable (`Clone` shares the same inner state).
///
/// # Examples
///
/// ```
/// use ironflow_engine::notify::{WorkflowEvent, WorkflowEventBus, WorkflowStepStartedEvent};
/// use uuid::Uuid;
/// use chrono::Utc;
///
/// let bus = WorkflowEventBus::new();
/// let run_id = Uuid::now_v7();
///
/// let mut rx = bus.subscribe(run_id);
/// bus.publish(run_id, WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
///     step_name: "build".to_string(),
///     step_index: 0,
///     timestamp: Utc::now(),
/// }));
/// ```
#[derive(Clone)]
pub struct WorkflowEventBus {
    channels: std::sync::Arc<RwLock<HashMap<Uuid, broadcast::Sender<WorkflowEvent>>>>,
}

impl WorkflowEventBus {
    /// Create a new empty event bus.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::WorkflowEventBus;
    ///
    /// let bus = WorkflowEventBus::new();
    /// ```
    pub fn new() -> Self {
        Self {
            channels: std::sync::Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Subscribe to events for a specific workflow run.
    ///
    /// If no channel exists for this `run_id`, one is created on demand.
    /// Returns a broadcast receiver that yields [`WorkflowEvent`]s for
    /// that run only.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::WorkflowEventBus;
    /// use uuid::Uuid;
    ///
    /// let bus = WorkflowEventBus::new();
    /// let run_id = Uuid::now_v7();
    /// let _rx = bus.subscribe(run_id);
    /// ```
    pub fn subscribe(&self, run_id: Uuid) -> broadcast::Receiver<WorkflowEvent> {
        let mut channels = self.channels.write().expect("event bus lock poisoned");
        let sender = channels
            .entry(run_id)
            .or_insert_with(|| broadcast::channel(DEFAULT_BUFFER_SIZE).0);
        sender.subscribe()
    }

    /// Broadcast an event to all subscribers of a specific workflow run.
    ///
    /// If no channel exists for `run_id` (no subscriber has called
    /// [`subscribe`](Self::subscribe)), the event is silently dropped.
    /// If subscribers exist but none are actively listening, the send
    /// error is ignored.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::{WorkflowEvent, WorkflowEventBus, WorkflowStepStartedEvent};
    /// use uuid::Uuid;
    /// use chrono::Utc;
    ///
    /// let bus = WorkflowEventBus::new();
    /// let run_id = Uuid::now_v7();
    ///
    /// // No subscriber -- silently dropped.
    /// bus.publish(run_id, WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
    ///     step_name: "build".to_string(),
    ///     step_index: 0,
    ///     timestamp: Utc::now(),
    /// }));
    /// ```
    pub fn publish(&self, run_id: Uuid, event: WorkflowEvent) {
        let channels = self.channels.read().expect("event bus lock poisoned");
        if let Some(sender) = channels.get(&run_id) {
            let _ = sender.send(event);
        }
    }

    /// Remove the channel for a workflow run.
    ///
    /// Call this when a run completes or is cleaned up to free resources.
    /// If no channel exists for `run_id`, this is a no-op.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::WorkflowEventBus;
    /// use uuid::Uuid;
    ///
    /// let bus = WorkflowEventBus::new();
    /// let run_id = Uuid::now_v7();
    /// let _rx = bus.subscribe(run_id);
    /// bus.remove(run_id);
    /// ```
    pub fn remove(&self, run_id: Uuid) {
        let mut channels = self.channels.write().expect("event bus lock poisoned");
        channels.remove(&run_id);
    }
}

impl Default for WorkflowEventBus {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for WorkflowEventBus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let count = self.channels.read().map(|c| c.len()).unwrap_or(0);
        f.debug_struct("WorkflowEventBus")
            .field("active_channels", &count)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn step_started(step_name: &str) -> WorkflowEvent {
        WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
            step_name: step_name.to_string(),
            step_index: 0,
            timestamp: Utc::now(),
        })
    }

    #[tokio::test]
    async fn subscribe_receives_published_events() {
        let bus = WorkflowEventBus::new();
        let run_id = Uuid::now_v7();

        let mut rx = bus.subscribe(run_id);

        bus.publish(run_id, step_started("build"));

        let received = rx.recv().await.expect("should receive event");
        assert_eq!(received.event_type(), "step_started");
        match received {
            WorkflowEvent::StepStarted(e) => {
                assert_eq!(e.step_name, "build");
                assert_eq!(e.step_index, 0);
            }
            _ => panic!("expected StepStarted"),
        }
    }

    #[test]
    fn subscribe_creates_channel_on_demand() {
        let bus = WorkflowEventBus::new();
        let run_id = Uuid::now_v7();

        let count_before = bus.channels.read().unwrap().len();
        assert_eq!(count_before, 0);

        let _rx = bus.subscribe(run_id);

        let count_after = bus.channels.read().unwrap().len();
        assert_eq!(count_after, 1);
    }

    #[test]
    fn publish_unknown_run_is_noop() {
        let bus = WorkflowEventBus::new();
        let unknown_run = Uuid::now_v7();

        bus.publish(unknown_run, step_started("build"));
    }

    #[test]
    fn remove_cleans_up_channel() {
        let bus = WorkflowEventBus::new();
        let run_id = Uuid::now_v7();

        let _rx = bus.subscribe(run_id);
        assert_eq!(bus.channels.read().unwrap().len(), 1);

        bus.remove(run_id);
        assert_eq!(bus.channels.read().unwrap().len(), 0);
    }

    #[test]
    fn remove_unknown_is_noop() {
        let bus = WorkflowEventBus::new();
        bus.remove(Uuid::now_v7());
    }

    #[test]
    fn workflow_event_serde_roundtrip() {
        let cases: Vec<WorkflowEvent> = vec![
            WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
                step_name: "build".to_string(),
                step_index: 0,
                timestamp: Utc::now(),
            }),
            WorkflowEvent::StepCompleted(WorkflowStepCompletedEvent {
                step_name: "deploy".to_string(),
                step_index: 1,
                duration_ms: 5000,
                output_summary: Some("deployed v1.2.3".to_string()),
            }),
            WorkflowEvent::StepFailed(WorkflowStepFailedEvent {
                step_name: "test".to_string(),
                step_index: 2,
                error: "exit code 1".to_string(),
                duration_ms: 3000,
            }),
            WorkflowEvent::ApprovalRequired(WorkflowApprovalRequiredEvent {
                step_name: "prod-gate".to_string(),
                step_index: 3,
                approval_id: Uuid::now_v7(),
            }),
            WorkflowEvent::InputRequired(WorkflowInputRequiredEvent {
                run_id: Uuid::now_v7(),
                step_id: Uuid::now_v7(),
                step_name: "clarify".to_string(),
                step_index: 4,
                message: "Answer the questions".to_string(),
                schema: json!({"type": "object"}),
            }),
            WorkflowEvent::AgentStepTokensUsed(WorkflowAgentStepTokensUsedEvent {
                step_name: "review".to_string(),
                tokens: 15000,
                cost_usd: Decimal::new(42, 4),
            }),
        ];

        for event in &cases {
            let json = serde_json::to_string(event).expect("serialize");
            let back: WorkflowEvent = serde_json::from_str(&json).expect("deserialize");

            assert_eq!(back.event_type(), event.event_type());
            assert!(json.contains(&format!("\"type\":\"{}\"", event.event_type())));
        }
    }

    /// The pre-refactor wire format used flat inline-struct variants. Newtype
    /// variants produce and accept the same JSON, so SSE consumers and stored
    /// payloads need no migration.
    #[test]
    fn workflow_event_legacy_flat_json_deserializes() {
        let approval_id: Uuid = "01890000-0000-7000-8000-000000000002"
            .parse()
            .expect("valid uuid");

        let raw = r#"{"type":"step_started","step_name":"build","step_index":0,"timestamp":"2026-01-01T00:00:00Z"}"#;
        match serde_json::from_str::<WorkflowEvent>(raw).expect("legacy payload") {
            WorkflowEvent::StepStarted(e) => {
                assert_eq!(e.step_name, "build");
                assert_eq!(e.step_index, 0);
            }
            other => panic!("expected StepStarted, got {other:?}"),
        }

        let raw = r#"{"type":"step_completed","step_name":"deploy","step_index":1,"duration_ms":5000,"output_summary":"deployed v1.2.3"}"#;
        match serde_json::from_str::<WorkflowEvent>(raw).expect("legacy payload") {
            WorkflowEvent::StepCompleted(e) => {
                assert_eq!(e.duration_ms, 5000);
                assert_eq!(e.output_summary.as_deref(), Some("deployed v1.2.3"));
            }
            other => panic!("expected StepCompleted, got {other:?}"),
        }

        let raw = r#"{"type":"step_failed","step_name":"test","step_index":2,"error":"exit code 1","duration_ms":3000}"#;
        match serde_json::from_str::<WorkflowEvent>(raw).expect("legacy payload") {
            WorkflowEvent::StepFailed(e) => {
                assert_eq!(e.error, "exit code 1");
                assert_eq!(e.duration_ms, 3000);
            }
            other => panic!("expected StepFailed, got {other:?}"),
        }

        let raw = r#"{"type":"approval_required","step_name":"prod-gate","step_index":3,"approval_id":"01890000-0000-7000-8000-000000000002"}"#;
        match serde_json::from_str::<WorkflowEvent>(raw).expect("legacy payload") {
            WorkflowEvent::ApprovalRequired(e) => {
                assert_eq!(e.approval_id, approval_id);
            }
            other => panic!("expected ApprovalRequired, got {other:?}"),
        }

        let raw = r#"{"type":"agent_step_tokens_used","step_name":"review","tokens":15000,"cost_usd":0.5}"#;
        match serde_json::from_str::<WorkflowEvent>(raw).expect("legacy payload") {
            WorkflowEvent::AgentStepTokensUsed(e) => {
                assert_eq!(e.tokens, 15000);
                assert_eq!(e.cost_usd, Decimal::new(5, 1));
            }
            other => panic!("expected AgentStepTokensUsed, got {other:?}"),
        }
    }

    /// Guards the internally-tagged representation: payload fields must stay
    /// siblings of `type`, never nested under a variant key.
    #[test]
    fn serialized_workflow_event_is_flat_with_type_tag() {
        let event = WorkflowEvent::StepFailed(WorkflowStepFailedEvent {
            step_name: "test".to_string(),
            step_index: 2,
            error: "exit code 1".to_string(),
            duration_ms: 3000,
        });

        let value: serde_json::Value = serde_json::to_value(&event).expect("serialize");
        let object = value.as_object().expect("event serializes to an object");

        assert_eq!(
            object.get("type").and_then(|v| v.as_str()),
            Some("step_failed")
        );
        assert_eq!(
            object.get("step_name").and_then(|v| v.as_str()),
            Some("test")
        );
        assert_eq!(object.get("step_index").and_then(|v| v.as_u64()), Some(2));
        assert_eq!(
            object.get("error").and_then(|v| v.as_str()),
            Some("exit code 1")
        );
        assert_eq!(
            object.get("duration_ms").and_then(|v| v.as_u64()),
            Some(3000)
        );
        assert_eq!(object.len(), 5, "no nesting: {object:?}");
    }

    #[test]
    fn input_required_event_serializes_flat_with_its_schema() {
        let step_id = Uuid::now_v7();
        let event = WorkflowEvent::InputRequired(WorkflowInputRequiredEvent {
            run_id: Uuid::now_v7(),
            step_id,
            step_name: "clarify".to_string(),
            step_index: 1,
            message: "Answer the questions".to_string(),
            schema: json!({"type": "object", "required": ["answers"]}),
        });

        let value = serde_json::to_value(&event).expect("serialize");
        assert_eq!(value["type"], "input_required");
        assert_eq!(value["step_id"], step_id.to_string());
        assert_eq!(value["message"], "Answer the questions");
        assert_eq!(value["schema"]["required"][0], "answers");
        assert_eq!(event.event_type(), WorkflowEvent::INPUT_REQUIRED);
    }

    #[test]
    fn event_type_all_variants() {
        let cases: Vec<(WorkflowEvent, &str)> = vec![
            (
                WorkflowEvent::StepStarted(WorkflowStepStartedEvent {
                    step_name: "s".to_string(),
                    step_index: 0,
                    timestamp: Utc::now(),
                }),
                "step_started",
            ),
            (
                WorkflowEvent::StepCompleted(WorkflowStepCompletedEvent {
                    step_name: "s".to_string(),
                    step_index: 0,
                    duration_ms: 0,
                    output_summary: None,
                }),
                "step_completed",
            ),
            (
                WorkflowEvent::StepFailed(WorkflowStepFailedEvent {
                    step_name: "s".to_string(),
                    step_index: 0,
                    error: "e".to_string(),
                    duration_ms: 0,
                }),
                "step_failed",
            ),
            (
                WorkflowEvent::ApprovalRequired(WorkflowApprovalRequiredEvent {
                    step_name: "s".to_string(),
                    step_index: 0,
                    approval_id: Uuid::now_v7(),
                }),
                "approval_required",
            ),
            (
                WorkflowEvent::InputRequired(WorkflowInputRequiredEvent {
                    run_id: Uuid::now_v7(),
                    step_id: Uuid::now_v7(),
                    step_name: "s".to_string(),
                    step_index: 0,
                    message: "m".to_string(),
                    schema: Value::Null,
                }),
                "input_required",
            ),
            (
                WorkflowEvent::AgentStepTokensUsed(WorkflowAgentStepTokensUsedEvent {
                    step_name: "s".to_string(),
                    tokens: 0,
                    cost_usd: Decimal::ZERO,
                }),
                "agent_step_tokens_used",
            ),
        ];

        for (event, expected) in cases {
            assert_eq!(event.event_type(), expected);
        }
    }

    #[tokio::test]
    async fn multiple_subscribers_receive_same_event() {
        let bus = WorkflowEventBus::new();
        let run_id = Uuid::now_v7();

        let mut rx1 = bus.subscribe(run_id);
        let mut rx2 = bus.subscribe(run_id);

        bus.publish(run_id, step_started("build"));

        let e1 = rx1.recv().await.expect("rx1 should receive");
        let e2 = rx2.recv().await.expect("rx2 should receive");

        assert_eq!(e1.event_type(), "step_started");
        assert_eq!(e2.event_type(), "step_started");
    }

    #[tokio::test]
    async fn events_isolated_between_runs() {
        let bus = WorkflowEventBus::new();
        let run_a = Uuid::now_v7();
        let run_b = Uuid::now_v7();

        let mut rx_a = bus.subscribe(run_a);
        let mut rx_b = bus.subscribe(run_b);

        bus.publish(run_a, step_started("only-for-a"));

        let received = rx_a.recv().await.expect("rx_a should receive");
        match received {
            WorkflowEvent::StepStarted(e) => {
                assert_eq!(e.step_name, "only-for-a");
            }
            _ => panic!("expected StepStarted"),
        }

        // rx_b should have nothing -- try_recv returns Empty.
        assert!(rx_b.try_recv().is_err());
    }
}