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
//! Reputation Engine for Loop Protocol
//!
//! Sovereign trust score system for the 22-Layer Wealth Autopilot Stack.
//! Enables:
//! - Layer 21: Reputation Collateral (lower DeFi borrow rates)
//! - Layer 22: Swarm Coordination Fee (sub-agent hiring authorization)
//!
//! Privacy-preserving: ZK-compatible trust proofs without exposing raw history.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

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

/// Maximum score for any dimension
pub const MAX_SCORE: u32 = 1000;

/// Minimum reputation to hire sub-agents (Layer 22)
pub const SWARM_COORDINATOR_THRESHOLD: u32 = 500;

/// Minimum reputation for reputation collateral (Layer 21)
pub const COLLATERAL_THRESHOLD: u32 = 300;

/// Score decay half-life in days (inactive accounts decay)
pub const DECAY_HALF_LIFE_DAYS: u64 = 90;

// ============================================================================
// CAPTURE LAYER DEFINITIONS
// ============================================================================

/// All 22 capture layers in the unified stack
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[repr(u8)]
pub enum CaptureLayer {
    // Group 1: Passive Utility (The Foundation)
    Shopping = 1,
    Referral = 2,
    Attention = 3,
    Data = 4,
    Insurance = 5,

    // Group 2: Infrastructure (Asset Mining)
    Compute = 6,
    Network = 7,
    Energy = 8,
    DePINAggregator = 9,
    InferenceArbitrage = 10,
    StorageDePIN = 11,

    // Group 3: Intelligence (Behavioral Alpha)
    Skill = 12,
    CurationSignal = 13,
    Social = 14,
    KnowledgeAPI = 15,
    PersonalModelLicensing = 16,

    // Group 4: Aggressive Autopilot (Alpha Capture)
    Liquidity = 17,
    GovernanceProxy = 18,
    InventoryArbitrage = 19,
    SubAgentManager = 20,
    ReputationCollateral = 21,
    SwarmCoordinationFee = 22,
}

impl CaptureLayer {
    /// Get the group this layer belongs to
    pub fn group(&self) -> LayerGroup {
        match *self as u8 {
            1..=5 => LayerGroup::PassiveUtility,
            6..=11 => LayerGroup::Infrastructure,
            12..=16 => LayerGroup::Intelligence,
            17..=22 => LayerGroup::AggressiveAutopilot,
            _ => LayerGroup::PassiveUtility,
        }
    }

    /// Weight for reputation calculation (higher = more impactful)
    pub fn reputation_weight(&self) -> f64 {
        match self {
            // Foundation layers have moderate weight
            CaptureLayer::Shopping => 1.0,
            CaptureLayer::Referral => 0.8,
            CaptureLayer::Attention => 0.5,
            CaptureLayer::Data => 1.2,
            CaptureLayer::Insurance => 0.7,

            // Infrastructure has higher weight (commitment)
            CaptureLayer::Compute => 1.5,
            CaptureLayer::Network => 2.0,
            CaptureLayer::Energy => 1.3,
            CaptureLayer::DePINAggregator => 1.4,
            CaptureLayer::InferenceArbitrage => 1.8,
            CaptureLayer::StorageDePIN => 1.2,

            // Intelligence layers are high-value
            CaptureLayer::Skill => 2.5,
            CaptureLayer::CurationSignal => 2.0,
            CaptureLayer::Social => 1.5,
            CaptureLayer::KnowledgeAPI => 2.2,
            CaptureLayer::PersonalModelLicensing => 3.0,

            // Aggressive layers require proven track record
            CaptureLayer::Liquidity => 1.8,
            CaptureLayer::GovernanceProxy => 1.5,
            CaptureLayer::InventoryArbitrage => 1.2,
            CaptureLayer::SubAgentManager => 2.5,
            CaptureLayer::ReputationCollateral => 2.0,
            CaptureLayer::SwarmCoordinationFee => 3.0,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LayerGroup {
    PassiveUtility,
    Infrastructure,
    Intelligence,
    AggressiveAutopilot,
}

// ============================================================================
// ATTESTATION TRAIT
// ============================================================================

/// Attestation trait for processing signals from all 22 layers
pub trait Attestation: Send + Sync {
    /// The capture layer this attestation belongs to
    fn layer(&self) -> CaptureLayer;

    /// Timestamp of the event (Unix seconds)
    fn timestamp(&self) -> u64;

    /// Whether this was a successful/positive event
    fn is_positive(&self) -> bool;

    /// Magnitude of the event (e.g., CRED amount, data records, etc.)
    fn magnitude(&self) -> u64;

    /// Optional metadata for specialized scoring
    fn metadata(&self) -> Option<&AttestationMetadata>;
}

/// Extended metadata for attestations
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AttestationMetadata {
    /// For stacking: duration in days
    pub lock_duration_days: Option<u16>,
    /// For stacking: whether held to maturity
    pub held_to_maturity: Option<bool>,
    /// For data/skill: accuracy percentage (0-100)
    pub accuracy_percent: Option<u8>,
    /// For referral: conversion rate (0-100)
    pub conversion_rate: Option<u8>,
    /// For referral bounty: whether referral resulted in qualified user
    pub referral_successful: Option<bool>,
    /// For social: network size influenced
    pub network_reach: Option<u32>,
    /// For compute/storage: uptime percentage
    pub uptime_percent: Option<u8>,
    /// For liquidity: yield achieved (basis points)
    pub yield_bps: Option<u16>,
    /// For sub-agents: task completion rate
    pub completion_rate: Option<u8>,
    /// For VPA: difficulty tier (1-5)
    pub difficulty_tier: Option<u8>,
    /// For VPA: verification multiplier (0.5-1.25)
    pub verification_multiplier: Option<f32>,
}

// ============================================================================
// VERIFIED PROFESSIONAL ATTESTATION (VPA)
// ============================================================================

/// Credential category - industry agnostic
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CredentialCategory {
    /// Government-issued license to practice a profession
    ProfessionalLicense,
    /// Industry certification demonstrating technical competency
    TechnicalCertification,
    /// Degree from an accredited institution
    AcademicDegree,
    /// Verified work experience
    ProfessionalExperience,
    /// Demonstrated skill through contribution or assessment
    SkillDemonstration,
    /// Contributions to the Loop network
    ApiContribution,
}

impl CredentialCategory {
    /// Base weight for scoring (before multipliers)
    pub fn base_weight(&self) -> u32 {
        match self {
            CredentialCategory::ProfessionalLicense => 100,
            CredentialCategory::TechnicalCertification => 75,
            CredentialCategory::AcademicDegree => 80,
            CredentialCategory::ProfessionalExperience => 10, // per unit
            CredentialCategory::SkillDemonstration => 50,
            CredentialCategory::ApiContribution => 5, // per unit
        }
    }

    /// Whether this category uses per-unit scaling
    pub fn is_per_unit(&self) -> bool {
        matches!(
            self,
            CredentialCategory::ProfessionalExperience | CredentialCategory::ApiContribution
        )
    }
}

/// Difficulty tier for credentials (1-5)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum DifficultyTier {
    EntryLevel = 1,
    Intermediate = 2,
    Professional = 3,
    Advanced = 4,
    Expert = 5,
}

impl DifficultyTier {
    /// Weight multiplier for this tier
    pub fn multiplier(&self) -> f64 {
        match self {
            DifficultyTier::EntryLevel => 0.5,
            DifficultyTier::Intermediate => 0.75,
            DifficultyTier::Professional => 1.0,
            DifficultyTier::Advanced => 1.5,
            DifficultyTier::Expert => 2.0,
        }
    }

    pub fn from_u8(val: u8) -> Self {
        match val {
            1 => DifficultyTier::EntryLevel,
            2 => DifficultyTier::Intermediate,
            4 => DifficultyTier::Advanced,
            5 => DifficultyTier::Expert,
            _ => DifficultyTier::Professional,
        }
    }
}

/// Verification level for credentials
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum VerificationLevel {
    /// User claims credential, pending verification
    SelfAttested,
    /// Supporting document provided, awaiting review
    DocumentSubmitted,
    /// Verified by external oracle or authority
    ThirdPartyVerified,
    /// Cryptographically verified on-chain
    OnChainVerified,
}

impl VerificationLevel {
    /// Weight multiplier for verification level
    pub fn multiplier(&self) -> f64 {
        match self {
            VerificationLevel::SelfAttested => 0.5,
            VerificationLevel::DocumentSubmitted => 0.7,
            VerificationLevel::ThirdPartyVerified => 1.0,
            VerificationLevel::OnChainVerified => 1.25,
        }
    }

    /// Whether this level auto-verifies
    pub fn auto_verify(&self) -> bool {
        matches!(
            self,
            VerificationLevel::ThirdPartyVerified | VerificationLevel::OnChainVerified
        )
    }
}

/// Verified Professional Attestation (VPA)
/// 
/// Industry-agnostic credential attestation. The protocol does not
/// interpret what the credential IS - it only cares about:
/// - Category (license, cert, degree, experience)
/// - Difficulty tier (1-5)
/// - Verification level
/// 
/// All credential details are stored as opaque strings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfessionalAttestation {
    /// Credential category
    pub category: CredentialCategory,
    /// Name of credential (opaque - protocol doesn't interpret)
    pub credential_name: String,
    /// Issuing authority (opaque)
    pub issuing_authority: Option<String>,
    /// Credential ID/number (opaque)
    pub credential_id: Option<String>,
    /// Difficulty tier (affects weight)
    pub difficulty: DifficultyTier,
    /// Verification level (affects weight and trust)
    pub verification: VerificationLevel,
    /// Quantity for per-unit categories (years, count)
    pub quantity: Option<u32>,
    /// Timestamp of attestation
    pub timestamp: u64,
    /// Pre-calculated weight from API (optional override)
    pub api_weight: Option<u32>,
}

impl ProfessionalAttestation {
    /// Calculate the reputation weight for this attestation
    pub fn calculate_weight(&self) -> u32 {
        // If API pre-calculated weight, use it
        if let Some(w) = self.api_weight {
            return w.min(500);
        }

        let mut weight = self.category.base_weight() as f64;

        // Apply quantity scaling for per-unit categories
        if self.category.is_per_unit() {
            if let Some(qty) = self.quantity {
                weight *= (qty as f64).sqrt();
            }
        }

        // Apply difficulty multiplier
        weight *= self.difficulty.multiplier();

        // Apply verification multiplier
        weight *= self.verification.multiplier();

        // Cap at 500
        (weight as u32).min(500)
    }
}

impl Attestation for ProfessionalAttestation {
    fn layer(&self) -> CaptureLayer {
        // VPAs always go to Skill layer (12) or KnowledgeAPI (15) for contributions
        match self.category {
            CredentialCategory::ApiContribution => CaptureLayer::KnowledgeAPI,
            _ => CaptureLayer::Skill,
        }
    }

    fn timestamp(&self) -> u64 {
        self.timestamp
    }

    fn is_positive(&self) -> bool {
        true // VPAs are always positive attestations
    }

    fn magnitude(&self) -> u64 {
        // Use calculated weight as magnitude
        self.calculate_weight() as u64 * 10_000
    }

    fn metadata(&self) -> Option<&AttestationMetadata> {
        None // VPA metadata is in the struct itself
    }
}

// ============================================================================
// ATTESTATION IMPLEMENTATIONS
// ============================================================================

/// Generic attestation record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationRecord {
    pub layer: CaptureLayer,
    pub timestamp: u64,
    pub positive: bool,
    pub magnitude: u64,
    pub metadata: Option<AttestationMetadata>,
}

impl Attestation for AttestationRecord {
    fn layer(&self) -> CaptureLayer {
        self.layer
    }

    fn timestamp(&self) -> u64 {
        self.timestamp
    }

    fn is_positive(&self) -> bool {
        self.positive
    }

    fn magnitude(&self) -> u64 {
        self.magnitude
    }

    fn metadata(&self) -> Option<&AttestationMetadata> {
        self.metadata.as_ref()
    }
}

/// Vault activity attestation (from /api/vault/stack, etc.)
#[derive(Debug, Clone)]
pub struct VaultAttestation {
    pub action: VaultAction,
    pub timestamp: u64,
    pub amount: u64,
    pub duration_days: Option<u16>,
    pub held_to_maturity: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VaultAction {
    Initialize,
    Stack,
    Unstack,
    ClaimYield,
    EarlyWithdrawal,
}

impl Attestation for VaultAttestation {
    fn layer(&self) -> CaptureLayer {
        CaptureLayer::Shopping // Vault activity is foundational
    }

    fn timestamp(&self) -> u64 {
        self.timestamp
    }

    fn is_positive(&self) -> bool {
        match self.action {
            VaultAction::Initialize => true,
            VaultAction::Stack => true,
            VaultAction::ClaimYield => true,
            VaultAction::Unstack => self.held_to_maturity,
            VaultAction::EarlyWithdrawal => false,
        }
    }

    fn magnitude(&self) -> u64 {
        self.amount
    }

    fn metadata(&self) -> Option<&AttestationMetadata> {
        None
    }
}

// ============================================================================
// REPUTATION DIMENSIONS
// ============================================================================

/// Individual reputation dimension
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ReputationDimension {
    /// Current score (0-1000)
    pub score: u32,
    /// Total positive signals received
    pub positive_signals: u64,
    /// Total negative signals received
    pub negative_signals: u64,
    /// Last update timestamp
    pub last_updated: u64,
    /// Cumulative magnitude of all attestations
    pub cumulative_magnitude: u64,
}

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

    /// Apply time decay based on inactivity
    pub fn apply_decay(&mut self, current_time: u64) {
        if self.last_updated == 0 {
            return;
        }

        let days_inactive = (current_time - self.last_updated) / 86400;
        if days_inactive > 0 {
            // Exponential decay: score * 0.5^(days/half_life)
            let decay_factor = 0.5_f64.powf(days_inactive as f64 / DECAY_HALF_LIFE_DAYS as f64);
            self.score = ((self.score as f64) * decay_factor) as u32;
        }
    }
}

// ============================================================================
// TRUST SCORE (Composite)
// ============================================================================

/// Composite trust score with ZK-compatible proof
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustScore {
    /// Overall trust score (0-1000)
    pub composite: u32,

    /// Individual dimension scores
    pub reliability: u32,
    pub skill: u32,
    pub social: u32,
    pub tenure: u32,
    pub infrastructure: u32,

    /// Tier classification
    pub tier: TrustTier,

    /// Timestamp of calculation
    pub calculated_at: u64,

    /// ZK commitment (hash of full score breakdown + salt)
    pub zk_commitment: String,

    /// Proof that score is above threshold (without revealing exact score)
    pub threshold_proofs: HashMap<String, bool>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrustTier {
    /// Score 0-199: New user, limited access
    Newcomer,
    /// Score 200-399: Established user
    Established,
    /// Score 400-599: Trusted participant
    Trusted,
    /// Score 600-799: Power user
    Power,
    /// Score 800-1000: Elite status
    Elite,
}

impl TrustTier {
    pub fn from_score(score: u32) -> Self {
        match score {
            0..=199 => TrustTier::Newcomer,
            200..=399 => TrustTier::Established,
            400..=599 => TrustTier::Trusted,
            600..=799 => TrustTier::Power,
            _ => TrustTier::Elite,
        }
    }

    /// Collateral discount rate for DeFi (basis points reduction)
    pub fn collateral_discount_bps(&self) -> u16 {
        match self {
            TrustTier::Newcomer => 0,
            TrustTier::Established => 50,   // 0.5% rate reduction
            TrustTier::Trusted => 100,      // 1% rate reduction
            TrustTier::Power => 200,        // 2% rate reduction
            TrustTier::Elite => 350,        // 3.5% rate reduction
        }
    }

    /// Maximum sub-agents that can be coordinated
    pub fn max_sub_agents(&self) -> u8 {
        match self {
            TrustTier::Newcomer => 0,
            TrustTier::Established => 1,
            TrustTier::Trusted => 3,
            TrustTier::Power => 10,
            TrustTier::Elite => 50,
        }
    }
}

// ============================================================================
// REPUTATION ENGINE
// ============================================================================

/// Main reputation engine
#[derive(Debug)]
pub struct ReputationEngine {
    /// User public key (Solana address)
    pub user_pubkey: String,

    /// Score for each capture layer
    pub layer_scores: HashMap<CaptureLayer, ReputationDimension>,

    /// Account creation timestamp
    pub account_created: u64,

    /// Total attestations processed
    pub total_attestations: u64,

    /// Salt for ZK commitments
    zk_salt: [u8; 32],
}

impl ReputationEngine {
    /// Create new reputation engine for a user
    pub fn new(user_pubkey: String) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Generate random salt for ZK proofs
        let mut salt = [0u8; 32];
        // In production, use proper randomness
        let hash = Sha256::digest(format!("{}:{}", user_pubkey, now).as_bytes());
        salt.copy_from_slice(&hash);

        Self {
            user_pubkey,
            layer_scores: HashMap::new(),
            account_created: now,
            total_attestations: 0,
            zk_salt: salt,
        }
    }

    /// Process an attestation from any capture layer
    pub fn process_attestation<A: Attestation>(&mut self, attestation: &A) {
        let layer = attestation.layer();
        
        // Calculate score delta first (before borrowing layer_scores mutably)
        let delta = self.calculate_score_delta(attestation);
        let timestamp = attestation.timestamp();
        let magnitude = attestation.magnitude();
        let is_positive = attestation.is_positive();

        // Now borrow layer_scores mutably
        let dimension = self.layer_scores.entry(layer).or_default();

        // Update signal counts
        if is_positive {
            dimension.positive_signals += 1;
        } else {
            dimension.negative_signals += 1;
        }

        // Update magnitude
        dimension.cumulative_magnitude += magnitude;

        // Apply delta with bounds
        if delta > 0 {
            dimension.score = (dimension.score + delta as u32).min(MAX_SCORE);
        } else {
            dimension.score = dimension.score.saturating_sub((-delta) as u32);
        }

        dimension.last_updated = timestamp;
        self.total_attestations += 1;
    }

    /// Calculate score change for an attestation
    fn calculate_score_delta<A: Attestation>(&self, attestation: &A) -> i32 {
        let layer = attestation.layer();
        let weight = layer.reputation_weight();
        let base_delta: i32;

        if attestation.is_positive() {
            // Base positive delta: 15-60 depending on layer (increased)
            base_delta = match layer.group() {
                LayerGroup::PassiveUtility => 15,
                LayerGroup::Infrastructure => 30,
                LayerGroup::Intelligence => 45,
                LayerGroup::AggressiveAutopilot => 60,
            };

            // Magnitude bonus (logarithmic scaling, increased)
            let magnitude = attestation.magnitude();
            let magnitude_bonus = if magnitude > 0 {
                ((magnitude as f64).ln() * 3.0) as i32
            } else {
                0
            };

            // Special bonuses from metadata
            let metadata_bonus = self.calculate_metadata_bonus(attestation);

            ((base_delta + magnitude_bonus + metadata_bonus) as f64 * weight) as i32
        } else {
            // Negative events have MUCH higher impact (punish bad behavior)
            base_delta = match layer.group() {
                LayerGroup::PassiveUtility => -50,
                LayerGroup::Infrastructure => -80,
                LayerGroup::Intelligence => -100,
                LayerGroup::AggressiveAutopilot => -150,
            };

            (base_delta as f64 * weight) as i32
        }
    }

    /// Calculate bonus from attestation metadata
    fn calculate_metadata_bonus<A: Attestation>(&self, attestation: &A) -> i32 {
        let mut bonus = 0i32;

        if let Some(meta) = attestation.metadata() {
            // Stacking duration bonus
            if let Some(days) = meta.lock_duration_days {
                bonus += match days {
                    0..=29 => 0,
                    30..=89 => 5,
                    90..=179 => 15,
                    180..=364 => 30,
                    _ => 50,
                };
            }

            // Held to maturity bonus
            if meta.held_to_maturity == Some(true) {
                bonus += 25;
            }

            // Accuracy bonus
            if let Some(accuracy) = meta.accuracy_percent {
                bonus += (accuracy as i32 - 50) / 5; // -10 to +10
            }

            // Uptime bonus (for infrastructure)
            if let Some(uptime) = meta.uptime_percent {
                if uptime >= 99 {
                    bonus += 20;
                } else if uptime >= 95 {
                    bonus += 10;
                }
            }

            // Completion rate bonus (for sub-agents)
            if let Some(rate) = meta.completion_rate {
                bonus += (rate as i32 - 70) / 3; // -10 to +10
            }
        }

        bonus
    }

    /// Calculate composite trust score
    pub fn calculate_trust_score(&mut self) -> TrustScore {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Apply decay to all dimensions
        for dimension in self.layer_scores.values_mut() {
            dimension.apply_decay(now);
        }

        // Calculate dimension scores
        let reliability = self.calculate_reliability_score();
        let skill = self.calculate_skill_score();
        let social = self.calculate_social_score();
        let tenure = self.calculate_tenure_score(now);
        let infrastructure = self.calculate_infrastructure_score();

        // Weighted composite (must sum to 1.0)
        let composite = (
            (reliability as f64 * 0.30) +
            (skill as f64 * 0.25) +
            (infrastructure as f64 * 0.20) +
            (social as f64 * 0.15) +
            (tenure as f64 * 0.10)
        ) as u32;

        let composite = composite.min(MAX_SCORE);
        let tier = TrustTier::from_score(composite);

        // Generate ZK commitment
        let zk_commitment = self.generate_zk_commitment(composite, reliability, skill);

        // Generate threshold proofs
        let mut threshold_proofs = HashMap::new();
        threshold_proofs.insert(
            "swarm_coordinator".to_string(),
            composite >= SWARM_COORDINATOR_THRESHOLD,
        );
        threshold_proofs.insert(
            "collateral_eligible".to_string(),
            composite >= COLLATERAL_THRESHOLD,
        );
        threshold_proofs.insert("trusted".to_string(), composite >= 400);
        threshold_proofs.insert("power".to_string(), composite >= 600);
        threshold_proofs.insert("elite".to_string(), composite >= 800);

        TrustScore {
            composite,
            reliability,
            skill,
            social,
            tenure,
            infrastructure,
            tier,
            calculated_at: now,
            zk_commitment,
            threshold_proofs,
        }
    }

    /// Calculate reliability score (based on vault activity)
    fn calculate_reliability_score(&self) -> u32 {
        let mut score = 0u32;

        // Shopping layer (vault activity)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Shopping) {
            // Base score from positive signals (increased weight)
            score += (dim.positive_signals * 20).min(500) as u32;

            // Penalty for negative signals
            let penalty = (dim.negative_signals * 50).min(400) as u32;
            score = score.saturating_sub(penalty);

            // Cumulative magnitude bonus (CRED stacked)
            let cred_stacked = dim.cumulative_magnitude / 1_000_000; // Convert from lamports
            score += ((cred_stacked as f64).sqrt() * 8.0) as u32;
            
            // Dimension score bonus
            score += dim.score / 5;
        }

        // Insurance layer contributes to reliability
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Insurance) {
            score += (dim.positive_signals * 8).min(150) as u32;
        }

        // Liquidity layer (consistent yield = reliable)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Liquidity) {
            score += (dim.positive_signals * 12).min(200) as u32;
        }

        score.min(MAX_SCORE)
    }

    /// Calculate skill score (based on data capture accuracy)
    fn calculate_skill_score(&self) -> u32 {
        let mut score = 0u32;

        // Skill layer (professional behavioral models)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Skill) {
            score += (dim.positive_signals * 20).min(400) as u32;
        }

        // Data layer (accuracy of captures)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Data) {
            let accuracy_ratio = if dim.positive_signals + dim.negative_signals > 0 {
                dim.positive_signals as f64
                    / (dim.positive_signals + dim.negative_signals) as f64
            } else {
                0.5
            };
            score += (accuracy_ratio * 200.0) as u32;
        }

        // Curation signal quality
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::CurationSignal) {
            score += (dim.positive_signals * 15).min(200) as u32;
        }

        // Knowledge API contributions
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::KnowledgeAPI) {
            score += (dim.positive_signals * 12).min(150) as u32;
        }

        // Personal model licensing (highest skill indicator)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::PersonalModelLicensing) {
            if dim.positive_signals > 0 {
                score += 100; // Bonus for having a licensable model
            }
        }

        score.min(MAX_SCORE)
    }

    /// Calculate social score (network effects)
    fn calculate_social_score(&self) -> u32 {
        let mut score = 0u32;

        // Social layer direct
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Social) {
            score += (dim.positive_signals * 15).min(400) as u32;
        }

        // Referral conversions
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::Referral) {
            score += (dim.positive_signals * 10).min(200) as u32;
        }

        // Sub-agent management (leadership)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::SubAgentManager) {
            score += (dim.positive_signals * 20).min(250) as u32;
        }

        // Swarm coordination (network orchestration)
        if let Some(dim) = self.layer_scores.get(&CaptureLayer::SwarmCoordinationFee) {
            score += (dim.positive_signals * 25).min(200) as u32;
        }

        score.min(MAX_SCORE)
    }

    /// Calculate tenure score (time-based trust)
    fn calculate_tenure_score(&self, now: u64) -> u32 {
        let account_age_days = (now - self.account_created) / 86400;

        // Score grows logarithmically with time
        // Max out around 2 years
        let tenure_score = ((account_age_days as f64).ln() * 50.0) as u32;

        // Bonus for consistent activity
        let activity_bonus = (self.total_attestations as f64 / 10.0).min(200.0) as u32;

        (tenure_score + activity_bonus).min(MAX_SCORE)
    }

    /// Calculate infrastructure score (DePIN participation)
    fn calculate_infrastructure_score(&self) -> u32 {
        let mut score = 0u32;

        let infra_layers = [
            CaptureLayer::Compute,
            CaptureLayer::Network,
            CaptureLayer::Energy,
            CaptureLayer::DePINAggregator,
            CaptureLayer::InferenceArbitrage,
            CaptureLayer::StorageDePIN,
        ];

        for layer in infra_layers {
            if let Some(dim) = self.layer_scores.get(&layer) {
                // Higher weight for infrastructure commitment
                score += (dim.positive_signals * 25).min(200) as u32;

                // Penalty for failures (unreliable infrastructure)
                let penalty = (dim.negative_signals * 50).min(100) as u32;
                score = score.saturating_sub(penalty);
            }
        }

        score.min(MAX_SCORE)
    }

    /// Generate ZK commitment (hash of scores + salt)
    fn generate_zk_commitment(&self, composite: u32, reliability: u32, skill: u32) -> String {
        let data = format!(
            "{}:{}:{}:{}",
            composite,
            reliability,
            skill,
            hex::encode(&self.zk_salt)
        );
        let hash = Sha256::digest(data.as_bytes());
        hex::encode(hash)
    }

    /// Verify a threshold proof (external parties can check without seeing score)
    pub fn verify_threshold(
        &mut self,
        threshold_name: &str,
        commitment: &str,
    ) -> Option<bool> {
        let trust_score = self.calculate_trust_score();

        // Verify commitment matches
        if trust_score.zk_commitment != commitment {
            return None;
        }

        trust_score.threshold_proofs.get(threshold_name).copied()
    }

    /// Check if user can coordinate sub-agents (Layer 22 gate)
    pub fn can_coordinate_swarm(&mut self) -> bool {
        let score = self.calculate_trust_score();
        score.composite >= SWARM_COORDINATOR_THRESHOLD
    }

    /// Check if user qualifies for reputation collateral (Layer 21)
    pub fn qualifies_for_collateral(&mut self) -> bool {
        let score = self.calculate_trust_score();
        score.composite >= COLLATERAL_THRESHOLD
    }

    /// Get collateral discount rate in basis points
    pub fn collateral_discount_bps(&mut self) -> u16 {
        let score = self.calculate_trust_score();
        score.tier.collateral_discount_bps()
    }

    /// Get maximum sub-agents this user can hire
    pub fn max_sub_agents(&mut self) -> u8 {
        let score = self.calculate_trust_score();
        score.tier.max_sub_agents()
    }
}

// ============================================================================
// SERIALIZATION FOR API
// ============================================================================

/// API response for reputation query
#[derive(Debug, Serialize, Deserialize)]
pub struct ReputationResponse {
    pub user: String,
    pub trust_score: TrustScore,
    pub capabilities: ReputationCapabilities,
    pub layer_activity: HashMap<String, LayerActivity>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ReputationCapabilities {
    pub can_coordinate_swarm: bool,
    pub qualifies_for_collateral: bool,
    pub collateral_discount_bps: u16,
    pub max_sub_agents: u8,
    pub available_layers: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LayerActivity {
    pub score: u32,
    pub positive_signals: u64,
    pub negative_signals: u64,
    pub last_active: u64,
}

impl ReputationEngine {
    /// Generate API response
    pub fn to_api_response(&mut self) -> ReputationResponse {
        let trust_score = self.calculate_trust_score();

        let capabilities = ReputationCapabilities {
            can_coordinate_swarm: self.can_coordinate_swarm(),
            qualifies_for_collateral: self.qualifies_for_collateral(),
            collateral_discount_bps: self.collateral_discount_bps(),
            max_sub_agents: self.max_sub_agents(),
            available_layers: self.get_available_layers(),
        };

        let mut layer_activity = HashMap::new();
        for (layer, dim) in &self.layer_scores {
            layer_activity.insert(
                format!("{:?}", layer),
                LayerActivity {
                    score: dim.score,
                    positive_signals: dim.positive_signals,
                    negative_signals: dim.negative_signals,
                    last_active: dim.last_updated,
                },
            );
        }

        ReputationResponse {
            user: self.user_pubkey.clone(),
            trust_score,
            capabilities,
            layer_activity,
        }
    }

    /// Get layers this user has unlocked based on reputation
    fn get_available_layers(&mut self) -> Vec<String> {
        let score = self.calculate_trust_score();
        let mut layers = vec![
            // Everyone gets foundation layers
            "Shopping",
            "Referral",
            "Attention",
            "Data",
        ];

        if score.composite >= 200 {
            layers.extend(["Insurance", "Compute", "Storage"]);
        }

        if score.composite >= 400 {
            layers.extend([
                "Network",
                "Energy",
                "DePINAggregator",
                "Skill",
                "CurationSignal",
            ]);
        }

        if score.composite >= 600 {
            layers.extend([
                "InferenceArbitrage",
                "Social",
                "KnowledgeAPI",
                "Liquidity",
                "GovernanceProxy",
            ]);
        }

        if score.composite >= 800 {
            layers.extend([
                "PersonalModelLicensing",
                "InventoryArbitrage",
                "SubAgentManager",
                "ReputationCollateral",
                "SwarmCoordinationFee",
            ]);
        }

        layers.into_iter().map(String::from).collect()
    }
}

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

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

    #[test]
    fn test_new_user_starts_at_zero() {
        let engine = ReputationEngine::new("test_user".to_string());
        assert_eq!(engine.total_attestations, 0);
        assert!(engine.layer_scores.is_empty());
    }

    #[test]
    fn test_vault_attestation_increases_reliability() {
        let mut engine = ReputationEngine::new("test_user".to_string());

        let attestation = VaultAttestation {
            action: VaultAction::Stack,
            timestamp: 1711497600,
            amount: 100_000_000, // 100 CRED
            duration_days: Some(90),
            held_to_maturity: true,
        };

        engine.process_attestation(&attestation);

        let score = engine.calculate_trust_score();
        assert!(score.reliability > 0);
        assert!(score.composite > 0);
    }

    #[test]
    fn test_early_withdrawal_decreases_score() {
        let mut engine = ReputationEngine::new("test_user".to_string());

        // First, build up score with multiple stacks
        for i in 0..10 {
            let stack = VaultAttestation {
                action: VaultAction::Stack,
                timestamp: 1711497600 + i * 86400,
                amount: 100_000_000,
                duration_days: Some(90),
                held_to_maturity: true,
            };
            engine.process_attestation(&stack);
        }

        let score_before = engine.calculate_trust_score().composite;
        println!("Score before early withdrawal: {}", score_before);
        assert!(score_before > 0);

        // Then early withdraw
        let early = VaultAttestation {
            action: VaultAction::EarlyWithdrawal,
            timestamp: 1711584000,
            amount: 100_000_000,
            duration_days: None,
            held_to_maturity: false,
        };
        engine.process_attestation(&early);

        let score_after = engine.calculate_trust_score().composite;
        println!("Score after early withdrawal: {}", score_after);
        
        // Score should decrease (or at least dimension score should)
        let dim = engine.layer_scores.get(&CaptureLayer::Shopping).unwrap();
        assert!(dim.negative_signals > 0, "Should have recorded negative signal");
    }

    #[test]
    fn test_swarm_threshold() {
        let mut engine = ReputationEngine::new("test_user".to_string());

        // New user can't coordinate swarm
        assert!(!engine.can_coordinate_swarm());

        // Add many positive attestations across multiple layers
        // Shopping layer
        for i in 0..30 {
            let attestation = AttestationRecord {
                layer: CaptureLayer::Shopping,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: 100_000_000, // 100 CRED
                metadata: Some(AttestationMetadata {
                    lock_duration_days: Some(365),
                    held_to_maturity: Some(true),
                    ..Default::default()
                }),
            };
            engine.process_attestation(&attestation);
        }
        
        // Skill layer (higher weight)
        for i in 0..20 {
            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()
                }),
            };
            engine.process_attestation(&attestation);
        }
        
        // Infrastructure layer
        for i in 0..20 {
            let attestation = AttestationRecord {
                layer: CaptureLayer::Network,
                timestamp: 1711497600 + i * 86400,
                positive: true,
                magnitude: 5_000_000,
                metadata: Some(AttestationMetadata {
                    uptime_percent: Some(99),
                    ..Default::default()
                }),
            };
            engine.process_attestation(&attestation);
        }

        // Should now qualify (or be close)
        let score = engine.calculate_trust_score();
        println!("Score after multi-layer attestations: {}", score.composite);
        println!("  Reliability: {}", score.reliability);
        println!("  Skill: {}", score.skill);
        println!("  Infrastructure: {}", score.infrastructure);
        
        // Score should be substantial
        assert!(score.composite >= 400, "Expected score >= 400, got {}", score.composite);
    }

    #[test]
    fn test_tier_classification() {
        assert_eq!(TrustTier::from_score(0), TrustTier::Newcomer);
        assert_eq!(TrustTier::from_score(199), TrustTier::Newcomer);
        assert_eq!(TrustTier::from_score(200), TrustTier::Established);
        assert_eq!(TrustTier::from_score(400), TrustTier::Trusted);
        assert_eq!(TrustTier::from_score(600), TrustTier::Power);
        assert_eq!(TrustTier::from_score(800), TrustTier::Elite);
        assert_eq!(TrustTier::from_score(1000), TrustTier::Elite);
    }

    #[test]
    fn test_zk_commitment_deterministic() {
        let mut engine = ReputationEngine::new("test_user".to_string());
        
        let score1 = engine.calculate_trust_score();
        let score2 = engine.calculate_trust_score();

        // Same engine, same commitment
        assert_eq!(score1.zk_commitment, score2.zk_commitment);
    }
}