af-workflow 0.4.0

Spec-driven workflow chassis: typed node expressions composed into a branched DAG. Port of agent_core/workflow.
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
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
//! Stable contracts for durable workflow execution.
//!
//! These types describe immutable definitions, accepted source facts and
//! external effects. Products provide capabilities; the workflow kernel owns
//! lifecycle, fencing and persistence semantics.

use af_context::{InstanceId, RunId, SubjectId, TenantId};
use std::collections::{BTreeMap, BTreeSet};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Named workflow whose revisions are immutable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkflowDefinition {
    /// Stable identifier of this record.
    pub id: String,
    /// Display name.
    pub name: String,
}

/// One durable instance pinned to a revision and execution profile for its lifetime.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowInstance {
    /// Stable identifier of this record.
    pub id: String,
    /// Tenant that owns this record.
    pub tenant_id: TenantId,
    /// Subject (user or service principal) acting on or owning this record.
    pub subject_id: SubjectId,
    /// Workflow definition this record belongs to.
    pub definition_id: String,
    /// Monotonic revision number.
    pub revision: u64,
    /// Execution profile the instance pins.
    pub execution_profile_id: String,
    /// Pinned execution profile revision.
    pub execution_profile_revision: u64,
    /// Lifecycle policy applied on database time.
    pub lifecycle: LifecyclePolicy,
    /// Current lifecycle status.
    pub status: String,
    /// CAS version of the authoritative state.
    pub state_version: i64,
    /// Sequence of the last authoritative event.
    pub event_sequence: i64,
    /// Instance control epoch; pause/resume bump it and stale workers fail.
    pub control_epoch: i64,
}

/// Subscription of an instance to a source event type, with a JSON-containment predicate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TriggerBinding {
    /// Stable identifier of this record.
    pub id: String,
    /// Monotonic revision number.
    pub revision: u64,
    /// Source the binding subscribes to.
    pub source: String,
    /// Stable machine-readable event type.
    pub event_type: String,
    /// Workflow instance this record refers to.
    pub instance_id: InstanceId,
    /// JSON object the event payload must contain (`@>`) to create a delivery.
    pub predicate: Value,
    /// How out-of-order source sequences are handled.
    pub ordering: OrderingPolicy,
    /// Earliest time the binding or instance is active.
    pub starts_at: Option<DateTime<Utc>>,
    /// When the record stops being valid.
    pub expires_at: Option<DateTime<Utc>>,
    /// How long a missing source sequence may block before it is reported as a gap.
    #[serde(default = "default_gap_wait_ms")]
    pub gap_wait_ms: u64,
    /// Maximum buffered out-of-order deliveries before the source is blocked.
    #[serde(default = "default_gap_limit")]
    pub gap_limit: u32,
}

impl TriggerBinding {
    /// Reject blank identifiers, out-of-range gap settings and inverted windows.
    pub fn validate(&self) -> Result<(), ContractError> {
        for (name, value) in [
            ("trigger binding id", self.id.as_str()),
            ("trigger source", self.source.as_str()),
            ("trigger event_type", self.event_type.as_str()),
            ("trigger instance_id", self.instance_id.as_str()),
        ] {
            required(name, value)?;
        }
        if self.gap_wait_ms == 0 || self.gap_wait_ms > 3_600_000 {
            return Err(ContractError::Invalid(
                "trigger gap_wait_ms must be between 1 and 3600000".into(),
            ));
        }
        if self.gap_limit == 0 || self.gap_limit > 10_000 {
            return Err(ContractError::Invalid(
                "trigger gap_limit must be between 1 and 10000".into(),
            ));
        }
        if !self.predicate.is_object() {
            return Err(ContractError::Invalid(
                "trigger predicate must be a JSON object".into(),
            ));
        }
        if matches!((self.starts_at, self.expires_at), (Some(start), Some(end)) if end <= start) {
            return Err(ContractError::Invalid(
                "trigger expires_at must be after starts_at".into(),
            ));
        }
        Ok(())
    }
}

const fn default_gap_wait_ms() -> u64 {
    30_000
}

const fn default_gap_limit() -> u32 {
    100
}

/// Authoritative, append-only fact recorded by a committed transition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WorkflowEvent {
    /// Workflow instance this record refers to.
    pub instance_id: InstanceId,
    /// Position in the instance's event log.
    pub sequence: i64,
    /// Stable machine-readable event type.
    pub event_type: String,
    /// Structured payload.
    pub payload: Value,
    /// Content hash that makes the referenced artifact immutable.
    pub content_digest: String,
    /// When the event happened.
    pub occurred_at: DateTime<Utc>,
}

/// Where an execution profile is allowed to act.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionMode {
    /// In-memory dry run; no external effects.
    Simulation,
    /// Historical replay.
    Backtest,
    /// Live data, simulated effects.
    Paper,
    /// Real external effects.
    Live,
}

/// Durability the deployment must provide for an execution profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DurabilityGrade {
    /// Up to five minutes RPO for ordinary work.
    Standard,
    /// Committed intents synchronously preserved before dispatch; required for funds actions.
    FundsGrade,
}

/// Immutable execution profile: mode, durability grade and provider bindings an instance pins.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionProfileRevision {
    /// Stable identifier of this record.
    pub id: String,
    /// Monotonic revision number.
    pub revision: u64,
    /// Content hash that makes the referenced artifact immutable.
    pub content_digest: String,
    /// Execution mode this record was produced under.
    pub mode: ExecutionMode,
    /// Durability the deployment guarantees for this profile.
    pub durability_grade: DurabilityGrade,
    /// Provider that feeds triggers.
    pub trigger_provider: String,
    /// Provider that feeds market or reference data.
    pub data_provider: String,
    /// Clock source; `database` is the only kernel-supported value.
    pub clock_model: String,
    /// Provider that dispatches actions.
    pub action_provider: String,
    /// Model bindings by role.
    #[serde(default)]
    pub models: BTreeMap<String, Value>,
    /// Environment settings the product interprets.
    #[serde(default)]
    pub environment: Value,
    /// Product policy bundle applied to permissions and guards.
    #[serde(default)]
    pub policy_bundle: Value,
    /// Named external connections by role.
    #[serde(default)]
    pub connection_bindings: BTreeMap<String, String>,
}

impl ExecutionProfileRevision {
    /// Reject blank identifiers and provider names.
    pub fn validate(&self) -> Result<(), ContractError> {
        for (name, value) in [
            ("execution profile id", self.id.as_str()),
            (
                "execution profile content_digest",
                self.content_digest.as_str(),
            ),
            ("trigger_provider", self.trigger_provider.as_str()),
            ("data_provider", self.data_provider.as_str()),
            ("clock_model", self.clock_model.as_str()),
            ("action_provider", self.action_provider.as_str()),
        ] {
            required(name, value)?;
        }
        Ok(())
    }
}

/// Exact capability identity: id, contract version and content digest.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct CapabilityPin {
    /// Stable identifier of this record.
    pub id: String,
    /// Contract version of the capability.
    pub contract_version: String,
    /// Content hash that makes the referenced artifact immutable.
    pub content_digest: String,
}

/// Immutable, digest-locked revision of a workflow spec with its pinned capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowRevision {
    /// Workflow definition this record belongs to.
    pub definition_id: String,
    /// Monotonic revision number.
    pub revision: u64,
    /// Content hash that makes the referenced artifact immutable.
    pub content_digest: String,
    /// Kernel ABI the revision was validated against.
    pub kernel_abi_version: String,
    /// Digest over the pinned capabilities.
    pub dependency_set_digest: String,
    /// Versions of generic expressions used by the spec.
    #[serde(default)]
    pub expression_versions: BTreeMap<String, String>,
    /// Capabilities the spec may dispatch.
    #[serde(default)]
    pub capabilities: Vec<CapabilityPin>,
    /// Where the spec came from (template, draft command, author).
    #[serde(default)]
    pub template_provenance: Value,
    /// The validated spec.
    pub spec: crate::Spec,
}

impl WorkflowRevision {
    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        required("definition_id", &self.definition_id)?;
        required("content_digest", &self.content_digest)?;
        required("kernel_abi_version", &self.kernel_abi_version)?;
        required("dependency_set_digest", &self.dependency_set_digest)?;
        self.spec
            .validate_structure()
            .map_err(|error| ContractError::Invalid(error.to_string()))?;
        let unique = self
            .capabilities
            .iter()
            .map(|pin| (&pin.id, &pin.contract_version))
            .collect::<BTreeSet<_>>();
        if unique.len() != self.capabilities.len() {
            return Err(ContractError::Invalid(
                "capability pins must be unique by id and contract version".into(),
            ));
        }
        for pin in &self.capabilities {
            required("capability id", &pin.id)?;
            required("capability contract_version", &pin.contract_version)?;
            required("capability content_digest", &pin.content_digest)?;
        }
        Ok(())
    }
}

/// Role a capability plays in a graph.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CapabilityKind {
    /// Produces events.
    Trigger,
    /// Pure or read-only transform.
    Expression,
    /// Authorization, freshness, reservation or policy check dominating an action.
    Guard,
    /// External effect dispatched through an intent.
    Action,
    /// Terminal consumer.
    Sink,
}

/// Side-effect class of a capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Effect {
    /// No I/O.
    Pure,
    /// Reads external state.
    Read,
    /// Writes kernel-owned state only.
    InternalWrite,
    /// Writes external state; requires authorization dominance.
    ExternalWrite,
    /// Moves value; requires authorization, freshness, reservation and funds-grade durability.
    Funds,
}

/// Whether repeating a dispatch is safe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IdempotencyMode {
    /// Not idempotent; never retried automatically.
    None,
    /// The provider deduplicates by idempotency key; safe to retry.
    Native,
    /// Must reconcile the previous attempt before dispatching again.
    ReconcileBeforeRetry,
    /// Retry only through an explicit operator action.
    NeverAutomaticRetry,
}

/// Deployment state of a capability provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CapabilityLifecycle {
    /// Registered but not yet serving.
    Installed,
    /// Serving new and existing work.
    Active,
    /// Serving pinned work only; new pins rejected.
    Deprecated,
    /// Not serving; pinned work waits.
    Disabled,
    /// Temporarily unreachable.
    Unavailable,
    /// Blocks every action immediately.
    EmergencyRevoked,
}

/// Automatic retry policy of a capability.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RetryPolicy {
    /// Total dispatch attempts allowed.
    pub max_attempts: u32,
    /// Per-attempt deadline.
    pub timeout_ms: u64,
    /// Backoff after the first failure.
    pub initial_backoff_ms: u64,
    /// Cap on exponential backoff.
    pub max_backoff_ms: u64,
}

impl RetryPolicy {
    /// Exponential backoff for the 1-based `attempt`, capped at `max_backoff_ms`
    /// with up to 25% deterministic jitter derived from `jitter_seed`.
    pub fn backoff_ms(&self, attempt: u32, jitter_seed: u64) -> u64 {
        let factor = 1_u64
            .checked_shl(attempt.saturating_sub(1).min(20))
            .unwrap_or(u64::MAX);
        let base = self
            .initial_backoff_ms
            .saturating_mul(factor)
            .min(self.max_backoff_ms);
        let jitter_ceiling = (base / 4).max(1);
        base.saturating_add(jitter_seed % jitter_ceiling)
            .min(self.max_backoff_ms)
    }
}

/// Immutable contract of a trigger, expression, guard, action or sink.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CapabilityManifest {
    /// Stable identifier of this record.
    pub id: String,
    /// Contract version of the capability.
    pub contract_version: String,
    /// Content hash that makes the referenced artifact immutable.
    pub content_digest: String,
    /// Discriminator naming the variant of this record.
    pub kind: CapabilityKind,
    /// JSON Schema for provider input.
    pub input_schema: Value,
    /// JSON Schema for provider output.
    pub output_schema: Value,
    /// Side-effect class of the action.
    pub effect: Effect,
    /// Whether equal inputs always produce equal outputs.
    pub deterministic: bool,
    /// Retry safety class.
    pub idempotency_mode: IdempotencyMode,
    /// Retry policy.
    pub retry: RetryPolicy,
    /// Permissions granted or required.
    #[serde(default)]
    pub permissions: BTreeSet<String>,
    /// Guards that must dominate the action.
    #[serde(default)]
    pub required_guards: BTreeSet<GuardKind>,
    /// Which inputs may be LLM-tainted.
    #[serde(default)]
    pub taint_rules: Value,
    /// Declared cost for budgeting.
    #[serde(default)]
    pub resource_cost: Value,
    /// Usable in simulation.
    pub supports_simulation: bool,
    /// Usable in backtest replay.
    pub supports_replay: bool,
    /// Usable in paper mode.
    pub supports_paper: bool,
    /// Usable live.
    pub supports_live: bool,
    /// Clock guarantees the provider needs.
    #[serde(default)]
    pub clock_requirements: Value,
    /// Data freshness the provider needs.
    #[serde(default)]
    pub data_requirements: Value,
    /// Whether the provider can observe a dispatched action's outcome.
    pub supports_reconciliation: bool,
    /// Deployment state.
    pub lifecycle: CapabilityLifecycle,
}

impl CapabilityManifest {
    /// Manifest for an action capability with conservative defaults (one attempt, 30 s timeout).
    pub fn action(
        id: impl Into<String>,
        contract_version: impl Into<String>,
        content_digest: impl Into<String>,
        effect: Effect,
        idempotency_mode: IdempotencyMode,
        supports_reconciliation: bool,
    ) -> Self {
        let required_guards = match effect {
            Effect::Funds => BTreeSet::from([
                GuardKind::Authorization,
                GuardKind::Freshness,
                GuardKind::Reservation,
            ]),
            Effect::ExternalWrite => BTreeSet::from([GuardKind::Authorization]),
            _ => BTreeSet::new(),
        };
        Self {
            id: id.into(),
            contract_version: contract_version.into(),
            content_digest: content_digest.into(),
            kind: CapabilityKind::Action,
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: serde_json::json!({"type": "object"}),
            effect,
            deterministic: false,
            idempotency_mode,
            retry: RetryPolicy {
                max_attempts: 1,
                timeout_ms: 30_000,
                initial_backoff_ms: 100,
                max_backoff_ms: 5_000,
            },
            permissions: BTreeSet::new(),
            required_guards,
            taint_rules: Value::Null,
            resource_cost: Value::Null,
            supports_simulation: true,
            supports_replay: false,
            supports_paper: true,
            supports_live: true,
            clock_requirements: Value::Null,
            data_requirements: Value::Null,
            supports_reconciliation,
            lifecycle: CapabilityLifecycle::Active,
        }
    }

    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        required("capability id", &self.id)?;
        required("contract_version", &self.contract_version)?;
        required("content_digest", &self.content_digest)?;
        if self.retry.max_attempts == 0
            || self.retry.timeout_ms == 0
            || self.retry.initial_backoff_ms == 0
            || self.retry.max_backoff_ms < self.retry.initial_backoff_ms
        {
            return Err(ContractError::Invalid(
                "retry attempts, timeout and backoff bounds are invalid".into(),
            ));
        }
        if self.effect == Effect::Funds {
            if self.kind != CapabilityKind::Action {
                return Err(ContractError::Invalid(
                    "funds effect is only valid for action capabilities".into(),
                ));
            }
            if !self.supports_reconciliation && self.idempotency_mode != IdempotencyMode::Native {
                return Err(ContractError::Invalid(
                    "funds actions require native idempotency or reconciliation".into(),
                ));
            }
            for guard in [
                GuardKind::Authorization,
                GuardKind::Freshness,
                GuardKind::Reservation,
            ] {
                if !self.required_guards.contains(&guard) {
                    return Err(ContractError::Invalid(format!(
                        "funds action must require {guard:?} guard"
                    )));
                }
            }
        }
        Ok(())
    }

    /// Whether new intents may pin this provider (`installed` or `active`).
    pub fn can_start_new_work(&self) -> bool {
        matches!(
            self.lifecycle,
            CapabilityLifecycle::Installed
                | CapabilityLifecycle::Active
                | CapabilityLifecycle::Deprecated
        )
    }
}

/// Role a guard plays on an action's dominating path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GuardKind {
    /// Caller may perform the effect.
    Authorization,
    /// Inputs are recent enough.
    Freshness,
    /// Resources are reserved and fenced.
    Reservation,
    /// Product policy allows it.
    Policy,
}

/// How a binding treats source sequence order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OrderingPolicy {
    /// Reject a gap; the next accepted sequence must be previous + 1.
    StrictSequence,
    /// Order does not matter.
    Commutative,
    /// Only the latest event matters.
    LatestStateReconcile,
    /// Reject anything older than the last accepted sequence.
    RejectUnordered,
}

/// Immutable source event as delivered by a trigger adapter.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TriggerEnvelope {
    /// Source-unique event id.
    pub event_id: String,
    /// Stable machine-readable event type.
    pub event_type: String,
    /// Trigger adapter that delivered the event.
    pub source: String,
    /// Projection schema version.
    pub schema_version: String,
    /// Tenant that owns this record.
    pub tenant_id: TenantId,
    /// Subject (user or service principal) acting on or owning this record.
    pub subject_id: SubjectId,
    /// Aggregate the event belongs to (for ordering).
    pub aggregate_id: String,
    /// Per-aggregate sequence from the source.
    pub source_sequence: Option<i64>,
    /// Version of the observed object, if any.
    pub observed_version: Option<String>,
    /// When the event happened.
    pub occurred_at: DateTime<Utc>,
    /// When the receipt arrived.
    pub received_at: DateTime<Utc>,
    /// Source watermark up to which events are complete.
    pub watermark: Option<DateTime<Utc>>,
    /// Key that correlates related events.
    pub correlation_key: String,
    /// Key that deduplicates redeliveries.
    pub dedup_key: String,
    /// Source cursor after this event.
    pub cursor: Option<String>,
    /// Structured payload.
    pub payload: Value,
    /// Distributed tracing context.
    #[serde(default)]
    pub trace_context: Value,
}

impl TriggerEnvelope {
    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        for (name, value) in [
            ("event_id", self.event_id.as_str()),
            ("event_type", self.event_type.as_str()),
            ("source", self.source.as_str()),
            ("schema_version", self.schema_version.as_str()),
            ("tenant_id", self.tenant_id.as_str()),
            ("aggregate_id", self.aggregate_id.as_str()),
            ("correlation_key", self.correlation_key.as_str()),
            ("dedup_key", self.dedup_key.as_str()),
        ] {
            required(name, value)?;
        }
        if self.occurred_at > self.received_at + chrono::Duration::minutes(5) {
            return Err(ContractError::Invalid(
                "occurred_at is implausibly ahead of received_at".into(),
            ));
        }
        Ok(())
    }
}

/// When an instance completes on its own.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompletionPolicy {
    /// Only an operator stops it.
    ExplicitStop,
    /// After the first consumed trigger or timer.
    FirstTrigger,
    /// After the first evaluation that matched.
    FirstMatch,
    /// After the first action reaches a terminal state.
    FirstActionTerminal,
    /// After the first successful evaluation.
    FirstSuccess,
    /// After this many matched evaluations.
    AfterMatchedEvaluations(u64),
    /// After this many successful evaluations.
    AfterSuccessfulRuns(u64),
}

/// What happens when a lifecycle deadline passes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExpiryPolicy {
    /// Stop new work; let dispatched actions finish.
    Drain,
    /// Stop and request cancellation.
    Cancel,
}

/// How a schedule fires.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ScheduleCadence {
    /// Cron expression evaluated in the schedule's timezone.
    Cron {
        /// Six- or seven-field cron expression.
        expression: String,
    },
    /// Fixed period measured from the scheduled time.
    FixedRate {
        /// Period in milliseconds.
        milliseconds: u64,
    },
    /// Fixed delay measured from the previous completion.
    FixedDelay {
        /// Delay in milliseconds.
        milliseconds: u64,
    },
}

/// How missed schedule windows are handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CatchUpPolicy {
    /// Run only the most recent due occurrence.
    Skip,
    /// Run once, listing the missed windows it covers.
    CatchUpOnce,
    /// Run every missed occurrence oldest first, at most `limit` per transition.
    CatchUpAll {
        /// Maximum occurrences per transition.
        limit: u32,
    },
}

/// Cadence, timezone and catch-up behavior of a schedule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchedulePolicy {
    /// Cron, fixed-rate or fixed-delay.
    pub cadence: ScheduleCadence,
    /// IANA timezone for cron evaluation and DST.
    pub timezone: String,
    /// Missed-window behavior.
    pub catch_up: CatchUpPolicy,
}

impl SchedulePolicy {
    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        self.timezone.parse::<chrono_tz::Tz>().map_err(|_| {
            ContractError::Invalid(format!("unknown IANA timezone '{}'", self.timezone))
        })?;
        match &self.cadence {
            ScheduleCadence::Cron { expression } => {
                expression.parse::<cron::Schedule>().map_err(|error| {
                    ContractError::Invalid(format!("invalid cron '{expression}': {error}"))
                })?;
            }
            ScheduleCadence::FixedRate { milliseconds }
            | ScheduleCadence::FixedDelay { milliseconds }
                if *milliseconds == 0 =>
            {
                return Err(ContractError::Invalid(
                    "schedule interval must be positive".into(),
                ));
            }
            _ => {}
        }
        if matches!(self.catch_up, CatchUpPolicy::CatchUpAll { limit: 0 }) {
            return Err(ContractError::Invalid(
                "catch_up_all limit must be positive".into(),
            ));
        }
        Ok(())
    }
}

/// Start, completion, timeout and expiry rules evaluated on database time.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LifecyclePolicy {
    /// Earliest time the binding or instance is active.
    pub starts_at: Option<DateTime<Utc>>,
    /// When the record stops being valid.
    pub expires_at: Option<DateTime<Utc>>,
    /// When the instance completes.
    pub completion: CompletionPolicy,
    /// Terminalize after this long without a consumed event.
    pub event_idle_timeout_ms: Option<u64>,
    /// Terminalize after this long without a committed transition.
    pub progress_timeout_ms: Option<u64>,
    /// Drain or cancel on expiry.
    pub on_expiry: ExpiryPolicy,
    /// Hard stop for draining.
    pub drain_deadline: Option<DateTime<Utc>>,
}

impl LifecyclePolicy {
    /// One-shot lifecycle: completes on the first success, drains on expiry.
    pub fn run_once() -> Self {
        Self {
            starts_at: None,
            expires_at: None,
            completion: CompletionPolicy::FirstSuccess,
            event_idle_timeout_ms: None,
            progress_timeout_ms: None,
            on_expiry: ExpiryPolicy::Drain,
            drain_deadline: None,
        }
    }

    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        if self
            .starts_at
            .zip(self.expires_at)
            .is_some_and(|(a, b)| a >= b)
        {
            return Err(ContractError::Invalid(
                "lifecycle starts_at must be before expires_at".into(),
            ));
        }
        if self.drain_deadline.is_some() && self.on_expiry != ExpiryPolicy::Drain {
            return Err(ContractError::Invalid(
                "drain_deadline requires on_expiry=drain".into(),
            ));
        }
        if self
            .expires_at
            .zip(self.drain_deadline)
            .is_some_and(|(expires, drain)| drain <= expires)
        {
            return Err(ContractError::Invalid(
                "lifecycle drain_deadline must be after expires_at".into(),
            ));
        }
        if self.event_idle_timeout_ms == Some(0) || self.progress_timeout_ms == Some(0) {
            return Err(ContractError::Invalid(
                "lifecycle timeouts must be positive".into(),
            ));
        }
        if matches!(
            self.completion,
            CompletionPolicy::AfterMatchedEvaluations(0) | CompletionPolicy::AfterSuccessfulRuns(0)
        ) {
            return Err(ContractError::Invalid(
                "lifecycle completion count must be positive".into(),
            ));
        }
        Ok(())
    }
}

/// How a step ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepOutcomeKind {
    /// Terminal success.
    Succeeded,
    /// Filtered out.
    Skipped,
    /// Parked on a wake condition.
    Waiting,
    /// Errored.
    Failed,
    /// Cancelled.
    Cancelled,
}

/// Recorded outcome of one step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StepOutcome {
    /// Discriminator naming the variant of this record.
    pub kind: StepOutcomeKind,
    /// Stable code for material outcomes.
    pub reason_code: Option<String>,
    /// What resumes a waiting step.
    #[serde(default)]
    pub wake_condition: Value,
}

/// Lifecycle of an action intent; `dispatch_committed` is the point of no return.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionState {
    /// Created by a transition; not yet authorized.
    Prepared,
    /// Waiting for a human confirmation.
    AwaitingConfirmation,
    /// Guards passed; may be dispatched.
    Authorized,
    /// Effect committed; cancellation can no longer claim it was not performed.
    DispatchCommitted,
    /// Provider reports progress.
    Executing,
    /// Terminal success.
    Succeeded,
    /// Terminal rejection.
    Rejected,
    /// Failed; waits for its backoff, then dispatches again.
    Retryable,
    /// Outcome unknown; waits for reconciliation.
    Unknown,
    /// Outcome established by reconciliation.
    Reconciled,
}

impl ActionState {
    /// Whether the state machine allows `self -> next`.
    pub fn can_transition_to(self, next: Self) -> bool {
        use ActionState::*;
        matches!(
            (self, next),
            (Prepared, AwaitingConfirmation | Authorized | Rejected)
                | (AwaitingConfirmation, Authorized | Rejected)
                | (Authorized, DispatchCommitted | Rejected)
                | (
                    DispatchCommitted,
                    Executing | Succeeded | Rejected | Retryable | Unknown
                )
                | (Executing, Succeeded | Rejected | Retryable | Unknown)
                | (Retryable, DispatchCommitted | Reconciled)
                | (Unknown, Reconciled)
                | (Succeeded | Rejected, Reconciled)
        )
    }

    /// Whether the effect may already have happened.
    pub fn dispatch_committed(self) -> bool {
        matches!(
            self,
            Self::DispatchCommitted
                | Self::Executing
                | Self::Succeeded
                | Self::Rejected
                | Self::Retryable
                | Self::Unknown
                | Self::Reconciled
        )
    }
}

/// Control epochs an intent was created under; any bump makes it stale.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ControlEpochs {
    /// Tenant control epoch.
    pub tenant: i64,
    /// Resource control epoch.
    pub resource: i64,
    /// Instance control epoch.
    pub instance: i64,
}

/// Scope of a control command.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ControlScope {
    /// Whole tenant.
    Tenant,
    /// One external resource.
    Resource,
    /// One instance.
    Instance,
}

/// Operating mode set by a control command.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ControlMode {
    /// Normal operation.
    Running,
    /// No new evaluations or dispatches.
    Paused,
    /// Terminal stop.
    Stopped,
    /// Immediate stop that also revokes providers.
    EmergencyStopped,
}

/// Operator command that bumps a control epoch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ControlCommand {
    /// Scope kind.
    pub scope: ControlScope,
    /// Scope identity.
    pub scope_id: String,
    /// Execution mode this record was produced under.
    pub mode: ControlMode,
    /// Operator issuing the command.
    pub operator_subject_id: SubjectId,
    /// Human-readable reason.
    pub reason: String,
    /// When an override lapses.
    pub override_expires_at: Option<DateTime<Utc>>,
}

impl ControlCommand {
    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        required("control scope_id", &self.scope_id)?;
        required("control operator_subject_id", &self.operator_subject_id)?;
        required("control reason", &self.reason)?;
        Ok(())
    }
}

/// Reference to a product-owned fenced reservation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceReservationRef {
    /// Reservation identity.
    pub reservation_id: String,
    /// Fence the reservation was taken under.
    pub fencing_token: i64,
}

/// Durable intent to perform one external effect, created inside a fenced transition.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionIntent {
    /// Stable identifier of this record.
    pub id: String,
    /// Tenant that owns this record.
    pub tenant_id: TenantId,
    /// Workflow instance this record refers to.
    pub instance_id: InstanceId,
    /// Run this record belongs to.
    pub run_id: RunId,
    /// Pinned capability (id, contract version, content digest).
    pub capability: CapabilityPin,
    /// Caller-supplied key that makes repeated submissions return the first result.
    pub idempotency_key: String,
    /// Current lifecycle state.
    pub state: ActionState,
    /// Structured input handed to the provider.
    pub input: Value,
    /// Side-effect class of the action.
    pub effect: Effect,
    /// Idempotency class that decides whether automatic retry is safe.
    pub retry_class: IdempotencyMode,
    /// Control epochs at creation.
    pub control_epochs: ControlEpochs,
    /// Resource the effect targets; empty when unscoped.
    pub resource_scope_id: String,
    /// Instance lease version at creation.
    pub lease_epoch: i64,
    /// Bumped on every claim; fences claim owners.
    pub action_epoch: i64,
    /// Latest time by which the work must finish.
    pub deadline: Option<DateTime<Utc>>,
    /// Fenced reservation for funds actions.
    pub reservation: Option<ResourceReservationRef>,
    /// When the record was created (database time).
    pub created_at: DateTime<Utc>,
}

impl ActionIntent {
    /// Check this contract's invariants; returns the first violation.
    pub fn validate(&self) -> Result<(), ContractError> {
        required("action id", &self.id)?;
        required("action idempotency_key", &self.idempotency_key)?;
        if self.effect == Effect::Funds && self.reservation.is_none() {
            return Err(ContractError::Invalid(
                "funds action requires a resource reservation".into(),
            ));
        }
        if self.effect == Effect::Funds && self.resource_scope_id.trim().is_empty() {
            return Err(ContractError::Invalid(
                "funds action requires a resource scope".into(),
            ));
        }
        if self.effect == Effect::Funds && self.retry_class == IdempotencyMode::None {
            return Err(ContractError::Invalid(
                "funds action requires an explicit retry class".into(),
            ));
        }
        if self
            .deadline
            .is_some_and(|deadline| deadline <= self.created_at)
        {
            return Err(ContractError::Invalid(
                "action deadline must be after creation".into(),
            ));
        }
        Ok(())
    }

    /// Validate an intent at the only creation boundary. Later states are
    /// reached exclusively through the fenced store transition.
    pub fn validate_prepared(&self) -> Result<(), ContractError> {
        self.validate()?;
        if self.state != ActionState::Prepared {
            return Err(ContractError::Invalid(
                "new action intent must start in prepared state".into(),
            ));
        }
        Ok(())
    }
}

/// Provider's answer to a dispatch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionReceipt {
    /// Stable identifier of this record.
    pub id: String,
    /// Intent this refers to.
    pub action_intent_id: String,
    /// Provider version that produced it.
    pub provider_version: String,
    /// When the receipt arrived.
    pub received_at: DateTime<Utc>,
    /// State the provider reports.
    pub outcome: ActionState,
    /// Structured payload.
    pub payload: Value,
    /// Digest of the raw provider response; deduplicates receipts.
    pub raw_receipt_digest: String,
}

/// Observed state of a dispatched action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActionObservation {
    /// Stable identifier of this record.
    pub id: String,
    /// Intent this refers to.
    pub action_intent_id: String,
    /// Provider version that produced it.
    pub provider_version: String,
    /// When the state was observed.
    pub observed_at: DateTime<Utc>,
    /// Current lifecycle state.
    pub state: String,
    /// External resource created or affected.
    pub resource_ref: Option<Value>,
    /// Digest of the raw provider response; deduplicates receipts.
    pub raw_receipt_digest: String,
    /// Whether this observation ends the action.
    pub terminal: bool,
    /// A reconciliation provider sets this only after proving that repeating
    /// the same idempotent action is safe.
    #[serde(default)]
    pub retry_authorized: bool,
}

/// A missing source-sequence range that blocks ordered delivery for an aggregate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceGap {
    /// Tenant that owns this record.
    pub tenant_id: TenantId,
    /// Source the gap belongs to.
    pub source: String,
    /// Aggregate whose sequence has the hole.
    pub aggregate_id: String,
    /// First missing sequence (inclusive).
    pub missing_from: i64,
    /// Last missing sequence (inclusive).
    pub missing_to: i64,
    /// When waiting for the gap expires and delivery blocks.
    pub deadline: DateTime<Utc>,
    /// Gap status (`waiting`, `blocked`, `unblocked`).
    pub status: String,
}

/// Scope of a resource reservation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReservationScope {
    /// Whole tenant.
    Tenant,
    /// One external resource.
    Resource,
}

/// Lifecycle of a reservation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReservationState {
    /// Held.
    Reserved,
    /// Used by a committed dispatch.
    Consumed,
    /// Given back.
    Released,
    /// Lapsed unused.
    Expired,
}

/// Mirror of a product-owned fenced reservation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceReservation {
    /// Stable identifier of this record.
    pub id: String,
    /// Tenant that owns this record.
    pub tenant_id: TenantId,
    /// Scope kind.
    pub scope: ReservationScope,
    /// Scope identity.
    pub scope_id: String,
    /// Kind of resource reserved.
    pub resource_kind: String,
    /// Reserved amount as a decimal string.
    pub amount: String,
    /// Product policy version that granted it.
    pub policy_version: String,
    /// When the record stops being valid.
    pub expires_at: DateTime<Utc>,
    /// Fence the reservation was taken under.
    pub fencing_token: i64,
    /// Provider-side reservation id.
    pub provider_reservation_id: Option<String>,
    /// Current lifecycle state.
    pub state: ReservationState,
}

/// A value with provenance and freshness metadata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObservedValue<T> {
    /// The value carried by this record.
    pub value: T,
    /// Where the value was observed.
    pub source: String,
    /// When the state was observed.
    pub observed_at: DateTime<Utc>,
    /// When the receipt arrived.
    pub received_at: DateTime<Utc>,
    /// Version of the source.
    pub source_version: String,
    /// Quality label from the source.
    pub quality: String,
    /// Digest of the value.
    pub digest: String,
}

impl<T> ObservedValue<T> {
    /// Whether the value is fresh enough for `max_age` at `now`.
    pub fn is_accepted(
        &self,
        now: DateTime<Utc>,
        max_age: chrono::Duration,
        accepted_quality: &BTreeSet<String>,
    ) -> bool {
        self.observed_at <= now
            && now - self.observed_at <= max_age
            && accepted_quality.contains(&self.quality)
    }
}

/// Everything a decision depended on, for replay and audit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DecisionSnapshot {
    /// Digests of the inputs.
    pub input_digests: Vec<String>,
    /// Config version.
    pub instance_config_version: String,
    /// Product policy version that granted it.
    pub policy_version: String,
    /// Capabilities in force.
    pub capability_versions: Vec<CapabilityPin>,
    /// Execution profile revision in force.
    pub execution_profile_revision_id: String,
    /// Context values used.
    #[serde(default)]
    pub context_snapshot: Value,
    /// Policy values used.
    #[serde(default)]
    pub policy_snapshot: Value,
    /// Which Agent artifacts influenced the decision.
    #[serde(default)]
    pub agent_provenance: Value,
}

/// Who supplied a parameter value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParameterProvenance {
    /// Explicitly supplied by the user.
    UserSupplied,
    /// Product default.
    ProductDefault,
    /// Inferred by an Agent.
    AgentInferred,
    /// Computed from other parameters.
    Derived,
}

/// A parameter with its provenance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParameterValue {
    /// The value carried by this record.
    pub value: Value,
    /// Who supplied it.
    pub provenance: ParameterProvenance,
}

/// Declared parameter and its live-mode requirements.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParameterSpec {
    /// Display name.
    pub name: String,
    /// Must be present.
    pub required: bool,
    /// Must be user-supplied in live mode.
    pub required_explicit_for_live: bool,
}

/// Check supplied parameters against their specs for `mode`.
pub fn validate_parameters(
    mode: ExecutionMode,
    specs: &[ParameterSpec],
    values: &BTreeMap<String, ParameterValue>,
) -> Result<(), MissingRequirements> {
    let missing = specs
        .iter()
        .filter(|spec| match values.get(&spec.name) {
            None => {
                spec.required || (mode == ExecutionMode::Live && spec.required_explicit_for_live)
            }
            Some(value) => {
                mode == ExecutionMode::Live
                    && spec.required_explicit_for_live
                    && value.provenance != ParameterProvenance::UserSupplied
            }
        })
        .map(|spec| spec.name.clone())
        .collect::<Vec<_>>();
    if missing.is_empty() {
        Ok(())
    } else {
        Err(MissingRequirements {
            parameters: missing,
        })
    }
}

/// Parameters that block a live run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[error("missing explicit workflow requirements: {parameters:?}")]
pub struct MissingRequirements {
    /// Missing or non-explicit parameter names.
    pub parameters: Vec<String>,
}

/// Budget reserved atomically before a root operation starts children.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RootOperationBudget {
    /// Root operation identity.
    pub root_operation_id: String,
    /// Maximum nesting depth.
    pub max_depth: u32,
    /// Maximum descendants.
    pub descendant_limit: u32,
    /// Maximum runs.
    pub run_limit: u32,
    /// Token budget.
    pub token_budget: u64,
    /// Cost budget in micro-units.
    pub cost_budget_micros: u64,
    /// Maximum actions.
    pub action_budget: u32,
    /// Latest time by which the work must finish.
    pub deadline: DateTime<Utc>,
    /// Permissions children may not exceed.
    #[serde(default)]
    pub permission_ceiling: BTreeSet<String>,
}

/// Persisted Agent decision reused after recovery instead of re-asking the model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DecisionArtifact {
    /// Stable identifier of this record.
    pub id: String,
    /// Root operation identity.
    pub root_operation_id: String,
    /// Content hash that makes the referenced artifact immutable.
    pub content_digest: String,
    /// Model identifier as registered in the model registry.
    pub model: String,
    /// Digest of the prompt.
    pub prompt_digest: String,
    /// Model output.
    pub output: Value,
    /// When the record was created (database time).
    pub created_at: DateTime<Utc>,
}

/// Operator-facing diagnostic attached to an instance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DiagnosticRecord {
    /// Stable diagnostic code.
    pub code: String,
    /// Human-readable message.
    pub message: String,
    /// When it was recorded.
    pub at: DateTime<Utc>,
    /// Structured detail.
    #[serde(default)]
    pub detail: Value,
}

/// Rebuildable read model of an instance; never authorizes or schedules work.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionProjection {
    /// Projection schema version.
    pub schema_version: String,
    /// Authoritative event sequence the projection was built from.
    pub source_sequence: i64,
    /// Steps in progress.
    pub current_steps: Vec<String>,
    /// Steps completed.
    pub completed_steps: Vec<String>,
    /// What the instance waits for.
    pub waiting_on: Option<Value>,
    /// Most recent decision.
    pub last_decision: Option<Value>,
    /// Steps that may run next.
    pub next_possible_steps: Vec<String>,
    /// Next scheduled evaluation.
    pub next_trigger_at: Option<DateTime<Utc>>,
    /// Actions prepared but not dispatched.
    pub planned_actions: Vec<String>,
    /// Most recent diagnostic.
    pub latest_diagnostic: Option<DiagnosticRecord>,
    /// Product-defined progress.
    pub progress: Value,
    /// When the record stops being valid.
    pub expires_at: Option<DateTime<Utc>>,
}

/// A contract value violates its invariants.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ContractError {
    /// Invalid workflow contract.
    #[error("invalid workflow contract: {0}")]
    Invalid(String),
}

fn required(name: &str, value: &str) -> Result<(), ContractError> {
    if value.trim().is_empty() {
        Err(ContractError::Invalid(format!("{name} is required")))
    } else {
        Ok(())
    }
}

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

    fn empty_spec() -> crate::Spec {
        crate::Spec {
            spec_id: "test".into(),
            version: "1".into(),
            description: String::new(),
            aliases: vec![],
            instance_config_schema: None,
            display: BTreeMap::new(),
            branches: vec![],
        }
    }

    fn funds_manifest() -> CapabilityManifest {
        CapabilityManifest::action(
            "action.example",
            "1",
            "sha256:x",
            Effect::Funds,
            IdempotencyMode::ReconcileBeforeRetry,
            true,
        )
    }

    #[test]
    fn funds_capability_requires_reconciliation_and_all_guards() {
        assert!(funds_manifest().validate().is_ok());
        let mut invalid = funds_manifest();
        invalid.required_guards.remove(&GuardKind::Freshness);
        assert!(invalid.validate().is_err());
        invalid.required_guards.insert(GuardKind::Freshness);
        invalid.supports_reconciliation = false;
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn action_state_never_skips_dispatch_commit() {
        assert!(ActionState::Authorized.can_transition_to(ActionState::DispatchCommitted));
        assert!(!ActionState::Authorized.can_transition_to(ActionState::Succeeded));
        assert!(ActionState::Unknown.can_transition_to(ActionState::Reconciled));
    }

    #[test]
    fn live_parameters_cannot_be_silently_inferred() {
        let specs = [ParameterSpec {
            name: "account".into(),
            required: true,
            required_explicit_for_live: true,
        }];
        let inferred = BTreeMap::from([(
            "account".into(),
            ParameterValue {
                value: Value::String("a".into()),
                provenance: ParameterProvenance::AgentInferred,
            },
        )]);
        assert_eq!(
            validate_parameters(ExecutionMode::Live, &specs, &inferred)
                .unwrap_err()
                .parameters,
            ["account"]
        );
        assert!(validate_parameters(ExecutionMode::Paper, &specs, &inferred).is_ok());
    }

    #[test]
    fn freshness_is_fail_closed() {
        let now = Utc::now();
        let observed = ObservedValue {
            value: 1,
            source: "source".into(),
            observed_at: now - chrono::Duration::seconds(2),
            received_at: now,
            source_version: "1".into(),
            quality: "good".into(),
            digest: "d".into(),
        };
        assert!(observed.is_accepted(
            now,
            chrono::Duration::seconds(3),
            &BTreeSet::from(["good".into()])
        ));
        assert!(!observed.is_accepted(
            now,
            chrono::Duration::seconds(1),
            &BTreeSet::from(["good".into()])
        ));
    }

    #[test]
    fn revision_and_manifest_contracts_fail_closed() {
        let mut revision = WorkflowRevision {
            definition_id: "definition".into(),
            revision: 1,
            content_digest: "digest".into(),
            kernel_abi_version: "1".into(),
            dependency_set_digest: "dependencies".into(),
            expression_versions: BTreeMap::new(),
            capabilities: vec![CapabilityPin {
                id: "action.example".into(),
                contract_version: "1".into(),
                content_digest: "capability-digest".into(),
            }],
            template_provenance: Value::Null,
            spec: empty_spec(),
        };
        assert!(revision.validate().is_ok());
        revision.capabilities.push(revision.capabilities[0].clone());
        assert!(revision.validate().is_err());
        revision.capabilities.pop();
        revision.kernel_abi_version.clear();
        assert!(revision.validate().is_err());

        let external = CapabilityManifest::action(
            "action.notify",
            "1",
            "digest",
            Effect::ExternalWrite,
            IdempotencyMode::NeverAutomaticRetry,
            false,
        );
        assert_eq!(
            external.required_guards,
            BTreeSet::from([GuardKind::Authorization])
        );
        assert!(external.validate().is_ok());
        let mut invalid = external;
        invalid.retry.max_attempts = 0;
        assert!(invalid.validate().is_err());

        let mut wrong_kind = funds_manifest();
        wrong_kind.kind = CapabilityKind::Expression;
        assert!(wrong_kind.validate().is_err());
        wrong_kind.kind = CapabilityKind::Action;
        wrong_kind.idempotency_mode = IdempotencyMode::Native;
        wrong_kind.supports_reconciliation = false;
        assert!(wrong_kind.validate().is_ok());
        wrong_kind.lifecycle = CapabilityLifecycle::Disabled;
        assert!(!wrong_kind.can_start_new_work());
    }

    #[test]
    fn trigger_schedule_lifecycle_and_control_validate_boundaries() {
        let now = Utc::now();
        let mut trigger = TriggerEnvelope {
            event_id: "event".into(),
            event_type: "example".into(),
            source: "source".into(),
            schema_version: "1".into(),
            tenant_id: "tenant".parse().unwrap(),
            subject_id: "subject".parse().unwrap(),
            aggregate_id: "aggregate".into(),
            source_sequence: Some(1),
            observed_version: None,
            occurred_at: now,
            received_at: now,
            watermark: None,
            correlation_key: "key".into(),
            dedup_key: "dedup".into(),
            cursor: None,
            payload: Value::Null,
            trace_context: Value::Null,
        };
        assert!(trigger.validate().is_ok());
        trigger.occurred_at = now + chrono::Duration::minutes(6);
        assert!(trigger.validate().is_err());

        let valid_schedule = SchedulePolicy {
            cadence: ScheduleCadence::Cron {
                expression: "0 0 * * * *".into(),
            },
            timezone: "Asia/Shanghai".into(),
            catch_up: CatchUpPolicy::CatchUpOnce,
        };
        assert!(valid_schedule.validate().is_ok());
        for invalid in [
            SchedulePolicy {
                timezone: "Nowhere/Invalid".into(),
                ..valid_schedule.clone()
            },
            SchedulePolicy {
                cadence: ScheduleCadence::FixedRate { milliseconds: 0 },
                ..valid_schedule.clone()
            },
            SchedulePolicy {
                catch_up: CatchUpPolicy::CatchUpAll { limit: 0 },
                ..valid_schedule
            },
        ] {
            assert!(invalid.validate().is_err());
        }

        let mut lifecycle = LifecyclePolicy::run_once();
        assert!(lifecycle.validate().is_ok());
        lifecycle.starts_at = Some(now);
        lifecycle.expires_at = Some(now);
        assert!(lifecycle.validate().is_err());
        lifecycle.starts_at = None;
        lifecycle.expires_at = None;
        lifecycle.on_expiry = ExpiryPolicy::Cancel;
        lifecycle.drain_deadline = Some(now);
        assert!(lifecycle.validate().is_err());

        let mut command = ControlCommand {
            scope: ControlScope::Instance,
            scope_id: "instance".into(),
            mode: ControlMode::Paused,
            operator_subject_id: "operator".parse().unwrap(),
            reason: "maintenance".into(),
            override_expires_at: None,
        };
        assert!(command.validate().is_ok());
        command.reason.clear();
        assert!(command.validate().is_err());
    }

    #[test]
    fn funds_intent_requires_reservation_scope_and_retry_class() {
        let now = Utc::now();
        let mut intent = ActionIntent {
            id: "intent".into(),
            tenant_id: "tenant".parse().unwrap(),
            instance_id: "instance".parse().unwrap(),
            run_id: "run".parse().unwrap(),
            capability: CapabilityPin {
                id: "action.example".into(),
                contract_version: "1".into(),
                content_digest: "digest".into(),
            },
            idempotency_key: "idempotency".into(),
            state: ActionState::Prepared,
            input: Value::Null,
            effect: Effect::Funds,
            retry_class: IdempotencyMode::ReconcileBeforeRetry,
            control_epochs: ControlEpochs::default(),
            resource_scope_id: "resource".into(),
            lease_epoch: 1,
            action_epoch: 1,
            deadline: None,
            reservation: Some(ResourceReservationRef {
                reservation_id: "reservation".into(),
                fencing_token: 1,
            }),
            created_at: now,
        };
        assert!(intent.validate().is_ok());
        assert!(intent.validate_prepared().is_ok());
        intent.reservation = None;
        assert!(intent.validate().is_err());
        intent.reservation = Some(ResourceReservationRef {
            reservation_id: "reservation".into(),
            fencing_token: 1,
        });
        intent.resource_scope_id.clear();
        assert!(intent.validate().is_err());
        intent.resource_scope_id = "resource".into();
        intent.retry_class = IdempotencyMode::None;
        assert!(intent.validate().is_err());
        intent.retry_class = IdempotencyMode::ReconcileBeforeRetry;
        intent.state = ActionState::Authorized;
        assert!(intent.validate_prepared().is_err());
        assert!(!ActionState::Prepared.dispatch_committed());
        assert!(ActionState::Unknown.dispatch_committed());
    }

    fn trigger_binding() -> TriggerBinding {
        TriggerBinding {
            id: "binding".into(),
            revision: 1,
            source: "source".into(),
            event_type: "event".into(),
            instance_id: "instance".parse().unwrap(),
            predicate: serde_json::json!({}),
            ordering: OrderingPolicy::Commutative,
            starts_at: None,
            expires_at: None,
            gap_wait_ms: default_gap_wait_ms(),
            gap_limit: default_gap_limit(),
        }
    }

    #[test]
    fn trigger_binding_rejects_blank_ids_bad_gaps_and_inverted_windows() {
        assert!(trigger_binding().validate().is_ok());
        let blank = TriggerBinding {
            source: "  ".into(),
            ..trigger_binding()
        };
        assert!(blank.validate().is_err());
        for gap_wait_ms in [0, 3_600_001] {
            let binding = TriggerBinding {
                gap_wait_ms,
                ..trigger_binding()
            };
            assert!(binding.validate().is_err(), "gap_wait_ms {gap_wait_ms}");
        }
        for gap_limit in [0, 10_001] {
            let binding = TriggerBinding {
                gap_limit,
                ..trigger_binding()
            };
            assert!(binding.validate().is_err(), "gap_limit {gap_limit}");
        }
        let array_predicate = TriggerBinding {
            predicate: serde_json::json!([1]),
            ..trigger_binding()
        };
        assert!(array_predicate.validate().is_err());
        let now = Utc::now();
        let inverted = TriggerBinding {
            starts_at: Some(now),
            expires_at: Some(now),
            ..trigger_binding()
        };
        assert!(inverted.validate().is_err());
        let ordered = TriggerBinding {
            starts_at: Some(now),
            expires_at: Some(now + chrono::Duration::seconds(1)),
            ..trigger_binding()
        };
        assert!(ordered.validate().is_ok());
        let defaults: TriggerBinding = serde_json::from_value(serde_json::json!({
            "id": "binding", "revision": 1, "source": "s", "event_type": "e",
            "instance_id": "i", "predicate": {}, "ordering": "commutative",
            "starts_at": null, "expires_at": null
        }))
        .unwrap();
        assert_eq!(defaults.gap_wait_ms, 30_000);
        assert_eq!(defaults.gap_limit, 100);
    }

    #[test]
    fn execution_profile_revision_requires_every_provider_name() {
        let profile = ExecutionProfileRevision {
            id: "profile".into(),
            revision: 1,
            content_digest: "sha256:profile".into(),
            mode: ExecutionMode::Paper,
            durability_grade: DurabilityGrade::Standard,
            trigger_provider: "triggers".into(),
            data_provider: "data".into(),
            clock_model: "database".into(),
            action_provider: "actions".into(),
            models: BTreeMap::new(),
            environment: Value::Null,
            policy_bundle: Value::Null,
            connection_bindings: BTreeMap::new(),
        };
        assert!(profile.validate().is_ok());
        let blank_provider = ExecutionProfileRevision {
            action_provider: String::new(),
            ..profile.clone()
        };
        assert!(blank_provider.validate().is_err());
        let blank_digest = ExecutionProfileRevision {
            content_digest: " ".into(),
            ..profile
        };
        assert!(blank_digest.validate().is_err());
    }

    #[test]
    fn retry_backoff_grows_exponentially_with_bounded_jitter_and_cap() {
        let policy = RetryPolicy {
            max_attempts: 5,
            timeout_ms: 1_000,
            initial_backoff_ms: 100,
            max_backoff_ms: 1_000,
        };
        assert_eq!(policy.backoff_ms(1, 0), 100);
        assert_eq!(policy.backoff_ms(2, 0), 200);
        assert_eq!(policy.backoff_ms(3, 0), 400);
        // Jitter is deterministic and never exceeds 25% of the base.
        assert_eq!(policy.backoff_ms(1, 24), 124);
        assert_eq!(policy.backoff_ms(1, 25), 100);
        // Jitter is taken modulo the ceiling (800 / 4 = 200 here).
        assert_eq!(policy.backoff_ms(4, 249), 849);
        // The cap holds for large attempts and for base + jitter.
        assert_eq!(policy.backoff_ms(5, 0), 1_000);
        assert_eq!(policy.backoff_ms(5, 249), 1_000);
        assert_eq!(policy.backoff_ms(40, u64::MAX), 1_000);
        // Attempt 0 behaves like the first attempt instead of underflowing.
        assert_eq!(policy.backoff_ms(0, 0), 100);
    }

    #[test]
    fn lifecycle_policy_rejects_inconsistent_windows_and_zero_counts() {
        let now = Utc::now();
        let later = now + chrono::Duration::hours(1);
        assert!(LifecyclePolicy::run_once().validate().is_ok());
        let inverted = LifecyclePolicy {
            starts_at: Some(later),
            expires_at: Some(now),
            ..LifecyclePolicy::run_once()
        };
        assert!(inverted.validate().is_err());
        let drain_without_policy = LifecyclePolicy {
            on_expiry: ExpiryPolicy::Cancel,
            drain_deadline: Some(later),
            ..LifecyclePolicy::run_once()
        };
        assert!(drain_without_policy.validate().is_err());
        let drain_before_expiry = LifecyclePolicy {
            expires_at: Some(later),
            drain_deadline: Some(now),
            ..LifecyclePolicy::run_once()
        };
        assert!(drain_before_expiry.validate().is_err());
        let zero_timeout = LifecyclePolicy {
            event_idle_timeout_ms: Some(0),
            ..LifecyclePolicy::run_once()
        };
        assert!(zero_timeout.validate().is_err());
        for completion in [
            CompletionPolicy::AfterMatchedEvaluations(0),
            CompletionPolicy::AfterSuccessfulRuns(0),
        ] {
            let zero_count = LifecyclePolicy {
                completion,
                ..LifecyclePolicy::run_once()
            };
            assert!(zero_count.validate().is_err());
        }
        let bounded = LifecyclePolicy {
            starts_at: Some(now),
            expires_at: Some(later),
            completion: CompletionPolicy::AfterSuccessfulRuns(2),
            event_idle_timeout_ms: Some(1_000),
            progress_timeout_ms: Some(1_000),
            on_expiry: ExpiryPolicy::Drain,
            drain_deadline: Some(later + chrono::Duration::minutes(1)),
        };
        assert!(bounded.validate().is_ok());
    }
}