cctop 0.28.0

An htop-like terminal monitor for AI coding agent sessions on Linux (Claude Code, Codex, Cursor, Devin, Gemini CLI, OpenCode, Pi, Windsurf)
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
//! Where each skill, agent and MCP server a session was offered is defined,
//! and whether it is still switched on.
//!
//! The transcript says what a session was given (see
//! [`crate::session::Loadout`]). It cannot say where that came from, and a
//! finding that says "remove it" without naming the file is a chore handed back
//! to the reader. So this reads Claude Code's configuration — `~/.claude.json`,
//! the settings files, `.mcp.json`, the skills and agents directories, the
//! installed plugins — and answers one question per name: which file would you
//! edit to stop loading it?
//!
//! It also answers the question the old transcripts cannot: is it *still*
//! loaded? A server somebody disabled last week is in fifty transcripts from
//! before then, and reporting it again would be telling them to do what they
//! already did.
//!
//! # Read-only, and names only
//!
//! Nothing here writes. And nothing here keeps a value: an MCP entry can carry
//! an API key in `env` or a bearer token in `headers`, so the only things that
//! leave this module are server names and file paths. The configuration is
//! parsed into the few sets of names the resolvers need and then dropped.
//!
//! ponytail: one profile. Sessions run under another `CLAUDE_CONFIG_DIR` are
//! resolved against this one's files, where their skills and servers are
//! usually not found — and something not found is never reported, so the
//! mistake can only be silence.

use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::session::mcp_server_key;

/// Where Claude Code keeps its configuration.
#[derive(Debug, Clone)]
pub struct Roots {
    /// The account file: `~/.claude.json`, or `.claude.json` inside
    /// `$CLAUDE_CONFIG_DIR` when that is set. User-wide and per-project MCP
    /// servers live here, not in `settings.json`.
    pub account: PathBuf,
    /// `~/.claude`, or `$CLAUDE_CONFIG_DIR`.
    pub claude_dir: PathBuf,
}

impl Roots {
    /// This machine's.
    pub fn here() -> Roots {
        let claude_dir = crate::config::CLAUDE_CONFIG_DIR.clone();
        // With the variable set, Claude Code keeps its account file inside that
        // directory rather than beside it — see `config::argv_under_profile`.
        let account = match crate::config::env_dir("CLAUDE_CONFIG_DIR") {
            Some(dir) => dir.join(".claude.json"),
            None => crate::config::HOME.join(".claude.json"),
        };
        Roots {
            account,
            claude_dir,
        }
    }
}

/// The file, directory or switch that would stop something loading.
///
/// What findings are grouped by, because it is the unit somebody acts on: one
/// edit to one file, however many names are in it.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Source {
    /// `mcpServers` at the top of the account file: every session, everywhere.
    McpUser(PathBuf),
    /// `projects.<dir>.mcpServers` in the account file: one directory, only
    /// for whoever owns this machine.
    McpLocal { account: PathBuf, project: String },
    /// A project's `.mcp.json`, which is checked in and shared with everybody
    /// who clones it.
    McpProject(PathBuf),
    /// A connector on the claude.ai account, which Claude Code picks up too.
    Connector,
    /// A plugin, by name. Its skills, agents and servers come and go together.
    Plugin(String),
    /// A skills directory, user-wide or a project's.
    Skills(PathBuf),
    /// An agents directory, likewise.
    Agents(PathBuf),
    /// Skills synced down from claude.ai rather than kept on this machine.
    SyncedSkills,
}

/// What a name resolves to for a session in one directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolved {
    At(Source),
    /// Defined, and switched off since. Not loaded now, so not reported.
    Disabled,
    /// Built into Claude Code, managed by an administrator, passed on the
    /// command line, or deleted since — nothing a finding can point at.
    Unknown,
}

/// One project's configuration, as far as the resolvers need it.
#[derive(Debug, Default)]
struct Project {
    /// `projects.<dir>.mcpServers` keys, by [`mcp_server_key`].
    local: HashSet<String>,
    /// `<dir>/.mcp.json` keys, by [`mcp_server_key`] -> the key as written,
    /// which is what `disabledMcpjsonServers` lists.
    mcp_json: HashMap<String, String>,
    /// `disabledMcpServers`, which switches off any server in this directory,
    /// whatever defined it. Holds display names, keyed.
    disabled: HashSet<String>,
    /// `disabledMcpjsonServers`, from the account file and every settings file
    /// that applies here.
    disabled_json: HashSet<String>,
    skills: HashSet<String>,
    agents: HashSet<String>,
    /// `enabledPlugins` as the project's own settings override it.
    plugins: HashMap<String, bool>,
}

/// Every definition the resolvers can find, read once.
#[derive(Debug, Default)]
pub struct Inventory {
    account: PathBuf,
    claude_dir: PathBuf,
    user_mcp: HashSet<String>,
    user_skills: HashSet<String>,
    user_agents: HashSet<String>,
    /// Skill names synced from claude.ai.
    synced_skills: HashSet<String>,
    /// Installed or synced plugins, by name -> the `name@marketplace` key
    /// `enabledPlugins` uses, where one is known.
    plugins: HashMap<String, Option<String>>,
    /// `enabledPlugins` from the user's settings.
    user_plugins: HashMap<String, bool>,
    projects: HashMap<String, Project>,
}

fn read_json(path: &Path) -> Option<Value> {
    let text = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&text).ok()
}

/// The keys of an object, which for a server map are the server names.
/// Only the keys: the values are where the secrets are.
fn keys_of(v: Option<&Value>) -> impl Iterator<Item = &str> {
    v.and_then(Value::as_object).into_iter().flat_map(|m| {
        m.iter()
            .filter(|(_, cfg)| cfg.is_object())
            .map(|(k, _)| k.as_str())
    })
}

fn strings_of(v: Option<&Value>) -> impl Iterator<Item = &str> {
    v.and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
}

/// `enabledPlugins`, keyed by plugin name as well as by its full key, since a
/// listing spells a plugin's skills by the bare name.
fn plugin_switches(settings: &Value) -> HashMap<String, bool> {
    let mut out = HashMap::new();
    if let Some(map) = settings.get("enabledPlugins").and_then(Value::as_object) {
        for (key, on) in map {
            if let Some(on) = on.as_bool() {
                let name = key.split('@').next().unwrap_or(key);
                out.insert(name.to_string(), on);
            }
        }
    }
    out
}

/// Skill names in a skills directory, as the listing spells them.
fn skill_names(dir: &Path) -> HashSet<String> {
    crate::access::skills(dir)
        .into_iter()
        .map(|s| s.name)
        .collect()
}

/// Agent names in an agents directory: the front matter's `name:`, else the
/// file's stem, which is what Claude Code falls back to.
fn agent_names(dir: &Path) -> HashSet<String> {
    let mut out = HashSet::new();
    for entry in crate::config::list_dir(dir) {
        let Some(stem) = entry.strip_suffix(".md") else {
            continue;
        };
        let named = crate::util::read_head(&dir.join(&entry), 4096).and_then(|text| {
            text.lines()
                .take(20)
                .find_map(|l| l.strip_prefix("name:").map(|v| v.trim().to_string()))
        });
        out.insert(named.unwrap_or_else(|| stem.to_string()));
    }
    out
}

impl Inventory {
    /// Read the configuration that applies to sessions in `cwds`.
    pub fn load<'a>(roots: &Roots, cwds: impl IntoIterator<Item = &'a str>) -> Inventory {
        let account = read_json(&roots.account).unwrap_or(Value::Null);
        let user_settings =
            read_json(&roots.claude_dir.join("settings.json")).unwrap_or(Value::Null);
        let skills_dir = roots.claude_dir.join("skills");

        let mut inv = Inventory {
            account: roots.account.clone(),
            claude_dir: roots.claude_dir.clone(),
            user_mcp: keys_of(account.get("mcpServers"))
                .map(mcp_server_key)
                .collect(),
            user_skills: skill_names(&skills_dir),
            user_agents: agent_names(&roots.claude_dir.join("agents")),
            user_plugins: plugin_switches(&user_settings),
            ..Inventory::default()
        };

        // Synced skills sit one level further down, under the organisation
        // that provides them.
        let synced = skills_dir.join("synced");
        for org in crate::config::list_dir(&synced) {
            inv.synced_skills.extend(skill_names(&synced.join(org)));
        }

        let plugins_dir = roots.claude_dir.join("plugins");
        if let Some(installed) = read_json(&plugins_dir.join("installed_plugins.json"))
            && let Some(map) = installed.get("plugins").and_then(Value::as_object)
        {
            for key in map.keys() {
                let name = key.split('@').next().unwrap_or(key);
                inv.plugins.insert(name.to_string(), Some(key.clone()));
            }
        }
        // A synced plugin's directory may carry a generation suffix,
        // `modern-web-guidance~g2`, which its skills' names do not.
        let synced = plugins_dir.join("synced");
        for org in crate::config::list_dir(&synced) {
            for entry in crate::config::list_dir(&synced.join(&org)) {
                if synced.join(&org).join(&entry).is_dir() {
                    let name = entry.split('~').next().unwrap_or(&entry);
                    inv.plugins.entry(name.to_string()).or_insert(None);
                }
            }
        }

        let user_disabled_json: Vec<&str> =
            strings_of(user_settings.get("disabledMcpjsonServers")).collect();
        for cwd in cwds {
            if cwd.is_empty() || inv.projects.contains_key(cwd) {
                continue;
            }
            let dir = Path::new(cwd);
            let entry = account.get("projects").and_then(|p| p.get(cwd));
            let settings: Vec<Value> = ["settings.json", "settings.local.json"]
                .iter()
                .filter_map(|f| read_json(&dir.join(".claude").join(f)))
                .collect();
            let mcp_json = read_json(&dir.join(".mcp.json"));
            let mut project = Project {
                local: keys_of(entry.and_then(|e| e.get("mcpServers")))
                    .map(mcp_server_key)
                    .collect(),
                // A `.mcp.json` may or may not wrap its servers in
                // `mcpServers`, the same as `access::mcp_from_json` reads it.
                mcp_json: mcp_json
                    .as_ref()
                    .map(|v| keys_of(Some(v.get("mcpServers").unwrap_or(v))))
                    .into_iter()
                    .flatten()
                    .map(|k| (mcp_server_key(k), k.to_string()))
                    .collect(),
                disabled: strings_of(entry.and_then(|e| e.get("disabledMcpServers")))
                    .map(mcp_server_key)
                    .collect(),
                disabled_json: strings_of(entry.and_then(|e| e.get("disabledMcpjsonServers")))
                    .chain(user_disabled_json.iter().copied())
                    .map(str::to_string)
                    .collect(),
                skills: skill_names(&dir.join(".claude").join("skills")),
                agents: agent_names(&dir.join(".claude").join("agents")),
                plugins: HashMap::new(),
            };
            for s in &settings {
                project
                    .disabled_json
                    .extend(strings_of(s.get("disabledMcpjsonServers")).map(str::to_string));
                // Local after shared, so the personal override wins.
                project.plugins.extend(plugin_switches(s));
            }
            inv.projects.insert(cwd.to_string(), project);
        }
        inv
    }

    fn project(&self, cwd: &str) -> Option<&Project> {
        self.projects.get(cwd)
    }

    /// The plugin a prefixed name belongs to, and whether it is switched off
    /// for `cwd`.
    fn plugin(&self, cwd: &str, name: &str) -> Resolved {
        if !self.plugins.contains_key(name) {
            return Resolved::Unknown;
        }
        let on = self
            .project(cwd)
            .and_then(|p| p.plugins.get(name))
            .or_else(|| self.user_plugins.get(name))
            .copied();
        match on {
            Some(false) => Resolved::Disabled,
            _ => Resolved::At(Source::Plugin(name.to_string())),
        }
    }

    /// Where the MCP server `server` (as its tool names spell it) comes from,
    /// for a session in `cwd`.
    ///
    /// Claude Code's own precedence: a local definition shadows the project's,
    /// which shadows the user's.
    pub fn mcp(&self, cwd: &str, server: &str) -> Resolved {
        let project = self.project(cwd);
        if project.is_some_and(|p| p.disabled.contains(server)) {
            return Resolved::Disabled;
        }
        if project.is_some_and(|p| p.local.contains(server)) {
            return Resolved::At(Source::McpLocal {
                account: self.account.clone(),
                project: cwd.to_string(),
            });
        }
        if let Some(p) = project
            && let Some(key) = p.mcp_json.get(server)
        {
            if p.disabled_json.contains(key) {
                return Resolved::Disabled;
            }
            let file = Path::new(cwd).join(".mcp.json");
            return Resolved::At(Source::McpProject(PathBuf::from(super::checkout_path(
                &file.to_string_lossy(),
            ))));
        }
        if self.user_mcp.contains(server) {
            return Resolved::At(Source::McpUser(self.account.clone()));
        }
        if server.starts_with("claude_ai_") {
            return Resolved::At(Source::Connector);
        }
        // `plugin_<plugin>_<server>`, where either half may hold underscores
        // of its own — so it is matched against the plugins that exist rather
        // than split.
        if let Some(rest) = server.strip_prefix("plugin_") {
            let mut names: Vec<&String> = self
                .plugins
                .keys()
                .filter(|p| rest.starts_with(&format!("{}_", mcp_server_key(p))))
                .collect();
            names.sort_by_key(|p| std::cmp::Reverse(p.len()));
            if let Some(name) = names.first() {
                return self.plugin(cwd, name);
            }
        }
        Resolved::Unknown
    }

    /// Where the skill `name` comes from, for a session in `cwd`.
    pub fn skill(&self, cwd: &str, name: &str) -> Resolved {
        if let Some((prefix, bare)) = name.split_once(':') {
            return match self.plugin(cwd, prefix) {
                Resolved::Unknown if self.synced_skills.contains(bare) => {
                    Resolved::At(Source::SyncedSkills)
                }
                other => other,
            };
        }
        if self.project(cwd).is_some_and(|p| p.skills.contains(name)) {
            let dir = Path::new(cwd).join(".claude").join("skills");
            return Resolved::At(Source::Skills(PathBuf::from(super::checkout_path(
                &dir.to_string_lossy(),
            ))));
        }
        if self.user_skills.contains(name) {
            return Resolved::At(Source::Skills(self.claude_dir.join("skills")));
        }
        Resolved::Unknown
    }

    /// Where the agent type `name` comes from, for a session in `cwd`.
    pub fn agent(&self, cwd: &str, name: &str) -> Resolved {
        if let Some((prefix, _)) = name.split_once(':') {
            return self.plugin(cwd, prefix);
        }
        if self.project(cwd).is_some_and(|p| p.agents.contains(name)) {
            let dir = Path::new(cwd).join(".claude").join("agents");
            return Resolved::At(Source::Agents(PathBuf::from(super::checkout_path(
                &dir.to_string_lossy(),
            ))));
        }
        if self.user_agents.contains(name) {
            return Resolved::At(Source::Agents(self.claude_dir.join("agents")));
        }
        Resolved::Unknown
    }

    /// The `enabledPlugins` key for a plugin, where one is known.
    pub fn plugin_key(&self, name: &str) -> Option<&str> {
        self.plugins.get(name).and_then(|k| k.as_deref())
    }

    /// The user settings file, for a remedy that names it.
    pub fn user_settings(&self) -> PathBuf {
        self.claude_dir.join("settings.json")
    }
}

/// A configuration root of its own, so no test reads the real one.
///
/// `Roots` is the only seam into this module, so a directory tree under a
/// `TempDir` is a whole Claude Code installation as far as the resolvers are
/// concerned.
#[cfg(test)]
pub(crate) struct Machine {
    dir: tempfile::TempDir,
}

#[cfg(test)]
impl Machine {
    pub(crate) fn new() -> Machine {
        Machine {
            dir: tempfile::tempdir().unwrap(),
        }
    }

    pub(crate) fn path(&self, rel: &str) -> PathBuf {
        self.dir.path().join(rel)
    }

    pub(crate) fn write(&self, rel: &str, body: &str) {
        let p = self.path(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, body).unwrap();
    }

    pub(crate) fn roots(&self) -> Roots {
        Roots {
            account: self.path("home/.claude.json"),
            claude_dir: self.path("home/.claude"),
        }
    }

    /// A project directory inside the machine, as the loaders spell one.
    pub(crate) fn project(&self) -> String {
        self.path("work/app").to_string_lossy().into_owned()
    }
}

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

    /// Four levels, and the one that answers is not the one that defines it: a
    /// name the user switched off is nothing to point at, whichever file the
    /// definition is in.
    #[test]
    fn a_server_resolves_to_the_most_local_definition_that_defines_it() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude.json",
            &format!(
                r#"{{"mcpServers": {{"everywhere": {{"command": "x"}}, "shared": {{"command": "x"}}}},
                    "projects": {{"{project}": {{"mcpServers": {{"shared": {{"command": "x"}}}}}}}}}}"#
            ),
        );
        m.write(
            "work/app/.mcp.json",
            r#"{"mcpServers": {"shared": {"command": "x"}, "checked-in": {"command": "x"}}}"#,
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);

        // The project's own shadows the user's, so the file to edit is the
        // account file's project entry rather than its top-level list.
        assert_eq!(
            inv.mcp(&project, "shared"),
            Resolved::At(Source::McpLocal {
                account: m.path("home/.claude.json"),
                project: project.clone(),
            })
        );
        // `.mcp.json` shadows both for a name it alone defines.
        assert_eq!(
            inv.mcp(&project, "checked-in"),
            Resolved::At(Source::McpProject(PathBuf::from(format!(
                "{project}/.mcp.json"
            ))))
        );
        // And the user's is what is left.
        assert_eq!(
            inv.mcp(&project, "everywhere"),
            Resolved::At(Source::McpUser(m.path("home/.claude.json")))
        );
        assert_eq!(inv.mcp(&project, "never-configured"), Resolved::Unknown);
    }

    /// `disabledMcpServers` switches off a server wherever it was defined, so
    /// precedence must not decide it: a name that resolves to three files and is
    /// switched off in this one resolves to nothing.
    #[test]
    fn a_server_switched_off_for_a_project_is_not_defined_at_all() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude.json",
            &format!(
                r#"{{"mcpServers": {{"tracker": {{"command": "x"}}}},
                    "projects": {{"{project}": {{"disabledMcpServers": ["tracker"]}}}}}}"#
            ),
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(inv.mcp(&project, "tracker"), Resolved::Disabled);
        // …and only for that project: it is a directory's switch, not the user's.
        assert!(matches!(
            inv.mcp("/somewhere-else", "tracker"),
            Resolved::At(Source::McpUser(_))
        ));
    }

    /// A `.mcp.json` server switched off by name is the same refusal, and the
    /// name it is listed under is the one as written in the file rather than the
    /// key a tool name would use.
    #[test]
    fn a_project_server_switched_off_by_its_written_name_is_disabled() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "work/app/.mcp.json",
            r#"{"mcpServers": {"my.server": {"command": "x"}}}"#,
        );
        m.write(
            "work/app/.claude/settings.json",
            r#"{"disabledMcpjsonServers": ["my.server"]}"#,
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        // `my.server` keys as `my_server` in a tool name, and only the written
        // form is switched off.
        assert_eq!(inv.mcp(&project, "my_server"), Resolved::Disabled);
    }

    /// A plugin's servers arrive as `plugin_<plugin>_<server>`, and a plugin name
    /// may itself end in what the suffix looks like. The longest match wins, or
    /// `data-tools` would be read as the `data` plugin with a `tools` server.
    #[test]
    fn a_plugin_server_resolves_to_the_longest_plugin_name() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude/plugins/installed_plugins.json",
            r#"{"plugins": {"data@marketplace": {}, "data-tools@marketplace": {}}}"#,
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.mcp(&project, "plugin_data-tools_fetch_x"),
            Resolved::At(Source::Plugin("data-tools".into()))
        );
        assert_eq!(
            inv.mcp(&project, "plugin_data_fetch_x"),
            Resolved::At(Source::Plugin("data".into()))
        );
        // A server under a plugin that is not installed is nothing to point at.
        assert_eq!(inv.mcp(&project, "plugin_absent_fetch"), Resolved::Unknown);
    }

    /// A plugin switched off in the user's settings is off for every directory;
    /// a project that switches it back on is on for its own, because the
    /// project's own settings file is read last.
    #[test]
    fn a_projects_plugin_switch_wins_over_the_users() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude/plugins/installed_plugins.json",
            r#"{"plugins": {"web@marketplace": {}}}"#,
        );
        m.write(
            "home/.claude/settings.json",
            r#"{"enabledPlugins": {"web@marketplace": false}}"#,
        );
        m.write(
            "work/app/.claude/settings.local.json",
            r#"{"enabledPlugins": {"web@marketplace": true}}"#,
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.mcp(&project, "plugin_web_fetch"),
            Resolved::At(Source::Plugin("web".into()))
        );

        // With no project override it is the user's switch that decides.
        m.write("work/app/.claude/settings.local.json", "{}");
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(inv.mcp(&project, "plugin_web_fetch"), Resolved::Disabled);
    }

    /// A skill's name is prefixed by its plugin, and a prefix that is not a
    /// plugin on this machine is not a dead end: claude.ai syncs skills down
    /// without a plugin, and there is no file here to point at.
    #[test]
    fn a_synced_skill_is_reached_through_a_prefix_that_is_not_a_plugin() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude/skills/synced/org/guidance/SKILL.md",
            "---\nname: guidance\ndescription: how to\n---\n",
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.skill(&project, "claude.ai:guidance"),
            Resolved::At(Source::SyncedSkills)
        );
        // A prefix that is a plugin wins over the synced fallback.
        m.write(
            "home/.claude/plugins/installed_plugins.json",
            r#"{"plugins": {"org@marketplace": {}}}"#,
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.skill(&project, "org:guidance"),
            Resolved::At(Source::Plugin("org".into()))
        );
        // A name nothing knows is not a finding about a file.
        assert_eq!(inv.skill(&project, "nothing:absent"), Resolved::Unknown);
    }

    /// An unprefixed skill belongs to whichever directory has it, and the
    /// project's own shadows the user's — the same precedence the servers use.
    #[test]
    fn a_skills_directory_is_the_project_ones_or_the_users() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude/skills/everywhere/SKILL.md",
            "---\nname: everywhere\n---\n",
        );
        m.write(
            "work/app/.claude/skills/here/SKILL.md",
            "---\nname: here\n---\n",
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.skill(&project, "here"),
            Resolved::At(Source::Skills(PathBuf::from(format!(
                "{project}/.claude/skills"
            ))))
        );
        assert_eq!(
            inv.skill(&project, "everywhere"),
            Resolved::At(Source::Skills(m.path("home/.claude/skills")))
        );
        assert_eq!(inv.skill(&project, "neither"), Resolved::Unknown);
    }

    /// An agent's front matter names it; without one the file's stem is the name,
    /// which is the fallback Claude Code itself uses.
    #[test]
    fn an_agent_is_named_by_its_front_matter_or_its_file() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude/agents/reviewer.md",
            "---\nname: review\n---\n",
        );
        m.write("home/.claude/agents/planner.md", "no front matter here\n");
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.agent(&project, "review"),
            Resolved::At(Source::Agents(m.path("home/.claude/agents")))
        );
        assert_eq!(
            inv.agent(&project, "planner"),
            Resolved::At(Source::Agents(m.path("home/.claude/agents")))
        );
        assert_eq!(inv.agent(&project, "nobody"), Resolved::Unknown);
    }

    /// Nothing here keeps a value: a server entry can carry an API key in `env` or
    /// a bearer token in `headers`, and the module says the only things that
    /// leave it are names and paths. The answer for a user-wide server is the
    /// account file and nothing else, which is what makes that true rather than
    /// a promise.
    #[test]
    fn no_resolved_source_carries_a_secret() {
        let m = Machine::new();
        let project = m.project();
        m.write(
            "home/.claude.json",
            r#"{"mcpServers": {"tracker": {"command": "npx", "env": {"TOKEN": "sk-live-SECRET"}}}}"#,
        );
        let inv = Inventory::load(&m.roots(), [project.as_str()]);
        assert_eq!(
            inv.mcp(&project, "tracker"),
            Resolved::At(Source::McpUser(m.path("home/.claude.json")))
        );
    }
}