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
/// Issue #19: Granular Approval Levels CLI Interface
/// Enhanced multi-level approval system with role-based approval workflow

use crate::edit_control::{
    ApprovalLevel, ApprovalRecord, ApprovalRole, ApprovalState, 
    GranularApprovalSystem, ModifiableEdit
};
use crossterm::{
    cursor, execute, style, terminal,
    event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
    style::{Color, SetForegroundColor, ResetColor},
    terminal::ClearType,
};
use std::io::{self, Write};
use std::time::SystemTime;

/// Enhanced approval decision with granular levels
#[derive(Debug, Clone, PartialEq)]
pub enum GranularApprovalDecision {
    Approve(ApprovalRole),
    ApproveWithComments(ApprovalRole, String),
    RequestEscalation(String),
    Delegate(ApprovalRole, String), // Delegate to another role with reason
    ConditionalApproval(ApprovalRole, Vec<String>), // Conditions that must be met
    Reject(String),
    MoreInfo,
    Skip,
}

/// Interactive granular approval interface
pub struct GranularApprovalInterface {
    approval_system: GranularApprovalSystem,
    current_user_role: ApprovalRole,
    current_user_id: String,
    #[allow(dead_code)]
    approval_history: Vec<ApprovalRecord>,
}

impl GranularApprovalInterface {
    pub fn new(user_role: ApprovalRole, user_id: String) -> Self {
        Self {
            approval_system: GranularApprovalSystem::new(),
            current_user_role: user_role,
            current_user_id: user_id,
            approval_history: Vec::new(),
        }
    }

    /// Main entry point for granular approval workflow
    pub fn process_approval_request(
        &mut self, 
        edit: &mut ModifiableEdit
    ) -> Result<GranularApprovalDecision, Box<dyn std::error::Error>> {
        // Clear screen and initialize
        execute!(io::stdout(), terminal::Clear(ClearType::All), cursor::MoveTo(0, 0))?;
        
        // Determine required approval level
        let required_level = self.approval_system.determine_required_level(edit);
        
        // Display edit information and approval context
        self.display_edit_overview(edit, &required_level)?;
        
        // Display current approval status
        self.display_approval_status(edit, &required_level)?;
        
        // Show approval options based on user role and required level
        self.display_approval_options(&required_level)?;
        
        // Get user decision
        self.get_approval_decision(edit, &required_level)
    }

    fn display_edit_overview(
        &self, 
        edit: &ModifiableEdit, 
        required_level: &ApprovalLevel
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("╔═══════════════════════════════════════════════════════════════════════╗");
        println!("║                    🔒 GRANULAR APPROVAL REQUIRED                     ║");
        println!("╚═══════════════════════════════════════════════════════════════════════╝");
        
        // Edit details
        println!("\n📝 Edit Details:");
        println!("   File: {}", edit.base_edit.file);
        println!("   Lines: {:?}", edit.base_edit.line_range);
        println!("   Confidence: {:.1}%", edit.get_effective_confidence() * 100.0);
        println!("   File: {}", edit.base_edit.file);
        println!("   Reason: {}", edit.base_edit.reason);
        
        // Required approval level with color coding
        print!("\nđŸŽ¯ Required Approval Level: ");
        match required_level {
            ApprovalLevel::Auto => {
                execute!(io::stdout(), 
                    SetForegroundColor(Color::Green),
                    style::Print("AUTO"),
                    ResetColor
                )?;
                println!(" (Automatic approval)");
            }
            ApprovalLevel::Low => {
                execute!(io::stdout(), 
                    SetForegroundColor(Color::Blue),
                    style::Print("LOW"),
                    ResetColor
                )?;
                println!(" (Single reviewer required)");
            }
            ApprovalLevel::Medium => {
                execute!(io::stdout(), 
                    SetForegroundColor(Color::Yellow),
                    style::Print("MEDIUM"),
                    ResetColor
                )?;
                println!(" (Senior reviewer or 2 junior reviewers)");
            }
            ApprovalLevel::High => {
                execute!(io::stdout(), 
                    SetForegroundColor(Color::Magenta),
                    style::Print("HIGH"),
                    ResetColor
                )?;
                println!(" (Lead/Architect approval required)");
            }
            ApprovalLevel::Critical => {
                execute!(io::stdout(), 
                    SetForegroundColor(Color::Red),
                    style::Print("CRITICAL"),
                    ResetColor
                )?;
                println!(" (Multiple leads + security review)");
            }
        }

        // Risk assessment
        self.display_risk_assessment(edit)?;
        
        Ok(())
    }

    fn display_risk_assessment(&self, edit: &ModifiableEdit) -> Result<(), Box<dyn std::error::Error>> {
        println!("\nâš ī¸  Risk Assessment:");
        
        let lines_changed = edit.base_edit.new_code.lines().count();
        let confidence = edit.get_effective_confidence();
        
        // Lines changed assessment
        if lines_changed > self.approval_system.policy.risk_thresholds.lines_changed_high_risk {
            execute!(io::stdout(), SetForegroundColor(Color::Red))?;
            println!("   🔴 Large change: {} lines modified", lines_changed);
        } else if lines_changed > 20 {
            execute!(io::stdout(), SetForegroundColor(Color::Yellow))?;
            println!("   🟡 Medium change: {} lines modified", lines_changed);
        } else {
            execute!(io::stdout(), SetForegroundColor(Color::Green))?;
            println!("   đŸŸĸ Small change: {} lines modified", lines_changed);
        }
        execute!(io::stdout(), ResetColor)?;
        
        // Confidence assessment
        if confidence < self.approval_system.policy.risk_thresholds.confidence_threshold_escalation {
            execute!(io::stdout(), SetForegroundColor(Color::Red))?;
            println!("   🔴 Low confidence: {:.1}% (may require escalation)", confidence * 100.0);
        } else if confidence < 0.8 {
            execute!(io::stdout(), SetForegroundColor(Color::Yellow))?;
            println!("   🟡 Medium confidence: {:.1}%", confidence * 100.0);
        } else {
            execute!(io::stdout(), SetForegroundColor(Color::Green))?;
            println!("   đŸŸĸ High confidence: {:.1}%", confidence * 100.0);
        }
        execute!(io::stdout(), ResetColor)?;
        
        // Security pattern check
        let code_lower = edit.base_edit.new_code.to_lowercase();
        for pattern in &self.approval_system.policy.risk_thresholds.security_sensitive_patterns {
            if code_lower.contains(pattern) {
                execute!(io::stdout(), SetForegroundColor(Color::Red))?;
                println!("   🔴 Security-sensitive: Contains '{}'", pattern);
                execute!(io::stdout(), ResetColor)?;
                break;
            }
        }
        
        Ok(())
    }

    fn display_approval_status(
        &self, 
        edit: &ModifiableEdit, 
        required_level: &ApprovalLevel
    ) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n📊 Current Approval Status:");
        
        // Extract current approvals from edit state
        let current_approvals = match &edit.approval_state {
            ApprovalState::GranularPending { current_approvals, .. } => current_approvals,
            ApprovalState::PartiallyApproved { approvals, .. } => approvals,
            ApprovalState::EscalationRequired { approvals, .. } => approvals,
            _ => {
                println!("   âŗ No approvals yet");
                return Ok(());
            }
        };
        
        if current_approvals.is_empty() {
            println!("   âŗ No approvals yet");
            return Ok(());
        }
        
        // Create temporary system to calculate status
        let mut temp_system = GranularApprovalSystem::new();
        for approval in current_approvals {
            let _ = temp_system.add_approval(approval.clone());
        }
        
        let status = temp_system.get_approval_status(required_level);
        
        println!("   📈 Progress: {}/{} approvals", status.approval_count, 
                 self.calculate_required_approvals(required_level));
        println!("   đŸŽ¯ Current Level: {:?}", status.current_level);
        println!("   ✅ Sufficient: {}", if status.is_sufficient { "Yes" } else { "No" });
        
        if let Some(next_role) = status.next_required_role {
            println!("   👤 Next Required: {:?}", next_role);
        }
        
        // Display individual approvals
        println!("\n📋 Approval History:");
        for (i, approval) in current_approvals.iter().enumerate() {
            let _timestamp = approval.timestamp
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            println!("   {}. {:?} by {} ({}s ago)", 
                     i + 1, 
                     approval.approver_role, 
                     approval.approver_id,
                     SystemTime::now().duration_since(approval.timestamp)
                         .unwrap_or_default().as_secs());
            
            if let Some(comments) = &approval.comments {
                println!("      đŸ’Ŧ \"{comments}\"");
            }
        }
        
        Ok(())
    }

    fn display_approval_options(&self, required_level: &ApprovalLevel) -> Result<(), Box<dyn std::error::Error>> {
        println!("\nđŸŽ›ī¸  Approval Options:");
        println!("   Current User: {} ({:?})", self.current_user_id, self.current_user_role);
        
        // Check if user can approve at current level
        let can_approve = self.can_user_approve_at_level(required_level);
        
        if can_approve {
            execute!(io::stdout(), SetForegroundColor(Color::Green))?;
            println!("   [a] ✅ Approve");
            execute!(io::stdout(), ResetColor)?;
            println!("   [c] đŸ’Ŧ Approve with Comments");
        } else {
            execute!(io::stdout(), SetForegroundColor(Color::DarkGrey))?;
            println!("   [a] ❌ Approve (insufficient role)");
            execute!(io::stdout(), ResetColor)?;
        }
        
        println!("   [e] đŸ”ē Request Escalation");
        println!("   [d] đŸ‘Ĩ Delegate to Another Reviewer");
        println!("   [o] âš ī¸  Conditional Approval (with conditions)");
        println!("   [r] ❌ Reject");
        println!("   [i] â„šī¸  More Information");
        println!("   [s] â­ī¸  Skip");
        
        // Show code preview option
        println!("   [v] đŸ‘ī¸  View Code Changes");
        
        Ok(())
    }

    fn get_approval_decision(
        &mut self, 
        edit: &ModifiableEdit, 
        required_level: &ApprovalLevel
    ) -> Result<GranularApprovalDecision, Box<dyn std::error::Error>> {
        print!("\n🤔 Your decision: ");
        io::stdout().flush()?;
        
        loop {
            if let Event::Key(KeyEvent { code, modifiers: KeyModifiers::NONE, .. }) = event::read()? {
                match code {
                    KeyCode::Char('a') => {
                        if self.can_user_approve_at_level(required_level) {
                            return Ok(GranularApprovalDecision::Approve(self.current_user_role.clone()));
                        } else {
                            println!("\n❌ Insufficient role for approval at this level");
                            print!("🤔 Your decision: ");
                            io::stdout().flush()?;
                        }
                    }
                    KeyCode::Char('c') => {
                        if self.can_user_approve_at_level(required_level) {
                            let comments = self.get_approval_comments()?;
                            return Ok(GranularApprovalDecision::ApproveWithComments(
                                self.current_user_role.clone(), 
                                comments
                            ));
                        } else {
                            println!("\n❌ Insufficient role for approval at this level");
                            print!("🤔 Your decision: ");
                            io::stdout().flush()?;
                        }
                    }
                    KeyCode::Char('e') => {
                        let reason = self.get_escalation_reason()?;
                        return Ok(GranularApprovalDecision::RequestEscalation(reason));
                    }
                    KeyCode::Char('d') => {
                        let (target_role, reason) = self.get_delegation_info()?;
                        return Ok(GranularApprovalDecision::Delegate(target_role, reason));
                    }
                    KeyCode::Char('o') => {
                        let conditions = self.get_approval_conditions()?;
                        return Ok(GranularApprovalDecision::ConditionalApproval(
                            self.current_user_role.clone(), 
                            conditions
                        ));
                    }
                    KeyCode::Char('r') => {
                        let reason = self.get_rejection_reason()?;
                        return Ok(GranularApprovalDecision::Reject(reason));
                    }
                    KeyCode::Char('i') => {
                        return Ok(GranularApprovalDecision::MoreInfo);
                    }
                    KeyCode::Char('s') => {
                        return Ok(GranularApprovalDecision::Skip);
                    }
                    KeyCode::Char('v') => {
                        self.display_code_changes(edit)?;
                        println!("\nPress any key to continue...");
                        event::read()?;
                        self.display_approval_options(required_level)?;
                        print!("🤔 Your decision: ");
                        io::stdout().flush()?;
                    }
                    KeyCode::Esc => {
                        return Ok(GranularApprovalDecision::Skip);
                    }
                    _ => {
                        println!("\n❓ Invalid option. Please try again.");
                        print!("🤔 Your decision: ");
                        io::stdout().flush()?;
                    }
                }
            }
        }
    }

    fn display_code_changes(&self, edit: &ModifiableEdit) -> Result<(), Box<dyn std::error::Error>> {
        execute!(io::stdout(), terminal::Clear(ClearType::All), cursor::MoveTo(0, 0))?;
        
        println!("╔═══════════════════════════════════════════════════════════════════════╗");
        println!("║                           📄 CODE CHANGES                            ║");
        println!("╚═══════════════════════════════════════════════════════════════════════╝");
        
        println!("\n📁 File: {}", edit.base_edit.file);
        println!("📍 Lines: {:?}", edit.base_edit.line_range);
        
        println!("\n📝 Proposed Code:");
        println!("{}", "─".repeat(70));
        
        for (i, line) in edit.base_edit.new_code.lines().enumerate() {
            println!("{:3}: {}", i + 1, line);
        }
        
        println!("{}", "─".repeat(70));
        
        // Show final code if modifications exist
        if !edit.modifications.is_empty() {
            println!("\n🔄 Final Code (with modifications):");
            println!("{}", "─".repeat(70));
            
            let final_code = edit.compute_final_code();
            for (i, line) in final_code.lines().enumerate() {
                println!("{:3}: {}", i + 1, line);
            }
            
            println!("{}", "─".repeat(70));
        }
        
        Ok(())
    }

    fn get_approval_comments(&self) -> Result<String, Box<dyn std::error::Error>> {
        println!("\nđŸ’Ŧ Enter approval comments (press Enter when done):");
        print!("Comments: ");
        io::stdout().flush()?;
        
        let mut comments = String::new();
        io::stdin().read_line(&mut comments)?;
        Ok(comments.trim().to_string())
    }

    fn get_escalation_reason(&self) -> Result<String, Box<dyn std::error::Error>> {
        println!("\nđŸ”ē Enter escalation reason:");
        print!("Reason: ");
        io::stdout().flush()?;
        
        let mut reason = String::new();
        io::stdin().read_line(&mut reason)?;
        Ok(reason.trim().to_string())
    }

    fn get_delegation_info(&self) -> Result<(ApprovalRole, String), Box<dyn std::error::Error>> {
        println!("\nđŸ‘Ĩ Delegate to which role?");
        println!("   [1] Junior");
        println!("   [2] Senior");
        println!("   [3] Lead");
        println!("   [4] Architect");
        println!("   [5] Security");
        print!("Choice: ");
        io::stdout().flush()?;
        
        let mut choice = String::new();
        io::stdin().read_line(&mut choice)?;
        
        let target_role = match choice.trim() {
            "1" => ApprovalRole::Junior,
            "2" => ApprovalRole::Senior,
            "3" => ApprovalRole::Lead,
            "4" => ApprovalRole::Architect,
            "5" => ApprovalRole::Security,
            _ => return Err("Invalid role selection".into()),
        };
        
        println!("Enter delegation reason:");
        print!("Reason: ");
        io::stdout().flush()?;
        
        let mut reason = String::new();
        io::stdin().read_line(&mut reason)?;
        
        Ok((target_role, reason.trim().to_string()))
    }

    fn get_approval_conditions(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        println!("\nâš ī¸  Enter conditions for approval (one per line, empty line to finish):");
        
        let mut conditions = Vec::new();
        let mut line_num = 1;
        
        loop {
            print!("Condition {}: ", line_num);
            io::stdout().flush()?;
            
            let mut condition = String::new();
            io::stdin().read_line(&mut condition)?;
            let condition = condition.trim();
            
            if condition.is_empty() {
                break;
            }
            
            conditions.push(condition.to_string());
            line_num += 1;
        }
        
        Ok(conditions)
    }

    fn get_rejection_reason(&self) -> Result<String, Box<dyn std::error::Error>> {
        println!("\n❌ Enter rejection reason:");
        print!("Reason: ");
        io::stdout().flush()?;
        
        let mut reason = String::new();
        io::stdin().read_line(&mut reason)?;
        Ok(reason.trim().to_string())
    }

    fn can_user_approve_at_level(&self, required_level: &ApprovalLevel) -> bool {
        match required_level {
            ApprovalLevel::Auto => true, // Anyone can approve auto-level
            ApprovalLevel::Low => matches!(
                self.current_user_role,
                ApprovalRole::Senior | ApprovalRole::Lead | ApprovalRole::Architect | ApprovalRole::Security
            ),
            ApprovalLevel::Medium => matches!(
                self.current_user_role,
                ApprovalRole::Senior | ApprovalRole::Lead | ApprovalRole::Architect | ApprovalRole::Security
            ),
            ApprovalLevel::High => matches!(
                self.current_user_role,
                ApprovalRole::Lead | ApprovalRole::Architect | ApprovalRole::Security
            ),
            ApprovalLevel::Critical => matches!(
                self.current_user_role,
                ApprovalRole::Architect | ApprovalRole::Security
            ),
        }
    }

    fn calculate_required_approvals(&self, level: &ApprovalLevel) -> usize {
        match level {
            ApprovalLevel::Auto => 0,
            ApprovalLevel::Low => 1,
            ApprovalLevel::Medium => 2,
            ApprovalLevel::High => 1,
            ApprovalLevel::Critical => 2,
        }
    }

    /// Apply the approval decision to the edit
    pub fn apply_decision(
        &mut self,
        edit: &mut ModifiableEdit,
        decision: GranularApprovalDecision
    ) -> Result<(), Box<dyn std::error::Error>> {
        match decision {
            GranularApprovalDecision::Approve(role) => {
                let approval = ApprovalRecord {
                    approver_id: self.current_user_id.clone(),
                    approver_role: role,
                    level: self.approval_system.determine_required_level(edit),
                    timestamp: SystemTime::now(),
                    comments: None,
                    delegation_chain: Vec::new(),
                };
                
                edit.add_approval_record(approval)?;
                edit.evaluate_granular_approval()?;
            }
            GranularApprovalDecision::ApproveWithComments(role, comments) => {
                let approval = ApprovalRecord {
                    approver_id: self.current_user_id.clone(),
                    approver_role: role,
                    level: self.approval_system.determine_required_level(edit),
                    timestamp: SystemTime::now(),
                    comments: Some(comments),
                    delegation_chain: Vec::new(),
                };
                
                edit.add_approval_record(approval)?;
                edit.evaluate_granular_approval()?;
            }
            GranularApprovalDecision::RequestEscalation(reason) => {
                let current_level = self.approval_system.determine_required_level(edit);
                let required_level = match current_level {
                    ApprovalLevel::Auto => ApprovalLevel::Low,
                    ApprovalLevel::Low => ApprovalLevel::Medium,
                    ApprovalLevel::Medium => ApprovalLevel::High,
                    ApprovalLevel::High => ApprovalLevel::Critical,
                    ApprovalLevel::Critical => ApprovalLevel::Critical, // Already at max
                };
                
                edit.approval_state = ApprovalState::EscalationRequired {
                    current_level,
                    required_level,
                    reason,
                    approvals: Vec::new(),
                };
            }
            GranularApprovalDecision::Reject(reason) => {
                edit.approval_state = ApprovalState::Rejected;
                println!("❌ Edit rejected: {}", reason);
            }
            GranularApprovalDecision::ConditionalApproval(_role, conditions) => {
                edit.approval_state = ApprovalState::Conditional { conditions };
            }
            _ => {
                // Handle other cases (delegate, more info, skip)
                println!("â„šī¸  Decision noted: {:?}", decision);
            }
        }
        
        Ok(())
    }
}

/// Utility function to create approval record
pub fn create_approval_record(
    approver_id: String,
    role: ApprovalRole,
    level: ApprovalLevel,
    comments: Option<String>
) -> ApprovalRecord {
    ApprovalRecord {
        approver_id,
        approver_role: role,
        level,
        timestamp: SystemTime::now(),
        comments,
        delegation_chain: Vec::new(),
    }
}

/// Integration function for CLI workflow
pub fn process_edit_with_granular_approval(
    edit: &mut ModifiableEdit,
    user_role: ApprovalRole,
    user_id: String
) -> Result<(), Box<dyn std::error::Error>> {
    let mut approval_interface = GranularApprovalInterface::new(user_role, user_id);
    
    let decision = approval_interface.process_approval_request(edit)?;
    approval_interface.apply_decision(edit, decision)?;
    
    Ok(())
}