ironflow-engine 2.40.1

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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
//! Domain events emitted throughout the ironflow lifecycle.

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use ironflow_store::entities::LogStream;
use ironflow_store::models::{ApprovalRequirement, Assignee, RunStatus, StepKind};

/// Vote counts assumed for approval events serialized before multi-approver
/// gates existed: one approval was always enough.
fn default_approval_count() -> u32 {
    1
}

/// Payload of the `Event::RunCreated` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::RunCreatedEvent;
/// use uuid::Uuid;
///
/// let payload = RunCreatedEvent {
///     run_id: Uuid::now_v7(),
///     workflow_name: "deploy".to_string(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.workflow_name, "deploy");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RunCreatedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Workflow name.
    pub workflow_name: String,
    /// When the run was created.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::RunStatusChanged` event.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// use chrono::Utc;
/// use ironflow_engine::notify::RunStatusChangedEvent;
/// use ironflow_store::models::RunStatus;
/// use rust_decimal::Decimal;
/// use uuid::Uuid;
///
/// let payload = RunStatusChangedEvent {
///     run_id: Uuid::now_v7(),
///     workflow_name: "deploy".to_string(),
///     from: RunStatus::Running,
///     to: RunStatus::Completed,
///     error: None,
///     cost_usd: Decimal::ZERO,
///     duration_ms: 5000,
///     labels: HashMap::new(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.to, RunStatus::Completed);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RunStatusChangedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Workflow name.
    pub workflow_name: String,
    /// Previous status.
    pub from: RunStatus,
    /// New status.
    pub to: RunStatus,
    /// Error message (when transitioning to Failed).
    pub error: Option<String>,
    /// Aggregated cost in USD at the time of transition.
    pub cost_usd: Decimal,
    /// Aggregated duration in milliseconds at the time of transition.
    pub duration_ms: u64,
    /// Labels of the run at the time of the transition.
    #[serde(default)]
    pub labels: HashMap<String, String>,
    /// When the transition occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::RunFailed` event.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
///
/// use chrono::Utc;
/// use ironflow_engine::notify::RunFailedEvent;
/// use rust_decimal::Decimal;
/// use uuid::Uuid;
///
/// let payload = RunFailedEvent {
///     run_id: Uuid::now_v7(),
///     workflow_name: "deploy".to_string(),
///     error: Some("step crashed".to_string()),
///     cost_usd: Decimal::ZERO,
///     duration_ms: 3000,
///     labels: HashMap::new(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.error.as_deref(), Some("step crashed"));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RunFailedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Workflow name.
    pub workflow_name: String,
    /// Error message.
    pub error: Option<String>,
    /// Aggregated cost in USD at the time of failure.
    pub cost_usd: Decimal,
    /// Aggregated duration in milliseconds at the time of failure.
    pub duration_ms: u64,
    /// Labels of the run at the time of the failure.
    #[serde(default)]
    pub labels: HashMap<String, String>,
    /// When the failure occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::RunBudgetExceeded` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::RunBudgetExceededEvent;
/// use rust_decimal::Decimal;
/// use uuid::Uuid;
///
/// let payload = RunBudgetExceededEvent {
///     run_id: Uuid::now_v7(),
///     workflow_name: "deploy".to_string(),
///     limit_usd: Decimal::new(200, 2),
///     spent_usd: Decimal::new(180, 2),
///     step_budget_usd: Decimal::new(50, 2),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.limit_usd, Decimal::new(200, 2));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RunBudgetExceededEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Workflow name.
    pub workflow_name: String,
    /// The configured cost cap in USD.
    pub limit_usd: Decimal,
    /// Cost already consumed when the cap was reached, in USD.
    pub spent_usd: Decimal,
    /// Declared budget of the refused step, in USD.
    pub step_budget_usd: Decimal,
    /// When the refusal occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::RetryForced` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::RetryForcedEvent;
/// use uuid::Uuid;
///
/// let payload = RetryForcedEvent {
///     run_id: Uuid::now_v7(),
///     workflow_name: "deploy".to_string(),
///     original_version: "1".to_string(),
///     current_version: "2".to_string(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.current_version, "2");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct RetryForcedEvent {
    /// The new run created by the forced retry.
    pub run_id: Uuid,
    /// Workflow name.
    pub workflow_name: String,
    /// Version stored on the original run.
    pub original_version: String,
    /// Current version of the handler.
    pub current_version: String,
    /// When the forced retry occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::StepCompleted` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::StepCompletedEvent;
/// use ironflow_store::models::StepKind;
/// use rust_decimal::Decimal;
/// use uuid::Uuid;
///
/// let payload = StepCompletedEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Uuid::now_v7(),
///     step_name: "build".to_string(),
///     kind: StepKind::Shell,
///     duration_ms: 1200,
///     cost_usd: Decimal::ZERO,
///     at: Utc::now(),
/// };
/// assert_eq!(payload.step_name, "build");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct StepCompletedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Step identifier.
    pub step_id: Uuid,
    /// Human-readable step name.
    pub step_name: String,
    /// Step operation kind.
    #[cfg_attr(feature = "openapi", schema(value_type = String))]
    pub kind: StepKind,
    /// Step duration in milliseconds.
    pub duration_ms: u64,
    /// Step cost in USD.
    pub cost_usd: Decimal,
    /// When the step completed.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::StepFailed` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::StepFailedEvent;
/// use ironflow_store::models::StepKind;
/// use uuid::Uuid;
///
/// let payload = StepFailedEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Uuid::now_v7(),
///     step_name: "build".to_string(),
///     kind: StepKind::Shell,
///     error: "exit code 1".to_string(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.error, "exit code 1");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct StepFailedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Step identifier.
    pub step_id: Uuid,
    /// Human-readable step name.
    pub step_name: String,
    /// Step operation kind.
    #[cfg_attr(feature = "openapi", schema(value_type = String))]
    pub kind: StepKind,
    /// Error message.
    pub error: String,
    /// When the step failed.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::ApprovalRequested` event.
///
/// Published when an approval gate opens. Carries the approvers the handler
/// required, if it set any.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::ApprovalRequestedEvent;
/// use uuid::Uuid;
///
/// let payload = ApprovalRequestedEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Uuid::now_v7(),
///     message: "Deploy to prod?".to_string(),
///     requirement: None,
///     at: Utc::now(),
/// };
/// assert_eq!(payload.message, "Deploy to prod?");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ApprovalRequestedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Approval step identifier.
    pub step_id: Uuid,
    /// Message displayed to reviewers.
    pub message: String,
    /// Approvers the handler required. `None` for a gate opened without
    /// approvers: one approval resolves it.
    #[serde(default)]
    pub requirement: Option<ApprovalRequirement>,
    /// When the approval was requested.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::ApprovalGranted` event.
///
/// Published for every vote cast on a gate. A vote with
/// `approvals_received < approvals_required` is recorded but does not resolve
/// the gate: the run stays `AwaitingApproval` until enough distinct approvers
/// voted.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::ApprovalGrantedEvent;
/// use uuid::Uuid;
///
/// let payload = ApprovalGrantedEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Some(Uuid::now_v7()),
///     approved_by: "alice".to_string(),
///     approvals_received: 1,
///     approvals_required: 2,
///     requirement: None,
///     at: Utc::now(),
/// };
/// assert!(payload.approvals_received < payload.approvals_required);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ApprovalGrantedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Approval step identifier. `None` in events recorded before it existed.
    #[serde(default)]
    pub step_id: Option<Uuid>,
    /// User who approved (ID or username).
    pub approved_by: String,
    /// Distinct approvals recorded on the gate, this one included.
    #[serde(default = "default_approval_count")]
    pub approvals_received: u32,
    /// Distinct approvals needed to resolve the gate.
    #[serde(default = "default_approval_count")]
    pub approvals_required: u32,
    /// Approvers the handler required, if any.
    #[serde(default)]
    pub requirement: Option<ApprovalRequirement>,
    /// When the approval was granted.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::ApprovalRejected` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::ApprovalRejectedEvent;
/// use uuid::Uuid;
///
/// let payload = ApprovalRejectedEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Some(Uuid::now_v7()),
///     rejected_by: "bob".to_string(),
///     requirement: None,
///     at: Utc::now(),
/// };
/// assert_eq!(payload.rejected_by, "bob");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ApprovalRejectedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Approval step identifier. `None` in events recorded before it existed.
    #[serde(default)]
    pub step_id: Option<Uuid>,
    /// User who rejected (ID or username).
    pub rejected_by: String,
    /// Approvers the handler required, if any.
    #[serde(default)]
    pub requirement: Option<ApprovalRequirement>,
    /// When the rejection occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::ApprovalEscalated` event.
///
/// Emitted every time an approval gate misses its SLA deadline, including the
/// repeated firings of a bare `Notify`/`Escalate` policy and the final
/// "chain exhausted" notice. The audit log persists it verbatim, so the whole
/// escalation history of a gate is reconstructable from it.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::ApprovalEscalatedEvent;
/// use uuid::Uuid;
///
/// let payload = ApprovalEscalatedEvent {
///     run_id: Uuid::now_v7(),
///     step_id: Uuid::now_v7(),
///     step_name: "prod-gate".to_string(),
///     stage: 0,
///     policy: "auto_reject".to_string(),
///     action: "rejected".to_string(),
///     reason: "approval deadline of 3600s expired".to_string(),
///     assignee: None,
///     at: Utc::now(),
/// };
/// assert_eq!(payload.policy, "auto_reject");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ApprovalEscalatedEvent {
    /// Run identifier.
    pub run_id: Uuid,
    /// Approval step identifier.
    pub step_id: Uuid,
    /// Human-readable step name.
    pub step_name: String,
    /// Escalation stage that fired (0-based index into the policy chain).
    pub stage: u32,
    /// Policy applied, e.g. `"auto_reject"`, `"notify"`, `"escalate"`.
    pub policy: String,
    /// What the escalation did, for the audit log.
    pub action: String,
    /// Why it fired, e.g. `"approval deadline of 3600s expired"`.
    pub reason: String,
    /// Assignee after the escalation, when it reassigned the gate.
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
    pub assignee: Option<Assignee>,
    /// When the escalation ran.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::LogLine` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::{LogLineEvent, LogStream};
/// use uuid::Uuid;
///
/// let payload = LogLineEvent {
///     id: Uuid::now_v7(),
///     run_id: Uuid::now_v7(),
///     step_id: Uuid::now_v7(),
///     step_name: "build".to_string(),
///     stream: LogStream::Stdout,
///     line: "Compiling ironflow v0.1.0".to_string(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.line, "Compiling ironflow v0.1.0");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct LogLineEvent {
    /// Persisted entry identifier (UUID v7, time-ordered).
    ///
    /// Matches the `id` of the log entry later stored for this line, so clients
    /// can de-duplicate the live SSE stream against the persisted history
    /// fetched from `GET /runs/:id/logs`.
    ///
    /// Defaults to the nil UUID when absent, so a payload emitted by an older
    /// producer still deserializes instead of dropping the whole event.
    #[serde(default)]
    pub id: Uuid,
    /// Run identifier.
    pub run_id: Uuid,
    /// Step identifier.
    pub step_id: Uuid,
    /// Human-readable step name.
    pub step_name: String,
    /// Output stream.
    pub stream: LogStream,
    /// The log line content.
    pub line: String,
    /// When the line was emitted.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::UserSignedIn` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::UserSignedInEvent;
/// use uuid::Uuid;
///
/// let payload = UserSignedInEvent {
///     user_id: Uuid::now_v7(),
///     username: "alice".to_string(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.username, "alice");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct UserSignedInEvent {
    /// User identifier.
    pub user_id: Uuid,
    /// Username.
    pub username: String,
    /// When the sign-in occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::UserSignedUp` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::UserSignedUpEvent;
/// use uuid::Uuid;
///
/// let payload = UserSignedUpEvent {
///     user_id: Uuid::now_v7(),
///     username: "alice".to_string(),
///     at: Utc::now(),
/// };
/// assert_eq!(payload.username, "alice");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct UserSignedUpEvent {
    /// User identifier.
    pub user_id: Uuid,
    /// Username.
    pub username: String,
    /// When the sign-up occurred.
    pub at: DateTime<Utc>,
}

/// Payload of the `Event::UserSignedOut` event.
///
/// # Examples
///
/// ```
/// use chrono::Utc;
/// use ironflow_engine::notify::UserSignedOutEvent;
/// use uuid::Uuid;
///
/// let user_id = Uuid::now_v7();
/// let payload = UserSignedOutEvent {
///     user_id,
///     at: Utc::now(),
/// };
/// assert_eq!(payload.user_id, user_id);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct UserSignedOutEvent {
    /// User identifier.
    pub user_id: Uuid,
    /// When the sign-out occurred.
    pub at: DateTime<Utc>,
}

/// A domain event emitted by the ironflow system.
///
/// Covers the full lifecycle: runs, steps, approvals, and authentication.
/// Subscribers receive these via [`EventPublisher`](super::EventPublisher)
/// and pattern-match on the variants they care about.
///
/// Each variant wraps a dedicated payload struct. The serialized form stays
/// flat: the `type` discriminant sits next to the payload fields, so
/// `{"type":"run_created","run_id":...}` round-trips unchanged.
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use ironflow_engine::notify::{Event, RunStatusChangedEvent};
/// use ironflow_store::models::RunStatus;
/// use uuid::Uuid;
///
/// let event = Event::RunStatusChanged(RunStatusChangedEvent {
///     run_id: Uuid::now_v7(),
///     workflow_name: "deploy".to_string(),
///     from: RunStatus::Running,
///     to: RunStatus::Completed,
///     error: None,
///     cost_usd: rust_decimal::Decimal::ZERO,
///     duration_ms: 5000,
///     labels: HashMap::new(),
///     at: chrono::Utc::now(),
/// });
/// assert_eq!(event.event_type(), "run_status_changed");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    // -- Run lifecycle --
    /// A new run was created (status: Pending).
    RunCreated(RunCreatedEvent),

    /// A run changed status.
    RunStatusChanged(RunStatusChangedEvent),

    /// A run transitioned to [`Failed`](ironflow_store::models::RunStatus::Failed).
    ///
    /// This is a convenience event emitted alongside [`RunStatusChanged`](Event::RunStatusChanged)
    /// when the target status is `Failed`. Subscribe to this instead of
    /// `RUN_STATUS_CHANGED` when you only care about failures.
    RunFailed(RunFailedEvent),

    /// A run was stopped because it reached its cumulative cost cap.
    ///
    /// Emitted when the engine refuses an agent step that would cross the run's
    /// `max_cost_usd`. The run transitions to
    /// [`Cancelled`](ironflow_store::models::RunStatus::Cancelled) and the step
    /// is never launched, so the reported spend is what the run had already
    /// consumed.
    RunBudgetExceeded(RunBudgetExceededEvent),

    /// A manual retry was forced despite a handler version mismatch.
    ///
    /// Emitted when a caller passes `force=true` on a retry where the
    /// handler version differs from the run's recorded version. This is
    /// an audit event: it means the new code will execute on the old
    /// payload without the handler explicitly declaring compatibility.
    RetryForced(RetryForcedEvent),

    // -- Step lifecycle --
    /// A step completed successfully.
    StepCompleted(StepCompletedEvent),

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

    // -- Approval --
    /// A run is waiting for human approval.
    ApprovalRequested(ApprovalRequestedEvent),

    /// A run was approved by a human.
    ApprovalGranted(ApprovalGrantedEvent),

    /// A run was rejected by a human.
    ApprovalRejected(ApprovalRejectedEvent),

    /// An approval gate missed its SLA deadline and an escalation policy ran.
    ApprovalEscalated(ApprovalEscalatedEvent),

    // -- Log streaming --
    /// A log line emitted during step execution.
    ///
    /// Pushed by the worker in real time so that SSE clients can stream
    /// step output as it happens, without waiting for step completion.
    LogLine(LogLineEvent),

    // -- Authentication --
    /// A user signed in.
    UserSignedIn(UserSignedInEvent),

    /// A new user signed up.
    UserSignedUp(UserSignedUpEvent),

    /// A user signed out.
    UserSignedOut(UserSignedOutEvent),
}

impl Event {
    /// Event type constant for [`RunCreated`](Event::RunCreated).
    pub const RUN_CREATED: &'static str = "run_created";
    /// Event type constant for [`RunStatusChanged`](Event::RunStatusChanged).
    pub const RUN_STATUS_CHANGED: &'static str = "run_status_changed";
    /// Event type constant for [`RunFailed`](Event::RunFailed).
    pub const RUN_FAILED: &'static str = "run_failed";
    /// Event type constant for [`RunBudgetExceeded`](Event::RunBudgetExceeded).
    pub const RUN_BUDGET_EXCEEDED: &'static str = "run_budget_exceeded";
    /// Event type constant for [`RetryForced`](Event::RetryForced).
    pub const RETRY_FORCED: &'static str = "retry_forced";
    /// Event type constant for [`StepCompleted`](Event::StepCompleted).
    pub const STEP_COMPLETED: &'static str = "step_completed";
    /// Event type constant for [`StepFailed`](Event::StepFailed).
    pub const STEP_FAILED: &'static str = "step_failed";
    /// Event type constant for [`ApprovalRequested`](Event::ApprovalRequested).
    pub const APPROVAL_REQUESTED: &'static str = "approval_requested";
    /// Event type constant for [`ApprovalGranted`](Event::ApprovalGranted).
    pub const APPROVAL_GRANTED: &'static str = "approval_granted";
    /// Event type constant for [`ApprovalRejected`](Event::ApprovalRejected).
    pub const APPROVAL_REJECTED: &'static str = "approval_rejected";
    /// Event type constant for [`ApprovalEscalated`](Event::ApprovalEscalated).
    pub const APPROVAL_ESCALATED: &'static str = "approval_escalated";
    /// Event type constant for [`LogLine`](Event::LogLine).
    pub const LOG_LINE: &'static str = "log_line";
    /// Event type constant for [`UserSignedIn`](Event::UserSignedIn).
    pub const USER_SIGNED_IN: &'static str = "user_signed_in";
    /// Event type constant for [`UserSignedUp`](Event::UserSignedUp).
    pub const USER_SIGNED_UP: &'static str = "user_signed_up";
    /// Event type constant for [`UserSignedOut`](Event::UserSignedOut).
    pub const USER_SIGNED_OUT: &'static str = "user_signed_out";

    /// All event types. Pass this to
    /// [`EventPublisher::subscribe`](super::EventPublisher::subscribe) to
    /// receive every event.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ironflow_engine::notify::{Event, EventPublisher, WebhookSubscriber};
    ///
    /// let mut publisher = EventPublisher::new();
    /// publisher.subscribe(
    ///     WebhookSubscriber::new("https://example.com/all"),
    ///     Event::ALL,
    /// );
    /// ```
    pub const ALL: &'static [&'static str] = &[
        Self::RUN_CREATED,
        Self::RUN_STATUS_CHANGED,
        Self::RUN_FAILED,
        Self::RUN_BUDGET_EXCEEDED,
        Self::STEP_COMPLETED,
        Self::STEP_FAILED,
        Self::APPROVAL_REQUESTED,
        Self::APPROVAL_GRANTED,
        Self::APPROVAL_REJECTED,
        Self::APPROVAL_ESCALATED,
        Self::LOG_LINE,
        Self::USER_SIGNED_IN,
        Self::USER_SIGNED_UP,
        Self::USER_SIGNED_OUT,
        Self::RETRY_FORCED,
    ];

    /// Returns the event type as a static string (e.g. `"run_status_changed"`).
    ///
    /// Useful for filtering and logging without deserializing.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::{Event, UserSignedInEvent};
    /// use uuid::Uuid;
    /// use chrono::Utc;
    ///
    /// let event = Event::UserSignedIn(UserSignedInEvent {
    ///     user_id: Uuid::now_v7(),
    ///     username: "alice".to_string(),
    ///     at: Utc::now(),
    /// });
    /// assert_eq!(event.event_type(), "user_signed_in");
    /// ```
    #[deny(unreachable_patterns)]
    pub fn event_type(&self) -> &'static str {
        match self {
            Event::RunCreated(_) => Self::RUN_CREATED,
            Event::RunStatusChanged(_) => Self::RUN_STATUS_CHANGED,
            Event::RunFailed(_) => Self::RUN_FAILED,
            Event::RunBudgetExceeded(_) => Self::RUN_BUDGET_EXCEEDED,
            Event::RetryForced(_) => Self::RETRY_FORCED,
            Event::StepCompleted(_) => Self::STEP_COMPLETED,
            Event::StepFailed(_) => Self::STEP_FAILED,
            Event::ApprovalRequested(_) => Self::APPROVAL_REQUESTED,
            Event::ApprovalGranted(_) => Self::APPROVAL_GRANTED,
            Event::ApprovalRejected(_) => Self::APPROVAL_REJECTED,
            Event::ApprovalEscalated(_) => Self::APPROVAL_ESCALATED,
            Event::LogLine(_) => Self::LOG_LINE,
            Event::UserSignedIn(_) => Self::USER_SIGNED_IN,
            Event::UserSignedUp(_) => Self::USER_SIGNED_UP,
            Event::UserSignedOut(_) => Self::USER_SIGNED_OUT,
        }
    }

    /// Returns the run this event belongs to, if any.
    ///
    /// Auth events ([`UserSignedIn`](Event::UserSignedIn),
    /// [`UserSignedUp`](Event::UserSignedUp),
    /// [`UserSignedOut`](Event::UserSignedOut)) are not tied to a run and
    /// return `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::{Event, RunCreatedEvent};
    /// use uuid::Uuid;
    /// use chrono::Utc;
    ///
    /// let run_id = Uuid::now_v7();
    /// let event = Event::RunCreated(RunCreatedEvent {
    ///     run_id,
    ///     workflow_name: "deploy".to_string(),
    ///     at: Utc::now(),
    /// });
    /// assert_eq!(event.run_id(), Some(run_id));
    /// ```
    #[deny(unreachable_patterns)]
    pub fn run_id(&self) -> Option<Uuid> {
        match self {
            Event::RunCreated(e) => Some(e.run_id),
            Event::RunStatusChanged(e) => Some(e.run_id),
            Event::RunFailed(e) => Some(e.run_id),
            Event::RunBudgetExceeded(e) => Some(e.run_id),
            Event::RetryForced(e) => Some(e.run_id),
            Event::StepCompleted(e) => Some(e.run_id),
            Event::StepFailed(e) => Some(e.run_id),
            Event::ApprovalRequested(e) => Some(e.run_id),
            Event::ApprovalGranted(e) => Some(e.run_id),
            Event::ApprovalRejected(e) => Some(e.run_id),
            Event::ApprovalEscalated(e) => Some(e.run_id),
            Event::LogLine(e) => Some(e.run_id),
            Event::UserSignedIn(_) | Event::UserSignedUp(_) | Event::UserSignedOut(_) => None,
        }
    }

    /// Returns the step this event belongs to, if any.
    ///
    /// Only [`StepCompleted`](Event::StepCompleted),
    /// [`StepFailed`](Event::StepFailed),
    /// [`ApprovalRequested`](Event::ApprovalRequested) and
    /// [`ApprovalEscalated`](Event::ApprovalEscalated) always carry a step
    /// identifier; [`ApprovalGranted`](Event::ApprovalGranted) and
    /// [`ApprovalRejected`](Event::ApprovalRejected) carry one when it was
    /// recorded; every other variant returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::{Event, StepFailedEvent};
    /// use ironflow_store::models::StepKind;
    /// use uuid::Uuid;
    /// use chrono::Utc;
    ///
    /// let step_id = Uuid::now_v7();
    /// let event = Event::StepFailed(StepFailedEvent {
    ///     run_id: Uuid::now_v7(),
    ///     step_id,
    ///     step_name: "build".to_string(),
    ///     kind: StepKind::Shell,
    ///     error: "exit code 1".to_string(),
    ///     at: Utc::now(),
    /// });
    /// assert_eq!(event.step_id(), Some(step_id));
    /// ```
    #[deny(unreachable_patterns)]
    pub fn step_id(&self) -> Option<Uuid> {
        match self {
            Event::StepCompleted(e) => Some(e.step_id),
            Event::StepFailed(e) => Some(e.step_id),
            Event::ApprovalRequested(e) => Some(e.step_id),
            Event::ApprovalEscalated(e) => Some(e.step_id),
            Event::ApprovalGranted(e) => e.step_id,
            Event::ApprovalRejected(e) => e.step_id,
            Event::RunCreated(_)
            | Event::RunStatusChanged(_)
            | Event::RunFailed(_)
            | Event::RunBudgetExceeded(_)
            | Event::RetryForced(_)
            | Event::LogLine(_)
            | Event::UserSignedIn(_)
            | Event::UserSignedUp(_)
            | Event::UserSignedOut(_) => None,
        }
    }

    /// Returns the user this event belongs to, if any.
    ///
    /// Only the auth events ([`UserSignedIn`](Event::UserSignedIn),
    /// [`UserSignedUp`](Event::UserSignedUp),
    /// [`UserSignedOut`](Event::UserSignedOut)) carry a user identifier;
    /// every other variant returns `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::notify::{Event, UserSignedInEvent};
    /// use uuid::Uuid;
    /// use chrono::Utc;
    ///
    /// let user_id = Uuid::now_v7();
    /// let event = Event::UserSignedIn(UserSignedInEvent {
    ///     user_id,
    ///     username: "alice".to_string(),
    ///     at: Utc::now(),
    /// });
    /// assert_eq!(event.user_id(), Some(user_id));
    /// ```
    #[deny(unreachable_patterns)]
    pub fn user_id(&self) -> Option<Uuid> {
        match self {
            Event::UserSignedIn(e) => Some(e.user_id),
            Event::UserSignedUp(e) => Some(e.user_id),
            Event::UserSignedOut(e) => Some(e.user_id),
            Event::RunCreated(_)
            | Event::RunStatusChanged(_)
            | Event::RunFailed(_)
            | Event::RunBudgetExceeded(_)
            | Event::RetryForced(_)
            | Event::StepCompleted(_)
            | Event::StepFailed(_)
            | Event::ApprovalRequested(_)
            | Event::ApprovalGranted(_)
            | Event::ApprovalRejected(_)
            | Event::ApprovalEscalated(_)
            | Event::LogLine(_) => None,
        }
    }
}

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

    #[test]
    fn run_status_changed_serde_roundtrip() {
        let event = Event::RunStatusChanged(RunStatusChangedEvent {
            run_id: Uuid::now_v7(),
            workflow_name: "deploy".to_string(),
            from: RunStatus::Running,
            to: RunStatus::Completed,
            error: None,
            cost_usd: Decimal::new(42, 2),
            duration_ms: 5000,
            labels: HashMap::new(),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(back.event_type(), "run_status_changed");
        assert!(json.contains("\"type\":\"run_status_changed\""));
    }

    #[test]
    fn run_failed_serde_roundtrip() {
        let event = Event::RunFailed(RunFailedEvent {
            run_id: Uuid::now_v7(),
            workflow_name: "deploy".to_string(),
            error: Some("step crashed".to_string()),
            cost_usd: Decimal::new(10, 2),
            duration_ms: 3000,
            labels: HashMap::new(),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(back.event_type(), "run_failed");
        assert!(json.contains("\"type\":\"run_failed\""));
        assert!(json.contains("step crashed"));
    }

    #[test]
    fn run_budget_exceeded_serde_roundtrip() {
        let event = Event::RunBudgetExceeded(RunBudgetExceededEvent {
            run_id: Uuid::now_v7(),
            workflow_name: "deploy".to_string(),
            limit_usd: Decimal::new(200, 2),
            spent_usd: Decimal::new(180, 2),
            step_budget_usd: Decimal::new(50, 2),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(back.event_type(), "run_budget_exceeded");
        assert!(json.contains("\"type\":\"run_budget_exceeded\""));
        assert!(json.contains("limit_usd"));
        assert!(json.contains("step_budget_usd"));
    }

    #[test]
    fn all_contains_run_budget_exceeded() {
        assert!(Event::ALL.contains(&Event::RUN_BUDGET_EXCEEDED));
    }

    #[test]
    fn user_signed_in_serde_roundtrip() {
        let event = Event::UserSignedIn(UserSignedInEvent {
            user_id: Uuid::now_v7(),
            username: "alice".to_string(),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(back.event_type(), "user_signed_in");
        assert!(json.contains("alice"));
    }

    #[test]
    fn step_failed_serde_roundtrip() {
        let event = Event::StepFailed(StepFailedEvent {
            run_id: Uuid::now_v7(),
            step_id: Uuid::now_v7(),
            step_name: "build".to_string(),
            kind: StepKind::Shell,
            error: "exit code 1".to_string(),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(back.event_type(), "step_failed");
    }

    #[test]
    fn legacy_approval_granted_defaults_to_a_single_vote() {
        let raw = r#"{"type":"approval_granted","run_id":"01890000-0000-7000-8000-000000000000","approved_by":"alice","at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("deserialize");
        let Event::ApprovalGranted(event) = event else {
            panic!("expected approval_granted");
        };

        assert_eq!(event.step_id, None);
        assert_eq!(event.approvals_received, 1);
        assert_eq!(event.approvals_required, 1);
        assert!(event.requirement.is_none());
    }

    #[test]
    fn legacy_approval_requested_and_rejected_have_no_requirement() {
        let raw = r#"{"type":"approval_requested","run_id":"01890000-0000-7000-8000-000000000000","step_id":"01890000-0000-7000-8000-000000000001","message":"ok?","at":"2026-01-01T00:00:00Z"}"#;
        let requested: Event = serde_json::from_str(raw).expect("deserialize");
        let Event::ApprovalRequested(requested) = requested else {
            panic!("expected approval_requested");
        };
        assert!(requested.requirement.is_none());

        let raw = r#"{"type":"approval_rejected","run_id":"01890000-0000-7000-8000-000000000000","rejected_by":"bob","at":"2026-01-01T00:00:00Z"}"#;
        let rejected: Event = serde_json::from_str(raw).expect("deserialize");
        let Event::ApprovalRejected(rejected) = rejected else {
            panic!("expected approval_rejected");
        };
        assert_eq!(rejected.step_id, None);
        assert!(rejected.requirement.is_none());
    }

    #[test]
    fn approval_granted_roundtrips_the_vote_counts() {
        let requirement = ApprovalRequirement {
            reason: Some("amount > 10k".to_string()),
            required_approvers: 2,
            approver_groups: vec!["finance".to_string()],
        };
        let event = Event::ApprovalGranted(ApprovalGrantedEvent {
            run_id: Uuid::now_v7(),
            step_id: Some(Uuid::now_v7()),
            approved_by: "alice".to_string(),
            approvals_received: 1,
            approvals_required: 2,
            requirement: Some(requirement.clone()),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");
        let Event::ApprovalGranted(back) = back else {
            panic!("expected approval_granted");
        };
        assert_eq!(back.approvals_received, 1);
        assert_eq!(back.approvals_required, 2);
        assert_eq!(back.requirement, Some(requirement));
    }

    #[test]
    fn approval_requested_serde_roundtrip() {
        let event = Event::ApprovalRequested(ApprovalRequestedEvent {
            run_id: Uuid::now_v7(),
            step_id: Uuid::now_v7(),
            message: "Deploy to prod?".to_string(),
            requirement: None,
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        assert!(json.contains("approval_requested"));
    }

    #[test]
    fn log_line_serde_roundtrip() {
        let event = Event::LogLine(LogLineEvent {
            id: Uuid::now_v7(),
            run_id: Uuid::now_v7(),
            step_id: Uuid::now_v7(),
            step_name: "build".to_string(),
            stream: LogStream::Stdout,
            line: "Compiling ironflow v0.1.0".to_string(),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        let back: Event = serde_json::from_str(&json).expect("deserialize");

        assert_eq!(back.event_type(), "log_line");
        assert!(json.contains("\"type\":\"log_line\""));
        assert!(json.contains("Compiling ironflow"));
    }

    /// The pre-refactor wire format used flat inline-struct variants. Newtype
    /// variants over named-field payloads produce and accept the exact same
    /// JSON, so audit rows and in-flight payloads written before the refactor
    /// still deserialize. No data migration is required.
    #[test]
    fn legacy_flat_json_deserializes_into_typed_payload() {
        let run_id: Uuid = "01890000-0000-7000-8000-000000000000"
            .parse()
            .expect("valid uuid");

        let raw = r#"{"type":"run_created","run_id":"01890000-0000-7000-8000-000000000000","workflow_name":"deploy","at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("legacy payload must deserialize");
        match event {
            Event::RunCreated(e) => {
                assert_eq!(e.run_id, run_id);
                assert_eq!(e.workflow_name, "deploy");
            }
            other => panic!("expected RunCreated, got {other:?}"),
        }

        let raw = r#"{"type":"run_status_changed","run_id":"01890000-0000-7000-8000-000000000000","workflow_name":"deploy","from":"running","to":"completed","error":null,"cost_usd":0.5,"duration_ms":5000,"labels":{"env":"prod"},"at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("legacy payload must deserialize");
        match event {
            Event::RunStatusChanged(e) => {
                assert_eq!(e.from, RunStatus::Running);
                assert_eq!(e.to, RunStatus::Completed);
                assert_eq!(e.cost_usd, Decimal::new(5, 1));
                assert_eq!(e.duration_ms, 5000);
                assert_eq!(e.labels.get("env").map(String::as_str), Some("prod"));
            }
            other => panic!("expected RunStatusChanged, got {other:?}"),
        }

        // `labels` predates no payload: omitting it must still work via `#[serde(default)]`.
        let raw = r#"{"type":"run_status_changed","run_id":"01890000-0000-7000-8000-000000000000","workflow_name":"deploy","from":"running","to":"failed","error":"boom","cost_usd":0,"duration_ms":0,"at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("missing labels must default");
        match event {
            Event::RunStatusChanged(e) => {
                assert!(e.labels.is_empty());
                assert_eq!(e.error.as_deref(), Some("boom"));
            }
            other => panic!("expected RunStatusChanged, got {other:?}"),
        }

        let raw = r#"{"type":"run_failed","run_id":"01890000-0000-7000-8000-000000000000","workflow_name":"deploy","error":"boom","cost_usd":0.25,"duration_ms":3000,"at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("legacy payload must deserialize");
        match event {
            Event::RunFailed(e) => {
                assert_eq!(e.error.as_deref(), Some("boom"));
                assert!(e.labels.is_empty());
            }
            other => panic!("expected RunFailed, got {other:?}"),
        }

        let raw = r#"{"type":"step_failed","run_id":"01890000-0000-7000-8000-000000000000","step_id":"01890000-0000-7000-8000-000000000001","step_name":"build","kind":"shell","error":"exit code 1","at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("legacy payload must deserialize");
        match event {
            Event::StepFailed(e) => {
                assert_eq!(e.kind, StepKind::Shell);
                assert_eq!(e.error, "exit code 1");
            }
            other => panic!("expected StepFailed, got {other:?}"),
        }

        let raw = r#"{"type":"log_line","run_id":"01890000-0000-7000-8000-000000000000","step_id":"01890000-0000-7000-8000-000000000001","step_name":"build","stream":"stdout","line":"hello","at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("legacy payload must deserialize");
        match event {
            Event::LogLine(e) => {
                assert_eq!(e.stream, LogStream::Stdout);
                assert_eq!(e.line, "hello");
                // A payload predating the `id` field degrades to the nil UUID
                // rather than failing to deserialize.
                assert_eq!(e.id, Uuid::nil());
            }
            other => panic!("expected LogLine, got {other:?}"),
        }

        let raw = r#"{"type":"user_signed_in","user_id":"01890000-0000-7000-8000-000000000000","username":"alice","at":"2026-01-01T00:00:00Z"}"#;
        let event: Event = serde_json::from_str(raw).expect("legacy payload must deserialize");
        match event {
            Event::UserSignedIn(e) => assert_eq!(e.username, "alice"),
            other => panic!("expected UserSignedIn, got {other:?}"),
        }
    }

    /// Guards the internally-tagged representation: payload fields must stay
    /// siblings of `type`, never nested under a variant key.
    #[test]
    fn serialized_event_is_flat_with_type_tag() {
        let run_id = Uuid::now_v7();
        let event = Event::RunCreated(RunCreatedEvent {
            run_id,
            workflow_name: "deploy".to_string(),
            at: Utc::now(),
        });

        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("run_created")
        );
        assert_eq!(
            object.get("workflow_name").and_then(|v| v.as_str()),
            Some("deploy")
        );
        assert_eq!(
            object.get("run_id").and_then(|v| v.as_str()),
            Some(run_id.to_string().as_str())
        );
        assert!(object.contains_key("at"));
        assert_eq!(object.len(), 4, "no nesting: {object:?}");
        assert!(!object.contains_key("RunCreated"));
    }

    #[test]
    fn run_id_returns_some_for_run_events() {
        let run_id = Uuid::now_v7();
        let now = Utc::now();

        let events = vec![
            Event::RunCreated(RunCreatedEvent {
                run_id,
                workflow_name: "w".to_string(),
                at: now,
            }),
            Event::RunStatusChanged(RunStatusChangedEvent {
                run_id,
                workflow_name: "w".to_string(),
                from: RunStatus::Pending,
                to: RunStatus::Running,
                error: None,
                cost_usd: Decimal::ZERO,
                duration_ms: 0,
                labels: HashMap::new(),
                at: now,
            }),
            Event::RunFailed(RunFailedEvent {
                run_id,
                workflow_name: "w".to_string(),
                error: None,
                cost_usd: Decimal::ZERO,
                duration_ms: 0,
                labels: HashMap::new(),
                at: now,
            }),
            Event::RunBudgetExceeded(RunBudgetExceededEvent {
                run_id,
                workflow_name: "w".to_string(),
                limit_usd: Decimal::ZERO,
                spent_usd: Decimal::ZERO,
                step_budget_usd: Decimal::ZERO,
                at: now,
            }),
            Event::RetryForced(RetryForcedEvent {
                run_id,
                workflow_name: "w".to_string(),
                original_version: "1".to_string(),
                current_version: "2".to_string(),
                at: now,
            }),
            Event::StepCompleted(StepCompletedEvent {
                run_id,
                step_id: Uuid::now_v7(),
                step_name: "s".to_string(),
                kind: StepKind::Shell,
                duration_ms: 0,
                cost_usd: Decimal::ZERO,
                at: now,
            }),
            Event::StepFailed(StepFailedEvent {
                run_id,
                step_id: Uuid::now_v7(),
                step_name: "s".to_string(),
                kind: StepKind::Shell,
                error: "e".to_string(),
                at: now,
            }),
            Event::ApprovalRequested(ApprovalRequestedEvent {
                run_id,
                step_id: Uuid::now_v7(),
                message: "ok?".to_string(),
                requirement: None,
                at: now,
            }),
            Event::ApprovalGranted(ApprovalGrantedEvent {
                run_id,
                step_id: None,
                approved_by: "alice".to_string(),
                approvals_received: 1,
                approvals_required: 1,
                requirement: None,
                at: now,
            }),
            Event::ApprovalRejected(ApprovalRejectedEvent {
                run_id,
                step_id: None,
                rejected_by: "bob".to_string(),
                requirement: None,
                at: now,
            }),
            Event::LogLine(LogLineEvent {
                id: Uuid::now_v7(),
                run_id,
                step_id: Uuid::now_v7(),
                step_name: "s".to_string(),
                stream: LogStream::Stdout,
                line: "l".to_string(),
                at: now,
            }),
        ];

        for event in &events {
            assert_eq!(
                event.run_id(),
                Some(run_id),
                "{} should carry a run_id",
                event.event_type()
            );
        }
    }

    #[test]
    fn run_id_returns_none_for_auth_events() {
        let user_id = Uuid::now_v7();
        let now = Utc::now();

        let events = vec![
            Event::UserSignedIn(UserSignedInEvent {
                user_id,
                username: "alice".to_string(),
                at: now,
            }),
            Event::UserSignedUp(UserSignedUpEvent {
                user_id,
                username: "alice".to_string(),
                at: now,
            }),
            Event::UserSignedOut(UserSignedOutEvent { user_id, at: now }),
        ];

        for event in &events {
            assert_eq!(event.run_id(), None, "{} has no run", event.event_type());
        }
    }

    #[test]
    fn step_id_returns_some_only_for_step_events() {
        let step_id = Uuid::now_v7();
        let run_id = Uuid::now_v7();
        let now = Utc::now();

        let with_step = vec![
            Event::StepCompleted(StepCompletedEvent {
                run_id,
                step_id,
                step_name: "s".to_string(),
                kind: StepKind::Shell,
                duration_ms: 0,
                cost_usd: Decimal::ZERO,
                at: now,
            }),
            Event::StepFailed(StepFailedEvent {
                run_id,
                step_id,
                step_name: "s".to_string(),
                kind: StepKind::Shell,
                error: "e".to_string(),
                at: now,
            }),
            Event::ApprovalRequested(ApprovalRequestedEvent {
                run_id,
                step_id,
                message: "ok?".to_string(),
                requirement: None,
                at: now,
            }),
            Event::ApprovalGranted(ApprovalGrantedEvent {
                run_id,
                step_id: Some(step_id),
                approved_by: "alice".to_string(),
                approvals_received: 1,
                approvals_required: 2,
                requirement: None,
                at: now,
            }),
            Event::ApprovalRejected(ApprovalRejectedEvent {
                run_id,
                step_id: Some(step_id),
                rejected_by: "bob".to_string(),
                requirement: None,
                at: now,
            }),
        ];

        for event in &with_step {
            assert_eq!(
                event.step_id(),
                Some(step_id),
                "{} should carry a step_id",
                event.event_type()
            );
        }

        let without_step = vec![
            Event::RunCreated(RunCreatedEvent {
                run_id,
                workflow_name: "w".to_string(),
                at: now,
            }),
            // A granted event recorded before step ids were carried.
            Event::ApprovalGranted(ApprovalGrantedEvent {
                run_id,
                step_id: None,
                approved_by: "alice".to_string(),
                approvals_received: 1,
                approvals_required: 1,
                requirement: None,
                at: now,
            }),
            // LogLine carries a step_id field but is reported as a run-level
            // stream event, matching the pre-refactor behaviour.
            Event::LogLine(LogLineEvent {
                id: Uuid::now_v7(),
                run_id,
                step_id,
                step_name: "s".to_string(),
                stream: LogStream::Stdout,
                line: "l".to_string(),
                at: now,
            }),
            Event::UserSignedOut(UserSignedOutEvent {
                user_id: Uuid::now_v7(),
                at: now,
            }),
        ];

        for event in &without_step {
            assert_eq!(
                event.step_id(),
                None,
                "{} should not carry a step_id",
                event.event_type()
            );
        }
    }

    #[test]
    fn user_id_returns_some_only_for_auth_events() {
        let user_id = Uuid::now_v7();
        let run_id = Uuid::now_v7();
        let now = Utc::now();

        let auth = vec![
            Event::UserSignedIn(UserSignedInEvent {
                user_id,
                username: "alice".to_string(),
                at: now,
            }),
            Event::UserSignedUp(UserSignedUpEvent {
                user_id,
                username: "alice".to_string(),
                at: now,
            }),
            Event::UserSignedOut(UserSignedOutEvent { user_id, at: now }),
        ];

        for event in &auth {
            assert_eq!(
                event.user_id(),
                Some(user_id),
                "{} should carry a user_id",
                event.event_type()
            );
        }

        let non_auth = vec![
            Event::RunCreated(RunCreatedEvent {
                run_id,
                workflow_name: "w".to_string(),
                at: now,
            }),
            Event::StepFailed(StepFailedEvent {
                run_id,
                step_id: Uuid::now_v7(),
                step_name: "s".to_string(),
                kind: StepKind::Shell,
                error: "e".to_string(),
                at: now,
            }),
        ];

        for event in &non_auth {
            assert_eq!(
                event.user_id(),
                None,
                "{} should not carry a user_id",
                event.event_type()
            );
        }
    }

    #[test]
    fn event_type_all_variants() {
        let id = Uuid::now_v7();
        let now = Utc::now();

        let cases: Vec<(Event, &str)> = vec![
            (
                Event::RunCreated(RunCreatedEvent {
                    run_id: id,
                    workflow_name: "w".to_string(),
                    at: now,
                }),
                "run_created",
            ),
            (
                Event::RunStatusChanged(RunStatusChangedEvent {
                    run_id: id,
                    workflow_name: "w".to_string(),
                    from: RunStatus::Pending,
                    to: RunStatus::Running,
                    error: None,
                    cost_usd: Decimal::ZERO,
                    duration_ms: 0,
                    labels: HashMap::new(),
                    at: now,
                }),
                "run_status_changed",
            ),
            (
                Event::RunFailed(RunFailedEvent {
                    run_id: id,
                    workflow_name: "w".to_string(),
                    error: Some("boom".to_string()),
                    cost_usd: Decimal::ZERO,
                    duration_ms: 0,
                    labels: HashMap::new(),
                    at: now,
                }),
                "run_failed",
            ),
            (
                Event::RunBudgetExceeded(RunBudgetExceededEvent {
                    run_id: id,
                    workflow_name: "w".to_string(),
                    limit_usd: Decimal::new(200, 2),
                    spent_usd: Decimal::new(180, 2),
                    step_budget_usd: Decimal::new(50, 2),
                    at: now,
                }),
                "run_budget_exceeded",
            ),
            (
                Event::RetryForced(RetryForcedEvent {
                    run_id: id,
                    workflow_name: "w".to_string(),
                    original_version: "1".to_string(),
                    current_version: "2".to_string(),
                    at: now,
                }),
                "retry_forced",
            ),
            (
                Event::StepCompleted(StepCompletedEvent {
                    run_id: id,
                    step_id: id,
                    step_name: "s".to_string(),
                    kind: StepKind::Shell,
                    duration_ms: 0,
                    cost_usd: Decimal::ZERO,
                    at: now,
                }),
                "step_completed",
            ),
            (
                Event::StepFailed(StepFailedEvent {
                    run_id: id,
                    step_id: id,
                    step_name: "s".to_string(),
                    kind: StepKind::Shell,
                    error: "err".to_string(),
                    at: now,
                }),
                "step_failed",
            ),
            (
                Event::ApprovalRequested(ApprovalRequestedEvent {
                    run_id: id,
                    step_id: id,
                    message: "ok?".to_string(),
                    requirement: None,
                    at: now,
                }),
                "approval_requested",
            ),
            (
                Event::ApprovalGranted(ApprovalGrantedEvent {
                    run_id: id,
                    step_id: Some(id),
                    approved_by: "alice".to_string(),
                    approvals_received: 1,
                    approvals_required: 1,
                    requirement: None,
                    at: now,
                }),
                "approval_granted",
            ),
            (
                Event::ApprovalRejected(ApprovalRejectedEvent {
                    run_id: id,
                    step_id: Some(id),
                    rejected_by: "bob".to_string(),
                    requirement: None,
                    at: now,
                }),
                "approval_rejected",
            ),
            (
                Event::ApprovalEscalated(ApprovalEscalatedEvent {
                    run_id: id,
                    step_id: id,
                    step_name: "prod-gate".to_string(),
                    stage: 0,
                    policy: "auto_reject".to_string(),
                    action: "rejected".to_string(),
                    reason: "approval deadline of 3600s expired".to_string(),
                    assignee: None,
                    at: now,
                }),
                "approval_escalated",
            ),
            (
                Event::LogLine(LogLineEvent {
                    id,
                    run_id: id,
                    step_id: id,
                    step_name: "build".to_string(),
                    stream: LogStream::Stdout,
                    line: "Compiling ironflow v0.1.0".to_string(),
                    at: now,
                }),
                "log_line",
            ),
            (
                Event::UserSignedIn(UserSignedInEvent {
                    user_id: id,
                    username: "u".to_string(),
                    at: now,
                }),
                "user_signed_in",
            ),
            (
                Event::UserSignedUp(UserSignedUpEvent {
                    user_id: id,
                    username: "u".to_string(),
                    at: now,
                }),
                "user_signed_up",
            ),
            (
                Event::UserSignedOut(UserSignedOutEvent {
                    user_id: id,
                    at: now,
                }),
                "user_signed_out",
            ),
        ];

        assert_eq!(
            cases.len(),
            Event::ALL.len(),
            "every variant must be covered"
        );

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

    #[test]
    fn approval_escalated_serde_roundtrip() {
        let run_id = Uuid::now_v7();
        let step_id = Uuid::now_v7();
        let event = Event::ApprovalEscalated(ApprovalEscalatedEvent {
            run_id,
            step_id,
            step_name: "prod-gate".to_string(),
            stage: 1,
            policy: "escalate".to_string(),
            action: "reassigned to sre-oncall".to_string(),
            reason: "approval deadline of 3600s expired".to_string(),
            assignee: Some(Assignee::group("sre-oncall")),
            at: Utc::now(),
        });

        let json = serde_json::to_string(&event).expect("serialize");
        assert!(
            json.contains("\"type\":\"approval_escalated\""),
            "got {json}"
        );

        let back: Event = serde_json::from_str(&json).expect("deserialize");
        let Event::ApprovalEscalated(payload) = back else {
            panic!("expected an approval_escalated event");
        };
        assert_eq!(payload.run_id, run_id);
        assert_eq!(payload.stage, 1);
        assert_eq!(payload.assignee, Some(Assignee::group("sre-oncall")));
    }

    #[test]
    fn approval_escalated_carries_run_and_step_ids() {
        let run_id = Uuid::now_v7();
        let step_id = Uuid::now_v7();
        let event = Event::ApprovalEscalated(ApprovalEscalatedEvent {
            run_id,
            step_id,
            step_name: "prod-gate".to_string(),
            stage: 0,
            policy: "notify".to_string(),
            action: "notified 1 target".to_string(),
            reason: "approval deadline of 60s expired".to_string(),
            assignee: None,
            at: Utc::now(),
        });

        assert_eq!(event.run_id(), Some(run_id));
        assert_eq!(event.step_id(), Some(step_id));
        assert_eq!(event.user_id(), None);
    }
}