canic-host 0.110.53

Host-side App build and desired-state Fleet reconciliation library for Canic workspaces
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
//! Module: fleet_ensure::model
//!
//! Responsibility: own current-generation Fleet reconciliation state and conservation records.
//! Does not own: transport parsing, policy decisions, persistence, or IC effects.
//! Boundary: workflow persists these records before and after every effect.

pub mod attempt_recovery;
pub mod capacity_import;
pub mod clean_reinstall;
pub mod completed_operation;
pub mod funding_observation;
pub mod infrastructure_bootstrap;
pub mod operator_mint;
pub mod release;
pub(in crate::fleet_ensure) mod serialization;
pub mod terminal;

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

pub const FLEET_ENSURE_SCHEMA_VERSION: u16 = 1;
pub const MAX_FLEET_ENSURE_CANISTERS: usize = 4_096;
pub const MAX_FLEET_ENSURE_PROTOCOL_STEPS: usize = 4_096;

/// Host concurrency bound for admitted independent effects, not total plan capacity.
pub(in crate::fleet_ensure) const MAX_INDEPENDENT_EFFECTS_IN_FLIGHT: usize = 4;

/// One exact observed canister state used by planning and effect reconciliation.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct LiveCanister {
    pub canister_version: Option<u64>,
    pub controllers: Vec<String>,
    #[serde(with = "u128_text")]
    pub cycles: u128,
    pub module_sha256: Option<String>,
    pub principal: String,
    pub reinstall_required: bool,
    pub root_owned_lifecycle: Option<RootOwnedCanisterLifecycle>,
    pub status: CanisterRuntimeStatus,
}

/// Root-owned lifecycle of one explicitly seeded paid canister.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RootOwnedCanisterLifecycle {
    Claimed,
    Idle,
    /// Live PendingReset/Failed asset; funding belongs to pool reconciliation.
    Reconciling,
    /// Last exact current-generation balance retained while Root status is fenced.
    Retained,
    Store,
    Workload,
}

impl RootOwnedCanisterLifecycle {
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Claimed => "claimed",
            Self::Idle => "idle",
            Self::Reconciling => "reconciling",
            Self::Retained => "retained",
            Self::Store => "store",
            Self::Workload => "workload",
        }
    }
}

/// Management status relevant to reconciliation.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CanisterRuntimeStatus {
    Running,
    Stopped,
    Stopping,
}

/// Complete live snapshot of the explicitly controlled Fleet estate.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct FleetObservation {
    pub additional_controlled_cycles: BTreeMap<String, u128>,
    pub canisters: BTreeMap<String, Option<LiveCanister>>,
    pub estate_funding_domains: BTreeMap<String, EstateFundingDomainObservation>,
    #[serde(with = "u128_text")]
    pub ledger_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub operator_cycles: u128,
    pub protocol_ready: BTreeMap<String, bool>,
}

/// Exact read-only observation of one Root-owned Cycles Ledger account.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstateFundingDomainObservation {
    #[serde(with = "option_u128_text")]
    pub balance_cycles: Option<u128>,
    pub cycles_ledger: String,
    pub pool: Option<EstatePoolInventoryObservation>,
    pub root_principal: Option<String>,
}

/// Complete protected Root-pool observation used for capacity and conservation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstatePoolInventoryObservation {
    pub assets: Vec<EstatePoolAssetObservation>,
    pub maximum_size: u32,
    pub minimum_size: u32,
    pub pending_creation: Option<EstatePoolPendingCreationObservation>,
    #[serde(with = "u128_text")]
    pub readiness_floor_cycles: u128,
    #[serde(with = "u128_text")]
    pub creation_execution_margin_cycles: u128,
}

/// One non-Store physical asset retained by a Root pool.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstatePoolAssetObservation {
    pub creation_receipt: Option<EstatePoolCreationReceiptObservation>,
    #[serde(with = "u128_text")]
    pub cycles: u128,
    pub lifecycle: EstatePoolAssetLifecycle,
    pub origin: EstatePoolAssetOrigin,
    pub principal: String,
}

/// Exact autonomous-creation receipt exposed by the protected Root inventory.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstatePoolCreationReceiptObservation {
    pub block_index: u64,
    pub operation_id: String,
    pub cycles_ledger: String,
    #[serde(with = "u128_text")]
    pub ledger_amount_cycles: u128,
    #[serde(with = "u128_text")]
    pub ledger_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub readiness_floor_cycles: u128,
    #[serde(with = "u128_text")]
    pub creation_execution_margin_cycles: u128,
    #[serde(with = "u128_text")]
    pub management_creation_fee_cycles: u128,
    #[serde(with = "option_u128_text")]
    pub first_observed_cycles: Option<u128>,
}

/// Protected provenance of one Root-owned pool asset.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EstatePoolAssetOrigin {
    InfrastructureStore,
    Created,
    Imported,
    Recycled,
}

/// Reviewed Root authority and lifecycle of a native pool funding target.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PoolFundingAuthority {
    pub root: String,
    pub lifecycle: EstatePoolAssetLifecycle,
}

/// Capacity-relevant lifecycle of one Root-owned pool asset.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EstatePoolAssetLifecycle {
    Claimed,
    Failed,
    HandingOff,
    PendingReset,
    Ready,
    Recycling,
    Workload,
}

/// Exact in-flight creation occupying one slot in the Root pool.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstatePoolPendingCreationObservation {
    pub attempt_count: u32,
    #[serde(with = "option_u128_text")]
    pub available_cycles: Option<u128>,
    #[serde(with = "u128_text")]
    pub creation_amount_cycles: u128,
    pub created_principal: Option<String>,
    pub diagnostic: Option<EstatePoolCreationDiagnostic>,
    pub last_attempt_at_ns: Option<u64>,
    pub operation_id: String,
    #[serde(with = "option_u128_text")]
    pub required_cycles: Option<u128>,
    pub retry_at_ns: Option<u64>,
    #[serde(with = "option_u128_text")]
    pub shortfall_cycles: Option<u128>,
    pub uncertain_result: bool,
}

/// Typed reason retained by an autonomous pool creation that cannot advance.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EstatePoolCreationDiagnostic {
    FundingRequired,
    LedgerCreationFailed,
    LedgerRejected,
    UnresolvedAfterLedgerWindow,
}

/// Maintained disposition of one configured canister.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DesiredPresence {
    Absent,
    Present,
}

/// Exact method used by a controlled source to transfer its cycles before retirement.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DrainAuthority {
    pub candid: String,
    pub method: String,
    pub destination: String,
    pub maximum_execution_burn_cycles: String,
}

/// Current desired state for one controlled canister.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DesiredCanister {
    #[serde(default)]
    pub canic_init: Option<DesiredCanisterInit>,
    #[serde(default)]
    pub controller_canisters: Vec<String>,
    pub controllers: Vec<String>,
    pub drain: Option<DrainAuthority>,
    pub initial_cycles: String,
    pub init_arg: Option<String>,
    pub init_candid: Option<String>,
    pub kind: DesiredCanisterKind,
    pub minimum_cycles: String,
    pub name: String,
    pub parent: Option<String>,
    pub presence: DesiredPresence,
    pub principal: Option<String>,
    #[serde(skip)]
    pub(crate) protocol_binding: Option<crate::protocol_binding::RegistryProtocolBinding>,
    pub replace: bool,
    pub subnet: String,
    pub wasm: Option<String>,
}

/// Canic-owned role class used to derive Fleet control-plane choreography.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DesiredCanisterKind {
    Auxiliary,
    Component,
    Coordinator,
    Pool,
    Root,
    Store,
}

/// Canic-owned typed initialization role for one infrastructure canister.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "role")]
pub enum DesiredCanisterInit {
    Coordinator,
    Root { root: String },
    Store { root: String },
}

/// One current-only idempotent protocol transition owned by the Fleet journal.
///
/// The three argument documents use Candid text. They may bind a dynamically
/// created canister with `{{principal:<logical-name>}}`, the retained operation
/// string with `{{operation_id}}`, or its 32-byte value with
/// `{{operation_id_blob}}`.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct DesiredProtocolStep {
    pub canister: String,
    pub candid: String,
    pub command_args: String,
    pub command_method: String,
    pub expected_status: String,
    pub maximum_execution_burn_cycles: String,
    pub name: String,
    pub status_args: String,
    pub status_method: String,
}

/// Current-only desired Fleet contract consumed by `canic fleet ensure`.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DesiredFleet {
    #[serde(default)]
    pub bootstrap: Option<DesiredFleetBootstrap>,
    pub canisters: Vec<DesiredCanister>,
    pub cycles_ledger: String,
    pub environment: String,
    pub fleet: String,
    pub ledger_fee_cycles: String,
    pub management_creation_fee_cycles: String,
    pub material_cycle_threshold: String,
    pub maximum_observation_burn_cycles: String,
    /// Observation stall bound and maximum paid attempts per fixture publication action.
    pub maximum_stalled_observations: u32,
    pub maximum_update_burn_cycles: String,
    pub operator: String,
    #[serde(default)]
    pub protocol: Option<DesiredFleetProtocol>,
    #[serde(skip)]
    pub(crate) protocol_steps: Vec<DesiredProtocolStep>,
    pub schema_version: u16,
    /// Logical name of the present controlled canister that owns retirement receipts.
    pub treasury: String,
}

/// Complete current-generation Canic initialization authority generated from App and Fleet input.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DesiredFleetBootstrap {
    /// Browser Principal namespace reviewed with this Fleet's admission input.
    #[serde(default)]
    pub admission_identity_origin: Option<String>,
    pub admission: canic_core::ids::FleetAdmissionPolicyTemplate,
    pub app: canic_core::ids::AppId,
    pub canonical_network_id: canic_core::ids::CanonicalNetworkId,
    pub component_deployment_configuration:
        canic_core::control_plane_support::config::ComponentDeploymentConfiguration,
    pub coordinator: String,
    pub coordinator_subnet: canic_core::ids::SubnetId,
    /// Exact direct recovery controllers for every Fleet canister.
    pub recovery_controllers: Vec<canic_core::cdk::types::Principal>,
    pub fleet_id: canic_core::ids::FleetId,
    pub fresh_estate: bool,
    pub release_build_id: canic_core::ids::ReleaseBuildId,
    pub root_funding: Option<canic_core::ids::FleetCoordinatorRootFundingPolicy>,
    pub roots: Vec<DesiredFleetBootstrapRoot>,
}

/// One Root/Store pair's generated immutable initialization authority.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DesiredFleetBootstrapRoot {
    /// No import hold is represented by an omitted TOML field (TOML has no null).
    pub capacity_import_bootstrap: Option<capacity_import::CapacityImportBootstrapRecord>,
    pub canister_pool_imports: Vec<String>,
    pub component_admissions: Vec<canic_core::ids::ComponentSpecAdmission>,
    pub component_topology_digest: canic_core::ids::ComponentTopologyDigest,
    pub funding: canic_core::ids::FleetSubnetRootFundingAuthority,
    pub limits: canic_core::ids::FleetSubnetRootLimits,
    pub placement_subnet: canic_core::ids::SubnetId,
    pub root: String,
    pub store: String,
}

/// Current Canic-owned control-plane intent compiled from one App topology.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DesiredFleetProtocol {
    /// Canonical application `canic.toml` used to compile Component topology.
    pub app_config: String,
    /// Exact initial group placements assigned to declared Root roles.
    pub component_group_placements: Vec<DesiredComponentGroupPlacement>,
    /// Exact Coordinator Candid used only by Canic's typed protocol adapter.
    pub coordinator_candid: String,
    /// Exact Root Candid used only by Canic's typed protocol adapter.
    pub root_candid: String,
    /// Exact Store Candid used only by Canic's typed protocol adapter.
    pub store_candid: String,
}

/// One typed initial Component Group placement owned by Canic policy.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DesiredComponentGroupPlacement {
    pub deployment: String,
    pub ordinal: u32,
    pub root: String,
}

/// Content identities resolved from current desired-state artifact paths by ops.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DesiredFleetArtifacts {
    pub continuation: Option<FleetEnsureContinuationAuthority>,
    pub drain_candid_sha256_by_canister: BTreeMap<String, String>,
    pub init_arg_sha256_by_canister: BTreeMap<String, String>,
    pub init_candid_sha256_by_canister: BTreeMap<String, String>,
    pub wasm_sha256_by_canister: BTreeMap<String, String>,
    pub startup_funding_by_root: BTreeMap<String, StartupFundingRequirement>,
    pub(crate) protocol_by_step: BTreeMap<String, ProtocolArtifactDigests>,
}

/// Configuration-bound startup demand; live grant usage and execution are separate inputs.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StartupFundingRequirement {
    /// Root-local upper bound from the selected continuation artifact catalogue.
    pub maximum_continuation_steps: u32,
    pub minimum_native_cycles: u128,
    pub unfunded_role: Option<StartupRoleShortfall>,
}

/// A role whose fresh lifetime allowance or disabled top-up cannot supply initial demand.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct StartupRoleShortfall {
    pub role: canic_core::ids::CanisterRole,
    #[serde(with = "u128_text")]
    pub cycles: u128,
}

/// Content identities for one declarative protocol transition.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct ProtocolArtifactDigests {
    pub candid_sha256: String,
    pub command_args_sha256: String,
    pub expected_status_sha256: String,
    pub status_args_sha256: String,
}

/// Validated numeric funding bounds for one desired canister.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CanisterCyclePolicy {
    #[serde(with = "u128_text")]
    pub initial_cycles: u128,
    #[serde(with = "u128_text")]
    pub minimum_cycles: u128,
}

/// Exact Root authority and Candid contract for replicated reinstall observations.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ReinstallHistoryWitness {
    /// Exact installed module retained before this reviewed reinstall.
    pub prior_module_sha256: String,
    pub authority: RootManagementBinding,
    pub candid: String,
    pub candid_sha256: String,
    /// Exact replacement Root admitted only while reconciling its own durable intent.
    #[serde(deserialize_with = "serialization::required_option")]
    pub replacement: Option<Box<ReinstallRootWitnessRecord>>,
}

/// Exact management identity and protocol for the selected replacement Root.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ReinstallRootWitnessRecord {
    pub authority: RootManagementBinding,
    pub candid: String,
    pub candid_sha256: String,
}

/// Exact effect kind retained before execution.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum EnsureAction {
    Create {
        controller_canisters: Vec<String>,
        controllers: Vec<String>,
        created_at_time: u64,
        ledger: String,
        name: String,
        #[serde(with = "u128_text")]
        requested_initial_cycles: u128,
        subnet: String,
    },
    Delete {
        #[serde(with = "u128_text")]
        maximum_remaining_cycles: u128,
        name: String,
        principal: String,
    },
    /// Remove one reviewed snapshot under stopped, exclusive operator custody.
    DeleteSnapshot {
        name: String,
        principal: String,
        snapshot_id: String,
        /// Exact inventory before this deletion, in canonical hexadecimal order.
        expected_snapshots: Vec<String>,
        #[serde(deserialize_with = "serialization::required_option")]
        expected_module_sha256: Option<String>,
    },
    Fund {
        /// Exact Root and lifecycle for protected inspection of a pool funding target.
        #[serde(deserialize_with = "serialization::required_option")]
        pool_funding: Option<PoolFundingAuthority>,
        #[serde(with = "u128_text")]
        amount: u128,
        created_at_time: u64,
        #[serde(with = "u128_text")]
        expected_post_cycles: u128,
        #[serde(with = "u128_text")]
        funding_deficit_cycles: u128,
        #[serde(with = "u128_text")]
        funding_margin_cycles: u128,
        ledger: String,
        name: String,
        principal: String,
    },
    FundEstate {
        #[serde(with = "u128_text")]
        amount: u128,
        created_at_time: u64,
        #[serde(with = "u128_text")]
        expected_post_cycles: u128,
        ledger: String,
        #[serde(with = "u128_text")]
        ledger_fee_cycles: u128,
        name: String,
        principal: String,
    },
    Install {
        canic_init: Option<DesiredCanisterInit>,
        #[serde(deserialize_with = "serialization::required_option")]
        reinstall_witness: Option<Box<ReinstallHistoryWitness>>,
        init_arg: Option<String>,
        init_arg_sha256: Option<String>,
        init_candid: Option<String>,
        init_candid_sha256: Option<String>,
        mode: InstallMode,
        name: String,
        principal: String,
        wasm: String,
        wasm_sha256: String,
    },
    FleetProtocol {
        action: Box<CurrentFleetProtocolAction>,
        candid: String,
        candid_sha256: String,
        #[serde(with = "u128_text")]
        maximum_execution_burn_cycles: u128,
        name: String,
        principal: String,
    },
    Protocol {
        candid: String,
        candid_sha256: String,
        command_args: String,
        command_args_sha256: String,
        command_method: String,
        expected_status: String,
        expected_status_sha256: String,
        #[serde(with = "u128_text")]
        maximum_execution_burn_cycles: u128,
        name: String,
        principal: String,
        status_args: String,
        status_args_sha256: String,
        status_method: String,
    },
    SetControllers {
        controller_canisters: Vec<String>,
        controllers: Vec<String>,
        name: String,
        principal: String,
    },
    Start {
        name: String,
        principal: String,
    },
    Stop {
        name: String,
        principal: String,
    },
    /// Clear supplied infrastructure code and state without deleting the canister.
    Uninstall {
        name: String,
        principal: String,
    },
    Transfer {
        #[serde(with = "u128_text")]
        amount: u128,
        candid: String,
        candid_sha256: String,
        destination: String,
        #[serde(with = "u128_text")]
        maximum_execution_burn_cycles: u128,
        method: String,
        name: String,
        principal: String,
    },
}

impl EnsureAction {
    /// Paid publication attempts retained in the reviewed action, independent of observations.
    pub(crate) fn fixture_publication_attempt_limit(&self) -> Option<u32> {
        if let Self::FleetProtocol { action, .. } = self {
            match action.as_ref() {
                CurrentFleetProtocolAction::PrepareStoreFixture {
                    maximum_attempts, ..
                }
                | CurrentFleetProtocolAction::PublishStoreFixtureChunk {
                    maximum_attempts, ..
                } => {
                    return Some(*maximum_attempts);
                }
                _ => {}
            }
        }
        None
    }

    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Create { name, .. }
            | Self::Delete { name, .. }
            | Self::DeleteSnapshot { name, .. }
            | Self::FleetProtocol { name, .. }
            | Self::Fund { name, .. }
            | Self::FundEstate { name, .. }
            | Self::Install { name, .. }
            | Self::Protocol { name, .. }
            | Self::SetControllers { name, .. }
            | Self::Start { name, .. }
            | Self::Stop { name, .. }
            | Self::Uninstall { name, .. }
            | Self::Transfer { name, .. } => name,
        }
    }
}

/// Closed current-only Canic choreography emitted from roles and topology.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[expect(
    clippy::large_enum_variant,
    reason = "each exact typed action is boxed by EnsureAction before durable retention"
)]
pub enum CurrentFleetProtocolAction {
    /// Verify host-created local supply without authorizing mainnet-only refill.
    ObservePoolReadiness {
        minimum_ready: u32,
        readiness_floor: canic_core::cdk::types::Cycles,
    },
    MaintainPoolReadiness {
        maximum_updates: u32,
        minimum_ready: u32,
        readiness_floor: canic_core::cdk::types::Cycles,
    },
    ReconcilePoolAsset {
        request: canic_core::dto::pool::PoolCanisterRequest,
        minimum_cycles: canic_core::cdk::types::Cycles,
    },
    ActivateRegistry {
        expected_registry: canic_core::dto::fleet_registry::FleetRegistry,
        expected_version: canic_core::dto::fleet_registry::FleetRegistryVersion,
        request: canic_core::dto::fleet_registry::FleetRegistryActivationRequest,
    },
    ActivateRegistryMirror {
        expected: canic_core::dto::fleet_registry::FleetSubnetRootRegistryMirrorActivationResponse,
        request: canic_core::dto::fleet_registry::FleetSubnetRootRegistrySyncRequest,
    },
    AdoptStore {
        request: canic_core::dto::fleet_subnet_root::FleetSubnetWasmStoreAdoptionRequest,
    },
    BootstrapStore {
        expected: canic_core::dto::root_store::RootStoreBootstrapResponse,
        request: canic_core::dto::root_store::RootStoreBootstrapRequest,
    },
    JoinRoot {
        expected_registry: canic_core::dto::fleet_registry::FleetRegistry,
        expected_version: canic_core::dto::fleet_registry::FleetRegistryVersion,
        request: canic_core::dto::fleet_registry::FleetSubnetRootJoinRequest,
    },
    PrepareStoreFixture {
        /// Total paid calls admitted by this exact reviewed action.
        maximum_attempts: u32,
        request: canic_core::dto::root_store::RootStoreFixturePrepareRequest,
        source: canic_core::dto::root_store::RootStoreFixture,
        store: candid::Principal,
    },
    PublishStoreFixtureChunk {
        /// Total paid calls admitted by this exact reviewed action.
        maximum_attempts: u32,
        request: canic_core::dto::fixture_provisioning::FixtureChunkUpload,
        expected: canic_core::dto::fixture_provisioning::FixtureSourceStatus,
        source_bytes: u64,
    },
    PrepareComponentRegistry {
        expected: canic_core::dto::component_registry::RootComponentRegistryStatusResponse,
        request: canic_core::dto::component_registry::RootComponentRegistryPreparationRequest,
    },
    ProvisionComponents {
        plan_hash: [u8; 32],
        request: canic_core::dto::component_provisioning::FleetComponentProvisioningPrepareRequest,
    },
    PublishStoreChunk {
        request: canic_control_plane::dto::template::TemplateChunkInput,
    },
    SynchronizeRegistry {
        expected: canic_core::dto::fleet_registry::FleetSubnetRootRegistrySyncResponse,
        request: canic_core::dto::fleet_registry::FleetSubnetRootRegistrySyncRequest,
    },
}

impl CurrentFleetProtocolAction {
    /// Retained payload shared by publication reporting and the plan content store.
    pub(crate) fn publication_bytes(&self) -> Option<&[u8]> {
        match self {
            Self::PublishStoreChunk { request } => Some(&request.bytes),
            Self::PublishStoreFixtureChunk { request, .. } => Some(&request.bytes),
            _ => None,
        }
    }

    pub(crate) const fn publication_bytes_mut(&mut self) -> Option<&mut Vec<u8>> {
        match self {
            Self::PublishStoreChunk { request } => Some(&mut request.bytes),
            Self::PublishStoreFixtureChunk { request, .. } => Some(&mut request.bytes),
            _ => None,
        }
    }

    /// Role that exclusively owns this current control-plane transition.
    #[must_use]
    pub const fn target_kind(&self) -> DesiredCanisterKind {
        match self {
            Self::ActivateRegistry { .. }
            | Self::JoinRoot { .. }
            | Self::ProvisionComponents { .. } => DesiredCanisterKind::Coordinator,
            Self::ActivateRegistryMirror { .. }
            | Self::ReconcilePoolAsset { .. }
            | Self::MaintainPoolReadiness { .. }
            | Self::ObservePoolReadiness { .. }
            | Self::AdoptStore { .. }
            | Self::BootstrapStore { .. }
            | Self::PrepareStoreFixture { .. }
            | Self::PrepareComponentRegistry { .. }
            | Self::SynchronizeRegistry { .. } => DesiredCanisterKind::Root,
            Self::PublishStoreChunk { .. } | Self::PublishStoreFixtureChunk { .. } => {
                DesiredCanisterKind::Store
            }
        }
    }

    /// Durable operation identity when this transition has a protocol-owned replay key.
    #[must_use]
    pub const fn operation_id(&self) -> Option<[u8; 32]> {
        match self {
            Self::ActivateRegistry { .. }
            | Self::ReconcilePoolAsset { .. }
            | Self::MaintainPoolReadiness { .. }
            | Self::ObservePoolReadiness { .. }
            | Self::JoinRoot { .. }
            | Self::PrepareComponentRegistry { .. }
            | Self::PrepareStoreFixture { .. }
            | Self::PublishStoreChunk { .. }
            | Self::PublishStoreFixtureChunk { .. } => None,
            Self::ActivateRegistryMirror { request, .. }
            | Self::SynchronizeRegistry { request, .. } => Some(request.operation_id),
            Self::AdoptStore { request } => Some(request.operation_id),
            Self::BootstrapStore { request, .. } => Some(request.operation_id),
            Self::ProvisionComponents { request, .. } => Some(request.operation_id),
        }
    }
}

/// Explicit Wasm installation mode selected from live state.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum InstallMode {
    Install,
    Reinstall,
}

/// Planned disposition and effects for one controlled canister.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CanisterPlan {
    pub actions: Vec<EnsureAction>,
    pub disposition: CanisterDisposition,
    pub name: String,
    #[serde(with = "u128_text")]
    pub observed_cycles: u128,
    #[serde(deserialize_with = "serialization::required_option")]
    pub principal: Option<String>,
}

/// Operator-visible canister disposition.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CanisterDisposition {
    Create,
    Delete,
    Replace,
    Reinstall,
    Reuse,
}

/// Exact cycle conservation proof reviewed before apply.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CycleConservation {
    pub estate_funding_domains: Vec<EstateFundingDomainPlan>,
    #[serde(with = "u128_text")]
    pub expected_post_operation_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_execution_burn_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_new_funding_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_operator_debit_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_unavoidable_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub observed_controlled_cycles: u128,
    #[serde(with = "u128_text")]
    pub retained_in_reused_canisters_cycles: u128,
    #[serde(with = "u128_text")]
    pub scheduled_transfer_cycles: u128,
}

/// Reviewed autonomous-creation exposure for one Root-owned Cycles Ledger account.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstateFundingDomainPlan {
    pub allocated_workloads: u32,
    #[serde(with = "option_u128_text")]
    pub available_cycles: Option<u128>,
    pub available_pool_slots: u32,
    #[serde(with = "u128_text")]
    pub creation_amount_cycles: u128,
    pub cycles_ledger: String,
    #[serde(with = "u128_text")]
    pub creation_execution_margin_cycles: u128,
    #[serde(with = "u128_text")]
    pub readiness_floor_cycles: u128,
    pub eligible_ready_pool_assets: u32,
    pub initial_pool_assets: Vec<String>,
    #[serde(with = "u128_text")]
    pub ledger_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub management_creation_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_creation_debit_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_creation_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_funding_cycles: u128,
    pub occupied_pool_assets: u32,
    pub pending_creation_count: u32,
    pub pending_creation: Option<EstatePoolPendingCreationObservation>,
    pub pool_maximum_size: u32,
    pub planned_initial_workloads: u32,
    pub required_creation_count: u32,
    pub root: String,
    pub root_principal: Option<String>,
    #[serde(with = "u128_text")]
    pub shortfall_cycles: u128,
}

/// Durable no-effect pause for one underfunded Root-owned creation domain.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EstateFundingRequiredRecord {
    pub attempt_count: Option<u32>,
    #[serde(with = "u128_text")]
    pub available_cycles: u128,
    #[serde(with = "u128_text")]
    pub creation_amount_cycles: u128,
    pub cycles_ledger: String,
    #[serde(with = "u128_text")]
    pub creation_execution_margin_cycles: u128,
    #[serde(with = "u128_text")]
    pub readiness_floor_cycles: u128,
    #[serde(with = "u128_text")]
    pub ledger_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub management_creation_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_creation_debit_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_creation_fee_cycles: u128,
    pub operation_id: String,
    pub pending_creation_operation_id: Option<String>,
    pub plan_sha256: String,
    pub required_creation_count: u32,
    pub root: String,
    pub root_principal: String,
    pub last_attempt_at_ns: Option<u64>,
    pub retry_at_ns: Option<u64>,
    #[serde(with = "u128_text")]
    pub shortfall_cycles: u128,
}

/// Terminal net balance accounting for the exact applied operation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ActualCycleConservation {
    #[serde(with = "u128_text")]
    pub estate_funding_cycles: u128,
    #[serde(with = "u128_text")]
    pub exact_estate_creation_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub exact_unavoidable_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub final_controlled_cycles: u128,
    /// Net balance deficit after accounted funding and fees, not gross execution burn.
    /// Concurrent external deposits may conceal consumption.
    #[serde(with = "u128_text")]
    pub observed_net_cycle_debit_cycles: u128,
    #[serde(with = "u128_text")]
    pub observed_starting_cycles: u128,
    /// Net surplus in the controlled estate. It grants no payment authority and
    /// does not attribute an origin or prove a Ledger credit.
    #[serde(with = "u128_text")]
    pub observed_net_cycle_credit_cycles: u128,
    #[serde(with = "u128_text")]
    pub operator_debit_cycles: u128,
    #[serde(with = "u128_text")]
    pub received_new_funding_cycles: u128,
}

/// Sum the separately reviewed Create execution and first-observation bounds.
/// Overflow cannot grant an unbounded allowance.
pub(crate) const fn creation_observation_burn(observation: u128, update: u128) -> Option<u128> {
    observation.checked_add(update)
}

/// Whether a newly created canister's first balance is covered by its reviewed
/// Create execution plus first-observation allowance. The Ledger receipt owns
/// the requested amount; live status owns the exact retained balance.
pub(crate) const fn create_balance_is_terminal(
    actual_cycles: Option<u128>,
    requested_initial_cycles: u128,
    maximum_observation_burn_cycles: u128,
) -> bool {
    let Some(actual_cycles) = actual_cycles else {
        return false;
    };
    requested_initial_cycles.saturating_sub(actual_cycles) <= maximum_observation_burn_cycles
}

/// Exact normalized desired input retained by one in-progress operation.
///
/// The public desired document cannot declare internal protocol steps. This
/// wrapper persists those Canic-owned steps without making them an input
/// surface and restores them before any resumed observation or effect.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReviewedDesiredFleetRecord {
    desired: DesiredFleet,
}

impl ReviewedDesiredFleetRecord {
    pub(crate) fn capture(desired: &DesiredFleet) -> Self {
        Self {
            desired: desired.clone(),
        }
    }

    /// Borrow the complete normalized desired input, including internal steps.
    #[must_use]
    pub const fn desired(&self) -> &DesiredFleet {
        &self.desired
    }

    /// Consume the retained authority as the complete normalized desired input.
    #[must_use]
    pub fn into_desired(self) -> DesiredFleet {
        self.desired
    }
}

#[derive(Deserialize, Serialize)]
struct ReviewedDesiredFleetRecordProjection {
    desired: DesiredFleet,
    protocol_steps: Vec<DesiredProtocolStep>,
}

impl Serialize for ReviewedDesiredFleetRecord {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        ReviewedDesiredFleetRecordProjection {
            desired: self.desired.clone(),
            protocol_steps: self.desired.protocol_steps.clone(),
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for ReviewedDesiredFleetRecord {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let mut projection = ReviewedDesiredFleetRecordProjection::deserialize(deserializer)?;
        projection.desired.protocol_steps = projection.protocol_steps;
        Ok(Self {
            desired: projection.desired,
        })
    }
}

/// Immutable reviewed plan produced from desired state plus one live observation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetEnsurePlan {
    #[serde(deserialize_with = "serialization::required_option")]
    pub infrastructure_bootstrap:
        Option<Box<infrastructure_bootstrap::InfrastructureBootstrapRecord>>,
    /// Informational dependent work; grants no funding or effect authority.
    #[serde(deserialize_with = "serialization::required_option")]
    pub recovery_review: Option<Box<FleetRecoveryReview>>,
    /// One explicit selected-build wipe, retained through preparation and full convergence.
    #[serde(deserialize_with = "serialization::required_option")]
    pub reinstall: Option<Box<FleetReinstallRecord>>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub continuation: Option<FleetEnsureContinuationAuthority>,
    pub canisters: Vec<CanisterPlan>,
    pub conservation: CycleConservation,
    pub desired_sha256: String,
    pub environment: String,
    pub fleet: String,
    pub operation_id: String,
    pub plan_sha256: String,
    pub planned_at_time: u64,
    pub protocol_actions: Vec<EnsureAction>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub root_start_authority: Option<Box<RetainedRootStartAuthorityRecord>>,
    /// Exact installed Root authority approved for replacement by this plan.
    pub root_reinstall_bindings: Vec<RootManagementBinding>,
    /// Required for execution; normalization may clear it when comparing action projections.
    #[serde(deserialize_with = "serialization::required_option")]
    pub reviewed_desired: Option<Box<ReviewedDesiredFleetRecord>>,
    pub schema_version: u16,
    pub scope: FleetEnsurePlanScope,
    /// Exact terminal operation that owns the currently active Registry observation.
    #[serde(deserialize_with = "serialization::required_option")]
    pub terminal_inventory_operation_id: Option<String>,
}

/// Exact authority scope of one current Fleet Ensure plan.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FleetEnsurePlanScope {
    /// Complete desired-state convergence after all protected roles are observable.
    #[default]
    Full,
    /// Initialize supplied infrastructure before any Root-local capacity handoff.
    InfrastructureBootstrap,
    /// Quiesce unfinished activation before reviewing its complete physical reset closure.
    ReinstallPreparation,
    /// Exact reviewed Root reset before current protected interfaces become available.
    RootReinstallPrerequisite,
    /// Exact management-authorized Root Start prerequisite.
    RootStartPrerequisite,
}

impl FleetEnsurePlanScope {
    /// Stable operator-facing name shared by text and JSON reports.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::InfrastructureBootstrap => "infrastructure_bootstrap",
            Self::ReinstallPreparation => "reinstall_preparation",
            Self::RootReinstallPrerequisite => "root_reinstall_prerequisite",
            Self::RootStartPrerequisite => "root_start_prerequisite",
        }
    }
}

/// Exact unfinished activation and observed authority for its reviewed reset.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetReinstallRecord {
    #[serde(deserialize_with = "serialization::required_option")]
    pub activation_reset: Option<Box<FleetActivationResetRecord>>,

    pub operation_id: String,
    pub source_operation_id: String,
    pub authorities: Vec<RootManagementBinding>,
    /// Empty during preparation; the full plan binds every observed physical asset.
    pub assets: Vec<FleetReinstallAssetRecord>,
}

/// Exact retained source bytes and issued protocol effects inspected for activation recovery.
/// The source plan label is a journal reference, not executable replacement authority.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetActivationSourceRecord {
    pub infrastructure: Vec<RootManagementBinding>,
    pub operator: String,
    pub cycles_ledger: String,
    #[serde(with = "u128_text")]
    pub initial_controlled_cycles: u128,
    #[serde(with = "u128_text")]
    pub maximum_execution_burn_cycles: u128,
    #[serde(with = "u128_text_map")]
    pub initial_estate_funding_cycles_by_root: BTreeMap<String, u128>,
    pub operation_id: String,
    pub plan_sha256: String,
    pub plan_document_sha256: String,
    pub journal_document_sha256: String,
    pub state_document_sha256: String,
    pub provisioning: EnsureAction,
    pub registry_preparations: Vec<EnsureAction>,
    pub stores: Vec<FleetProtocolReadRecord>,
}

/// Reviewed inactive activation evidence retained through preparation and reset.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetActivationResetRecord {
    #[serde(deserialize_with = "serialization::required_option")]
    pub preparation: Option<ActivationPreparationEvidenceRecord>,
    pub source: FleetActivationSourceRecord,
    pub roots: Vec<RootActivationResetRecord>,
}

/// Exact completed preparation documents retained before the separate Root-reset review.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ActivationPreparationEvidenceRecord {
    pub plan_document_sha256: String,
    pub journal_document_sha256: String,
}

/// Durable local handoff intent; completion is recorded before remote effects can run.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ActivationResetAdoptionRecord {
    pub source_plan_sha256: String,
    pub source_journal_sha256: String,
    pub source_state_sha256: String,
    pub replacement_plan_sha256: String,
    pub replacement_journal_sha256: String,
    pub complete: bool,
}

/// Exact retained Candid and target used only to observe a source protocol owner.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetProtocolReadRecord {
    pub candid: String,
    pub candid_sha256: String,
    pub principal: String,
}

/// Inactive Root identity and sealed initial membership observed before a reset.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RootActivationResetRecord {
    pub root: String,
    pub activation_operation_id: [u8; 32],
    pub inventory_hash: [u8; 32],
    pub provisioning_receipt_hash: [u8; 32],
    pub component_count: u32,
    pub managed_descendants: u32,
}

/// One controlled physical asset in the sealed reset closure.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetReinstallAssetRecord {
    pub controllers: Vec<String>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub module_sha256: Option<String>,
    pub principal: String,
    pub root: String,
    pub subnet: String,
}

/// Exact management-canister observation of one configured Fleet Subnet Root.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RootManagementCanisterObservation {
    pub live: LiveCanister,
    pub name: String,
    pub subnet: String,
}

/// Read-only management evidence available before protected Root ingress can run.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RootManagementObservation {
    pub operator_cycles: u128,
    pub roots: BTreeMap<String, RootManagementCanisterObservation>,
}

/// Exact installed Root identity, module and controller authority observed through management.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RootManagementBinding {
    pub controllers: Vec<String>,
    pub name: String,
    pub module_sha256: String,
    pub principal: String,
    pub subnet: String,
}

/// Generator-owned authority for management-bound Root prerequisites before protected observation.
///
/// The separately reviewed plan permits only Start for the exact observed module.
/// It cannot authorize replacement, installation or reuse across releases.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RetainedRootStartAuthorityRecord {
    pub authority_sha256: String,
    pub environment: String,
    pub fleet: String,
    pub fleet_id: canic_core::ids::FleetId,
    pub roots: Vec<RootManagementBinding>,
    pub schema_version: u16,
}

impl RetainedRootStartAuthorityRecord {
    pub(crate) fn seal(&mut self) {
        self.authority_sha256 = self.expected_sha256();
    }

    pub(crate) fn has_valid_digest(&self) -> bool {
        self.authority_sha256 == self.expected_sha256()
    }

    fn expected_sha256(&self) -> String {
        let mut canonical = self.clone();
        canonical.authority_sha256.clear();
        let bytes = serde_json::to_vec(&canonical)
            .expect("retained Root-start authority is JSON serializable");
        let mut framed = b"canic:fleet-ensure:root-start-authority:v1".to_vec();
        framed.extend_from_slice(&u64::try_from(bytes.len()).unwrap_or(u64::MAX).to_be_bytes());
        framed.extend_from_slice(&bytes);
        canic_core::cdk::utils::hash::sha256_hex(&framed)
    }
}

/// Durable state of one planned effect.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EffectState {
    Applied,
    Intent,
    Issued,
}

/// Durable outcome of one reviewed Fleet ensure operation.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FleetEnsureCompletion {
    Converged,
    /// Unfinished activation is quiescent; its full reset still requires review and execution.
    Prepared,
    InProgress,
    ReplanRequired,
}

/// Durable intent/result record for one action.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EffectRecord {
    /// Root maintenance calls whose intent was persisted, including lost responses.
    pub maintenance_attempts: u32,
    /// Fixture publication calls reserved before issue, including failed or lost replies.
    pub publication_attempts: u32,
    pub action_sha256: String,
    #[serde(deserialize_with = "serialization::required_option")]
    pub created_principal: Option<String>,
    #[serde(with = "option_u128_text")]
    pub destination_post_cycles: Option<u128>,
    #[serde(with = "option_u128_text")]
    pub destination_pre_cycles: Option<u128>,
    #[serde(with = "option_u128_text")]
    pub post_cycles: Option<u128>,
    #[serde(with = "option_u128_text")]
    pub pre_cycles: Option<u128>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub pre_canister_version: Option<u64>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub progress_identity: Option<String>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub receipt: Option<String>,
    pub state: EffectState,
}

impl EffectRecord {
    /// Validate paid retry counters against this exact action's reviewed limits.
    pub(in crate::fleet_ensure) fn attempts_match(&self, action: &EnsureAction) -> bool {
        let publication = match action.fixture_publication_attempt_limit() {
            Some(limit) => limit > 0 && self.publication_attempts <= limit,
            None => self.publication_attempts == 0,
        };
        let maintenance = match action {
            EnsureAction::FleetProtocol { action, .. } => match action.as_ref() {
                CurrentFleetProtocolAction::MaintainPoolReadiness {
                    maximum_updates, ..
                } => self.maintenance_attempts <= *maximum_updates,
                _ => self.maintenance_attempts == 0,
            },
            _ => self.maintenance_attempts == 0,
        };
        publication && maintenance
    }
}

/// Complete retained/live balance tuple for one exact retirement transfer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RetirementTransferBalances {
    pub destination_after: u128,
    pub destination_before: u128,
    pub maximum_execution_burn: u128,
    pub source_after: u128,
    pub source_before: u128,
    pub transfer_amount: u128,
}

/// Model-owned result of reconciling both controlled sides of a retirement transfer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RetirementTransferReconciliation {
    Conserved {
        destination_credit: u128,
        source_debit: u128,
    },
    Pending,
}

/// Exact invariant failure while reconciling a retirement transfer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RetirementTransferInvariantError {
    ArithmeticOverflow,
    BalanceMovedInInvalidDirection,
    Unbalanced {
        destination_credit: u128,
        maximum_source_debit: u128,
        source_debit: u128,
    },
}

/// Require a matching source debit and treasury credit before retirement may continue.
pub fn reconcile_retirement_transfer(
    balances: RetirementTransferBalances,
) -> Result<RetirementTransferReconciliation, RetirementTransferInvariantError> {
    let source_debit = balances
        .source_before
        .checked_sub(balances.source_after)
        .ok_or(RetirementTransferInvariantError::BalanceMovedInInvalidDirection)?;
    let destination_credit = balances
        .destination_after
        .checked_sub(balances.destination_before)
        .ok_or(RetirementTransferInvariantError::BalanceMovedInInvalidDirection)?;
    let maximum_source_debit = balances
        .transfer_amount
        .checked_add(balances.maximum_execution_burn)
        .ok_or(RetirementTransferInvariantError::ArithmeticOverflow)?;
    if source_debit == 0 && destination_credit == 0 {
        return Ok(RetirementTransferReconciliation::Pending);
    }
    if source_debit >= balances.transfer_amount
        && source_debit <= maximum_source_debit
        && destination_credit == balances.transfer_amount
    {
        return Ok(RetirementTransferReconciliation::Conserved {
            destination_credit,
            source_debit,
        });
    }
    Err(RetirementTransferInvariantError::Unbalanced {
        destination_credit,
        maximum_source_debit,
        source_debit,
    })
}

/// Current discovered identities retained only to seed live observation.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetEnsureStateRecord {
    #[serde(deserialize_with = "serialization::required_option")]
    pub active_registry: Option<canic_core::dto::fleet_registry::FleetRegistry>,
    /// Exact applied action identities for the adjacent completed reinstalls.
    pub completed_reinstall_action_sha256: BTreeMap<String, String>,
    /// Exact operation owning the adjacent completed-reinstall thresholds.
    #[serde(deserialize_with = "serialization::required_option")]
    pub completed_reinstall_operation_id: Option<String>,
    /// Pre-effect version thresholds for exact journal-proved reinstalls in the
    /// immediately preceding nonterminal operation.
    pub completed_reinstalls: BTreeMap<String, u64>,
    pub fleet: String,
    pub pending_principals: BTreeMap<String, String>,
    pub principals: BTreeMap<String, String>,
    pub retained_cycles_by_principal: BTreeMap<String, u128>,
    pub schema_version: u16,
    pub topology: BTreeMap<String, FleetEnsureTopologyRecord>,
}

/// Current typed topology retained independently from any historical install evidence.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetEnsureTopologyRecord {
    pub kind: DesiredCanisterKind,
    #[serde(deserialize_with = "serialization::required_option")]
    pub module_hash: Option<String>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub parent: Option<String>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub protocol_binding: Option<crate::protocol_binding::RegistryProtocolBinding>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub role: Option<String>,
}

/// Sole current-generation host journal for one Fleet ensure operation.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetEnsureJournalRecord {
    /// Whole-Fleet release shares this journal and the ordinary exclusive operation lock.
    #[serde(deserialize_with = "serialization::required_option")]
    pub release: Option<release::FleetReleaseExecutionRecord>,
    /// An explicit extension of this operation's registration authority; null until requested.
    #[serde(deserialize_with = "serialization::required_option")]
    pub bootstrap_registration_recovery: Option<
        infrastructure_bootstrap::registration_recovery::BootstrapRegistrationRecoveryRecord,
    >,
    pub funding_observations: BTreeMap<String, funding_observation::FundingObservationReviewRecord>,
    pub funding_reviews: Vec<FundingReviewRecord>,
    pub successor_phases: Vec<FleetEnsureSuccessorPhaseRecord>,
    pub completion: FleetEnsureCompletion,
    #[serde(deserialize_with = "serialization::required_option")]
    pub estate_funding_required: Option<EstateFundingRequiredRecord>,
    pub effects: Vec<EffectRecord>,
    pub fleet: String,
    #[serde(with = "u128_text")]
    pub initial_controlled_cycles: u128,
    #[serde(with = "u128_text_map")]
    pub initial_estate_funding_cycles_by_root: BTreeMap<String, u128>,
    #[serde(with = "u128_text")]
    pub initial_operator_cycles: u128,
    pub operation_id: String,
    pub plan_sha256: String,
    pub schema_version: u16,
    pub stalled_observations: u32,
}

/// Reviewed input identities and finite protocol expansion for a fresh Fleet.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetEnsureContinuationAuthority {
    /// Additional paid fixture attempts, beyond each publication action's first call.
    pub fixture_publication_retry_attempts: u32,
    pub app_config_sha256: String,
    pub application_artifact_union_sha256: String,
    pub coordinator_candid_sha256: String,
    pub maximum_successor_actions: u32,
    pub root_candid_sha256: String,
    pub store_candid_sha256: String,
}

/// One immutable successor plan retained before its first effect intent.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetEnsureSuccessorPhaseRecord {
    /// Highest net debit observed at a phase boundary; donations cannot reduce it.
    /// This is not gross execution consumption, which balance snapshots cannot prove.
    #[serde(with = "u128_text")]
    pub execution_burn_before_phase: u128,
    pub plan_sha256: String,
    /// Hydrated by the owning file reader; durable JSON contains only the digest.
    #[serde(skip)]
    pub plan: Option<Box<FleetEnsurePlan>>,
}

/// Typed boundary requiring a new review instead of automatic protocol continuation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FleetEnsureSuccessorReviewReason {
    AdditionalEffect,
    BudgetExceeded,
    ChangedInputs,
    PhaseBound,
    ProtocolAuthority,
}

/// Result returned by one plan-only or apply invocation.

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FleetEnsureReport {
    pub funding_review: Option<FundingReviewRecord>,
    pub actual_conservation: Option<ActualCycleConservation>,
    pub effects_applied: u32,
    pub plan: FleetEnsurePlan,
    pub terminal: bool,
}

/// Funding review within an existing Fleet operation.
///
/// An operator shortfall
/// refers to the original action and never adds a second withdrawal effect.
/// Other pauses use the nullable effect as the additional transfer approval.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FundingReviewRecord {
    pub action: EnsureAction,
    #[serde(deserialize_with = "serialization::required_option")]
    pub effect: Option<EffectRecord>,
    #[serde(deserialize_with = "serialization::required_option")]
    pub operator_mint: Option<operator_mint::OperatorMintReviewRecord>,
    pub pause: FundingPauseRecord,
    pub review_sha256: String,
}

/// Funding destination and retained-operation reason for an additional reviewed credit.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(
    tag = "kind",
    content = "evidence",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum FundingPauseRecord {
    Estate(EstateFundingRequiredRecord),
    Native(NativeFundingRequiredRecord),
    Operator(operator_mint::InitialOperatorFundingRequiredRecord),
}

impl FundingPauseRecord {
    /// Original withdrawal target; for an operator pause this is not the mint account.
    #[must_use]
    pub fn root(&self) -> &str {
        match self {
            Self::Estate(p) => &p.root,
            Self::Native(p) => &p.root,
            Self::Operator(p) => &p.target,
        }
    }

    /// Original withdrawal receiver Principal, separate from the operator mint account.
    #[must_use]
    pub fn root_principal(&self) -> &str {
        match self {
            Self::Estate(p) => &p.root_principal,
            Self::Native(p) => &p.root_principal,
            Self::Operator(p) => &p.target_principal,
        }
    }

    /// Ledger that owns the operator's source account.
    #[must_use]
    pub fn cycles_ledger(&self) -> &str {
        match self {
            Self::Estate(p) => &p.cycles_ledger,
            Self::Native(p) => &p.cycles_ledger,
            Self::Operator(p) => &p.cycles_ledger,
        }
    }

    /// Balance observed at the paused account or native destination before review.
    #[must_use]
    pub const fn available_cycles(&self) -> u128 {
        match self {
            Self::Estate(p) => p.available_cycles,
            Self::Native(p) => p.available_cycles,
            Self::Operator(p) => p.available_cycles,
        }
    }

    /// Exact additional amount requiring approval.
    #[must_use]
    pub const fn shortfall_cycles(&self) -> u128 {
        match self {
            Self::Estate(p) => p.shortfall_cycles,
            Self::Native(p) => p.shortfall_cycles,
            Self::Operator(p) => p.shortfall_cycles,
        }
    }

    /// Exact operator Ledger fee, separately accounted from the credit.
    #[must_use]
    pub const fn ledger_fee_cycles(&self) -> u128 {
        match self {
            Self::Estate(p) => p.ledger_fee_cycles,
            Self::Native(p) => p.ledger_fee_cycles,
            Self::Operator(p) => p.ledger_fee_cycles,
        }
    }
}

/// Native reserve review bound to one already-issued provisioning effect and Root.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct NativeFundingRequiredRecord {
    #[serde(deserialize_with = "serialization::required_option")]
    pub observation_quote: Option<funding_observation::FundingQuoteSourceRecord>,
    #[serde(with = "u128_text")]
    pub available_cycles: u128,
    pub cycles_ledger: String,
    #[serde(with = "u128_text")]
    pub funding_margin_cycles: u128,
    #[serde(with = "u128_text")]
    pub ledger_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub minimum_cycles: u128,
    pub operation_id: String,
    pub plan_sha256: String,
    pub provisioning_action_sha256: String,
    pub root: String,
    pub root_principal: String,
    #[serde(with = "u128_text")]
    pub shortfall_cycles: u128,
}

/// Management/Ledger evidence available even while runtime activation is incomplete.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NativeFundingObservation {
    pub cycles_ledger: String,
    pub ledger_fee_cycles: u128,
    pub live: LiveCanister,
    pub operator_cycles: u128,
}

pub(in crate::fleet_ensure) mod u128_text {
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(value: &u128, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&value.to_string())
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<u128, D::Error>
    where
        D: Deserializer<'de>,
    {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

pub(crate) mod option_u128_text {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    #[expect(
        clippy::ref_option,
        reason = "serde(with) requires the serializer to accept the field by reference"
    )]
    pub fn serialize<S>(value: &Option<u128>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        value.map(|cycles| cycles.to_string()).serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<u128>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::<String>::deserialize(deserializer)?
            .map(|value| value.parse().map_err(serde::de::Error::custom))
            .transpose()
    }
}

mod u128_text_map {
    use std::collections::BTreeMap;

    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S>(values: &BTreeMap<String, u128>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        values
            .iter()
            .map(|(key, value)| (key, value.to_string()))
            .collect::<BTreeMap<_, _>>()
            .serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<BTreeMap<String, u128>, D::Error>
    where
        D: Deserializer<'de>,
    {
        BTreeMap::<String, String>::deserialize(deserializer)?
            .into_iter()
            .map(|(key, value)| {
                value
                    .parse()
                    .map(|value| (key, value))
                    .map_err(serde::de::Error::custom)
            })
            .collect()
    }
}

/// Conservative base and continuation allowances, with separately reviewed dependent funding.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FleetRecoveryReview {
    #[serde(with = "u128_text")]
    pub base_execution_burn_cycles: u128,
    #[serde(with = "u128_text")]
    pub continuation_reserve_cycles: u128,
    #[serde(with = "u128_text")]
    pub whole_continuation_ceiling_cycles: u128,
    pub maximum_successor_actions: u32,
    pub fixture_publication_retry_attempts: u32,
    #[serde(with = "u128_text")]
    pub per_step_burn_cycles: u128,
    pub startup_funding: Vec<RootStartupFundingForecast>,
    pub known_pool_funding: Vec<PoolRecoveryFunding>,
    /// Current protocol installation and fresh inventory may reveal more work or debit.
    pub discovery: RecoveryDiscovery,
}

/// Configuration-bound native demand, excluding installation margins and dependent pool funding.
///
/// This projection grants no funding authority and credits no observed reuse.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RootStartupFundingForecast {
    pub root: String,
    #[serde(with = "u128_text")]
    pub startup_minimum_cycles: u128,
    pub maximum_continuation_steps: u32,
    #[serde(with = "u128_text")]
    pub continuation_allowance_cycles: u128,
    #[serde(with = "u128_text")]
    pub configured_minimum_cycles: u128,
    #[serde(with = "u128_text")]
    pub required_native_cycles: u128,
    pub reuse_assumption: StartupFundingReuseAssumption,
    #[serde(deserialize_with = "serialization::required_option")]
    pub unfunded_role: Option<StartupRoleShortfall>,
}

/// Conservative scenario used before current installation and pool reuse are established.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StartupFundingReuseAssumption {
    FreshChildrenAndFullPublication,
}

/// Availability of authoritative dependent-work observations at review time.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RecoveryDiscovery {
    PendingCurrentProtocol,
}

/// Exact current pool reset top-up estimate; execution requires its own reviewed Fund action.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PoolRecoveryFunding {
    pub principal: String,
    pub root: String,
    #[serde(with = "u128_text")]
    pub amount_cycles: u128,
    #[serde(with = "u128_text")]
    pub ledger_fee_cycles: u128,
    #[serde(with = "u128_text")]
    pub funding_deficit_cycles: u128,
    #[serde(with = "u128_text")]
    pub funding_margin_cycles: u128,
    #[serde(with = "u128_text")]
    pub expected_post_cycles: u128,
}

/// Informational difference requiring another plan review; never grants effect authority.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FleetSuccessorReview {
    pub actions: Vec<FleetReviewAction>,
    #[serde(with = "u128_text")]
    pub maximum_additional_debit_cycles: u128,
    pub next_review_command: String,
}

/// Exact target and current action kind in a newly observed phase.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct FleetReviewAction {
    pub name: String,
    pub principal: Option<String>,
    pub kind: String,
}

impl std::fmt::Display for FleetSuccessorReview {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "remaining actions: ")?;
        for (index, action) in self.actions.iter().enumerate() {
            if index > 0 {
                write!(f, ", ")?;
            }
            write!(
                f,
                "{} {} ({})",
                action.kind,
                action.name,
                action.principal.as_deref().unwrap_or("not yet created")
            )?;
        }
        write!(
            f,
            "; maximum additional debit including fees: {} cycles; next review: {}",
            self.maximum_additional_debit_cycles, self.next_review_command
        )
    }
}