ruvllm 2.2.0

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
//! # Claude Task Fine-Tuning Dataset Generator
//!
//! Generates synthetic training datasets for RuvLTRA models fine-tuned on
//! Claude Flow agent tasks. Includes data augmentation, quality scoring,
//! and export to standard formats (JSONL, Parquet).
//!
//! ## Task Categories
//!
//! The dataset covers 5 primary task categories aligned with Claude Flow agents:
//! - **Coder**: Code generation, debugging, refactoring
//! - **Researcher**: Analysis, exploration, documentation
//! - **Security**: Audit, vulnerability analysis, threat detection
//! - **Architecture**: Design, planning, system architecture
//! - **Reviewer**: Code review, quality assessment, best practices
//!
//! ## Example
//!
//! ```rust,ignore
//! use ruvllm::training::{DatasetGenerator, DatasetConfig};
//!
//! let config = DatasetConfig::default();
//! let generator = DatasetGenerator::new(config);
//! let dataset = generator.generate()?;
//!
//! // Export to JSONL
//! dataset.export_jsonl("training_data.jsonl")?;
//!
//! // Export to Parquet
//! dataset.export_parquet("training_data.parquet")?;
//! ```

use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

/// Task categories matching Claude Flow agents
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TaskCategory {
    /// Code generation, debugging, refactoring
    Coder,
    /// Analysis, exploration, documentation
    Researcher,
    /// Audit, vulnerability analysis, threat detection
    Security,
    /// Design, planning, system architecture
    Architecture,
    /// Code review, quality assessment
    Reviewer,
}

impl TaskCategory {
    /// Get all task categories
    pub fn all() -> Vec<Self> {
        vec![
            Self::Coder,
            Self::Researcher,
            Self::Security,
            Self::Architecture,
            Self::Reviewer,
        ]
    }

    /// Get category name
    pub fn name(&self) -> &'static str {
        match self {
            Self::Coder => "coder",
            Self::Researcher => "researcher",
            Self::Security => "security",
            Self::Architecture => "architecture",
            Self::Reviewer => "reviewer",
        }
    }

    /// Get recommended model for this category
    pub fn recommended_model(&self, complexity: ComplexityLevel) -> &'static str {
        match (self, complexity) {
            (Self::Coder, ComplexityLevel::Simple) => "haiku",
            (Self::Coder, ComplexityLevel::Moderate) => "sonnet",
            (Self::Coder, ComplexityLevel::Complex) => "opus",
            (Self::Researcher, ComplexityLevel::Simple) => "haiku",
            (Self::Researcher, _) => "sonnet",
            (Self::Security, _) => "opus",
            (Self::Architecture, ComplexityLevel::Simple) => "sonnet",
            (Self::Architecture, _) => "opus",
            (Self::Reviewer, ComplexityLevel::Simple) => "haiku",
            (Self::Reviewer, _) => "sonnet",
        }
    }
}

/// Complexity level for task classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ComplexityLevel {
    /// Simple, straightforward tasks
    Simple,
    /// Moderate complexity requiring analysis
    Moderate,
    /// Complex tasks requiring deep reasoning
    Complex,
}

/// Domain type for task context
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DomainType {
    /// Web development (frontend/backend)
    Web,
    /// Systems programming (low-level, OS, drivers)
    Systems,
    /// Data science and ML
    DataScience,
    /// Mobile development
    Mobile,
    /// DevOps and infrastructure
    DevOps,
    /// Security and cryptography
    Security,
    /// Database and storage
    Database,
    /// API design and integration
    Api,
}

/// Metadata for task examples
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskMetadata {
    /// Task category
    pub category: TaskCategory,
    /// Complexity level
    pub complexity: ComplexityLevel,
    /// Domain type
    pub domain: DomainType,
    /// Expected model (haiku/sonnet/opus)
    pub expected_model: String,
    /// Quality score (0.0-1.0)
    pub quality_score: f32,
    /// Tags for filtering
    pub tags: Vec<String>,
}

/// A single training example for Claude task routing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeTaskExample {
    /// Input task description
    pub input: String,
    /// Context information
    pub context: String,
    /// Expected agent routing decision
    pub output_agent: String,
    /// Metadata
    pub metadata: TaskMetadata,
}

/// Dataset configuration
#[derive(Debug, Clone)]
pub struct DatasetConfig {
    /// Number of seed examples per category
    pub examples_per_category: usize,
    /// Enable data augmentation
    pub enable_augmentation: bool,
    /// Augmentation configuration
    pub augmentation: AugmentationConfig,
    /// Random seed for reproducibility
    pub seed: u64,
}

impl Default for DatasetConfig {
    fn default() -> Self {
        Self {
            examples_per_category: 100,
            enable_augmentation: true,
            augmentation: AugmentationConfig::default(),
            seed: 42,
        }
    }
}

/// Data augmentation configuration
#[derive(Debug, Clone)]
pub struct AugmentationConfig {
    /// Number of paraphrases per example
    pub paraphrases_per_example: usize,
    /// Number of complexity variations per example
    pub complexity_variations: usize,
    /// Enable domain transfer
    pub enable_domain_transfer: bool,
}

impl Default for AugmentationConfig {
    fn default() -> Self {
        Self {
            paraphrases_per_example: 2,
            complexity_variations: 2,
            enable_domain_transfer: true,
        }
    }
}

/// Complete dataset with statistics
#[derive(Debug)]
pub struct ClaudeTaskDataset {
    /// All training examples
    pub examples: Vec<ClaudeTaskExample>,
    /// Dataset statistics
    pub stats: DatasetStats,
}

/// Dataset statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DatasetStats {
    /// Total number of examples
    pub total_examples: usize,
    /// Examples per category
    pub examples_per_category: HashMap<String, usize>,
    /// Examples per complexity level
    pub examples_per_complexity: HashMap<String, usize>,
    /// Examples per domain
    pub examples_per_domain: HashMap<String, usize>,
    /// Average quality score
    pub avg_quality_score: f32,
}

impl ClaudeTaskDataset {
    /// Create a new dataset from examples
    pub fn new(examples: Vec<ClaudeTaskExample>) -> Self {
        let stats = Self::compute_stats(&examples);
        Self { examples, stats }
    }

    /// Compute statistics for the dataset
    fn compute_stats(examples: &[ClaudeTaskExample]) -> DatasetStats {
        let mut stats = DatasetStats {
            total_examples: examples.len(),
            examples_per_category: HashMap::new(),
            examples_per_complexity: HashMap::new(),
            examples_per_domain: HashMap::new(),
            avg_quality_score: 0.0,
        };

        let mut total_quality = 0.0;

        for example in examples {
            // Count by category
            *stats
                .examples_per_category
                .entry(example.metadata.category.name().to_string())
                .or_insert(0) += 1;

            // Count by complexity
            let complexity = format!("{:?}", example.metadata.complexity);
            *stats.examples_per_complexity.entry(complexity).or_insert(0) += 1;

            // Count by domain
            let domain = format!("{:?}", example.metadata.domain);
            *stats.examples_per_domain.entry(domain).or_insert(0) += 1;

            total_quality += example.metadata.quality_score;
        }

        if !examples.is_empty() {
            stats.avg_quality_score = total_quality / examples.len() as f32;
        }

        stats
    }

    /// Export dataset to JSONL format
    pub fn export_jsonl<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);

        for example in &self.examples {
            let json = serde_json::to_string(example)?;
            writeln!(writer, "{}", json)?;
        }

        writer.flush()?;
        Ok(())
    }

    /// Export dataset to JSON format (full array)
    pub fn export_json<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
        let file = File::create(path)?;
        serde_json::to_writer_pretty(file, &self.examples)?;
        Ok(())
    }

    /// Export statistics to JSON
    pub fn export_stats<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
        let file = File::create(path)?;
        serde_json::to_writer_pretty(file, &self.stats)?;
        Ok(())
    }

    /// Split dataset into train/validation/test sets
    pub fn split(
        &self,
        train: f32,
        val: f32,
        test: f32,
        seed: u64,
    ) -> (
        Vec<ClaudeTaskExample>,
        Vec<ClaudeTaskExample>,
        Vec<ClaudeTaskExample>,
    ) {
        assert!(
            (train + val + test - 1.0).abs() < 1e-6,
            "Split ratios must sum to 1.0"
        );

        let mut rng = StdRng::seed_from_u64(seed);
        let mut examples = self.examples.clone();
        examples.shuffle(&mut rng);

        let total = examples.len();
        let train_size = (total as f32 * train) as usize;
        let val_size = (total as f32 * val) as usize;

        let train_set = examples[..train_size].to_vec();
        let val_set = examples[train_size..train_size + val_size].to_vec();
        let test_set = examples[train_size + val_size..].to_vec();

        (train_set, val_set, test_set)
    }
}

/// Dataset generator
pub struct DatasetGenerator {
    config: DatasetConfig,
    rng: StdRng,
}

impl DatasetGenerator {
    /// Create a new dataset generator
    pub fn new(config: DatasetConfig) -> Self {
        let rng = StdRng::seed_from_u64(config.seed);
        Self { config, rng }
    }

    /// Generate the complete dataset
    pub fn generate(&mut self) -> ClaudeTaskDataset {
        let mut examples = Vec::new();

        for category in TaskCategory::all() {
            let seed_examples = self.generate_seed_examples(category);
            examples.extend(seed_examples);
        }

        if self.config.enable_augmentation {
            let augmented = self.augment_examples(&examples);
            examples.extend(augmented);
        }

        ClaudeTaskDataset::new(examples)
    }

    /// Generate seed examples for a category
    fn generate_seed_examples(&mut self, category: TaskCategory) -> Vec<ClaudeTaskExample> {
        let templates = self.get_templates_for_category(category);
        let mut examples = Vec::new();

        for _ in 0..self.config.examples_per_category {
            let template = templates.choose(&mut self.rng).unwrap();
            let example = self.instantiate_template(template, category);
            examples.push(example);
        }

        examples
    }

    /// Get templates for a specific category
    fn get_templates_for_category(&self, category: TaskCategory) -> Vec<TaskTemplate> {
        match category {
            TaskCategory::Coder => self.coder_templates(),
            TaskCategory::Researcher => self.researcher_templates(),
            TaskCategory::Security => self.security_templates(),
            TaskCategory::Architecture => self.architecture_templates(),
            TaskCategory::Reviewer => self.reviewer_templates(),
        }
    }

    /// Generate coder task templates
    fn coder_templates(&self) -> Vec<TaskTemplate> {
        vec![
            // Code generation templates
            TaskTemplate {
                input: "Implement a {function_type} function in {language} that {functionality}",
                context: "The function should {requirements}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Web,
                tags: vec!["code-generation", "function"],
                quality: 0.9,
            },
            TaskTemplate {
                input: "Create a {component_type} component using {framework} for {purpose}",
                context: "Requirements: {requirements}. Should follow {pattern} pattern",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["code-generation", "component"],
                quality: 0.85,
            },
            TaskTemplate {
                input: "Write a {data_structure} implementation in {language} with {operations}",
                context: "Must support {requirements} and optimize for {optimization_target}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Systems,
                tags: vec!["data-structures", "algorithms"],
                quality: 0.88,
            },
            // Debugging templates
            TaskTemplate {
                input: "Debug the {issue_type} error in {context}",
                context: "Error: {error_message}. Stack trace: {stack_trace}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Web,
                tags: vec!["debugging", "error-handling"],
                quality: 0.87,
            },
            TaskTemplate {
                input: "Fix memory leak in {component} caused by {cause}",
                context: "Profiler shows {profiler_output}. Occurring in {scenario}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Systems,
                tags: vec!["debugging", "memory", "performance"],
                quality: 0.92,
            },
            // Refactoring templates
            TaskTemplate {
                input: "Refactor {code_section} to improve {quality_attribute}",
                context: "Current issues: {issues}. Should maintain {constraints}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["refactoring", "code-quality"],
                quality: 0.86,
            },
            TaskTemplate {
                input: "Extract {pattern} from {codebase_section}",
                context: "Duplicated code in {locations}. Create reusable {abstraction}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["refactoring", "dry"],
                quality: 0.84,
            },
            // API integration templates
            TaskTemplate {
                input: "Integrate {api_name} API for {purpose}",
                context: "API documentation: {docs}. Need to handle {edge_cases}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Api,
                tags: vec!["api", "integration"],
                quality: 0.83,
            },
            TaskTemplate {
                input: "Build REST endpoint {endpoint_path} with {http_method}",
                context: "Should accept {input_schema} and return {output_schema}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Api,
                tags: vec!["api", "rest", "backend"],
                quality: 0.88,
            },
            // Testing templates
            TaskTemplate {
                input: "Write unit tests for {function_name} covering {test_cases}",
                context: "Test framework: {framework}. Should cover {coverage_requirements}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Web,
                tags: vec!["testing", "unit-tests"],
                quality: 0.90,
            },
        ]
    }

    /// Generate researcher task templates
    fn researcher_templates(&self) -> Vec<TaskTemplate> {
        vec![
            // Analysis templates
            TaskTemplate {
                input: "Analyze {codebase_component} for {analysis_goal}",
                context: "Focus on {focus_areas}. Document {documentation_requirements}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["analysis", "documentation"],
                quality: 0.85,
            },
            TaskTemplate {
                input: "Research best practices for {topic} in {context}",
                context: "Current approach: {current_approach}. Constraints: {constraints}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["research", "best-practices"],
                quality: 0.87,
            },
            TaskTemplate {
                input: "Investigate {performance_issue} in {system_component}",
                context: "Metrics: {metrics}. Threshold: {threshold}. Need root cause analysis",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Systems,
                tags: vec!["research", "performance", "analysis"],
                quality: 0.89,
            },
            // Documentation templates
            TaskTemplate {
                input: "Document {api_component} with usage examples",
                context: "Target audience: {audience}. Include {sections}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Api,
                tags: vec!["documentation", "api"],
                quality: 0.82,
            },
            TaskTemplate {
                input: "Create architecture documentation for {system}",
                context: "Include: {components}. Diagrams for {diagram_types}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["documentation", "architecture"],
                quality: 0.84,
            },
            // Exploration templates
            TaskTemplate {
                input: "Explore {technology} for {use_case}",
                context: "Requirements: {requirements}. Compare with {alternatives}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["research", "exploration", "technology"],
                quality: 0.80,
            },
            TaskTemplate {
                input: "Compare {option_a} vs {option_b} for {purpose}",
                context: "Evaluate based on: {criteria}. Context: {context}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["research", "comparison"],
                quality: 0.83,
            },
            // Pattern analysis templates
            TaskTemplate {
                input: "Identify design patterns in {codebase}",
                context: "Looking for: {patterns}. Document anti-patterns in {areas}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Web,
                tags: vec!["analysis", "patterns"],
                quality: 0.86,
            },
            TaskTemplate {
                input: "Analyze data flow in {system} from {source} to {destination}",
                context: "Map transformations at {stages}. Document {aspects}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::DataScience,
                tags: vec!["analysis", "data-flow"],
                quality: 0.88,
            },
            TaskTemplate {
                input: "Survey {library_ecosystem} for {functionality}",
                context: "Must support {requirements}. Evaluate {criteria}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["research", "libraries"],
                quality: 0.81,
            },
        ]
    }

    /// Generate security task templates
    fn security_templates(&self) -> Vec<TaskTemplate> {
        vec![
            // Vulnerability analysis templates
            TaskTemplate {
                input: "Audit {code_component} for {vulnerability_type} vulnerabilities",
                context: "Focus areas: {focus_areas}. Check against {standards}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "audit", "vulnerability"],
                quality: 0.95,
            },
            TaskTemplate {
                input: "Analyze authentication flow for security weaknesses",
                context: "Current implementation: {implementation}. Threats: {threat_model}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "authentication"],
                quality: 0.93,
            },
            TaskTemplate {
                input: "Review {api_endpoint} for injection vulnerabilities",
                context: "Input sources: {inputs}. Sanitization: {sanitization}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "injection", "api"],
                quality: 0.94,
            },
            // Threat detection templates
            TaskTemplate {
                input: "Identify potential {attack_type} attack vectors in {system}",
                context: "System architecture: {architecture}. Trust boundaries: {boundaries}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "threat-modeling"],
                quality: 0.92,
            },
            TaskTemplate {
                input: "Analyze {dependency} for known vulnerabilities",
                context: "Version: {version}. Usage context: {usage}. CVE database: {cve_db}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Security,
                tags: vec!["security", "dependencies", "cve"],
                quality: 0.89,
            },
            // Security hardening templates
            TaskTemplate {
                input: "Implement {security_control} for {component}",
                context: "Threat model: {threats}. Compliance requirements: {compliance}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "hardening"],
                quality: 0.91,
            },
            TaskTemplate {
                input: "Add input validation for {input_type} in {context}",
                context: "Expected format: {format}. Constraints: {constraints}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Security,
                tags: vec!["security", "validation"],
                quality: 0.87,
            },
            // Cryptography templates
            TaskTemplate {
                input: "Review cryptographic implementation of {feature}",
                context:
                    "Algorithm: {algorithm}. Key management: {key_mgmt}. Standards: {standards}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "cryptography"],
                quality: 0.96,
            },
            TaskTemplate {
                input: "Audit data encryption at rest for {storage_system}",
                context: "Encryption scheme: {scheme}. Key rotation: {rotation}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "encryption"],
                quality: 0.94,
            },
            // Compliance templates
            TaskTemplate {
                input: "Ensure {standard} compliance in {system_area}",
                context: "Requirements: {requirements}. Current gaps: {gaps}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Security,
                tags: vec!["security", "compliance"],
                quality: 0.90,
            },
        ]
    }

    /// Generate architecture task templates
    fn architecture_templates(&self) -> Vec<TaskTemplate> {
        vec![
            // System design templates
            TaskTemplate {
                input: "Design {system_type} system for {purpose}",
                context: "Requirements: {requirements}. Scale: {scale}. Constraints: {constraints}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Web,
                tags: vec!["architecture", "system-design"],
                quality: 0.90,
            },
            TaskTemplate {
                input: "Architect microservices for {domain}",
                context: "Services needed: {services}. Communication: {patterns}. Data: {data_strategy}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Web,
                tags: vec!["architecture", "microservices"],
                quality: 0.92,
            },
            TaskTemplate {
                input: "Design database schema for {application}",
                context: "Entities: {entities}. Relationships: {relationships}. Access patterns: {patterns}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Database,
                tags: vec!["architecture", "database"],
                quality: 0.88,
            },
            // API design templates
            TaskTemplate {
                input: "Design RESTful API for {resource_type}",
                context: "Operations: {operations}. Versioning: {versioning}. Auth: {auth}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Api,
                tags: vec!["architecture", "api", "rest"],
                quality: 0.85,
            },
            TaskTemplate {
                input: "Architect GraphQL schema for {domain}",
                context: "Types: {types}. Queries: {queries}. Mutations: {mutations}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Api,
                tags: vec!["architecture", "api", "graphql"],
                quality: 0.86,
            },
            // Scalability templates
            TaskTemplate {
                input: "Plan scaling strategy for {system} to handle {target_load}",
                context: "Current: {current_state}. Bottlenecks: {bottlenecks}. Budget: {budget}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Web,
                tags: vec!["architecture", "scalability"],
                quality: 0.91,
            },
            TaskTemplate {
                input: "Design caching strategy for {application}",
                context: "Access patterns: {patterns}. Data volatility: {volatility}. Layers: {layers}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["architecture", "caching"],
                quality: 0.84,
            },
            // Infrastructure templates
            TaskTemplate {
                input: "Design deployment architecture for {application}",
                context: "Environments: {environments}. CI/CD: {cicd}. Monitoring: {monitoring}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::DevOps,
                tags: vec!["architecture", "deployment", "infrastructure"],
                quality: 0.87,
            },
            TaskTemplate {
                input: "Plan disaster recovery strategy for {system}",
                context: "RTO: {rto}. RPO: {rpo}. Critical data: {data}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::DevOps,
                tags: vec!["architecture", "disaster-recovery"],
                quality: 0.93,
            },
            // Integration templates
            TaskTemplate {
                input: "Design integration pattern for {system_a} and {system_b}",
                context: "Data flow: {flow}. Consistency: {consistency}. Error handling: {errors}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["architecture", "integration"],
                quality: 0.83,
            },
        ]
    }

    /// Generate reviewer task templates
    fn reviewer_templates(&self) -> Vec<TaskTemplate> {
        vec![
            // Code review templates
            TaskTemplate {
                input: "Review pull request #{pr_number} for {purpose}",
                context: "Changes: {changes}. Focus on: {focus_areas}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Web,
                tags: vec!["review", "code-review", "pull-request"],
                quality: 0.84,
            },
            TaskTemplate {
                input: "Assess code quality of {module}",
                context: "Check: {criteria}. Standards: {standards}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["review", "code-quality"],
                quality: 0.86,
            },
            TaskTemplate {
                input: "Review {code_section} for adherence to {coding_standard}",
                context: "Violations to check: {violations}. Document issues in: {format}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Web,
                tags: vec!["review", "standards"],
                quality: 0.82,
            },
            // Best practices templates
            TaskTemplate {
                input: "Evaluate {implementation} against {framework} best practices",
                context: "Current approach: {approach}. Recommended patterns: {patterns}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["review", "best-practices"],
                quality: 0.85,
            },
            TaskTemplate {
                input: "Review error handling in {component}",
                context: "Error scenarios: {scenarios}. Current handling: {handling}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Web,
                tags: vec!["review", "error-handling"],
                quality: 0.87,
            },
            // Performance review templates
            TaskTemplate {
                input: "Review {code_section} for performance issues",
                context: "Metrics: {metrics}. Hot paths: {hot_paths}. Optimizations: {optimizations}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Systems,
                tags: vec!["review", "performance"],
                quality: 0.88,
            },
            TaskTemplate {
                input: "Analyze query performance in {data_layer}",
                context: "Slow queries: {queries}. Execution plans: {plans}",
                complexity: ComplexityLevel::Moderate,
                domain: DomainType::Database,
                tags: vec!["review", "performance", "database"],
                quality: 0.89,
            },
            // Architecture review templates
            TaskTemplate {
                input: "Review architectural decisions in {design_doc}",
                context: "Proposed: {proposal}. Alternatives: {alternatives}. Trade-offs: {tradeoffs}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Web,
                tags: vec!["review", "architecture"],
                quality: 0.90,
            },
            TaskTemplate {
                input: "Assess scalability of {system_design}",
                context: "Expected load: {load}. Current capacity: {capacity}. Bottlenecks: {bottlenecks}",
                complexity: ComplexityLevel::Complex,
                domain: DomainType::Web,
                tags: vec!["review", "scalability"],
                quality: 0.91,
            },
            // Testing review templates
            TaskTemplate {
                input: "Review test coverage for {module}",
                context: "Current coverage: {coverage}. Critical paths: {paths}. Gaps: {gaps}",
                complexity: ComplexityLevel::Simple,
                domain: DomainType::Web,
                tags: vec!["review", "testing", "coverage"],
                quality: 0.83,
            },
        ]
    }

    /// Instantiate a template with random values
    fn instantiate_template(
        &mut self,
        template: &TaskTemplate,
        category: TaskCategory,
    ) -> ClaudeTaskExample {
        let input = self.fill_template(&template.input);
        let context = self.fill_template(&template.context);
        let expected_model = category.recommended_model(template.complexity);

        ClaudeTaskExample {
            input,
            context,
            output_agent: category.name().to_string(),
            metadata: TaskMetadata {
                category,
                complexity: template.complexity,
                domain: template.domain,
                expected_model: expected_model.to_string(),
                quality_score: template.quality,
                tags: template.tags.iter().map(|s| s.to_string()).collect(),
            },
        }
    }

    /// Fill template placeholders with random values
    fn fill_template(&mut self, template: &str) -> String {
        let mut result = template.to_string();

        // Replace placeholders with random values
        let replacements = self.get_template_replacements();
        for (placeholder, options) in replacements {
            let value = options.choose(&mut self.rng).unwrap();
            result = result.replace(&format!("{{{}}}", placeholder), value);
        }

        result
    }

    /// Get replacement options for template placeholders.
    ///
    /// Returns a `BTreeMap` (sorted by key) instead of `HashMap` because
    /// `fill_template` consumes the RNG once per placeholder, so the
    /// iteration order has to be deterministic for seeded reproducibility.
    fn get_template_replacements(
        &self,
    ) -> std::collections::BTreeMap<&'static str, Vec<&'static str>> {
        let mut map = std::collections::BTreeMap::new();

        map.insert(
            "language",
            vec!["Rust", "TypeScript", "Python", "Go", "Java"],
        );
        map.insert(
            "framework",
            vec!["React", "Vue", "Angular", "Svelte", "Next.js"],
        );
        map.insert(
            "function_type",
            vec!["async", "recursive", "higher-order", "pure", "generic"],
        );
        map.insert(
            "component_type",
            vec!["form", "table", "modal", "dashboard", "navigation"],
        );
        map.insert(
            "data_structure",
            vec![
                "binary tree",
                "hash map",
                "linked list",
                "priority queue",
                "trie",
            ],
        );
        map.insert(
            "issue_type",
            vec![
                "null pointer",
                "type mismatch",
                "race condition",
                "deadlock",
                "stack overflow",
            ],
        );
        map.insert(
            "quality_attribute",
            vec![
                "readability",
                "maintainability",
                "performance",
                "testability",
                "modularity",
            ],
        );
        map.insert(
            "pattern",
            vec!["singleton", "factory", "observer", "strategy", "repository"],
        );
        map.insert(
            "api_name",
            vec!["Stripe", "Twilio", "SendGrid", "AWS S3", "OpenAI"],
        );
        map.insert("http_method", vec!["GET", "POST", "PUT", "DELETE", "PATCH"]);
        map.insert(
            "vulnerability_type",
            vec![
                "SQL injection",
                "XSS",
                "CSRF",
                "authentication",
                "authorization",
            ],
        );
        map.insert(
            "attack_type",
            vec![
                "DDoS",
                "man-in-the-middle",
                "replay",
                "privilege escalation",
            ],
        );
        map.insert(
            "security_control",
            vec!["rate limiting", "CORS", "CSP", "input sanitization"],
        );
        map.insert(
            "system_type",
            vec![
                "distributed",
                "event-driven",
                "real-time",
                "batch processing",
            ],
        );
        map.insert(
            "resource_type",
            vec!["users", "products", "orders", "payments", "inventory"],
        );

        map
    }

    /// Augment examples with paraphrases and variations
    fn augment_examples(&mut self, examples: &[ClaudeTaskExample]) -> Vec<ClaudeTaskExample> {
        let mut augmented = Vec::new();

        for example in examples {
            // Generate paraphrases
            for _ in 0..self.config.augmentation.paraphrases_per_example {
                if let Some(paraphrased) = self.paraphrase_example(example) {
                    augmented.push(paraphrased);
                }
            }

            // Generate complexity variations
            for _ in 0..self.config.augmentation.complexity_variations {
                if let Some(varied) = self.vary_complexity(example) {
                    augmented.push(varied);
                }
            }

            // Domain transfer (if enabled)
            if self.config.augmentation.enable_domain_transfer {
                if let Some(transferred) = self.transfer_domain(example) {
                    augmented.push(transferred);
                }
            }
        }

        augmented
    }

    /// Paraphrase an example (simple implementation)
    fn paraphrase_example(&mut self, example: &ClaudeTaskExample) -> Option<ClaudeTaskExample> {
        // Simple paraphrasing by replacing words
        let paraphrase_map: HashMap<&str, Vec<&str>> = [
            ("implement", vec!["create", "build", "develop", "write"]),
            ("analyze", vec!["examine", "investigate", "study", "review"]),
            ("design", vec!["architect", "plan", "structure", "outline"]),
            ("fix", vec!["resolve", "correct", "repair", "patch"]),
            ("optimize", vec!["improve", "enhance", "refine", "tune"]),
        ]
        .iter()
        .cloned()
        .collect();

        let mut paraphrased_input = example.input.clone();
        for (original, alternatives) in &paraphrase_map {
            if paraphrased_input.to_lowercase().contains(original) {
                let replacement = alternatives.choose(&mut self.rng)?;
                paraphrased_input = paraphrased_input
                    .to_lowercase()
                    .replace(original, replacement);
            }
        }

        Some(ClaudeTaskExample {
            input: paraphrased_input,
            context: example.context.clone(),
            output_agent: example.output_agent.clone(),
            metadata: example.metadata.clone(),
        })
    }

    /// Vary the complexity of an example
    fn vary_complexity(&mut self, example: &ClaudeTaskExample) -> Option<ClaudeTaskExample> {
        let new_complexity = match example.metadata.complexity {
            ComplexityLevel::Simple => {
                if self.rng.gen_bool(0.5) {
                    ComplexityLevel::Moderate
                } else {
                    return None;
                }
            }
            ComplexityLevel::Moderate => {
                if self.rng.gen_bool(0.5) {
                    ComplexityLevel::Simple
                } else {
                    ComplexityLevel::Complex
                }
            }
            ComplexityLevel::Complex => {
                if self.rng.gen_bool(0.5) {
                    ComplexityLevel::Moderate
                } else {
                    return None;
                }
            }
        };

        let new_model = example.metadata.category.recommended_model(new_complexity);

        Some(ClaudeTaskExample {
            input: example.input.clone(),
            context: example.context.clone(),
            output_agent: example.output_agent.clone(),
            metadata: TaskMetadata {
                complexity: new_complexity,
                expected_model: new_model.to_string(),
                ..example.metadata.clone()
            },
        })
    }

    /// Transfer an example to a different domain
    fn transfer_domain(&mut self, example: &ClaudeTaskExample) -> Option<ClaudeTaskExample> {
        let domains = [
            DomainType::Web,
            DomainType::Systems,
            DomainType::DataScience,
            DomainType::Mobile,
            DomainType::DevOps,
            DomainType::Security,
            DomainType::Database,
            DomainType::Api,
        ];

        let new_domain = *domains.choose(&mut self.rng)?;
        if new_domain == example.metadata.domain {
            return None;
        }

        Some(ClaudeTaskExample {
            input: example.input.clone(),
            context: example.context.clone(),
            output_agent: example.output_agent.clone(),
            metadata: TaskMetadata {
                domain: new_domain,
                ..example.metadata.clone()
            },
        })
    }
}

/// Task template for seed example generation
#[derive(Debug, Clone)]
struct TaskTemplate {
    input: &'static str,
    context: &'static str,
    complexity: ComplexityLevel,
    domain: DomainType,
    tags: Vec<&'static str>,
    quality: f32,
}

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

    #[test]
    fn test_dataset_generation() {
        let config = DatasetConfig {
            examples_per_category: 10,
            enable_augmentation: false,
            ..Default::default()
        };

        let mut generator = DatasetGenerator::new(config);
        let dataset = generator.generate();

        // Should have 5 categories * 10 examples = 50 examples
        assert_eq!(dataset.examples.len(), 50);
        assert_eq!(dataset.stats.total_examples, 50);

        // Check category distribution
        for category in TaskCategory::all() {
            let count = dataset
                .stats
                .examples_per_category
                .get(category.name())
                .unwrap_or(&0);
            assert_eq!(*count, 10);
        }
    }

    #[test]
    fn test_dataset_augmentation() {
        let config = DatasetConfig {
            examples_per_category: 5,
            enable_augmentation: true,
            augmentation: AugmentationConfig {
                paraphrases_per_example: 1,
                complexity_variations: 1,
                enable_domain_transfer: true,
            },
            ..Default::default()
        };

        let mut generator = DatasetGenerator::new(config);
        let dataset = generator.generate();

        // Should have base examples + augmented examples
        // Base: 5 categories * 5 = 25
        // Augmented: 25 * (1 paraphrase + 1 complexity + 1 domain) = ~75 more
        assert!(dataset.examples.len() >= 25);
    }

    #[test]
    fn test_dataset_split() {
        let config = DatasetConfig {
            examples_per_category: 20,
            enable_augmentation: false,
            ..Default::default()
        };

        let mut generator = DatasetGenerator::new(config);
        let dataset = generator.generate();

        let (train, val, test) = dataset.split(0.7, 0.15, 0.15, 42);

        assert_eq!(train.len() + val.len() + test.len(), dataset.examples.len());
        assert!(train.len() > val.len());
        assert!(train.len() > test.len());
    }

    #[test]
    fn test_model_recommendation() {
        assert_eq!(
            TaskCategory::Coder.recommended_model(ComplexityLevel::Simple),
            "haiku"
        );
        assert_eq!(
            TaskCategory::Security.recommended_model(ComplexityLevel::Simple),
            "opus"
        );
        assert_eq!(
            TaskCategory::Architecture.recommended_model(ComplexityLevel::Complex),
            "opus"
        );
    }
}