ruvllm 2.2.1

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
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
//! Advanced Pretraining Pipeline for RuvLTRA Claude Flow Integration
//!
//! This module provides a multi-phase pretraining pipeline optimized for Claude Flow tasks:
//!
//! - **Bootstrap Phase**: Seed patterns from agent keywords and typical tasks
//! - **Synthetic Phase**: Generate diverse training samples per agent type
//! - **Reinforce Phase**: Replay successful trajectories with SONA
//! - **Consolidate Phase**: EWC++ to lock in learned patterns
//!
//! ## Key Features
//!
//! - Quality-gated learning (only learn from successful patterns)
//! - Curriculum learning (start simple, increase complexity)
//! - Progress tracking and checkpoint saving
//! - Multi-agent task generation
//!
//! ## Example
//!
//! ```rust,ignore
//! use ruvllm::claude_flow::pretrain_pipeline::{PretrainPipeline, PretrainConfig, Phase};
//!
//! let config = PretrainConfig::default();
//! let mut pipeline = PretrainPipeline::new(config);
//!
//! // Run full pipeline
//! let result = pipeline.run_full_pipeline()?;
//! println!("Trained {} patterns with {:.2}% quality", result.total_patterns, result.avg_quality * 100.0);
//!
//! // Save checkpoint
//! pipeline.save_checkpoint("./checkpoints/claude_flow_v1.bin")?;
//! ```

use super::task_generator::{GeneratedTask, TaskCategory, TaskComplexity, TaskGenerator};
use super::{ClaudeFlowAgent, ClaudeFlowTask};
use crate::sona::{
    PretrainSample, RoutingPretrainResult, RuvLtraPretrainConfig, RuvLtraPretrainer, SeedingResult,
    SonaConfig, SonaIntegration, Trajectory,
};
use parking_lot::RwLock;
use ruvector_sona::{
    EwcConfig, EwcPlusPlus, LearnedPattern, PatternConfig, ReasoningBank, SonaEngine,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Pretraining phase
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Phase {
    /// Seed patterns from agent keywords and typical tasks
    Bootstrap,
    /// Generate diverse training samples per agent type
    Synthetic,
    /// Replay successful trajectories with SONA
    Reinforce,
    /// EWC++ to lock in learned patterns
    Consolidate,
}

/// Static array of all phases for zero-allocation access
static ALL_PHASES: [Phase; 4] = [
    Phase::Bootstrap,
    Phase::Synthetic,
    Phase::Reinforce,
    Phase::Consolidate,
];

impl Phase {
    /// Get all phases in order
    #[inline]
    pub fn all() -> &'static [Phase] {
        &ALL_PHASES
    }

    /// Get phase name
    #[inline]
    pub fn name(&self) -> &'static str {
        match self {
            Phase::Bootstrap => "bootstrap",
            Phase::Synthetic => "synthetic",
            Phase::Reinforce => "reinforce",
            Phase::Consolidate => "consolidate",
        }
    }

    /// Get phase description
    #[inline]
    pub fn description(&self) -> &'static str {
        match self {
            Phase::Bootstrap => "Seed patterns from agent keywords and typical tasks",
            Phase::Synthetic => "Generate diverse training samples per agent type",
            Phase::Reinforce => "Replay successful trajectories with SONA learning",
            Phase::Consolidate => "Lock in learned patterns with EWC++ consolidation",
        }
    }
}

/// Configuration for the pretraining pipeline
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PretrainConfig {
    /// Phases to execute
    pub phases: Vec<Phase>,
    /// Samples per phase
    pub samples_per_phase: usize,
    /// Quality threshold for learning (0.0 - 1.0)
    pub quality_threshold: f32,
    /// Enable curriculum learning
    pub curriculum_learning: bool,
    /// Curriculum stages (complexity levels)
    pub curriculum_stages: usize,
    /// Samples per curriculum stage
    pub samples_per_stage: usize,
    /// Embedding dimension
    pub embedding_dim: usize,
    /// SONA configuration
    pub sona_config: SonaConfig,
    /// Enable checkpointing
    pub enable_checkpoints: bool,
    /// Checkpoint interval (samples)
    pub checkpoint_interval: usize,
    /// Checkpoint directory
    pub checkpoint_dir: String,
    /// Verbose logging
    pub verbose: bool,
    /// Random seed for reproducibility
    pub random_seed: u64,
    /// Number of reinforcement replays per trajectory
    pub reinforce_replays: usize,
    /// EWC++ consolidation lambda
    pub ewc_lambda: f32,
    /// Minimum samples per agent type
    pub min_samples_per_agent: usize,
}

impl Default for PretrainConfig {
    fn default() -> Self {
        Self {
            phases: Phase::all().to_vec(),
            samples_per_phase: 1000,
            quality_threshold: 0.6,
            curriculum_learning: true,
            curriculum_stages: 4,
            samples_per_stage: 250,
            embedding_dim: 384,
            sona_config: SonaConfig {
                hidden_dim: 128,
                embedding_dim: 384,
                micro_lora_rank: 1,
                base_lora_rank: 4,
                instant_learning_rate: 0.005,
                background_learning_rate: 0.0005,
                ewc_lambda: 500.0,
                pattern_capacity: 5000,
                background_interval_secs: 1800,
                deep_interval_secs: 259200,
                quality_threshold: 0.6,
            },
            enable_checkpoints: true,
            checkpoint_interval: 500,
            checkpoint_dir: "./checkpoints".to_string(),
            verbose: false,
            random_seed: 42,
            reinforce_replays: 3,
            ewc_lambda: 500.0,
            min_samples_per_agent: 50,
        }
    }
}

impl PretrainConfig {
    /// Configuration optimized for Claude Flow
    pub fn for_claude_flow() -> Self {
        Self {
            samples_per_phase: 2000,
            quality_threshold: 0.65,
            curriculum_stages: 5,
            samples_per_stage: 400,
            reinforce_replays: 5,
            ..Default::default()
        }
    }

    /// Configuration for quick testing
    pub fn for_testing() -> Self {
        Self {
            samples_per_phase: 100,
            quality_threshold: 0.5,
            curriculum_stages: 2,
            samples_per_stage: 50,
            enable_checkpoints: false,
            verbose: false,
            reinforce_replays: 1,
            min_samples_per_agent: 10,
            ..Default::default()
        }
    }

    /// Configuration for edge deployment (minimal footprint)
    pub fn for_edge() -> Self {
        Self {
            phases: vec![Phase::Bootstrap, Phase::Synthetic],
            samples_per_phase: 500,
            quality_threshold: 0.7,
            curriculum_learning: false,
            embedding_dim: 256,
            sona_config: SonaConfig {
                hidden_dim: 64,
                embedding_dim: 256,
                micro_lora_rank: 1,
                base_lora_rank: 2,
                pattern_capacity: 1000,
                ..SonaConfig::default()
            },
            enable_checkpoints: false,
            reinforce_replays: 1,
            min_samples_per_agent: 20,
            ..Default::default()
        }
    }
}

/// Curriculum scheduler for progressive learning
#[derive(Debug, Clone)]
pub struct CurriculumScheduler {
    /// Total stages
    total_stages: usize,
    /// Current stage (0-indexed)
    current_stage: usize,
    /// Samples completed in current stage
    samples_in_stage: usize,
    /// Samples per stage
    samples_per_stage: usize,
    /// Quality history per stage
    quality_history: Vec<Vec<f32>>,
    /// Current complexity level
    current_complexity: TaskComplexity,
}

impl CurriculumScheduler {
    /// Create a new curriculum scheduler
    pub fn new(total_stages: usize, samples_per_stage: usize) -> Self {
        // Pre-allocate quality history with estimated capacity
        let quality_history: Vec<Vec<f32>> = (0..total_stages)
            .map(|_| Vec::with_capacity(samples_per_stage))
            .collect();

        Self {
            total_stages,
            current_stage: 0,
            samples_in_stage: 0,
            samples_per_stage,
            quality_history,
            current_complexity: TaskComplexity::Simple,
        }
    }

    /// Get current complexity level
    #[inline]
    pub fn current_complexity(&self) -> TaskComplexity {
        self.current_complexity
    }

    /// Get current stage
    #[inline]
    pub fn current_stage(&self) -> usize {
        self.current_stage
    }

    /// Check if curriculum is complete
    #[inline]
    pub fn is_complete(&self) -> bool {
        self.current_stage >= self.total_stages
    }

    /// Record sample quality and advance if needed
    pub fn record_sample(&mut self, quality: f32) -> bool {
        if self.is_complete() {
            return false;
        }

        self.quality_history[self.current_stage].push(quality);
        self.samples_in_stage += 1;

        // Check if we should advance to next stage
        if self.samples_in_stage >= self.samples_per_stage {
            self.advance_stage()
        } else {
            false
        }
    }

    /// Advance to next stage
    fn advance_stage(&mut self) -> bool {
        if self.current_stage + 1 < self.total_stages {
            self.current_stage += 1;
            self.samples_in_stage = 0;

            // Update complexity based on stage
            self.current_complexity = match self.current_stage {
                0 => TaskComplexity::Simple,
                1 => TaskComplexity::Moderate,
                2 => TaskComplexity::Complex,
                _ => TaskComplexity::Expert,
            };

            true
        } else {
            self.current_stage = self.total_stages;
            false
        }
    }

    /// Get average quality for a stage
    #[inline]
    pub fn stage_avg_quality(&self, stage: usize) -> f32 {
        if stage >= self.quality_history.len() || self.quality_history[stage].is_empty() {
            return 0.0;
        }
        let history = &self.quality_history[stage];
        let sum: f32 = history.iter().sum();
        sum / history.len() as f32
    }

    /// Get overall average quality
    #[inline]
    pub fn overall_avg_quality(&self) -> f32 {
        let mut total: f32 = 0.0;
        let mut count: usize = 0;
        for v in &self.quality_history {
            for &q in v {
                total += q;
                count += 1;
            }
        }
        if count == 0 {
            0.0
        } else {
            total / count as f32
        }
    }

    /// Reset the scheduler
    pub fn reset(&mut self) {
        self.current_stage = 0;
        self.samples_in_stage = 0;
        self.quality_history = vec![Vec::new(); self.total_stages];
        self.current_complexity = TaskComplexity::Simple;
    }
}

/// Quality gate for filtering training samples
#[derive(Debug, Clone)]
pub struct QualityGate {
    /// Minimum quality threshold
    threshold: f32,
    /// Total samples seen
    total_seen: u64,
    /// Samples accepted
    accepted: u64,
    /// Samples rejected
    rejected: u64,
    /// Quality distribution (buckets of 0.1)
    quality_buckets: [u64; 10],
}

impl QualityGate {
    /// Create a new quality gate
    #[inline]
    pub fn new(threshold: f32) -> Self {
        Self {
            threshold: threshold.clamp(0.0, 1.0),
            total_seen: 0,
            accepted: 0,
            rejected: 0,
            quality_buckets: [0; 10],
        }
    }

    /// Check if a sample passes the quality gate
    #[inline]
    pub fn check(&mut self, quality: f32) -> bool {
        self.total_seen += 1;

        // Record in bucket using fast integer conversion
        let bucket = ((quality * 10.0) as usize).min(9);
        self.quality_buckets[bucket] += 1;

        if quality >= self.threshold {
            self.accepted += 1;
            true
        } else {
            self.rejected += 1;
            false
        }
    }

    /// Get acceptance rate
    #[inline]
    pub fn acceptance_rate(&self) -> f32 {
        if self.total_seen == 0 {
            0.0
        } else {
            self.accepted as f32 / self.total_seen as f32
        }
    }

    /// Get quality statistics
    pub fn stats(&self) -> QualityGateStats {
        QualityGateStats {
            threshold: self.threshold,
            total_seen: self.total_seen,
            accepted: self.accepted,
            rejected: self.rejected,
            acceptance_rate: self.acceptance_rate(),
            quality_distribution: self.quality_buckets,
        }
    }

    /// Reset the gate
    pub fn reset(&mut self) {
        self.total_seen = 0;
        self.accepted = 0;
        self.rejected = 0;
        self.quality_buckets = [0; 10];
    }

    /// Adjust threshold based on acceptance rate
    pub fn auto_adjust(&mut self, target_acceptance_rate: f32) {
        let current_rate = self.acceptance_rate();
        if current_rate < target_acceptance_rate {
            // Lower threshold to accept more
            self.threshold = (self.threshold - 0.05).max(0.1);
        } else if current_rate > target_acceptance_rate + 0.2 {
            // Raise threshold to be more selective
            self.threshold = (self.threshold + 0.05).min(0.95);
        }
    }
}

/// Quality gate statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityGateStats {
    pub threshold: f32,
    pub total_seen: u64,
    pub accepted: u64,
    pub rejected: u64,
    pub acceptance_rate: f32,
    pub quality_distribution: [u64; 10],
}

/// Progress tracker for pretraining
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressTracker {
    /// Current phase
    pub current_phase: Phase,
    /// Phase progress (0.0 - 1.0)
    pub phase_progress: f32,
    /// Overall progress (0.0 - 1.0)
    pub overall_progress: f32,
    /// Samples processed per phase
    pub samples_per_phase: HashMap<String, u64>,
    /// Patterns learned per phase
    pub patterns_per_phase: HashMap<String, usize>,
    /// Quality history per phase
    pub quality_per_phase: HashMap<String, f32>,
    /// Start time
    pub start_time: Option<u64>,
    /// Elapsed time (seconds)
    pub elapsed_secs: f64,
    /// Estimated remaining time (seconds)
    pub estimated_remaining_secs: f64,
    /// Checkpoints saved
    pub checkpoints_saved: usize,
}

impl Default for ProgressTracker {
    fn default() -> Self {
        Self {
            current_phase: Phase::Bootstrap,
            phase_progress: 0.0,
            overall_progress: 0.0,
            samples_per_phase: HashMap::new(),
            patterns_per_phase: HashMap::new(),
            quality_per_phase: HashMap::new(),
            start_time: None,
            elapsed_secs: 0.0,
            estimated_remaining_secs: 0.0,
            checkpoints_saved: 0,
        }
    }
}

impl ProgressTracker {
    /// Start tracking
    pub fn start(&mut self) {
        self.start_time = Some(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        );
    }

    /// Update progress
    pub fn update(&mut self, phase: Phase, samples: u64, total_samples: u64, quality: f32) {
        self.current_phase = phase;
        self.phase_progress = samples as f32 / total_samples.max(1) as f32;

        let phase_name = phase.name().to_string();
        self.samples_per_phase.insert(phase_name.clone(), samples);
        self.quality_per_phase.insert(phase_name, quality);

        // Update elapsed time
        if let Some(start) = self.start_time {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs();
            self.elapsed_secs = (now - start) as f64;

            // Estimate remaining time
            if self.overall_progress > 0.0 {
                let total_estimated = self.elapsed_secs / self.overall_progress as f64;
                self.estimated_remaining_secs = total_estimated - self.elapsed_secs;
            }
        }
    }

    /// Update overall progress
    pub fn set_overall_progress(&mut self, progress: f32) {
        self.overall_progress = progress.clamp(0.0, 1.0);
    }

    /// Record checkpoint
    pub fn record_checkpoint(&mut self) {
        self.checkpoints_saved += 1;
    }

    /// Record patterns for phase
    pub fn record_patterns(&mut self, phase: Phase, count: usize) {
        self.patterns_per_phase
            .insert(phase.name().to_string(), count);
    }
}

/// Result of a single phase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhaseResult {
    /// Phase that was run
    pub phase: Phase,
    /// Samples processed
    pub samples_processed: u64,
    /// Patterns learned
    pub patterns_learned: usize,
    /// Average quality
    pub avg_quality: f32,
    /// Duration (seconds)
    pub duration_secs: f64,
    /// Quality gate stats
    pub quality_gate_stats: QualityGateStats,
}

/// Result of full pipeline
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineResult {
    /// Total patterns learned
    pub total_patterns: usize,
    /// Total samples processed
    pub total_samples: u64,
    /// Average quality across all phases
    pub avg_quality: f32,
    /// Total duration (seconds)
    pub total_duration_secs: f64,
    /// Results per phase
    pub phase_results: Vec<PhaseResult>,
    /// Final curriculum stats (if curriculum learning enabled)
    pub curriculum_stats: Option<CurriculumStats>,
    /// Checkpoints saved
    pub checkpoints_saved: usize,
}

/// Curriculum learning statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurriculumStats {
    /// Stages completed
    pub stages_completed: usize,
    /// Average quality per stage
    pub quality_per_stage: Vec<f32>,
    /// Samples per stage
    pub samples_per_stage: Vec<usize>,
}

/// Checkpoint data for saving/loading
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Checkpoint {
    /// Configuration
    pub config: PretrainConfig,
    /// Progress tracker
    pub progress: ProgressTracker,
    /// Learned patterns (serialized)
    pub patterns: Vec<SerializedPattern>,
    /// Curriculum state
    pub curriculum_stage: usize,
    /// Quality gate threshold
    pub quality_threshold: f32,
    /// Random seed state
    pub random_state: u64,
}

/// Serializable pattern representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedPattern {
    pub id: u64,
    pub centroid: Vec<f32>,
    pub avg_quality: f32,
    pub cluster_size: usize,
    pub pattern_type: String,
}

/// The main pretraining pipeline
pub struct PretrainPipeline {
    /// Configuration
    config: PretrainConfig,
    /// Task generator
    task_generator: TaskGenerator,
    /// SONA pretrainer
    pretrainer: RuvLtraPretrainer,
    /// Curriculum scheduler
    curriculum: CurriculumScheduler,
    /// Quality gate
    quality_gate: QualityGate,
    /// Progress tracker
    progress: ProgressTracker,
    /// Successful trajectories for replay
    successful_trajectories: Vec<TrajectoryRecord>,
    /// Samples processed
    samples_processed: u64,
    /// Patterns per agent
    patterns_per_agent: HashMap<ClaudeFlowAgent, usize>,
}

/// Record of a successful trajectory for replay
#[derive(Debug, Clone)]
struct TrajectoryRecord {
    task: GeneratedTask,
    embedding: Vec<f32>,
    quality: f32,
    agent: ClaudeFlowAgent,
}

impl PretrainPipeline {
    /// Create a new pretraining pipeline
    pub fn new(config: PretrainConfig) -> Self {
        let pretrain_config = RuvLtraPretrainConfig {
            sona: config.sona_config.clone(),
            dataset: crate::sona::DatasetConfig {
                max_routing_prompts: config.samples_per_phase,
                max_quality_prompts: config.samples_per_phase / 2,
                embedding_batch_size: 32,
                min_prompt_length: 10,
                max_prompt_length: 2048,
                quality_threshold: config.quality_threshold,
            },
            routing: crate::sona::RoutingPretrainConfig {
                num_clusters: 50,
                learning_rate: 0.001,
                epochs: 5,
                min_samples_per_class: config.min_samples_per_agent,
                model_mappings: vec![],
            },
            quality: crate::sona::QualityPretrainConfig {
                num_buckets: 5,
                learning_rate: 0.001,
                epochs: 3,
                use_regression: false,
            },
            seeding: crate::sona::SeedingConfig {
                patterns_per_category: 20,
                categories: vec![],
                initial_quality: 0.7,
                embedding_dim: config.embedding_dim,
            },
        };

        let pretrainer = RuvLtraPretrainer::new(pretrain_config);
        let curriculum =
            CurriculumScheduler::new(config.curriculum_stages, config.samples_per_stage);
        let quality_gate = QualityGate::new(config.quality_threshold);

        Self {
            config,
            task_generator: TaskGenerator::new(),
            pretrainer,
            curriculum,
            quality_gate,
            progress: ProgressTracker::default(),
            successful_trajectories: Vec::new(),
            samples_processed: 0,
            patterns_per_agent: HashMap::new(),
        }
    }

    /// Run the full pretraining pipeline
    pub fn run_full_pipeline(&mut self) -> Result<PipelineResult, String> {
        self.progress.start();
        let start_time = Instant::now();
        let mut phase_results = Vec::new();

        let total_phases = self.config.phases.len();

        for (phase_idx, phase) in self.config.phases.clone().iter().enumerate() {
            let phase_result = self.run_phase(*phase)?;
            phase_results.push(phase_result);

            // Update overall progress
            self.progress
                .set_overall_progress((phase_idx + 1) as f32 / total_phases as f32);

            // Save checkpoint if enabled
            if self.config.enable_checkpoints {
                let checkpoint_path = format!(
                    "{}/checkpoint_phase_{}.bin",
                    self.config.checkpoint_dir,
                    phase.name()
                );
                if let Err(e) = self.save_checkpoint(&checkpoint_path) {
                    if self.config.verbose {
                        eprintln!("Warning: Failed to save checkpoint: {}", e);
                    }
                }
            }
        }

        // Calculate final statistics
        let total_patterns: usize = phase_results.iter().map(|r| r.patterns_learned).sum();
        let total_samples: u64 = phase_results.iter().map(|r| r.samples_processed).sum();
        let avg_quality: f32 = if phase_results.is_empty() {
            0.0
        } else {
            phase_results.iter().map(|r| r.avg_quality).sum::<f32>() / phase_results.len() as f32
        };

        let curriculum_stats = if self.config.curriculum_learning {
            Some(CurriculumStats {
                stages_completed: self.curriculum.current_stage(),
                quality_per_stage: (0..self.config.curriculum_stages)
                    .map(|s| self.curriculum.stage_avg_quality(s))
                    .collect(),
                samples_per_stage: vec![
                    self.config.samples_per_stage;
                    self.config.curriculum_stages
                ],
            })
        } else {
            None
        };

        Ok(PipelineResult {
            total_patterns,
            total_samples,
            avg_quality,
            total_duration_secs: start_time.elapsed().as_secs_f64(),
            phase_results,
            curriculum_stats,
            checkpoints_saved: self.progress.checkpoints_saved,
        })
    }

    /// Run a single phase
    pub fn run_phase(&mut self, phase: Phase) -> Result<PhaseResult, String> {
        let start_time = Instant::now();
        self.quality_gate.reset();

        let result = match phase {
            Phase::Bootstrap => self.run_bootstrap_phase(),
            Phase::Synthetic => self.run_synthetic_phase(),
            Phase::Reinforce => self.run_reinforce_phase(),
            Phase::Consolidate => self.run_consolidate_phase(),
        };

        let (samples, patterns, quality) = result?;

        Ok(PhaseResult {
            phase,
            samples_processed: samples,
            patterns_learned: patterns,
            avg_quality: quality,
            duration_secs: start_time.elapsed().as_secs_f64(),
            quality_gate_stats: self.quality_gate.stats(),
        })
    }

    /// Bootstrap phase: seed patterns from agent keywords
    fn run_bootstrap_phase(&mut self) -> Result<(u64, usize, f32), String> {
        if self.config.verbose {
            println!("Running Bootstrap Phase...");
        }

        // Seed the reasoning bank with initial patterns
        let seeding_result = self.pretrainer.seed_reasoning_bank();

        // Generate bootstrap samples from agent keywords
        let mut total_quality = 0.0f32;
        let mut samples_count = 0u64;

        for agent in ClaudeFlowAgent::all() {
            for keyword in agent.keywords() {
                // Create bootstrap task
                let task = GeneratedTask {
                    description: format!("{} task for {}", keyword, agent.name()),
                    category: TaskCategory::from_agent(*agent),
                    complexity: TaskComplexity::Simple,
                    expected_agent: *agent,
                    keywords: vec![keyword.to_string()],
                    context: None,
                };

                // Generate embedding
                let embedding = self.generate_embedding(&task.description);

                // Simulate quality (bootstrap tasks are high quality by definition)
                let quality = 0.8 + (rand_simple() * 0.15);

                if self.quality_gate.check(quality) {
                    // Create pretrain sample
                    let sample = PretrainSample {
                        prompt: task.description.clone(),
                        embedding: Some(embedding.clone()),
                        target_model_index: Some(self.agent_to_model_index(*agent)),
                        quality_score: Some(quality),
                        category: Some(agent.name().to_string()),
                    };

                    // Train
                    self.pretrainer.pretrain_routing_patterns(&[sample]);

                    // Record successful trajectory
                    self.successful_trajectories.push(TrajectoryRecord {
                        task,
                        embedding,
                        quality,
                        agent: *agent,
                    });

                    total_quality += quality;
                    samples_count += 1;
                }

                self.samples_processed += 1;
                self.progress.update(
                    Phase::Bootstrap,
                    samples_count,
                    self.config.samples_per_phase as u64,
                    total_quality / samples_count.max(1) as f32,
                );
            }
        }

        let patterns_learned = seeding_result.patterns_seeded + self.successful_trajectories.len();
        let avg_quality = if samples_count > 0 {
            total_quality / samples_count as f32
        } else {
            0.0
        };

        self.progress
            .record_patterns(Phase::Bootstrap, patterns_learned);

        Ok((samples_count, patterns_learned, avg_quality))
    }

    /// Synthetic phase: generate diverse training samples
    fn run_synthetic_phase(&mut self) -> Result<(u64, usize, f32), String> {
        if self.config.verbose {
            println!("Running Synthetic Phase...");
        }

        // Pre-allocate with expected capacity
        let estimated_samples = self.config.samples_per_phase;
        let mut samples = Vec::with_capacity(estimated_samples);
        let mut total_quality = 0.0f32;
        let mut samples_count = 0u64;

        // Cache agent list length
        let all_agents = ClaudeFlowAgent::all();
        let agent_count = all_agents.len();

        // Generate samples for each agent type
        for agent in all_agents {
            let agent_samples = self.config.samples_per_phase / agent_count;

            for _ in 0..agent_samples {
                // Get complexity based on curriculum
                let complexity = if self.config.curriculum_learning {
                    self.curriculum.current_complexity()
                } else {
                    TaskComplexity::random()
                };

                // Generate task
                let task = self.task_generator.generate_for_agent(*agent, complexity);
                let embedding = self.generate_embedding(&task.description);

                // Simulate quality based on complexity match
                let base_quality = self.simulate_quality(&task, *agent);
                let quality = base_quality + (rand_simple() * 0.1 - 0.05);

                if self.quality_gate.check(quality) {
                    samples.push(PretrainSample {
                        prompt: task.description.clone(),
                        embedding: Some(embedding.clone()),
                        target_model_index: Some(self.agent_to_model_index(*agent)),
                        quality_score: Some(quality),
                        category: Some(task.category.name().to_string()),
                    });

                    // Record successful trajectory
                    self.successful_trajectories.push(TrajectoryRecord {
                        task,
                        embedding,
                        quality,
                        agent: *agent,
                    });

                    total_quality += quality;
                    samples_count += 1;

                    // Update curriculum
                    if self.config.curriculum_learning {
                        self.curriculum.record_sample(quality);
                    }
                }

                self.samples_processed += 1;

                // Checkpoint if needed
                if self.config.enable_checkpoints
                    && self.samples_processed % self.config.checkpoint_interval as u64 == 0
                {
                    let _ = self.save_checkpoint(&format!(
                        "{}/checkpoint_synthetic_{}.bin",
                        self.config.checkpoint_dir, self.samples_processed
                    ));
                }

                self.progress.update(
                    Phase::Synthetic,
                    samples_count,
                    self.config.samples_per_phase as u64,
                    total_quality / samples_count.max(1) as f32,
                );
            }
        }

        // Train on all samples
        let result = self.pretrainer.pretrain_routing_patterns(&samples);

        let avg_quality = if samples_count > 0 {
            total_quality / samples_count as f32
        } else {
            0.0
        };

        self.progress
            .record_patterns(Phase::Synthetic, result.patterns_learned);

        Ok((samples_count, result.patterns_learned, avg_quality))
    }

    /// Reinforce phase: replay successful trajectories
    fn run_reinforce_phase(&mut self) -> Result<(u64, usize, f32), String> {
        if self.config.verbose {
            println!("Running Reinforce Phase...");
        }

        let mut total_quality = 0.0f32;
        let mut samples_count = 0u64;
        let mut patterns_learned = 0;

        // Pre-sort trajectories once (highest quality first for importance sampling)
        let mut sorted_trajectories = self.successful_trajectories.clone();
        sorted_trajectories.sort_by(|a, b| b.quality.partial_cmp(&a.quality).unwrap());

        // Replay successful trajectories multiple times
        for replay_idx in 0..self.config.reinforce_replays {
            // Use pre-sorted list instead of re-sorting each iteration
            let trajectories = &sorted_trajectories;

            for record in trajectories {
                // Slight perturbation to prevent overfitting
                // Pre-allocate and use in-place mutation
                let mut perturbed_embedding: Vec<f32> = Vec::with_capacity(record.embedding.len());
                for &x in &record.embedding {
                    perturbed_embedding.push(x + (rand_simple() * 0.02 - 0.01));
                }

                // Boost quality for replay (successful patterns are reinforced)
                let boosted_quality = (record.quality * 1.1).min(1.0);

                if self.quality_gate.check(boosted_quality) {
                    let sample = PretrainSample {
                        prompt: record.task.description.clone(),
                        embedding: Some(perturbed_embedding),
                        target_model_index: Some(self.agent_to_model_index(record.agent)),
                        quality_score: Some(boosted_quality),
                        category: Some(record.task.category.name().to_string()),
                    };

                    let result = self.pretrainer.pretrain_routing_patterns(&[sample]);
                    patterns_learned += result.patterns_learned;

                    total_quality += boosted_quality;
                    samples_count += 1;
                }

                self.samples_processed += 1;
                self.progress.update(
                    Phase::Reinforce,
                    samples_count,
                    (self.successful_trajectories.len() * self.config.reinforce_replays) as u64,
                    total_quality / samples_count.max(1) as f32,
                );
            }

            if self.config.verbose {
                println!(
                    "  Replay {} complete, quality: {:.3}",
                    replay_idx + 1,
                    total_quality / samples_count.max(1) as f32
                );
            }
        }

        let avg_quality = if samples_count > 0 {
            total_quality / samples_count as f32
        } else {
            0.0
        };

        self.progress
            .record_patterns(Phase::Reinforce, patterns_learned);

        Ok((samples_count, patterns_learned, avg_quality))
    }

    /// Consolidate phase: EWC++ to lock in patterns
    fn run_consolidate_phase(&mut self) -> Result<(u64, usize, f32), String> {
        if self.config.verbose {
            println!("Running Consolidate Phase...");
        }

        // Get all learned patterns
        let reasoning_bank = self.pretrainer.reasoning_bank();
        let patterns = reasoning_bank.get_all_patterns();

        // Compute Fisher information for important patterns
        let ewc = self.pretrainer.ewc();
        let ewc_task_count = ewc.task_count();

        // Consolidate patterns using EWC++
        // This prevents catastrophic forgetting by regularizing updates
        let mut total_quality = 0.0f32;
        let mut consolidated_count = 0;

        for pattern in &patterns {
            if pattern.avg_quality >= self.config.quality_threshold {
                // Pattern is important, contribute to Fisher diagonal
                let pseudo_gradients = self.compute_pattern_gradients(pattern);

                // The EWC++ will use these to compute importance weights
                // (Actual EWC++ update happens internally in the pretrainer)

                total_quality += pattern.avg_quality;
                consolidated_count += 1;
            }
        }

        // Record consolidation metrics
        let avg_quality = if consolidated_count > 0 {
            total_quality / consolidated_count as f32
        } else {
            0.0
        };

        self.progress.update(
            Phase::Consolidate,
            consolidated_count as u64,
            patterns.len() as u64,
            avg_quality,
        );
        self.progress
            .record_patterns(Phase::Consolidate, consolidated_count);

        Ok((consolidated_count as u64, consolidated_count, avg_quality))
    }

    /// Generate embedding for text
    /// Optimized with single-pass normalization
    #[inline]
    fn generate_embedding(&self, text: &str) -> Vec<f32> {
        let dim = self.config.embedding_dim;
        let mut embedding = vec![0.0f32; dim];

        // Character-based hashing for deterministic pseudo-embeddings
        // Use bytes for faster iteration when ASCII is expected
        for (i, ch) in text.chars().enumerate() {
            let idx = i % dim;
            let val = (ch as u32 as f32) * (1.0 / 65536.0); // Pre-computed inverse
            embedding[idx] += val;
        }

        // L2 normalize in single pass
        let mut norm_sq: f32 = 0.0;
        for &e in &embedding {
            norm_sq += e * e;
        }

        let norm = norm_sq.sqrt();
        if norm > 1e-8 {
            let inv_norm = 1.0 / norm;
            for e in &mut embedding {
                *e *= inv_norm;
            }
        }

        embedding
    }

    /// Map agent to model index
    #[inline]
    fn agent_to_model_index(&self, agent: ClaudeFlowAgent) -> usize {
        match agent {
            ClaudeFlowAgent::Coder | ClaudeFlowAgent::BackendDev => 1,
            ClaudeFlowAgent::Researcher => 1,
            ClaudeFlowAgent::Tester => 1,
            ClaudeFlowAgent::Reviewer => 2,
            ClaudeFlowAgent::Architect => 2,
            ClaudeFlowAgent::SecurityAuditor => 2,
            ClaudeFlowAgent::PerformanceEngineer => 2,
            ClaudeFlowAgent::MlDeveloper => 2,
            ClaudeFlowAgent::CicdEngineer => 1,
        }
    }

    /// Simulate quality based on task/agent match
    #[inline]
    fn simulate_quality(&self, task: &GeneratedTask, agent: ClaudeFlowAgent) -> f32 {
        let base_quality: f32 = if task.expected_agent == agent {
            0.85
        } else {
            0.5
        };

        // Adjust for complexity
        let complexity_modifier: f32 = match task.complexity {
            TaskComplexity::Simple => 0.1,
            TaskComplexity::Moderate => 0.0,
            TaskComplexity::Complex => -0.05,
            TaskComplexity::Expert => -0.1,
        };

        (base_quality + complexity_modifier).clamp(0.0_f32, 1.0_f32)
    }

    /// Compute pseudo-gradients for a pattern
    fn compute_pattern_gradients(&self, pattern: &LearnedPattern) -> Vec<f32> {
        let dim = self.config.sona_config.hidden_dim;
        let mut gradients = vec![0.0f32; dim];

        let centroid_len = pattern.centroid.len().min(dim);
        for i in 0..centroid_len {
            gradients[i] = pattern.centroid[i] * pattern.avg_quality;
        }

        gradients
    }

    /// Save checkpoint to disk
    pub fn save_checkpoint(&mut self, path: &str) -> Result<(), String> {
        // Create checkpoint directory if needed
        if let Some(parent) = Path::new(path).parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("Failed to create checkpoint directory: {}", e))?;
        }

        // Serialize patterns
        let reasoning_bank = self.pretrainer.reasoning_bank();
        let patterns: Vec<SerializedPattern> = reasoning_bank
            .get_all_patterns()
            .iter()
            .map(|p| SerializedPattern {
                id: p.id,
                centroid: p.centroid.clone(),
                avg_quality: p.avg_quality,
                cluster_size: p.cluster_size,
                pattern_type: format!("{:?}", p.pattern_type),
            })
            .collect();

        let checkpoint = Checkpoint {
            config: self.config.clone(),
            progress: self.progress.clone(),
            patterns,
            curriculum_stage: self.curriculum.current_stage(),
            quality_threshold: self.quality_gate.threshold,
            random_state: self.samples_processed, // Use as pseudo-random state
        };

        let serialized = serde_json::to_string_pretty(&checkpoint)
            .map_err(|e| format!("Failed to serialize checkpoint: {}", e))?;

        std::fs::write(path, serialized)
            .map_err(|e| format!("Failed to write checkpoint: {}", e))?;

        self.progress.record_checkpoint();

        if self.config.verbose {
            println!("Checkpoint saved: {}", path);
        }

        Ok(())
    }

    /// Load checkpoint from disk
    pub fn load_checkpoint(path: &str) -> Result<Self, String> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("Failed to read checkpoint: {}", e))?;

        let checkpoint: Checkpoint = serde_json::from_str(&content)
            .map_err(|e| format!("Failed to parse checkpoint: {}", e))?;

        let mut pipeline = Self::new(checkpoint.config);
        pipeline.progress = checkpoint.progress;
        pipeline.quality_gate.threshold = checkpoint.quality_threshold;

        // Note: Patterns would need to be reloaded into the reasoning bank
        // This is a simplified version

        Ok(pipeline)
    }

    /// Get current progress
    pub fn progress(&self) -> &ProgressTracker {
        &self.progress
    }

    /// Get quality gate statistics
    pub fn quality_gate_stats(&self) -> QualityGateStats {
        self.quality_gate.stats()
    }

    /// Get curriculum statistics
    pub fn curriculum_stats(&self) -> CurriculumStats {
        CurriculumStats {
            stages_completed: self.curriculum.current_stage(),
            quality_per_stage: (0..self.config.curriculum_stages)
                .map(|s| self.curriculum.stage_avg_quality(s))
                .collect(),
            samples_per_stage: vec![self.config.samples_per_stage; self.config.curriculum_stages],
        }
    }

    /// Get configuration
    pub fn config(&self) -> &PretrainConfig {
        &self.config
    }

    /// Get the trained pretrainer
    pub fn into_pretrainer(self) -> RuvLtraPretrainer {
        self.pretrainer
    }
}

/// Simple pseudo-random number generator (for determinism without external deps)
fn rand_simple() -> f32 {
    use std::cell::RefCell;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    thread_local! {
        static STATE: RefCell<u64> = RefCell::new(42);
    }

    STATE.with(|state| {
        let mut s = state.borrow_mut();
        // LCG parameters
        *s = s.wrapping_mul(6364136223846793005).wrapping_add(1);
        (*s >> 33) as f32 / u32::MAX as f32
    })
}

/// Type alias for error handling
type Result<T, E> = std::result::Result<T, E>;

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

    #[test]
    fn test_config_defaults() {
        let config = PretrainConfig::default();
        assert_eq!(config.phases.len(), 4);
        assert_eq!(config.quality_threshold, 0.6);
        assert!(config.curriculum_learning);
    }

    #[test]
    fn test_config_for_testing() {
        let config = PretrainConfig::for_testing();
        assert_eq!(config.samples_per_phase, 100);
        assert!(!config.enable_checkpoints);
    }

    #[test]
    fn test_curriculum_scheduler() {
        let mut scheduler = CurriculumScheduler::new(4, 10);

        assert_eq!(scheduler.current_stage(), 0);
        assert_eq!(scheduler.current_complexity(), TaskComplexity::Simple);
        assert!(!scheduler.is_complete());

        // Complete first stage
        for _ in 0..10 {
            scheduler.record_sample(0.8);
        }

        assert_eq!(scheduler.current_stage(), 1);
        assert_eq!(scheduler.current_complexity(), TaskComplexity::Moderate);
    }

    #[test]
    fn test_quality_gate() {
        let mut gate = QualityGate::new(0.6);

        assert!(gate.check(0.7));
        assert!(!gate.check(0.5));
        assert_eq!(gate.acceptance_rate(), 0.5);
    }

    #[test]
    fn test_progress_tracker() {
        let mut tracker = ProgressTracker::default();
        tracker.start();

        tracker.update(Phase::Bootstrap, 50, 100, 0.75);
        assert_eq!(tracker.phase_progress, 0.5);
    }

    #[test]
    fn test_pipeline_creation() {
        let config = PretrainConfig::for_testing();
        let pipeline = PretrainPipeline::new(config);

        assert_eq!(pipeline.samples_processed, 0);
    }

    #[test]
    fn test_embedding_generation() {
        let config = PretrainConfig::for_testing();
        let pipeline = PretrainPipeline::new(config);

        let embedding = pipeline.generate_embedding("test task");
        assert_eq!(embedding.len(), pipeline.config.embedding_dim);

        // Check normalization
        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_phase_names() {
        assert_eq!(Phase::Bootstrap.name(), "bootstrap");
        assert_eq!(Phase::Synthetic.name(), "synthetic");
        assert_eq!(Phase::Reinforce.name(), "reinforce");
        assert_eq!(Phase::Consolidate.name(), "consolidate");
    }

    #[test]
    fn test_quality_gate_auto_adjust() {
        let mut gate = QualityGate::new(0.9);

        // Simulate low acceptance rate
        for _ in 0..10 {
            gate.check(0.5);
        }

        let old_threshold = gate.threshold;
        gate.auto_adjust(0.5);
        assert!(gate.threshold < old_threshold);
    }
}