soma-core 2.0.0

World's first production-ready self-aware development system with meta-cognitive capabilities and cognitive reasoning engine for intelligent development platforms
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
// GPT-4: High-performance edit control system
use crate::agents::gpt4_agent::ProposedEdit;
use std::collections::BTreeSet;

pub mod validation;
pub mod staged_application;
pub mod edit_history_time_travel;
pub mod conditional_logic;
pub mod file_protection;



#[derive(Debug, Clone)]
pub struct ModifiableEdit {
    pub base_edit: ProposedEdit,
    pub modifications: Vec<EditModification>,
    pub approval_state: ApprovalState,
    pub processing_metadata: ProcessingMetadata,
}

#[derive(Debug, Clone)]
pub enum EditModification {
    CodeChange {
        line: usize,
        old: String,
        new: String,
    },
    ScopeExpansion {
        additional_lines: (usize, usize),
    },
    ScopeReduction {
        removed_lines: BTreeSet<usize>,
    },
    ConfidenceAdjustment {
        new_confidence: f64,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub enum ApprovalState {
    Pending,
    Approved,
    ApprovedWithModifications,
    Conditional { conditions: Vec<String> },
    Queued { priority: u8 },
    Rejected,
    // Issue #19: Granular Approval Levels
    GranularPending { 
        required_level: ApprovalLevel,
        current_approvals: Vec<ApprovalRecord>,
    },
    PartiallyApproved {
        required_level: ApprovalLevel,
        current_level: ApprovalLevel,
        approvals: Vec<ApprovalRecord>,
        pending_escalation: bool,
    },
    EscalationRequired {
        current_level: ApprovalLevel,
        required_level: ApprovalLevel,
        reason: String,
        approvals: Vec<ApprovalRecord>,
    },
}

/// Issue #19: Multi-level approval system
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ApprovalLevel {
    Auto,      // Automatic approval for low-risk changes
    Low,       // Single reviewer approval
    Medium,    // Senior reviewer or two junior reviewers
    High,      // Lead/architect approval required
    Critical,  // Multiple leads + security review
}

#[derive(Debug, Clone, PartialEq)]
pub struct ApprovalRecord {
    pub approver_id: String,
    pub approver_role: ApprovalRole,
    pub level: ApprovalLevel,
    pub timestamp: std::time::SystemTime,
    pub comments: Option<String>,
    pub delegation_chain: Vec<String>, // Track if approval was delegated
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ApprovalRole {
    Junior,
    Senior,
    Lead,
    Architect,
    Security,
    System, // For automatic approvals
}

/// Policy engine for determining required approval levels
#[derive(Debug, Clone)]
pub struct ApprovalPolicy {
    pub risk_thresholds: RiskThresholds,
    pub file_patterns: Vec<FileApprovalRule>,
    pub change_type_rules: Vec<ChangeTypeRule>,
    pub delegation_rules: DelegationRules,
}

#[derive(Debug, Clone)]
pub struct RiskThresholds {
    pub lines_changed_high_risk: usize,
    pub complexity_score_critical: f64,
    pub confidence_threshold_escalation: f64,
    pub security_sensitive_patterns: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct FileApprovalRule {
    pub pattern: String,
    pub required_level: ApprovalLevel,
    pub reason: String,
}

#[derive(Debug, Clone)]
pub struct ChangeTypeRule {
    pub change_type: String,
    pub required_level: ApprovalLevel,
    pub conditions: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct DelegationRules {
    pub max_delegation_depth: usize,
    pub allowed_delegations: std::collections::HashMap<ApprovalRole, Vec<ApprovalRole>>,
    pub time_based_escalation: Option<std::time::Duration>,
}

#[derive(Debug, Clone)]
pub struct ProcessingMetadata {
    pub processing_time_ms: u64,
    pub memory_usage_bytes: usize,
    pub validation_results: Vec<ValidationResult>,
}

#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub validator_name: String,
    pub passed: bool,
    pub message: String,
    pub severity: ValidationSeverity,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ValidationSeverity {
    Info,
    Warning,
    Error,
    Critical,
}

impl Default for ApprovalPolicy {
    fn default() -> Self {
        let mut allowed_delegations = std::collections::HashMap::new();
        allowed_delegations.insert(ApprovalRole::Architect, vec![ApprovalRole::Lead]);
        allowed_delegations.insert(ApprovalRole::Lead, vec![ApprovalRole::Senior]);
        allowed_delegations.insert(ApprovalRole::Senior, vec![ApprovalRole::Junior]);

        Self {
            risk_thresholds: RiskThresholds {
                lines_changed_high_risk: 50,
                complexity_score_critical: 0.8,
                confidence_threshold_escalation: 0.6,
                security_sensitive_patterns: vec![
                    "password".to_string(),
                    "secret".to_string(),
                    "token".to_string(),
                    "auth".to_string(),
                    "crypto".to_string(),
                ],
            },
            file_patterns: vec![
                FileApprovalRule {
                    pattern: "src/security/*".to_string(),
                    required_level: ApprovalLevel::Critical,
                    reason: "Security-critical code".to_string(),
                },
                FileApprovalRule {
                    pattern: "*/mod.rs".to_string(),
                    required_level: ApprovalLevel::High,
                    reason: "Module structure changes".to_string(),
                },
                FileApprovalRule {
                    pattern: "Cargo.toml".to_string(),
                    required_level: ApprovalLevel::High,
                    reason: "Dependency changes".to_string(),
                },
            ],
            change_type_rules: vec![
                ChangeTypeRule {
                    change_type: "refactoring".to_string(),
                    required_level: ApprovalLevel::Medium,
                    conditions: vec!["Large scope changes".to_string()],
                },
                ChangeTypeRule {
                    change_type: "bug_fix".to_string(),
                    required_level: ApprovalLevel::Low,
                    conditions: vec!["Small isolated fixes".to_string()],
                },
            ],
            delegation_rules: DelegationRules {
                max_delegation_depth: 2,
                allowed_delegations,
                time_based_escalation: Some(std::time::Duration::from_secs(24 * 60 * 60)), // 24 hours
            },
        }
    }
}

/// Granular approval management system
#[derive(Debug, Clone)]
pub struct GranularApprovalSystem {
    pub policy: ApprovalPolicy,
    pub approval_history: Vec<ApprovalRecord>,
    pub escalation_queue: Vec<EscalationRequest>,
}

#[derive(Debug, Clone)]
pub struct EscalationRequest {
    pub edit_id: String,
    pub current_level: ApprovalLevel,
    pub required_level: ApprovalLevel,
    pub reason: String,
    pub timestamp: std::time::SystemTime,
    pub requesting_approver: String,
}

impl GranularApprovalSystem {
    pub fn new() -> Self {
        Self {
            policy: ApprovalPolicy::default(),
            approval_history: Vec::new(),
            escalation_queue: Vec::new(),
        }
    }

    /// Determine required approval level for an edit
    pub fn determine_required_level(&self, edit: &ModifiableEdit) -> ApprovalLevel {
        let mut required_level = ApprovalLevel::Auto;

        // Check confidence threshold
        if edit.get_effective_confidence() < self.policy.risk_thresholds.confidence_threshold_escalation {
            required_level = std::cmp::max(required_level, ApprovalLevel::Medium);
        }

        // Check file patterns
        for rule in &self.policy.file_patterns {
            if self.matches_pattern(&edit.base_edit.file, &rule.pattern) {
                required_level = std::cmp::max(required_level, rule.required_level.clone());
            }
        }

        // Check lines changed
        let lines_changed = edit.base_edit.new_code.lines().count();
        if lines_changed > self.policy.risk_thresholds.lines_changed_high_risk {
            required_level = std::cmp::max(required_level, ApprovalLevel::High);
        }

        // Check security patterns
        for pattern in &self.policy.risk_thresholds.security_sensitive_patterns {
            if edit.base_edit.new_code.to_lowercase().contains(pattern) {
                required_level = std::cmp::max(required_level, ApprovalLevel::Critical);
                break;
            }
        }

        required_level
    }

    /// Add approval record
    pub fn add_approval(&mut self, approval: ApprovalRecord) -> Result<ApprovalLevel, String> {
        // Validate approval
        if approval.delegation_chain.len() > self.policy.delegation_rules.max_delegation_depth {
            return Err("Delegation chain too deep".to_string());
        }

        self.approval_history.push(approval.clone());
        
        // Calculate current approval level based on all approvals
        self.calculate_current_approval_level()
    }

    /// Calculate current approval level based on collected approvals
    pub fn calculate_current_approval_level(&self) -> Result<ApprovalLevel, String> {
        if self.approval_history.is_empty() {
            return Ok(ApprovalLevel::Auto);
        }

        let mut highest_level = ApprovalLevel::Auto;
        let mut senior_count = 0;
        let mut has_lead = false;
        let mut has_architect = false;
        let mut has_security = false;

        for approval in &self.approval_history {
            match approval.approver_role {
                ApprovalRole::Junior => {
                    // Junior approvals contribute minimally
                }
                ApprovalRole::Senior => {
                    senior_count += 1;
                    highest_level = std::cmp::max(highest_level, ApprovalLevel::Low);
                }
                ApprovalRole::Lead => {
                    has_lead = true;
                    highest_level = std::cmp::max(highest_level, ApprovalLevel::High);
                }
                ApprovalRole::Architect => {
                    has_architect = true;
                    highest_level = std::cmp::max(highest_level, ApprovalLevel::High);
                }
                ApprovalRole::Security => {
                    has_security = true;
                }
                ApprovalRole::System => {
                    // System approvals for auto-approval
                }
            }
        }

        // Apply approval level logic
        if has_architect && has_security {
            highest_level = std::cmp::max(highest_level, ApprovalLevel::Critical);
        } else if has_lead || has_architect {
            highest_level = std::cmp::max(highest_level, ApprovalLevel::High);
        } else if senior_count >= 2 {
            highest_level = std::cmp::max(highest_level, ApprovalLevel::Medium);
        } else if senior_count >= 1 {
            highest_level = std::cmp::max(highest_level, ApprovalLevel::Low);
        }

        Ok(highest_level)
    }

    /// Check if current approvals meet required level
    pub fn is_approval_sufficient(&self, required_level: &ApprovalLevel) -> Result<bool, String> {
        let current_level = self.calculate_current_approval_level()?;
        Ok(current_level >= *required_level)
    }

    /// Request escalation to higher approval level
    pub fn request_escalation(&mut self, request: EscalationRequest) {
        self.escalation_queue.push(request);
    }

    /// Get approval status summary
    pub fn get_approval_status(&self, required_level: &ApprovalLevel) -> ApprovalStatus {
        let current_level = self.calculate_current_approval_level().unwrap_or(ApprovalLevel::Auto);
        let is_sufficient = current_level >= *required_level;

        ApprovalStatus {
            required_level: required_level.clone(),
            current_level: current_level.clone(),
            is_sufficient,
            approval_count: self.approval_history.len(),
            escalation_pending: !self.escalation_queue.is_empty(),
            next_required_role: self.determine_next_required_role(required_level, &current_level),
        }
    }

    fn matches_pattern(&self, file_path: &str, pattern: &str) -> bool {
        // Simple pattern matching - could be enhanced with regex or globbing
        if pattern.contains('*') {
            let prefix = pattern.split('*').next().unwrap_or("");
            let suffix = pattern.split('*').last().unwrap_or("");
            file_path.starts_with(prefix) && file_path.ends_with(suffix)
        } else {
            file_path == pattern
        }
    }

    fn determine_next_required_role(&self, required_level: &ApprovalLevel, current_level: &ApprovalLevel) -> Option<ApprovalRole> {
        if current_level >= required_level {
            return None;
        }

        match required_level {
            ApprovalLevel::Auto => None,
            ApprovalLevel::Low => Some(ApprovalRole::Senior),
            ApprovalLevel::Medium => {
                let senior_count = self.approval_history.iter()
                    .filter(|a| a.approver_role == ApprovalRole::Senior)
                    .count();
                if senior_count < 2 {
                    Some(ApprovalRole::Senior)
                } else {
                    Some(ApprovalRole::Lead)
                }
            },
            ApprovalLevel::High => Some(ApprovalRole::Lead),
            ApprovalLevel::Critical => {
                let has_architect = self.approval_history.iter()
                    .any(|a| a.approver_role == ApprovalRole::Architect);
                let has_security = self.approval_history.iter()
                    .any(|a| a.approver_role == ApprovalRole::Security);
                
                if !has_architect {
                    Some(ApprovalRole::Architect)
                } else if !has_security {
                    Some(ApprovalRole::Security)
                } else {
                    None
                }
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct ApprovalStatus {
    pub required_level: ApprovalLevel,
    pub current_level: ApprovalLevel,
    pub is_sufficient: bool,
    pub approval_count: usize,
    pub escalation_pending: bool,
    pub next_required_role: Option<ApprovalRole>,
}

impl Default for ProcessingMetadata {
    fn default() -> Self {
        Self {
            processing_time_ms: 0,
            memory_usage_bytes: 0,
            validation_results: Vec::new(),
        }
    }
}

impl ModifiableEdit {
    // GPT-4: Zero-copy optimized constructor
    pub fn from_proposed_edit(edit: ProposedEdit) -> Self {
        Self {
            base_edit: edit,
            modifications: Vec::with_capacity(4), // Optimized allocation
            approval_state: ApprovalState::Pending,
            processing_metadata: ProcessingMetadata::default(),
        }
    }

    /// Issue #19: Initialize with granular approval system
    pub fn from_proposed_edit_with_approval_level(edit: ProposedEdit, required_level: ApprovalLevel) -> Self {
        Self {
            base_edit: edit,
            modifications: Vec::with_capacity(4),
            approval_state: ApprovalState::GranularPending {
                required_level,
                current_approvals: Vec::new(),
            },
            processing_metadata: ProcessingMetadata::default(),
        }
    }

    /// Issue #19: Add approval record to granular approval system
    pub fn add_approval_record(&mut self, approval: ApprovalRecord) -> Result<(), String> {
        match &mut self.approval_state {
            ApprovalState::GranularPending { current_approvals, .. } => {
                current_approvals.push(approval);
                Ok(())
            }
            ApprovalState::PartiallyApproved { approvals, .. } => {
                approvals.push(approval);
                Ok(())
            }
            ApprovalState::EscalationRequired { approvals, .. } => {
                approvals.push(approval);
                Ok(())
            }
            _ => Err("Edit is not in a granular approval state".to_string())
        }
    }

    /// Issue #19: Check if edit meets granular approval requirements
    pub fn evaluate_granular_approval(&mut self) -> Result<(), String> {
        let mut approval_system = GranularApprovalSystem::new();
        
        // Copy approval records to system
        let approvals = match &self.approval_state {
            ApprovalState::GranularPending { current_approvals, required_level } => {
                (current_approvals.clone(), required_level.clone())
            }
            ApprovalState::PartiallyApproved { approvals, required_level, .. } => {
                (approvals.clone(), required_level.clone())
            }
            ApprovalState::EscalationRequired { approvals, required_level, .. } => {
                (approvals.clone(), required_level.clone())
            }
            _ => return Err("Edit is not in a granular approval state".to_string())
        };

        // Add approvals to system
        for approval in &approvals.0 {
            approval_system.add_approval(approval.clone())?;
        }

        // Check if approval is sufficient
        if approval_system.is_approval_sufficient(&approvals.1)? {
            self.approval_state = ApprovalState::Approved;
        } else {
            let status = approval_system.get_approval_status(&approvals.1);
            if status.current_level < status.required_level {
                self.approval_state = ApprovalState::PartiallyApproved {
                    required_level: status.required_level,
                    current_level: status.current_level,
                    approvals: approvals.0,
                    pending_escalation: status.escalation_pending,
                };
            }
        }

        Ok(())
    }

    // GPT-4: Efficient diff computation with string interning
    pub fn compute_final_code(&self) -> String {
        let mut result = self.base_edit.new_code.clone();

        // Apply modifications in order
        for modification in &self.modifications {
            match modification {
                EditModification::CodeChange { line: _, old, new } => {
                    // Simple implementation - can be optimized with rope data structure
                    result = result.replace(old, new);
                }
                EditModification::ScopeExpansion { additional_lines } => {
                    // Add placeholder for scope expansion
                    result.push_str(&format!(
                        "\n// Expanded scope: lines {}-{}",
                        additional_lines.0, additional_lines.1
                    ));
                }
                EditModification::ScopeReduction { removed_lines: _ } => {
                    // Add placeholder for scope reduction
                    result.push_str("\n// Scope reduced");
                }
                EditModification::ConfidenceAdjustment { new_confidence: _ } => {
                    // Confidence adjustments don't affect code content
                }
            }
        }

        result
    }

    pub fn add_modification(&mut self, modification: EditModification) {
        self.modifications.push(modification);
    }

    pub fn set_approval_state(&mut self, state: ApprovalState) {
        self.approval_state = state;
    }

    pub fn get_effective_confidence(&self) -> f64 {
        // Start with base confidence
        let mut confidence = self.base_edit.confidence;

        // Apply confidence adjustments
        for modification in &self.modifications {
            if let EditModification::ConfidenceAdjustment { new_confidence } = modification {
                confidence = *new_confidence;
            }
        }

        confidence
    }

    pub fn is_approved(&self) -> bool {
        matches!(
            self.approval_state,
            ApprovalState::Approved | ApprovalState::ApprovedWithModifications
        )
    }

    pub fn is_ready_for_application(&self) -> bool {
        self.is_approved()
            && self
                .processing_metadata
                .validation_results
                .iter()
                .all(|v| v.severity != ValidationSeverity::Critical)
    }
}

/// Enhanced EditModificationInterface for Issue #17
/// Provides advanced inline edit modification capabilities with undo/redo support
#[derive(Debug, Clone)]
pub struct EditModificationInterface {
    pub modifiable_edit: ModifiableEdit,
    pub modification_history: Vec<ModificationSnapshot>,
    pub current_snapshot: usize,
    pub interface_state: InterfaceState,
    pub view_mode: ViewMode,
    pub syntax_highlighting: bool,
}

#[derive(Debug, Clone)]
pub struct ModificationSnapshot {
    pub modifications: Vec<EditModification>,
    pub code_content: String,
    pub timestamp: std::time::SystemTime,
    pub description: String,
}

#[derive(Debug, Clone, PartialEq)]
pub enum InterfaceState {
    Editing,
    Comparing,
    Previewing,
    Validating,
    Saving,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ViewMode {
    Single,        // Single pane editor
    SideBySide,    // Original vs Modified
    Unified,       // Diff view
    FullScreen,    // Full terminal view
}

impl EditModificationInterface {
    /// Create a new EditModificationInterface from a ModifiableEdit
    pub fn new(modifiable_edit: ModifiableEdit) -> Self {
        let initial_snapshot = ModificationSnapshot {
            modifications: modifiable_edit.modifications.clone(),
            code_content: modifiable_edit.compute_final_code(),
            timestamp: std::time::SystemTime::now(),
            description: "Initial state".to_string(),
        };

        Self {
            modifiable_edit,
            modification_history: vec![initial_snapshot],
            current_snapshot: 0,
            interface_state: InterfaceState::Editing,
            view_mode: ViewMode::Single,
            syntax_highlighting: true,
        }
    }

    /// Add a new modification with snapshot creation
    pub fn add_modification(&mut self, modification: EditModification, description: String) {
        // Add modification to the edit
        self.modifiable_edit.add_modification(modification);
        
        // Create new snapshot
        let snapshot = ModificationSnapshot {
            modifications: self.modifiable_edit.modifications.clone(),
            code_content: self.modifiable_edit.compute_final_code(),
            timestamp: std::time::SystemTime::now(),
            description,
        };

        // Truncate history if we're not at the end (undo was performed)
        if self.current_snapshot < self.modification_history.len() - 1 {
            self.modification_history.truncate(self.current_snapshot + 1);
        }

        self.modification_history.push(snapshot);
        self.current_snapshot = self.modification_history.len() - 1;
    }

    /// Undo last modification
    pub fn undo(&mut self) -> bool {
        if self.current_snapshot > 0 {
            self.current_snapshot -= 1;
            self.restore_snapshot();
            true
        } else {
            false
        }
    }

    /// Redo next modification
    pub fn redo(&mut self) -> bool {
        if self.current_snapshot < self.modification_history.len() - 1 {
            self.current_snapshot += 1;
            self.restore_snapshot();
            true
        } else {
            false
        }
    }

    /// Restore state from current snapshot
    fn restore_snapshot(&mut self) {
        if let Some(snapshot) = self.modification_history.get(self.current_snapshot) {
            self.modifiable_edit.modifications = snapshot.modifications.clone();
        }
    }

    /// Get current modification count
    pub fn modification_count(&self) -> usize {
        self.modifiable_edit.modifications.len()
    }

    /// Check if there are available undos
    pub fn can_undo(&self) -> bool {
        self.current_snapshot > 0
    }

    /// Check if there are available redos
    pub fn can_redo(&self) -> bool {
        self.current_snapshot < self.modification_history.len() - 1
    }

    /// Set view mode for the interface
    pub fn set_view_mode(&mut self, mode: ViewMode) {
        self.view_mode = mode;
    }

    /// Set interface state
    pub fn set_state(&mut self, state: InterfaceState) {
        self.interface_state = state;
    }

    /// Toggle syntax highlighting
    pub fn toggle_syntax_highlighting(&mut self) {
        self.syntax_highlighting = !self.syntax_highlighting;
    }

    /// Get the current snapshot description
    pub fn current_snapshot_description(&self) -> Option<&str> {
        self.modification_history
            .get(self.current_snapshot)
            .map(|s| s.description.as_str())
    }

    /// Get modification history summary
    pub fn get_history_summary(&self) -> Vec<String> {
        self.modification_history
            .iter()
            .enumerate()
            .map(|(i, snapshot)| {
                let marker = if i == self.current_snapshot { ">" } else { " " };
                format!("{} {}: {}", marker, i, snapshot.description)
            })
            .collect()
    }

    /// Calculate diff from original to current
    pub fn get_diff_summary(&self) -> DiffSummary {
        let original = &self.modifiable_edit.base_edit.new_code;
        let current = &self.modifiable_edit.compute_final_code();
        
        let original_lines: Vec<&str> = original.lines().collect();
        let current_lines: Vec<&str> = current.lines().collect();
        
        DiffSummary {
            lines_added: current_lines.len().saturating_sub(original_lines.len()),
            lines_removed: original_lines.len().saturating_sub(current_lines.len()),
            lines_modified: self.calculate_modified_lines(&original_lines, &current_lines),
            total_changes: self.modification_count(),
        }
    }

    fn calculate_modified_lines(&self, original: &[&str], current: &[&str]) -> usize {
        let min_len = original.len().min(current.len());
        let mut modified = 0;
        
        for i in 0..min_len {
            if original[i] != current[i] {
                modified += 1;
            }
        }
        
        modified
    }
}

#[derive(Debug, Clone)]
pub struct DiffSummary {
    pub lines_added: usize,
    pub lines_removed: usize,
    pub lines_modified: usize,
    pub total_changes: usize,
}

// Re-exports for ConditionalLogicSystem
pub use conditional_logic::{
    ConditionalLogicSystem, Condition, ConditionType, ClassificationCriteria,
    TestConfiguration, ConditionalChain, ChainLink, ChainFailureStrategy,
    ConditionalApplicationResult, ChainExecutionResult, ExecutionContext
};

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

    fn create_test_edit() -> ProposedEdit {
        ProposedEdit {
            file: "test.rs".to_string(),
            line_range: (10, 15),
            new_code: "fn test() {\n    println!(\"Hello\");\n}".to_string(),
            reason: "Test function".to_string(),
            confidence: 0.9,
        }
    }

    #[test]
    fn test_modifiable_edit_creation() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);

        assert_eq!(modifiable.approval_state, ApprovalState::Pending);
        assert_eq!(modifiable.modifications.len(), 0);
        assert_eq!(modifiable.get_effective_confidence(), 0.9);
    }

    #[test]
    fn test_code_modification() {
        let edit = create_test_edit();
        let mut modifiable = ModifiableEdit::from_proposed_edit(edit);

        modifiable.add_modification(EditModification::CodeChange {
            line: 1,
            old: "Hello".to_string(),
            new: "World".to_string(),
        });

        let final_code = modifiable.compute_final_code();
        assert!(final_code.contains("World"));
        assert!(!final_code.contains("Hello"));
    }

    #[test]
    fn test_confidence_adjustment() {
        let edit = create_test_edit();
        let mut modifiable = ModifiableEdit::from_proposed_edit(edit);

        modifiable.add_modification(EditModification::ConfidenceAdjustment {
            new_confidence: 0.8,
        });

        assert_eq!(modifiable.get_effective_confidence(), 0.8);
    }

    #[test]
    fn test_approval_states() {
        let edit = create_test_edit();
        let mut modifiable = ModifiableEdit::from_proposed_edit(edit);

        assert!(!modifiable.is_approved());

        modifiable.set_approval_state(ApprovalState::Approved);
        assert!(modifiable.is_approved());
        assert!(modifiable.is_ready_for_application());

        modifiable.set_approval_state(ApprovalState::Rejected);
        assert!(!modifiable.is_approved());
    }

    // === EDIT MODIFICATION INTERFACE TESTS ===

    #[test]
    fn test_edit_modification_interface_creation() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let interface = EditModificationInterface::new(modifiable);

        assert_eq!(interface.current_snapshot, 0);
        assert_eq!(interface.modification_history.len(), 1);
        assert_eq!(interface.interface_state, InterfaceState::Editing);
        assert_eq!(interface.view_mode, ViewMode::Single);
        assert!(interface.syntax_highlighting);
        assert_eq!(interface.modification_count(), 0);
    }

    #[test]
    fn test_modification_tracking_with_snapshots() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        // Add first modification
        interface.add_modification(
            EditModification::CodeChange {
                line: 1,
                old: "Hello".to_string(),
                new: "World".to_string(),
            },
            "Changed greeting".to_string(),
        );

        assert_eq!(interface.modification_count(), 1);
        assert_eq!(interface.modification_history.len(), 2);
        assert_eq!(interface.current_snapshot, 1);

        // Add second modification
        interface.add_modification(
            EditModification::ConfidenceAdjustment { new_confidence: 0.8 },
            "Adjusted confidence".to_string(),
        );

        assert_eq!(interface.modification_count(), 2);
        assert_eq!(interface.modification_history.len(), 3);
        assert_eq!(interface.current_snapshot, 2);
    }

    #[test]
    fn test_undo_redo_functionality() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        // Add modifications
        interface.add_modification(
            EditModification::CodeChange {
                line: 1,
                old: "Hello".to_string(),
                new: "World".to_string(),
            },
            "First change".to_string(),
        );
        
        interface.add_modification(
            EditModification::ConfidenceAdjustment { new_confidence: 0.8 },
            "Second change".to_string(),
        );

        assert_eq!(interface.modification_count(), 2);
        assert!(interface.can_undo());
        assert!(!interface.can_redo());

        // Test undo
        assert!(interface.undo());
        assert_eq!(interface.modification_count(), 1);
        assert_eq!(interface.current_snapshot, 1);
        assert!(interface.can_undo());
        assert!(interface.can_redo());

        // Test undo again
        assert!(interface.undo());
        assert_eq!(interface.modification_count(), 0);
        assert_eq!(interface.current_snapshot, 0);
        assert!(!interface.can_undo());
        assert!(interface.can_redo());

        // Test redo
        assert!(interface.redo());
        assert_eq!(interface.modification_count(), 1);
        assert_eq!(interface.current_snapshot, 1);
        assert!(interface.can_undo());
        assert!(interface.can_redo());

        // Test redo again
        assert!(interface.redo());
        assert_eq!(interface.modification_count(), 2);
        assert_eq!(interface.current_snapshot, 2);
        assert!(interface.can_undo());
        assert!(!interface.can_redo());
    }

    #[test]
    fn test_branching_history_after_undo() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        // Add two modifications
        interface.add_modification(
            EditModification::CodeChange {
                line: 1,
                old: "Hello".to_string(),
                new: "World".to_string(),
            },
            "First change".to_string(),
        );
        
        interface.add_modification(
            EditModification::ConfidenceAdjustment { new_confidence: 0.8 },
            "Second change".to_string(),
        );

        assert_eq!(interface.modification_history.len(), 3);

        // Undo once, then add a new modification (should branch history)
        interface.undo();
        assert_eq!(interface.current_snapshot, 1);

        interface.add_modification(
            EditModification::ScopeExpansion {
                additional_lines: (5, 10),
            },
            "Branched change".to_string(),
        );

        // History should be truncated and new path created
        assert_eq!(interface.modification_history.len(), 3); // Initial + First + Branched
        assert_eq!(interface.current_snapshot, 2);
        assert!(!interface.can_redo()); // No redo available after branching
    }

    #[test]
    fn test_view_mode_and_interface_state() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        // Test view mode changes
        assert_eq!(interface.view_mode, ViewMode::Single);
        
        interface.set_view_mode(ViewMode::SideBySide);
        assert_eq!(interface.view_mode, ViewMode::SideBySide);

        interface.set_view_mode(ViewMode::Unified);
        assert_eq!(interface.view_mode, ViewMode::Unified);

        // Test interface state changes
        assert_eq!(interface.interface_state, InterfaceState::Editing);
        
        interface.set_state(InterfaceState::Comparing);
        assert_eq!(interface.interface_state, InterfaceState::Comparing);

        interface.set_state(InterfaceState::Previewing);
        assert_eq!(interface.interface_state, InterfaceState::Previewing);
    }

    #[test]
    fn test_syntax_highlighting_toggle() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        assert!(interface.syntax_highlighting);
        
        interface.toggle_syntax_highlighting();
        assert!(!interface.syntax_highlighting);

        interface.toggle_syntax_highlighting();
        assert!(interface.syntax_highlighting);
    }

    #[test]
    fn test_history_summary() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        let summary = interface.get_history_summary();
        assert_eq!(summary.len(), 1);
        assert!(summary[0].contains("> 0: Initial state"));

        interface.add_modification(
            EditModification::CodeChange {
                line: 1,
                old: "Hello".to_string(),
                new: "World".to_string(),
            },
            "Changed greeting".to_string(),
        );

        let summary = interface.get_history_summary();
        assert_eq!(summary.len(), 2);
        assert!(summary[0].contains("  0: Initial state"));
        assert!(summary[1].contains("> 1: Changed greeting"));
    }

    #[test]
    fn test_diff_summary_calculation() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        // Initial diff should show no changes
        let diff = interface.get_diff_summary();
        assert_eq!(diff.total_changes, 0);

        // Add a modification
        interface.add_modification(
            EditModification::CodeChange {
                line: 1,
                old: "println!(\"Hello\")".to_string(),
                new: "println!(\"Hello, World!\")".to_string(),
            },
            "Enhanced greeting".to_string(),
        );

        let diff = interface.get_diff_summary();
        assert_eq!(diff.total_changes, 1);
        // The diff calculation will depend on the actual content changes
    }

    #[test]
    fn test_current_snapshot_description() {
        let edit = create_test_edit();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        let mut interface = EditModificationInterface::new(modifiable);

        assert_eq!(interface.current_snapshot_description(), Some("Initial state"));

        interface.add_modification(
            EditModification::CodeChange {
                line: 1,
                old: "Hello".to_string(),
                new: "World".to_string(),
            },
            "Custom description".to_string(),
        );

        assert_eq!(interface.current_snapshot_description(), Some("Custom description"));

        interface.undo();
        assert_eq!(interface.current_snapshot_description(), Some("Initial state"));
    }

    // === ISSUE #19: GRANULAR APPROVAL LEVELS TESTS ===

    #[test]
    fn test_approval_level_ordering() {
        use std::cmp::Ordering;
        
        assert_eq!(ApprovalLevel::Auto.cmp(&ApprovalLevel::Low), Ordering::Less);
        assert_eq!(ApprovalLevel::Low.cmp(&ApprovalLevel::Medium), Ordering::Less);
        assert_eq!(ApprovalLevel::Medium.cmp(&ApprovalLevel::High), Ordering::Less);
        assert_eq!(ApprovalLevel::High.cmp(&ApprovalLevel::Critical), Ordering::Less);
        assert_eq!(ApprovalLevel::Critical.cmp(&ApprovalLevel::Critical), Ordering::Equal);
    }

    #[test]
    fn test_granular_approval_system_creation() {
        let system = GranularApprovalSystem::new();
        assert_eq!(system.approval_history.len(), 0);
        assert_eq!(system.escalation_queue.len(), 0);
        assert!(system.policy.risk_thresholds.lines_changed_high_risk > 0);
    }

    #[test]
    fn test_approval_level_determination() {
        let system = GranularApprovalSystem::new();
        
        // Test low confidence edit
        let mut edit = create_test_edit();
        edit.confidence = 0.5; // Below threshold
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        
        let level = system.determine_required_level(&modifiable);
        assert!(level >= ApprovalLevel::Medium); // Should escalate due to low confidence
    }

    #[test]
    fn test_security_pattern_detection() {
        let system = GranularApprovalSystem::new();
        
        let mut edit = create_test_edit();
        edit.new_code = "const password = 'secret123';".to_string();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        
        let level = system.determine_required_level(&modifiable);
        assert_eq!(level, ApprovalLevel::Critical); // Should require critical approval
    }

    #[test]
    fn test_file_pattern_matching() {
        let system = GranularApprovalSystem::new();
        
        let mut edit = create_test_edit();
        edit.file = "src/security/crypto.rs".to_string();
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        
        let level = system.determine_required_level(&modifiable);
        assert_eq!(level, ApprovalLevel::Critical); // Security files require critical approval
    }

    #[test]
    fn test_large_change_detection() {
        let system = GranularApprovalSystem::new();
        
        let mut edit = create_test_edit();
        // Create a large change (> 50 lines)
        edit.new_code = (0..60).map(|i| format!("line {}", i)).collect::<Vec<_>>().join("\n");
        let modifiable = ModifiableEdit::from_proposed_edit(edit);
        
        let level = system.determine_required_level(&modifiable);
        assert!(level >= ApprovalLevel::High); // Large changes require high approval
    }

    #[test]
    fn test_approval_record_creation() {
        use std::time::SystemTime;
        
        let approval = ApprovalRecord {
            approver_id: "test_user".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Low,
            timestamp: SystemTime::now(),
            comments: Some("Looks good".to_string()),
            delegation_chain: Vec::new(),
        };
        
        assert_eq!(approval.approver_id, "test_user");
        assert_eq!(approval.approver_role, ApprovalRole::Senior);
        assert!(approval.comments.is_some());
    }

    #[test]
    fn test_approval_level_calculation() {
        let mut system = GranularApprovalSystem::new();
        
        // Add senior approval
        let senior_approval = ApprovalRecord {
            approver_id: "senior1".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Low,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        system.add_approval(senior_approval).unwrap();
        let level = system.calculate_current_approval_level().unwrap();
        assert_eq!(level, ApprovalLevel::Low);
        
        // Add another senior approval
        let senior_approval2 = ApprovalRecord {
            approver_id: "senior2".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Medium,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        system.add_approval(senior_approval2).unwrap();
        let level = system.calculate_current_approval_level().unwrap();
        assert_eq!(level, ApprovalLevel::Medium); // Two seniors = Medium level
    }

    #[test]
    fn test_lead_approval() {
        let mut system = GranularApprovalSystem::new();
        
        let lead_approval = ApprovalRecord {
            approver_id: "lead1".to_string(),
            approver_role: ApprovalRole::Lead,
            level: ApprovalLevel::High,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        system.add_approval(lead_approval).unwrap();
        let level = system.calculate_current_approval_level().unwrap();
        assert_eq!(level, ApprovalLevel::High);
    }

    #[test]
    fn test_critical_approval_requirements() {
        let mut system = GranularApprovalSystem::new();
        
        // Add architect approval
        let architect_approval = ApprovalRecord {
            approver_id: "architect1".to_string(),
            approver_role: ApprovalRole::Architect,
            level: ApprovalLevel::Critical,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        system.add_approval(architect_approval).unwrap();
        let level = system.calculate_current_approval_level().unwrap();
        assert_eq!(level, ApprovalLevel::High); // Architect alone is not enough for Critical
        
        // Add security approval
        let security_approval = ApprovalRecord {
            approver_id: "security1".to_string(),
            approver_role: ApprovalRole::Security,
            level: ApprovalLevel::Critical,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        system.add_approval(security_approval).unwrap();
        let level = system.calculate_current_approval_level().unwrap();
        assert_eq!(level, ApprovalLevel::Critical); // Architect + Security = Critical
    }

    #[test]
    fn test_approval_sufficiency_check() {
        let mut system = GranularApprovalSystem::new();
        
        // Test insufficient approval
        assert!(!system.is_approval_sufficient(&ApprovalLevel::Medium).unwrap());
        
        // Add sufficient approvals
        let senior_approval1 = ApprovalRecord {
            approver_id: "senior1".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Medium,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        let senior_approval2 = ApprovalRecord {
            approver_id: "senior2".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Medium,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        system.add_approval(senior_approval1).unwrap();
        system.add_approval(senior_approval2).unwrap();
        
        assert!(system.is_approval_sufficient(&ApprovalLevel::Medium).unwrap());
    }

    #[test]
    fn test_approval_status_summary() {
        let system = GranularApprovalSystem::new();
        let required_level = ApprovalLevel::High;
        
        let status = system.get_approval_status(&required_level);
        assert_eq!(status.required_level, ApprovalLevel::High);
        assert_eq!(status.current_level, ApprovalLevel::Auto);
        assert!(!status.is_sufficient);
        assert_eq!(status.approval_count, 0);
        assert_eq!(status.next_required_role, Some(ApprovalRole::Lead));
    }

    #[test]
    fn test_delegation_chain_validation() {
        let mut system = GranularApprovalSystem::new();
        
        // Test valid delegation
        let valid_approval = ApprovalRecord {
            approver_id: "delegated_user".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Low,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: vec!["lead1".to_string()], // One level delegation
        };
        
        assert!(system.add_approval(valid_approval).is_ok());
        
        // Test invalid delegation (too deep)
        let invalid_approval = ApprovalRecord {
            approver_id: "delegated_user2".to_string(),
            approver_role: ApprovalRole::Junior,
            level: ApprovalLevel::Low,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: vec!["lead1".to_string(), "senior1".to_string(), "junior1".to_string()], // Too deep
        };
        
        assert!(system.add_approval(invalid_approval).is_err());
    }

    #[test]
    fn test_escalation_request() {
        let mut system = GranularApprovalSystem::new();
        
        let escalation = EscalationRequest {
            edit_id: "edit_123".to_string(),
            current_level: ApprovalLevel::Medium,
            required_level: ApprovalLevel::High,
            reason: "Complex security implications".to_string(),
            timestamp: std::time::SystemTime::now(),
            requesting_approver: "senior1".to_string(),
        };
        
        system.request_escalation(escalation);
        assert_eq!(system.escalation_queue.len(), 1);
    }

    #[test]
    fn test_modifiable_edit_granular_approval_integration() {
        let edit = create_test_edit();
        let mut modifiable = ModifiableEdit::from_proposed_edit_with_approval_level(
            edit, 
            ApprovalLevel::Medium
        );
        
        // Check initial state
        match &modifiable.approval_state {
            ApprovalState::GranularPending { required_level, current_approvals } => {
                assert_eq!(*required_level, ApprovalLevel::Medium);
                assert_eq!(current_approvals.len(), 0);
            }
            _ => panic!("Expected GranularPending state"),
        }
        
        // Add approval
        let approval = ApprovalRecord {
            approver_id: "senior1".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Medium,
            timestamp: std::time::SystemTime::now(),
            comments: Some("Approved".to_string()),
            delegation_chain: Vec::new(),
        };
        
        modifiable.add_approval_record(approval).unwrap();
        
        // Verify approval was added
        match &modifiable.approval_state {
            ApprovalState::GranularPending { current_approvals, .. } => {
                assert_eq!(current_approvals.len(), 1);
            }
            _ => panic!("Expected approval to be added"),
        }
    }

    #[test]
    fn test_approval_evaluation_workflow() {
        let edit = create_test_edit();
        let mut modifiable = ModifiableEdit::from_proposed_edit_with_approval_level(
            edit, 
            ApprovalLevel::Low
        );
        
        // Add sufficient approval
        let approval = ApprovalRecord {
            approver_id: "senior1".to_string(),
            approver_role: ApprovalRole::Senior,
            level: ApprovalLevel::Low,
            timestamp: std::time::SystemTime::now(),
            comments: None,
            delegation_chain: Vec::new(),
        };
        
        modifiable.add_approval_record(approval).unwrap();
        modifiable.evaluate_granular_approval().unwrap();
        
        // Should be approved now
        assert_eq!(modifiable.approval_state, ApprovalState::Approved);
    }

    #[test]
    fn test_pattern_matching() {
        let system = GranularApprovalSystem::new();
        
        // Test exact match
        assert!(system.matches_pattern("Cargo.toml", "Cargo.toml"));
        
        // Test wildcard patterns
        assert!(system.matches_pattern("src/security/auth.rs", "src/security/*"));
        assert!(system.matches_pattern("tests/mod.rs", "*/mod.rs"));
        assert!(!system.matches_pattern("src/main.rs", "*/mod.rs"));
    }
}

// Issue #29: File Protection Constraints - Export public types
pub use file_protection::{
    FileProtectionSystem, FileProtectionRule, FunctionConstraint, ProtectionConfig,
    ProtectionLevel, EditType, ProtectionResult
};