lifeloop-cli 0.1.0

Provider-neutral lifecycle abstraction and normalizer for AI harnesses
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
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
//! Provider-neutral lifecycle contracts for AI harnesses.
//!
//! `docs/specs/lifecycle-contract/body.md` is the normative target. This module
//! implements the `lifeloop.v0.1` slice of that contract: the wire enums,
//! lifecycle receipt, payload envelope, and the callback request/response
//! envelopes that clients implement.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

pub mod host_assets;
pub mod protocol;
pub mod router;
pub mod source_files;
pub mod telemetry;

pub const SCHEMA_VERSION: &str = "lifeloop.v0.1";

// ============================================================================
// Wire enums
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IntegrationMode {
    ManualSkill,
    LauncherWrapper,
    NativeHook,
    ReferenceAdapter,
    TelemetryOnly,
}

impl IntegrationMode {
    pub const ALL: &'static [Self] = &[
        Self::ManualSkill,
        Self::LauncherWrapper,
        Self::NativeHook,
        Self::ReferenceAdapter,
        Self::TelemetryOnly,
    ];
}

/// Support states for adapter capability claims.
///
/// Per `docs/specs/lifecycle-contract/body.md` ("Support states"), the
/// pre-issue-#6 vocabulary distinguished `simulated` from `inferred`.
/// Issue #6 simplified to one synthesizing state plus `partial`:
///
/// * `simulated` → renamed to `synthesized` (clearer about derivation).
/// * `inferred` → folded into `partial` (telemetry-derived behavior is
///   partial behavior).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SupportState {
    Native,
    Synthesized,
    Manual,
    Partial,
    Unavailable,
}

impl SupportState {
    pub const ALL: &'static [Self] = &[
        Self::Native,
        Self::Synthesized,
        Self::Manual,
        Self::Partial,
        Self::Unavailable,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AdapterRole {
    PrimaryWorker,
    Worker,
    Supervisor,
    Observer,
}

impl AdapterRole {
    pub const ALL: &'static [Self] = &[
        Self::PrimaryWorker,
        Self::Worker,
        Self::Supervisor,
        Self::Observer,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub enum LifecycleEventKind {
    #[serde(rename = "session.starting")]
    SessionStarting,
    #[serde(rename = "session.started")]
    SessionStarted,
    #[serde(rename = "frame.opening")]
    FrameOpening,
    #[serde(rename = "frame.opened")]
    FrameOpened,
    #[serde(rename = "context.pressure_observed")]
    ContextPressureObserved,
    #[serde(rename = "context.compacted")]
    ContextCompacted,
    #[serde(rename = "frame.ending")]
    FrameEnding,
    #[serde(rename = "frame.ended")]
    FrameEnded,
    #[serde(rename = "session.ending")]
    SessionEnding,
    #[serde(rename = "session.ended")]
    SessionEnded,
    #[serde(rename = "supervisor.tick")]
    SupervisorTick,
    #[serde(rename = "capability.degraded")]
    CapabilityDegraded,
    #[serde(rename = "receipt.emitted")]
    ReceiptEmitted,
    #[serde(rename = "receipt.gap_detected")]
    ReceiptGapDetected,
}

impl LifecycleEventKind {
    pub const ALL: &'static [Self] = &[
        Self::SessionStarting,
        Self::SessionStarted,
        Self::FrameOpening,
        Self::FrameOpened,
        Self::ContextPressureObserved,
        Self::ContextCompacted,
        Self::FrameEnding,
        Self::FrameEnded,
        Self::SessionEnding,
        Self::SessionEnded,
        Self::SupervisorTick,
        Self::CapabilityDegraded,
        Self::ReceiptEmitted,
        Self::ReceiptGapDetected,
    ];
}

pub fn lifecycle_event_kinds() -> Vec<LifecycleEventKind> {
    LifecycleEventKind::ALL.to_vec()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptStatus {
    Observed,
    Delivered,
    Skipped,
    Degraded,
    Failed,
}

impl ReceiptStatus {
    pub const ALL: &'static [Self] = &[
        Self::Observed,
        Self::Delivered,
        Self::Skipped,
        Self::Degraded,
        Self::Failed,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailureClass {
    AdapterUnavailable,
    CapabilityUnsupported,
    CapabilityDegraded,
    PlacementUnavailable,
    PayloadTooLarge,
    PayloadRejected,
    IdentityUnavailable,
    TransportError,
    Timeout,
    OperatorRequired,
    StateConflict,
    InvalidRequest,
    InternalError,
}

impl FailureClass {
    pub const ALL: &'static [Self] = &[
        Self::AdapterUnavailable,
        Self::CapabilityUnsupported,
        Self::CapabilityDegraded,
        Self::PlacementUnavailable,
        Self::PayloadTooLarge,
        Self::PayloadRejected,
        Self::IdentityUnavailable,
        Self::TransportError,
        Self::Timeout,
        Self::OperatorRequired,
        Self::StateConflict,
        Self::InvalidRequest,
        Self::InternalError,
    ];

    /// Default retry-class mapping per the spec's failure-to-retry table.
    pub fn default_retry(self) -> RetryClass {
        match self {
            Self::AdapterUnavailable => RetryClass::RetryAfterReconfigure,
            Self::CapabilityUnsupported => RetryClass::DoNotRetry,
            Self::CapabilityDegraded => RetryClass::RetryAfterReread,
            Self::PlacementUnavailable => RetryClass::RetryAfterReconfigure,
            Self::PayloadTooLarge => RetryClass::DoNotRetry,
            Self::PayloadRejected => RetryClass::RetryAfterReconfigure,
            Self::IdentityUnavailable => RetryClass::RetryAfterReconfigure,
            Self::TransportError => RetryClass::SafeRetry,
            Self::Timeout => RetryClass::SafeRetry,
            Self::OperatorRequired => RetryClass::RetryAfterOperator,
            Self::StateConflict => RetryClass::RetryAfterReread,
            Self::InvalidRequest => RetryClass::DoNotRetry,
            Self::InternalError => RetryClass::RetryAfterReread,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RetryClass {
    SafeRetry,
    RetryAfterReread,
    RetryAfterReconfigure,
    RetryAfterOperator,
    DoNotRetry,
}

impl RetryClass {
    pub const ALL: &'static [Self] = &[
        Self::SafeRetry,
        Self::RetryAfterReread,
        Self::RetryAfterReconfigure,
        Self::RetryAfterOperator,
        Self::DoNotRetry,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlacementClass {
    DeveloperEquivalentFrame,
    PrePromptFrame,
    SideChannelContext,
    ReceiptOnly,
}

impl PlacementClass {
    pub const ALL: &'static [Self] = &[
        Self::DeveloperEquivalentFrame,
        Self::PrePromptFrame,
        Self::SideChannelContext,
        Self::ReceiptOnly,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlacementOutcome {
    Delivered,
    Skipped,
    Degraded,
    Failed,
}

impl PlacementOutcome {
    pub const ALL: &'static [Self] =
        &[Self::Delivered, Self::Skipped, Self::Degraded, Self::Failed];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RequirementLevel {
    Required,
    Preferred,
    Optional,
}

impl RequirementLevel {
    pub const ALL: &'static [Self] = &[Self::Required, Self::Preferred, Self::Optional];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NegotiationOutcome {
    Satisfied,
    Degraded,
    Unsupported,
    RequiresOperator,
}

impl NegotiationOutcome {
    pub const ALL: &'static [Self] = &[
        Self::Satisfied,
        Self::Degraded,
        Self::Unsupported,
        Self::RequiresOperator,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrameClass {
    TopLevel,
    Subcall,
}

impl FrameClass {
    pub const ALL: &'static [Self] = &[Self::TopLevel, Self::Subcall];
}

// ============================================================================
// Validation
// ============================================================================

/// Reasons a Lifeloop envelope, payload, or receipt failed validation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "detail")]
pub enum ValidationError {
    EmptyField(String),
    SchemaVersionMismatch { expected: String, found: String },
    InvalidFrameContext(String),
    InvalidPayload(String),
    InvalidReceipt(String),
    InvalidRequest(String),
    InvalidResponse(String),
    InvalidManifest(String),
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyField(name) => write!(f, "empty sentinel string in field `{name}`"),
            Self::SchemaVersionMismatch { expected, found } => write!(
                f,
                "schema_version mismatch: expected `{expected}`, found `{found}`"
            ),
            Self::InvalidFrameContext(msg) => write!(f, "invalid frame_context: {msg}"),
            Self::InvalidPayload(msg) => write!(f, "invalid payload: {msg}"),
            Self::InvalidReceipt(msg) => write!(f, "invalid receipt: {msg}"),
            Self::InvalidRequest(msg) => write!(f, "invalid callback request: {msg}"),
            Self::InvalidResponse(msg) => write!(f, "invalid callback response: {msg}"),
            Self::InvalidManifest(msg) => write!(f, "invalid adapter manifest: {msg}"),
        }
    }
}

impl std::error::Error for ValidationError {}

fn require_non_empty(value: &str, field: &'static str) -> Result<(), ValidationError> {
    if value.is_empty() {
        return Err(ValidationError::EmptyField(field.to_string()));
    }
    Ok(())
}

// ============================================================================
// Frame context
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FrameContext {
    pub frame_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_frame_id: Option<String>,
    pub frame_class: FrameClass,
}

impl FrameContext {
    pub fn top_level(frame_id: impl Into<String>) -> Self {
        Self {
            frame_id: frame_id.into(),
            parent_frame_id: None,
            frame_class: FrameClass::TopLevel,
        }
    }

    pub fn subcall(frame_id: impl Into<String>, parent_frame_id: impl Into<String>) -> Self {
        Self {
            frame_id: frame_id.into(),
            parent_frame_id: Some(parent_frame_id.into()),
            frame_class: FrameClass::Subcall,
        }
    }

    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.frame_id, "frame_context.frame_id")?;
        if let Some(parent) = &self.parent_frame_id {
            require_non_empty(parent, "frame_context.parent_frame_id")?;
        }
        match (self.frame_class, &self.parent_frame_id) {
            (FrameClass::TopLevel, Some(_)) => Err(ValidationError::InvalidFrameContext(
                "frame_class=top_level must not carry parent_frame_id".into(),
            )),
            (FrameClass::Subcall, None) => Err(ValidationError::InvalidFrameContext(
                "frame_class=subcall requires parent_frame_id".into(),
            )),
            _ => Ok(()),
        }
    }
}

// ============================================================================
// Payload envelope and references
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcceptablePlacement {
    pub placement: PlacementClass,
    pub requirement: RequirementLevel,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadRef {
    pub payload_id: String,
    pub payload_kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub byte_size: Option<u64>,
}

impl PayloadRef {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.payload_id, "payload_ref.payload_id")?;
        require_non_empty(&self.payload_kind, "payload_ref.payload_kind")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadEnvelope {
    pub schema_version: String,
    pub payload_id: String,
    pub client_id: String,
    pub payload_kind: String,
    pub format: String,
    pub content_encoding: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_ref: Option<String>,
    pub byte_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
    pub acceptable_placements: Vec<AcceptablePlacement>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at_epoch_s: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redaction: Option<String>,
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

impl PayloadEnvelope {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.schema_version.clone(),
            });
        }
        require_non_empty(&self.payload_id, "payload.payload_id")?;
        require_non_empty(&self.client_id, "payload.client_id")?;
        require_non_empty(&self.payload_kind, "payload.payload_kind")?;
        require_non_empty(&self.format, "payload.format")?;
        require_non_empty(&self.content_encoding, "payload.content_encoding")?;
        match (self.body.is_some(), self.body_ref.is_some()) {
            (true, true) => Err(ValidationError::InvalidPayload(
                "body and body_ref are mutually exclusive".into(),
            )),
            (false, false) => Err(ValidationError::InvalidPayload(
                "exactly one of body or body_ref must be present".into(),
            )),
            _ => Ok(()),
        }?;
        if let Some(idem) = &self.idempotency_key {
            require_non_empty(idem, "payload.idempotency_key")?;
        }
        if self.acceptable_placements.is_empty() {
            return Err(ValidationError::InvalidPayload(
                "acceptable_placements must list at least one placement".into(),
            ));
        }
        Ok(())
    }
}

// ============================================================================
// Receipts
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadReceipt {
    pub payload_id: String,
    pub placement: PlacementClass,
    pub status: PlacementOutcome,
    pub byte_size: u64,
}

impl PayloadReceipt {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.payload_id, "payload_receipt.payload_id")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CapabilityDegradation {
    pub capability: String,
    pub previous_support: SupportState,
    pub current_support: SupportState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_class: Option<RetryClass>,
}

impl CapabilityDegradation {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.capability, "capability_degradation.capability")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Warning {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capability: Option<String>,
}

impl Warning {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.code, "warning.code")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LifecycleReceipt {
    pub schema_version: String,
    pub receipt_id: String,
    pub idempotency_key: Option<String>,
    pub client_id: String,
    pub adapter_id: String,
    pub invocation_id: String,
    pub event: LifecycleEventKind,
    pub event_id: String,
    pub sequence: Option<u64>,
    pub parent_receipt_id: Option<String>,
    pub integration_mode: IntegrationMode,
    pub status: ReceiptStatus,
    pub at_epoch_s: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_run_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_task_id: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub payload_receipts: Vec<PayloadReceipt>,
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub telemetry_summary: serde_json::Map<String, serde_json::Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capability_degradations: Vec<CapabilityDegradation>,
    pub failure_class: Option<FailureClass>,
    pub retry_class: Option<RetryClass>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<Warning>,
}

impl LifecycleReceipt {
    /// Wire keys that are required *and* nullable: the JSON object MUST carry
    /// them even when the value is `null`. A producer that omits one of these
    /// keys is rejected at deserialize time. See
    /// `docs/specs/lifecycle-contract/body.md` ("required and nullable") and
    /// `docs/specs/README.md` for the field-presence taxonomy.
    pub const REQUIRED_NULLABLE_FIELDS: &'static [&'static str] = &[
        "idempotency_key",
        "sequence",
        "parent_receipt_id",
        "failure_class",
        "retry_class",
    ];
}

// `Option<T>` defaults to "missing key → None" under serde, which would let an
// inbound receipt drop a required-nullable key entirely and still deserialize.
// The validator runs after that, so the omission goes silent.
//
// The fix is a parent-level intercept: a serde Visitor that walks the input
// map generically, tracks which keys appeared, and only then constructs the
// receipt. Required-nullable keys missing from the map → multi-key error so a
// draft client hears about all omissions on the first try. Required-non-null
// keys → standard `missing_field`. Optional keys default to `None`/empty.
//
// The Visitor stays format-agnostic (no dependency on `serde_json` types in
// the Deserialize signature) so a non-JSON serde backend — bincode, YAML,
// CBOR — can deserialize a `LifecycleReceipt` whenever the contract is
// represented in that format.
impl<'de> Deserialize<'de> for LifecycleReceipt {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "LifecycleReceipt",
            LIFECYCLE_RECEIPT_FIELDS,
            LifecycleReceiptVisitor,
        )
    }
}

const LIFECYCLE_RECEIPT_FIELDS: &[&str] = &[
    "schema_version",
    "receipt_id",
    "idempotency_key",
    "client_id",
    "adapter_id",
    "invocation_id",
    "event",
    "event_id",
    "sequence",
    "parent_receipt_id",
    "integration_mode",
    "status",
    "at_epoch_s",
    "harness_session_id",
    "harness_run_id",
    "harness_task_id",
    "payload_receipts",
    "telemetry_summary",
    "capability_degradations",
    "failure_class",
    "retry_class",
    "warnings",
];

#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum LifecycleReceiptField {
    SchemaVersion,
    ReceiptId,
    IdempotencyKey,
    ClientId,
    AdapterId,
    InvocationId,
    Event,
    EventId,
    Sequence,
    ParentReceiptId,
    IntegrationMode,
    Status,
    AtEpochS,
    HarnessSessionId,
    HarnessRunId,
    HarnessTaskId,
    PayloadReceipts,
    TelemetrySummary,
    CapabilityDegradations,
    FailureClass,
    RetryClass,
    Warnings,
}

struct LifecycleReceiptVisitor;

impl<'de> serde::de::Visitor<'de> for LifecycleReceiptVisitor {
    type Value = LifecycleReceipt;

    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("a LifecycleReceipt object")
    }

    fn visit_map<A>(self, mut map: A) -> Result<LifecycleReceipt, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        // For `Option<T>` fields we use `Option<Option<T>>` so the outer
        // layer encodes "did the key appear" and the inner layer encodes the
        // wire value. For required non-null fields we use `Option<T>` and
        // emit `missing_field` at the end. For default-able collection
        // fields we use `Option<...>` and fall back to `Default::default()`.
        let mut schema_version: Option<String> = None;
        let mut receipt_id: Option<String> = None;
        let mut idempotency_key: Option<Option<String>> = None;
        let mut client_id: Option<String> = None;
        let mut adapter_id: Option<String> = None;
        let mut invocation_id: Option<String> = None;
        let mut event: Option<LifecycleEventKind> = None;
        let mut event_id: Option<String> = None;
        let mut sequence: Option<Option<u64>> = None;
        let mut parent_receipt_id: Option<Option<String>> = None;
        let mut integration_mode: Option<IntegrationMode> = None;
        let mut status: Option<ReceiptStatus> = None;
        let mut at_epoch_s: Option<u64> = None;
        let mut harness_session_id: Option<Option<String>> = None;
        let mut harness_run_id: Option<Option<String>> = None;
        let mut harness_task_id: Option<Option<String>> = None;
        let mut payload_receipts: Option<Vec<PayloadReceipt>> = None;
        let mut telemetry_summary: Option<serde_json::Map<String, serde_json::Value>> = None;
        let mut capability_degradations: Option<Vec<CapabilityDegradation>> = None;
        let mut failure_class: Option<Option<FailureClass>> = None;
        let mut retry_class: Option<Option<RetryClass>> = None;
        let mut warnings: Option<Vec<Warning>> = None;

        while let Some(field) = map.next_key::<LifecycleReceiptField>()? {
            match field {
                LifecycleReceiptField::SchemaVersion => {
                    set_once(&mut schema_version, &mut map, "schema_version")?;
                }
                LifecycleReceiptField::ReceiptId => {
                    set_once(&mut receipt_id, &mut map, "receipt_id")?;
                }
                LifecycleReceiptField::IdempotencyKey => {
                    set_once(&mut idempotency_key, &mut map, "idempotency_key")?;
                }
                LifecycleReceiptField::ClientId => {
                    set_once(&mut client_id, &mut map, "client_id")?;
                }
                LifecycleReceiptField::AdapterId => {
                    set_once(&mut adapter_id, &mut map, "adapter_id")?;
                }
                LifecycleReceiptField::InvocationId => {
                    set_once(&mut invocation_id, &mut map, "invocation_id")?;
                }
                LifecycleReceiptField::Event => {
                    set_once(&mut event, &mut map, "event")?;
                }
                LifecycleReceiptField::EventId => {
                    set_once(&mut event_id, &mut map, "event_id")?;
                }
                LifecycleReceiptField::Sequence => {
                    set_once(&mut sequence, &mut map, "sequence")?;
                }
                LifecycleReceiptField::ParentReceiptId => {
                    set_once(&mut parent_receipt_id, &mut map, "parent_receipt_id")?;
                }
                LifecycleReceiptField::IntegrationMode => {
                    set_once(&mut integration_mode, &mut map, "integration_mode")?;
                }
                LifecycleReceiptField::Status => {
                    set_once(&mut status, &mut map, "status")?;
                }
                LifecycleReceiptField::AtEpochS => {
                    set_once(&mut at_epoch_s, &mut map, "at_epoch_s")?;
                }
                LifecycleReceiptField::HarnessSessionId => {
                    set_once(&mut harness_session_id, &mut map, "harness_session_id")?;
                }
                LifecycleReceiptField::HarnessRunId => {
                    set_once(&mut harness_run_id, &mut map, "harness_run_id")?;
                }
                LifecycleReceiptField::HarnessTaskId => {
                    set_once(&mut harness_task_id, &mut map, "harness_task_id")?;
                }
                LifecycleReceiptField::PayloadReceipts => {
                    set_once(&mut payload_receipts, &mut map, "payload_receipts")?;
                }
                LifecycleReceiptField::TelemetrySummary => {
                    set_once(&mut telemetry_summary, &mut map, "telemetry_summary")?;
                }
                LifecycleReceiptField::CapabilityDegradations => {
                    set_once(
                        &mut capability_degradations,
                        &mut map,
                        "capability_degradations",
                    )?;
                }
                LifecycleReceiptField::FailureClass => {
                    set_once(&mut failure_class, &mut map, "failure_class")?;
                }
                LifecycleReceiptField::RetryClass => {
                    set_once(&mut retry_class, &mut map, "retry_class")?;
                }
                LifecycleReceiptField::Warnings => {
                    set_once(&mut warnings, &mut map, "warnings")?;
                }
            }
        }

        // Required-nullable presence check. Collect every missing key so a
        // draft client that drops several at once gets one error.
        let mut missing_required_nullable: Vec<&'static str> = Vec::new();
        if idempotency_key.is_none() {
            missing_required_nullable.push("idempotency_key");
        }
        if sequence.is_none() {
            missing_required_nullable.push("sequence");
        }
        if parent_receipt_id.is_none() {
            missing_required_nullable.push("parent_receipt_id");
        }
        if failure_class.is_none() {
            missing_required_nullable.push("failure_class");
        }
        if retry_class.is_none() {
            missing_required_nullable.push("retry_class");
        }
        if !missing_required_nullable.is_empty() {
            return Err(serde::de::Error::custom(format!(
                "LifecycleReceipt is missing required-nullable field(s): {}; \
                 these keys MUST be present even when their value is null",
                missing_required_nullable.join(", ")
            )));
        }

        Ok(LifecycleReceipt {
            schema_version: schema_version
                .ok_or_else(|| serde::de::Error::missing_field("schema_version"))?,
            receipt_id: receipt_id.ok_or_else(|| serde::de::Error::missing_field("receipt_id"))?,
            idempotency_key: idempotency_key.expect("checked above"),
            client_id: client_id.ok_or_else(|| serde::de::Error::missing_field("client_id"))?,
            adapter_id: adapter_id.ok_or_else(|| serde::de::Error::missing_field("adapter_id"))?,
            invocation_id: invocation_id
                .ok_or_else(|| serde::de::Error::missing_field("invocation_id"))?,
            event: event.ok_or_else(|| serde::de::Error::missing_field("event"))?,
            event_id: event_id.ok_or_else(|| serde::de::Error::missing_field("event_id"))?,
            sequence: sequence.expect("checked above"),
            parent_receipt_id: parent_receipt_id.expect("checked above"),
            integration_mode: integration_mode
                .ok_or_else(|| serde::de::Error::missing_field("integration_mode"))?,
            status: status.ok_or_else(|| serde::de::Error::missing_field("status"))?,
            at_epoch_s: at_epoch_s.ok_or_else(|| serde::de::Error::missing_field("at_epoch_s"))?,
            harness_session_id: harness_session_id.unwrap_or(None),
            harness_run_id: harness_run_id.unwrap_or(None),
            harness_task_id: harness_task_id.unwrap_or(None),
            payload_receipts: payload_receipts.unwrap_or_default(),
            telemetry_summary: telemetry_summary.unwrap_or_default(),
            capability_degradations: capability_degradations.unwrap_or_default(),
            failure_class: failure_class.expect("checked above"),
            retry_class: retry_class.expect("checked above"),
            warnings: warnings.unwrap_or_default(),
        })
    }
}

fn set_once<'de, T, A>(
    slot: &mut Option<T>,
    map: &mut A,
    field: &'static str,
) -> Result<(), A::Error>
where
    T: serde::Deserialize<'de>,
    A: serde::de::MapAccess<'de>,
{
    if slot.is_some() {
        return Err(serde::de::Error::duplicate_field(field));
    }
    *slot = Some(map.next_value()?);
    Ok(())
}

impl LifecycleReceipt {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.schema_version.clone(),
            });
        }
        require_non_empty(&self.receipt_id, "receipt.receipt_id")?;
        require_non_empty(&self.client_id, "receipt.client_id")?;
        require_non_empty(&self.adapter_id, "receipt.adapter_id")?;
        require_non_empty(&self.invocation_id, "receipt.invocation_id")?;
        require_non_empty(&self.event_id, "receipt.event_id")?;
        if let Some(idem) = &self.idempotency_key {
            require_non_empty(idem, "receipt.idempotency_key")?;
        }
        if let Some(parent) = &self.parent_receipt_id {
            require_non_empty(parent, "receipt.parent_receipt_id")?;
        }
        if matches!(self.event, LifecycleEventKind::ReceiptEmitted) {
            return Err(ValidationError::InvalidReceipt(
                "receipt.emitted is a notification event and must not itself produce a receipt"
                    .into(),
            ));
        }
        for pr in &self.payload_receipts {
            pr.validate()?;
        }
        for deg in &self.capability_degradations {
            deg.validate()?;
        }
        for w in &self.warnings {
            w.validate()?;
        }
        match (
            matches!(self.status, ReceiptStatus::Failed),
            self.failure_class.is_some(),
        ) {
            (true, false) => {
                return Err(ValidationError::InvalidReceipt(
                    "status=failed requires failure_class".into(),
                ));
            }
            (false, true) => {
                return Err(ValidationError::InvalidReceipt(
                    "failure_class is only valid on status=failed receipts".into(),
                ));
            }
            _ => {}
        }
        if matches!(self.status, ReceiptStatus::Failed) && self.retry_class.is_none() {
            return Err(ValidationError::InvalidReceipt(
                "status=failed requires retry_class (clients must declare retry posture)".into(),
            ));
        }
        Ok(())
    }
}

// ============================================================================
// Adapter manifest (issue #6: full registry)
// ============================================================================

/// Manifest placement classes — the trust-neutral, lifecycle-timing
/// vocabulary the adapter manifest uses to declare placement support.
///
/// **Distinct from [`PlacementClass`]**, which is the routing
/// vocabulary the runtime uses on `acceptable_placements` for
/// concrete payload delivery. The manifest declares *capability*;
/// the payload envelope declares *routing intent*. A future
/// revision may unify them; the current contract keeps them
/// separate so manifest evolution does not churn payload routing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ManifestPlacementClass {
    /// Before any frame opens; e.g. session-init context.
    PreSession,
    /// Leading edge of a frame, before user/task input arrives.
    PreFrameLeading,
    /// Trailing edge of a frame, after input but before model execution.
    PreFrameTrailing,
    /// Inside a tool-result envelope returned to the model.
    ToolResult,
    /// Through an operator or manual surface (skill, command, wrapper).
    ManualOperator,
}

impl ManifestPlacementClass {
    pub const ALL: &'static [Self] = &[
        Self::PreSession,
        Self::PreFrameLeading,
        Self::PreFrameTrailing,
        Self::ToolResult,
        Self::ManualOperator,
    ];
}

/// Per-event capability claim inside a manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestLifecycleEventSupport {
    pub support: SupportState,
    /// Integration modes through which the adapter delivers this event.
    /// May be empty when `support` is `unavailable`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub modes: Vec<IntegrationMode>,
}

/// Per-placement capability claim inside a manifest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestPlacementSupport {
    pub support: SupportState,
    /// Placement size limit in bytes when the adapter declares one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_bytes: Option<u64>,
}

/// Capability claim describing how the adapter surfaces
/// `context.pressure_observed` lifecycle evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestContextPressure {
    pub support: SupportState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<String>,
}

/// Capability claim describing receipt emission and ledger support.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestReceipts {
    /// Adapter emits its own native receipts.
    pub native: bool,
    /// Lifeloop synthesizes receipts on the adapter's behalf.
    pub lifeloop_synthesized: bool,
    /// Durable cross-invocation receipt ledger.
    pub receipt_ledger: SupportState,
}

/// Per-id support claims for harness identity correlation. Optional
/// on the manifest because a telemetry-only adapter may not expose
/// any of these.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestSessionIdentity {
    pub harness_session_id: SupportState,
    pub harness_run_id: SupportState,
    pub harness_task_id: SupportState,
}

/// Capability claim for the adapter's session-rename surface.
/// Optional on the manifest; absent means "no rename concept."
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestSessionRename {
    pub support: SupportState,
}

/// Capability claim for operator approval/intervention surfaces.
/// Optional; absent means "no operator surface."
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestApprovalSurface {
    pub support: SupportState,
}

/// One telemetry source the adapter exposes for lifecycle evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestTelemetrySource {
    pub source: String,
    pub support: SupportState,
}

/// One pre-declared capability degradation the adapter ships with.
/// Lets a manifest say "this build's `context_pressure` was native
/// upstream but is currently `unavailable` here" without firing a
/// runtime `capability.degraded` event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestKnownDegradation {
    pub capability: String,
    pub previous_support: SupportState,
    pub current_support: SupportState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<String>,
}

/// Adapter manifest. Issue #6 lands the full shape; pre-issue-#6
/// drafts shipped a stub with only schema_version, adapter_id,
/// adapter_version, display_name, roles, integration_modes, and
/// lifecycle_events.
///
/// `contract_version` (this struct's first field) carries the
/// Lifeloop contract version label (e.g. `lifeloop.v0.1`),
/// independent of `adapter_version`. The two are separate so
/// adapters can iterate without bumping the contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AdapterManifest {
    pub contract_version: String,
    pub adapter_id: String,
    pub adapter_version: String,
    pub display_name: String,
    pub role: AdapterRole,
    pub integration_modes: Vec<IntegrationMode>,
    pub lifecycle_events: BTreeMap<LifecycleEventKind, ManifestLifecycleEventSupport>,
    pub placement: BTreeMap<ManifestPlacementClass, ManifestPlacementSupport>,
    pub context_pressure: ManifestContextPressure,
    pub receipts: ManifestReceipts,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_identity: Option<ManifestSessionIdentity>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_rename: Option<ManifestSessionRename>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approval_surface: Option<ManifestApprovalSurface>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub failure_modes: Vec<FailureClass>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub telemetry_sources: Vec<ManifestTelemetrySource>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub known_degradations: Vec<ManifestKnownDegradation>,
}

impl AdapterManifest {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.contract_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.contract_version.clone(),
            });
        }
        require_non_empty(&self.adapter_id, "manifest.adapter_id")?;
        require_non_empty(&self.adapter_version, "manifest.adapter_version")?;
        require_non_empty(&self.display_name, "manifest.display_name")?;
        if self.integration_modes.is_empty() {
            return Err(ValidationError::InvalidManifest(
                "manifest.integration_modes must declare at least one integration mode".into(),
            ));
        }
        for deg in &self.known_degradations {
            require_non_empty(&deg.capability, "manifest.known_degradations[].capability")?;
        }
        for src in &self.telemetry_sources {
            require_non_empty(&src.source, "manifest.telemetry_sources[].source")?;
        }
        Ok(())
    }
}

// ----------------------------------------------------------------------------
// Manifest registry
// ----------------------------------------------------------------------------

/// Conformance posture of a registered adapter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConformanceLevel {
    /// v1-conformance adapter: every capability claim that depends on
    /// extracted code (asset rendering, telemetry, placement) is
    /// paired with a test that verifies the claim.
    V1Conformance,
    /// Initial manifest shipped without full claim verification. The
    /// claims describe expected behavior so clients can negotiate, but
    /// the registry does not yet run capability-claim tests for them.
    PreConformance,
}

/// Registry entry pairing an [`AdapterManifest`] with its
/// [`ConformanceLevel`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegisteredAdapter {
    pub manifest: AdapterManifest,
    pub conformance: ConformanceLevel,
}

/// Built-in adapter manifest registry. Order is stable so callers
/// that render a `lifeloop adapters` listing get a predictable
/// output without sorting client-side.
pub fn manifest_registry() -> Vec<RegisteredAdapter> {
    vec![
        RegisteredAdapter {
            manifest: codex_manifest(),
            conformance: ConformanceLevel::V1Conformance,
        },
        RegisteredAdapter {
            manifest: claude_manifest(),
            conformance: ConformanceLevel::V1Conformance,
        },
        RegisteredAdapter {
            manifest: hermes_manifest(),
            conformance: ConformanceLevel::PreConformance,
        },
        RegisteredAdapter {
            manifest: openclaw_manifest(),
            conformance: ConformanceLevel::PreConformance,
        },
        RegisteredAdapter {
            manifest: gemini_manifest(),
            conformance: ConformanceLevel::PreConformance,
        },
        RegisteredAdapter {
            manifest: opencode_manifest(),
            conformance: ConformanceLevel::PreConformance,
        },
    ]
}

/// Resolve a registered adapter by `adapter_id`. Returns `None` for
/// unknown ids.
pub fn lookup_manifest(adapter_id: &str) -> Option<RegisteredAdapter> {
    manifest_registry()
        .into_iter()
        .find(|entry| entry.manifest.adapter_id == adapter_id)
}

fn synthesized() -> SupportState {
    SupportState::Synthesized
}

fn native() -> SupportState {
    SupportState::Native
}

fn unavailable() -> SupportState {
    SupportState::Unavailable
}

fn manual() -> SupportState {
    SupportState::Manual
}

/// Codex manifest. Native-hook integration covers Codex's stable hook
/// surface, including `PreCompact` in Codex CLI 0.129+. Capability
/// claims here are paired with verification tests in
/// `tests/manifest_claims.rs`.
pub fn codex_manifest() -> AdapterManifest {
    let lifecycle_events = BTreeMap::from([
        (
            LifecycleEventKind::SessionStarting,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::SessionStarted,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameOpening,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameOpened,
            ManifestLifecycleEventSupport {
                support: synthesized(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ContextPressureObserved,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ContextCompacted,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameEnding,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameEnded,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::SessionEnding,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
        (
            LifecycleEventKind::SessionEnded,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
        (
            LifecycleEventKind::SupervisorTick,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
        (
            LifecycleEventKind::CapabilityDegraded,
            ManifestLifecycleEventSupport {
                support: synthesized(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ReceiptEmitted,
            ManifestLifecycleEventSupport {
                support: synthesized(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ReceiptGapDetected,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
    ]);

    let placement = BTreeMap::from([
        (
            ManifestPlacementClass::PreSession,
            ManifestPlacementSupport {
                support: native(),
                max_bytes: Some(8192),
            },
        ),
        (
            ManifestPlacementClass::PreFrameLeading,
            ManifestPlacementSupport {
                support: native(),
                max_bytes: Some(8192),
            },
        ),
        (
            ManifestPlacementClass::PreFrameTrailing,
            ManifestPlacementSupport {
                support: unavailable(),
                max_bytes: None,
            },
        ),
        (
            ManifestPlacementClass::ToolResult,
            ManifestPlacementSupport {
                support: unavailable(),
                max_bytes: None,
            },
        ),
        (
            ManifestPlacementClass::ManualOperator,
            ManifestPlacementSupport {
                support: manual(),
                max_bytes: None,
            },
        ),
    ]);

    AdapterManifest {
        contract_version: SCHEMA_VERSION.to_string(),
        adapter_id: "codex".into(),
        adapter_version: "0.1.0".into(),
        display_name: "Codex".into(),
        role: AdapterRole::PrimaryWorker,
        integration_modes: vec![IntegrationMode::NativeHook, IntegrationMode::ManualSkill],
        lifecycle_events,
        placement,
        context_pressure: ManifestContextPressure {
            support: native(),
            evidence: Some(
                "Codex CLI 0.129 exposes PreCompact before context pressure handling and PostCompact after context compacts"
                    .into(),
            ),
        },
        receipts: ManifestReceipts {
            native: false,
            lifeloop_synthesized: true,
            receipt_ledger: unavailable(),
        },
        session_identity: Some(ManifestSessionIdentity {
            harness_session_id: native(),
            harness_run_id: synthesized(),
            harness_task_id: unavailable(),
        }),
        session_rename: None,
        approval_surface: None,
        failure_modes: vec![FailureClass::TransportError, FailureClass::PayloadTooLarge],
        telemetry_sources: Vec::new(),
        known_degradations: Vec::new(),
    }
}

/// Claude manifest. Native-hook integration via `.claude/settings.json`.
pub fn claude_manifest() -> AdapterManifest {
    let lifecycle_events = BTreeMap::from([
        (
            LifecycleEventKind::SessionStarting,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::SessionStarted,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameOpening,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameOpened,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ContextPressureObserved,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ContextCompacted,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
        (
            LifecycleEventKind::FrameEnding,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::FrameEnded,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::SessionEnding,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::SessionEnded,
            ManifestLifecycleEventSupport {
                support: native(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::SupervisorTick,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
        (
            LifecycleEventKind::CapabilityDegraded,
            ManifestLifecycleEventSupport {
                support: synthesized(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ReceiptEmitted,
            ManifestLifecycleEventSupport {
                support: synthesized(),
                modes: vec![IntegrationMode::NativeHook],
            },
        ),
        (
            LifecycleEventKind::ReceiptGapDetected,
            ManifestLifecycleEventSupport {
                support: unavailable(),
                modes: Vec::new(),
            },
        ),
    ]);

    let placement = BTreeMap::from([
        (
            ManifestPlacementClass::PreSession,
            ManifestPlacementSupport {
                support: native(),
                max_bytes: Some(16_384),
            },
        ),
        (
            ManifestPlacementClass::PreFrameLeading,
            ManifestPlacementSupport {
                support: native(),
                max_bytes: Some(16_384),
            },
        ),
        (
            ManifestPlacementClass::PreFrameTrailing,
            ManifestPlacementSupport {
                support: unavailable(),
                max_bytes: None,
            },
        ),
        (
            ManifestPlacementClass::ToolResult,
            ManifestPlacementSupport {
                support: unavailable(),
                max_bytes: None,
            },
        ),
        (
            ManifestPlacementClass::ManualOperator,
            ManifestPlacementSupport {
                support: manual(),
                max_bytes: None,
            },
        ),
    ]);

    AdapterManifest {
        contract_version: SCHEMA_VERSION.to_string(),
        adapter_id: "claude".into(),
        adapter_version: "0.1.0".into(),
        display_name: "Claude".into(),
        role: AdapterRole::PrimaryWorker,
        integration_modes: vec![IntegrationMode::NativeHook],
        lifecycle_events,
        placement,
        context_pressure: ManifestContextPressure {
            support: native(),
            evidence: Some(
                "Claude emits PreCompact and SessionEnd events that map directly to context.pressure_observed"
                    .into(),
            ),
        },
        receipts: ManifestReceipts {
            native: false,
            lifeloop_synthesized: true,
            receipt_ledger: unavailable(),
        },
        session_identity: Some(ManifestSessionIdentity {
            harness_session_id: native(),
            harness_run_id: synthesized(),
            harness_task_id: unavailable(),
        }),
        session_rename: None,
        approval_surface: None,
        failure_modes: vec![FailureClass::TransportError, FailureClass::PayloadTooLarge],
        telemetry_sources: Vec::new(),
        known_degradations: Vec::new(),
    }
}

/// Hermes pre-conformance manifest. Reference-adapter integration
/// supplied as a JSON descriptor at the path declared in
/// [`crate::host_assets::HERMES_TARGET_ADAPTER`].
pub fn hermes_manifest() -> AdapterManifest {
    pre_conformance_reference_adapter_manifest("hermes", "Hermes")
}

/// OpenClaw pre-conformance manifest.
pub fn openclaw_manifest() -> AdapterManifest {
    pre_conformance_reference_adapter_manifest("openclaw", "OpenClaw")
}

/// Gemini pre-conformance manifest.
pub fn gemini_manifest() -> AdapterManifest {
    pre_conformance_telemetry_only_manifest("gemini", "Gemini")
}

/// OpenCode pre-conformance manifest.
pub fn opencode_manifest() -> AdapterManifest {
    pre_conformance_telemetry_only_manifest("opencode", "OpenCode")
}

fn pre_conformance_reference_adapter_manifest(
    adapter_id: &str,
    display_name: &str,
) -> AdapterManifest {
    let lifecycle_events = BTreeMap::from([
        (
            LifecycleEventKind::SessionStarting,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::ReferenceAdapter],
            },
        ),
        (
            LifecycleEventKind::SessionStarted,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::ReferenceAdapter],
            },
        ),
        (
            LifecycleEventKind::FrameOpening,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::ReferenceAdapter],
            },
        ),
        (
            LifecycleEventKind::FrameEnded,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::ReferenceAdapter],
            },
        ),
        (
            LifecycleEventKind::SessionEnded,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::ReferenceAdapter],
            },
        ),
    ]);

    let placement = BTreeMap::from([
        (
            ManifestPlacementClass::PreSession,
            ManifestPlacementSupport {
                support: SupportState::Partial,
                max_bytes: None,
            },
        ),
        (
            ManifestPlacementClass::PreFrameLeading,
            ManifestPlacementSupport {
                support: SupportState::Partial,
                max_bytes: None,
            },
        ),
        (
            ManifestPlacementClass::ManualOperator,
            ManifestPlacementSupport {
                support: SupportState::Manual,
                max_bytes: None,
            },
        ),
    ]);

    AdapterManifest {
        contract_version: SCHEMA_VERSION.to_string(),
        adapter_id: adapter_id.to_string(),
        adapter_version: "0.0.1-pre".into(),
        display_name: display_name.to_string(),
        role: AdapterRole::Worker,
        integration_modes: vec![IntegrationMode::ReferenceAdapter],
        lifecycle_events,
        placement,
        context_pressure: ManifestContextPressure {
            support: SupportState::Partial,
            evidence: None,
        },
        receipts: ManifestReceipts {
            native: false,
            lifeloop_synthesized: true,
            receipt_ledger: SupportState::Unavailable,
        },
        session_identity: None,
        session_rename: None,
        approval_surface: None,
        failure_modes: Vec::new(),
        telemetry_sources: Vec::new(),
        known_degradations: Vec::new(),
    }
}

fn pre_conformance_telemetry_only_manifest(
    adapter_id: &str,
    display_name: &str,
) -> AdapterManifest {
    let lifecycle_events = BTreeMap::from([
        (
            LifecycleEventKind::SessionStarting,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::TelemetryOnly],
            },
        ),
        (
            LifecycleEventKind::ContextPressureObserved,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::TelemetryOnly],
            },
        ),
        (
            LifecycleEventKind::SessionEnded,
            ManifestLifecycleEventSupport {
                support: SupportState::Partial,
                modes: vec![IntegrationMode::TelemetryOnly],
            },
        ),
    ]);

    let placement = BTreeMap::from([(
        ManifestPlacementClass::ManualOperator,
        ManifestPlacementSupport {
            support: SupportState::Manual,
            max_bytes: None,
        },
    )]);

    AdapterManifest {
        contract_version: SCHEMA_VERSION.to_string(),
        adapter_id: adapter_id.to_string(),
        adapter_version: "0.0.1-pre".into(),
        display_name: display_name.to_string(),
        role: AdapterRole::Observer,
        integration_modes: vec![IntegrationMode::TelemetryOnly],
        lifecycle_events,
        placement,
        context_pressure: ManifestContextPressure {
            support: SupportState::Partial,
            evidence: None,
        },
        receipts: ManifestReceipts {
            native: false,
            lifeloop_synthesized: true,
            receipt_ledger: SupportState::Unavailable,
        },
        session_identity: None,
        session_rename: None,
        approval_surface: None,
        failure_modes: Vec::new(),
        telemetry_sources: Vec::new(),
        known_degradations: Vec::new(),
    }
}

// ============================================================================
// Callback request and response envelopes
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CallbackRequest {
    pub schema_version: String,
    pub event: LifecycleEventKind,
    pub event_id: String,
    pub adapter_id: String,
    pub adapter_version: String,
    pub integration_mode: IntegrationMode,
    pub invocation_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_run_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_task_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frame_context: Option<FrameContext>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capability_snapshot_ref: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub payload_refs: Vec<PayloadRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sequence: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

impl CallbackRequest {
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.schema_version.clone(),
            });
        }
        require_non_empty(&self.event_id, "request.event_id")?;
        require_non_empty(&self.adapter_id, "request.adapter_id")?;
        require_non_empty(&self.adapter_version, "request.adapter_version")?;
        require_non_empty(&self.invocation_id, "request.invocation_id")?;
        if let Some(s) = &self.harness_session_id {
            require_non_empty(s, "request.harness_session_id")?;
        }
        if let Some(s) = &self.harness_run_id {
            require_non_empty(s, "request.harness_run_id")?;
        }
        if let Some(s) = &self.harness_task_id {
            require_non_empty(s, "request.harness_task_id")?;
        }
        if let Some(s) = &self.capability_snapshot_ref {
            require_non_empty(s, "request.capability_snapshot_ref")?;
        }
        if let Some(s) = &self.idempotency_key {
            require_non_empty(s, "request.idempotency_key")?;
        }
        if let Some(fc) = &self.frame_context {
            fc.validate()?;
        }
        for r in &self.payload_refs {
            r.validate()?;
        }
        match self.event {
            LifecycleEventKind::FrameOpening
            | LifecycleEventKind::FrameOpened
            | LifecycleEventKind::FrameEnding
            | LifecycleEventKind::FrameEnded
                if self.frame_context.is_none() =>
            {
                Err(ValidationError::InvalidRequest(
                    "frame.* events require frame_context".into(),
                ))
            }
            LifecycleEventKind::ReceiptEmitted if self.idempotency_key.is_some() => {
                Err(ValidationError::InvalidRequest(
                    "receipt.emitted is a notification event and must not carry an idempotency_key"
                        .into(),
                ))
            }
            _ => Ok(()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CallbackResponse {
    pub schema_version: String,
    pub status: ReceiptStatus,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub client_payloads: Vec<PayloadEnvelope>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub receipt_refs: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<Warning>,
    pub failure_class: Option<FailureClass>,
    pub retry_class: Option<RetryClass>,
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

impl CallbackResponse {
    pub fn ok(status: ReceiptStatus) -> Self {
        Self {
            schema_version: SCHEMA_VERSION.to_string(),
            status,
            client_payloads: Vec::new(),
            receipt_refs: Vec::new(),
            warnings: Vec::new(),
            failure_class: None,
            retry_class: None,
            metadata: serde_json::Map::new(),
        }
    }

    pub fn failed(failure: FailureClass) -> Self {
        Self {
            schema_version: SCHEMA_VERSION.to_string(),
            status: ReceiptStatus::Failed,
            client_payloads: Vec::new(),
            receipt_refs: Vec::new(),
            warnings: Vec::new(),
            failure_class: Some(failure),
            retry_class: Some(failure.default_retry()),
            metadata: serde_json::Map::new(),
        }
    }

    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.schema_version.clone(),
            });
        }
        for p in &self.client_payloads {
            p.validate()?;
        }
        for r in &self.receipt_refs {
            require_non_empty(r, "response.receipt_refs[]")?;
        }
        for w in &self.warnings {
            w.validate()?;
        }
        match (
            matches!(self.status, ReceiptStatus::Failed),
            self.failure_class.is_some(),
        ) {
            (true, false) => {
                return Err(ValidationError::InvalidResponse(
                    "status=failed requires failure_class".into(),
                ));
            }
            (false, true) => {
                return Err(ValidationError::InvalidResponse(
                    "failure_class is only valid on status=failed responses".into(),
                ));
            }
            _ => {}
        }
        if matches!(self.status, ReceiptStatus::Failed) && self.retry_class.is_none() {
            return Err(ValidationError::InvalidResponse(
                "status=failed requires retry_class (clients must declare retry posture)".into(),
            ));
        }
        Ok(())
    }
}

// ============================================================================
// Dispatch envelope (transport boundary)
// ============================================================================

/// Wire shape carrying a [`CallbackRequest`] and the opaque
/// [`PayloadEnvelope`] bodies a dispatch is delivering with.
///
/// The lifecycle contract distinguishes two concerns:
///
/// * the *request* a client receives describing what is happening
///   (event kind, frame context, [`CallbackRequest::payload_refs`]
///   pointing at named/sized/digested payloads), and
/// * the *envelope bodies* the request refers to.
///
/// Until issue #22 the CLI and the subprocess invoker only transported
/// the request — the envelopes were not delivered, so subprocess clients
/// could not reach payload bodies and negotiation never saw real
/// placement inputs. `DispatchEnvelope` is the transport-boundary shape
/// that carries both:
///
/// ```json
/// {
///   "schema_version": "lifeloop.v0.1",
///   "request": { "...CallbackRequest...": "..." },
///   "payloads": [ { "...PayloadEnvelope...": "..." } ]
/// }
/// ```
///
/// Lifeloop does not parse `payloads[].body` — it is transported
/// verbatim, consistent with the spec rule that bodies are opaque
/// (`docs/specs/lifecycle-contract/body.md`, "Opaque Payload Envelope").
/// `payloads` is omitted on the wire when empty.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DispatchEnvelope {
    pub schema_version: String,
    pub request: CallbackRequest,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub payloads: Vec<PayloadEnvelope>,
}

impl DispatchEnvelope {
    /// Construct a dispatch envelope at the canonical schema version.
    pub fn new(request: CallbackRequest, payloads: Vec<PayloadEnvelope>) -> Self {
        Self {
            schema_version: SCHEMA_VERSION.to_string(),
            request,
            payloads,
        }
    }

    /// Validate the envelope: schema version, the inner request, and
    /// each carried payload. Cross-correlation between
    /// `request.payload_refs` and `payloads[]` is intentionally *not*
    /// enforced here — a request may declare refs that are delivered
    /// out-of-band, and clients may receive bodies the request did not
    /// list (e.g. degraded fallback bodies). Cross-correlation belongs
    /// in negotiation/receipt synthesis, not the transport boundary.
    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.schema_version.clone(),
            });
        }
        self.request.validate()?;
        for p in &self.payloads {
            p.validate()?;
        }
        Ok(())
    }
}