granite-cli 0.2.9

CLI for discovering, configuring, and launching AI workflows powered by IBM Granite models.
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
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
//! The prompts that ask what to do about a broken configuration reference,
//! and the code that applies the answer.
//!
//! [`remediate`] offers a fix for one broken reference at a time, until what
//! the caller named validates or the user stops accepting fixes.
//! [`confirm_removal`] runs before a removal and reports what points at the
//! instance about to be deleted, so the user can take those with it, cancel,
//! or leave them.
//!
//! Reconfigure and remove run the instance's own setup and removal commands,
//! the ones a user would run by hand. Un-enabling is the one repair applied
//! here, dropping an id from a launcher's `enabled_capabilities`.
//!
use std::collections::HashMap;

use anyhow::Result;

use crate::commands::{CapabilityCommands, LauncherCommands, ModelCommands, ProviderCommands};
use crate::config::Config;
use crate::config::validation::{
    Problem, RefKind, ValidationError, dependents, find_dangling, type_name, validate_ref,
};

/*-- public --------------------------------------------------------------------*/

/// What declining a fix means for the command that asked, which decides only
/// how the last choice is worded. The caller acts on the returned
/// [`Outcome`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OnDecline {
    /// The command carries on with the instance left as it is, which is what
    /// an info or detail command does.
    Skip,
    /// The command cannot run against a broken configuration and stops,
    /// which is what `launch` does.
    Abort,
}

/// Whether what the caller named validates now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
    /// Nothing was broken, or everything broken was fixed.
    Clean,
    /// Something is still broken: the user declined to fix it, or there was
    /// nobody to ask. Also returned when the user chose to remove the
    /// instance the caller named, which leaves nothing to validate.
    Unresolved,
}

/// The note a list command puts against each instance of `kind` whose
/// references do not resolve, keyed by instance id.
///
/// A list reports that a problem exists and never prompts about it. Acting on
/// it is left to a command the user chooses to run next.
pub(crate) fn dangling_notes(ctx: &crate::AppContext, kind: RefKind) -> HashMap<String, String> {
    find_dangling(kind, ctx.config(), &ctx.sources())
        .into_iter()
        .map(|dangling| {
            (
                dangling.instance_id,
                ctx.ui.warn_mark(&format!("⚠ {}", dangling.reason)),
            )
        })
        .collect()
}

/// A selection prompt that names the instance currently configured, and says
/// so when it no longer resolves.
///
/// A setup run over an existing instance offers its current values as
/// defaults. Without this, pressing Enter through the wizard re-saves a
/// dangling reference with nothing on screen to say it was one.
pub(crate) fn prompt_with_current(
    ctx: &crate::AppContext,
    prompt: &str,
    kind: RefKind,
    current: Option<&str>,
) -> String {
    let Some(current) = current.filter(|id| !id.is_empty()) else {
        return prompt.to_string();
    };

    match validate_ref(kind, current, ctx.config(), &ctx.sources()) {
        Ok(()) => format!("{prompt} [current: '{current}']"),
        Err(_) => format!(
            "{prompt} [current: '{current}', {} no longer resolves]",
            ctx.ui.warn_mark("⚠")
        ),
    }
}

/// How a removal command should behave when other configured instances point
/// at the entity being removed.
///
/// Passed as `--dependents <cascade|refuse|leave>` on the CLI. When the flag
/// is omitted the caller passes `None`: an interactive session asks what to
/// do, and a session that cannot ask refuses with exit code 1 and an error
/// naming the three policies.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum DependentsPolicy {
    /// Remove the target and every dependent automatically, without asking.
    /// Cascades recursively so dependents-of-dependents are taken too.
    Cascade,
    /// Refuse to remove the target and exit with code 1 if anything depends
    /// on it.
    Refuse,
    /// Remove only the target. Dependents are left configured but broken.
    Leave,
}

/// What a removal should do about the instances pointing at what is being
/// removed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Removal {
    /// Go ahead, taking these instances with it. Empty when nothing pointed
    /// at the target, or when the user chose to strand what did.
    Proceed { with: Vec<(RefKind, String)> },
    /// Leave everything alone.
    Cancel,
}

/// Asks what to do about the instances that point at `(kind, id)` before a
/// removal strands them.
///
/// `policy` is `Some(DependentsPolicy::...)` when a `--dependents` flag was
/// given, or `None` to fall back to the session's default:
///
/// - `Some(Refuse)`: fails immediately with a non-zero exit if anything
///   depends on the target. Nothing is removed or printed beyond the error.
/// - `Some(Cascade)`: removes the target and all dependents automatically,
///   reporting what will be removed before doing so.
/// - `Some(Leave)`: removes only the target; warns about what was left
///   broken. Same as the old non-interactive fallback.
/// - `None`, interactive session: prompts the user with three choices.
/// - `None`, non-interactive session (`--output json` / `--output markdown`,
///   or no terminal to ask on): fails with a non-zero exit, like `Refuse`,
///   with an error that names the three policies.
pub(crate) fn confirm_removal(
    ctx: &crate::AppContext,
    kind: RefKind,
    id: &str,
    policy: Option<DependentsPolicy>,
) -> Result<Removal> {
    let stranded = dependents(kind, id, ctx.config());
    if stranded.is_empty() {
        return Ok(Removal::Proceed { with: stranded });
    }

    match policy {
        Some(DependentsPolicy::Refuse) | None if !ctx.ui.is_interactive() => {
            anyhow::bail!(
                "Cannot remove {kind} '{id}' because other configured instances depend on it. \
                 Pass --dependents cascade, --dependents leave, or --dependents refuse."
            );
        }
        Some(DependentsPolicy::Refuse) => {
            anyhow::bail!(
                "Cannot remove {kind} '{id}' because other configured instances depend on it."
            );
        }
        Some(DependentsPolicy::Cascade) => {
            ctx.ui
                .warn(&format!("Removing {kind} '{id}' and its dependents:"));
            for (dependent_kind, dependent_id) in &stranded {
                let type_suffix = type_name(*dependent_kind, dependent_id, ctx.config())
                    .map(|t| format!(" ({t})"))
                    .unwrap_or_default();
                ctx.ui.info(&format!(
                    "  - {dependent_kind} '{dependent_id}'{type_suffix}"
                ));
            }
            return Ok(Removal::Proceed { with: stranded });
        }
        Some(DependentsPolicy::Leave) => {
            ctx.ui.warn(&format!("Removing {kind} '{id}' will break:"));
            for (dependent_kind, dependent_id) in &stranded {
                let type_suffix = type_name(*dependent_kind, dependent_id, ctx.config())
                    .map(|t| format!(" ({t})"))
                    .unwrap_or_default();
                ctx.ui.info(&format!(
                    "  - {dependent_kind} '{dependent_id}'{type_suffix}"
                ));
            }
            ctx.ui.warn(&format!(
                "Removing only {kind} '{id}'. What depended on it needs fixing."
            ));
            return Ok(Removal::Proceed { with: Vec::new() });
        }
        None => {
            ctx.ui.warn(&format!("Removing {kind} '{id}' will break:"));
            for (dependent_kind, dependent_id) in &stranded {
                let type_suffix = type_name(*dependent_kind, dependent_id, ctx.config())
                    .map(|t| format!(" ({t})"))
                    .unwrap_or_default();
                ctx.ui.info(&format!(
                    "  - {dependent_kind} '{dependent_id}'{type_suffix}"
                ));
            }
        }
    }

    // Only reachable when policy is None and the session is interactive.

    let together = match stranded.as_slice() {
        [(dependent_kind, dependent_id)] => {
            format!("Remove {kind} '{id}' and {dependent_kind} '{dependent_id}' together")
        }
        _ => format!(
            "Remove {kind} '{id}' and the {} instances that depend on it",
            stranded.len()
        ),
    };
    let items = vec![
        together,
        format!("Cancel, keep {kind} '{id}'"),
        format!("Remove only {kind} '{id}', fix the rest later"),
    ];

    // Cancelling is the default: this is the destructive prompt, and the
    // other two answers both delete something.
    match ctx.ui.select("What would you like to do?", &items, 1)? {
        0 => Ok(Removal::Proceed { with: stranded }),
        2 => Ok(Removal::Proceed { with: Vec::new() }),
        _ => Ok(Removal::Cancel),
    }
}

/// Removes each instance through its own removal command, so anything
/// depending on *them* gets the same question in turn.
///
/// `policy` is threaded down so that second-level dependents are also
/// removed automatically when the original call used `--dependents cascade`.
pub(crate) fn remove_all(
    ctx: &mut crate::AppContext,
    ids: &[(RefKind, String)],
    policy: Option<DependentsPolicy>,
) -> Result<()> {
    for (kind, id) in ids {
        remove(ctx, *kind, id, policy)?;
    }
    Ok(())
}

/// Validates `(kind, id)` and offers a fix for whatever is broken,
/// re-validating after each one so a repair that exposes a second problem is
/// offered in turn.
///
/// `may_prompt` is the caller's own mode, false for a non-prompting run such
/// as `setup --auto`. Prompting also needs a `Ui` with somebody to ask, so a
/// JSON or Markdown session never reaches a prompt whatever the caller
/// passes. Without prompting the problem is reported and left alone, which is
/// what skipping does.
///
/// Reached through a launcher, the removal on offer is disabling: the
/// launcher stops enabling the capability and the capability itself stays
/// configured. Deleting an instance is offered only to a caller that named
/// that instance, since a capability may be enabled by more than one launcher.
///
/// The loop ends when validation comes back clean, when the user declines,
/// when a removal takes the instance the caller named, or when every repair
/// on offer has been tried against the same problem. A repair that changes
/// nothing is dropped from the choices rather than ending the run, so it
/// always terminates and always leaves the remaining repairs reachable.
pub(crate) async fn remediate(
    ctx: &mut crate::AppContext,
    kind: RefKind,
    id: &str,
    on_decline: OnDecline,
    may_prompt: bool,
) -> Result<Outcome> {
    let prompting = may_prompt && ctx.ui.is_interactive();
    let mut previous: Option<ValidationError> = None;
    let mut tried: Vec<Choice> = Vec::new();

    loop {
        let Err(error) = validate_ref(kind, id, ctx.config(), &ctx.sources()) else {
            return Ok(Outcome::Clean);
        };

        // A repair that left the problem exactly as it was will do so again,
        // so it is dropped from the choices rather than ending the run. A
        // reconfiguration the user walked out of, or used to change something
        // else, comes back to the same question with the rest still on offer.
        // A different problem starts over with all of them.
        if previous.as_ref() != Some(&error) {
            tried.clear();
        }

        let Some(fix) = Fix::for_error(&error, ctx.config(), (kind, id)) else {
            // The instance the caller asked about is itself missing, so
            // there is nothing to offer: reconfiguring or removing needs
            // something that exists.
            ctx.ui.warn(&error.to_string());
            return Ok(Outcome::Unresolved);
        };

        if !prompting {
            ctx.ui.warn(&error.to_string());
            return Ok(Outcome::Unresolved);
        }

        // Every repair has been tried and the problem is still here.
        let Some(choice) = choose(ctx, &error, &fix, on_decline, &tried)? else {
            ctx.ui.warn(&format!("Still unresolved: {error}"));
            return Ok(Outcome::Unresolved);
        };

        tried.push(choice);
        match choice {
            Choice::Reconfigure => {
                previous = Some(error);
                reconfigure(ctx, &fix).await?;
            }
            Choice::Reset => {
                previous = Some(error);
                reset(ctx, &fix)?;
            }
            Choice::Remove => {
                previous = Some(error);
                remove(ctx, fix.kind, &fix.id, None)?;
                // The removal took the instance the caller named, either as
                // the fix itself or as a dependent of it. Validating again
                // would report it as not configured right after the removal
                // said it was removed. The caller checks whether it still
                // exists.
                if type_name(kind, id, ctx.config()).is_none() {
                    return Ok(Outcome::Unresolved);
                }
            }
            Choice::Disable => {
                previous = Some(error);
                disable(ctx, &fix)?;
            }
            // The walk is deterministic, so the next pass would report the
            // problem just declined. Stop rather than ask about it again.
            Choice::Decline => return Ok(Outcome::Unresolved),
        }
    }
}

/*-- private -------------------------------------------------------------------*/

/// The instance a fix acts on, and what can be done to it.
#[derive(Debug, PartialEq, Eq)]
struct Fix {
    kind: RefKind,
    id: String,
    /// The instance's `*_type`, which reconfiguring hands back to setup.
    type_name: String,
    /// False when the type name is itself the problem. Setup cannot run a
    /// type the registry does not have, so removal is the only fix.
    can_reconfigure: bool,
    /// What resetting would change, when the problem is settings that are not
    /// valid and replacing some of them with this type's defaults leaves an
    /// instance that builds. `None` when no such replacement exists, which is
    /// the case for a type whose defaults carry the same unusable value (an
    /// `agent-model` capability's default model id is empty, like the one
    /// that is not valid).
    reset: Option<ResetPlan>,
    /// The `(launcher, capability)` pair to disable, when remediation was
    /// reached through a launcher that enables the capability. Some means the
    /// removal on offer drops the id from that launcher's list rather than
    /// deleting the instance.
    disable: Option<(String, String)>,
}

impl Fix {
    fn for_error(error: &ValidationError, config: &Config, root: (RefKind, &str)) -> Option<Self> {
        // An instance that is not configured cannot be acted on, so the fix
        // belongs to whoever points at it: `launch claude` finding that
        // `chat`'s model is gone reconfigures `chat`. Every other problem is
        // a property of the target itself.
        let (kind, id) = match &error.problem {
            Problem::NotConfigured => error.referrer.clone()?,
            _ => error.target.clone(),
        };

        let type_name = type_name(kind, &id, config)?.to_string();
        let reset = match &error.problem {
            Problem::UnreadableSettings { .. } => {
                plan_reset(kind, &type_name, settings(kind, &id, config)?)
            }
            _ => None,
        };
        Some(Self {
            can_reconfigure: !matches!(error.problem, Problem::UnknownType { .. }),
            reset,
            type_name,
            disable: disable_target(error, kind, &id, root, config),
            kind,
            id,
        })
    }
}

/// The settings an instance carries, which is what a reset works from.
fn settings<'a>(kind: RefKind, id: &str, config: &'a Config) -> Option<&'a serde_json::Value> {
    match kind {
        RefKind::Launcher => config.get_launcher(id).map(|c| &c.config),
        RefKind::Capability => config.get_capability(id).map(|c| &c.config),
        RefKind::Model => config.get_model(id).map(|c| &c.config),
        RefKind::Provider => config.get_provider(id).map(|c| &c.config),
    }
}

/// The settings a reset would write, and the fields it would change to get
/// there.
#[derive(Debug, PartialEq, Eq)]
struct ResetPlan {
    /// The settings to write: the instance's own, with the fields below
    /// replaced by this type's defaults.
    settings: serde_json::Value,
    /// Each field the reset replaces, with the default value it takes.
    changes: Vec<(String, serde_json::Value)>,
}

impl ResetPlan {
    /// What the prompt offers, naming the fields and the values they take, so
    /// nobody accepts a repair without knowing what it moves.
    fn describe(&self, kind: RefKind, id: &str) -> String {
        let render = |value: &serde_json::Value| match value {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        };
        match self.changes.as_slice() {
            [(field, value)] => format!(
                "Reset {kind} '{id}' {field} setting to its default value of {}",
                render(value)
            ),
            changes => format!(
                "Reset {kind} '{id}' settings to their default values: {}",
                changes
                    .iter()
                    .map(|(field, value)| format!("{field} {}", render(value)))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    }
}

/// A replacement of some of an instance's settings by its type's defaults
/// that builds, or `None` when no replacement does.
///
/// The settings blob is valid JSON; it is reading it as the type's config that
/// failed, and usually over one field. So each field that differs from the
/// default is tried on its own first. When no single field is enough, the
/// differing fields are replaced one after another, in the order the defaults
/// list them, and the first set that builds is the plan. That set can include
/// fields that did not need replacing. Construction reads settings and does no
/// I/O, so trying a few is cheap.
fn plan_reset(kind: RefKind, type_name: &str, current: &serde_json::Value) -> Option<ResetPlan> {
    let defaults = default_settings(kind, type_name)?;
    let (Some(current_fields), Some(default_fields)) = (current.as_object(), defaults.as_object())
    else {
        return constructs(kind, type_name, &defaults).then(|| ResetPlan {
            settings: defaults.clone(),
            changes: Vec::new(),
        });
    };

    let differing: Vec<(&String, &serde_json::Value)> = default_fields
        .iter()
        .filter(|(field, value)| current_fields.get(*field) != Some(*value))
        .collect();

    for (field, value) in &differing {
        let mut candidate = current.clone();
        candidate[field.as_str()] = (*value).clone();
        if constructs(kind, type_name, &candidate) {
            return Some(ResetPlan {
                settings: candidate,
                changes: vec![((*field).clone(), (*value).clone())],
            });
        }
    }

    let mut candidate = current.clone();
    let mut changes = Vec::new();
    for (field, value) in differing {
        candidate[field.as_str()] = value.clone();
        changes.push((field.clone(), value.clone()));
        if constructs(kind, type_name, &candidate) {
            return Some(ResetPlan {
                settings: candidate,
                changes,
            });
        }
    }
    None
}

/// Whether these settings produce an instance of this type.
fn constructs(kind: RefKind, type_name: &str, settings: &serde_json::Value) -> bool {
    match kind {
        RefKind::Launcher => crate::launchers::LAUNCHER_REGISTRY
            .construct(type_name, type_name, settings)
            .is_ok(),
        RefKind::Capability => crate::capabilities::CAPABILITY_REGISTRY
            .construct(type_name, type_name, settings)
            .is_ok(),
        RefKind::Model => crate::models::MODEL_REGISTRY
            .construct(type_name, type_name, settings)
            .is_ok(),
        RefKind::Provider => crate::providers::PROVIDER_REGISTRY
            .construct(type_name, type_name, settings)
            .is_ok(),
    }
}

/// A type's default settings, as its registry entry declares them.
fn default_settings(kind: RefKind, type_name: &str) -> Option<serde_json::Value> {
    match kind {
        RefKind::Launcher => crate::launchers::LAUNCHER_REGISTRY.default_config(type_name),
        RefKind::Capability => crate::capabilities::CAPABILITY_REGISTRY.default_config(type_name),
        RefKind::Model => crate::models::MODEL_REGISTRY.default_config(type_name),
        RefKind::Provider => crate::providers::PROVIDER_REGISTRY.default_config(type_name),
    }
}

/// The `(launcher, capability)` pair a fix reached through a launcher can
/// disable.
///
/// A capability is shared: other launchers may enable the same instance, and
/// the caller asked to launch one launcher rather than to change the
/// configuration at large. Dropping the id from that launcher's own list
/// repairs what was asked about and leaves everything else alone.
///
/// Two shapes reach here. The launcher enables a capability whose own
/// reference is broken, where the fix acts on that capability; and the
/// launcher enables a capability that is not configured at all, where the fix
/// acts on the launcher.
fn disable_target(
    error: &ValidationError,
    kind: RefKind,
    id: &str,
    root: (RefKind, &str),
    config: &Config,
) -> Option<(String, String)> {
    if root.0 != RefKind::Launcher {
        return None;
    }
    let launcher_id = root.1;

    let capability_id = match kind {
        RefKind::Capability => id,
        RefKind::Launcher if error.target.0 == RefKind::Capability => error.target.1.as_str(),
        _ => return None,
    };

    config
        .get_launcher(launcher_id)?
        .enabled_capabilities
        .iter()
        .any(|enabled| enabled == capability_id)
        .then(|| (launcher_id.to_string(), capability_id.to_string()))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Choice {
    Reconfigure,
    Reset,
    Remove,
    Disable,
    Decline,
}

/// Reports the problem and asks what to do about it. Declining is the
/// default, so a user who answers without reading changes nothing.
fn choose(
    ctx: &crate::AppContext,
    error: &ValidationError,
    fix: &Fix,
    on_decline: OnDecline,
    tried: &[Choice],
) -> Result<Option<Choice>> {
    let mut choices = Vec::new();
    let mut items = Vec::new();

    if fix.can_reconfigure && !tried.contains(&Choice::Reconfigure) {
        choices.push(Choice::Reconfigure);
        items.push(format!("Reconfigure {} '{}' now", fix.kind, fix.id.clone()));
    }

    if let Some(plan) = &fix.reset
        && !tried.contains(&Choice::Reset)
    {
        choices.push(Choice::Reset);
        items.push(plan.describe(fix.kind, &fix.id));
    }

    match &fix.disable {
        Some((launcher_id, capability_id)) if !tried.contains(&Choice::Disable) => {
            choices.push(Choice::Disable);
            items.push(format!(
                "Remove capability '{capability_id}' from launcher '{launcher_id}'"
            ));
        }
        None if !tried.contains(&Choice::Remove) => {
            choices.push(Choice::Remove);
            items.push(format!("Remove {} '{}'", fix.kind, fix.id));
        }
        _ => {}
    }

    if choices.is_empty() {
        return Ok(None);
    }

    choices.push(Choice::Decline);
    items.push(match on_decline {
        OnDecline::Skip => format!("Skip for now, '{}' stays broken until fixed", fix.id),
        OnDecline::Abort => "Cancel".to_string(),
    });

    ctx.ui.warn(&format!("Configuration issue: {error}"));
    let picked = ctx
        .ui
        .select("What would you like to do?", &items, items.len() - 1)?;

    Ok(Some(choices[picked]))
}

/// Runs the instance's own setup command against the instance, which is what
/// the user would run by hand to change what it points at.
///
/// Passes `force_overwrite: true` so the wizard does not ask a second
/// "already configured, overwrite?" question — the choice made at the
/// remediation prompt was already that confirmation.
async fn reconfigure(ctx: &mut crate::AppContext, fix: &Fix) -> Result<()> {
    let (kind, type_name, id) = (fix.kind, fix.type_name.as_str(), Some(fix.id.as_str()));
    match kind {
        RefKind::Launcher => LauncherCommands::setup(ctx, type_name, id, true).await,
        RefKind::Capability => CapabilityCommands::setup(ctx, type_name, id, true).await,
        RefKind::Model => ModelCommands::setup(ctx, type_name, id, true).await,
        RefKind::Provider => ProviderCommands::setup(ctx, type_name, id, true).await,
    }
}

/// Replaces the fields that are not valid with their type's defaults, and
/// keeps everything else the instance was configured with. Reconfiguring also
/// repairs the instance, but setup offers the instance's current values, and
/// for a field whose value is not valid it offers a zero value (`0` for a
/// number, `false` for a flag). Accepting those writes that value, where this
/// writes the type's default.
fn reset(ctx: &mut crate::AppContext, fix: &Fix) -> Result<()> {
    let Some(plan) = &fix.reset else {
        return Ok(());
    };
    let defaults = plan.settings.clone();
    let (kind, id) = (fix.kind, fix.id.clone());
    // The in-memory change lands either way, which is what the walk about to
    // re-run reads. A failure to persist is reported the way the removal
    // commands report theirs.
    let saved = match kind {
        RefKind::Launcher => ctx
            .config_mut()
            .update_launcher(&id, |launcher| launcher.config = defaults),
        RefKind::Capability => ctx
            .config_mut()
            .update_capability(&id, |capability| capability.config = defaults),
        RefKind::Model => ctx
            .config_mut()
            .update_model(&id, |model| model.config = defaults),
        RefKind::Provider => ctx
            .config_mut()
            .update_provider(&id, |provider| provider.config = defaults),
    };
    if let Err(e) = saved {
        ctx.ui
            .warn(&format!("failed to persist the change to '{id}': {e}"));
    }
    ctx.ui.info(&format!(
        "{kind} '{id}': {} now holds the default from '{}'.",
        plan.changes
            .iter()
            .map(|(field, _)| field.as_str())
            .collect::<Vec<_>>()
            .join(", "),
        fix.type_name
    ));
    Ok(())
}

/// Drops the capability from the launcher's `enabled_capabilities`. The
/// capability stays configured, so any other launcher enabling it is
/// untouched.
fn disable(ctx: &mut crate::AppContext, fix: &Fix) -> Result<()> {
    let Some((launcher_id, capability_id)) = fix.disable.clone() else {
        return Ok(());
    };
    // The in-memory change lands either way, which is what the walk about to
    // re-run reads. A failure to persist is reported the way the removal
    // commands report theirs.
    if let Err(e) = ctx.config_mut().update_launcher(&launcher_id, |launcher| {
        launcher
            .enabled_capabilities
            .retain(|id| id != &capability_id)
    }) {
        ctx.ui.warn(&format!(
            "failed to persist the change to '{launcher_id}': {e}"
        ));
    }
    ctx.ui.info(&format!(
        "Launcher '{launcher_id}' no longer enables capability '{capability_id}'."
    ));
    Ok(())
}

fn remove(
    ctx: &mut crate::AppContext,
    kind: RefKind,
    id: &str,
    policy: Option<DependentsPolicy>,
) -> Result<()> {
    match kind {
        RefKind::Launcher => LauncherCommands::remove(ctx, id, policy),
        RefKind::Capability => CapabilityCommands::remove(ctx, id, policy),
        RefKind::Model => ModelCommands::remove(ctx, id, policy),
        RefKind::Provider => ProviderCommands::remove(ctx, id, policy),
    }
}

/*-- tests ---------------------------------------------------------------------*/

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{CapabilityConfig, LauncherConfig, ModelConfig, ProviderConfig};
    use crate::utils::ui::base::tests::CaptureUi;
    use std::sync::Arc;

    fn capture(ctx: &crate::AppContext) -> &CaptureUi {
        (&*ctx.ui as &dyn std::any::Any)
            .downcast_ref::<CaptureUi>()
            .expect("test contexts are built with a CaptureUi")
    }

    /// Answers the remediation prompts in order. `CaptureUi` falls back to
    /// the prompt's own default once the queue is empty, which is declining.
    fn answer(ctx: &crate::AppContext, choices: &[usize]) {
        let ui = capture(ctx);
        for choice in choices {
            ui.select_answers.borrow_mut().push_back(*choice);
        }
    }

    fn prompts(ctx: &crate::AppContext) -> Vec<(String, Vec<String>)> {
        capture(ctx)
            .select_prompts
            .borrow()
            .iter()
            .map(|(prompt, items, _)| (prompt.clone(), items.clone()))
            .collect()
    }

    /// A provider whose settings hold a field of the wrong type, which is
    /// the state the reset repair exists for.
    fn ctx_with_unreadable_provider_settings() -> crate::AppContext {
        let mut ctx = crate::AppContext::new(Config::default(), Arc::new(CaptureUi::default()));
        ctx.config_mut().providers.insert(
            "ollama".to_string(),
            ProviderConfig {
                provider_id: "ollama".to_string(),
                provider_type: "ollama".to_string(),
                // A deliberately chosen endpoint beside a field that cannot
                // be read, which is what a scoped repair has to tell apart.
                config: serde_json::json!({
                    "base_url": "http://127.0.0.1:18080",
                    "timeout_secs": "ten",
                }),
            },
        );
        ctx
    }

    #[tokio::test]
    async fn a_reset_replaces_the_field_that_cannot_be_read_and_keeps_the_rest() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_unreadable_provider_settings();
        // Reconfigure, reset, remove, decline: reset is the second.
        answer(&ctx, &[1]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Provider,
            "ollama",
            OnDecline::Abort,
            true,
        )
        .await
        .unwrap();

        assert_eq!(outcome, Outcome::Clean);
        let settings = &ctx.config().get_provider("ollama").unwrap().config;
        assert_eq!(
            settings.get("timeout_secs"),
            crate::providers::PROVIDER_REGISTRY
                .default_config("ollama")
                .as_ref()
                .and_then(|defaults| defaults.get("timeout_secs")),
            "the field that could not be read now holds its type's default"
        );
        assert_eq!(
            settings.get("base_url").and_then(|v| v.as_str()),
            Some("http://127.0.0.1:18080"),
            "a field that reads fine is left as it was configured"
        );
    }

    #[tokio::test]
    async fn the_reset_on_offer_names_the_field_and_the_value_it_takes() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_unreadable_provider_settings();

        let _ = remediate(
            &mut ctx,
            RefKind::Provider,
            "ollama",
            OnDecline::Abort,
            true,
        )
        .await
        .unwrap();

        let offered = &prompts(&ctx)[0].1;
        assert!(
            offered.iter().any(|item| item
                == "Reset provider 'ollama' timeout_secs setting to its default value of 10"),
            "got: {offered:?}"
        );
    }

    #[tokio::test]
    async fn a_reset_is_not_offered_when_the_defaults_would_not_help() {
        // `agent-model`'s default settings hold an empty model id, the same
        // value that is not valid here, so resetting repairs nothing and is
        // not offered.
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = crate::AppContext::new(Config::default(), Arc::new(CaptureUi::default()));
        ctx.config_mut().capabilities.insert(
            "chat".to_string(),
            CapabilityConfig {
                capability_id: "chat".to_string(),
                capability_type: "agent-model".to_string(),
                config: serde_json::json!({ "model_id": "" }),
            },
        );

        let _ = remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        let offered = prompts(&ctx);
        assert!(!offered.is_empty(), "the problem was reported");
        assert!(
            !offered[0].1.iter().any(|item| item.contains("Reset")),
            "got: {:?}",
            offered[0].1
        );
    }

    /// Launcher `claude` enables capability `chat`, which points at a model
    /// that is not configured. One healthy model satisfies `agent-model`'s
    /// Chat requirement, so reconfiguring `chat` picks it without a prompt
    /// of its own.
    fn ctx_with_a_dangling_model_ref() -> crate::AppContext {
        let mut ctx = crate::AppContext::new(Config::default(), Arc::new(CaptureUi::default()));
        ctx.config_mut().providers.insert(
            "ollama".to_string(),
            ProviderConfig {
                provider_id: "ollama".to_string(),
                provider_type: "ollama".to_string(),
                config: serde_json::json!({}),
            },
        );
        ctx.config_mut().models.insert(
            "granite-3.1-8b-instruct".to_string(),
            ModelConfig {
                model_id: "granite-3.1-8b-instruct".to_string(),
                model_type: "granite-3.1-8b-instruct".to_string(),
                provider_id: "ollama".to_string(),
                variant: None,
                config: serde_json::json!({}),
            },
        );
        ctx.config_mut().capabilities.insert(
            "chat".to_string(),
            CapabilityConfig {
                capability_id: "chat".to_string(),
                capability_type: "agent-model".to_string(),
                config: serde_json::json!({ "model_id": "gone" }),
            },
        );
        ctx.config_mut().launchers.insert(
            "claude".to_string(),
            LauncherConfig {
                launcher_id: "claude".to_string(),
                launcher_type: "claude".to_string(),
                enabled_capabilities: vec!["chat".to_string()],
                config: serde_json::json!({}),
            },
        );
        ctx
    }

    /// Capability `chat` uses the one configured model, and nothing enables
    /// the capability, so removing it strands nothing further.
    fn ctx_model_with_one_dependent() -> crate::AppContext {
        let mut ctx = ctx_with_a_dangling_model_ref();
        ctx.config_mut().launchers.clear();
        ctx.config_mut()
            .capabilities
            .get_mut("chat")
            .unwrap()
            .config = serde_json::json!({ "model_id": "granite-3.1-8b-instruct" });
        ctx
    }

    #[test]
    fn removing_a_model_with_its_dependent_removes_both() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        answer(&ctx, &[0]);

        ModelCommands::remove(&mut ctx, "granite-3.1-8b-instruct", None).unwrap();

        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        assert!(ctx.config().get_capability("chat").is_none());
    }

    #[test]
    fn cancelling_a_removal_keeps_both() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        answer(&ctx, &[1]);

        ModelCommands::remove(&mut ctx, "granite-3.1-8b-instruct", None).unwrap();

        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_some());
        assert!(ctx.config().get_capability("chat").is_some());
    }

    #[test]
    fn removing_only_what_was_asked_leaves_the_dependent_broken() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        answer(&ctx, &[2]);

        ModelCommands::remove(&mut ctx, "granite-3.1-8b-instruct", None).unwrap();

        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        // Left in place, and now dangling, which `capability list` reports.
        assert!(ctx.config().get_capability("chat").is_some());
        assert!(!find_dangling(RefKind::Capability, ctx.config(), &ctx.sources()).is_empty());
    }

    #[test]
    fn a_session_with_nobody_to_ask_refuses_when_dependents_exist() {
        // Non-interactive sessions default to refuse so scripts fail loudly
        // rather than silently stranding dependents.
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        *capture(&ctx).interactive.borrow_mut() = Some(false);

        let err = ModelCommands::remove(&mut ctx, "granite-3.1-8b-instruct", None).unwrap_err();

        assert!(prompts(&ctx).is_empty());
        assert!(err.to_string().contains("Pass --dependents"), "got: {err}");
        // Nothing was removed.
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_some());
        assert!(ctx.config().get_capability("chat").is_some());
    }

    #[test]
    fn a_non_interactive_session_with_leave_removes_only_what_was_asked() {
        // Explicit --dependents leave preserves the old non-interactive
        // behaviour for scripts that want it.
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        *capture(&ctx).interactive.borrow_mut() = Some(false);

        ModelCommands::remove(
            &mut ctx,
            "granite-3.1-8b-instruct",
            Some(DependentsPolicy::Leave),
        )
        .unwrap();

        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        assert!(ctx.config().get_capability("chat").is_some());
        let warns = capture(&ctx).warns.borrow().clone();
        assert!(warns.iter().any(|w| w.contains("will break")), "{warns:?}");
    }

    #[test]
    fn removing_something_nothing_depends_on_does_not_prompt() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();

        CapabilityCommands::remove(&mut ctx, "chat", None).unwrap();

        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_capability("chat").is_none());
    }
    #[test]
    fn removing_with_cascade_removes_target_and_dependents_without_prompting() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        *capture(&ctx).interactive.borrow_mut() = Some(false);

        ModelCommands::remove(
            &mut ctx,
            "granite-3.1-8b-instruct",
            Some(DependentsPolicy::Cascade),
        )
        .unwrap();

        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        assert!(ctx.config().get_capability("chat").is_none());
    }

    #[test]
    fn removing_with_cascade_does_not_prompt_in_an_interactive_session() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();

        ModelCommands::remove(
            &mut ctx,
            "granite-3.1-8b-instruct",
            Some(DependentsPolicy::Cascade),
        )
        .unwrap();

        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        assert!(ctx.config().get_capability("chat").is_none());
    }

    #[test]
    fn cascade_follows_dependents_of_dependents() {
        let _home = crate::config::TestConfigHome::new();
        // provider <- model <- capability: removing the provider has to take
        // the capability too, which only the model's own removal reaches.
        let mut ctx = ctx_model_with_one_dependent();
        *capture(&ctx).interactive.borrow_mut() = Some(false);

        ProviderCommands::remove(&mut ctx, "ollama", Some(DependentsPolicy::Cascade)).unwrap();

        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_provider("ollama").is_none());
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        assert!(ctx.config().get_capability("chat").is_none());
    }

    #[test]
    fn removing_with_refuse_fails_when_dependents_exist() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();
        *capture(&ctx).interactive.borrow_mut() = Some(false);

        let err = ModelCommands::remove(
            &mut ctx,
            "granite-3.1-8b-instruct",
            Some(DependentsPolicy::Refuse),
        )
        .unwrap_err();

        assert!(
            err.to_string().contains("Cannot remove model"),
            "got: {err}"
        );
        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_some());
        assert!(ctx.config().get_capability("chat").is_some());
    }

    #[test]
    fn removing_with_refuse_does_not_prompt_in_an_interactive_session() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();

        let result = ModelCommands::remove(
            &mut ctx,
            "granite-3.1-8b-instruct",
            Some(DependentsPolicy::Refuse),
        );

        assert!(result.is_err());
        assert!(prompts(&ctx).is_empty());
        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_some());
    }

    #[test]
    fn removing_with_refuse_succeeds_when_no_dependents_exist() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_model_with_one_dependent();

        CapabilityCommands::remove(&mut ctx, "chat", Some(DependentsPolicy::Refuse)).unwrap();

        assert!(ctx.config().get_capability("chat").is_none());
    }

    #[tokio::test]
    async fn a_healthy_instance_is_clean_without_prompting() {
        let mut ctx = ctx_with_a_dangling_model_ref();

        let outcome = remediate(
            &mut ctx,
            RefKind::Model,
            "granite-3.1-8b-instruct",
            OnDecline::Skip,
            true,
        )
        .await
        .unwrap();

        assert_eq!(outcome, Outcome::Clean);
        assert!(prompts(&ctx).is_empty());
    }

    #[tokio::test]
    async fn reconfigure_runs_setup_against_the_instance_holding_the_reference() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[0]);
        // Remediation passes force_overwrite=true to setup, so no
        // "already configured, overwrite?" confirm appears — the choice made
        // at the remediation prompt is the only confirmation needed.

        let outcome = remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        // Setup ran against `chat`, the capability holding the broken
        // reference, not against the model that is missing.
        assert_eq!(
            ctx.config()
                .get_capability("chat")
                .and_then(|c| c.config.get("model_id"))
                .and_then(|v| v.as_str()),
            Some("granite-3.1-8b-instruct")
        );
        // And the loop re-validated afterwards rather than taking the fix on
        // trust.
        assert_eq!(outcome, Outcome::Clean);

        let (_, items) = &prompts(&ctx)[0];
        assert!(
            items[0].contains("Reconfigure capability 'chat'"),
            "{items:?}"
        );
        // No overwrite confirm was issued.
        assert!(
            capture(&ctx).confirm_answers.borrow().is_empty(),
            "no canned confirms were consumed, so no confirm was issued"
        );
    }

    #[tokio::test]
    async fn remove_deletes_the_instance_holding_the_reference() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        // Remove, then keep the launcher that enables `chat` when the
        // removal asks about it.
        answer(&ctx, &[1, 2]);

        let outcome = remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        assert!(ctx.config().get_capability("chat").is_none());
        // What the caller asked about is gone, so it does not validate.
        assert_eq!(outcome, Outcome::Unresolved);
    }

    #[tokio::test]
    async fn a_fix_that_exposes_a_second_problem_is_offered_in_turn() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        // A second broken capability, so repairing the first leaves one more
        // for the loop to find.
        ctx.config_mut().capabilities.insert(
            "vision".to_string(),
            CapabilityConfig {
                capability_id: "vision".to_string(),
                capability_type: "agent-model".to_string(),
                config: serde_json::json!({ "model_id": "also-gone" }),
            },
        );
        ctx.config_mut()
            .launchers
            .get_mut("claude")
            .unwrap()
            .enabled_capabilities
            .push("vision".to_string());
        // Un-enable the first, then decline the second.
        answer(&ctx, &[1, 2]);

        let outcome = remediate(&mut ctx, RefKind::Launcher, "claude", OnDecline::Skip, true)
            .await
            .unwrap();

        let prompts = prompts(&ctx);
        assert_eq!(prompts.len(), 2, "{prompts:?}");
        assert!(prompts[0].1[0].contains("capability 'chat'"), "{prompts:?}");
        assert!(
            prompts[1].1[0].contains("capability 'vision'"),
            "{prompts:?}"
        );
        assert_eq!(outcome, Outcome::Unresolved);
    }

    #[tokio::test]
    async fn a_launch_un_enables_a_capability_instead_of_deleting_it() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[1]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Launcher,
            "claude",
            OnDecline::Abort,
            true,
        )
        .await
        .unwrap();

        let (_, items) = &prompts(&ctx)[0];
        assert_eq!(
            items[1], "Remove capability 'chat' from launcher 'claude'",
            "{items:?}"
        );
        assert_eq!(outcome, Outcome::Clean);
        assert!(
            ctx.config()
                .get_launcher("claude")
                .unwrap()
                .enabled_capabilities
                .is_empty()
        );
        assert!(
            ctx.config().get_capability("chat").is_some(),
            "the capability stays configured for any other launcher"
        );
    }

    #[tokio::test]
    async fn a_launch_un_enables_a_capability_that_is_not_configured() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        ctx.config_mut().capabilities.remove("chat");
        answer(&ctx, &[1]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Launcher,
            "claude",
            OnDecline::Abort,
            true,
        )
        .await
        .unwrap();

        // The fix acts on the launcher here, and the removal on offer is still
        // the entry in its list rather than the launcher itself.
        let (_, items) = &prompts(&ctx)[0];
        assert_eq!(
            items[1], "Remove capability 'chat' from launcher 'claude'",
            "{items:?}"
        );
        assert_eq!(outcome, Outcome::Clean);
        assert!(
            ctx.config()
                .get_launcher("claude")
                .unwrap()
                .enabled_capabilities
                .is_empty()
        );
    }

    #[tokio::test]
    async fn a_caller_naming_the_capability_is_still_offered_deletion() {
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[2]);

        remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        let (_, items) = &prompts(&ctx)[0];
        assert_eq!(items[1], "Remove capability 'chat'", "{items:?}");
    }

    #[tokio::test]
    async fn reconfigure_proceeds_without_an_overwrite_confirm() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[0]);

        let outcome = remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        assert_eq!(outcome, Outcome::Clean);
        let prompts = prompts(&ctx);
        assert!(prompts[0].1[0].starts_with("Reconfigure"), "{prompts:?}");
        // No overwrite confirm — force_overwrite skips the second prompt.
        assert!(capture(&ctx).confirm_answers.borrow().is_empty());
        assert_eq!(
            ctx.config()
                .get_capability("chat")
                .and_then(|c| c.config.get("model_id"))
                .and_then(|v| v.as_str()),
            Some("granite-3.1-8b-instruct"),
        );
    }

    #[tokio::test]
    async fn a_launch_reconfigure_fixes_the_reference_without_an_overwrite_confirm() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[0]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Launcher,
            "claude",
            OnDecline::Abort,
            true,
        )
        .await
        .unwrap();

        assert_eq!(outcome, Outcome::Clean);

        // No overwrite confirm — force_overwrite skips the second prompt.
        assert!(capture(&ctx).confirm_answers.borrow().is_empty());
        assert_eq!(
            ctx.config()
                .get_capability("chat")
                .and_then(|c| c.config.get("model_id"))
                .and_then(|v| v.as_str()),
            Some("granite-3.1-8b-instruct"),
        );
    }

    fn ctx_with_a_dangling_provider_ref() -> crate::AppContext {
        let mut ctx = crate::AppContext::new(
            Config::default(),
            Arc::new(crate::utils::ui::base::tests::CaptureUi::default()),
        );
        ctx.config_mut().providers.insert(
            "ollama".to_string(),
            ProviderConfig {
                provider_id: "ollama".to_string(),
                provider_type: "ollama".to_string(),
                config: serde_json::json!({}),
            },
        );
        ctx.config_mut().models.insert(
            "granite-3.1-8b-instruct".to_string(),
            ModelConfig {
                model_id: "granite-3.1-8b-instruct".to_string(),
                model_type: "granite-3.1-8b-instruct".to_string(),
                provider_id: "gone-provider".to_string(),
                variant: None,
                config: serde_json::json!({}),
            },
        );
        ctx
    }

    #[tokio::test]
    async fn reconfigure_model_arm_fixes_a_broken_provider_ref() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_provider_ref();
        answer(&ctx, &[0]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Model,
            "granite-3.1-8b-instruct",
            OnDecline::Skip,
            true,
        )
        .await
        .unwrap();

        assert_eq!(outcome, Outcome::Clean);
        assert_ne!(
            ctx.config()
                .get_model("granite-3.1-8b-instruct")
                .map(|m| m.provider_id.as_str()),
            Some("gone-provider"),
        );
        assert!(capture(&ctx).confirm_answers.borrow().is_empty());
    }

    #[tokio::test]
    async fn removing_the_named_instance_ends_without_reporting_it_missing() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_provider_ref();
        // Reconfigure, remove, skip: remove is the second.
        answer(&ctx, &[1]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Model,
            "granite-3.1-8b-instruct",
            OnDecline::Skip,
            true,
        )
        .await
        .unwrap();

        assert!(ctx.config().get_model("granite-3.1-8b-instruct").is_none());
        assert_eq!(outcome, Outcome::Unresolved);
        assert_eq!(prompts(&ctx).len(), 1);
        let warns = capture(&ctx).warns.borrow().clone();
        assert!(
            !warns
                .iter()
                .any(|w| w == "model 'granite-3.1-8b-instruct' is not configured"),
            "the model the user chose to remove is not reported as missing: {warns:?}"
        );
    }

    #[tokio::test]
    async fn declining_stops_instead_of_asking_again() {
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[2]);

        let outcome = remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        assert_eq!(outcome, Outcome::Unresolved);
        assert_eq!(prompts(&ctx).len(), 1);
        assert_eq!(
            ctx.config()
                .get_capability("chat")
                .and_then(|c| c.config.get("model_id"))
                .and_then(|v| v.as_str()),
            Some("gone"),
            "declining leaves the configuration alone"
        );
    }

    #[tokio::test]
    async fn a_non_prompting_caller_never_reaches_a_prompt() {
        let mut ctx = ctx_with_a_dangling_model_ref();

        let outcome = remediate(
            &mut ctx,
            RefKind::Capability,
            "chat",
            OnDecline::Skip,
            false,
        )
        .await
        .unwrap();

        assert_eq!(outcome, Outcome::Unresolved);
        assert!(prompts(&ctx).is_empty());
        assert!(!capture(&ctx).warns.borrow().is_empty(), "still reported");
    }

    #[tokio::test]
    async fn a_non_interactive_session_never_reaches_a_prompt() {
        let mut ctx = ctx_with_a_dangling_model_ref();
        *capture(&ctx).interactive.borrow_mut() = Some(false);

        let outcome = remediate(&mut ctx, RefKind::Capability, "chat", OnDecline::Skip, true)
            .await
            .unwrap();

        assert_eq!(outcome, Outcome::Unresolved);
        assert!(prompts(&ctx).is_empty());
    }

    #[tokio::test]
    async fn an_unknown_type_offers_removal_but_not_reconfiguration() {
        let mut ctx = ctx_with_a_dangling_model_ref();
        ctx.config_mut()
            .models
            .get_mut("granite-3.1-8b-instruct")
            .unwrap()
            .model_type = "not-a-model".to_string();
        answer(&ctx, &[1]);

        let outcome = remediate(
            &mut ctx,
            RefKind::Model,
            "granite-3.1-8b-instruct",
            OnDecline::Skip,
            true,
        )
        .await
        .unwrap();

        // Setup cannot run a type the registry does not have, so the only
        // fix offered is removal.
        let (_, items) = &prompts(&ctx)[0];
        assert_eq!(items.len(), 2, "{items:?}");
        assert!(items[0].starts_with("Remove model"), "{items:?}");
        assert_eq!(outcome, Outcome::Unresolved);
    }

    // The `launch` pre-launch is thin policy over `remediate`, so its two
    // tests live here with the fixture rather than in `launcher.rs`.

    #[tokio::test]
    async fn the_launch_prelaunch_aborts_when_the_user_declines() {
        let mut ctx = ctx_with_a_dangling_model_ref();

        // No canned answer, so the prompt takes its default, which declines.
        let result = crate::commands::LauncherCommands::prelaunch(&mut ctx, "claude").await;

        assert!(result.is_err(), "declining must stop the launch");
        assert_eq!(
            result.unwrap_err().to_string(),
            "Launch aborted: launcher 'claude' has a configuration problem that was not fixed."
        );
    }

    #[tokio::test]
    async fn the_launch_prelaunch_proceeds_once_the_reference_is_repaired() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[0]);
        // No second confirm needed: force_overwrite bypasses the overwrite
        // prompt, so the remediation choice is the only confirmation.

        crate::commands::LauncherCommands::prelaunch(&mut ctx, "claude")
            .await
            .expect("a repaired configuration launches");

        assert_eq!(
            ctx.config()
                .get_capability("chat")
                .and_then(|c| c.config.get("model_id"))
                .and_then(|v| v.as_str()),
            Some("granite-3.1-8b-instruct")
        );
    }

    #[tokio::test]
    async fn aborting_callers_are_offered_cancel_rather_than_skip() {
        let mut ctx = ctx_with_a_dangling_model_ref();
        answer(&ctx, &[2]);

        remediate(
            &mut ctx,
            RefKind::Launcher,
            "claude",
            OnDecline::Abort,
            true,
        )
        .await
        .unwrap();

        let (_, items) = &prompts(&ctx)[0];
        assert_eq!(items[2], "Cancel", "{items:?}");
    }

    // The Launcher and Provider arms of reconfigure() are unreachable via
    // the normal validation flow, so Fix is constructed directly here.
    #[tokio::test]
    async fn reconfigure_launcher_arm_calls_launcher_setup() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        let fix = Fix {
            kind: RefKind::Launcher,
            id: "claude".to_string(),
            type_name: "claude".to_string(),
            can_reconfigure: true,
            reset: None,
            disable: None,
        };
        // Binary not found in CI is fine — the arm is covered regardless.
        let _ = reconfigure(&mut ctx, &fix).await;
    }

    #[tokio::test]
    async fn reconfigure_provider_arm_calls_provider_setup() {
        let _home = crate::config::TestConfigHome::new();
        let mut ctx = ctx_with_a_dangling_model_ref();
        let fix = Fix {
            kind: RefKind::Provider,
            id: "ollama".to_string(),
            type_name: "ollama".to_string(),
            can_reconfigure: true,
            reset: None,
            disable: None,
        };
        reconfigure(&mut ctx, &fix).await.unwrap();
        assert!(ctx.config().get_provider("ollama").is_some());
        assert!(capture(&ctx).confirm_answers.borrow().is_empty());
    }
}