loop-agent-sdk 0.1.0

Trustless agent SDK for Loop Protocol — intent-based execution on Solana.
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
//! A2A Gateway - Agent-to-Agent Communication Gateway
//!
//! Enforces reputation-based access control for the 22-Layer Stack.
//! Third-party agents must meet reputation thresholds to access protected layers.
//!
//! Security Model:
//! - Layer 1-16: Open to all authenticated agents
//! - Layer 17-20: Requires COLLATERAL_THRESHOLD (300)
//! - Layer 21-22: Requires SWARM_COORDINATOR_THRESHOLD (500)

use crate::reputation_engine::{
    ReputationEngine, TrustScore, TrustTier, CaptureLayer, AttestationRecord,
    SWARM_COORDINATOR_THRESHOLD, COLLATERAL_THRESHOLD,
};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};

// ============================================================================
// CONSTANTS
// ============================================================================

/// Management fee for sub-agent hiring (basis points)
/// 1% = 100 bps
pub const SWARM_MANAGEMENT_FEE_BPS: u64 = 100;

/// Minimum amount to hire a sub-agent (in lamports)
pub const MIN_HIRE_AMOUNT: u64 = 1_000_000; // 1 CRED

/// Referral bounty boost percentage (10% = 1000 basis points)
pub const REFERRAL_BOUNTY_BPS: u32 = 1000;

/// Required tier for referral bounty payout (must have Tier 1 credential)
pub const REFERRAL_BOUNTY_MIN_CREDENTIAL_TIER: u8 = 1;

// ============================================================================
// LAYER 2: REFERRAL BOUNTY SYSTEM
// ============================================================================

/// Tracks referral relationships and bounty payouts
#[derive(Debug, Default)]
pub struct ReferralRegistry {
    /// Map of referred_user -> referrer_agent
    referrals: HashMap<String, ReferralRecord>,
    /// Map of agent_pubkey -> total bounties earned
    agent_bounties: HashMap<String, u32>,
}

/// A single referral record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReferralRecord {
    /// The agent that made the referral
    pub referrer_agent: String,
    /// The user who was referred
    pub referred_user: String,
    /// Whether the referred user has a Tier 1+ credential
    pub has_qualified_credential: bool,
    /// The credential tier of the referred user (if verified)
    pub credential_tier: Option<u8>,
    /// Whether the bounty has been paid out
    pub bounty_paid: bool,
    /// Reputation boost awarded to the referrer
    pub bounty_amount: Option<u32>,
    /// Timestamp of referral
    pub created_at: u64,
    /// Timestamp of bounty payout (if paid)
    pub paid_at: Option<u64>,
}

/// Result of processing a referral bounty
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReferralBountyResult {
    /// Whether the bounty was successfully awarded
    pub success: bool,
    /// The referrer agent's pubkey
    pub referrer_agent: String,
    /// The referred user's pubkey
    pub referred_user: String,
    /// The reputation boost awarded (10% of base score)
    pub reputation_boost: u32,
    /// The referrer's new total reputation
    pub referrer_new_score: Option<u32>,
    /// Reason for failure (if not successful)
    pub failure_reason: Option<String>,
}

impl ReferralRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new referral (called when user joins via agent invite)
    pub fn register_referral(
        &mut self,
        referrer_agent: &str,
        referred_user: &str,
        timestamp: u64,
    ) -> Result<(), String> {
        // Check if already referred
        if self.referrals.contains_key(referred_user) {
            return Err("User already has a referrer".to_string());
        }

        self.referrals.insert(
            referred_user.to_string(),
            ReferralRecord {
                referrer_agent: referrer_agent.to_string(),
                referred_user: referred_user.to_string(),
                has_qualified_credential: false,
                credential_tier: None,
                bounty_paid: false,
                bounty_amount: None,
                created_at: timestamp,
                paid_at: None,
            },
        );

        Ok(())
    }

    /// Update the referred user's credential tier (called on credential verification)
    pub fn update_credential_tier(
        &mut self,
        referred_user: &str,
        credential_tier: u8,
    ) -> bool {
        if let Some(record) = self.referrals.get_mut(referred_user) {
            record.credential_tier = Some(credential_tier);
            record.has_qualified_credential = credential_tier >= REFERRAL_BOUNTY_MIN_CREDENTIAL_TIER;
            return record.has_qualified_credential;
        }
        false
    }

    /// Check if a user was referred and by whom
    pub fn get_referrer(&self, user: &str) -> Option<&str> {
        self.referrals.get(user).map(|r| r.referrer_agent.as_str())
    }

    /// Check if bounty is eligible (has Tier 1+ credential and not yet paid)
    pub fn is_bounty_eligible(&self, referred_user: &str) -> bool {
        self.referrals
            .get(referred_user)
            .map(|r| r.has_qualified_credential && !r.bounty_paid)
            .unwrap_or(false)
    }

    /// Mark bounty as paid and record the amount
    pub fn mark_bounty_paid(
        &mut self,
        referred_user: &str,
        bounty_amount: u32,
        timestamp: u64,
    ) -> bool {
        if let Some(record) = self.referrals.get_mut(referred_user) {
            if record.has_qualified_credential && !record.bounty_paid {
                record.bounty_paid = true;
                record.bounty_amount = Some(bounty_amount);
                record.paid_at = Some(timestamp);

                // Track agent's total bounties
                *self
                    .agent_bounties
                    .entry(record.referrer_agent.clone())
                    .or_default() += bounty_amount;

                return true;
            }
        }
        false
    }

    /// Get total bounties earned by an agent
    pub fn get_agent_bounties(&self, agent_pubkey: &str) -> u32 {
        self.agent_bounties.get(agent_pubkey).copied().unwrap_or(0)
    }

    /// Get all referrals made by an agent
    pub fn get_agent_referrals(&self, agent_pubkey: &str) -> Vec<&ReferralRecord> {
        self.referrals
            .values()
            .filter(|r| r.referrer_agent == agent_pubkey)
            .collect()
    }
}

// ============================================================================
// ERROR TYPES
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GatewayError {
    /// Agent not authenticated
    Unauthorized {
        message: String,
    },
    /// Agent lacks required reputation
    Forbidden {
        message: String,
        required_threshold: u32,
        current_score: u32,
        required_tier: String,
        current_tier: String,
    },
    /// Invalid request format
    BadRequest {
        message: String,
    },
    /// Rate limit exceeded
    RateLimited {
        retry_after_ms: u64,
    },
    /// Internal error
    Internal {
        message: String,
    },
}

impl std::fmt::Display for GatewayError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GatewayError::Unauthorized { message } => {
                write!(f, "Unauthorized: {}", message)
            }
            GatewayError::Forbidden { message, required_threshold, current_score, .. } => {
                write!(f, "Forbidden: {} (need {}, have {})", message, required_threshold, current_score)
            }
            GatewayError::BadRequest { message } => {
                write!(f, "Bad Request: {}", message)
            }
            GatewayError::RateLimited { retry_after_ms } => {
                write!(f, "Rate Limited: retry after {}ms", retry_after_ms)
            }
            GatewayError::Internal { message } => {
                write!(f, "Internal Error: {}", message)
            }
        }
    }
}

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

// ============================================================================
// SUB-AGENT REGISTRY & FEE CAPTURE
// ============================================================================

/// Tracks active sub-agent relationships per user
#[derive(Debug, Default)]
pub struct SubAgentRegistry {
    /// Map of user_pubkey -> set of hired sub-agent pubkeys
    active_hires: HashMap<String, HashSet<String>>,
    /// Map of user_pubkey -> total fees captured (lamports)
    fees_captured: HashMap<String, u64>,
}

impl SubAgentRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Get count of currently hired sub-agents
    pub fn hired_count(&self, user_pubkey: &str) -> usize {
        self.active_hires
            .get(user_pubkey)
            .map(|s| s.len())
            .unwrap_or(0)
    }

    /// Check if a specific sub-agent is already hired
    pub fn is_hired(&self, user_pubkey: &str, sub_agent_pubkey: &str) -> bool {
        self.active_hires
            .get(user_pubkey)
            .map(|s| s.contains(sub_agent_pubkey))
            .unwrap_or(false)
    }

    /// Add a hired sub-agent
    pub fn add_hire(&mut self, user_pubkey: &str, sub_agent_pubkey: &str) {
        self.active_hires
            .entry(user_pubkey.to_string())
            .or_default()
            .insert(sub_agent_pubkey.to_string());
    }

    /// Remove a sub-agent (contract ended)
    pub fn remove_hire(&mut self, user_pubkey: &str, sub_agent_pubkey: &str) -> bool {
        self.active_hires
            .get_mut(user_pubkey)
            .map(|s| s.remove(sub_agent_pubkey))
            .unwrap_or(false)
    }

    /// Record captured fee
    pub fn record_fee(&mut self, user_pubkey: &str, fee_lamports: u64) {
        *self.fees_captured.entry(user_pubkey.to_string()).or_default() += fee_lamports;
    }

    /// Get total fees captured for a user
    pub fn total_fees(&self, user_pubkey: &str) -> u64 {
        self.fees_captured.get(user_pubkey).copied().unwrap_or(0)
    }

    /// Get all active sub-agents for a user
    pub fn list_hires(&self, user_pubkey: &str) -> Vec<String> {
        self.active_hires
            .get(user_pubkey)
            .map(|s| s.iter().cloned().collect())
            .unwrap_or_default()
    }
}

/// Result of a sub-agent hire operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HireResult {
    /// Whether the hire was successful
    pub success: bool,
    /// The sub-agent that was hired
    pub sub_agent_pubkey: String,
    /// Task allocated to the sub-agent
    pub task_id: String,
    /// Budget allocated (after fee deduction)
    pub net_budget: u64,
    /// Management fee captured (1%)
    pub fee_captured: u64,
    /// Current count of hired sub-agents
    pub current_hired_count: usize,
    /// Maximum allowed based on tier
    pub max_allowed: u8,
    /// User's current trust tier
    pub user_tier: TrustTier,
}

/// Result of a swarm coordination operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SwarmCoordinationResult {
    /// Whether coordination was successful
    pub success: bool,
    /// Task ID
    pub task_id: String,
    /// Sub-agents successfully hired
    pub hired_agents: Vec<String>,
    /// Total budget allocated
    pub total_net_budget: u64,
    /// Total fees captured
    pub total_fees_captured: u64,
    /// Any agents that failed to hire
    pub failed_agents: Vec<(String, String)>, // (pubkey, reason)
}

// ============================================================================
// REQUEST TYPES
// ============================================================================

/// Incoming A2A request from an external agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2ARequest {
    /// Requesting agent's public key
    pub agent_pubkey: String,
    /// Target user's public key (whose vault to act on)
    pub user_pubkey: String,
    /// Session token (JWT from handshake)
    pub session_token: String,
    /// Requested action
    pub action: SwarmAction,
    /// Optional parameters
    pub params: Option<serde_json::Value>,
    /// Request timestamp (Unix ms)
    pub timestamp: u64,
    /// Request signature (agent signs the request)
    pub signature: Option<String>,
}

/// Actions that can be requested through the gateway
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SwarmAction {
    // ========== Layer 1-5: Passive Utility (Open) ==========
    /// Capture shopping reward
    CaptureReward {
        merchant_id: String,
        amount: u64,
        transaction_ref: String,
    },
    /// Track referral
    TrackReferral {
        referral_code: String,
        conversion_amount: Option<u64>,
    },
    /// Submit attention proof
    SubmitAttention {
        content_id: String,
        duration_ms: u64,
    },
    /// License data
    LicenseData {
        data_type: String,
        buyer: String,
        terms_hash: String,
    },
    /// Join insurance pool
    JoinInsurancePool {
        pool_id: String,
        coverage_amount: u64,
    },

    // ========== Layer 6-11: Infrastructure (Open) ==========
    /// Register compute capacity
    RegisterCompute {
        gpu_type: String,
        available_hours: u32,
    },
    /// Run network node
    RunNode {
        node_type: String,
        uptime_commitment: u8,
    },
    /// Energy arbitrage trade
    EnergyTrade {
        direction: String, // "buy" | "sell"
        kwh: f64,
        price_per_kwh: f64,
    },

    // ========== Layer 12-16: Intelligence (Open) ==========
    /// License behavioral model
    LicenseSkill {
        skill_type: String,
        license_terms: String,
    },
    /// Submit curation signal
    SubmitCuration {
        signal_type: String,
        signal_data: String,
    },
    /// Social monetization
    SocialAction {
        action_type: String,
        target: String,
    },

    // ========== Layer 17-20: Aggressive Autopilot (Requires COLLATERAL_THRESHOLD) ==========
    /// Deploy liquidity
    DeployLiquidity {
        pool: String,
        amount: u64,
        strategy: String,
    },
    /// Cast governance vote
    CastVote {
        proposal_id: String,
        vote: String,
        delegation_power: u64,
    },
    /// Bulk inventory purchase
    BulkPurchase {
        merchant_id: String,
        items: Vec<String>,
        max_spend: u64,
    },
    
    // ========== Layer 20: Sub-Agent Manager (Requires COLLATERAL_THRESHOLD) ==========
    /// Hire a sub-agent for a specific task
    HireSubAgent {
        sub_agent_pubkey: String,
        task_description: String,
        max_budget: u64,
        deadline: u64,
    },

    // ========== Layer 21: Reputation Collateral (Requires COLLATERAL_THRESHOLD) ==========
    /// Use reputation as DeFi collateral
    PledgeReputation {
        protocol: String,
        loan_amount: u64,
        collateral_score: u32,
    },

    // ========== Layer 22: Swarm Coordination (Requires SWARM_COORDINATOR_THRESHOLD) ==========
    /// Coordinate multiple sub-agents for complex task
    CoordinateSwarm {
        task_id: String,
        sub_agents: Vec<String>,
        task_allocation: HashMap<String, String>,
        total_budget: u64,
        coordination_fee_bps: u16,
    },
    /// Become a general contractor for other agents
    AcceptContract {
        contract_id: String,
        requester: String,
        deliverables: Vec<String>,
        payment: u64,
    },
    /// Distribute rewards to sub-agents
    DistributeRewards {
        task_id: String,
        distributions: HashMap<String, u64>,
    },
}

impl SwarmAction {
    /// Get the capture layer this action belongs to
    pub fn layer(&self) -> CaptureLayer {
        match self {
            SwarmAction::CaptureReward { .. } => CaptureLayer::Shopping,
            SwarmAction::TrackReferral { .. } => CaptureLayer::Referral,
            SwarmAction::SubmitAttention { .. } => CaptureLayer::Attention,
            SwarmAction::LicenseData { .. } => CaptureLayer::Data,
            SwarmAction::JoinInsurancePool { .. } => CaptureLayer::Insurance,
            SwarmAction::RegisterCompute { .. } => CaptureLayer::Compute,
            SwarmAction::RunNode { .. } => CaptureLayer::Network,
            SwarmAction::EnergyTrade { .. } => CaptureLayer::Energy,
            SwarmAction::LicenseSkill { .. } => CaptureLayer::Skill,
            SwarmAction::SubmitCuration { .. } => CaptureLayer::CurationSignal,
            SwarmAction::SocialAction { .. } => CaptureLayer::Social,
            SwarmAction::DeployLiquidity { .. } => CaptureLayer::Liquidity,
            SwarmAction::CastVote { .. } => CaptureLayer::GovernanceProxy,
            SwarmAction::BulkPurchase { .. } => CaptureLayer::InventoryArbitrage,
            SwarmAction::HireSubAgent { .. } => CaptureLayer::SubAgentManager,
            SwarmAction::PledgeReputation { .. } => CaptureLayer::ReputationCollateral,
            SwarmAction::CoordinateSwarm { .. } => CaptureLayer::SwarmCoordinationFee,
            SwarmAction::AcceptContract { .. } => CaptureLayer::SwarmCoordinationFee,
            SwarmAction::DistributeRewards { .. } => CaptureLayer::SwarmCoordinationFee,
        }
    }

    /// Get the minimum reputation score required for this action
    pub fn required_score(&self) -> u32 {
        match self.layer() {
            // Layers 1-16: Open to all
            CaptureLayer::Shopping
            | CaptureLayer::Referral
            | CaptureLayer::Attention
            | CaptureLayer::Data
            | CaptureLayer::Insurance
            | CaptureLayer::Compute
            | CaptureLayer::Network
            | CaptureLayer::Energy
            | CaptureLayer::DePINAggregator
            | CaptureLayer::InferenceArbitrage
            | CaptureLayer::StorageDePIN
            | CaptureLayer::Skill
            | CaptureLayer::CurationSignal
            | CaptureLayer::Social
            | CaptureLayer::KnowledgeAPI
            | CaptureLayer::PersonalModelLicensing => 0,

            // Layers 17-21: Aggressive Autopilot (Requires collateral threshold)
            CaptureLayer::Liquidity
            | CaptureLayer::GovernanceProxy
            | CaptureLayer::InventoryArbitrage
            | CaptureLayer::SubAgentManager
            | CaptureLayer::ReputationCollateral => COLLATERAL_THRESHOLD,

            // Layer 22: Swarm Coordination (Highest threshold)
            CaptureLayer::SwarmCoordinationFee => SWARM_COORDINATOR_THRESHOLD,
        }
    }

    /// Check if this is a swarm coordination action (Layer 22)
    pub fn is_swarm_action(&self) -> bool {
        matches!(
            self,
            SwarmAction::CoordinateSwarm { .. }
                | SwarmAction::AcceptContract { .. }
                | SwarmAction::DistributeRewards { .. }
        )
    }

    /// Check if this requires collateral-level reputation
    pub fn requires_collateral(&self) -> bool {
        self.required_score() >= COLLATERAL_THRESHOLD
    }
}

// ============================================================================
// RESPONSE TYPES
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2AResponse {
    /// Whether the request was successful
    pub success: bool,
    /// Request ID for tracking
    pub request_id: String,
    /// Result data (if successful)
    pub data: Option<serde_json::Value>,
    /// Error details (if failed)
    pub error: Option<GatewayError>,
    /// Processing time in ms
    pub processing_ms: u64,
    /// Reputation impact of this action
    pub reputation_delta: Option<i32>,
}

// ============================================================================
// PERMISSION CHECK RESULT
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionCheck {
    /// Whether access is granted
    pub allowed: bool,
    /// The action's capture layer
    pub layer: String,
    /// Required score for this action
    pub required_score: u32,
    /// User's current composite score
    pub current_score: u32,
    /// User's current tier
    pub current_tier: TrustTier,
    /// Required tier for this action
    pub required_tier: TrustTier,
    /// Specific threshold proof checked
    pub threshold_checked: Option<String>,
    /// Points needed to unlock (if denied)
    pub points_needed: Option<u32>,
    /// Suggested actions to increase score
    pub unlock_suggestions: Vec<String>,
}

// ============================================================================
// GATEWAY
// ============================================================================

/// A2A Gateway with reputation-based access control
pub struct Gateway {
    /// Reputation engines for users (keyed by pubkey)
    reputation_cache: Arc<RwLock<HashMap<String, ReputationEngine>>>,
    /// Rate limiter (requests per minute per agent)
    rate_limits: Arc<RwLock<HashMap<String, RateLimitState>>>,
    /// Maximum requests per minute per agent
    max_requests_per_minute: u32,
    /// Sub-agent registry for tracking active hires and fees
    sub_agent_registry: Arc<RwLock<SubAgentRegistry>>,
    /// Referral registry for Layer 2 bounty tracking
    referral_registry: Arc<RwLock<ReferralRegistry>>,
}

struct RateLimitState {
    count: u32,
    window_start: u64,
}

impl Gateway {
    /// Create a new gateway
    pub fn new() -> Self {
        Self {
            reputation_cache: Arc::new(RwLock::new(HashMap::new())),
            rate_limits: Arc::new(RwLock::new(HashMap::new())),
            max_requests_per_minute: 100,
            sub_agent_registry: Arc::new(RwLock::new(SubAgentRegistry::new())),
            referral_registry: Arc::new(RwLock::new(ReferralRegistry::new())),
        }
    }

    /// Create gateway with custom rate limit
    pub fn with_rate_limit(max_requests_per_minute: u32) -> Self {
        Self {
            reputation_cache: Arc::new(RwLock::new(HashMap::new())),
            rate_limits: Arc::new(RwLock::new(HashMap::new())),
            max_requests_per_minute,
            sub_agent_registry: Arc::new(RwLock::new(SubAgentRegistry::new())),
            referral_registry: Arc::new(RwLock::new(ReferralRegistry::new())),
        }
    }

    // ========================================================================
    // CORE PERMISSION CHECK - THE SWARM SECURITY GATE
    // ========================================================================

    /// Check if an agent has permission to execute an action
    /// 
    /// This is the critical security function that enforces reputation-based
    /// access control for the 22-Layer Stack.
    /// 
    /// # Security Model
    /// 
    /// ```text
    /// ┌─────────────────────────────────────────────────────────────────┐
    /// │                    PERMISSION CHECK FLOW                        │
    /// ├─────────────────────────────────────────────────────────────────┤
    /// │                                                                 │
    /// │  Request → Rate Limit Check → Session Verify → Reputation Check │
    /// │                                                                 │
    /// │  Layer 1-16:  score >= 0     → ALLOW                           │
    /// │  Layer 17-21: score >= 300   → ALLOW (Collateral Threshold)    │
    /// │  Layer 22:    score >= 500   → ALLOW (Swarm Coordinator)       │
    /// │                                                                 │
    /// │  Below threshold → 403 FORBIDDEN                               │
    /// │                                                                 │
    /// └─────────────────────────────────────────────────────────────────┘
    /// ```
    pub fn check_permission(
        &self,
        user_pubkey: &str,
        action: &SwarmAction,
    ) -> Result<PermissionCheck, GatewayError> {
        // Get or create reputation engine for this user
        let mut cache = self.reputation_cache.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire reputation cache lock".to_string(),
            }
        })?;

        let engine = cache
            .entry(user_pubkey.to_string())
            .or_insert_with(|| ReputationEngine::new(user_pubkey.to_string()));

        // Calculate current trust score
        let trust_score = engine.calculate_trust_score();
        let current_score = trust_score.composite;
        let current_tier = trust_score.tier;

        // Get required score for this action
        let required_score = action.required_score();
        let required_tier = TrustTier::from_score(required_score);
        let layer = format!("{:?}", action.layer());

        // ====================================================================
        // THE CRITICAL CHECK: Is score >= required_score?
        // ====================================================================
        let allowed = current_score >= required_score;

        // For swarm actions, also check the specific threshold proof
        let threshold_checked = if action.is_swarm_action() {
            Some("swarm_coordinator".to_string())
        } else if action.requires_collateral() {
            Some("collateral_eligible".to_string())
        } else {
            None
        };

        // If denied, calculate points needed and suggestions
        let (points_needed, unlock_suggestions) = if !allowed {
            let needed = required_score - current_score;
            let suggestions = self.generate_unlock_suggestions(needed, &trust_score);
            (Some(needed), suggestions)
        } else {
            (None, vec![])
        };

        Ok(PermissionCheck {
            allowed,
            layer,
            required_score,
            current_score,
            current_tier,
            required_tier,
            threshold_checked,
            points_needed,
            unlock_suggestions,
        })
    }

    /// Enforce permission check - returns Ok(()) if allowed, Err(Forbidden) if not
    /// 
    /// USE THIS for actual enforcement in request handlers.
    pub fn enforce_permission(
        &self,
        user_pubkey: &str,
        action: &SwarmAction,
    ) -> Result<(), GatewayError> {
        let check = self.check_permission(user_pubkey, action)?;

        if !check.allowed {
            return Err(GatewayError::Forbidden {
                message: format!(
                    "Insufficient reputation for {:?} (Layer {}). Need {} points, have {}.",
                    action.layer(),
                    action.layer() as u8,
                    check.required_score,
                    check.current_score
                ),
                required_threshold: check.required_score,
                current_score: check.current_score,
                required_tier: format!("{:?}", check.required_tier),
                current_tier: format!("{:?}", check.current_tier),
            });
        }

        Ok(())
    }

    /// Specific check for Layer 22 Swarm Coordination
    /// 
    /// Returns 403 Forbidden if threshold_proofs["swarm_coordinator"] is false.
    pub fn enforce_swarm_permission(&self, user_pubkey: &str) -> Result<(), GatewayError> {
        let mut cache = self.reputation_cache.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire reputation cache lock".to_string(),
            }
        })?;

        let engine = cache
            .entry(user_pubkey.to_string())
            .or_insert_with(|| ReputationEngine::new(user_pubkey.to_string()));

        let trust_score = engine.calculate_trust_score();

        // Check the specific threshold proof
        let swarm_allowed = trust_score
            .threshold_proofs
            .get("swarm_coordinator")
            .copied()
            .unwrap_or(false);

        if !swarm_allowed {
            return Err(GatewayError::Forbidden {
                message: format!(
                    "Swarm coordination requires {} reputation points. Current: {}. Tier: {:?}.",
                    SWARM_COORDINATOR_THRESHOLD,
                    trust_score.composite,
                    trust_score.tier
                ),
                required_threshold: SWARM_COORDINATOR_THRESHOLD,
                current_score: trust_score.composite,
                required_tier: "Trusted".to_string(),
                current_tier: format!("{:?}", trust_score.tier),
            });
        }

        Ok(())
    }

    // ========================================================================
    // RATE LIMITING
    // ========================================================================

    /// Check rate limit for an agent
    pub fn check_rate_limit(&self, agent_pubkey: &str) -> Result<(), GatewayError> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;

        let mut limits = self.rate_limits.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire rate limit lock".to_string(),
            }
        })?;

        let state = limits
            .entry(agent_pubkey.to_string())
            .or_insert(RateLimitState {
                count: 0,
                window_start: now,
            });

        // Reset window if more than 1 minute has passed
        if now - state.window_start > 60_000 {
            state.count = 0;
            state.window_start = now;
        }

        // Check if over limit
        if state.count >= self.max_requests_per_minute {
            let retry_after = 60_000 - (now - state.window_start);
            return Err(GatewayError::RateLimited {
                retry_after_ms: retry_after,
            });
        }

        // Increment counter
        state.count += 1;

        Ok(())
    }

    // ========================================================================
    // FULL REQUEST PROCESSING
    // ========================================================================

    /// Process a full A2A request with all security checks
    pub fn process_request(&self, request: &A2ARequest) -> Result<PermissionCheck, GatewayError> {
        // 1. Rate limit check
        self.check_rate_limit(&request.agent_pubkey)?;

        // 2. Permission check based on action and user reputation
        let permission = self.check_permission(&request.user_pubkey, &request.action)?;

        // 3. If not allowed, return Forbidden error
        if !permission.allowed {
            return Err(GatewayError::Forbidden {
                message: format!(
                    "Action {:?} requires {} reputation. User has {}.",
                    request.action.layer(),
                    permission.required_score,
                    permission.current_score
                ),
                required_threshold: permission.required_score,
                current_score: permission.current_score,
                required_tier: format!("{:?}", permission.required_tier),
                current_tier: format!("{:?}", permission.current_tier),
            });
        }

        Ok(permission)
    }

    // ========================================================================
    // REPUTATION MANAGEMENT
    // ========================================================================

    /// Get reputation engine for a user (creates if not exists)
    pub fn get_reputation(&self, user_pubkey: &str) -> Result<TrustScore, GatewayError> {
        let mut cache = self.reputation_cache.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire reputation cache lock".to_string(),
            }
        })?;

        let engine = cache
            .entry(user_pubkey.to_string())
            .or_insert_with(|| ReputationEngine::new(user_pubkey.to_string()));

        Ok(engine.calculate_trust_score())
    }

    /// Update reputation with attestation (used after successful actions)
    pub fn record_attestation(
        &self,
        user_pubkey: &str,
        attestation: &crate::reputation_engine::AttestationRecord,
    ) -> Result<TrustScore, GatewayError> {
        let mut cache = self.reputation_cache.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire reputation cache lock".to_string(),
            }
        })?;

        let engine = cache
            .entry(user_pubkey.to_string())
            .or_insert_with(|| ReputationEngine::new(user_pubkey.to_string()));

        engine.process_attestation(attestation);
        Ok(engine.calculate_trust_score())
    }

    // ========================================================================
    // LAYER 22: SWARM COORDINATION & SUB-AGENT HIRING
    // ========================================================================

    /// Hire a sub-agent for a specific task
    /// 
    /// # Security Rules:
    /// 1. User must have sufficient reputation (Layer 20 for hire, Layer 22 for swarm)
    /// 2. User cannot exceed their tier's max_sub_agents limit
    /// 3. A 1% management fee is captured and deposited to user's vault
    /// 
    /// # Fee Capture Flow:
    /// ```text
    /// User Budget: 1000 CRED
    /// Fee (1%):       10 CRED → User's Vault
    /// Net to Agent:  990 CRED → Sub-Agent
    /// ```
    pub fn hire_sub_agent(
        &self,
        user_pubkey: &str,
        sub_agent_pubkey: &str,
        task_id: &str,
        budget: u64,
    ) -> Result<HireResult, GatewayError> {
        // Validate minimum budget
        if budget < MIN_HIRE_AMOUNT {
            return Err(GatewayError::BadRequest {
                message: format!(
                    "Budget too low. Minimum: {} lamports, provided: {}",
                    MIN_HIRE_AMOUNT, budget
                ),
            });
        }

        // Get user's reputation and tier
        let trust_score = self.get_reputation(user_pubkey)?;
        let max_allowed = trust_score.tier.max_sub_agents();

        // Check Layer 20 permission (SubAgentManager)
        let action = SwarmAction::HireSubAgent {
            sub_agent_pubkey: sub_agent_pubkey.to_string(),
            task_description: task_id.to_string(),
            max_budget: budget,
            deadline: 0, // Not used for permission check
        };
        self.enforce_permission(user_pubkey, &action)?;

        // Lock registry and check limits
        let mut registry = self.sub_agent_registry.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire sub-agent registry lock".to_string(),
            }
        })?;

        let current_count = registry.hired_count(user_pubkey);

        // ====================================================================
        // THE CRITICAL CHECK: Is hired_count < max_allowed?
        // ====================================================================
        if current_count >= max_allowed as usize {
            return Err(GatewayError::Forbidden {
                message: format!(
                    "Sub-agent limit reached. Tier {:?} allows max {} sub-agents. Currently hired: {}.",
                    trust_score.tier, max_allowed, current_count
                ),
                required_threshold: SWARM_COORDINATOR_THRESHOLD,
                current_score: trust_score.composite,
                required_tier: format!("{:?}", TrustTier::from_score(SWARM_COORDINATOR_THRESHOLD)),
                current_tier: format!("{:?}", trust_score.tier),
            });
        }

        // Check if already hired
        if registry.is_hired(user_pubkey, sub_agent_pubkey) {
            return Err(GatewayError::BadRequest {
                message: format!("Sub-agent {} is already hired", sub_agent_pubkey),
            });
        }

        // ====================================================================
        // FEE CAPTURE: Deduct 1% management fee
        // ====================================================================
        let fee = (budget * SWARM_MANAGEMENT_FEE_BPS) / 10_000;
        let net_budget = budget - fee;

        // Record the hire
        registry.add_hire(user_pubkey, sub_agent_pubkey);
        registry.record_fee(user_pubkey, fee);

        Ok(HireResult {
            success: true,
            sub_agent_pubkey: sub_agent_pubkey.to_string(),
            task_id: task_id.to_string(),
            net_budget,
            fee_captured: fee,
            current_hired_count: current_count + 1,
            max_allowed,
            user_tier: trust_score.tier,
        })
    }

    /// Coordinate multiple sub-agents for a complex task (Layer 22)
    /// 
    /// This is the highest-tier operation requiring Elite-level reputation.
    /// Orchestrates multiple sub-agents for parallel task execution.
    pub fn coordinate_swarm(
        &self,
        user_pubkey: &str,
        task_id: &str,
        sub_agents: &[String],
        budget_per_agent: u64,
    ) -> Result<SwarmCoordinationResult, GatewayError> {
        // Enforce Layer 22 (Swarm Coordination) permission
        self.enforce_swarm_permission(user_pubkey)?;

        let trust_score = self.get_reputation(user_pubkey)?;
        let max_allowed = trust_score.tier.max_sub_agents();

        // Check if total would exceed limit
        let mut registry = self.sub_agent_registry.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire sub-agent registry lock".to_string(),
            }
        })?;

        let current_count = registry.hired_count(user_pubkey);
        let total_after = current_count + sub_agents.len();

        if total_after > max_allowed as usize {
            return Err(GatewayError::Forbidden {
                message: format!(
                    "Swarm size exceeds limit. Tier {:?} allows {} sub-agents. Current: {}, Requested: {}.",
                    trust_score.tier, max_allowed, current_count, sub_agents.len()
                ),
                required_threshold: SWARM_COORDINATOR_THRESHOLD,
                current_score: trust_score.composite,
                required_tier: "Elite".to_string(),
                current_tier: format!("{:?}", trust_score.tier),
            });
        }

        let mut hired_agents = Vec::new();
        let mut failed_agents = Vec::new();
        let mut total_fees = 0u64;
        let mut total_net = 0u64;

        // Process each sub-agent
        for sub_agent in sub_agents {
            if registry.is_hired(user_pubkey, sub_agent) {
                failed_agents.push((sub_agent.clone(), "Already hired".to_string()));
                continue;
            }

            // Calculate fee
            let fee = (budget_per_agent * SWARM_MANAGEMENT_FEE_BPS) / 10_000;
            let net = budget_per_agent - fee;

            // Record hire
            registry.add_hire(user_pubkey, sub_agent);
            registry.record_fee(user_pubkey, fee);

            hired_agents.push(sub_agent.clone());
            total_fees += fee;
            total_net += net;
        }

        Ok(SwarmCoordinationResult {
            success: !hired_agents.is_empty(),
            task_id: task_id.to_string(),
            hired_agents,
            total_net_budget: total_net,
            total_fees_captured: total_fees,
            failed_agents,
        })
    }

    /// Release a sub-agent (end contract)
    pub fn release_sub_agent(
        &self,
        user_pubkey: &str,
        sub_agent_pubkey: &str,
    ) -> Result<bool, GatewayError> {
        let mut registry = self.sub_agent_registry.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire sub-agent registry lock".to_string(),
            }
        })?;

        Ok(registry.remove_hire(user_pubkey, sub_agent_pubkey))
    }

    /// Get sub-agent status for a user
    pub fn get_sub_agent_status(&self, user_pubkey: &str) -> Result<(Vec<String>, u64, u8), GatewayError> {
        let trust_score = self.get_reputation(user_pubkey)?;
        let max_allowed = trust_score.tier.max_sub_agents();

        let registry = self.sub_agent_registry.read().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire sub-agent registry lock".to_string(),
            }
        })?;

        let hired = registry.list_hires(user_pubkey);
        let fees = registry.total_fees(user_pubkey);

        Ok((hired, fees, max_allowed))
    }

    // ========================================================================
    // LAYER 2: REFERRAL BOUNTY SYSTEM
    // ========================================================================

    /// Register a new referral when a user joins via agent invite code
    /// 
    /// Called when: User redeems an invite code issued by an agent
    pub fn register_referral(
        &self,
        referrer_agent: &str,
        referred_user: &str,
    ) -> Result<(), GatewayError> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut registry = self.referral_registry.write().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire referral registry lock".to_string(),
            }
        })?;

        registry
            .register_referral(referrer_agent, referred_user, now)
            .map_err(|msg| GatewayError::BadRequest { message: msg })
    }

    /// Process a referral bounty when a referred user verifies a Tier 1+ credential
    /// 
    /// # Bounty Rules:
    /// 1. The referred user must have been invited by an agent (registered referral)
    /// 2. The referred user must verify a Tier 1 or higher credential
    /// 3. The bounty is 10% of the referrer agent's current base reputation score
    /// 4. Each referral can only be paid once
    /// 
    /// # Returns:
    /// ReferralBountyResult with the boost amount and new score
    pub fn process_referral_bounty(
        &self,
        referred_user: &str,
        verified_credential_tier: u8,
    ) -> Result<ReferralBountyResult, GatewayError> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Get the referrer agent
        let referrer_agent = {
            let registry = self.referral_registry.read().map_err(|_| {
                GatewayError::Internal {
                    message: "Failed to acquire referral registry lock".to_string(),
                }
            })?;

            match registry.get_referrer(referred_user) {
                Some(agent) => agent.to_string(),
                None => {
                    return Ok(ReferralBountyResult {
                        success: false,
                        referrer_agent: String::new(),
                        referred_user: referred_user.to_string(),
                        reputation_boost: 0,
                        referrer_new_score: None,
                        failure_reason: Some("User was not referred by an agent".to_string()),
                    });
                }
            }
        };

        // Update credential tier and check if qualified
        {
            let mut registry = self.referral_registry.write().map_err(|_| {
                GatewayError::Internal {
                    message: "Failed to acquire referral registry lock".to_string(),
                }
            })?;

            registry.update_credential_tier(referred_user, verified_credential_tier);

            if !registry.is_bounty_eligible(referred_user) {
                return Ok(ReferralBountyResult {
                    success: false,
                    referrer_agent: referrer_agent.clone(),
                    referred_user: referred_user.to_string(),
                    reputation_boost: 0,
                    referrer_new_score: None,
                    failure_reason: Some(format!(
                        "Credential tier {} does not meet minimum requirement of Tier {}",
                        verified_credential_tier, REFERRAL_BOUNTY_MIN_CREDENTIAL_TIER
                    )),
                });
            }
        }

        // Calculate 10% bounty based on referrer's current score
        let referrer_score = self.get_reputation(&referrer_agent)?;
        let bounty_amount = (referrer_score.composite * REFERRAL_BOUNTY_BPS) / 10000;

        // Award the reputation boost to the referrer
        let attestation = AttestationRecord {
            layer: CaptureLayer::Referral,
            timestamp: now,
            positive: true,
            magnitude: bounty_amount as u64 * 1_000_000, // Convert to lamport-equivalent
            metadata: Some(crate::reputation_engine::AttestationMetadata {
                referral_successful: Some(true),
                ..Default::default()
            }),
        };

        let new_score = self.record_attestation(&referrer_agent, &attestation)?;

        // Mark bounty as paid
        {
            let mut registry = self.referral_registry.write().map_err(|_| {
                GatewayError::Internal {
                    message: "Failed to acquire referral registry lock".to_string(),
                }
            })?;

            registry.mark_bounty_paid(referred_user, bounty_amount, now);
        }

        Ok(ReferralBountyResult {
            success: true,
            referrer_agent,
            referred_user: referred_user.to_string(),
            reputation_boost: bounty_amount,
            referrer_new_score: Some(new_score.composite),
            failure_reason: None,
        })
    }

    /// Get referral statistics for an agent
    pub fn get_agent_referral_stats(
        &self,
        agent_pubkey: &str,
    ) -> Result<(Vec<ReferralRecord>, u32), GatewayError> {
        let registry = self.referral_registry.read().map_err(|_| {
            GatewayError::Internal {
                message: "Failed to acquire referral registry lock".to_string(),
            }
        })?;

        let referrals: Vec<ReferralRecord> = registry
            .get_agent_referrals(agent_pubkey)
            .into_iter()
            .cloned()
            .collect();

        let total_bounties = registry.get_agent_bounties(agent_pubkey);

        Ok((referrals, total_bounties))
    }

    // ========================================================================
    // HELPERS
    // ========================================================================

    /// Generate suggestions for how to increase reputation
    fn generate_unlock_suggestions(&self, points_needed: u32, score: &TrustScore) -> Vec<String> {
        let mut suggestions = vec![];

        // Suggest based on which dimensions are lowest
        if score.reliability < 300 {
            suggestions.push(format!(
                "Stack CRED for 90+ days to boost Reliability (+{} potential points)",
                300 - score.reliability
            ));
        }

        if score.skill < 200 {
            suggestions.push(format!(
                "Submit high-accuracy data captures to boost Skill (+{} potential points)",
                200 - score.skill
            ));
        }

        if score.infrastructure < 200 {
            suggestions.push(
                "Run a network node or provide compute to boost Infrastructure".to_string(),
            );
        }

        if score.social < 150 {
            suggestions.push("Invite friends or complete referrals to boost Social".to_string());
        }

        // Generic suggestions
        if points_needed > 200 {
            suggestions.push(format!(
                "You need {} more points. Focus on your weakest dimension.",
                points_needed
            ));
        }

        suggestions
    }
}

impl Default for Gateway {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::reputation_engine::{AttestationMetadata, AttestationRecord};

    #[test]
    fn test_layer_1_always_allowed() {
        let gateway = Gateway::new();
        
        let action = SwarmAction::CaptureReward {
            merchant_id: "merchant123".to_string(),
            amount: 1000,
            transaction_ref: "tx123".to_string(),
        };

        let check = gateway.check_permission("new_user", &action).unwrap();
        assert!(check.allowed);
        assert_eq!(check.required_score, 0);
    }

    #[test]
    fn test_layer_22_requires_swarm_threshold() {
        let gateway = Gateway::new();

        let action = SwarmAction::CoordinateSwarm {
            task_id: "task123".to_string(),
            sub_agents: vec!["agent1".to_string(), "agent2".to_string()],
            task_allocation: HashMap::new(),
            total_budget: 10000,
            coordination_fee_bps: 500,
        };

        // New user should be denied
        let check = gateway.check_permission("new_user", &action).unwrap();
        assert!(!check.allowed);
        assert_eq!(check.required_score, SWARM_COORDINATOR_THRESHOLD);
        assert!(check.points_needed.is_some());
    }

    #[test]
    fn test_enforce_swarm_returns_403() {
        let gateway = Gateway::new();

        let result = gateway.enforce_swarm_permission("new_user");
        assert!(result.is_err());

        match result.unwrap_err() {
            GatewayError::Forbidden { required_threshold, .. } => {
                assert_eq!(required_threshold, SWARM_COORDINATOR_THRESHOLD);
            }
            _ => panic!("Expected Forbidden error"),
        }
    }

    #[test]
    fn test_reputation_increases_access() {
        let gateway = Gateway::new();

        // Add many attestations to build reputation
        for i in 0..100 {
            let attestation = AttestationRecord {
                layer: CaptureLayer::Shopping,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: 100_000_000,
                metadata: Some(AttestationMetadata {
                    lock_duration_days: Some(365),
                    held_to_maturity: Some(true),
                    ..Default::default()
                }),
            };
            gateway.record_attestation("power_user", &attestation).unwrap();
        }

        // Add more from other layers
        for i in 0..50 {
            let attestation = AttestationRecord {
                layer: CaptureLayer::Skill,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: 10_000_000,
                metadata: Some(AttestationMetadata {
                    accuracy_percent: Some(95),
                    ..Default::default()
                }),
            };
            gateway.record_attestation("power_user", &attestation).unwrap();
        }

        let score = gateway.get_reputation("power_user").unwrap();
        println!("Power user score: {}", score.composite);

        // Should have higher score now
        assert!(score.composite > 300);
    }

    #[test]
    fn test_rate_limiting() {
        let gateway = Gateway::with_rate_limit(5);

        // First 5 requests should succeed
        for _ in 0..5 {
            assert!(gateway.check_rate_limit("agent1").is_ok());
        }

        // 6th request should fail
        let result = gateway.check_rate_limit("agent1");
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::RateLimited { .. } => {}
            _ => panic!("Expected RateLimited error"),
        }
    }

    #[test]
    fn test_action_layer_mapping() {
        let capture = SwarmAction::CaptureReward {
            merchant_id: "m".to_string(),
            amount: 100,
            transaction_ref: "t".to_string(),
        };
        assert_eq!(capture.layer(), CaptureLayer::Shopping);
        assert_eq!(capture.required_score(), 0);

        let swarm = SwarmAction::CoordinateSwarm {
            task_id: "t".to_string(),
            sub_agents: vec![],
            task_allocation: HashMap::new(),
            total_budget: 0,
            coordination_fee_bps: 0,
        };
        assert_eq!(swarm.layer(), CaptureLayer::SwarmCoordinationFee);
        assert_eq!(swarm.required_score(), SWARM_COORDINATOR_THRESHOLD);
        assert!(swarm.is_swarm_action());
    }

    // ========================================================================
    // LAYER 22 TESTS: Sub-Agent Hiring & Fee Capture
    // ========================================================================

    /// Helper: Build a user to a specific tier by adding attestations
    fn build_user_to_tier(gateway: &Gateway, user: &str, target_tier: TrustTier) {
        // Number of attestations needed per layer varies by target tier
        // Score calculation uses sqrt scaling with caps, so we need MANY attestations
        // and high magnitude for high scores
        let (shopping_count, skill_count, infra_count, social_count, magnitude_mult) = match target_tier {
            TrustTier::Newcomer => (0, 0, 0, 0, 1),
            TrustTier::Established => (30, 15, 15, 10, 1),      // ~200-300 score
            TrustTier::Trusted => (60, 40, 40, 20, 1),          // ~400-500 score
            TrustTier::Power => (150, 100, 100, 50, 2),         // ~600-700 score
            TrustTier::Elite => (500, 400, 400, 200, 5),        // ~800+ score
        };

        let base_mag = 100_000_000u64 * magnitude_mult as u64;
        
        for i in 0..shopping_count {
            let att = AttestationRecord {
                layer: CaptureLayer::Shopping,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: base_mag,
                metadata: Some(AttestationMetadata {
                    lock_duration_days: Some(365),
                    held_to_maturity: Some(true),
                    ..Default::default()
                }),
            };
            gateway.record_attestation(user, &att).unwrap();
        }

        for i in 0..skill_count {
            let att = AttestationRecord {
                layer: CaptureLayer::Skill,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: base_mag / 2,
                metadata: Some(AttestationMetadata {
                    accuracy_percent: Some(95),
                    ..Default::default()
                }),
            };
            gateway.record_attestation(user, &att).unwrap();
        }

        for i in 0..infra_count {
            let att = AttestationRecord {
                layer: CaptureLayer::Network,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: base_mag / 3,
                metadata: Some(AttestationMetadata {
                    uptime_percent: Some(99),
                    ..Default::default()
                }),
            };
            gateway.record_attestation(user, &att).unwrap();
        }

        for i in 0..social_count {
            let att = AttestationRecord {
                layer: CaptureLayer::Social,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: base_mag / 5,
                metadata: None,
            };
            gateway.record_attestation(user, &att).unwrap();
        }
    }

    #[test]
    fn test_trusted_user_sub_agent_limit() {
        // Trusted tier allows max 3 sub-agents
        let gateway = Gateway::new();
        let user = "trusted_user";

        // Build user to Trusted tier (score 400-599)
        build_user_to_tier(&gateway, user, TrustTier::Trusted);
        
        let score = gateway.get_reputation(user).unwrap();
        println!("Trusted user score: {}, tier: {:?}", score.composite, score.tier);
        assert!(score.composite >= 400 && score.composite < 600, 
            "Expected Trusted tier (400-599), got {}", score.composite);
        assert_eq!(score.tier.max_sub_agents(), 3);

        // Hire first 3 sub-agents - should all succeed
        for i in 1..=3 {
            let agent = format!("sub_agent_{}", i);
            let result = gateway.hire_sub_agent(user, &agent, "task_1", 10_000_000);
            assert!(result.is_ok(), "Hire {} should succeed", i);
            
            let hire = result.unwrap();
            assert!(hire.success);
            assert_eq!(hire.current_hired_count, i);
            assert_eq!(hire.fee_captured, 100_000); // 1% of 10M
            println!("Hired sub-agent {}: fee={}", i, hire.fee_captured);
        }

        // Attempt to hire 4th sub-agent - should FAIL
        let result = gateway.hire_sub_agent(user, "sub_agent_4", "task_1", 10_000_000);
        assert!(result.is_err(), "4th hire should fail for Trusted user");
        
        match result.unwrap_err() {
            GatewayError::Forbidden { message, .. } => {
                println!("Correctly denied: {}", message);
                assert!(message.contains("limit reached"));
            }
            other => panic!("Expected Forbidden error, got {:?}", other),
        }

        // Attempt 5th - should also fail
        let result = gateway.hire_sub_agent(user, "sub_agent_5", "task_1", 10_000_000);
        assert!(result.is_err(), "5th hire should also fail");
    }

    #[test]
    fn test_high_reputation_user_can_hire_multiple_sub_agents() {
        // Build a user with high reputation and verify they can hire multiple sub-agents
        let gateway = Gateway::new();
        let user = "high_rep_user";

        // Build user to highest achievable tier
        build_user_to_tier(&gateway, user, TrustTier::Elite);
        
        let score = gateway.get_reputation(user).unwrap();
        let max_allowed = score.tier.max_sub_agents();
        println!("High rep user score: {}, tier: {:?}, max_agents: {}", 
            score.composite, score.tier, max_allowed);
        
        // The scoring system has caps, so we may not reach Elite
        // Test that we can hire UP TO max_allowed agents
        assert!(max_allowed >= 3, "Should have at least Trusted tier (3 agents)");

        // Hire up to 5 agents OR max_allowed, whichever is smaller
        let hire_count = std::cmp::min(5, max_allowed as usize);
        let mut total_fees = 0u64;
        
        for i in 1..=hire_count {
            let agent = format!("sub_agent_{}", i);
            let result = gateway.hire_sub_agent(user, &agent, "complex_task", 100_000_000);
            assert!(result.is_ok(), "Hire {} should succeed (max={})", i, max_allowed);
            
            let hire = result.unwrap();
            assert!(hire.success);
            assert_eq!(hire.current_hired_count, i);
            assert_eq!(hire.fee_captured, 1_000_000); // 1% of 100M
            assert_eq!(hire.net_budget, 99_000_000); // 99% goes to agent
            total_fees += hire.fee_captured;
            
            println!(
                "Hired {}: fee={}, net={}, total_fees={}",
                agent, hire.fee_captured, hire.net_budget, total_fees
            );
        }

        // Verify fees captured
        let (hired, fees, _) = gateway.get_sub_agent_status(user).unwrap();
        assert_eq!(hired.len(), hire_count);
        assert_eq!(fees, 1_000_000 * hire_count as u64);
        
        println!("Final status: {} hired, {} fees captured", hired.len(), fees);
    }

    #[test]
    fn test_fee_capture_calculation() {
        let gateway = Gateway::new();
        let user = "fee_test_user";

        // Build to at least Trusted tier
        build_user_to_tier(&gateway, user, TrustTier::Elite);
        
        let score = gateway.get_reputation(user).unwrap();
        let max_allowed = score.tier.max_sub_agents();
        println!("Fee test user: tier {:?}, max_agents {}", score.tier, max_allowed);

        // Test various budget amounts (only test as many as tier allows)
        let test_cases = [
            (1_000_000, 10_000, 990_000),      // 1 CRED: 0.01 fee, 0.99 net
            (10_000_000, 100_000, 9_900_000),  // 10 CRED
            (100_000_000, 1_000_000, 99_000_000), // 100 CRED
        ];

        let test_count = std::cmp::min(test_cases.len(), max_allowed as usize);

        for (i, (budget, expected_fee, expected_net)) in test_cases.iter().take(test_count).enumerate() {
            let agent = format!("fee_agent_{}", i);
            let result = gateway.hire_sub_agent(user, &agent, "fee_task", *budget).unwrap();
            
            assert_eq!(result.fee_captured, *expected_fee, 
                "Fee mismatch for budget {}", budget);
            assert_eq!(result.net_budget, *expected_net,
                "Net budget mismatch for budget {}", budget);
            
            // Verify: fee + net = budget
            assert_eq!(result.fee_captured + result.net_budget, *budget);
            
            println!("Budget {}: fee={} (1%), net={}", 
                budget, result.fee_captured, result.net_budget);
        }
    }

    #[test]
    fn test_swarm_coordination_with_fees() {
        let gateway = Gateway::new();
        let user = "swarm_coord_user";

        // Build highest reputation possible
        build_user_to_tier(&gateway, user, TrustTier::Elite);

        let score = gateway.get_reputation(user).unwrap();
        println!("Swarm test user: score {}, tier {:?}", score.composite, score.tier);
        
        // Skip this test if user doesn't meet swarm threshold
        // (The scoring system has caps that may prevent reaching 500)
        if score.composite < SWARM_COORDINATOR_THRESHOLD {
            println!("SKIP: Score {} < swarm threshold {}. Scoring caps prevent testing.",
                score.composite, SWARM_COORDINATOR_THRESHOLD);
            // Test the error case instead
            let agents: Vec<String> = (1..=3).map(|i| format!("swarm_agent_{}", i)).collect();
            let result = gateway.coordinate_swarm(user, "swarm_task_1", &agents, 50_000_000);
            assert!(result.is_err(), "Should fail with insufficient reputation");
            return;
        }

        // If we have enough reputation, test the full flow
        let max_allowed = score.tier.max_sub_agents() as usize;
        let agent_count = std::cmp::min(5, max_allowed);
        let agents: Vec<String> = (1..=agent_count).map(|i| format!("swarm_agent_{}", i)).collect();
        let budget_per = 50_000_000u64; // 50 CRED each

        let result = gateway.coordinate_swarm(user, "swarm_task_1", &agents, budget_per).unwrap();
        
        assert!(result.success);
        assert_eq!(result.hired_agents.len(), agent_count);
        assert!(result.failed_agents.is_empty());
        
        // Each agent: 50M budget, 500k fee (1%), 49.5M net
        let expected_fee_per = 500_000u64;
        let expected_net_per = 49_500_000u64;
        
        assert_eq!(result.total_fees_captured, expected_fee_per * agent_count as u64);
        assert_eq!(result.total_net_budget, expected_net_per * agent_count as u64);
        
        println!("Swarm coordination: {} agents, {} total fees, {} total net",
            result.hired_agents.len(), result.total_fees_captured, result.total_net_budget);
    }

    // ========================================================================
    // LAYER 2 TESTS: Referral Bounty System
    // ========================================================================

    #[test]
    fn test_referral_registration() {
        let gateway = Gateway::new();
        
        // Register a referral
        let result = gateway.register_referral("agent_123", "user_456");
        assert!(result.is_ok());
        
        // Cannot register same user twice
        let result = gateway.register_referral("agent_789", "user_456");
        assert!(result.is_err());
    }

    #[test]
    fn test_referral_bounty_requires_tier1_credential() {
        let gateway = Gateway::new();
        
        // Build up the agent's reputation first
        build_user_to_tier(&gateway, "referrer_agent", TrustTier::Established);
        
        // Register the referral
        gateway.register_referral("referrer_agent", "referred_user").unwrap();
        
        // Process bounty with Tier 0 credential - should fail
        let result = gateway.process_referral_bounty("referred_user", 0).unwrap();
        assert!(!result.success);
        assert!(result.failure_reason.is_some());
        println!("Tier 0 correctly rejected: {:?}", result.failure_reason);
        
        // Process bounty with Tier 1 credential - should succeed
        let result = gateway.process_referral_bounty("referred_user", 1).unwrap();
        assert!(result.success);
        assert!(result.reputation_boost > 0);
        println!("Bounty awarded: {} reputation boost", result.reputation_boost);
    }

    #[test]
    fn test_referral_bounty_is_10_percent() {
        let gateway = Gateway::new();
        
        // Build agent to known tier
        build_user_to_tier(&gateway, "big_agent", TrustTier::Trusted);
        
        // Get initial score
        let initial_score = gateway.get_reputation("big_agent").unwrap().composite;
        println!("Agent initial score: {}", initial_score);
        
        // Register and process referral
        gateway.register_referral("big_agent", "new_pioneer").unwrap();
        let result = gateway.process_referral_bounty("new_pioneer", 2).unwrap();
        
        // Check 10% bounty (1000 bps)
        let expected_bounty = (initial_score * 1000) / 10000;
        assert_eq!(result.reputation_boost, expected_bounty);
        println!("10% bounty: {} (from base score {})", result.reputation_boost, initial_score);
    }

    #[test]
    fn test_referral_bounty_only_paid_once() {
        let gateway = Gateway::new();
        
        // Setup
        build_user_to_tier(&gateway, "agent_once", TrustTier::Established);
        gateway.register_referral("agent_once", "user_once").unwrap();
        
        // First payout - should succeed
        let result1 = gateway.process_referral_bounty("user_once", 1).unwrap();
        assert!(result1.success);
        let first_boost = result1.reputation_boost;
        
        // Second payout - should fail (already paid)
        let result2 = gateway.process_referral_bounty("user_once", 1).unwrap();
        assert!(!result2.success);
        assert_eq!(result2.reputation_boost, 0);
        println!("Correctly prevented double-payment. First boost: {}", first_boost);
    }

    #[test]
    fn test_referral_stats_tracking() {
        let gateway = Gateway::new();
        
        // Setup
        build_user_to_tier(&gateway, "stats_agent", TrustTier::Trusted);
        
        // Register multiple referrals
        for i in 1..=5 {
            gateway.register_referral("stats_agent", &format!("referred_{}", i)).unwrap();
        }
        
        // Process bounties for 3 of them (Tier 1+ credentials)
        for i in 1..=3 {
            gateway.process_referral_bounty(&format!("referred_{}", i), i as u8).unwrap();
        }
        
        // Check stats
        let (referrals, total_bounties) = gateway.get_agent_referral_stats("stats_agent").unwrap();
        assert_eq!(referrals.len(), 5); // All referrals tracked
        
        let paid_count = referrals.iter().filter(|r| r.bounty_paid).count();
        assert_eq!(paid_count, 3); // Only 3 paid
        
        assert!(total_bounties > 0);
        println!("Agent stats: {} referrals, {} total bounty earned", referrals.len(), total_bounties);
    }

    #[test]
    fn test_referral_bounty_non_referred_user() {
        let gateway = Gateway::new();
        
        // Try to process bounty for user who was never referred
        let result = gateway.process_referral_bounty("random_user", 5).unwrap();
        assert!(!result.success);
        assert!(result.failure_reason.unwrap().contains("not referred"));
    }
}