commitbee 0.6.0

AI-powered commit message generator using tree-sitter semantic analysis and local LLMs
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
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
// SPDX-FileCopyrightText: 2026 Sephyi <me@sephy.io>
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial

use std::io::IsTerminal;
use std::path::PathBuf;

use console::style;
use dialoguer::{Confirm, Editor, Input, Select};
use globset::{Glob, GlobSetBuilder};
use tokio::signal;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, warn};

use crate::cli::{Cli, Commands, HookAction};
use crate::config::Config;
use crate::domain::PromptContext;
use crate::domain::{ChangeStatus, CodeSymbol, CommitType, FileCategory, StagedChanges};
use crate::error::{Error, Result};
use crate::services::{
    analyzer::AnalyzerService,
    context::ContextBuilder,
    git::GitService,
    history::HistoryService,
    llm,
    progress::Progress,
    safety,
    sanitizer::{CommitSanitizer, CommitValidator},
    splitter::{CommitSplitter, SplitSuggestion},
    template,
};

pub struct App {
    cli: Cli,
    config: Config,
    cancel_token: CancellationToken,
}

impl App {
    pub fn new(cli: Cli) -> Result<Self> {
        let config = Config::load(&cli)?;
        debug!(
            provider = %config.provider,
            model = %config.model,
            max_diff_lines = config.max_diff_lines,
            "config loaded"
        );
        let cancel_token = CancellationToken::new();
        Ok(Self {
            cli,
            config,
            cancel_token,
        })
    }

    pub async fn run(&mut self) -> Result<()> {
        // Setup Ctrl+C handler with CancellationToken
        let cancel = self.cancel_token.clone();
        tokio::spawn(async move {
            signal::ctrl_c().await.ok();
            cancel.cancel();
        });

        // Handle subcommands
        if let Some(ref cmd) = self.cli.command {
            return self.handle_command(cmd).await;
        }

        self.generate_commit().await
    }

    async fn generate_commit(&mut self) -> Result<()> {
        if self.cancel_token.is_cancelled() {
            return Err(Error::Cancelled);
        }

        // Step 1: Discover repo and get changes
        let progress = Progress::new(self.cli.verbose);
        progress.phase("Analyzing staged changes...");

        let git = GitService::discover()?;
        let (changes, full_diff) = git
            .get_staged_changes(self.config.max_file_lines, self.config.rename_threshold)
            .await?;

        progress.info(&format!(
            "{} files with changes detected (+{} -{})",
            changes.files.len(),
            changes.stats.insertions,
            changes.stats.deletions
        ));

        // Step 1.5: Exclude files matching glob patterns
        let changes = self.apply_exclude_patterns(changes, &progress)?;

        // Step 2: Check for safety issues
        if safety::check_for_conflicts(&changes) {
            return Err(Error::MergeConflicts);
        }

        // Scan the full untruncated diff for secrets (not the per-file truncated diffs)
        let secret_patterns = safety::build_patterns(
            &self.config.custom_secret_patterns,
            &self.config.disabled_secret_patterns,
        );
        let secrets = safety::scan_full_diff_with_patterns(&full_diff, &secret_patterns);
        if !secrets.is_empty() {
            warn!(
                count = secrets.len(),
                "potential secrets detected in staged changes"
            );
            progress.warning("Potential secrets detected:");
            for s in &secrets {
                eprintln!(
                    "  {} in {} (line ~{})",
                    s.pattern_name,
                    s.file,
                    s.line.unwrap_or(0)
                );
            }

            // Cloud providers: always block when secrets detected
            if !self.cli.allow_secrets {
                return Err(Error::SecretsDetected {
                    patterns: secrets.iter().map(|s| s.pattern_name.clone()).collect(),
                });
            }

            // --allow-secrets passed: always require interactive confirmation
            if std::io::stdin().is_terminal() {
                progress.finish();
                eprintln!("\nwarning: Potential secrets detected in staged changes.");
                for s in &secrets {
                    eprintln!(
                        "  {} in {} (line ~{})",
                        s.pattern_name,
                        s.file,
                        s.line.unwrap_or(0)
                    );
                }
                eprintln!(
                    "Provider: {} ({})",
                    self.config.provider,
                    if self.config.provider == crate::config::Provider::Ollama {
                        &self.config.ollama_host
                    } else {
                        "cloud API"
                    }
                );
                eprint!("Send diff to LLM anyway? [y/N] ");
                let mut input = String::new();
                std::io::stdin().read_line(&mut input).ok();
                if !input.trim().eq_ignore_ascii_case("y") {
                    return Err(Error::SecretsDetected {
                        patterns: secrets.iter().map(|s| s.pattern_name.clone()).collect(),
                    });
                }
            } else {
                // Non-interactive: always block even with --allow-secrets
                return Err(Error::SecretsDetected {
                    patterns: secrets.iter().map(|s| s.pattern_name.clone()).collect(),
                });
            }
        }

        if self.cancel_token.is_cancelled() {
            return Err(Error::Cancelled);
        }

        // Step 3: Pre-fetch file content and analyze with tree-sitter
        progress.phase("Extracting code symbols...");

        let analyzer = AnalyzerService::new()?;

        // Fetch all file content concurrently (async I/O via tokio JoinSet)
        let file_paths: Vec<PathBuf> = changes.files.iter().map(|f| f.path.clone()).collect();
        let (staged_map, head_map) = git.fetch_file_contents(&file_paths).await;

        // Parse symbols in parallel across CPU cores (rayon)
        let (symbols, symbol_diffs) =
            analyzer.extract_symbols(&changes.files, &staged_map, &head_map);

        debug!(count = symbols.len(), "symbols extracted");

        // Finish analysis spinner before any interactive prompts
        progress.finish();

        let is_interactive = std::io::stdout().is_terminal() && std::io::stdin().is_terminal();

        // Step 3.5: Split detection
        if !self.cli.no_split && is_interactive && !self.cli.yes {
            let suggestion = CommitSplitter::analyze(&changes, &symbols);

            if let SplitSuggestion::SuggestSplit(groups) = suggestion {
                Self::display_split_suggestion(&groups, &changes);

                let split_confirm = Confirm::new()
                    .with_prompt("Split into separate commits?")
                    .default(true)
                    .interact()?;

                if split_confirm {
                    return self
                        .run_split_flow(&git, groups, &changes, &symbols, &symbol_diffs)
                        .await;
                }
                progress.info("Proceeding with single commit");
            }
        }

        // Step 3.7: History style learning (experimental)
        let history_prompt = if self.config.learn_from_history {
            debug!("learning commit style from history");
            match HistoryService::analyze(git.work_dir(), self.config.history_sample_size).await {
                Some(ctx) => {
                    let section = ctx.to_prompt_section(self.config.history_sample_size);
                    debug!(
                        conventional_ratio = ctx.conventional_ratio,
                        types = ctx.type_distribution.len(),
                        scopes = ctx.scope_patterns.len(),
                        "history analysis complete"
                    );
                    Some(section)
                }
                None => {
                    debug!("history analysis skipped (too few commits or git log failed)");
                    None
                }
            }
        } else {
            None
        };

        // Step 4: Build context
        let mut context = ContextBuilder::build(&changes, &symbols, &symbol_diffs, &self.config);
        context.history_context = history_prompt;
        debug!(prompt_chars = context.to_prompt().len(), "context built");

        let system_prompt = self.resolve_system_prompt()?;
        let prompt = self.resolve_user_prompt(&context)?;

        if self.cli.show_prompt {
            eprintln!("{}", style("--- PROMPT ---").dim());
            eprintln!("{}", prompt);
            eprintln!("{}", style("--- END PROMPT ---").dim());
            return Ok(());
        }

        if self.cancel_token.is_cancelled() {
            return Err(Error::Cancelled);
        }

        // Step 5: Generate commit message(s)
        let num_candidates = self.cli.generate;

        // Restart spinner for LLM generation phase
        let mut progress = Progress::new(self.cli.verbose);
        progress.phase(&format!(
            "Contacting {} ({})...",
            self.config.provider, self.config.model
        ));

        let provider = llm::create_provider(&self.config)?;
        debug!(provider = provider.name(), "verifying provider");
        provider.verify().await?;

        let mut candidates: Vec<String> = Vec::new();

        for i in 0..num_candidates {
            if self.cancel_token.is_cancelled() {
                return Err(Error::Cancelled);
            }

            if num_candidates > 1 {
                progress.phase(&format!(
                    "Generating candidate {}/{}...",
                    i + 1,
                    num_candidates
                ));
            } else {
                progress.phase("Generating...");
            }

            let (tx, mut rx) = mpsc::channel::<String>(64);

            // Only stream output for single generation
            let show_stream = num_candidates == 1;
            let cancel_for_printer = self.cancel_token.clone();
            let spinner = progress.take_bar();

            let print_handle = tokio::spawn(async move {
                let mut first = true;
                loop {
                    tokio::select! {
                        _ = cancel_for_printer.cancelled() => break,
                        token = rx.recv() => {
                            match token {
                                Some(t) if show_stream => {
                                    if first {
                                        if let Some(ref bar) = spinner {
                                            bar.finish_and_clear();
                                        }
                                        first = false;
                                    }
                                    eprint!("{}", t);
                                }
                                Some(_) => {} // Suppress streaming for multi-gen
                                None => break,
                            }
                        }
                    }
                }
            });

            let raw_message = provider
                .generate(&prompt, &system_prompt, tx, self.cancel_token.clone())
                .await?;

            if let Err(e) = print_handle.await {
                warn!("print task panicked: {e}");
            }

            if num_candidates == 1 {
                eprintln!(); // Newline after streaming
            }

            if raw_message.trim().is_empty() {
                warn!(candidate = i + 1, "empty response from LLM, skipping");
                continue;
            }

            debug!(
                raw_len = raw_message.len(),
                candidate = i + 1,
                "sanitizing LLM response"
            );

            // Validate against evidence and retry once if violations found
            let raw_to_sanitize = self
                .validate_and_retry(&raw_message, &context, &provider, &prompt, &system_prompt)
                .await
                .unwrap_or(raw_message);

            match CommitSanitizer::sanitize(&raw_to_sanitize, &self.config.format) {
                Ok(msg) => candidates.push(msg),
                Err(e) => {
                    warn!(candidate = i + 1, error = %e, "failed to sanitize candidate");
                }
            }
        }

        if candidates.is_empty() {
            return Err(Error::Provider {
                provider: provider.name().into(),
                message: "No valid commit messages generated".into(),
            });
        }

        // Step 6: Select message
        let mut message = if candidates.len() == 1 {
            candidates.into_iter().next().unwrap()
        } else {
            self.select_candidate(&candidates)?
        };

        // Step 6.5: Interactive Review / Edit
        if !self.cli.yes && is_interactive && !self.cli.dry_run && !self.cli.clipboard {
            loop {
                eprintln!("\n{}", style("Commit message:").bold());
                eprintln!("{}", style(&message).green());
                eprintln!();

                let options = &["Commit", "Edit", "Refine", "Cancel"];
                let selection = Select::new()
                    .with_prompt("What would you like to do?")
                    .items(options)
                    .default(0)
                    .interact()
                    .map_err(|e| Error::Dialog(e.to_string()))?;

                match selection {
                    0 => break, // Commit
                    1 => {
                        if let Some(edited) = Editor::new()
                            .edit(&message)
                            .map_err(|e| Error::Dialog(e.to_string()))?
                            && !edited.trim().is_empty()
                        {
                            message = edited;
                        }
                    }
                    2 => {
                        let feedback: String = Input::new()
                            .with_prompt("What should be improved?")
                            .interact_text()
                            .map_err(|e| Error::Dialog(e.to_string()))?;

                        if !feedback.trim().is_empty() {
                            let progress = Progress::new(self.cli.verbose);
                            progress.phase("Refining message...");

                            match self
                                .refine_message(
                                    &provider,
                                    &prompt,
                                    &system_prompt,
                                    &message,
                                    &feedback,
                                    &context,
                                )
                                .await
                            {
                                Ok(refined) => {
                                    message = refined;
                                }
                                Err(e) => {
                                    warn!(error = %e, "failed to refine message");
                                    eprintln!(
                                        "{} Failed to refine message: {}",
                                        style("error:").red(),
                                        e
                                    );
                                }
                            }
                        }
                    }
                    _ => return Err(Error::Cancelled),
                }
            }
        }

        // Step 7: Clipboard / dry-run / commit
        if self.cli.clipboard {
            Self::copy_to_clipboard(&message)?;
            eprintln!("{} Copied to clipboard!", style("").green().bold());
            println!("{}", message);
            return Ok(());
        }

        if self.cli.dry_run {
            println!("{}", message);
            return Ok(());
        }

        // Auto-commit if --yes is set
        if self.cli.yes {
            git.commit(&message).await?;
            eprintln!("{} Committed!", style("").green().bold());
            return Ok(());
        }

        if !is_interactive {
            eprintln!("{}", style("warning:").yellow().bold());
            eprintln!("  Not a terminal. Use --yes to auto-confirm in scripts/hooks.");
            println!("{}", message);
            return Ok(());
        }

        git.commit(&message).await?;

        eprintln!("{} Committed!", style("").green().bold());

        Ok(())
    }

    async fn handle_command(&self, cmd: &Commands) -> Result<()> {
        match cmd {
            Commands::Init => {
                let path = Config::create_default()?;
                println!("Created config: {}", path.display());
                Ok(())
            }
            Commands::Config => {
                println!("Provider: {}", self.config.provider);
                println!("Model: {}", self.config.model);
                println!("Ollama host: {}", self.config.ollama_host);
                println!("Max diff lines: {}", self.config.max_diff_lines);
                println!("Max file lines: {}", self.config.max_file_lines);
                println!("Max context chars: {}", self.config.max_context_chars);
                println!("Timeout: {}s", self.config.timeout_secs);
                println!("Temperature: {}", self.config.temperature);
                println!("Max tokens: {}", self.config.num_predict);
                println!("Think: {}", self.config.think);
                println!("Rename threshold: {}%", self.config.rename_threshold);
                println!(
                    "Learn from history: {} (sample: {})",
                    self.config.learn_from_history, self.config.history_sample_size
                );
                if !self.config.exclude_patterns.is_empty() {
                    println!(
                        "Exclude patterns: {}",
                        self.config.exclude_patterns.join(", ")
                    );
                }
                println!();
                println!("[format]");
                println!("  include_body: {}", self.config.format.include_body);
                println!("  include_scope: {}", self.config.format.include_scope);
                println!(
                    "  lowercase_subject: {}",
                    self.config.format.lowercase_subject
                );
                Ok(())
            }
            Commands::Doctor => self.run_doctor().await,
            Commands::Completions { shell } => {
                let mut cmd = <Cli as clap::CommandFactory>::command();
                clap_complete::generate(*shell, &mut cmd, "commitbee", &mut std::io::stdout());
                Ok(())
            }
            Commands::Hook { action } => self.handle_hook(action),
            #[cfg(feature = "secure-storage")]
            Commands::SetKey { provider } => self.set_api_key(provider),
            #[cfg(feature = "secure-storage")]
            Commands::GetKey { provider } => self.get_api_key(provider),
            #[cfg(feature = "eval")]
            Commands::Eval {
                fixtures_dir,
                filter,
            } => {
                let runner = crate::eval::EvalRunner::new(fixtures_dir.clone(), filter.clone());
                runner.run().await
            }
        }
    }

    async fn run_doctor(&self) -> Result<()> {
        eprintln!("{} Running diagnostics...\n", style("").cyan());

        // Config summary
        eprintln!("{}", style("Configuration").bold().underlined());
        eprintln!("  Provider:    {}", self.config.provider);
        eprintln!("  Model:       {}", self.config.model);
        eprintln!("  Timeout:     {}s", self.config.timeout_secs);
        if let Some(ref path) = Config::config_path() {
            let status = if path.exists() { "found" } else { "not found" };
            eprintln!("  Config file: {} ({})", path.display(), status);
        }
        eprintln!();

        // Provider connectivity
        eprintln!("{}", style("Provider Check").bold().underlined());
        match self.config.provider {
            crate::config::Provider::Ollama => {
                eprint!("  Ollama ({}): ", self.config.ollama_host);
                let provider = llm::create_provider(&self.config)?;
                match provider.verify().await {
                    Ok(()) => {
                        eprintln!("{}", style("OK").green().bold());
                        eprintln!(
                            "  Model '{}': {}",
                            self.config.model,
                            style("available").green()
                        );
                    }
                    Err(Error::OllamaNotRunning { .. }) => {
                        eprintln!("{}", style("NOT RUNNING").red().bold());
                        eprintln!("  Start with: {}", style("ollama serve").yellow());
                    }
                    Err(Error::ModelNotFound { ref available, .. }) => {
                        eprintln!("{}", style("connected").green());
                        eprintln!(
                            "  Model '{}': {}",
                            self.config.model,
                            style("NOT FOUND").red().bold()
                        );
                        eprintln!(
                            "  Pull with: {}",
                            style(format!("ollama pull {}", self.config.model)).yellow()
                        );
                        if !available.is_empty() {
                            eprintln!("  Available: {}", available.join(", "));
                        }
                    }
                    Err(e) => {
                        eprintln!("{}: {}", style("ERROR").red().bold(), e);
                    }
                }
            }
            other => {
                eprint!("  {} API key: ", other);
                if self.config.api_key.is_some() {
                    eprintln!("{}", style("configured").green());
                } else {
                    eprintln!("{}", style("MISSING").red().bold());
                }
            }
        }
        eprintln!();

        // Git check
        eprintln!("{}", style("Git Repository").bold().underlined());
        match GitService::discover() {
            Ok(_) => eprintln!("  Repository: {}", style("found").green()),
            Err(_) => eprintln!("  Repository: {}", style("NOT FOUND").red().bold()),
        }

        eprintln!();
        eprintln!("{} Diagnostics complete.", style("").green().bold());

        Ok(())
    }

    // ─── Split Detection ───

    async fn run_split_flow(
        &self,
        git: &GitService,
        groups: Vec<crate::services::splitter::CommitGroup>,
        changes: &StagedChanges,
        symbols: &[CodeSymbol],
        symbol_diffs: &[crate::domain::diff::SymbolDiff],
    ) -> Result<()> {
        // Safety: check for files with both staged and unstaged changes
        let overlap = git.has_unstaged_overlap().await?;
        if !overlap.is_empty() {
            eprintln!(
                "{} Cannot split: some staged files also have unstaged changes:",
                style("warning:").yellow().bold()
            );
            for path in &overlap {
                eprintln!("  {}", path.display());
            }
            eprintln!(
                "{} Stash or commit unstaged changes first, or use --no-split",
                style("info:").cyan()
            );
            return Err(Error::SplitAborted);
        }

        let progress = Progress::new(self.cli.verbose);
        // Generate messages for each group
        progress.phase(&format!(
            "Contacting {} ({})...",
            self.config.provider, self.config.model
        ));
        progress.finish();

        let provider = llm::create_provider(&self.config)?;
        provider.verify().await?;

        let system_prompt = self.resolve_system_prompt()?;
        let mut commit_messages: Vec<(String, Vec<PathBuf>)> = Vec::new();

        for (i, group) in groups.iter().enumerate() {
            if self.cancel_token.is_cancelled() {
                return Err(Error::Cancelled);
            }

            eprintln!(
                "{} Generating message for group {}/{}...",
                style("info:").cyan(),
                i + 1,
                groups.len(),
            );

            // Build sub-context for this group
            let sub_changes = changes.subset(&group.files);
            let sub_symbols: Vec<CodeSymbol> = symbols
                .iter()
                .filter(|s| group.files.contains(&s.file))
                .cloned()
                .collect();

            let sub_diffs: Vec<_> = symbol_diffs
                .iter()
                .filter(|d| sub_changes.files.iter().any(|f| f.path == d.file))
                .cloned()
                .collect();
            let mut context =
                ContextBuilder::build(&sub_changes, &sub_symbols, &sub_diffs, &self.config);
            context.group_rationale = Some(Self::infer_group_rationale(
                &sub_changes,
                &group.commit_type,
            ));
            let prompt = self.resolve_user_prompt(&context)?;

            if self.cli.show_prompt {
                eprintln!(
                    "{}",
                    style(format!("--- PROMPT (Group {}) ---", i + 1)).dim()
                );
                eprintln!("{}", prompt);
                eprintln!("{}", style("--- END PROMPT ---").dim());
            }

            let (tx, mut rx) = mpsc::channel::<String>(64);
            let cancel_for_printer = self.cancel_token.clone();
            let print_handle = tokio::spawn(async move {
                loop {
                    tokio::select! {
                        _ = cancel_for_printer.cancelled() => break,
                        token = rx.recv() => {
                            match token {
                                Some(_) => {}
                                None => break,
                            }
                        }
                    }
                }
            });

            let raw_message = provider
                .generate(&prompt, &system_prompt, tx, self.cancel_token.clone())
                .await?;

            if let Err(e) = print_handle.await {
                warn!("print task panicked: {e}");
            }

            if raw_message.trim().is_empty() {
                return Err(Error::Provider {
                    provider: provider.name().into(),
                    message: format!("Empty response for group {}", i + 1),
                });
            }

            debug!(
                raw_len = raw_message.len(),
                group = i + 1,
                "sanitizing split group response"
            );

            let raw_to_sanitize = self
                .validate_and_retry(&raw_message, &context, &provider, &prompt, &system_prompt)
                .await
                .unwrap_or(raw_message);

            let message = CommitSanitizer::sanitize(&raw_to_sanitize, &self.config.format)?;
            commit_messages.push((message, group.files.clone()));
        }

        // Display overview
        Self::display_split_overview(&commit_messages);

        // Dry run: stop here
        if self.cli.dry_run {
            for (msg, _) in &commit_messages {
                println!("\n{}", msg);
            }
            return Ok(());
        }

        // Confirm
        let confirm = Confirm::new()
            .with_prompt(format!("Create {} commits?", commit_messages.len()))
            .default(true)
            .interact()?;

        if !confirm {
            return Err(Error::Cancelled);
        }

        // Execute: unstage all, then stage+commit per group.
        // NOTE: This is non-atomic — if an intermediate commit fails, earlier
        // commits are already applied with no automatic rollback. The index
        // state between unstage_all() and stage_files() is also a TOCTOU window.
        for (i, (message, files)) in commit_messages.iter().enumerate() {
            git.unstage_all().await?;
            git.stage_files(files).await?;
            git.commit(message).await?;

            eprintln!(
                "{} Commit {}/{}: {}",
                style("").green().bold(),
                i + 1,
                commit_messages.len(),
                message.lines().next().unwrap_or(""),
            );
        }

        eprintln!(
            "\n{} {} commits created!",
            style("").green().bold(),
            commit_messages.len(),
        );

        Ok(())
    }

    /// Generate a short rationale describing why files were grouped together.
    fn infer_group_rationale(changes: &StagedChanges, commit_type: &CommitType) -> String {
        let file_count = changes.files.len();
        let categories: Vec<_> = changes.files.iter().map(|f| f.category).collect();

        // All same category?
        if categories.iter().all(|c| *c == categories[0]) {
            let cat = match categories[0] {
                FileCategory::Docs => "documentation",
                FileCategory::Test => "test",
                FileCategory::Config => "configuration",
                FileCategory::Build => "build/CI",
                FileCategory::Source => "source",
                FileCategory::Other => "miscellaneous",
            };
            return format!(
                "{} {} changes across {} files",
                commit_type.as_str(),
                cat,
                file_count
            );
        }

        // Mixed categories
        let source_count = categories
            .iter()
            .filter(|c| **c == FileCategory::Source)
            .count();
        let test_count = categories
            .iter()
            .filter(|c| **c == FileCategory::Test)
            .count();

        if source_count > 0 && test_count > 0 {
            format!(
                "{} changes in {} source + {} test files",
                commit_type.as_str(),
                source_count,
                test_count
            )
        } else {
            format!(
                "{} changes across {} files",
                commit_type.as_str(),
                file_count
            )
        }
    }

    fn display_split_suggestion(
        groups: &[crate::services::splitter::CommitGroup],
        changes: &StagedChanges,
    ) {
        eprintln!();
        eprintln!(
            "{} Commit split suggested — {} logical change groups detected:",
            style("").yellow(),
            groups.len(),
        );
        eprintln!();

        for (i, group) in groups.iter().enumerate() {
            let scope_str = group
                .scope
                .as_ref()
                .map(|s| format!("({})", s))
                .unwrap_or_default();
            let file_count = group.files.len();
            let files_label = if file_count == 1 { "file" } else { "files" };

            eprintln!(
                "  Group {}: {}{}  [{} {}]",
                i + 1,
                group.commit_type.as_str(),
                scope_str,
                file_count,
                files_label,
            );

            for file_path in &group.files {
                if let Some(fc) = changes.files.iter().find(|f| f.path == *file_path) {
                    let status = match fc.status {
                        ChangeStatus::Added => "[+]",
                        ChangeStatus::Modified => "[M]",
                        ChangeStatus::Deleted => "[-]",
                        ChangeStatus::Renamed => "[R]",
                    };
                    eprintln!(
                        "    {} {} (+{} -{})",
                        status,
                        file_path.display(),
                        fc.additions,
                        fc.deletions,
                    );
                }
            }
            eprintln!();
        }
    }

    fn display_split_overview(commits: &[(String, Vec<PathBuf>)]) {
        eprintln!();
        eprintln!("{}", style("→ Proposed commits:").cyan().bold());
        eprintln!();

        for (i, (message, files)) in commits.iter().enumerate() {
            let first_line = message.lines().next().unwrap_or("(empty)");
            eprintln!(
                "  Commit {}/{}: {}",
                i + 1,
                commits.len(),
                style(first_line).green(),
            );

            let files_str: Vec<String> = files.iter().map(|p| p.display().to_string()).collect();
            eprintln!("    Files: {}", files_str.join(", "));
            eprintln!();
        }
    }

    // ─── Candidate Selection ───

    fn select_candidate(&self, candidates: &[String]) -> Result<String> {
        if self.cli.yes {
            return Ok(candidates[0].clone());
        }

        let is_interactive = std::io::stdout().is_terminal() && std::io::stdin().is_terminal();

        if !is_interactive || self.cli.dry_run {
            // Non-interactive: print all candidates
            for (i, msg) in candidates.iter().enumerate() {
                eprintln!("\n{}", style(format!("--- Candidate {} ---", i + 1)).dim());
                println!("{}", msg);
            }
            return Ok(candidates[0].clone());
        }

        // Interactive: show summary of each and let user pick
        eprintln!();
        let items: Vec<String> = candidates
            .iter()
            .enumerate()
            .map(|(i, msg)| {
                let first_line = msg.lines().next().unwrap_or("(empty)");
                format!("[{}] {}", i + 1, first_line)
            })
            .collect();

        let selection = dialoguer::Select::new()
            .with_prompt("Pick a commit message")
            .items(&items)
            .default(0)
            .interact()
            .map_err(|e| Error::Dialog(e.to_string()))?;

        let chosen = &candidates[selection];
        eprintln!("\n{}", style("Selected:").bold());
        eprintln!("{}", style(chosen).green());
        eprintln!();

        Ok(chosen.clone())
    }

    // ─── Hook Commands ───

    fn handle_hook(&self, action: &HookAction) -> Result<()> {
        match action {
            HookAction::Install => self.hook_install(),
            HookAction::Uninstall => self.hook_uninstall(),
            HookAction::Status => self.hook_status(),
        }
    }

    fn hook_dir(&self) -> Result<PathBuf> {
        // Verify we're in a git repo first
        let _git = GitService::discover()?;

        let output = std::process::Command::new("git")
            .args(["rev-parse", "--git-dir"])
            .output()?;

        if !output.status.success() {
            return Err(Error::Git("Cannot find .git directory".into()));
        }

        let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();
        Ok(PathBuf::from(git_dir).join("hooks"))
    }

    fn hook_path(&self) -> Result<PathBuf> {
        Ok(self.hook_dir()?.join("prepare-commit-msg"))
    }

    fn hook_install(&self) -> Result<()> {
        let hooks_dir = self.hook_dir()?;
        let hook_path = hooks_dir.join("prepare-commit-msg");
        let backup_path = hooks_dir.join("prepare-commit-msg.commitbee-backup");

        // Create hooks directory if needed
        std::fs::create_dir_all(&hooks_dir)?;

        // Back up existing hook if present and not ours
        if hook_path.exists() {
            let content = match std::fs::read_to_string(&hook_path) {
                Ok(c) => c,
                Err(e) => {
                    warn!(path = %hook_path.display(), error = %e, "failed to read existing hook");
                    String::new()
                }
            };
            if content.contains("# commitbee hook") {
                eprintln!(
                    "{} Hook already installed at {}",
                    style("").green().bold(),
                    hook_path.display()
                );
                return Ok(());
            }
            std::fs::copy(&hook_path, &backup_path)?;
            eprintln!(
                "{} Backed up existing hook to {}",
                style("info:").cyan(),
                backup_path.display()
            );
        }

        let hook_script = r#"#!/bin/sh
# commitbee hook — auto-generated, do not edit
# Generates commit messages using commitbee when committing interactively.
# Skips merge, squash, amend, and message-provided commits.

COMMIT_MSG_FILE="$1"
COMMIT_SOURCE="$2"

# Skip non-interactive commits (merge, squash, message, amend)
case "$COMMIT_SOURCE" in
    merge|squash|message|commit)
        exit 0
        ;;
esac

# Only run if commitbee is available
if ! command -v commitbee >/dev/null 2>&1; then
    exit 0
fi

# Generate commit message and write to file
MSG=$(commitbee --yes --dry-run 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$MSG" ]; then
    printf '%s\n' "$MSG" > "$COMMIT_MSG_FILE"
fi
"#;

        // Write to temp file first, then rename (atomic)
        let temp_path = hooks_dir.join(".prepare-commit-msg.tmp");
        std::fs::write(&temp_path, hook_script)?;

        // Set executable permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&temp_path)?.permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&temp_path, perms)?;
        }

        std::fs::rename(&temp_path, &hook_path)?;

        eprintln!(
            "{} Hook installed at {}",
            style("").green().bold(),
            hook_path.display()
        );
        Ok(())
    }

    fn hook_uninstall(&self) -> Result<()> {
        let hooks_dir = self.hook_dir()?;
        let hook_path = hooks_dir.join("prepare-commit-msg");
        let backup_path = hooks_dir.join("prepare-commit-msg.commitbee-backup");

        if !hook_path.exists() {
            eprintln!(
                "{} No hook found at {}",
                style("info:").cyan(),
                hook_path.display()
            );
            return Ok(());
        }

        // Verify it's our hook before removing
        let content = match std::fs::read_to_string(&hook_path) {
            Ok(c) => c,
            Err(e) => {
                warn!(path = %hook_path.display(), error = %e, "failed to read hook file");
                String::new()
            }
        };
        if !content.contains("# commitbee hook") {
            return Err(Error::Git(format!(
                "Hook at {} was not installed by commitbee. Remove manually if intended.",
                hook_path.display()
            )));
        }

        std::fs::remove_file(&hook_path)?;

        // Restore backup if exists
        if backup_path.exists() {
            std::fs::rename(&backup_path, &hook_path)?;
            eprintln!(
                "{} Restored previous hook from backup",
                style("info:").cyan()
            );
        }

        eprintln!(
            "{} Hook removed from {}",
            style("").green().bold(),
            hook_path.display()
        );
        Ok(())
    }

    fn hook_status(&self) -> Result<()> {
        let hook_path = self.hook_path()?;

        if !hook_path.exists() {
            eprintln!(
                "{} No prepare-commit-msg hook installed",
                style("").red().bold()
            );
            eprintln!(
                "  Install with: {}",
                style("commitbee hook install").yellow()
            );
            return Ok(());
        }

        let content = match std::fs::read_to_string(&hook_path) {
            Ok(c) => c,
            Err(e) => {
                warn!(path = %hook_path.display(), error = %e, "failed to read hook file");
                String::new()
            }
        };
        if content.contains("# commitbee hook") {
            eprintln!(
                "{} CommitBee hook is installed at {}",
                style("").green().bold(),
                hook_path.display()
            );
        } else {
            eprintln!(
                "{} A prepare-commit-msg hook exists but was not installed by commitbee",
                style("info:").cyan()
            );
        }

        Ok(())
    }

    // ─── Keyring Commands ───

    #[cfg(feature = "secure-storage")]
    fn set_api_key(&self, provider: &str) -> Result<()> {
        let provider_lower = provider.to_lowercase();
        if provider_lower != "openai" && provider_lower != "anthropic" {
            return Err(Error::Config(format!(
                "Keyring storage is only for cloud providers (openai, anthropic), got '{}'",
                provider
            )));
        }

        eprintln!(
            "Enter API key for {} (input will be hidden):",
            style(&provider_lower).bold()
        );

        let key = dialoguer::Password::new()
            .with_prompt("API key")
            .interact()
            .map_err(|e| Error::Dialog(e.to_string()))?;

        if key.trim().is_empty() {
            return Err(Error::Config("API key cannot be empty".into()));
        }

        let entry = keyring::Entry::new("commitbee", &provider_lower)
            .map_err(|e| Error::Keyring(e.to_string()))?;
        entry
            .set_password(&key)
            .map_err(|e| Error::Keyring(e.to_string()))?;

        eprintln!(
            "{} API key stored for {}",
            style("").green().bold(),
            provider_lower
        );
        Ok(())
    }

    #[cfg(feature = "secure-storage")]
    fn get_api_key(&self, provider: &str) -> Result<()> {
        let provider_lower = provider.to_lowercase();
        if provider_lower != "openai" && provider_lower != "anthropic" {
            return Err(Error::Config(format!(
                "Keyring storage is only for cloud providers (openai, anthropic), got '{}'",
                provider
            )));
        }

        let entry = keyring::Entry::new("commitbee", &provider_lower)
            .map_err(|e| Error::Keyring(e.to_string()))?;

        match entry.get_password() {
            Ok(_) => {
                eprintln!(
                    "{} API key for {} is stored in keychain",
                    style("").green().bold(),
                    provider_lower
                );
            }
            Err(keyring::Error::NoEntry) => {
                eprintln!(
                    "{} No API key found for {} in keychain",
                    style("").red().bold(),
                    provider_lower
                );
                eprintln!(
                    "  Store one with: {}",
                    style(format!("commitbee set-key {}", provider_lower)).yellow()
                );
            }
            Err(e) => {
                return Err(Error::Keyring(e.to_string()));
            }
        }

        Ok(())
    }

    // ─── Post-Generation Validation ───

    /// Validate raw LLM output against evidence flags. If violations exist,
    /// re-prompt with corrections appended, up to 3 attempts. Returns the
    /// corrected raw output, or None if no retry was needed.
    async fn validate_and_retry(
        &self,
        raw: &str,
        context: &PromptContext,
        provider: &llm::LlmBackend,
        original_prompt: &str,
        system_prompt: &str,
    ) -> Option<String> {
        const MAX_RETRIES: usize = 3;

        let mut current_raw = raw.to_string();

        for attempt in 1..=MAX_RETRIES {
            let structured = match CommitSanitizer::parse_structured(&current_raw) {
                Some(s) => s,
                None => {
                    if attempt == 1 {
                        return None; // Can't parse, let sanitize() handle it
                    }
                    break; // Retry produced unparseable output, use last good one
                }
            };

            let violations = CommitValidator::validate(
                &structured,
                context.has_bug_evidence,
                context.is_mechanical,
                context.public_api_removed_count,
                context.is_dependency_only,
            );

            if violations.is_empty() {
                return if attempt == 1 {
                    None // First pass clean, use original
                } else {
                    debug!(attempt, "retry resolved all violations");
                    Some(current_raw)
                };
            }

            for v in &violations {
                debug!(attempt, violation = %v, "validation failed");
            }
            debug!(
                attempt,
                violations = violations.len(),
                "retrying with corrections"
            );

            let corrections = CommitValidator::format_corrections(&violations);
            let retry_prompt = format!("{}\n{}", original_prompt, corrections);

            let (tx, mut rx) = mpsc::channel::<String>(64);
            let cancel = self.cancel_token.clone();
            let drain_handle = tokio::spawn(async move { while rx.recv().await.is_some() {} });

            match provider
                .generate(&retry_prompt, system_prompt, tx, cancel)
                .await
            {
                Ok(retry_raw) if !retry_raw.trim().is_empty() => {
                    let _ = drain_handle.await;
                    current_raw = retry_raw;
                }
                _ => {
                    let _ = drain_handle.await;
                    warn!(attempt, "retry failed or empty, using previous output");
                    break;
                }
            }
        }

        // Exhausted retries — return best effort if we did any retries
        if current_raw != raw {
            warn!("max retries exhausted, using best-effort output");
            Some(current_raw)
        } else {
            None
        }
    }

    // ─── Prompt Helpers ───

    /// Resolve the system prompt: load from file if configured, otherwise use built-in.
    fn resolve_system_prompt(&self) -> Result<String> {
        if let Some(ref path) = self.config.system_prompt_path {
            template::load_file(path)
        } else {
            Ok(llm::SYSTEM_PROMPT.to_string())
        }
    }

    /// Resolve the user prompt: render from template if configured, otherwise use default.
    fn resolve_user_prompt(&self, context: &PromptContext) -> Result<String> {
        if let Some(ref path) = self.config.template_path {
            let symbols_text = self.build_symbols_text(context);
            let scope_text = context.suggested_scope.as_deref().unwrap_or("");

            let mut vars = std::collections::HashMap::new();
            vars.insert("diff", context.truncated_diff.as_str());
            vars.insert("symbols", symbols_text.as_str());
            vars.insert("files", context.file_breakdown.as_str());
            vars.insert("type", context.suggested_type.as_str());
            vars.insert("scope", scope_text);
            vars.insert("evidence", context.change_summary.as_str());
            vars.insert("constraints", context.public_api_removed.as_str());

            template::render_template(path, &vars)
        } else {
            Ok(context.to_prompt())
        }
    }

    /// Build combined symbol text from all symbol sections in a PromptContext.
    fn build_symbols_text(&self, context: &PromptContext) -> String {
        let mut parts = Vec::new();
        if !context.symbols_added.is_empty() {
            parts.push(format!(
                "Added:\n  {}",
                context.symbols_added.replace('\n', "\n  ")
            ));
        }
        if !context.symbols_removed.is_empty() {
            parts.push(format!(
                "Removed:\n  {}",
                context.symbols_removed.replace('\n', "\n  ")
            ));
        }
        if !context.symbols_modified.is_empty() {
            parts.push(format!(
                "Modified:\n  {}",
                context.symbols_modified.replace('\n', "\n  ")
            ));
        }
        parts.join("\n")
    }

    /// Refine a commit message based on user feedback.
    async fn refine_message(
        &self,
        provider: &llm::LlmBackend,
        original_prompt: &str,
        system_prompt: &str,
        current_message: &str,
        feedback: &str,
        context: &PromptContext,
    ) -> Result<String> {
        let refinement_prompt =
            self.resolve_refinement_prompt(original_prompt, current_message, feedback)?;

        let (tx, mut rx) = mpsc::channel::<String>(64);
        let cancel = self.cancel_token.clone();

        // Print streaming refinement
        let print_handle = tokio::spawn(async move {
            while let Some(t) = rx.recv().await {
                eprint!("{}", t);
            }
        });

        let raw_refined = provider
            .generate(&refinement_prompt, system_prompt, tx, cancel)
            .await?;

        print_handle.await.ok();
        eprintln!();

        // Validate and sanitize
        let refined_to_sanitize = self
            .validate_and_retry(
                &raw_refined,
                context,
                provider,
                &refinement_prompt,
                system_prompt,
            )
            .await
            .unwrap_or(raw_refined);

        CommitSanitizer::sanitize(&refined_to_sanitize, &self.config.format)
    }

    /// Resolve the refinement prompt.
    fn resolve_refinement_prompt(
        &self,
        original_prompt: &str,
        previous_message: &str,
        feedback: &str,
    ) -> Result<String> {
        Ok(format!(
            "{}\n\n---\nRefine the commit message based on the following user feedback:\n\"{}\"\n\nPrevious candidate was:\n\"{}\"\n\nRespond with ONLY the refined JSON object.",
            original_prompt, feedback, previous_message
        ))
    }

    // ─── Exclude Helpers ───

    /// Filter staged changes by removing files matching exclude glob patterns.
    /// Returns the filtered changes. Excluded files are listed in output.
    fn apply_exclude_patterns(
        &self,
        mut changes: StagedChanges,
        progress: &Progress,
    ) -> Result<StagedChanges> {
        if self.config.exclude_patterns.is_empty() {
            return Ok(changes);
        }

        let mut builder = GlobSetBuilder::new();
        for pattern in &self.config.exclude_patterns {
            let glob = Glob::new(pattern).map_err(|e| {
                Error::Config(format!("Invalid exclude pattern '{}': {}", pattern, e))
            })?;
            builder.add(glob);
        }
        let glob_set = builder
            .build()
            .map_err(|e| Error::Config(format!("Failed to build exclude patterns: {}", e)))?;

        let original_count = changes.files.len();
        let mut excluded: Vec<PathBuf> = Vec::new();

        changes.files.retain(|f| {
            if glob_set.is_match(&f.path) {
                excluded.push(f.path.clone());
                false
            } else {
                true
            }
        });

        if !excluded.is_empty() {
            // Recalculate stats from remaining files
            changes.stats.files_changed = changes.files.len();
            changes.stats.insertions = changes.files.iter().map(|f| f.additions).sum();
            changes.stats.deletions = changes.files.iter().map(|f| f.deletions).sum();

            progress.info(&format!(
                "Excluded {}/{} files matching patterns:",
                excluded.len(),
                original_count,
            ));
            for path in &excluded {
                debug!(path = %path.display(), "excluded by pattern");
            }
        }

        if changes.files.is_empty() {
            return Err(Error::NoStagedChanges);
        }

        Ok(changes)
    }

    // ─── Clipboard Helpers ───

    /// Copy text to the system clipboard using the arboard crate.
    fn copy_to_clipboard(text: &str) -> Result<()> {
        let mut clipboard = arboard::Clipboard::new().map_err(|e| {
            Error::Config(format!(
                "Failed to initialize clipboard: {e}. If on Linux, ensure x11 or wayland dependencies are installed."
            ))
        })?;

        clipboard
            .set_text(text)
            .map_err(|e| Error::Config(format!("Failed to copy to clipboard: {e}")))?;

        Ok(())
    }
}

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

    #[tokio::test]
    async fn test_resolve_refinement_prompt() {
        let app = App {
            cli: Cli::default(),
            config: Config::default(),
            cancel_token: CancellationToken::new(),
        };

        let original_prompt = "Original prompt";
        let previous_message = "Previous message";
        let feedback = "Make it shorter";

        let result = app
            .resolve_refinement_prompt(original_prompt, previous_message, feedback)
            .unwrap();

        assert!(result.contains("Original prompt"));
        assert!(result.contains("Previous message"));
        assert!(result.contains("Make it shorter"));
        assert!(result.contains("Respond with ONLY the refined JSON object."));
    }
}