granite-cli 0.2.0

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
//! Answers whether a configured instance's references resolve, reading the
//! configuration and static registry metadata and constructing nothing.
//!
//! Two kinds of reference are checked. An id names another configured
//! instance, and a `*_type` name names an entry in that kind's registry. A
//! name that resolves to nothing is the same kind of inconsistency either
//! way.
//!
//! One walk covers every kind. Each of the four config types implements
//! [`Validatable`] to say what its type name is and which ids it points at,
//! and [`validate`] does the rest.

use std::collections::HashMap;

// TODO: This is a circular dependency that needs to be untangled
use crate::capabilities::Dependency;
use crate::config::{
    CapabilityConfig, Config, ConfigId, LauncherConfig, ModelConfig, ProviderConfig,
};

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

/// The four kinds of configured instance that reference each other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum RefKind {
    Launcher,
    Capability,
    Model,
    Provider,
}

/// What went wrong with a reference. Callers branch on this to decide what to
/// offer the user, rather than matching on a rendered message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Problem {
    /// The named instance is not in the configuration.
    NotConfigured,
    /// The instance's `*_type` is not a key in its kind's registry.
    UnknownType { type_name: String },
    /// A capability whose config carries no id under a required dependency's
    /// `config_key`.
    MissingDependency { config_key: String },
}

/// A reference that does not resolve.
///
/// `referrer` is the configured instance that holds the broken reference, and
/// is what a caller offering a fix acts on: `launch claude` finding that
/// `chat`'s model is gone reconfigures `chat`, not the missing model. It is
/// absent when the instance asked about is itself the problem.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ValidationError {
    pub(crate) target: (RefKind, String),
    pub(crate) problem: Problem,
    pub(crate) referrer: Option<(RefKind, String)>,
}

/// One instance with a broken reference, as returned by [`find_dangling`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DanglingRef {
    pub(crate) kind: RefKind,
    pub(crate) instance_id: String,
    /// The validation error, rendered.
    pub(crate) reason: String,
}

/// Validates that `id`'s references resolve, one hop at a time, recursing
/// through whatever it finds. A launcher walks its enabled capabilities,
/// their models, and those models' providers, so a missing provider four
/// levels down is reported rather than the walk stopping at the first level.
///
/// The walk covers only what it was asked about. Nothing here reads a part of
/// the configuration the caller did not name.
pub(crate) fn validate_ref(
    kind: RefKind,
    id: &str,
    config: &Config,
) -> Result<(), ValidationError> {
    validate(kind, id, config, None)
}

/// Validates every configured instance of one kind, returning those that
/// fail. This is what a list command needs, whose subject genuinely is every
/// instance of its kind.
///
/// # Examples
///
/// ```ignore
/// // The status column of `model list`. One scan covers the whole table, and
/// // reports only models even when what is actually missing is a provider.
/// let broken = find_dangling(RefKind::Model, &config);
/// for row in &mut rows {
///     if let Some(d) = broken.iter().find(|d| d.instance_id == row.id) {
///         row.notes = format!("{} {}", ui.warn_mark(), d.reason);
///     }
/// }
/// ```
pub(crate) fn find_dangling(kind: RefKind, config: &Config) -> Vec<DanglingRef> {
    config_entries(config, kind)
        .into_iter()
        .filter_map(|entry| {
            let id = entry.config_id();
            validate_ref(kind, id, config).err().map(|e| DanglingRef {
                kind,
                instance_id: id.to_string(),
                reason: e.to_string(),
            })
        })
        .collect()
}

/// The configured instances that point at `(kind, id)`, which is what
/// removing it would strand. Sorted, so a caller listing them is stable.
///
/// This is [`Validatable::refs`] read backwards: an instance depends on the
/// target when the target appears among the references it declares.
///
/// # Examples
///
/// ```ignore
/// // Before `model remove granite-3.1-8b-instruct` deletes anything.
/// let stranded = dependents(RefKind::Model, "granite-3.1-8b-instruct", &config);
/// // -> [(RefKind::Capability, "chat")]
/// ```
pub(crate) fn dependents(kind: RefKind, id: &str, config: &Config) -> Vec<(RefKind, String)> {
    let mut found: Vec<(RefKind, String)> = [
        RefKind::Launcher,
        RefKind::Capability,
        RefKind::Model,
        RefKind::Provider,
    ]
    .into_iter()
    .flat_map(|referrer_kind| {
        config_entries(config, referrer_kind)
            .into_iter()
            .map(move |entry| (referrer_kind, entry))
    })
    .filter(|(_, entry)| {
        // An instance that cannot name its references, such as a capability
        // missing a required dependency, points at nothing.
        entry.refs().is_ok_and(|refs| {
            refs.iter()
                .any(|(target_kind, target_id)| *target_kind == kind && *target_id == id)
        })
    })
    .map(|(referrer_kind, entry)| (referrer_kind, entry.config_id().to_string()))
    .collect();

    found.sort_by(|a, b| a.0.to_string().cmp(&b.0.to_string()).then(a.1.cmp(&b.1)));
    found
}

/// The `*_type` of a configured instance: the registry key that its setup
/// command needs to reconfigure it. `None` when `id` names nothing.
pub(crate) fn type_name<'a>(kind: RefKind, id: &str, config: &'a Config) -> Option<&'a str> {
    config_entry(config, kind, id).map(Validatable::type_name)
}

impl std::fmt::Display for RefKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            RefKind::Launcher => "launcher",
            RefKind::Capability => "capability",
            RefKind::Model => "model",
            RefKind::Provider => "provider",
        };
        f.write_str(s)
    }
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (kind, id) = &self.target;
        match &self.referrer {
            Some((referrer_kind, referrer_id)) => write!(
                f,
                "{referrer_kind} '{referrer_id}' depends on {kind} '{id}', which "
            )?,
            None => write!(f, "{kind} '{id}' ")?,
        }
        match &self.problem {
            Problem::NotConfigured => write!(f, "is not configured"),
            Problem::UnknownType { type_name } => {
                write!(f, "has an unknown {kind} type '{type_name}'")
            }
            Problem::MissingDependency { config_key } => {
                write!(f, "is missing required dependency '{config_key}'")
            }
        }
    }
}

impl std::error::Error for ValidationError {}

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

/// What the walk needs from a configured instance: the name of its
/// implementation type, whether that name is registered, and the ids it
/// points at. Everything else about validating an instance is the same for
/// every kind and lives in [`validate`].
trait Validatable: ConfigId {
    /// The `*_type` field: the registry key this instance was configured
    /// from.
    fn type_name(&self) -> &str;

    /// Whether [`Self::type_name`] is a key in this kind's registry.
    fn type_is_registered(&self) -> bool;

    /// The instances this one points at, for the walk to follow.
    ///
    /// The error is for an instance that cannot name its references at all,
    /// such as a model with no provider. That is a problem with this
    /// instance rather than with anything it points at.
    fn refs(&self) -> Result<Vec<(RefKind, &str)>, Problem>;
}

/// Reaching the four maps by [`RefKind`] rather than by name. These live with
/// the walk because [`Validatable`] and [`RefKind`] are the only reason to
/// want them. The arms spell the four fields out because the maps have four
/// different value types and `kind` is only known at run time.
fn config_entry<'a>(config: &'a Config, kind: RefKind, id: &str) -> Option<&'a dyn Validatable> {
    match kind {
        RefKind::Launcher => lookup(&config.launchers, id),
        RefKind::Capability => lookup(&config.capabilities, id),
        RefKind::Model => lookup(&config.models, id),
        RefKind::Provider => lookup(&config.providers, id),
    }
}

fn config_entries(config: &Config, kind: RefKind) -> Vec<&dyn Validatable> {
    match kind {
        RefKind::Launcher => erase(&config.launchers),
        RefKind::Capability => erase(&config.capabilities),
        RefKind::Model => erase(&config.models),
        RefKind::Provider => erase(&config.providers),
    }
}

/// One entry of a single kind's map, as the walk sees it.
fn lookup<'a, T: Validatable>(
    map: &'a HashMap<String, T>,
    id: &str,
) -> Option<&'a dyn Validatable> {
    map.get(id).map(|entry| entry as &dyn Validatable)
}

/// Every entry of a single kind's map, as the walk sees it.
fn erase<T: Validatable>(map: &HashMap<String, T>) -> Vec<&dyn Validatable> {
    map.values()
        .map(|entry| entry as &dyn Validatable)
        .collect()
}

/// The recursive body of [`validate_ref`], and the whole of what validating
/// one instance means: it is configured, its type name resolves, and every id
/// it points at validates in turn.
///
/// `referrer` is the instance whose reference brought the walk here, and
/// rides along so that a failure names the instance a caller would act on
/// rather than only the missing thing.
fn validate(
    kind: RefKind,
    id: &str,
    config: &Config,
    referrer: Option<(RefKind, &str)>,
) -> Result<(), ValidationError> {
    let entry = config_entry(config, kind, id)
        .ok_or_else(|| err(kind, id, Problem::NotConfigured, referrer))?;

    if !entry.type_is_registered() {
        return Err(err(
            kind,
            id,
            Problem::UnknownType {
                type_name: entry.type_name().to_string(),
            },
            referrer,
        ));
    }

    let refs = entry
        .refs()
        .map_err(|problem| err(kind, id, problem, referrer))?;

    for (target_kind, target_id) in refs {
        validate(target_kind, target_id, config, Some((kind, id)))?;
    }
    Ok(())
}

impl Validatable for LauncherConfig {
    fn type_name(&self) -> &str {
        &self.launcher_type
    }

    fn type_is_registered(&self) -> bool {
        crate::launchers::LAUNCHER_REGISTRY
            .get(&self.launcher_type)
            .is_some()
    }

    fn refs(&self) -> Result<Vec<(RefKind, &str)>, Problem> {
        Ok(self
            .enabled_capabilities
            .iter()
            .map(|id| (RefKind::Capability, id.as_str()))
            .collect())
    }
}

impl Validatable for CapabilityConfig {
    fn type_name(&self) -> &str {
        &self.capability_type
    }

    fn type_is_registered(&self) -> bool {
        crate::capabilities::CAPABILITY_REGISTRY
            .get(&self.capability_type)
            .is_some()
    }

    /// A capability stores its dependency ids inside its own config JSON, and
    /// only its type's static metadata says which keys hold them. The walk
    /// has already established that the type resolves, so the error here is
    /// for a direct caller.
    fn refs(&self) -> Result<Vec<(RefKind, &str)>, Problem> {
        let metadata = crate::capabilities::CAPABILITY_REGISTRY
            .get(&self.capability_type)
            .ok_or_else(|| Problem::UnknownType {
                type_name: self.capability_type.clone(),
            })?;
        dependency_refs(&self.config, &metadata.dependencies)
    }
}

impl Validatable for ModelConfig {
    fn type_name(&self) -> &str {
        &self.model_type
    }

    fn type_is_registered(&self) -> bool {
        crate::models::MODEL_REGISTRY
            .get(&self.model_type)
            .is_some()
    }

    /// `provider_id` is required, so a model always names a provider. Whether
    /// that name resolves is the walk's business, like any other reference.
    fn refs(&self) -> Result<Vec<(RefKind, &str)>, Problem> {
        Ok(vec![(RefKind::Provider, &self.provider_id)])
    }
}

impl Validatable for ProviderConfig {
    fn type_name(&self) -> &str {
        &self.provider_type
    }

    fn type_is_registered(&self) -> bool {
        crate::providers::PROVIDER_REGISTRY
            .get(&self.provider_type)
            .is_some()
    }

    /// A provider references no other configured instance.
    fn refs(&self) -> Result<Vec<(RefKind, &str)>, Problem> {
        Ok(Vec::new())
    }
}

/// The ids a capability's config holds under its declared dependencies'
/// `config_key`s.
///
/// A dependency contributes a reference whenever it holds an id, whether or
/// not it is declared required, so a dangling optional dependency is walked
/// like any other. `required` governs only whether an absent value is itself
/// a problem: absent and required is a missing dependency, absent and
/// optional is a valid state with nothing to check. An id present but empty
/// counts as absent, which is the state `commands::setup` leaves behind when
/// no model was selected.
fn dependency_refs<'a>(
    capability_config: &'a serde_json::Value,
    dependencies: &[Dependency],
) -> Result<Vec<(RefKind, &'a str)>, Problem> {
    let mut refs = Vec::new();

    for dependency in dependencies {
        let (kind, config_key, required) = match dependency {
            Dependency::Model {
                config_key,
                required,
                ..
            } => (RefKind::Model, config_key, *required),
            Dependency::Provider {
                config_key,
                required,
                ..
            } => (RefKind::Provider, config_key, *required),
            // An external tool is a shell command, not a configured instance.
            Dependency::ExternalTool { .. } => continue,
        };

        let id = capability_config
            .get(config_key)
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();

        if id.is_empty() {
            if required {
                return Err(Problem::MissingDependency {
                    config_key: config_key.clone(),
                });
            }
            continue;
        }

        refs.push((kind, id));
    }

    Ok(refs)
}

fn err(
    kind: RefKind,
    id: &str,
    problem: Problem,
    referrer: Option<(RefKind, &str)>,
) -> ValidationError {
    ValidationError {
        target: (kind, id.to_string()),
        problem,
        referrer: referrer.map(|(k, i)| (k, i.to_string())),
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capabilities::{ModelRequirement, ShellCommandRequirement};

    fn provider(id: &str, provider_type: &str) -> ProviderConfig {
        ProviderConfig {
            provider_id: id.to_string(),
            provider_type: provider_type.to_string(),
            config: serde_json::json!({}),
        }
    }

    fn model(id: &str, model_type: &str, provider_id: Option<&str>) -> ModelConfig {
        ModelConfig {
            model_id: id.to_string(),
            model_type: model_type.to_string(),
            provider_id: provider_id.unwrap_or("ollama").to_string(),
            variant: None,
            config: serde_json::json!({}),
        }
    }

    fn capability(id: &str, capability_type: &str, model_id: &str) -> CapabilityConfig {
        CapabilityConfig {
            capability_id: id.to_string(),
            capability_type: capability_type.to_string(),
            config: serde_json::json!({ "model_id": model_id }),
        }
    }

    fn launcher(id: &str, launcher_type: &str, enabled: &[&str]) -> LauncherConfig {
        LauncherConfig {
            launcher_id: id.to_string(),
            launcher_type: launcher_type.to_string(),
            enabled_capabilities: enabled.iter().map(|s| s.to_string()).collect(),
            config: serde_json::json!({}),
        }
    }

    /// A configuration in which every reference resolves: launcher `claude`
    /// enables capability `chat`, which uses model `m1`, which uses provider
    /// `p1`.
    fn healthy() -> Config {
        let mut config = Config::default();
        config
            .providers
            .insert("p1".into(), provider("p1", "ollama"));
        config
            .models
            .insert("m1".into(), model("m1", "custom", Some("p1")));
        config
            .capabilities
            .insert("chat".into(), capability("chat", "agent-model", "m1"));
        config
            .launchers
            .insert("claude".into(), launcher("claude", "claude", &["chat"]));
        config
    }

    #[test]
    fn healthy_instance_of_each_kind_passes() {
        let config = healthy();
        for (kind, id) in [
            (RefKind::Provider, "p1"),
            (RefKind::Model, "m1"),
            (RefKind::Capability, "chat"),
            (RefKind::Launcher, "claude"),
        ] {
            assert!(
                validate_ref(kind, id, &config).is_ok(),
                "{kind} '{id}' should validate"
            );
        }
    }

    #[test]
    fn unconfigured_instance_of_each_kind_fails() {
        let config = healthy();
        for kind in [
            RefKind::Provider,
            RefKind::Model,
            RefKind::Capability,
            RefKind::Launcher,
        ] {
            let err = validate_ref(kind, "nope", &config).expect_err("should fail");
            assert_eq!(err.problem, Problem::NotConfigured);
            assert_eq!(err.target, (kind, "nope".to_string()));
            assert_eq!(err.referrer, None);
        }
    }

    #[test]
    fn dangling_instance_of_each_kind_fails_while_the_healthy_one_passes() {
        let mut config = healthy();
        config
            .models
            .insert("m-broken".into(), model("m-broken", "custom", Some("gone")));
        config.capabilities.insert(
            "cap-broken".into(),
            capability("cap-broken", "agent-model", "gone"),
        );
        config.launchers.insert(
            "launcher-broken".into(),
            launcher("launcher-broken", "claude", &["gone"]),
        );

        assert!(validate_ref(RefKind::Model, "m1", &config).is_ok());
        assert!(validate_ref(RefKind::Model, "m-broken", &config).is_err());
        assert!(validate_ref(RefKind::Capability, "chat", &config).is_ok());
        assert!(validate_ref(RefKind::Capability, "cap-broken", &config).is_err());
        assert!(validate_ref(RefKind::Launcher, "claude", &config).is_ok());
        assert!(validate_ref(RefKind::Launcher, "launcher-broken", &config).is_err());
    }

    #[test]
    fn walk_recurses_from_launcher_to_the_missing_provider() {
        let mut config = healthy();
        config.providers.remove("p1");

        let err = validate_ref(RefKind::Launcher, "claude", &config).expect_err("should fail");

        // The walk reached the provider rather than stopping at the launcher
        // or the capability, both of which are themselves configured.
        assert_eq!(err.target, (RefKind::Provider, "p1".to_string()));
        assert_eq!(err.problem, Problem::NotConfigured);
        // And it names the model as what to act on, not the launcher that
        // started the walk.
        assert_eq!(err.referrer, Some((RefKind::Model, "m1".to_string())));
    }

    #[test]
    fn error_names_the_capability_holding_a_missing_model() {
        let mut config = healthy();
        config.models.remove("m1");

        let err = validate_ref(RefKind::Launcher, "claude", &config).expect_err("should fail");

        assert_eq!(err.target, (RefKind::Model, "m1".to_string()));
        assert_eq!(
            err.referrer,
            Some((RefKind::Capability, "chat".to_string()))
        );
        assert_eq!(
            err.to_string(),
            "capability 'chat' depends on model 'm1', which is not configured"
        );
    }

    #[test]
    fn an_unknown_type_name_fails_for_each_kind() {
        let mut config = healthy();
        config
            .providers
            .insert("p-bad".into(), provider("p-bad", "not-a-provider"));
        config
            .models
            .insert("m-bad".into(), model("m-bad", "not-a-model", Some("p1")));
        config.capabilities.insert(
            "cap-bad".into(),
            capability("cap-bad", "not-a-capability", "m1"),
        );
        config.launchers.insert(
            "launcher-bad".into(),
            launcher("launcher-bad", "not-a-launcher", &[]),
        );

        for (kind, id, type_name) in [
            (RefKind::Provider, "p-bad", "not-a-provider"),
            (RefKind::Model, "m-bad", "not-a-model"),
            (RefKind::Capability, "cap-bad", "not-a-capability"),
            (RefKind::Launcher, "launcher-bad", "not-a-launcher"),
        ] {
            let err = validate_ref(kind, id, &config).expect_err("should fail");
            assert_eq!(
                err.problem,
                Problem::UnknownType {
                    type_name: type_name.to_string()
                },
                "{kind} '{id}'"
            );
        }
    }

    #[test]
    fn an_optional_dependency_contributes_a_ref_only_when_it_holds_an_id() {
        // No capability type declares an optional dependency today, so the
        // dependency list is supplied directly rather than through a type.
        let optional = |key: &str| {
            vec![Dependency::Model {
                config_key: key.to_string(),
                requirement: ModelRequirement::default(),
                resolved_id: None,
                required: false,
            }]
        };

        // Absent: nothing to check.
        assert_eq!(
            dependency_refs(&serde_json::json!({}), &optional("model_id")),
            Ok(vec![])
        );
        // Present but empty counts as absent.
        assert_eq!(
            dependency_refs(
                &serde_json::json!({ "model_id": "" }),
                &optional("model_id")
            ),
            Ok(vec![])
        );
        // Present: walked like any other reference, whether or not it
        // resolves. `gone` is not configured, and the walk is what reports
        // that.
        assert_eq!(
            dependency_refs(
                &serde_json::json!({ "model_id": "m1" }),
                &optional("model_id")
            ),
            Ok(vec![(RefKind::Model, "m1")])
        );
        assert_eq!(
            dependency_refs(
                &serde_json::json!({ "model_id": "gone" }),
                &optional("model_id")
            ),
            Ok(vec![(RefKind::Model, "gone")])
        );
    }

    #[test]
    fn an_absent_required_dependency_is_a_missing_dependency() {
        let required = vec![Dependency::Model {
            config_key: "model_id".to_string(),
            requirement: ModelRequirement::default(),
            resolved_id: None,
            required: true,
        }];

        assert_eq!(
            dependency_refs(&serde_json::json!({}), &required),
            Err(Problem::MissingDependency {
                config_key: "model_id".to_string()
            })
        );

        let rendered = err(
            RefKind::Capability,
            "cap",
            Problem::MissingDependency {
                config_key: "model_id".to_string(),
            },
            None,
        );
        assert_eq!(
            rendered.to_string(),
            "capability 'cap' is missing required dependency 'model_id'"
        );
    }

    #[test]
    fn a_capabilitys_own_problem_names_the_instance_that_reached_it() {
        let mut config = healthy();
        // `agent-model` requires a model id, and `setup` leaves an empty
        // string behind when none was selected.
        config
            .capabilities
            .insert("chat".into(), capability("chat", "agent-model", ""));

        let err = validate_ref(RefKind::Launcher, "claude", &config).expect_err("should fail");

        assert_eq!(err.target, (RefKind::Capability, "chat".to_string()));
        assert_eq!(
            err.problem,
            Problem::MissingDependency {
                config_key: "model_id".to_string()
            }
        );
        assert_eq!(
            err.referrer,
            Some((RefKind::Launcher, "claude".to_string()))
        );
        assert_eq!(
            err.to_string(),
            "launcher 'claude' depends on capability 'chat', \
             which is missing required dependency 'model_id'"
        );
    }

    #[test]
    fn an_external_tool_dependency_is_not_a_config_reference() {
        let deps = vec![Dependency::ExternalTool {
            requirement: ShellCommandRequirement {
                command: "ffmpeg".to_string(),
            },
            required: true,
        }];
        assert_eq!(dependency_refs(&serde_json::json!({}), &deps), Ok(vec![]));
    }

    #[test]
    fn find_dangling_returns_exactly_the_broken_instances_of_a_kind() {
        let mut config = healthy();
        config.models.insert(
            "m-no-provider".into(),
            model("m-no-provider", "custom", None),
        );
        config
            .models
            .insert("m-gone".into(), model("m-gone", "custom", Some("gone")));
        config
            .models
            .insert("m-bad-type".into(), model("m-bad-type", "nope", Some("p1")));

        let mut broken: Vec<String> = find_dangling(RefKind::Model, &config)
            .into_iter()
            .map(|d| d.instance_id)
            .collect();
        broken.sort();
        assert_eq!(broken, ["m-bad-type", "m-gone", "m-no-provider"]);

        assert!(find_dangling(RefKind::Provider, &config).is_empty());
        assert_eq!(find_dangling(RefKind::Capability, &config).len(), 0);
    }

    #[test]
    fn find_dangling_returns_nothing_for_a_healthy_config() {
        let config = healthy();
        for kind in [
            RefKind::Provider,
            RefKind::Model,
            RefKind::Capability,
            RefKind::Launcher,
        ] {
            assert!(find_dangling(kind, &config).is_empty(), "{kind}");
        }
    }

    #[test]
    fn find_dangling_only_reports_the_kind_it_was_asked_about() {
        let mut config = healthy();
        // Breaking the provider breaks the model, the capability and the
        // launcher that reach it, but each scan reports only its own kind.
        config.providers.remove("p1");

        for (kind, expected) in [
            (RefKind::Provider, Vec::<&str>::new()),
            (RefKind::Model, vec!["m1"]),
            (RefKind::Capability, vec!["chat"]),
            (RefKind::Launcher, vec!["claude"]),
        ] {
            let found: Vec<String> = find_dangling(kind, &config)
                .into_iter()
                .map(|d| d.instance_id)
                .collect();
            assert_eq!(found, expected, "{kind}");
            assert!(find_dangling(kind, &config).iter().all(|d| d.kind == kind));
        }
    }

    #[test]
    fn dependents_are_the_instances_pointing_at_the_target() {
        let config = healthy();

        assert_eq!(
            dependents(RefKind::Provider, "p1", &config),
            vec![(RefKind::Model, "m1".to_string())]
        );
        assert_eq!(
            dependents(RefKind::Model, "m1", &config),
            vec![(RefKind::Capability, "chat".to_string())]
        );
        assert_eq!(
            dependents(RefKind::Capability, "chat", &config),
            vec![(RefKind::Launcher, "claude".to_string())]
        );
        // Nothing points at a launcher, and nothing points at what is not
        // configured.
        assert!(dependents(RefKind::Launcher, "claude", &config).is_empty());
        assert!(dependents(RefKind::Model, "gone", &config).is_empty());
    }

    #[test]
    fn dependents_lists_every_referrer_of_one_target() {
        let mut config = healthy();
        config
            .capabilities
            .insert("second".into(), capability("second", "agent-model", "m1"));

        assert_eq!(
            dependents(RefKind::Model, "m1", &config),
            vec![
                (RefKind::Capability, "chat".to_string()),
                (RefKind::Capability, "second".to_string()),
            ]
        );
    }

    #[test]
    fn find_dangling_reports_the_rendered_reason() {
        let mut config = healthy();
        config.providers.remove("p1");

        let dangling = find_dangling(RefKind::Model, &config);
        assert_eq!(dangling.len(), 1);
        assert_eq!(dangling[0].kind, RefKind::Model);
        assert_eq!(dangling[0].instance_id, "m1");
        assert_eq!(
            dangling[0].reason,
            "model 'm1' depends on provider 'p1', which is not configured"
        );
    }
}