claudectl 0.29.1

Auto-pilot for Claude Code — a local model watches every session and decides what to approve
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
#![allow(dead_code)]

use std::collections::HashMap;

use super::decisions::{DecisionRecord, read_all_decisions};

// ────────────────────────────────────────────────────────────────────────────
// Risk tier classification
// ────────────────────────────────────────────────────────────────────────────

/// Risk tier for a decision, based on tool and command patterns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RiskTier {
    /// Read, Glob, Grep — no side effects
    Low,
    /// Edit, Write (non-config) — reversible changes
    Medium,
    /// Bash (non-destructive), file operations
    High,
    /// rm -rf, force push, DROP, production deploys
    Critical,
}

impl RiskTier {
    pub fn label(&self) -> &'static str {
        match self {
            RiskTier::Low => "low",
            RiskTier::Medium => "medium",
            RiskTier::High => "high",
            RiskTier::Critical => "critical",
        }
    }
}

impl std::fmt::Display for RiskTier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.label())
    }
}

/// Classify a decision into a risk tier based on tool and command.
pub fn classify_risk(tool: Option<&str>, command: Option<&str>) -> RiskTier {
    let tool = tool.unwrap_or("");
    let cmd = command.unwrap_or("").to_lowercase();

    // Critical: destructive patterns regardless of tool
    const CRITICAL_PATTERNS: &[&str] = &[
        "rm -rf",
        "rm -fr",
        "git push --force",
        "git push -f",
        "git reset --hard",
        "drop table",
        "drop database",
        "truncate table",
        "kubectl delete",
        "docker rm",
        "format c:",
        "> /dev/",
        ":(){ :|:& };:",
        "chmod -r 777",
        "chmod 777",
        "--no-verify",
    ];
    for pat in CRITICAL_PATTERNS {
        if cmd.contains(pat) {
            return RiskTier::Critical;
        }
    }

    match tool {
        // Low risk: read-only tools
        "Read" | "Glob" | "Grep" | "LS" | "Explore" => RiskTier::Low,

        // Medium risk: file modifications
        "Edit" | "Write" | "NotebookEdit" => {
            // Config files are higher risk
            if cmd.contains("config")
                || cmd.contains(".env")
                || cmd.contains("deploy")
                || cmd.contains("production")
                || cmd.contains("Dockerfile")
                || cmd.contains("ci.yml")
                || cmd.contains("ci.yaml")
            {
                RiskTier::High
            } else {
                RiskTier::Medium
            }
        }

        // Bash: depends on command
        "Bash" => {
            // High-risk bash patterns
            const HIGH_RISK_BASH: &[&str] = &[
                "git push",
                "git merge",
                "git rebase",
                "npm publish",
                "cargo publish",
                "pip install",
                "npm install -g",
                "brew install",
                "sudo ",
                "curl ",
                "wget ",
            ];
            for pat in HIGH_RISK_BASH {
                if cmd.contains(pat) {
                    return RiskTier::High;
                }
            }
            // Safe bash commands
            const SAFE_BASH: &[&str] = &[
                "cargo test",
                "cargo build",
                "cargo check",
                "cargo clippy",
                "cargo fmt",
                "npm test",
                "npm run",
                "pytest",
                "go test",
                "make test",
                "ls",
                "pwd",
                "cat ",
                "head ",
                "tail ",
                "wc ",
                "git status",
                "git log",
                "git diff",
                "git branch",
                "echo ",
            ];
            for pat in SAFE_BASH {
                if cmd.starts_with(pat) || cmd.contains(pat) {
                    return RiskTier::Low;
                }
            }
            RiskTier::Medium
        }

        // Unknown tools default to medium
        _ => RiskTier::Medium,
    }
}

// ────────────────────────────────────────────────────────────────────────────
// Rolling window computation
// ────────────────────────────────────────────────────────────────────────────

/// A point on the learning curve: decision index and rolling correction rate.
#[derive(Debug, Clone)]
pub struct CurvePoint {
    pub index: usize,
    pub correction_rate: f64,
    pub window_size: usize,
}

/// Compute rolling correction rate over decision history.
/// Returns one point per decision after the window fills.
fn rolling_correction_rate(decisions: &[DecisionRecord], window: usize) -> Vec<CurvePoint> {
    if decisions.len() < window {
        return Vec::new();
    }

    let mut points = Vec::new();
    for i in window..=decisions.len() {
        let window_slice = &decisions[i - window..i];
        let corrections = window_slice.iter().filter(|d| d.is_negative()).count();
        let rate = corrections as f64 / window as f64;
        points.push(CurvePoint {
            index: i,
            correction_rate: rate,
            window_size: window,
        });
    }
    points
}

// ────────────────────────────────────────────────────────────────────────────
// #129: Correction rate learning curve
// ────────────────────────────────────────────────────────────────────────────

/// Print the correction rate learning curve to stdout.
pub fn print_learning_curve() {
    let decisions = read_all_decisions();
    let total = decisions.len();

    println!("Brain Learning Curve");
    println!("====================");
    println!();

    if total < 10 {
        println!("  Not enough decisions yet ({total}). Need at least 10.");
        println!("  Use claudectl with --brain and accept/reject suggestions to build history.");
        return;
    }

    // Choose window size based on total decisions
    let window = if total < 50 { 10 } else { 50.min(total / 5) };

    let points = rolling_correction_rate(&decisions, window);
    if points.is_empty() {
        println!("  Not enough decisions for window size {window}.");
        return;
    }

    println!("  Total decisions: {total}");
    println!("  Window size: {window}");
    println!();

    // Print ASCII sparkline chart
    println!("  Correction rate over time (lower = brain is learning):");
    println!();

    // Sample ~20 points for the chart
    let step = (points.len() / 20).max(1);
    let sampled: Vec<&CurvePoint> = points.iter().step_by(step).collect();

    let max_rate = sampled
        .iter()
        .map(|p| p.correction_rate)
        .fold(0.0f64, f64::max)
        .max(0.01); // avoid division by zero

    for point in &sampled {
        let bar_len = ((point.correction_rate / max_rate) * 40.0) as usize;
        let bar: String = "#".repeat(bar_len);
        println!(
            "  {:>5} | {:<40} {:.0}%",
            point.index,
            bar,
            point.correction_rate * 100.0,
        );
    }

    println!();

    // Summary stats
    let first_rate = points.first().map(|p| p.correction_rate).unwrap_or(0.0);
    let last_rate = points.last().map(|p| p.correction_rate).unwrap_or(0.0);
    let delta = first_rate - last_rate;

    println!("  Early correction rate:  {:.1}%", first_rate * 100.0);
    println!("  Current correction rate: {:.1}%", last_rate * 100.0);

    if delta > 0.05 {
        println!(
            "  Improvement:            {:.1}pp (brain is learning)",
            delta * 100.0
        );
    } else if delta < -0.05 {
        println!(
            "  Regression:             {:.1}pp (accuracy declining)",
            delta.abs() * 100.0
        );
    } else {
        println!(
            "  Stable:                 {:.1}pp change",
            delta.abs() * 100.0
        );
    }

    // Detect phase transitions (significant rate changes)
    println!();
    println!("  Phase transitions:");
    let mut prev_rate = first_rate;
    for point in points.iter().skip(window) {
        let change = (point.correction_rate - prev_rate).abs();
        if change > 0.15 {
            let direction = if point.correction_rate < prev_rate {
                "improved"
            } else {
                "regressed"
            };
            println!(
                "    Decision ~{}: {direction} by {:.0}pp",
                point.index,
                change * 100.0,
            );
        }
        prev_rate = point.correction_rate;
    }
}

// ────────────────────────────────────────────────────────────────────────────
// #131: Category-specific accuracy breakdown
// ────────────────────────────────────────────────────────────────────────────

/// Per-category accuracy record.
#[derive(Debug, Clone)]
pub struct CategoryAccuracy {
    pub name: String,
    pub total: u32,
    pub correct: u32,
    pub rejected: u32,
}

impl CategoryAccuracy {
    fn accuracy_pct(&self) -> f64 {
        let decided = self.correct + self.rejected;
        if decided == 0 {
            return 0.0;
        }
        (self.correct as f64 / decided as f64) * 100.0
    }
}

/// Print category-specific accuracy breakdown.
pub fn print_accuracy() {
    let decisions = read_all_decisions();
    let total = decisions.len();

    println!("Brain Accuracy Breakdown");
    println!("========================");
    println!();

    if total < 5 {
        println!("  Not enough decisions yet ({total}). Need at least 5.");
        return;
    }

    let mut by_tool: HashMap<String, CategoryAccuracy> = HashMap::new();
    let mut by_risk: HashMap<String, CategoryAccuracy> = HashMap::new();
    let mut by_project: HashMap<String, CategoryAccuracy> = HashMap::new();

    for d in &decisions {
        let tool = d.tool.clone().unwrap_or_else(|| "unknown".into());
        let risk = classify_risk(d.tool.as_deref(), d.command.as_deref());
        let project = d.project.clone();

        let keys_and_maps: Vec<(String, &mut HashMap<String, CategoryAccuracy>)> = vec![
            (tool, &mut by_tool),
            (risk.label().to_string(), &mut by_risk),
            (project, &mut by_project),
        ];
        for (key, map) in keys_and_maps {
            let entry = map.entry(key.clone()).or_insert_with(|| CategoryAccuracy {
                name: key,
                total: 0,
                correct: 0,
                rejected: 0,
            });
            entry.total += 1;
            if d.is_positive() {
                entry.correct += 1;
            } else if d.is_negative() {
                entry.rejected += 1;
            }
        }
    }

    // Print tool breakdown
    println!("  By tool:");
    print_accuracy_table(&mut by_tool.into_values().collect());

    // Print risk tier breakdown
    println!();
    println!("  By risk tier:");
    print_accuracy_table(&mut by_risk.into_values().collect());

    // Print project breakdown (top 10)
    println!();
    println!("  By project:");
    let mut project_list: Vec<CategoryAccuracy> = by_project.into_values().collect();
    project_list.sort_by_key(|p| std::cmp::Reverse(p.total));
    project_list.truncate(10);
    print_accuracy_table(&mut project_list);

    // Print temporal breakdown
    println!();
    println!("  By phase:");
    print_temporal_accuracy(&decisions);
}

fn print_accuracy_table(entries: &mut Vec<CategoryAccuracy>) {
    entries.sort_by_key(|e| std::cmp::Reverse(e.total));

    println!(
        "    {:<20} {:>6} {:>8} {:>8} {:>8}",
        "Category", "Total", "Correct", "Rejected", "Accuracy"
    );
    println!("    {}", "-".repeat(54));

    for entry in entries {
        let decided = entry.correct + entry.rejected;
        if decided == 0 {
            println!(
                "    {:<20} {:>6} {:>8} {:>8} {:>7}",
                entry.name, entry.total, "-", "-", "n/a"
            );
        } else {
            println!(
                "    {:<20} {:>6} {:>8} {:>8} {:>7.1}%",
                entry.name,
                entry.total,
                entry.correct,
                entry.rejected,
                entry.accuracy_pct(),
            );
        }
    }
}

fn print_temporal_accuracy(decisions: &[DecisionRecord]) {
    let total = decisions.len();
    let phases: Vec<(&str, usize, usize)> = if total >= 500 {
        vec![
            ("early (0-100)", 0, 100),
            ("mid (100-500)", 100, 500),
            ("late (500+)", 500, total),
        ]
    } else if total >= 100 {
        let mid = total / 2;
        vec![("early", 0, mid), ("late", mid, total)]
    } else {
        vec![("all", 0, total)]
    };

    println!(
        "    {:<20} {:>6} {:>8} {:>8} {:>8}",
        "Phase", "Total", "Correct", "Rejected", "Accuracy"
    );
    println!("    {}", "-".repeat(54));

    for (label, start, end) in phases {
        let slice = &decisions[start..end];
        let correct = slice.iter().filter(|d| d.is_positive()).count() as u32;
        let rejected = slice.iter().filter(|d| d.is_negative()).count() as u32;
        let decided = correct + rejected;
        let accuracy = if decided > 0 {
            (correct as f64 / decided as f64) * 100.0
        } else {
            0.0
        };
        println!(
            "    {:<20} {:>6} {:>8} {:>8} {:>7.1}%",
            label,
            slice.len(),
            correct,
            rejected,
            accuracy,
        );
    }
}

// ────────────────────────────────────────────────────────────────────────────
// #136: Rules baseline comparison
// ────────────────────────────────────────────────────────────────────────────

/// A deterministic rules-only classifier for baseline comparison.
fn rules_baseline_classify(tool: Option<&str>, command: Option<&str>) -> &'static str {
    let tool = tool.unwrap_or("");
    let cmd = command.unwrap_or("").to_lowercase();

    // Always approve: read-only tools
    if matches!(tool, "Read" | "Glob" | "Grep" | "LS" | "Explore") {
        return "approve";
    }

    // Always deny: destructive patterns
    const DENY_PATTERNS: &[&str] = &[
        "rm -rf",
        "rm -fr",
        "git push --force",
        "git push -f",
        "git reset --hard",
        "drop table",
        "drop database",
        "--no-verify",
        "chmod 777",
    ];
    for pat in DENY_PATTERNS {
        if cmd.contains(pat) {
            return "deny";
        }
    }

    // Approve safe bash commands
    if tool == "Bash" {
        const SAFE_CMDS: &[&str] = &[
            "cargo test",
            "cargo build",
            "cargo check",
            "cargo clippy",
            "cargo fmt",
            "npm test",
            "npm run",
            "pytest",
            "go test",
            "make",
            "git status",
            "git log",
            "git diff",
            "git branch",
            "ls",
            "pwd",
            "echo",
            "cat ",
            "head ",
            "tail ",
        ];
        for pat in SAFE_CMDS {
            if cmd.starts_with(pat) || cmd.contains(pat) {
                return "approve";
            }
        }
    }

    // Approve file edits to test files
    if matches!(tool, "Edit" | "Write") {
        if cmd.contains("test") || cmd.contains("spec") || cmd.contains("_test.") {
            return "approve";
        }
    }

    // Default: abstain (can't decide)
    "abstain"
}

/// Print rules baseline comparison.
pub fn print_baseline() {
    let decisions = read_all_decisions();
    let total = decisions.len();

    println!("Rules Baseline Comparison");
    println!("=========================");
    println!();

    if total < 10 {
        println!("  Not enough decisions yet ({total}). Need at least 10.");
        return;
    }

    let mut brain_correct = 0u32;
    let mut brain_wrong = 0u32;
    let mut rules_correct = 0u32;
    let mut rules_wrong = 0u32;
    let mut rules_abstain = 0u32;
    let mut both_correct = 0u32;
    let mut brain_only = 0u32;
    let mut rules_only = 0u32;
    let mut both_wrong = 0u32;

    // Per-risk breakdown
    let mut risk_stats: HashMap<RiskTier, (u32, u32, u32, u32)> = HashMap::new(); // (brain_correct, brain_wrong, rules_correct, rules_wrong)

    for d in &decisions {
        // Ground truth: what the user wanted
        let user_wanted = if d.is_positive() {
            &d.brain_action // user agreed with brain
        } else if d.is_negative() {
            // user disagreed — the opposite
            if d.brain_action == "approve" {
                "deny"
            } else {
                "approve"
            }
        } else {
            continue; // no signal
        };

        let rules_said = rules_baseline_classify(d.tool.as_deref(), d.command.as_deref());
        let brain_said = d.brain_action.as_str();
        let risk = classify_risk(d.tool.as_deref(), d.command.as_deref());

        let brain_right = brain_said == user_wanted;
        let rules_right = rules_said == user_wanted;
        let rules_skipped = rules_said == "abstain";

        if brain_right {
            brain_correct += 1;
        } else {
            brain_wrong += 1;
        }

        if rules_skipped {
            rules_abstain += 1;
        } else if rules_right {
            rules_correct += 1;
        } else {
            rules_wrong += 1;
        }

        match (brain_right, rules_right || rules_skipped) {
            (true, true) if !rules_skipped => both_correct += 1,
            (true, _) => brain_only += 1,
            (false, true) if !rules_skipped => rules_only += 1,
            _ => both_wrong += 1,
        }

        // Risk breakdown
        let rs = risk_stats.entry(risk).or_insert((0, 0, 0, 0));
        if brain_right {
            rs.0 += 1;
        } else {
            rs.1 += 1;
        }
        if !rules_skipped {
            if rules_right {
                rs.2 += 1;
            } else {
                rs.3 += 1;
            }
        }
    }

    let decided = brain_correct + brain_wrong;
    let rules_decided = rules_correct + rules_wrong;

    // Overall comparison
    println!("  Overall ({decided} decisions with feedback):");
    println!();
    println!(
        "    {:<25} {:>8} {:>8} {:>8}",
        "", "Correct", "Wrong", "Accuracy"
    );
    println!("    {}", "-".repeat(49));

    if decided > 0 {
        println!(
            "    {:<25} {:>8} {:>8} {:>7.1}%",
            "Brain (LLM)",
            brain_correct,
            brain_wrong,
            (brain_correct as f64 / decided as f64) * 100.0,
        );
    }
    if rules_decided > 0 {
        println!(
            "    {:<25} {:>8} {:>8} {:>7.1}%",
            "Rules baseline",
            rules_correct,
            rules_wrong,
            (rules_correct as f64 / rules_decided as f64) * 100.0,
        );
    }
    println!(
        "    {:<25} {:>8}",
        "Rules abstained (no match)", rules_abstain,
    );

    // Venn diagram
    println!();
    println!("  Agreement:");
    println!("    Both correct:      {both_correct}");
    println!("    Brain only correct: {brain_only}");
    println!("    Rules only correct: {rules_only}");
    println!("    Both wrong:        {both_wrong}");

    // Per-risk breakdown
    println!();
    println!("  By risk tier:");
    println!(
        "    {:<12} {:>12} {:>12} {:>8}",
        "Risk", "Brain acc.", "Rules acc.", "Delta"
    );
    println!("    {}", "-".repeat(48));

    for risk in &[
        RiskTier::Low,
        RiskTier::Medium,
        RiskTier::High,
        RiskTier::Critical,
    ] {
        if let Some(&(bc, bw, rc, rw)) = risk_stats.get(risk) {
            let b_total = bc + bw;
            let r_total = rc + rw;
            let b_acc = if b_total > 0 {
                (bc as f64 / b_total as f64) * 100.0
            } else {
                0.0
            };
            let r_acc = if r_total > 0 {
                (rc as f64 / r_total as f64) * 100.0
            } else {
                0.0
            };
            let delta = b_acc - r_acc;
            let delta_str = if r_total == 0 {
                "n/a".to_string()
            } else {
                format!("{delta:+.1}pp")
            };
            println!(
                "    {:<12} {:>11.1}% {:>11.1}% {:>8}",
                risk.label(),
                b_acc,
                r_acc,
                delta_str,
            );
        }
    }
}

// ────────────────────────────────────────────────────────────────────────────
// #133: False-approve rate on risky actions
// ────────────────────────────────────────────────────────────────────────────

/// Print false-approve rate analysis for risky actions.
pub fn print_false_approve() {
    let decisions = read_all_decisions();
    let total = decisions.len();

    println!("False-Approve Rate (Risky Actions)");
    println!("===================================");
    println!();

    if total < 5 {
        println!("  Not enough decisions yet ({total}). Need at least 5.");
        return;
    }

    // Track false-approves by risk tier
    let mut tier_stats: HashMap<RiskTier, FalseApproveStats> = HashMap::new();
    let mut worst_cases: Vec<FalseApproveCase> = Vec::new();

    for d in &decisions {
        let risk = classify_risk(d.tool.as_deref(), d.command.as_deref());
        let stats = tier_stats.entry(risk).or_default();

        let brain_approved = d.brain_action == "approve";
        let user_rejected = d.is_negative();

        if brain_approved {
            stats.brain_approved += 1;
            if user_rejected {
                // False approve: brain said yes, user said no
                stats.false_approved += 1;
                if matches!(risk, RiskTier::High | RiskTier::Critical) {
                    worst_cases.push(FalseApproveCase {
                        risk,
                        tool: d.tool.clone().unwrap_or_default(),
                        command: d.command.clone().unwrap_or_default(),
                        confidence: d.brain_confidence,
                    });
                }
            }
        }

        stats.total += 1;
    }

    // Summary table
    println!(
        "  {:<12} {:>10} {:>12} {:>12} {:>12}",
        "Risk tier", "Decisions", "Approved", "False-approve", "FA rate"
    );
    println!("  {}", "-".repeat(62));

    for risk in &[
        RiskTier::Low,
        RiskTier::Medium,
        RiskTier::High,
        RiskTier::Critical,
    ] {
        let stats = tier_stats.get(risk).copied().unwrap_or_default();
        let fa_rate = if stats.brain_approved > 0 {
            (stats.false_approved as f64 / stats.brain_approved as f64) * 100.0
        } else {
            0.0
        };
        let rate_str = if stats.brain_approved == 0 {
            "n/a".to_string()
        } else {
            format!("{fa_rate:.1}%")
        };
        println!(
            "  {:<12} {:>10} {:>12} {:>12} {:>12}",
            risk.label(),
            stats.total,
            stats.brain_approved,
            stats.false_approved,
            rate_str,
        );
    }

    // Overall
    let total_approved: u32 = tier_stats.values().map(|s| s.brain_approved).sum();
    let total_false: u32 = tier_stats.values().map(|s| s.false_approved).sum();
    let overall_rate = if total_approved > 0 {
        (total_false as f64 / total_approved as f64) * 100.0
    } else {
        0.0
    };

    println!("  {}", "-".repeat(62));
    println!(
        "  {:<12} {:>10} {:>12} {:>12} {:>12}",
        "OVERALL",
        total,
        total_approved,
        total_false,
        format!("{overall_rate:.1}%"),
    );

    // High-risk focus
    let high_critical_approved: u32 = [RiskTier::High, RiskTier::Critical]
        .iter()
        .filter_map(|r| tier_stats.get(r))
        .map(|s| s.brain_approved)
        .sum();
    let high_critical_false: u32 = [RiskTier::High, RiskTier::Critical]
        .iter()
        .filter_map(|r| tier_stats.get(r))
        .map(|s| s.false_approved)
        .sum();

    println!();
    if high_critical_approved > 0 {
        let hc_rate = (high_critical_false as f64 / high_critical_approved as f64) * 100.0;
        println!(
            "  High+Critical false-approve rate: {:.1}% ({high_critical_false}/{high_critical_approved})",
            hc_rate
        );
        if hc_rate > 5.0 {
            println!("  WARNING: exceeds 5% target for high-risk actions");
        } else if hc_rate <= 1.0 {
            println!("  GOOD: within 1% target for high-risk actions");
        }
    } else {
        println!("  No high/critical risk approvals recorded yet.");
    }

    // Worst cases
    if !worst_cases.is_empty() {
        println!();
        println!("  Worst cases (high/critical risk, brain approved, user rejected):");
        for (i, case) in worst_cases.iter().take(10).enumerate() {
            let cmd_preview = if case.command.len() > 60 {
                format!("{}...", &case.command[..60])
            } else {
                case.command.clone()
            };
            println!(
                "    {}. [{}] {} \"{}\" (confidence: {:.0}%)",
                i + 1,
                case.risk,
                case.tool,
                cmd_preview,
                case.confidence * 100.0,
            );
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
struct FalseApproveStats {
    total: u32,
    brain_approved: u32,
    false_approved: u32,
}

#[derive(Debug, Clone)]
struct FalseApproveCase {
    risk: RiskTier,
    tool: String,
    command: String,
    confidence: f64,
}

// ────────────────────────────────────────────────────────────────────────────
// Dispatch
// ────────────────────────────────────────────────────────────────────────────

/// Dispatch a brain-stats subcommand.
pub fn dispatch(subcommand: &str) {
    match subcommand {
        "learning-curve" | "curve" => print_learning_curve(),
        "accuracy" | "acc" => print_accuracy(),
        "baseline" | "rules" => print_baseline(),
        "false-approve" | "fa" => print_false_approve(),
        "help" | "" => print_help(),
        _ => {
            eprintln!("Unknown brain-stats subcommand: '{subcommand}'");
            eprintln!();
            print_help();
        }
    }
}

fn print_help() {
    println!("Brain Statistics & Metrics");
    println!("==========================");
    println!();
    println!("Usage: claudectl --brain-stats <subcommand>");
    println!();
    println!("Subcommands:");
    println!("  learning-curve  Correction rate over time (is the brain learning?)");
    println!("  accuracy        Per-tool, per-risk, per-project accuracy breakdown");
    println!("  baseline        Compare brain vs. rules-only classifier");
    println!("  false-approve   False-approve rate on risky actions (safety metric)");
    println!("  help            Show this help");
    println!();
    println!("Aliases: curve, acc, rules, fa");
}

// ────────────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────────────

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

    // ── Risk classification tests ────────────────────────────────────

    #[test]
    fn classify_read_as_low() {
        assert_eq!(
            classify_risk(Some("Read"), Some("src/main.rs")),
            RiskTier::Low
        );
        assert_eq!(classify_risk(Some("Glob"), Some("**/*.rs")), RiskTier::Low);
        assert_eq!(classify_risk(Some("Grep"), Some("TODO")), RiskTier::Low);
    }

    #[test]
    fn classify_edit_as_medium() {
        assert_eq!(
            classify_risk(Some("Edit"), Some("src/lib.rs")),
            RiskTier::Medium
        );
        assert_eq!(
            classify_risk(Some("Write"), Some("tests/test.rs")),
            RiskTier::Medium
        );
    }

    #[test]
    fn classify_config_write_as_high() {
        assert_eq!(
            classify_risk(Some("Write"), Some("config.toml")),
            RiskTier::High
        );
        assert_eq!(classify_risk(Some("Edit"), Some(".env")), RiskTier::High);
    }

    #[test]
    fn classify_destructive_as_critical() {
        assert_eq!(
            classify_risk(Some("Bash"), Some("rm -rf /tmp")),
            RiskTier::Critical
        );
        assert_eq!(
            classify_risk(Some("Bash"), Some("git push --force origin main")),
            RiskTier::Critical
        );
        assert_eq!(
            classify_risk(Some("Bash"), Some("DROP TABLE users")),
            RiskTier::Critical
        );
    }

    #[test]
    fn classify_safe_bash_as_low() {
        assert_eq!(
            classify_risk(Some("Bash"), Some("cargo test --release")),
            RiskTier::Low
        );
        assert_eq!(
            classify_risk(Some("Bash"), Some("git status")),
            RiskTier::Low
        );
        assert_eq!(classify_risk(Some("Bash"), Some("ls -la")), RiskTier::Low);
    }

    #[test]
    fn classify_risky_bash_as_high() {
        assert_eq!(
            classify_risk(Some("Bash"), Some("git push origin main")),
            RiskTier::High
        );
        assert_eq!(
            classify_risk(Some("Bash"), Some("npm publish")),
            RiskTier::High
        );
    }

    #[test]
    fn classify_unknown_tool_as_medium() {
        assert_eq!(
            classify_risk(Some("CustomTool"), Some("anything")),
            RiskTier::Medium
        );
        assert_eq!(classify_risk(None, None), RiskTier::Medium);
    }

    // ── Rules baseline tests ─────────────────────────────────────────

    #[test]
    fn rules_approves_reads() {
        assert_eq!(
            rules_baseline_classify(Some("Read"), Some("file.rs")),
            "approve"
        );
        assert_eq!(
            rules_baseline_classify(Some("Glob"), Some("**/*.ts")),
            "approve"
        );
        assert_eq!(
            rules_baseline_classify(Some("Grep"), Some("TODO")),
            "approve"
        );
    }

    #[test]
    fn rules_denies_destructive() {
        assert_eq!(
            rules_baseline_classify(Some("Bash"), Some("rm -rf /tmp")),
            "deny"
        );
        assert_eq!(
            rules_baseline_classify(Some("Bash"), Some("git push --force")),
            "deny"
        );
    }

    #[test]
    fn rules_approves_safe_bash() {
        assert_eq!(
            rules_baseline_classify(Some("Bash"), Some("cargo test")),
            "approve"
        );
        assert_eq!(
            rules_baseline_classify(Some("Bash"), Some("git status")),
            "approve"
        );
    }

    #[test]
    fn rules_abstains_on_unknown() {
        assert_eq!(
            rules_baseline_classify(Some("Bash"), Some("python train.py")),
            "abstain"
        );
        assert_eq!(
            rules_baseline_classify(Some("Edit"), Some("src/main.rs")),
            "abstain"
        );
    }

    #[test]
    fn rules_approves_test_file_edits() {
        assert_eq!(
            rules_baseline_classify(Some("Write"), Some("tests/unit_test.rs")),
            "approve"
        );
    }

    // ── Rolling window tests ─────────────────────────────────────────

    #[test]
    fn rolling_window_empty() {
        assert!(rolling_correction_rate(&[], 10).is_empty());
    }

    #[test]
    fn rolling_window_too_small() {
        let decisions: Vec<DecisionRecord> = (0..5).map(|_| make_decision("accept")).collect();
        assert!(rolling_correction_rate(&decisions, 10).is_empty());
    }

    #[test]
    fn rolling_window_all_correct() {
        let decisions: Vec<DecisionRecord> = (0..20).map(|_| make_decision("accept")).collect();
        let points = rolling_correction_rate(&decisions, 10);
        assert!(!points.is_empty());
        for p in &points {
            assert!((p.correction_rate - 0.0).abs() < f64::EPSILON);
        }
    }

    #[test]
    fn rolling_window_all_rejected() {
        let decisions: Vec<DecisionRecord> = (0..20).map(|_| make_decision("reject")).collect();
        let points = rolling_correction_rate(&decisions, 10);
        for p in &points {
            assert!((p.correction_rate - 1.0).abs() < f64::EPSILON);
        }
    }

    #[test]
    fn rolling_window_decreasing() {
        // First 10 are all rejected, next 10 are all accepted
        let mut decisions: Vec<DecisionRecord> = (0..10).map(|_| make_decision("reject")).collect();
        decisions.extend((0..10).map(|_| make_decision("accept")));

        let points = rolling_correction_rate(&decisions, 10);
        let first = points.first().unwrap().correction_rate;
        let last = points.last().unwrap().correction_rate;
        assert!(
            first > last,
            "Expected decreasing curve: first={first}, last={last}"
        );
    }

    // ── Risk tier display tests ──────────────────────────────────────

    #[test]
    fn risk_tier_labels() {
        assert_eq!(RiskTier::Low.label(), "low");
        assert_eq!(RiskTier::Critical.label(), "critical");
        assert_eq!(format!("{}", RiskTier::High), "high");
    }

    // ── Helpers ──────────────────────────────────────────────────────

    fn make_decision(user_action: &str) -> DecisionRecord {
        DecisionRecord {
            timestamp: "0".into(),
            pid: 1,
            project: "test".into(),
            tool: Some("Bash".into()),
            command: Some("cargo test".into()),
            brain_action: "approve".into(),
            brain_confidence: 0.9,
            brain_reasoning: "test".into(),
            user_action: user_action.into(),
            context: None,
            outcome: None,
            decision_type: DecisionType::Session,
        }
    }

    // ── Dispatch tests ───────────────────────────────────────────────

    #[test]
    fn dispatch_help_no_panic() {
        // Just ensure it doesn't panic
        print_help();
    }
}