stax 0.87.2

Fast stacked Git branches and PRs
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
1528
use crate::config::Config;
use crate::engine::{BranchMetadata, Stack};
use crate::forge::ForgeClient;
use crate::git::GitRepo;
use crate::github::pr_template::{discover_pr_templates, select_template_interactive};
use crate::remote;
use anyhow::{bail, Context, Result};
use colored::Colorize;
use dialoguer::{theme::ColorfulTheme, Confirm, Editor, Select};
use regex::Regex;
use serde::Deserialize;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};

// ---------------------------------------------------------------------------
// Known models per agent — loaded from models.json at compile time.
// To add/update models edit src/commands/models.json; no Rust changes needed.
// ---------------------------------------------------------------------------

const MODELS_JSON: &str = include_str!("models.json");

#[derive(Deserialize)]
struct ModelsFile {
    claude: Vec<ModelOption>,
    codex: Vec<ModelOption>,
    gemini: Vec<ModelOption>,
    opencode: Vec<ModelOption>,
}

fn models_file() -> &'static ModelsFile {
    static PARSED: std::sync::OnceLock<ModelsFile> = std::sync::OnceLock::new();
    PARSED.get_or_init(|| {
        serde_json::from_str(MODELS_JSON).expect("src/commands/models.json is invalid JSON")
    })
}

const SUPPORTED_AGENTS: &[&str] = &["claude", "codex", "gemini", "opencode"];

#[derive(Clone, Copy, Debug)]
enum GenerateTarget {
    PrBody,
    PrTitle,
    CommitMsg,
}

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
pub fn run(
    pr_body: bool,
    pr_title: bool,
    commit_msg: bool,
    edit: bool,
    no_prompt: bool,
    agent_flag: Option<String>,
    model_flag: Option<String>,
    template_flag: Option<String>,
    no_template: bool,
) -> Result<()> {
    let artifact_count = [pr_body, pr_title, commit_msg]
        .iter()
        .filter(|&&flag| flag)
        .count();
    if artifact_count > 1 {
        bail!("Only one of --pr-body, --pr-title, or --commit-msg may be set at a time");
    }

    let selected = if pr_body {
        Some(GenerateTarget::PrBody)
    } else if pr_title {
        Some(GenerateTarget::PrTitle)
    } else if commit_msg {
        Some(GenerateTarget::CommitMsg)
    } else {
        None
    };

    let target = if let Some(t) = selected {
        t
    } else {
        let options = [
            "PR body     — refresh the open PR's body from current diff",
            "PR title    — refresh the open PR's title from current diff",
            "Commit msg  — amend the HEAD commit message from current diff",
        ];
        let choice = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("What do you want to generate?")
            .items(options)
            .default(0)
            .interact()?;
        match choice {
            0 => GenerateTarget::PrBody,
            1 => GenerateTarget::PrTitle,
            2 => GenerateTarget::CommitMsg,
            _ => unreachable!(),
        }
    };

    match target {
        GenerateTarget::PrBody => generate_pr_body(
            edit,
            no_prompt,
            agent_flag,
            model_flag,
            template_flag,
            no_template,
        ),
        GenerateTarget::PrTitle => generate_pr_title(edit, no_prompt, agent_flag, model_flag),
        GenerateTarget::CommitMsg => generate_commit_msg(edit, no_prompt, agent_flag, model_flag),
    }
}

fn generate_pr_body(
    edit: bool,
    no_prompt: bool,
    agent_flag: Option<String>,
    model_flag: Option<String>,
    template_flag: Option<String>,
    no_template: bool,
) -> Result<()> {
    let config = Config::load()?;
    let repo = GitRepo::open()?;
    let workdir = repo.workdir()?.to_path_buf();
    let stack = Stack::load(&repo)?;
    let current_branch = repo.current_branch()?;

    // Ensure current branch is tracked
    let branch_info = stack
        .branches
        .get(&current_branch)
        .context("Current branch is not tracked by stax. Run `stax branch track` first.")?;

    let parent = branch_info
        .parent
        .as_deref()
        .context("Current branch has no parent set")?;

    // Read metadata to find existing PR
    let meta = BranchMetadata::read(repo.inner(), &current_branch)?
        .context("No metadata for current branch")?;

    let pr_number = meta
        .pr_info
        .as_ref()
        .filter(|p| p.number > 0)
        .map(|p| p.number)
        .context("No PR found for current branch. Submit first with `stax submit` or `stax ss`.")?;

    // Resolve AI agent and model (interactive if needed)
    let mut config = config;
    let agent = resolve_agent(agent_flag.as_deref(), &mut config, no_prompt)?;
    let model = resolve_model(model_flag.as_deref(), &config, &agent, "generate")?;

    // Collect context for the prompt
    println!("{}", "Collecting context...".dimmed());
    let diff_stat = get_diff_stat(&workdir, parent, &current_branch);
    let diff = get_full_diff(&workdir, parent, &current_branch);
    let commits = collect_commit_messages(&workdir, parent, &current_branch);

    // Discover and select PR template using the same logic as `submit`
    let discovered_templates = if no_template {
        Vec::new()
    } else {
        discover_pr_templates(&workdir).unwrap_or_default()
    };

    let selected_template = if no_template {
        None
    } else if let Some(ref template_name) = template_flag {
        // --template flag: find by name
        let found = discovered_templates
            .iter()
            .find(|t| t.name == *template_name)
            .cloned();
        if found.is_none() {
            eprintln!(
                "  {} Template '{}' not found, using no template",
                "!".yellow(),
                template_name
            );
        }
        found
    } else if no_prompt {
        // --no-prompt: use first template if exactly one exists
        if discovered_templates.len() == 1 {
            Some(discovered_templates[0].clone())
        } else {
            None
        }
    } else {
        // Interactive selection (handles empty list, single template, and multiple)
        select_template_interactive(&discovered_templates)?
    };

    let template_content = selected_template.as_ref().map(|t| t.content.as_str());

    if diff.trim().is_empty() && commits.is_empty() {
        bail!("No changes found between {} and {}", parent, current_branch);
    }

    // Build the AI prompt
    let prompt = build_ai_prompt(&diff_stat, &diff, &commits, template_content);

    // Invoke AI agent
    print_using_agent(&agent, model.as_deref());

    let generated_body = invoke_ai_agent(&agent, model.as_deref(), &prompt)?;

    if generated_body.trim().is_empty() {
        bail!("AI agent returned an empty response");
    }

    // Let user review/edit the generated body
    let final_body = if edit {
        Editor::new()
            .edit(&generated_body)?
            .unwrap_or(generated_body)
    } else if no_prompt {
        generated_body
    } else {
        // Show preview and confirm
        println!();
        println!("{}", "─── Generated PR Body ───".blue().bold());
        println!("{}", generated_body);
        println!("{}", "──────────────────────────".blue().bold());
        println!();

        let options = vec!["Use as-is", "Edit in $EDITOR", "Cancel"];
        let choice = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("What would you like to do?")
            .items(&options)
            .default(0)
            .interact()?;

        match choice {
            0 => generated_body,
            1 => Editor::new()
                .edit(&generated_body)?
                .unwrap_or(generated_body),
            _ => {
                println!("{}", "Cancelled.".yellow());
                return Ok(());
            }
        }
    };

    // Update the PR body on the forge
    print!("  Updating PR #{} body... ", pr_number.to_string().cyan());
    std::io::stdout().flush().ok();

    let remote_info = remote::RemoteInfo::from_repo(&repo, &config)?;
    let runtime = tokio::runtime::Runtime::new()?;
    let _enter = runtime.enter();
    let client = ForgeClient::new(&remote_info)?;

    runtime.block_on(async { client.update_pr_body(pr_number, &final_body).await })?;

    println!("{}", "done".green());
    println!(
        "  {} PR #{} body updated successfully",
        "".green().bold(),
        pr_number
    );

    Ok(())
}

fn generate_pr_title(
    edit: bool,
    no_prompt: bool,
    agent_flag: Option<String>,
    model_flag: Option<String>,
) -> Result<()> {
    let config = Config::load()?;
    let repo = GitRepo::open()?;
    let workdir = repo.workdir()?.to_path_buf();
    let stack = Stack::load(&repo)?;
    let current_branch = repo.current_branch()?;

    let branch_info = stack
        .branches
        .get(&current_branch)
        .context("Current branch is not tracked by stax. Run `stax branch track` first.")?;

    let parent = branch_info
        .parent
        .as_deref()
        .context("Current branch has no parent set")?;

    let meta = BranchMetadata::read(repo.inner(), &current_branch)?
        .context("No metadata for current branch")?;

    let pr_number = meta
        .pr_info
        .as_ref()
        .filter(|p| p.number > 0)
        .map(|p| p.number)
        .context("No PR found for current branch. Submit first with `stax submit` or `stax ss`.")?;

    let mut config = config;
    let agent = resolve_agent(agent_flag.as_deref(), &mut config, no_prompt)?;
    let model = resolve_model(model_flag.as_deref(), &config, &agent, "generate")?;

    println!("{}", "Collecting context...".dimmed());
    let diff_stat = get_diff_stat(&workdir, parent, &current_branch);
    let diff = get_full_diff(&workdir, parent, &current_branch);
    let commits = collect_commit_messages(&workdir, parent, &current_branch);

    if diff.trim().is_empty() && commits.is_empty() {
        bail!("No changes found between {} and {}", parent, current_branch);
    }

    let prompt = build_ai_title_json_prompt(&diff_stat, &diff, &commits);
    print_using_agent(&agent, model.as_deref());
    let raw = invoke_ai_agent(&agent, model.as_deref(), &prompt)?;
    let title = parse_ai_pr_title_json(&raw)?;

    let final_title = if edit {
        Editor::new().edit(&title)?.unwrap_or(title)
    } else if no_prompt {
        title
    } else {
        println!();
        println!("{}", "─── Generated PR Title ───".blue().bold());
        println!("{}", title);
        println!("{}", "───────────────────────────".blue().bold());
        println!();

        let options = vec!["Use as-is", "Edit in $EDITOR", "Cancel"];
        let choice = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("What would you like to do?")
            .items(&options)
            .default(0)
            .interact()?;

        match choice {
            0 => title,
            1 => Editor::new().edit(&title)?.unwrap_or(title),
            _ => {
                println!("{}", "Cancelled.".yellow());
                return Ok(());
            }
        }
    };

    print!("  Updating PR #{} title... ", pr_number.to_string().cyan());
    std::io::stdout().flush().ok();

    let remote_info = remote::RemoteInfo::from_repo(&repo, &config)?;
    let runtime = tokio::runtime::Runtime::new()?;
    let _enter = runtime.enter();
    let client = ForgeClient::new(&remote_info)?;

    runtime.block_on(async { client.update_pr_title(pr_number, &final_title).await })?;

    println!("{}", "done".green());
    println!(
        "  {} PR #{} title updated successfully",
        "".green().bold(),
        pr_number
    );

    Ok(())
}

fn generate_commit_msg(
    edit: bool,
    no_prompt: bool,
    agent_flag: Option<String>,
    model_flag: Option<String>,
) -> Result<()> {
    let config = Config::load()?;
    let repo = GitRepo::open()?;
    let workdir = repo.workdir()?.to_path_buf();
    let stack = Stack::load(&repo)?;
    let current_branch = repo.current_branch()?;

    stack
        .branches
        .get(&current_branch)
        .context("Current branch is not tracked by stax. Run `stax branch track` first.")?;

    let mut config = config;
    let agent = resolve_agent(agent_flag.as_deref(), &mut config, no_prompt)?;
    let model = resolve_model(model_flag.as_deref(), &config, &agent, "generate")?;

    println!("{}", "Collecting context...".dimmed());
    let current_message = get_head_full_commit_message(&workdir)?;
    let patch = get_head_commit_patch(&workdir)?;

    if current_message.trim().is_empty() && patch.trim().is_empty() {
        bail!("No HEAD commit message or patch found");
    }

    let prompt = build_commit_message_prompt(&current_message, &patch);
    print_using_agent(&agent, model.as_deref());
    let raw = invoke_ai_agent(&agent, model.as_deref(), &prompt)?;
    let message = normalize_plain_ai_message(&raw);

    if message.trim().is_empty() {
        bail!("AI agent returned an empty response");
    }

    let final_message = if edit {
        Editor::new().edit(&message)?.unwrap_or(message)
    } else if no_prompt {
        message
    } else {
        println!();
        println!("{}", "─── Generated commit message ───".blue().bold());
        println!("{}", message);
        println!("{}", "─────────────────────────────────".blue().bold());
        println!();

        let options = vec!["Use as-is", "Edit in $EDITOR", "Cancel"];
        let choice = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("What would you like to do?")
            .items(&options)
            .default(0)
            .interact()?;

        match choice {
            0 => message,
            1 => Editor::new().edit(&message)?.unwrap_or(message),
            _ => {
                println!("{}", "Cancelled.".yellow());
                return Ok(());
            }
        }
    };

    let status = Command::new("git")
        .args(["commit", "--amend", "-m", &final_message])
        .current_dir(&workdir)
        .status()
        .context("failed to spawn git commit")?;

    if !status.success() {
        bail!("git commit --amend failed");
    }

    println!("  {} HEAD commit message updated", "".green().bold());

    Ok(())
}

fn get_head_full_commit_message(workdir: &Path) -> Result<String> {
    let output = Command::new("git")
        .args(["log", "-1", "--format=%B"])
        .current_dir(workdir)
        .output()
        .context("failed to run git log")?;
    if !output.status.success() {
        bail!(
            "git log failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout)
        .trim_end()
        .to_string())
}

fn get_head_commit_patch(workdir: &Path) -> Result<String> {
    let output = Command::new("git")
        .args(["show", "--pretty=format:", "--no-color", "HEAD"])
        .current_dir(workdir)
        .output()
        .context("failed to run git show")?;
    if !output.status.success() {
        bail!(
            "git show failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

fn build_commit_message_prompt(current_message: &str, patch: &str) -> String {
    let mut prompt = String::new();
    prompt.push_str(
        "Generate a concise replacement git commit message for the commit at HEAD.\n\
        Follow conventional-commit style when it fits the change. \
        Return only the commit message text, with no markdown fences and no preamble or explanation.\n\n",
    );
    if !current_message.trim().is_empty() {
        prompt.push_str("Current commit message:\n");
        prompt.push_str(current_message.trim_end());
        prompt.push_str("\n\n");
    }
    if !patch.trim().is_empty() {
        let truncated = truncate_diff_for_title_prompt(patch);
        prompt.push_str("Patch introduced by this commit:\n```diff\n");
        prompt.push_str(&truncated);
        prompt.push_str("\n```\n\n");
    }
    prompt
}

#[derive(Deserialize)]
struct RawAiPrTitle {
    title: Option<String>,
}

fn parse_ai_pr_title_json(raw: &str) -> Result<String> {
    let json = extract_ai_json_blob(raw);
    let parsed: RawAiPrTitle =
        serde_json::from_str(&json).context("AI agent did not return JSON with a title field")?;
    parsed
        .title
        .and_then(|t| {
            let s = t.trim();
            if s.is_empty() {
                None
            } else {
                Some(s.to_string())
            }
        })
        .context("AI agent did not return a non-empty title")
}

fn extract_ai_json_blob(raw: &str) -> String {
    let trimmed = raw.trim();
    let unfenced = if trimmed.starts_with("```") {
        let without_opening = trimmed.lines().skip(1).collect::<Vec<_>>().join("\n");
        without_opening
            .trim()
            .strip_suffix("```")
            .unwrap_or(without_opening.trim())
            .trim()
            .to_string()
    } else {
        trimmed.to_string()
    };

    if unfenced.starts_with('{') && unfenced.ends_with('}') {
        return unfenced;
    }

    match (unfenced.find('{'), unfenced.rfind('}')) {
        (Some(start), Some(end)) if start < end => unfenced[start..=end].to_string(),
        _ => unfenced,
    }
}

fn build_ai_title_json_prompt(diff_stat: &str, diff: &str, commits: &[String]) -> String {
    let mut prompt = String::new();
    prompt.push_str("Generate a pull request title for the following changes.\n\n");
    prompt.push_str(
        "Return only a compact JSON object with string field \"title\". \
        Do not include markdown fences or explanatory text.\n\n",
    );
    prompt.push_str(
        "Title requirements:\n- Concise PR title, no trailing period\n\
        - Describe the user-visible change, not the implementation mechanics\n\n",
    );

    if !commits.is_empty() {
        prompt.push_str("Commit messages:\n");
        for msg in commits {
            prompt.push_str(&format!("- {}\n", msg));
        }
        prompt.push('\n');
    }

    if !diff_stat.is_empty() {
        prompt.push_str("Diff stat:\n```\n");
        prompt.push_str(diff_stat);
        prompt.push_str("\n```\n\n");
    }

    if !diff.is_empty() {
        prompt.push_str("Full diff:\n```diff\n");
        prompt.push_str(&truncate_diff_for_title_prompt(diff));
        prompt.push_str("\n```\n\n");
    }

    prompt
}

fn truncate_diff_for_title_prompt(diff: &str) -> String {
    if diff.len() <= MAX_DIFF_BYTES {
        return diff.to_string();
    }
    let safe_end = safe_utf8_cut(diff, MAX_DIFF_BYTES);
    let safe = &diff[..safe_end];
    let cut = safe.rfind('\n').unwrap_or(safe.len());
    format!(
        "{}\n\n... (diff truncated, showing first ~80KB of {} total) ...",
        &safe[..cut],
        format_bytes(diff.len())
    )
}

fn safe_utf8_cut(value: &str, max: usize) -> usize {
    let mut end = max.min(value.len());
    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }
    end
}

fn normalize_plain_ai_message(raw: &str) -> String {
    let t = raw.trim();
    if t.starts_with("```") {
        let stripped: String = t
            .lines()
            .skip(1)
            .take_while(|line| !line.trim_start().starts_with("```"))
            .collect::<Vec<_>>()
            .join("\n");
        return stripped.trim().to_string();
    }
    t.to_string()
}

// ---------------------------------------------------------------------------
// Agent resolution
// ---------------------------------------------------------------------------

fn resolve_agent(cli_flag: Option<&str>, config: &mut Config, no_prompt: bool) -> Result<String> {
    // 1. CLI flag takes priority
    if let Some(agent) = cli_flag {
        validate_agent_name(agent)?;
        return Ok(agent.to_string());
    }

    // 2. Per-feature config is set — use it (no prompt needed)
    if config.ai.generate.agent.is_some() {
        return Ok(config.ai.agent_for("generate").unwrap().to_string());
    }

    // No per-feature config yet
    if no_prompt {
        // Non-interactive path: use global silently, or auto-detect as last resort
        if let Some(agent) = config.ai.agent_for("generate") {
            return Ok(agent.to_string());
        }
        let agent = auto_detect_agent(&detect_available_agents())?;
        println!(
            "  {} {}",
            "Detected AI agent:".dimmed(),
            agent.cyan().bold()
        );
        return Ok(agent);
    }

    // First-use: prompt and persist to [ai.generate], even if a global default exists
    let (agent, _) = prompt_for_feature_ai(config, "generate")?;
    Ok(agent)
}

pub(crate) fn resolve_agent_non_interactive(
    cli_flag: Option<&str>,
    config: &Config,
    feature: &str,
) -> Result<String> {
    if let Some(agent) = cli_flag {
        validate_agent_name(agent)?;
        return Ok(agent.to_string());
    }

    if let Some(agent) = config.ai.agent_for(feature) {
        return Ok(agent.to_string());
    }

    auto_detect_agent(&detect_available_agents())
}

pub(crate) fn validate_agent_name(agent: &str) -> Result<()> {
    if !SUPPORTED_AGENTS.contains(&agent) {
        bail!(
            "Unsupported AI agent: '{}'. Supported agents: {}",
            agent,
            SUPPORTED_AGENTS.join(", ")
        );
    }
    Ok(())
}

fn detect_available_agents() -> Vec<String> {
    SUPPORTED_AGENTS
        .iter()
        .filter(|&&name| which_exists(name))
        .map(|&name| name.to_string())
        .collect()
}

fn auto_detect_agent(available: &[String]) -> Result<String> {
    available.first().cloned().context(
        "No AI agent found on PATH.\n  \
         Install one of:\n    \
         - claude (https://docs.anthropic.com)\n    \
         - codex  (https://github.com/openai/codex)\n  \
         - gemini (https://github.com/google-gemini/gemini-cli)\n  \
         - opencode (https://opencode.ai)\n  \
         Or set manually in ~/.config/stax/config.toml:\n    \
         [ai]\n    \
         agent = \"claude\"",
    )
}

fn which_exists(command: &str) -> bool {
    Command::new("which")
        .arg(command)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Model resolution
// ---------------------------------------------------------------------------

pub(crate) fn resolve_model(
    cli_flag: Option<&str>,
    config: &Config,
    agent: &str,
    feature: &str,
) -> Result<Option<String>> {
    // 1. CLI flag takes priority
    if let Some(model) = cli_flag {
        validate_model_soft(agent, model);
        return Ok(Some(model.to_string()));
    }

    // 2. Per-feature config, then global config
    if let Some(model) = config.ai.model_for(feature) {
        // If resolved model is a known model for a different agent, ignore it and
        // fall back to the selected agent default.
        if let Some(model_agent) = known_agent_for_model(model) {
            if model_agent != agent {
                eprintln!(
                    "  {} Configured model '{}' is for agent '{}', but current agent is '{}'. Using agent default.",
                    "".yellow(),
                    model.yellow(),
                    model_agent,
                    agent
                );
                return Ok(None);
            }
        }
        validate_model_soft(agent, model);
        return Ok(Some(model.to_string()));
    }

    // 3. No model specified — let agent use its own default
    Ok(None)
}

fn pick_model_interactive(agent: &str) -> Result<Option<String>> {
    let models = available_models_for(agent);
    if models.is_empty() {
        return Ok(None);
    }

    // "Default" is always item 0 — selecting it saves model=None so the agent
    // picks its own default rather than pinning a specific version.
    let mut items = vec!["Default — let the agent decide".to_string()];
    items.extend(
        models
            .iter()
            .map(|m| format!("{}{}", m.id, m.description)),
    );

    let selection = Select::with_theme(&ColorfulTheme::default())
        .with_prompt(format!("Select model for {}", agent))
        .items(&items)
        .default(0)
        .interact()?;

    if selection == 0 {
        Ok(None)
    } else {
        Ok(Some(models[selection - 1].id.clone()))
    }
}

fn validate_model_soft(agent: &str, model: &str) {
    let models = known_models_for(agent);
    if !models.is_empty()
        && !models.iter().any(|m| m.id == model)
        && !model_matches_agent_family(agent, model)
    {
        eprintln!(
            "  {} Unknown model '{}' for agent '{}', proceeding anyway...",
            "".yellow(),
            model.yellow(),
            agent
        );
    }
}

fn known_models_for(agent: &str) -> Vec<ModelOption> {
    let f = models_file();
    match agent {
        "claude" => f.claude.clone(),
        "codex" => f.codex.clone(),
        "gemini" => f.gemini.clone(),
        "opencode" => f.opencode.clone(),
        _ => vec![],
    }
}

fn known_agent_for_model(model: &str) -> Option<&'static str> {
    ["claude", "gemini", "opencode"]
        .into_iter()
        .find(|agent| known_models_for(agent).iter().any(|m| m.id == model))
        .or_else(|| {
            if model_matches_agent_family("codex", model) {
                Some("codex")
            } else {
                None
            }
        })
}

pub(crate) fn prompt_for_agent_and_model(
    config: &mut Config,
    confirm_before_save: bool,
) -> Result<(String, Option<String>)> {
    let available = detect_available_agents();

    match available.len() {
        0 => auto_detect_agent(&available).map(|agent| (agent, None)),
        1 => {
            let agent = available[0].clone();
            println!(
                "  {} {}",
                "Detected AI agent:".dimmed(),
                agent.cyan().bold()
            );
            let model = pick_model_interactive(&agent)?;
            persist_prompt_selection(config, &agent, model.clone(), confirm_before_save)?;
            Ok((agent, model))
        }
        _ => {
            let items: Vec<String> = available
                .iter()
                .enumerate()
                .map(|(i, name)| {
                    if i == 0 {
                        format!("{} (default)", name)
                    } else {
                        name.to_string()
                    }
                })
                .collect();

            let selection = Select::with_theme(&ColorfulTheme::default())
                .with_prompt("Select AI agent")
                .items(&items)
                .default(0)
                .interact()?;

            let agent = available[selection].clone();
            let model = pick_model_interactive(&agent)?;
            persist_prompt_selection(config, &agent, model.clone(), confirm_before_save)?;
            Ok((agent, model))
        }
    }
}

fn persist_prompt_selection(
    config: &mut Config,
    agent: &str,
    model: Option<String>,
    confirm_before_save: bool,
) -> Result<()> {
    let should_save = if confirm_before_save {
        Confirm::with_theme(&ColorfulTheme::default())
            .with_prompt("Save choices to config?")
            .default(true)
            .interact()?
    } else {
        true
    };

    if should_save {
        config.ai.agent = Some(agent.to_string());
        config.ai.model = model.clone();
        config.save()?;
        let model_display = model.as_deref().unwrap_or("agent default");
        println!(
            "  {} Saved ai.agent = \"{}\", ai.model = \"{}\"",
            "".green().bold(),
            agent,
            model_display
        );
    }

    Ok(())
}

/// Interactively pick agent+model for a specific feature and persist to `[ai.<feature>]`.
/// Falls back to persisting to global `[ai]` when `feature` is "global" or unknown.
pub(crate) fn prompt_for_feature_ai(
    config: &mut Config,
    feature: &str,
) -> Result<(String, Option<String>)> {
    let available = detect_available_agents();

    let agent = match available.len() {
        0 => auto_detect_agent(&available)?,
        1 => {
            let agent = available[0].clone();
            println!(
                "  {} {}",
                "Detected AI agent:".dimmed(),
                agent.cyan().bold()
            );
            agent
        }
        _ => {
            let items: Vec<String> = available
                .iter()
                .enumerate()
                .map(|(i, name)| {
                    if i == 0 {
                        format!("{} (default)", name)
                    } else {
                        name.to_string()
                    }
                })
                .collect();

            let selection = Select::with_theme(&ColorfulTheme::default())
                .with_prompt(format!("Select AI agent for {}", feature))
                .items(&items)
                .default(0)
                .interact()?;

            available[selection].clone()
        }
    };

    let model = pick_model_interactive(&agent)?;

    // Persist to feature-specific config, or global if feature is "global"/unknown.
    if let Some(feat_cfg) = config.ai.feature_config_mut(feature) {
        feat_cfg.agent = Some(agent.clone());
        feat_cfg.model = model.clone();
        config.save()?;
        let model_display = model.as_deref().unwrap_or("agent default");
        println!(
            "  {} Saved [ai.{}] agent = \"{}\", model = \"{}\"",
            "".green().bold(),
            feature,
            agent,
            model_display
        );
    } else {
        // "global" or unknown feature — write to top-level [ai]
        config.ai.agent = Some(agent.clone());
        config.ai.model = model.clone();
        config.save()?;
        let model_display = model.as_deref().unwrap_or("agent default");
        println!(
            "  {} Saved ai.agent = \"{}\", ai.model = \"{}\"",
            "".green().bold(),
            agent,
            model_display
        );
    }

    Ok((agent, model))
}

/// Print a consistent "Using <agent> [with model <model>]" line before an AI call.
/// Uses stderr so it doesn't pollute captured stdout (e.g. `--json` flows).
pub(crate) fn print_using_agent(agent: &str, model: Option<&str>) {
    match model {
        Some(m) => eprintln!(
            "  {} {}",
            format!("Using {} with model", agent).dimmed(),
            m.cyan()
        ),
        None => eprintln!("  {}", format!("Using {}", agent).dimmed()),
    }
}

#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
struct ModelOption {
    id: String,
    description: String,
}

fn available_models_for(agent: &str) -> Vec<ModelOption> {
    if agent == "codex" {
        if let Ok(models) = fetch_openai_codex_models() {
            if !models.is_empty() {
                return models;
            }
        }
    }
    known_models_for(agent)
}

#[derive(Debug, Deserialize)]
struct OpenAiModelsResponse {
    data: Vec<OpenAiModel>,
}

#[derive(Debug, Deserialize)]
struct OpenAiModel {
    id: String,
}

fn fetch_openai_codex_models() -> Result<Vec<ModelOption>> {
    let api_key = std::env::var("OPENAI_API_KEY")
        .context("OPENAI_API_KEY is not set; falling back to local codex model list")?;
    let base_url = std::env::var("STAX_OPENAI_API_BASE_URL")
        .unwrap_or_else(|_| "https://api.openai.com".to_string());
    let url = format!("{}/v1/models", base_url.trim_end_matches('/'));

    let runtime = tokio::runtime::Runtime::new()?;
    let response = runtime.block_on(async {
        reqwest::Client::builder()
            .connect_timeout(std::time::Duration::from_secs(3))
            .timeout(std::time::Duration::from_secs(5))
            .build()?
            .get(&url)
            .bearer_auth(api_key)
            .send()
            .await?
            .error_for_status()?
            .json::<OpenAiModelsResponse>()
            .await
    })?;

    Ok(filter_live_codex_models(response.data))
}

fn filter_live_codex_models(models: Vec<OpenAiModel>) -> Vec<ModelOption> {
    let dated_snapshot = Regex::new(r"-\d{4}-\d{2}-\d{2}$").expect("valid regex");
    let mut model_ids: Vec<String> = models
        .into_iter()
        .map(|model| model.id)
        .filter(|id| is_codex_picker_candidate(id))
        .filter(|id| !id.contains("search-api"))
        .filter(|id| !id.ends_with("-chat-latest"))
        .filter(|id| !dated_snapshot.is_match(id))
        .collect();

    model_ids.sort_by(|a, b| compare_model_ids(a, b));
    model_ids.dedup();

    model_ids
        .into_iter()
        .map(|id| ModelOption {
            id,
            description: "live via OpenAI Models API".to_string(),
        })
        .collect()
}

fn compare_model_ids(left: &str, right: &str) -> std::cmp::Ordering {
    model_rank(right)
        .cmp(&model_rank(left))
        .then_with(|| left.cmp(right))
}

fn model_rank(model: &str) -> (i32, i32, i32, u8) {
    let version = parse_model_version(model);
    let family_rank = if model.contains("-nano") {
        0
    } else if model.contains("-mini") {
        1
    } else if model.contains("codex") {
        2
    } else if model.contains("-pro") {
        3
    } else {
        4
    };
    (version.0, version.1, version.2, family_rank)
}

fn parse_model_version(model: &str) -> (i32, i32, i32) {
    let version = model
        .trim_start_matches("gpt-")
        .split('-')
        .next()
        .unwrap_or_default();
    let mut parts = version.split('.');
    let major = parts
        .next()
        .and_then(|part| part.parse().ok())
        .unwrap_or_default();
    let minor = parts
        .next()
        .and_then(|part| part.parse().ok())
        .unwrap_or_default();
    let patch = parts
        .next()
        .and_then(|part| part.parse().ok())
        .unwrap_or_default();
    (major, minor, patch)
}

fn is_codex_picker_candidate(model: &str) -> bool {
    model.starts_with("gpt-5") || model.starts_with("gpt-4.1")
}

fn model_matches_agent_family(agent: &str, model: &str) -> bool {
    match agent {
        "claude" => model.starts_with("claude-"),
        "codex" => is_codex_picker_candidate(model) || model.starts_with("codex"),
        "gemini" => model.starts_with("gemini-"),
        "opencode" => model.starts_with("opencode/"),
        _ => false,
    }
}

// ---------------------------------------------------------------------------
// Context collection
// ---------------------------------------------------------------------------

pub fn get_diff_stat(workdir: &Path, parent: &str, branch: &str) -> String {
    let output = Command::new("git")
        .args(["diff", "--stat", &format!("{}..{}", parent, branch)])
        .current_dir(workdir)
        .output();

    match output {
        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        _ => String::new(),
    }
}

pub fn get_full_diff(workdir: &Path, parent: &str, branch: &str) -> String {
    let output = Command::new("git")
        .args(["diff", &format!("{}..{}", parent, branch)])
        .current_dir(workdir)
        .output();

    match output {
        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        _ => String::new(),
    }
}

fn collect_commit_messages(workdir: &Path, parent: &str, branch: &str) -> Vec<String> {
    let output = Command::new("git")
        .args([
            "log",
            "--reverse",
            "--format=%s",
            &format!("{}..{}", parent, branch),
        ])
        .current_dir(workdir)
        .output();

    match output {
        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout)
            .lines()
            .map(|line| line.trim().to_string())
            .filter(|line| !line.is_empty())
            .collect(),
        _ => Vec::new(),
    }
}

// ---------------------------------------------------------------------------
// Prompt construction
// ---------------------------------------------------------------------------

const MAX_DIFF_BYTES: usize = 80_000; // ~80KB limit to stay within context windows

pub fn build_ai_prompt(
    diff_stat: &str,
    diff: &str,
    commits: &[String],
    template: Option<&str>,
) -> String {
    let mut prompt = String::new();

    prompt.push_str("Generate a pull request description for the following changes.\n\n");

    if let Some(tmpl) = template {
        prompt.push_str(
            "Use this PR template as the structure. Fill in each section based on the changes:\n\n",
        );
        prompt.push_str(tmpl);
        prompt.push_str("\n\n");
    } else {
        prompt.push_str("Use a clear markdown format with a Summary section.\n\n");
    }

    if !commits.is_empty() {
        prompt.push_str("Commit messages:\n");
        for msg in commits {
            prompt.push_str(&format!("- {}\n", msg));
        }
        prompt.push('\n');
    }

    if !diff_stat.is_empty() {
        prompt.push_str("Diff stat (file-level summary):\n```\n");
        prompt.push_str(diff_stat);
        prompt.push_str("\n```\n\n");
    }

    if !diff.is_empty() {
        let truncated = if diff.len() > MAX_DIFF_BYTES {
            // Cut on a UTF-8 boundary so non-ASCII diffs do not panic.
            let safe = &diff[..safe_utf8_cut(diff, MAX_DIFF_BYTES)];
            let cut = safe.rfind('\n').unwrap_or(safe.len());
            format!(
                "{}\n\n... (diff truncated, showing first ~80KB of {} total) ...",
                &safe[..cut],
                format_bytes(diff.len())
            )
        } else {
            diff.to_string()
        };

        prompt.push_str("Full diff:\n```diff\n");
        prompt.push_str(&truncated);
        prompt.push_str("\n```\n\n");
    }

    prompt.push_str("Write only the PR body in markdown. Do not include any preamble, explanation, or wrapping code fences.");

    prompt
}

fn format_bytes(bytes: usize) -> String {
    if bytes >= 1_048_576 {
        format!("{:.1}MB", bytes as f64 / 1_048_576.0)
    } else if bytes >= 1024 {
        format!("{:.1}KB", bytes as f64 / 1024.0)
    } else {
        format!("{}B", bytes)
    }
}

// ---------------------------------------------------------------------------
// AI agent invocation
// ---------------------------------------------------------------------------

pub fn invoke_ai_agent(agent: &str, model: Option<&str>, prompt: &str) -> Result<String> {
    let mut args: Vec<String> = Vec::new();
    let mut write_prompt_to_stdin = true;

    match agent {
        "claude" => {
            args.extend(["-p".into(), "--output-format".into(), "text".into()]);
            if let Some(m) = model {
                args.extend(["--model".into(), m.into()]);
            }
        }
        "codex" => {
            args.push("exec".into());
            if let Some(m) = model {
                args.extend(["--model".into(), m.into()]);
            }
        }
        "gemini" => {
            if let Some(m) = model {
                args.extend(["-m".into(), m.into()]);
            }
        }
        "opencode" => {
            args.push("run".into());
            if let Some(m) = model {
                args.extend(["--model".into(), m.into()]);
            }
            args.extend(["--format".into(), "default".into()]);
            args.push(prompt.to_string());
            write_prompt_to_stdin = false;
        }
        _ => bail!("Unsupported agent: {}", agent),
    }

    let mut child = Command::new(agent)
        .args(&args)
        .stdin(if write_prompt_to_stdin {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context(format!(
            "Failed to start '{}'. Is it installed and on your PATH?",
            agent
        ))?;

    if write_prompt_to_stdin {
        // Write prompt to stdin
        if let Some(mut stdin) = child.stdin.take() {
            stdin
                .write_all(prompt.as_bytes())
                .context("Failed to write prompt to AI agent stdin")?;
            // stdin is dropped here, closing the pipe
        }
    }

    let output = child
        .wait_with_output()
        .context("Failed to read AI agent output")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "AI agent '{}' exited with status {}:\n{}",
            agent,
            output.status,
            stderr.trim()
        );
    }

    let body = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(body)
}

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

    #[test]
    fn build_ai_prompt_handles_multibyte_diff_at_truncation_boundary() {
        // Place a multibyte character so its bytes straddle MAX_DIFF_BYTES.
        let mut diff = "a".repeat(MAX_DIFF_BYTES - 1);
        diff.push('é');
        diff.push_str(&"b".repeat(1024));
        let prompt = build_ai_prompt("stat", &diff, &[], None);
        assert!(prompt.contains("diff truncated"));
    }

    #[test]
    fn validate_agent_name_accepts_gemini() {
        assert!(validate_agent_name("gemini").is_ok());
    }

    #[test]
    fn validate_agent_name_accepts_opencode() {
        assert!(validate_agent_name("opencode").is_ok());
    }

    #[test]
    fn known_models_include_gemini_defaults() {
        let models = known_models_for("gemini");
        assert!(models.iter().any(|m| m.id == "gemini-2.5-pro"));
        assert!(models.iter().any(|m| m.id == "gemini-2.5-flash"));
    }

    #[test]
    fn known_models_include_opencode_defaults() {
        let models = known_models_for("opencode");
        assert!(models.iter().any(|m| m.id == "opencode/gpt-5.5"));
        assert!(models.iter().any(|m| m.id == "opencode/gpt-5.5-fast"));
        assert!(models.iter().any(|m| m.id == "opencode/gpt-5.1-codex"));
    }

    #[test]
    fn known_models_include_codex_gpt_5_5_defaults() {
        let models = known_models_for("codex");
        assert!(models.iter().any(|m| m.id == "gpt-5.5"));
        assert!(models.iter().any(|m| m.id == "gpt-5.5-fast"));
    }

    #[test]
    fn live_codex_model_filter_keeps_latest_aliases() {
        let filtered = filter_live_codex_models(vec![
            OpenAiModel {
                id: "gpt-5.4-2026-03-05".to_string(),
            },
            OpenAiModel {
                id: "gpt-5.4".to_string(),
            },
            OpenAiModel {
                id: "gpt-5.3-codex".to_string(),
            },
            OpenAiModel {
                id: "gpt-5-search-api".to_string(),
            },
            OpenAiModel {
                id: "gpt-5.2-chat-latest".to_string(),
            },
        ]);

        let ids: Vec<&str> = filtered.iter().map(|model| model.id.as_str()).collect();
        assert_eq!(ids.first().copied(), Some("gpt-5.4"));
        assert!(ids.contains(&"gpt-5.4"));
        assert!(ids.contains(&"gpt-5.3-codex"));
        assert!(!ids.contains(&"gpt-5.4-2026-03-05"));
        assert!(!ids.contains(&"gpt-5-search-api"));
        assert!(!ids.contains(&"gpt-5.2-chat-latest"));
    }

    #[test]
    fn resolve_model_ignores_known_model_from_other_agent() {
        let mut config = Config::default();
        config.ai.model = Some("gpt-5.3-codex".to_string());

        let resolved = resolve_model(None, &config, "gemini", "generate").unwrap();
        assert_eq!(resolved, None);
    }

    #[test]
    fn resolve_model_keeps_unknown_custom_model() {
        let mut config = Config::default();
        config.ai.model = Some("my-custom-model".to_string());

        let resolved = resolve_model(None, &config, "gemini", "generate").unwrap();
        assert_eq!(resolved, Some("my-custom-model".to_string()));
    }

    #[test]
    fn resolve_model_ignores_opencode_model_for_other_agent() {
        let mut config = Config::default();
        config.ai.model = Some("opencode/gpt-5.1-codex".to_string());

        let resolved = resolve_model(None, &config, "claude", "generate").unwrap();
        assert_eq!(resolved, None);
    }

    #[test]
    fn resolve_model_prefers_per_feature_over_global() {
        let mut config = Config::default();
        config.ai.model = Some("global-model".to_string());
        config.ai.generate.model = Some("generate-model".to_string());

        let resolved = resolve_model(None, &config, "claude", "generate").unwrap();
        assert_eq!(resolved, Some("generate-model".to_string()));
    }

    #[test]
    fn resolve_model_falls_back_to_global_when_feature_unset() {
        let mut config = Config::default();
        config.ai.model = Some("global-model".to_string());

        let resolved = resolve_model(None, &config, "claude", "generate").unwrap();
        assert_eq!(resolved, Some("global-model".to_string()));
    }

    #[test]
    fn known_agent_for_model_recognizes_newer_codex_family_models() {
        assert_eq!(known_agent_for_model("gpt-5.5"), Some("codex"));
        assert_eq!(known_agent_for_model("gpt-5.5-fast"), Some("codex"));
        assert_eq!(known_agent_for_model("gpt-5.4"), Some("codex"));
        assert_eq!(known_agent_for_model("gpt-5.4-pro"), Some("codex"));
    }

    #[test]
    fn known_agent_for_model_recognizes_opencode_gpt_5_5_models() {
        assert_eq!(known_agent_for_model("opencode/gpt-5.5"), Some("opencode"));
        assert_eq!(
            known_agent_for_model("opencode/gpt-5.5-fast"),
            Some("opencode")
        );
    }

    #[test]
    fn auto_detect_agent_uses_first_available_agent() {
        let available = vec!["codex".to_string(), "gemini".to_string()];

        let resolved = auto_detect_agent(&available).unwrap();

        assert_eq!(resolved, "codex");
    }

    #[test]
    fn auto_detect_agent_errors_when_none_available() {
        let err = auto_detect_agent(&[]).unwrap_err();

        assert!(err.to_string().contains("No AI agent found on PATH"));
    }

    // ---------------------------------------------------------------------------
    // resolve_agent — first-use prompt behaviour
    //
    // The interactive branch (no_prompt=false) calls dialoguer and cannot be
    // exercised in unit tests. The no_prompt=true path covers the non-interactive
    // fallback (scripts, pipes) and proves the resolution order is correct.
    // ---------------------------------------------------------------------------

    #[test]
    fn resolve_agent_cli_flag_overrides_all_config() {
        let mut config = Config::default();
        config.ai.agent = Some("codex".to_string());
        config.ai.generate.agent = Some("gemini".to_string());

        let result = resolve_agent(Some("claude"), &mut config, true).unwrap();
        assert_eq!(result, "claude");
    }

    #[test]
    fn resolve_agent_uses_per_feature_when_set_no_prompt() {
        let mut config = Config::default();
        config.ai.agent = Some("codex".to_string()); // global
        config.ai.generate.agent = Some("claude".to_string()); // per-feature

        let result = resolve_agent(None, &mut config, true).unwrap();
        assert_eq!(result, "claude");
    }

    #[test]
    fn resolve_agent_falls_back_to_global_when_no_feature_config_no_prompt() {
        // This is the scenario that was broken: global config exists, no per-feature
        // config. With no_prompt=true (non-interactive), we should use the global
        // agent silently instead of blocking on a prompt or erroring.
        let mut config = Config::default();
        config.ai.agent = Some("codex".to_string()); // global only, no [ai.generate]

        let result = resolve_agent(None, &mut config, true).unwrap();
        assert_eq!(result, "codex");
    }

    #[test]
    fn resolve_agent_per_feature_takes_priority_over_global_no_prompt() {
        // Even in no_prompt mode the per-feature slot wins over global.
        let mut config = Config::default();
        config.ai.agent = Some("gemini".to_string());
        config.ai.generate.agent = Some("opencode".to_string());

        let result = resolve_agent(None, &mut config, true).unwrap();
        assert_eq!(result, "opencode");
    }
}