exochain-consent 0.2.0-beta

EXOCHAIN bailment-conditioned consent enforcement — no action without consent
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
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Bailment Contract Engine — clause-based composition, breach assessment, amendments.
//!
//! This module provides structured contract composition for bailments. Instead of
//! hashing raw bytes as `terms_hash`, callers compose a `ComposedContract` from a
//! `ContractTemplate`, binding parameters into clause templates. The resulting
//! `contract_hash` becomes the bailment's `terms_hash`.
//!
//! **Constitutional compliance**:
//! - No floating point — all monetary values in basis points (`u64`).
//! - No `HashMap` — `DeterministicMap` only.
//! - No `unsafe` code.
//! - No `std::time` — `Timestamp` (HLC) only.
//! - Canonical CBOR serialization for all hashing.
//! - All errors via `thiserror` (`ConsentError`).

use exo_core::{DeterministicMap, Did, Hash256, Timestamp, hash::hash_structured};
use serde::{Deserialize, Serialize};

use crate::{bailment::BailmentType, error::ConsentError};

// ---------------------------------------------------------------------------
// Core Types
// ---------------------------------------------------------------------------

/// Category of a contract clause.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ClauseCategory {
    /// Data custody and storage terms.
    DataCustody,
    /// Rights to process data.
    ProcessingRights,
    /// Remedies available upon breach.
    BreachRemedies,
    /// Caps on liability exposure.
    LiabilityCaps,
    /// Dispute resolution mechanism.
    DisputeResolution,
    /// Termination conditions.
    Termination,
    /// Governing jurisdiction.
    Jurisdiction,
    /// Indemnification obligations.
    Indemnification,
}

/// A clause template with `{{param}}` placeholders in the body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Clause {
    /// Unique clause identifier.
    pub id: String,
    /// The category this clause belongs to.
    pub category: ClauseCategory,
    /// Human-readable title.
    pub title: String,
    /// Template text with `{{param}}` placeholders.
    pub body: String,
    /// Whether this clause is required in every composition.
    pub required: bool,
    /// If set, this clause only applies to the specified jurisdiction.
    pub jurisdiction: Option<String>,
}

/// A contract template — a versioned collection of clauses for a `BailmentType`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContractTemplate {
    /// Stable template identifier.
    pub id: String,
    /// Human-readable template name.
    pub name: String,
    /// The bailment type this template serves.
    pub bailment_type: BailmentType,
    /// Clause templates.
    pub clauses: Vec<Clause>,
    /// Semantic version of this template.
    pub version: String,
}

/// Parameters used to bind a template into a concrete contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContractParams {
    /// Human-readable name of the bailor.
    pub bailor_name: String,
    /// Human-readable name of the bailee.
    pub bailee_name: String,
    /// DID of the bailor.
    pub bailor_did: Did,
    /// DID of the bailee.
    pub bailee_did: Did,
    /// When the contract becomes effective.
    pub effective_date: Timestamp,
    /// When the contract expires (if any).
    pub expiry_date: Option<Timestamp>,
    /// Governing jurisdiction.
    pub jurisdiction: String,
    /// Classification tier of the data under this contract.
    pub data_classification: DataClassification,
    /// Liability cap in basis points (1 bps = 0.01%). Integer only.
    pub liability_cap_bps: u64,
    /// Additional custom parameters for clause substitution.
    pub custom_params: DeterministicMap<String, String>,
}

/// Data classification tiers affecting contract terms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DataClassification {
    /// Publicly available data.
    Public,
    /// Internal-use data.
    Internal,
    /// Confidential data requiring access controls.
    Confidential,
    /// Restricted data with strict handling requirements.
    Restricted,
    /// Regulated data subject to legal compliance.
    Regulated,
}

impl std::fmt::Display for DataClassification {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Public => write!(f, "Public"),
            Self::Internal => write!(f, "Internal"),
            Self::Confidential => write!(f, "Confidential"),
            Self::Restricted => write!(f, "Restricted"),
            Self::Regulated => write!(f, "Regulated"),
        }
    }
}

impl DataClassification {
    fn custody_obligations(self) -> &'static str {
        match self {
            Self::Public => {
                "Public data may be stored with baseline integrity controls and publication-safe provenance tracking."
            }
            Self::Internal => {
                "Internal data requires organization-scoped access controls and non-public distribution records."
            }
            Self::Confidential => {
                "Confidential data requires least-privilege access, encrypted storage, encrypted transfer, and access logging."
            }
            Self::Restricted => {
                "Restricted data requires documented need-to-know approval, segregated storage, encrypted transfer, and dual-control access for export."
            }
            Self::Regulated => {
                "Regulated data requires statutory control mapping, jurisdiction-specific handling, audit-ready access logs, and retention policy enforcement."
            }
        }
    }

    fn processing_obligations(self) -> &'static str {
        match self {
            Self::Public => {
                "Public data processing is limited to authorized use, attribution preservation, and integrity checks."
            }
            Self::Internal => {
                "Internal data processing is limited to personnel, services, and agents operating under the bailee's internal authorization boundary."
            }
            Self::Confidential => {
                "Confidential data processing requires purpose-bound authorization and prohibits secondary use without signed amendment."
            }
            Self::Restricted => {
                "Restricted data processing is limited to named workflows and named operators; sub-processing requires explicit bailor approval."
            }
            Self::Regulated => {
                "Regulated data processing is limited to enumerated legal bases and auditable processing records."
            }
        }
    }

    fn breach_notice_obligations(self) -> &'static str {
        match self {
            Self::Public => {
                "Public classification breaches require notice within 10 business days when integrity or attribution is affected."
            }
            Self::Internal => {
                "Internal classification breaches require notice within 5 business days."
            }
            Self::Confidential => {
                "Confidential classification breaches require notice within 72 hours."
            }
            Self::Restricted => {
                "Restricted classification breaches require notice within 24 hours."
            }
            Self::Regulated => {
                "Regulated classification breaches require notice within the shortest applicable legal window, not exceeding 24 hours."
            }
        }
    }

    fn liability_obligations(self) -> &'static str {
        match self {
            Self::Public => {
                "Public data liability remains limited to integrity, availability, and attribution failures."
            }
            Self::Internal => {
                "Internal data liability includes unauthorized internal disclosure and unauthorized retention."
            }
            Self::Confidential => {
                "Confidential data liability includes unauthorized disclosure, unauthorized processing, and control failure."
            }
            Self::Restricted => {
                "Restricted data liability includes unauthorized access, export, delegation, or segregation failure."
            }
            Self::Regulated => {
                "Regulated data liability includes regulatory reporting failure, unlawful processing, and retention violation."
            }
        }
    }

    fn termination_obligations(self) -> &'static str {
        match self {
            Self::Public => {
                "Public data must be returned, deleted, or left published according to the bailor's written instruction."
            }
            Self::Internal => {
                "Internal data must be returned or deleted with an internal access revocation record."
            }
            Self::Confidential => {
                "Confidential data must be returned or destroyed with verifiable destruction evidence."
            }
            Self::Restricted => {
                "Restricted data must be quarantined immediately on termination until return or destruction is receipt-backed."
            }
            Self::Regulated => {
                "Regulated data must follow the governing retention schedule and produce a compliance evidence package on termination."
            }
        }
    }
}

/// A fully composed contract with all parameters bound and hash computed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ComposedContract {
    /// Unique contract identifier.
    pub id: String,
    /// The template this contract was composed from.
    pub template_id: String,
    /// The parameters used for composition.
    pub params: ContractParams,
    /// Rendered clauses with all placeholders substituted.
    pub rendered_clauses: Vec<RenderedClause>,
    /// When this contract was composed.
    pub composed_at: Timestamp,
    /// BLAKE3 hash of canonical CBOR — becomes `Bailment.terms_hash`.
    pub contract_hash: Hash256,
    /// Version counter (1 for original, increments on amendment).
    pub version: u32,
    /// Parent contract ID for amendments (None for originals).
    pub parent_contract_id: Option<String>,
}

/// A rendered clause with all parameters substituted.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RenderedClause {
    /// The source clause ID.
    pub clause_id: String,
    /// The clause category.
    pub category: ClauseCategory,
    /// The clause title.
    pub title: String,
    /// The clause body with all `{{param}}` placeholders replaced.
    pub rendered_body: String,
    /// Section number (e.g., "1", "2", "3").
    pub section_number: String,
}

/// Severity of a contract breach.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BreachSeverity {
    /// Non-material violation of a non-critical clause.
    Minor,
    /// Violation of a substantive clause affecting data integrity.
    Material,
    /// Violation that destroys the trust basis.
    Fundamental,
}

/// Assessment of a breach against contract terms.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BreachAssessment {
    /// The contract that was breached.
    pub contract_id: String,
    /// Severity classification.
    pub breach_severity: BreachSeverity,
    /// IDs of the clauses that were breached.
    pub breached_clauses: Vec<String>,
    /// Liability assessment in basis points.
    pub liability_assessment_bps: u64,
    /// Recommended remedy.
    pub recommended_remedy: Remedy,
    /// When the assessment was made.
    pub assessed_at: Timestamp,
}

/// Recommended remedy for a breach.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Remedy {
    /// Informational notice — no state change.
    Notice,
    /// Cure period — bailee has time to fix the breach.
    Cure {
        /// Number of days to cure the breach.
        cure_period_days: u32,
    },
    /// Suspend the bailment.
    Suspension,
    /// Terminate the bailment.
    Termination,
    /// Terminate and assess indemnification.
    Indemnification {
        /// Indemnification amount in basis points.
        amount_bps: u64,
    },
}

// ---------------------------------------------------------------------------
// Hashable payload for deterministic contract hashing
// ---------------------------------------------------------------------------

/// Internal struct for computing deterministic contract hashes via CBOR.
#[derive(Serialize)]
struct ContractHashPayload<'a> {
    template_id: &'a str,
    params: &'a ContractParams,
    rendered_clauses: &'a [RenderedClause],
    version: u32,
    parent_contract_id: &'a Option<String>,
}

// ---------------------------------------------------------------------------
// Functions
// ---------------------------------------------------------------------------

/// Returns the default contract template for the given `BailmentType`.
///
/// Each template contains one clause per `ClauseCategory` (8 total),
/// all required, with universal jurisdiction (no filtering).
#[must_use]
pub fn default_template(bailment_type: BailmentType) -> ContractTemplate {
    let (id, name, clauses) = match bailment_type {
        BailmentType::Custody => (
            "custody-standard-v1",
            "Standard Custody Agreement",
            custody_clauses(),
        ),
        BailmentType::Processing => (
            "processing-standard-v1",
            "Standard Processing Agreement",
            processing_clauses(),
        ),
        BailmentType::Delegation => (
            "delegation-standard-v1",
            "Standard Delegation Agreement",
            delegation_clauses(),
        ),
        BailmentType::Emergency => (
            "emergency-standard-v1",
            "Emergency Access Agreement",
            emergency_clauses(),
        ),
    };

    ContractTemplate {
        id: id.to_string(),
        name: name.to_string(),
        bailment_type,
        clauses,
        version: "1.0.0".to_string(),
    }
}

/// Compose a contract by substituting parameters into a template's clauses.
///
/// Filters clauses by jurisdiction, substitutes `{{param}}` placeholders,
/// assigns section numbers, and computes a deterministic `contract_hash`
/// via canonical CBOR + BLAKE3.
///
/// # Errors
///
/// Returns `ConsentError::Denied` if a required clause is filtered out by
/// jurisdiction mismatch.
pub fn compose(
    template: &ContractTemplate,
    params: &ContractParams,
    id: impl Into<String>,
    composed_at: Timestamp,
) -> Result<ComposedContract, ConsentError> {
    let id = id.into();
    validate_constructor_metadata("contract id", &id, "composed_at", &composed_at)?;

    // Filter clauses by jurisdiction
    let mut filtered_clauses = Vec::new();
    for clause in &template.clauses {
        match &clause.jurisdiction {
            Some(j) if *j != params.jurisdiction => {
                if clause.required {
                    return Err(ConsentError::Denied(format!(
                        "Required clause '{}' has jurisdiction '{}' but contract jurisdiction is '{}'",
                        clause.id, j, params.jurisdiction
                    )));
                }
                // Skip optional clause with mismatched jurisdiction
                continue;
            }
            _ => filtered_clauses.push(clause),
        }
    }

    // Render clauses
    let mut rendered_clauses = Vec::with_capacity(filtered_clauses.len());
    for (i, clause) in filtered_clauses.iter().enumerate() {
        let rendered_body = substitute_params(&clause.body, params);
        rendered_clauses.push(RenderedClause {
            clause_id: clause.id.clone(),
            category: clause.category,
            title: clause.title.clone(),
            rendered_body,
            section_number: format!("{}", i + 1),
        });
    }

    let version = 1u32;
    let template_id = template.id.clone();
    let parent_contract_id = None;

    // Compute deterministic hash
    let payload = ContractHashPayload {
        template_id: &template_id,
        params,
        rendered_clauses: &rendered_clauses,
        version,
        parent_contract_id: &parent_contract_id,
    };
    let contract_hash =
        hash_structured(&payload).map_err(|e| ConsentError::Denied(format!("Hash error: {e}")))?;

    Ok(ComposedContract {
        id,
        template_id,
        params: params.clone(),
        rendered_clauses,
        composed_at,
        contract_hash,
        version,
        parent_contract_id,
    })
}

/// Render a composed contract as a human-readable Markdown document.
#[must_use]
pub fn render_markdown(contract: &ComposedContract) -> String {
    let mut md = String::new();

    md.push_str("# Bailment Contract\n\n");
    md.push_str(&format!("**Contract ID**: {}\n", contract.id));
    md.push_str(&format!("**Version**: {}\n", contract.version));
    md.push_str(&format!("**Composed**: {}\n", contract.composed_at));
    md.push_str(&format!(
        "**Effective**: {}\n",
        contract.params.effective_date
    ));
    md.push_str(&format!(
        "**Expires**: {}\n",
        match &contract.params.expiry_date {
            Some(ts) => ts.to_string(),
            None => "No expiration".to_string(),
        }
    ));
    md.push_str(&format!(
        "**Jurisdiction**: {}\n",
        contract.params.jurisdiction
    ));
    md.push_str(&format!(
        "**Data Classification**: {}\n\n",
        contract.params.data_classification
    ));

    md.push_str("## Parties\n\n");
    md.push_str(&format!(
        "- **Bailor**: {} ({})\n",
        contract.params.bailor_name, contract.params.bailor_did
    ));
    md.push_str(&format!(
        "- **Bailee**: {} ({})\n\n",
        contract.params.bailee_name, contract.params.bailee_did
    ));

    for clause in &contract.rendered_clauses {
        md.push_str(&format!(
            "## {}. {}\n\n{}\n\n",
            clause.section_number, clause.title, clause.rendered_body
        ));
    }

    md.push_str("---\n");
    md.push_str(&format!("Contract Hash: {}\n", contract.contract_hash));

    md
}

/// Assess a breach against contract terms.
///
/// Validates that all breached clause IDs exist in the contract, then
/// recommends a remedy based on the breach severity.
///
/// # Errors
///
/// Returns `ConsentError::Denied` if any breached clause ID is not found
/// in the contract.
pub fn assess_breach(
    contract: &ComposedContract,
    breached_clause_ids: &[&str],
    severity: BreachSeverity,
    assessed_at: Timestamp,
) -> Result<BreachAssessment, ConsentError> {
    validate_constructor_metadata("contract id", &contract.id, "assessed_at", &assessed_at)?;

    // Validate all clause IDs exist
    for clause_id in breached_clause_ids {
        if !contract
            .rendered_clauses
            .iter()
            .any(|c| c.clause_id == *clause_id)
        {
            return Err(ConsentError::Denied(format!(
                "Clause '{}' not found in contract '{}'",
                clause_id, contract.id
            )));
        }
    }

    let (liability_bps, remedy) = match severity {
        BreachSeverity::Minor => (0u64, Remedy::Notice),
        BreachSeverity::Material => (
            contract.params.liability_cap_bps / 2,
            Remedy::Cure {
                cure_period_days: 30,
            },
        ),
        BreachSeverity::Fundamental => (
            contract.params.liability_cap_bps,
            Remedy::Indemnification {
                amount_bps: contract.params.liability_cap_bps,
            },
        ),
    };

    Ok(BreachAssessment {
        contract_id: contract.id.clone(),
        breach_severity: severity,
        breached_clauses: breached_clause_ids.iter().map(|s| s.to_string()).collect(),
        liability_assessment_bps: liability_bps,
        recommended_remedy: remedy,
        assessed_at,
    })
}

/// Create an amendment to an existing contract.
///
/// Produces a new `ComposedContract` with incremented version,
/// referencing the original via `parent_contract_id`. Optionally
/// replaces specific clauses and rebinds parameters.
///
/// # Errors
///
/// Returns `ConsentError::Denied` if the version would overflow or hashing fails.
pub fn amend(
    original: &ComposedContract,
    new_params: &ContractParams,
    amended_clauses: &[(String, Clause)],
    id: impl Into<String>,
    composed_at: Timestamp,
) -> Result<ComposedContract, ConsentError> {
    let id = id.into();
    validate_constructor_metadata("contract id", &id, "composed_at", &composed_at)?;

    // Start with original rendered clauses
    let mut clauses: Vec<RenderedClause> = original.rendered_clauses.clone();

    // Apply clause amendments
    for (target_id, new_clause) in amended_clauses {
        if let Some(rc) = clauses.iter_mut().find(|c| c.clause_id == *target_id) {
            rc.clause_id = new_clause.id.clone();
            rc.category = new_clause.category;
            rc.title = new_clause.title.clone();
            rc.rendered_body = substitute_params(&new_clause.body, new_params);
        } else {
            // New clause — append
            let section = format!("{}", clauses.len() + 1);
            clauses.push(RenderedClause {
                clause_id: new_clause.id.clone(),
                category: new_clause.category,
                title: new_clause.title.clone(),
                rendered_body: substitute_params(&new_clause.body, new_params),
                section_number: section,
            });
        }
    }

    // Re-substitute params for existing clauses that weren't explicitly amended
    // (in case params changed — e.g., new bailee name)
    // NOTE: We only re-render non-amended clauses from original template bodies
    // For simplicity, amended clauses are already re-rendered above.

    let new_version = original.version.checked_add(1).ok_or_else(|| {
        ConsentError::Denied(format!(
            "contract version overflow for contract '{}' at version {}",
            original.id, original.version
        ))
    })?;
    let parent_contract_id = Some(original.id.clone());

    let payload = ContractHashPayload {
        template_id: &original.template_id,
        params: new_params,
        rendered_clauses: &clauses,
        version: new_version,
        parent_contract_id: &parent_contract_id,
    };
    let contract_hash =
        hash_structured(&payload).map_err(|e| ConsentError::Denied(format!("Hash error: {e}")))?;

    Ok(ComposedContract {
        id,
        template_id: original.template_id.clone(),
        params: new_params.clone(),
        rendered_clauses: clauses,
        composed_at,
        contract_hash,
        version: new_version,
        parent_contract_id,
    })
}

/// Verify that a contract's hash matches its content.
///
/// Recomputes the hash from the contract's rendered clauses and params,
/// then compares with the stored `contract_hash`.
#[must_use]
pub fn verify_hash(contract: &ComposedContract) -> bool {
    let payload = ContractHashPayload {
        template_id: &contract.template_id,
        params: &contract.params,
        rendered_clauses: &contract.rendered_clauses,
        version: contract.version,
        parent_contract_id: &contract.parent_contract_id,
    };
    match hash_structured(&payload) {
        Ok(computed) => computed == contract.contract_hash,
        Err(_) => false,
    }
}

fn validate_constructor_metadata(
    id_label: &str,
    id: &str,
    timestamp_label: &str,
    timestamp: &Timestamp,
) -> Result<(), ConsentError> {
    if id.trim().is_empty() {
        return Err(ConsentError::Denied(format!(
            "{id_label} must be caller-supplied and non-empty"
        )));
    }
    if *timestamp == Timestamp::ZERO {
        return Err(ConsentError::Denied(format!(
            "{timestamp_label} must be caller-supplied and non-zero"
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Substitute `{{param}}` placeholders in a clause body with values from `ContractParams`.
fn substitute_params(body: &str, params: &ContractParams) -> String {
    let mut result = body.to_string();
    result = result.replace("{{bailor_name}}", &params.bailor_name);
    result = result.replace("{{bailee_name}}", &params.bailee_name);
    result = result.replace("{{bailor_did}}", params.bailor_did.as_str());
    result = result.replace("{{bailee_did}}", params.bailee_did.as_str());
    result = result.replace("{{effective_date}}", &params.effective_date.to_string());
    result = result.replace(
        "{{expiry_date}}",
        &params
            .expiry_date
            .map_or("No expiration".to_string(), |ts| ts.to_string()),
    );
    result = result.replace("{{jurisdiction}}", &params.jurisdiction);
    result = result.replace(
        "{{data_classification}}",
        &params.data_classification.to_string(),
    );
    result = result.replace(
        "{{classification_custody_obligations}}",
        params.data_classification.custody_obligations(),
    );
    result = result.replace(
        "{{classification_processing_obligations}}",
        params.data_classification.processing_obligations(),
    );
    result = result.replace(
        "{{classification_breach_notice}}",
        params.data_classification.breach_notice_obligations(),
    );
    result = result.replace(
        "{{classification_liability_obligations}}",
        params.data_classification.liability_obligations(),
    );
    result = result.replace(
        "{{classification_termination_obligations}}",
        params.data_classification.termination_obligations(),
    );
    result = result.replace(
        "{{liability_cap_bps}}",
        &params.liability_cap_bps.to_string(),
    );

    // Custom params
    for (key, value) in params.custom_params.iter() {
        let placeholder = format!("{{{{{key}}}}}");
        result = result.replace(&placeholder, value);
    }

    result
}

/// Generate standard clauses for Custody bailment type.
fn custody_clauses() -> Vec<Clause> {
    vec![
        Clause {
            id: "custody-data-custody".to_string(),
            category: ClauseCategory::DataCustody,
            title: "Data Custody".to_string(),
            body: "{{bailee_name}} shall hold {{bailor_name}}'s data in secure custody without modification. Data classification: {{data_classification}}. {{classification_custody_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-processing-rights".to_string(),
            category: ClauseCategory::ProcessingRights,
            title: "Processing Rights".to_string(),
            body: "No processing rights are granted. {{bailee_name}} may only store and return data to {{bailor_name}}. Any handling must satisfy: {{classification_processing_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-breach-remedies".to_string(),
            category: ClauseCategory::BreachRemedies,
            title: "Breach Remedies".to_string(),
            body: "Upon breach, {{bailor_name}} shall receive notice under the classification-specific notice rule. {{classification_breach_notice}} Material breaches trigger a 30-day cure period.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-liability-caps".to_string(),
            category: ClauseCategory::LiabilityCaps,
            title: "Liability Caps".to_string(),
            body: "Total liability capped at {{liability_cap_bps}} basis points of assessed value. {{classification_liability_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-dispute-resolution".to_string(),
            category: ClauseCategory::DisputeResolution,
            title: "Dispute Resolution".to_string(),
            body: "Disputes under jurisdiction {{jurisdiction}} resolved via binding arbitration.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-termination".to_string(),
            category: ClauseCategory::Termination,
            title: "Termination".to_string(),
            body: "Either party may terminate with 30 days written notice. Data must be returned or destroyed within 15 days of termination. {{classification_termination_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-jurisdiction".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "Governing Jurisdiction".to_string(),
            body: "This agreement governed by laws of {{jurisdiction}}.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "custody-indemnification".to_string(),
            category: ClauseCategory::Indemnification,
            title: "Indemnification".to_string(),
            body: "{{bailee_name}} shall indemnify {{bailor_name}} against third-party claims arising from {{bailee_name}}'s negligence or breach.".to_string(),
            required: true,
            jurisdiction: None,
        },
    ]
}

/// Generate standard clauses for Processing bailment type.
fn processing_clauses() -> Vec<Clause> {
    vec![
        Clause {
            id: "processing-data-custody".to_string(),
            category: ClauseCategory::DataCustody,
            title: "Data Custody".to_string(),
            body: "{{bailee_name}} shall hold {{bailor_name}}'s data in secure custody. Data classification: {{data_classification}}. {{classification_custody_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-processing-rights".to_string(),
            category: ClauseCategory::ProcessingRights,
            title: "Processing Rights".to_string(),
            body: "{{bailee_name}} may process {{bailor_name}}'s data for purposes defined in this agreement. Processing scope limited to {{data_classification}} tier data. {{classification_processing_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-breach-remedies".to_string(),
            category: ClauseCategory::BreachRemedies,
            title: "Breach Remedies".to_string(),
            body: "Upon breach, {{bailor_name}} shall receive notice under the classification-specific notice rule. {{classification_breach_notice}} Unauthorized processing constitutes a material breach.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-liability-caps".to_string(),
            category: ClauseCategory::LiabilityCaps,
            title: "Liability Caps".to_string(),
            body: "Total liability capped at {{liability_cap_bps}} basis points of assessed value. {{classification_liability_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-dispute-resolution".to_string(),
            category: ClauseCategory::DisputeResolution,
            title: "Dispute Resolution".to_string(),
            body: "Disputes under jurisdiction {{jurisdiction}} resolved via binding arbitration.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-termination".to_string(),
            category: ClauseCategory::Termination,
            title: "Termination".to_string(),
            body: "Either party may terminate with 30 days written notice. All processing must cease immediately upon termination notice. {{classification_termination_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-jurisdiction".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "Governing Jurisdiction".to_string(),
            body: "This agreement governed by laws of {{jurisdiction}}.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "processing-indemnification".to_string(),
            category: ClauseCategory::Indemnification,
            title: "Indemnification".to_string(),
            body: "{{bailee_name}} shall indemnify {{bailor_name}} against third-party claims arising from unauthorized processing or breach.".to_string(),
            required: true,
            jurisdiction: None,
        },
    ]
}

/// Generate standard clauses for Delegation bailment type.
fn delegation_clauses() -> Vec<Clause> {
    vec![
        Clause {
            id: "delegation-data-custody".to_string(),
            category: ClauseCategory::DataCustody,
            title: "Data Custody".to_string(),
            body: "{{bailee_name}} shall hold {{bailor_name}}'s data and may delegate custody to sub-bailees under equivalent terms. Data classification: {{data_classification}}. {{classification_custody_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-processing-rights".to_string(),
            category: ClauseCategory::ProcessingRights,
            title: "Processing Rights".to_string(),
            body: "{{bailee_name}} may process and delegate processing of {{bailor_name}}'s data. Sub-bailees must maintain equivalent or stricter terms. {{classification_processing_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-breach-remedies".to_string(),
            category: ClauseCategory::BreachRemedies,
            title: "Breach Remedies".to_string(),
            body: "Upon breach by {{bailee_name}} or any sub-bailee, {{bailor_name}} shall receive notice under the classification-specific notice rule. {{classification_breach_notice}} {{bailee_name}} remains liable for sub-bailee breaches.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-liability-caps".to_string(),
            category: ClauseCategory::LiabilityCaps,
            title: "Liability Caps".to_string(),
            body: "Total liability capped at {{liability_cap_bps}} basis points. {{bailee_name}} bears full liability for sub-bailee actions. {{classification_liability_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-dispute-resolution".to_string(),
            category: ClauseCategory::DisputeResolution,
            title: "Dispute Resolution".to_string(),
            body: "Disputes under jurisdiction {{jurisdiction}} resolved via binding arbitration. Sub-bailee disputes resolved through {{bailee_name}}.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-termination".to_string(),
            category: ClauseCategory::Termination,
            title: "Termination".to_string(),
            body: "Either party may terminate with 30 days written notice. All sub-bailments must be terminated within 15 days of primary termination. {{classification_termination_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-jurisdiction".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "Governing Jurisdiction".to_string(),
            body: "This agreement governed by laws of {{jurisdiction}}.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "delegation-indemnification".to_string(),
            category: ClauseCategory::Indemnification,
            title: "Indemnification".to_string(),
            body: "{{bailee_name}} shall indemnify {{bailor_name}} against all claims arising from sub-bailee actions.".to_string(),
            required: true,
            jurisdiction: None,
        },
    ]
}

/// Generate standard clauses for Emergency bailment type.
fn emergency_clauses() -> Vec<Clause> {
    vec![
        Clause {
            id: "emergency-data-custody".to_string(),
            category: ClauseCategory::DataCustody,
            title: "Emergency Data Custody".to_string(),
            body: "{{bailee_name}} granted emergency access to {{bailor_name}}'s data. Access expires {{expiry_date}}. Justification required for all access. Data classification: {{data_classification}}. {{classification_custody_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-processing-rights".to_string(),
            category: ClauseCategory::ProcessingRights,
            title: "Emergency Processing Rights".to_string(),
            body: "{{bailee_name}} may process data only as necessary for emergency resolution. Processing scope: {{data_classification}} tier data. All processing must be logged. {{classification_processing_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-breach-remedies".to_string(),
            category: ClauseCategory::BreachRemedies,
            title: "Breach Remedies".to_string(),
            body: "Upon breach, {{bailor_name}} shall receive immediate notice and the classification-specific notice rule applies. {{classification_breach_notice}} Emergency access revoked instantly upon breach detection.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-liability-caps".to_string(),
            category: ClauseCategory::LiabilityCaps,
            title: "Liability Caps".to_string(),
            body: "Total liability capped at {{liability_cap_bps}} basis points. Emergency access carries elevated liability. {{classification_liability_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-dispute-resolution".to_string(),
            category: ClauseCategory::DisputeResolution,
            title: "Dispute Resolution".to_string(),
            body: "Disputes under jurisdiction {{jurisdiction}} resolved via expedited arbitration due to emergency nature.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-termination".to_string(),
            category: ClauseCategory::Termination,
            title: "Termination".to_string(),
            body: "Emergency access automatically terminates at {{expiry_date}}. Either party may terminate immediately with written notice. {{classification_termination_obligations}}".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-jurisdiction".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "Governing Jurisdiction".to_string(),
            body: "This agreement governed by laws of {{jurisdiction}}.".to_string(),
            required: true,
            jurisdiction: None,
        },
        Clause {
            id: "emergency-indemnification".to_string(),
            category: ClauseCategory::Indemnification,
            title: "Indemnification".to_string(),
            body: "{{bailee_name}} shall indemnify {{bailor_name}} against all claims arising from emergency access misuse.".to_string(),
            required: true,
            jurisdiction: None,
        },
    ]
}

// ===========================================================================
// Tests
// ===========================================================================

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

    // -- Helpers --

    fn alice_did() -> Did {
        Did::new("did:exo:alice").unwrap()
    }

    fn bob_did() -> Did {
        Did::new("did:exo:bob").unwrap()
    }

    fn test_params() -> ContractParams {
        ContractParams {
            bailor_name: "Alice Corp".to_string(),
            bailee_name: "Bob Services".to_string(),
            bailor_did: alice_did(),
            bailee_did: bob_did(),
            effective_date: Timestamp::new(1_700_000_000_000, 0),
            expiry_date: Some(Timestamp::new(1_800_000_000_000, 0)),
            jurisdiction: "US-DE".to_string(),
            data_classification: DataClassification::Confidential,
            liability_cap_bps: 5000, // 50%
            custom_params: DeterministicMap::new(),
        }
    }

    fn test_params_with_classification(data_classification: DataClassification) -> ContractParams {
        let mut params = test_params();
        params.data_classification = data_classification;
        params
    }

    fn ts(ms: u64) -> Timestamp {
        Timestamp::new(ms, 0)
    }

    fn compose_test(template: &ContractTemplate, params: &ContractParams) -> ComposedContract {
        compose(template, params, "contract-test", ts(1_700_000_000_100))
            .expect("test contract composition")
    }

    fn compose_test_with_metadata(
        template: &ContractTemplate,
        params: &ContractParams,
        id: &str,
        composed_at: Timestamp,
    ) -> ComposedContract {
        compose(template, params, id, composed_at).expect("test contract composition metadata")
    }

    fn assess_breach_test(
        contract: &ComposedContract,
        breached_clause_ids: &[&str],
        severity: BreachSeverity,
    ) -> BreachAssessment {
        assess_breach(
            contract,
            breached_clause_ids,
            severity,
            ts(1_700_000_000_200),
        )
        .expect("test breach assessment")
    }

    fn amend_test(
        original: &ComposedContract,
        new_params: &ContractParams,
        amended_clauses: &[(String, Clause)],
    ) -> ComposedContract {
        amend(
            original,
            new_params,
            amended_clauses,
            "contract-amendment-test",
            ts(1_700_000_000_300),
        )
        .expect("test amendment")
    }

    fn compose_custody() -> ComposedContract {
        let template = default_template(BailmentType::Custody);
        compose_test(&template, &test_params())
    }

    fn rendered_contract_body(contract: &ComposedContract) -> String {
        contract
            .rendered_clauses
            .iter()
            .map(|clause| clause.rendered_body.clone())
            .collect::<Vec<_>>()
            .join(" ")
    }

    #[test]
    fn contract_constructors_have_no_internal_entropy_or_wall_clock() {
        let source = include_str!("contract.rs");
        let uuid_pattern = format!("{}{}", "Uuid::", "new_v4()");
        let now_pattern = format!("{}{}", "Timestamp::", "now_utc()");

        assert!(
            !source.contains(&uuid_pattern),
            "contract constructors must receive caller-supplied IDs"
        );
        assert!(
            !source.contains(&now_pattern),
            "contract constructors must receive caller-supplied HLC timestamps"
        );
    }

    #[test]
    fn compose_uses_caller_supplied_metadata() {
        let template = default_template(BailmentType::Custody);
        let contract =
            compose_test_with_metadata(&template, &test_params(), "contract-explicit", ts(4321));

        assert_eq!(contract.id, "contract-explicit");
        assert_eq!(contract.composed_at, ts(4321));
        assert_eq!(contract.version, 1);
        assert_eq!(contract.parent_contract_id, None);
    }

    #[test]
    fn compose_rejects_empty_id() {
        let template = default_template(BailmentType::Custody);
        let err = compose(&template, &test_params(), " ", ts(1000)).unwrap_err();

        assert_eq!(
            err,
            ConsentError::Denied("contract id must be caller-supplied and non-empty".into())
        );
    }

    #[test]
    fn compose_rejects_zero_composed_at() {
        let template = default_template(BailmentType::Custody);
        let err = compose(
            &template,
            &test_params(),
            "contract-explicit",
            Timestamp::ZERO,
        )
        .unwrap_err();

        assert_eq!(
            err,
            ConsentError::Denied("composed_at must be caller-supplied and non-zero".into())
        );
    }

    #[test]
    fn assess_breach_uses_caller_supplied_timestamp() {
        let contract = compose_custody();
        let clause_id = contract.rendered_clauses[0].clause_id.as_str();
        let assessment = assess_breach(&contract, &[clause_id], BreachSeverity::Minor, ts(4567))
            .expect("breach assessment");

        assert_eq!(assessment.assessed_at, ts(4567));
    }

    #[test]
    fn assess_breach_rejects_zero_timestamp() {
        let contract = compose_custody();
        let clause_id = contract.rendered_clauses[0].clause_id.as_str();
        let err = assess_breach(
            &contract,
            &[clause_id],
            BreachSeverity::Minor,
            Timestamp::ZERO,
        )
        .unwrap_err();

        assert_eq!(
            err,
            ConsentError::Denied("assessed_at must be caller-supplied and non-zero".into())
        );
    }

    #[test]
    fn amend_uses_caller_supplied_metadata() {
        let original = compose_custody();
        let amended = amend(
            &original,
            &test_params(),
            &[],
            "contract-amendment-explicit",
            ts(5678),
        )
        .expect("amendment");

        assert_eq!(amended.id, "contract-amendment-explicit");
        assert_eq!(amended.composed_at, ts(5678));
        assert_eq!(amended.parent_contract_id, Some(original.id.clone()));
    }

    #[test]
    fn amend_rejects_placeholder_metadata() {
        let original = compose_custody();

        let empty_id = amend(&original, &test_params(), &[], " ", ts(5678)).unwrap_err();
        assert_eq!(
            empty_id,
            ConsentError::Denied("contract id must be caller-supplied and non-empty".into())
        );

        let zero_time = amend(
            &original,
            &test_params(),
            &[],
            "contract-amendment-explicit",
            Timestamp::ZERO,
        )
        .unwrap_err();
        assert_eq!(
            zero_time,
            ConsentError::Denied("composed_at must be caller-supplied and non-zero".into())
        );
    }

    // All 8 clause categories
    fn all_categories() -> Vec<ClauseCategory> {
        vec![
            ClauseCategory::DataCustody,
            ClauseCategory::ProcessingRights,
            ClauseCategory::BreachRemedies,
            ClauseCategory::LiabilityCaps,
            ClauseCategory::DisputeResolution,
            ClauseCategory::Termination,
            ClauseCategory::Jurisdiction,
            ClauseCategory::Indemnification,
        ]
    }

    // -- Test 1: default template for Custody has all required clause categories --

    #[test]
    fn test_default_template_custody() {
        let template = default_template(BailmentType::Custody);
        assert_eq!(template.bailment_type, BailmentType::Custody);
        assert_eq!(template.clauses.len(), 8);

        let categories: Vec<ClauseCategory> = template.clauses.iter().map(|c| c.category).collect();
        for cat in all_categories() {
            assert!(
                categories.contains(&cat),
                "Custody template missing category: {cat:?}"
            );
        }

        // All clauses required
        assert!(template.clauses.iter().all(|c| c.required));
    }

    // -- Test 2: default template for Processing has all required clause categories --

    #[test]
    fn test_default_template_processing() {
        let template = default_template(BailmentType::Processing);
        assert_eq!(template.bailment_type, BailmentType::Processing);
        assert_eq!(template.clauses.len(), 8);

        let categories: Vec<ClauseCategory> = template.clauses.iter().map(|c| c.category).collect();
        for cat in all_categories() {
            assert!(
                categories.contains(&cat),
                "Processing template missing category: {cat:?}"
            );
        }

        assert!(template.clauses.iter().all(|c| c.required));
    }

    // -- Test 3: compose substitutes params --

    #[test]
    fn test_compose_substitutes_params() {
        let contract = compose_custody();

        // Check that param values appear in rendered clauses
        let all_bodies: String = contract
            .rendered_clauses
            .iter()
            .map(|c| c.rendered_body.clone())
            .collect::<Vec<_>>()
            .join(" ");

        assert!(
            all_bodies.contains("Alice Corp"),
            "Bailor name not substituted"
        );
        assert!(
            all_bodies.contains("Bob Services"),
            "Bailee name not substituted"
        );
        assert!(all_bodies.contains("US-DE"), "Jurisdiction not substituted");
        assert!(
            all_bodies.contains("Confidential"),
            "Data classification not substituted"
        );
        assert!(all_bodies.contains("5000"), "Liability cap not substituted");

        // No unsubstituted placeholders
        assert!(
            !all_bodies.contains("{{"),
            "Unsubstituted placeholders remain"
        );
    }

    #[test]
    fn data_classification_renders_tier_specific_obligations() {
        let template = default_template(BailmentType::Processing);
        let cases = [
            (
                DataClassification::Public,
                "Public data may be stored with baseline integrity controls",
                "Public data processing is limited to authorized use",
                "Public classification breaches require notice within 10 business days",
                "Public data liability remains limited to integrity, availability, and attribution failures",
                "Public data must be returned, deleted, or left published according to the bailor's written instruction",
            ),
            (
                DataClassification::Internal,
                "Internal data requires organization-scoped access controls",
                "Internal data processing is limited to personnel, services, and agents operating under the bailee's internal authorization boundary",
                "Internal classification breaches require notice within 5 business days",
                "Internal data liability includes unauthorized internal disclosure and unauthorized retention",
                "Internal data must be returned or deleted with an internal access revocation record",
            ),
            (
                DataClassification::Confidential,
                "Confidential data requires least-privilege access, encrypted storage, encrypted transfer, and access logging",
                "Confidential data processing requires purpose-bound authorization and prohibits secondary use without signed amendment",
                "Confidential classification breaches require notice within 72 hours",
                "Confidential data liability includes unauthorized disclosure, unauthorized processing, and control failure",
                "Confidential data must be returned or destroyed with verifiable destruction evidence",
            ),
            (
                DataClassification::Restricted,
                "Restricted data requires documented need-to-know approval, segregated storage, encrypted transfer, and dual-control access for export",
                "Restricted data processing is limited to named workflows and named operators",
                "Restricted classification breaches require notice within 24 hours",
                "Restricted data liability includes unauthorized access, export, delegation, or segregation failure",
                "Restricted data must be quarantined immediately on termination until return or destruction is receipt-backed",
            ),
            (
                DataClassification::Regulated,
                "Regulated data requires statutory control mapping, jurisdiction-specific handling, audit-ready access logs, and retention policy enforcement",
                "Regulated data processing is limited to enumerated legal bases and auditable processing records",
                "Regulated classification breaches require notice within the shortest applicable legal window, not exceeding 24 hours",
                "Regulated data liability includes regulatory reporting failure, unlawful processing, and retention violation",
                "Regulated data must follow the governing retention schedule and produce a compliance evidence package on termination",
            ),
        ];

        let mut rendered_bodies = Vec::new();
        for (
            classification,
            custody_obligation,
            processing_obligation,
            breach_obligation,
            liability_obligation,
            termination_obligation,
        ) in cases
        {
            let contract =
                compose_test(&template, &test_params_with_classification(classification));
            let body = rendered_contract_body(&contract);
            assert!(
                body.contains(custody_obligation),
                "{classification:?} custody obligation missing"
            );
            assert!(
                body.contains(processing_obligation),
                "{classification:?} processing obligation missing"
            );
            assert!(
                body.contains(breach_obligation),
                "{classification:?} breach obligation missing"
            );
            assert!(
                body.contains(liability_obligation),
                "{classification:?} liability obligation missing"
            );
            assert!(
                body.contains(termination_obligation),
                "{classification:?} termination obligation missing"
            );
            rendered_bodies.push((classification, body));
        }

        for (index, (left_classification, left_body)) in rendered_bodies.iter().enumerate() {
            for (right_classification, right_body) in rendered_bodies.iter().skip(index + 1) {
                assert_ne!(
                    left_body, right_body,
                    "{left_classification:?} and {right_classification:?} rendered identical contract bodies"
                );
            }
        }
    }

    #[test]
    fn standard_templates_bind_classification_obligation_placeholders() {
        for bailment_type in [
            BailmentType::Custody,
            BailmentType::Processing,
            BailmentType::Delegation,
            BailmentType::Emergency,
        ] {
            let template = default_template(bailment_type);
            let template_body = template
                .clauses
                .iter()
                .map(|clause| clause.body.clone())
                .collect::<Vec<_>>()
                .join(" ");
            for placeholder in [
                "{{classification_custody_obligations}}",
                "{{classification_processing_obligations}}",
                "{{classification_breach_notice}}",
                "{{classification_liability_obligations}}",
                "{{classification_termination_obligations}}",
            ] {
                assert!(
                    template_body.contains(placeholder),
                    "{bailment_type:?} standard clauses must bind {placeholder}"
                );
            }
        }
    }

    // -- Test 4: compose produces deterministic hash --

    #[test]
    fn test_compose_produces_deterministic_hash() {
        let template = default_template(BailmentType::Custody);
        let params = test_params();

        let c1 = compose_test(&template, &params);
        let c2 = compose_test(&template, &params);

        // Caller-supplied metadata is stable, and content hash is stable.
        assert_eq!(c1.id, c2.id);
        assert_eq!(c1.composed_at, c2.composed_at);
        assert_eq!(c1.contract_hash, c2.contract_hash);
    }

    // -- Test 5: compose hash changes with different params --

    #[test]
    fn test_compose_hash_changes_with_params() {
        let template = default_template(BailmentType::Custody);
        let params1 = test_params();
        let mut params2 = test_params();
        params2.liability_cap_bps = 9999;

        let c1 = compose_test(&template, &params1);
        let c2 = compose_test(&template, &params2);

        assert_ne!(c1.contract_hash, c2.contract_hash);
    }

    // -- Test 6: render markdown has all sections --

    #[test]
    fn test_render_markdown_has_all_sections() {
        let contract = compose_custody();
        let md = render_markdown(&contract);

        // Check all clause titles appear
        for clause in &contract.rendered_clauses {
            assert!(
                md.contains(&clause.title),
                "Markdown missing clause title: {}",
                clause.title
            );
            assert!(
                md.contains(&format!("{}.", clause.section_number)),
                "Markdown missing section number: {}",
                clause.section_number
            );
        }

        // Check structural elements
        assert!(md.contains("# Bailment Contract"));
        assert!(md.contains("## Parties"));
        assert!(md.contains("Contract Hash:"));
    }

    // -- Test 7: render markdown contains party names --

    #[test]
    fn test_render_markdown_party_names() {
        let contract = compose_custody();
        let md = render_markdown(&contract);

        assert!(
            md.contains("Alice Corp"),
            "Bailor name missing from markdown"
        );
        assert!(
            md.contains("Bob Services"),
            "Bailee name missing from markdown"
        );
        assert!(
            md.contains("did:exo:alice"),
            "Bailor DID missing from markdown"
        );
        assert!(
            md.contains("did:exo:bob"),
            "Bailee DID missing from markdown"
        );
    }

    // -- Test 8: breach assessment minor → Notice --

    #[test]
    fn test_breach_assessment_minor() {
        let contract = compose_custody();
        let clause_id = contract.rendered_clauses[0].clause_id.as_str();

        let assessment = assess_breach_test(&contract, &[clause_id], BreachSeverity::Minor);

        assert_eq!(assessment.breach_severity, BreachSeverity::Minor);
        assert_eq!(assessment.recommended_remedy, Remedy::Notice);
        assert_eq!(assessment.liability_assessment_bps, 0);
    }

    // -- Test 9: breach assessment material → Cure --

    #[test]
    fn test_breach_assessment_material() {
        let contract = compose_custody();
        let clause_id = contract.rendered_clauses[0].clause_id.as_str();

        let assessment = assess_breach_test(&contract, &[clause_id], BreachSeverity::Material);

        assert_eq!(assessment.breach_severity, BreachSeverity::Material);
        assert_eq!(
            assessment.recommended_remedy,
            Remedy::Cure {
                cure_period_days: 30
            }
        );
        assert_eq!(assessment.liability_assessment_bps, 2500); // 5000 / 2
    }

    // -- Test 10: breach assessment fundamental → Termination + Indemnification --

    #[test]
    fn test_breach_assessment_fundamental() {
        let contract = compose_custody();
        let clause_id = contract.rendered_clauses[0].clause_id.as_str();

        let assessment = assess_breach_test(&contract, &[clause_id], BreachSeverity::Fundamental);

        assert_eq!(assessment.breach_severity, BreachSeverity::Fundamental);
        assert_eq!(
            assessment.recommended_remedy,
            Remedy::Indemnification { amount_bps: 5000 }
        );
        assert_eq!(assessment.liability_assessment_bps, 5000);
    }

    // -- Test 11: breach with invalid clause ID → error --

    #[test]
    fn test_breach_invalid_clause_id() {
        let contract = compose_custody();

        let result = assess_breach(
            &contract,
            &["nonexistent-clause"],
            BreachSeverity::Minor,
            ts(1_700_000_000_200),
        );

        assert!(result.is_err());
        match result {
            Err(ConsentError::Denied(msg)) => {
                assert!(msg.contains("nonexistent-clause"));
            }
            other => panic!("Expected Denied error, got: {other:?}"),
        }
    }

    // -- Test 12: amend creates new version --

    #[test]
    fn test_amend_creates_new_version() {
        let original = compose_custody();
        let new_params = test_params();

        let amended = amend_test(&original, &new_params, &[]);

        assert_eq!(amended.version, original.version + 1);
        assert_eq!(amended.parent_contract_id, Some(original.id.clone()));
        assert_ne!(amended.id, original.id);
    }

    #[test]
    fn test_amend_rejects_version_overflow() {
        let mut original = compose_custody();
        original.version = u32::MAX;

        let err = amend(
            &original,
            &test_params(),
            &[],
            "overflow-amendment",
            ts(1_700_000_000_350),
        )
        .unwrap_err();

        match err {
            ConsentError::Denied(reason) => {
                assert!(reason.contains("contract version overflow"));
                assert!(reason.contains(&original.id));
            }
            other => panic!("expected denial for version overflow, got {other:?}"),
        }
    }

    // -- Test 13: amend preserves parent hash --

    #[test]
    fn test_amend_preserves_parent_hash() {
        let original = compose_custody();
        let original_hash = original.contract_hash;

        let mut new_params = test_params();
        new_params.liability_cap_bps = 9000;

        let _amended = amend_test(&original, &new_params, &[]);

        // Original's hash is unchanged
        assert_eq!(original.contract_hash, original_hash);
    }

    // -- Test 14: verify hash valid --

    #[test]
    fn test_verify_hash_valid() {
        let contract = compose_custody();
        assert!(verify_hash(&contract));
    }

    #[test]
    fn verify_hash_rejects_tampered_amendment_parent_contract_id() {
        let original = compose_custody();
        let mut amended = amend_test(&original, &test_params(), &[]);

        assert!(verify_hash(&amended));

        amended.parent_contract_id = Some("contract-forged-parent".to_string());
        assert!(!verify_hash(&amended));

        let mut orphaned = amend_test(&original, &test_params(), &[]);
        orphaned.parent_contract_id = None;
        assert!(!verify_hash(&orphaned));
    }

    // -- Test 15: verify hash tampered --

    #[test]
    fn test_verify_hash_tampered() {
        let mut contract = compose_custody();
        // Tamper with a rendered clause
        contract.rendered_clauses[0].rendered_body = "TAMPERED CONTENT".to_string();
        assert!(!verify_hash(&contract));
    }

    // -- Test 16: no floating point --

    #[test]
    fn test_no_floating_point() {
        let contract = compose_custody();

        // liability_cap_bps is u64
        let _cap: u64 = contract.params.liability_cap_bps;
        assert_eq!(contract.params.liability_cap_bps, 5000u64);

        // Breach assessment also uses u64
        let clause_id = contract.rendered_clauses[0].clause_id.as_str();
        let assessment = assess_breach_test(&contract, &[clause_id], BreachSeverity::Material);
        let _liability: u64 = assessment.liability_assessment_bps;
        assert_eq!(assessment.liability_assessment_bps, 2500u64);

        // Verify no f32/f64 by ensuring values are exact integer division
        assert_eq!(5000u64 / 2, 2500u64);
    }

    // -- Test 17: default template for Delegation --

    #[test]
    fn test_default_template_delegation() {
        let template = default_template(BailmentType::Delegation);
        assert_eq!(template.bailment_type, BailmentType::Delegation);
        assert_eq!(template.id, "delegation-standard-v1");
        assert_eq!(template.name, "Standard Delegation Agreement");
        assert!(!template.clauses.is_empty());
        // All clauses must be required by default.
        assert!(template.clauses.iter().all(|c| c.required));
        // Must cover the delegation-specific ProcessingRights category.
        let cats: Vec<ClauseCategory> = template.clauses.iter().map(|c| c.category).collect();
        assert!(cats.contains(&ClauseCategory::ProcessingRights));
    }

    // -- Test 18: default template for Emergency --

    #[test]
    fn test_default_template_emergency() {
        let template = default_template(BailmentType::Emergency);
        assert_eq!(template.bailment_type, BailmentType::Emergency);
        assert_eq!(template.id, "emergency-standard-v1");
        assert_eq!(template.name, "Emergency Access Agreement");
        assert!(!template.clauses.is_empty());
        assert!(template.clauses.iter().all(|c| c.required));
        // Must cover Termination clauses — emergencies expire fast.
        let cats: Vec<ClauseCategory> = template.clauses.iter().map(|c| c.category).collect();
        assert!(cats.contains(&ClauseCategory::Termination));
    }

    // -- Test 19: compose with a Delegation template composes + hashes --

    #[test]
    fn test_compose_delegation_template_succeeds() {
        let template = default_template(BailmentType::Delegation);
        let contract = compose_test(&template, &test_params());
        assert!(!contract.rendered_clauses.is_empty());
        assert_ne!(contract.contract_hash, Hash256::ZERO);
        // Section numbering is monotonic from 1.
        for (i, rc) in contract.rendered_clauses.iter().enumerate() {
            assert_eq!(rc.section_number, format!("{}", i + 1));
        }
    }

    // -- Test 20: compose with an Emergency template composes + hashes --

    #[test]
    fn test_compose_emergency_template_succeeds() {
        let template = default_template(BailmentType::Emergency);
        let contract = compose_test(&template, &test_params());
        assert!(!contract.rendered_clauses.is_empty());
        assert_ne!(contract.contract_hash, Hash256::ZERO);
    }

    // -- Test 21: compose skips OPTIONAL clause with jurisdiction mismatch --

    #[test]
    fn test_compose_skips_optional_foreign_jurisdiction_clause() {
        // Build a template with one required EU-only clause and one optional EU-only
        // clause. Required must match the caller jurisdiction; optional may be dropped.
        let mut template = default_template(BailmentType::Custody);
        template.clauses.push(Clause {
            id: "optional-eu-only".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "EU-Only Optional".to_string(),
            body: "GDPR-specific clause body.".to_string(),
            required: false,
            jurisdiction: Some("EU-DE".to_string()),
        });

        let contract = compose_test(&template, &test_params());
        assert!(
            contract
                .rendered_clauses
                .iter()
                .all(|c| c.clause_id != "optional-eu-only"),
            "Optional foreign-jurisdiction clause must be filtered out"
        );
    }

    // -- Test 22: compose ERRORS when a REQUIRED clause has wrong jurisdiction --

    #[test]
    fn test_compose_errors_on_required_foreign_jurisdiction_clause() {
        let mut template = default_template(BailmentType::Custody);
        template.clauses.push(Clause {
            id: "required-eu-only".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "EU-Only Required".to_string(),
            body: "GDPR-specific clause body.".to_string(),
            required: true,
            jurisdiction: Some("EU-DE".to_string()),
        });

        // test_params() uses "US-DE" — the required EU clause cannot apply.
        let result = compose(
            &template,
            &test_params(),
            "contract-test",
            ts(1_700_000_000_100),
        );
        match result {
            Err(ConsentError::Denied(msg)) => {
                assert!(msg.contains("required-eu-only"));
                assert!(msg.contains("EU-DE"));
                assert!(msg.contains("US-DE"));
            }
            other => panic!("Expected Denied error, got: {other:?}"),
        }
    }

    // -- Test 23: compose keeps a clause whose jurisdiction matches --

    #[test]
    fn test_compose_keeps_matching_jurisdiction_clause() {
        let mut template = default_template(BailmentType::Custody);
        template.clauses.push(Clause {
            id: "matching-us-clause".to_string(),
            category: ClauseCategory::Jurisdiction,
            title: "US-DE Specific".to_string(),
            body: "Delaware-specific clause body.".to_string(),
            required: false,
            jurisdiction: Some("US-DE".to_string()),
        });

        let contract = compose_test(&template, &test_params());
        assert!(
            contract
                .rendered_clauses
                .iter()
                .any(|c| c.clause_id == "matching-us-clause"),
            "Matching-jurisdiction clause must be included"
        );
    }

    // -- Test 24: amend REPLACES a named existing clause --

    #[test]
    fn test_amend_replaces_existing_clause() {
        let original = compose_custody();
        let target_id = original.rendered_clauses[0].clause_id.clone();

        let replacement = Clause {
            id: "custody-v2-revised".to_string(),
            category: ClauseCategory::DataCustody,
            title: "Revised Custody".to_string(),
            body:
                "Revised custody terms: Data must be returned to {{bailor_name}} upon termination."
                    .to_string(),
            required: true,
            jurisdiction: None,
        };

        let amended = amend(
            &original,
            &test_params(),
            &[(target_id.clone(), replacement.clone())],
            "contract-amendment-test",
            ts(1_700_000_000_300),
        )
        .unwrap();

        // Original clause count preserved (replacement, not insertion).
        assert_eq!(
            amended.rendered_clauses.len(),
            original.rendered_clauses.len()
        );
        // The slot previously named by `target_id` now carries the new clause_id.
        assert!(
            amended
                .rendered_clauses
                .iter()
                .any(|c| c.clause_id == "custody-v2-revised"),
            "Replacement clause must appear in amended contract"
        );
        // And the original id is gone.
        assert!(
            amended
                .rendered_clauses
                .iter()
                .all(|c| c.clause_id != target_id),
            "Original clause id must be replaced"
        );
        // The replacement body was parameter-substituted.
        let revised_body = amended
            .rendered_clauses
            .iter()
            .find(|c| c.clause_id == "custody-v2-revised")
            .map(|c| c.rendered_body.clone())
            .unwrap();
        assert!(
            revised_body.contains("Alice Corp"),
            "Replacement must have params substituted"
        );
        assert!(!revised_body.contains("{{"));
    }

    // -- Test 25: amend APPENDS a new clause when target_id is not in original --

    #[test]
    fn test_amend_appends_new_clause_when_not_present() {
        let original = compose_custody();
        let original_len = original.rendered_clauses.len();

        let new_clause = Clause {
            id: "new-amendment-clause".to_string(),
            category: ClauseCategory::Indemnification,
            title: "New Indemnification Rider".to_string(),
            body: "Added by amendment for {{bailee_name}}.".to_string(),
            required: true,
            jurisdiction: None,
        };

        let amended = amend(
            &original,
            &test_params(),
            &[("NON-EXISTENT-CLAUSE-ID".to_string(), new_clause)],
            "contract-amendment-test",
            ts(1_700_000_000_300),
        )
        .unwrap();

        assert_eq!(
            amended.rendered_clauses.len(),
            original_len + 1,
            "Unknown target_id must APPEND rather than replace"
        );
        let appended = amended
            .rendered_clauses
            .last()
            .expect("amended contract has at least one clause");
        assert_eq!(appended.clause_id, "new-amendment-clause");
        assert_eq!(
            appended.section_number,
            format!("{}", original_len + 1),
            "Appended clause must take the next section number"
        );
        assert!(appended.rendered_body.contains("Bob Services"));
    }

    // -- Test 26: amend with multiple operations in one call --

    #[test]
    fn test_amend_replace_and_append_mixed() {
        let original = compose_custody();
        let target_id = original.rendered_clauses[1].clause_id.clone();

        let replacement = Clause {
            id: "replacement-mixed".to_string(),
            category: original.rendered_clauses[1].category,
            title: "Replacement".to_string(),
            body: "Replaced text for {{jurisdiction}}.".to_string(),
            required: true,
            jurisdiction: None,
        };
        let addition = Clause {
            id: "addition-mixed".to_string(),
            category: ClauseCategory::DisputeResolution,
            title: "Additional".to_string(),
            body: "Added text.".to_string(),
            required: true,
            jurisdiction: None,
        };

        let amended = amend(
            &original,
            &test_params(),
            &[
                (target_id, replacement),
                ("UNKNOWN-ID".to_string(), addition),
            ],
            "contract-amendment-test",
            ts(1_700_000_000_300),
        )
        .unwrap();

        // Replacement kept the length; addition bumped it by 1.
        assert_eq!(
            amended.rendered_clauses.len(),
            original.rendered_clauses.len() + 1
        );
        assert!(
            amended
                .rendered_clauses
                .iter()
                .any(|c| c.clause_id == "replacement-mixed")
        );
        assert!(
            amended
                .rendered_clauses
                .iter()
                .any(|c| c.clause_id == "addition-mixed")
        );
    }

    // -- Test 27: amend hash differs from original --

    #[test]
    fn test_amend_changes_contract_hash() {
        let original = compose_custody();
        let amended = amend_test(&original, &test_params(), &[]);
        // Version differs (original = 1, amended = 2), so payload differs,
        // so hash must differ.
        assert_ne!(amended.contract_hash, original.contract_hash);
    }

    // -- Test 28: render_markdown emits "No expiration" when expiry_date is None --

    #[test]
    fn test_render_markdown_no_expiration() {
        let template = default_template(BailmentType::Custody);
        let mut params = test_params();
        params.expiry_date = None;
        let contract = compose_test(&template, &params);

        let md = render_markdown(&contract);
        assert!(
            md.contains("**Expires**: No expiration"),
            "Expected 'No expiration' line in Markdown; got:\n{md}"
        );
    }

    // -- Test 29: render_markdown emits the expiry timestamp when present --

    #[test]
    fn test_render_markdown_includes_expiry_when_set() {
        let contract = compose_custody();
        let md = render_markdown(&contract);
        // The default test_params sets expiry_date = Some(1_800_000_000_000 ms).
        assert!(
            md.contains("1800000000000")
                || md.contains("1_800_000_000_000")
                || md.contains("2027")
                || md.contains("Expires"),
            "Expected a non-'No expiration' Expires line; got:\n{md}"
        );
        assert!(
            !md.contains("**Expires**: No expiration"),
            "Should not render 'No expiration' when expiry is set"
        );
    }

    // -- Test 30: verify_hash returns false when params tampered --

    #[test]
    fn test_verify_hash_rejects_tampered_params() {
        let mut contract = compose_custody();
        // Tamper with the bailor name — this is inside the hashed payload.
        contract.params.bailor_name = "Malicious Party".to_string();
        assert!(!verify_hash(&contract));
    }

    // -- Test 31: verify_hash returns false when version bumped without rehashing --

    #[test]
    fn test_verify_hash_rejects_tampered_version() {
        let mut contract = compose_custody();
        contract.version = contract.version.saturating_add(1);
        assert!(!verify_hash(&contract));
    }

    // -- Test 32: compose with a template whose ALL clauses are required and
    //            whose jurisdictions are None produces all clauses --

    #[test]
    fn test_compose_includes_all_jurisdiction_neutral_required_clauses() {
        let template = default_template(BailmentType::Custody);
        // Default template clauses all have jurisdiction: None.
        let contract = compose_test(&template, &test_params());
        assert_eq!(contract.rendered_clauses.len(), template.clauses.len());
    }

    // -- Test 33: breach with multiple clause IDs (all valid) --

    #[test]
    fn test_breach_multiple_clauses() {
        let contract = compose_custody();
        let id0 = contract.rendered_clauses[0].clause_id.clone();
        let id1 = contract.rendered_clauses[1].clause_id.clone();

        let a = assess_breach_test(&contract, &[&id0, &id1], BreachSeverity::Material);
        assert_eq!(a.breached_clauses.len(), 2);
        assert!(a.breached_clauses.contains(&id0));
        assert!(a.breached_clauses.contains(&id1));
    }
}