depyler-core 3.24.0

Core transpilation engine for the Depyler Python-to-Rust transpiler
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
//! Andon Verifier - Visual Control and Stop-the-Line Signaling
//!
//! Implements Andon (行灯) - Visual Control / Stop the Line
//! Provides immediate visibility into system state and automatic
//! escalation on failure.
//!
//! Uses Cargo-First compilation strategy (DEPYLER-CARGO-FIRST) for
//! accurate verification with proper dependency resolution.
//!
//! Reference: Baudin, M. (2007). Working with Machines

use super::isolator::ReproCase;
use super::repair::Fix;
use crate::cargo_first;

/// Result of verification
#[derive(Debug, Clone)]
pub enum VerifyResult {
    /// Fix successfully applied and verified
    Success,
    /// Fix needs human review before committing
    NeedsReview {
        fix: Fix,
        confidence: f64,
        reason: String,
    },
    /// Fix failed verification
    FixFailed(String),
    /// No fix was available to verify
    NoFixAvailable,
}

/// Andon status indicator
///
/// Visual representation of system health for the dashboard.
#[derive(Debug, Clone)]
pub enum AndonStatus {
    /// All systems operational, compilation rate on target
    Green {
        compilation_rate: f64,
        message: String,
    },
    /// Warning condition, needs attention but not blocking
    Yellow {
        warnings: Vec<String>,
        needs_attention: bool,
    },
    /// Critical issue, cycle halted
    Red { error: String, cycle_halted: bool },
    /// System idle, no active work
    Idle,
}

impl AndonStatus {
    /// Check if status indicates a problem
    pub fn is_problem(&self) -> bool {
        matches!(
            self,
            AndonStatus::Yellow {
                needs_attention: true,
                ..
            } | AndonStatus::Red { .. }
        )
    }

    /// Check if cycle should halt
    pub fn should_halt(&self) -> bool {
        matches!(
            self,
            AndonStatus::Red {
                cycle_halted: true,
                ..
            }
        )
    }

    /// Get status color as string (for CLI display)
    pub fn color(&self) -> &'static str {
        match self {
            AndonStatus::Green { .. } => "green",
            AndonStatus::Yellow { .. } => "yellow",
            AndonStatus::Red { .. } => "red",
            AndonStatus::Idle => "gray",
        }
    }

    /// Get status emoji
    pub fn emoji(&self) -> &'static str {
        match self {
            AndonStatus::Green { .. } => "🟢",
            AndonStatus::Yellow { .. } => "🟡",
            AndonStatus::Red { .. } => "🔴",
            AndonStatus::Idle => "",
        }
    }
}

impl std::fmt::Display for AndonStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AndonStatus::Green {
                compilation_rate,
                message,
            } => {
                write!(
                    f,
                    "{} GREEN ({:.1}%): {}",
                    self.emoji(),
                    compilation_rate * 100.0,
                    message
                )
            }
            AndonStatus::Yellow { warnings, .. } => {
                write!(f, "{} YELLOW: {} warning(s)", self.emoji(), warnings.len())
            }
            AndonStatus::Red { error, .. } => {
                write!(f, "{} RED: {}", self.emoji(), error)
            }
            AndonStatus::Idle => {
                write!(f, "{} IDLE", self.emoji())
            }
        }
    }
}

/// Andon Verifier: Validates fixes and provides visual status
///
/// Andon: Immediate visibility and escalation on failure.
#[derive(Debug)]
pub struct AndonVerifier {
    /// Current status
    status: AndonStatus,
    /// History of status changes
    status_history: Vec<AndonStatus>,
    /// Total fixes verified
    total_verified: u32,
    /// Successful verifications
    successful_verifications: u32,
}

impl AndonVerifier {
    /// Create a new verifier
    pub fn new() -> Self {
        Self {
            status: AndonStatus::Idle,
            status_history: Vec::new(),
            total_verified: 0,
            successful_verifications: 0,
        }
    }

    /// Get current Andon status
    pub fn status(&self) -> &AndonStatus {
        &self.status
    }

    /// Verify a fix and commit if successful
    ///
    /// Andon: Immediate visibility and escalation on failure.
    pub fn verify_and_commit(
        &mut self,
        fix: &Fix,
        _repro: &ReproCase,
    ) -> anyhow::Result<VerifyResult> {
        self.total_verified += 1;

        // Step 1: Compile the fixed output
        let compile_result = self.try_compile(&fix.rust_output);

        match compile_result {
            Ok(()) => {
                // Step 2: Run property tests (if applicable)
                if let Err(prop_failure) = self.run_property_tests(fix) {
                    self.update_status(AndonStatus::Yellow {
                        warnings: vec![format!("Property test failed: {}", prop_failure)],
                        needs_attention: true,
                    });
                    return Ok(VerifyResult::NeedsReview {
                        fix: fix.clone(),
                        confidence: fix.confidence * 0.8, // Reduce confidence
                        reason: format!("Property test failed: {}", prop_failure),
                    });
                }

                // Step 3: Check for regressions
                if let Err(regression) = self.check_regressions(fix) {
                    self.update_status(AndonStatus::Red {
                        error: regression.clone(),
                        cycle_halted: true,
                    });
                    return Ok(VerifyResult::FixFailed(regression));
                }

                // Success!
                self.successful_verifications += 1;
                let new_rate = self.calculate_compilation_rate();

                self.update_status(AndonStatus::Green {
                    compilation_rate: new_rate,
                    message: format!("Fix {} verified successfully", fix.ticket_id),
                });

                // Commit the fix (in real impl, would update config or patch code)
                self.commit_fix(fix)?;

                Ok(VerifyResult::Success)
            }
            Err(compile_error) => {
                // STOP THE LINE - fix did not work
                self.update_status(AndonStatus::Red {
                    error: compile_error.clone(),
                    cycle_halted: true,
                });
                Ok(VerifyResult::FixFailed(compile_error))
            }
        }
    }

    /// Try to compile Rust code using Cargo-First approach
    ///
    /// DEPYLER-CARGO-FIRST: Uses ephemeral Cargo workspace for accurate
    /// verification with proper dependency resolution. This eliminates
    /// false-positive "missing crate" errors that plagued bare rustc.
    fn try_compile(&self, rust_code: &str) -> Result<(), String> {
        if rust_code.is_empty() {
            return Ok(());
        }

        // Use Cargo-First compilation strategy
        cargo_first::quick_check("verification_target", rust_code, None)
    }

    /// Run property tests
    fn run_property_tests(&self, _fix: &Fix) -> Result<(), String> {
        // In real implementation:
        // 1. Generate proptest tests
        // 2. Run cargo test
        // 3. Check results

        Ok(()) // Simulate success
    }

    /// Check for regressions in existing examples
    fn check_regressions(&self, _fix: &Fix) -> Result<(), String> {
        // In real implementation:
        // 1. Re-transpile all examples
        // 2. Verify previously passing code still passes
        // 3. Report any regressions

        Ok(()) // Simulate no regressions
    }

    /// Calculate current compilation rate
    fn calculate_compilation_rate(&self) -> f64 {
        // In real implementation, would measure actual rate
        // For now, estimate based on verification success rate
        if self.total_verified == 0 {
            return 0.0;
        }
        self.successful_verifications as f64 / self.total_verified as f64
    }

    /// Commit a verified fix
    fn commit_fix(&self, fix: &Fix) -> anyhow::Result<()> {
        // In real implementation:
        // 1. Update .depyler/config.toml with new rule
        // 2. Or patch depyler-core source code
        // 3. Run git commit

        tracing::info!("Committing fix: {} - {}", fix.ticket_id, fix.description);
        Ok(())
    }

    /// Update status and record in history
    fn update_status(&mut self, new_status: AndonStatus) {
        self.status_history.push(self.status.clone());
        self.status = new_status;
    }

    /// Get status history
    pub fn history(&self) -> &[AndonStatus] {
        &self.status_history
    }

    /// Get verification statistics
    pub fn stats(&self) -> (u32, u32) {
        (self.total_verified, self.successful_verifications)
    }

    /// Signal that human review is needed
    pub fn request_human_review(&mut self, reason: &str) {
        self.update_status(AndonStatus::Yellow {
            warnings: vec![reason.to_string()],
            needs_attention: true,
        });
    }

    /// Signal critical error (stop the line)
    pub fn halt(&mut self, error: &str) {
        self.update_status(AndonStatus::Red {
            error: error.to_string(),
            cycle_halted: true,
        });
    }

    /// Reset to idle state
    pub fn reset(&mut self) {
        self.update_status(AndonStatus::Idle);
    }
}

impl Default for AndonVerifier {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn create_test_fix() -> Fix {
        Fix {
            id: "fix_test".to_string(),
            ticket_id: "DEPYLER-TEST".to_string(),
            description: "Test fix".to_string(),
            mutator_name: "TestMutator".to_string(),
            confidence: 0.9,
            rust_output: "fn test() {}".to_string(),
            patch_location: None,
        }
    }

    fn create_test_repro() -> ReproCase {
        ReproCase::new(
            "test source".to_string(),
            "E0308".to_string(),
            "test_pattern".to_string(),
        )
    }

    #[test]
    fn test_verifier_new() {
        let verifier = AndonVerifier::new();
        assert!(matches!(verifier.status(), AndonStatus::Idle));
        assert_eq!(verifier.total_verified, 0);
    }

    #[test]
    #[ignore = "Flaky under llvm-cov due to cargo timing issues"]
    fn test_verify_success() {
        let mut verifier = AndonVerifier::new();
        let fix = create_test_fix();
        let repro = create_test_repro();

        let result = verifier.verify_and_commit(&fix, &repro).unwrap();
        assert!(matches!(result, VerifyResult::Success));
        assert!(matches!(verifier.status(), AndonStatus::Green { .. }));
    }

    #[test]
    #[ignore = "Flaky under llvm-cov due to cargo timing issues"]
    fn test_verify_compile_failure() {
        let mut verifier = AndonVerifier::new();
        let mut fix = create_test_fix();
        fix.rust_output = "COMPILE_ERROR".to_string();
        let repro = create_test_repro();

        let result = verifier.verify_and_commit(&fix, &repro).unwrap();
        assert!(matches!(result, VerifyResult::FixFailed(_)));
        assert!(matches!(verifier.status(), AndonStatus::Red { .. }));
    }

    #[test]
    fn test_andon_status_display() {
        let green = AndonStatus::Green {
            compilation_rate: 0.85,
            message: "All good".to_string(),
        };
        let display = format!("{}", green);
        assert!(display.contains("GREEN"));
        assert!(display.contains("85.0%"));
    }

    #[test]
    fn test_andon_status_emoji() {
        assert_eq!(AndonStatus::Idle.emoji(), "");
        assert_eq!(
            AndonStatus::Green {
                compilation_rate: 0.0,
                message: String::new()
            }
            .emoji(),
            "🟢"
        );
        assert_eq!(
            AndonStatus::Yellow {
                warnings: vec![],
                needs_attention: false
            }
            .emoji(),
            "🟡"
        );
        assert_eq!(
            AndonStatus::Red {
                error: String::new(),
                cycle_halted: false
            }
            .emoji(),
            "🔴"
        );
    }

    #[test]
    fn test_should_halt() {
        let red_halted = AndonStatus::Red {
            error: "error".to_string(),
            cycle_halted: true,
        };
        assert!(red_halted.should_halt());

        let red_not_halted = AndonStatus::Red {
            error: "error".to_string(),
            cycle_halted: false,
        };
        assert!(!red_not_halted.should_halt());
    }

    #[test]
    fn test_status_history() {
        let mut verifier = AndonVerifier::new();
        verifier.request_human_review("Test warning");
        verifier.reset();

        assert_eq!(verifier.history().len(), 2);
    }

    #[test]
    fn test_halt() {
        let mut verifier = AndonVerifier::new();
        verifier.halt("Critical error");

        assert!(verifier.status().should_halt());
        assert!(matches!(verifier.status(), AndonStatus::Red { .. }));
    }

    // DEPYLER-COVERAGE-95: Additional tests for untested components

    #[test]
    fn test_verify_result_debug() {
        let success = VerifyResult::Success;
        assert!(format!("{:?}", success).contains("Success"));

        let no_fix = VerifyResult::NoFixAvailable;
        assert!(format!("{:?}", no_fix).contains("NoFixAvailable"));

        let failed = VerifyResult::FixFailed("error".to_string());
        assert!(format!("{:?}", failed).contains("FixFailed"));

        let needs_review = VerifyResult::NeedsReview {
            fix: create_test_fix(),
            confidence: 0.5,
            reason: "low confidence".to_string(),
        };
        assert!(format!("{:?}", needs_review).contains("NeedsReview"));
    }

    #[test]
    fn test_verify_result_clone() {
        let success = VerifyResult::Success;
        let cloned = success.clone();
        assert!(matches!(cloned, VerifyResult::Success));

        let failed = VerifyResult::FixFailed("test".to_string());
        let cloned = failed.clone();
        assert!(matches!(cloned, VerifyResult::FixFailed(_)));
    }

    #[test]
    fn test_andon_status_is_problem() {
        let green = AndonStatus::Green {
            compilation_rate: 0.9,
            message: "good".to_string(),
        };
        assert!(!green.is_problem());

        let yellow_attention = AndonStatus::Yellow {
            warnings: vec!["warn".to_string()],
            needs_attention: true,
        };
        assert!(yellow_attention.is_problem());

        let yellow_no_attention = AndonStatus::Yellow {
            warnings: vec![],
            needs_attention: false,
        };
        assert!(!yellow_no_attention.is_problem());

        let red = AndonStatus::Red {
            error: "err".to_string(),
            cycle_halted: false,
        };
        assert!(red.is_problem());

        let idle = AndonStatus::Idle;
        assert!(!idle.is_problem());
    }

    #[test]
    fn test_andon_status_color() {
        assert_eq!(
            AndonStatus::Green {
                compilation_rate: 0.0,
                message: String::new()
            }
            .color(),
            "green"
        );
        assert_eq!(
            AndonStatus::Yellow {
                warnings: vec![],
                needs_attention: false
            }
            .color(),
            "yellow"
        );
        assert_eq!(
            AndonStatus::Red {
                error: String::new(),
                cycle_halted: false
            }
            .color(),
            "red"
        );
        assert_eq!(AndonStatus::Idle.color(), "gray");
    }

    #[test]
    fn test_andon_status_display_yellow() {
        let yellow = AndonStatus::Yellow {
            warnings: vec!["warn1".to_string(), "warn2".to_string()],
            needs_attention: true,
        };
        let display = format!("{}", yellow);
        assert!(display.contains("YELLOW"));
        assert!(display.contains("2 warning(s)"));
    }

    #[test]
    fn test_andon_status_display_red() {
        let red = AndonStatus::Red {
            error: "Critical failure".to_string(),
            cycle_halted: true,
        };
        let display = format!("{}", red);
        assert!(display.contains("RED"));
        assert!(display.contains("Critical failure"));
    }

    #[test]
    fn test_andon_status_display_idle() {
        let idle = AndonStatus::Idle;
        let display = format!("{}", idle);
        assert!(display.contains("IDLE"));
    }

    #[test]
    fn test_andon_status_debug() {
        let green = AndonStatus::Green {
            compilation_rate: 0.85,
            message: "ok".to_string(),
        };
        let debug_str = format!("{:?}", green);
        assert!(debug_str.contains("Green"));
        assert!(debug_str.contains("0.85"));
    }

    #[test]
    fn test_andon_status_clone() {
        let yellow = AndonStatus::Yellow {
            warnings: vec!["w1".to_string()],
            needs_attention: true,
        };
        let cloned = yellow.clone();
        if let AndonStatus::Yellow {
            warnings,
            needs_attention,
        } = cloned
        {
            assert_eq!(warnings.len(), 1);
            assert!(needs_attention);
        } else {
            panic!("Expected Yellow variant");
        }
    }

    #[test]
    fn test_andon_verifier_default() {
        let verifier: AndonVerifier = Default::default();
        assert!(matches!(verifier.status(), AndonStatus::Idle));
        assert_eq!(verifier.stats(), (0, 0));
    }

    #[test]
    fn test_andon_verifier_debug() {
        let verifier = AndonVerifier::new();
        let debug_str = format!("{:?}", verifier);
        assert!(debug_str.contains("AndonVerifier"));
        assert!(debug_str.contains("status"));
    }

    #[test]
    fn test_andon_verifier_stats() {
        let verifier = AndonVerifier::new();
        let (total, successful) = verifier.stats();
        assert_eq!(total, 0);
        assert_eq!(successful, 0);
    }

    #[test]
    fn test_request_human_review() {
        let mut verifier = AndonVerifier::new();
        verifier.request_human_review("Need review");

        assert!(verifier.status().is_problem());
        if let AndonStatus::Yellow {
            warnings,
            needs_attention,
        } = verifier.status()
        {
            assert!(warnings.contains(&"Need review".to_string()));
            assert!(*needs_attention);
        } else {
            panic!("Expected Yellow status");
        }
    }

    #[test]
    fn test_reset_clears_status() {
        let mut verifier = AndonVerifier::new();
        verifier.halt("error");
        assert!(verifier.status().should_halt());

        verifier.reset();
        assert!(matches!(verifier.status(), AndonStatus::Idle));
    }

    #[test]
    fn test_multiple_status_changes_history() {
        let mut verifier = AndonVerifier::new();

        verifier.request_human_review("warning 1");
        verifier.halt("critical");
        verifier.reset();

        assert_eq!(verifier.history().len(), 3);
    }

    #[test]
    fn test_should_halt_false_for_non_halted_red() {
        let red = AndonStatus::Red {
            error: "error".to_string(),
            cycle_halted: false,
        };
        assert!(!red.should_halt());
    }

    #[test]
    fn test_should_halt_false_for_other_statuses() {
        assert!(!AndonStatus::Green {
            compilation_rate: 0.9,
            message: String::new()
        }
        .should_halt());
        assert!(!AndonStatus::Yellow {
            warnings: vec![],
            needs_attention: true
        }
        .should_halt());
        assert!(!AndonStatus::Idle.should_halt());
    }

    #[test]
    fn test_try_compile_empty_code() {
        let verifier = AndonVerifier::new();
        let result = verifier.try_compile("");
        assert!(result.is_ok());
    }
}