cctop 0.16.9

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
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
//! What an agent can reach: its instructions, skills, MCP servers and rules.
//!
//! A session's cost and its tool log say what it *did*. This says what it was
//! allowed to do and what was in scope while it did it — the CLAUDE.md it was
//! given, the skills on its path, the MCP servers wired into it, whether it asks
//! before writing, and whether cctop's own hooks are installed to hear about any
//! of it. Two questions people actually ask are answered only by this: "why did
//! it do that" (usually an instruction file nobody remembered was there) and
//! "what can it touch" (usually more than expected).
//!
//! # Why the data and the drawing are separate
//!
//! The terminal has shown most of this for a long time, in
//! [`crate::ui::panels`], as styled lines built straight from the filesystem.
//! A browser cannot use styled lines, and re-reading the same files a second
//! way is how two surfaces come to disagree about which MCP servers exist. So
//! the readers live here and return values; the panel renders them, and so does
//! [`crate::serve`].
//!
//! # It reports the files, not the truth
//!
//! Every harness resolves its own configuration, and none of them document the
//! whole of it. A settings file may be overridden by a flag on the command line,
//! an MCP server may have failed to start, a skill directory may hold something
//! the harness rejected. So this is deliberately phrased as "these are the files
//! that apply to a session in this directory", which is checkable, rather than
//! "this is what the agent has loaded", which is not. Where a harness keeps a
//! setting somewhere cctop cannot read — Windsurf's global rules live in the
//! editor's own settings UI — the entry says so instead of reporting nothing.

use crate::hook::{self, Health, Scope};
use crate::pricing::Provider;
use crate::session::{Session, SessionData};
use crate::util;
use serde::Serialize;
use serde_json::Value;
use std::path::{Path, PathBuf};

/// The most of an instruction file that is carried.
///
/// Enough to read a CLAUDE.md that someone forgot they wrote, and short of
/// shipping a whole repository's worth of prose to a phone.
const MAX_FILE_CHARS: usize = 8 * 1024;

/// The most skills listed.
const MAX_SKILLS: usize = 60;

/// The most distinct tools reported as used.
const MAX_TOOLS: usize = 30;

/// The most recently written paths listed.
const MAX_WRITES: usize = 20;

/// Everything in scope for one session.
#[derive(Debug, Default, Serialize)]
pub struct Access {
    /// The working directory as the transcript recorded it, spelled with `~`.
    pub cwd: String,
    /// Whether that directory is still there. A session whose checkout was
    /// deleted cannot be resumed into it, and this is why.
    pub cwd_exists: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    pub harness: String,
    pub model: String,
    /// How much this session asks before it acts, when something has said.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission: Option<String>,
    /// What that mode means, in a sentence, since the labels are terse and the
    /// difference between two of them is the whole safety story.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_detail: Option<&'static str>,
    /// PID of the live agent, when there is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    /// Instruction files that apply here, global first.
    pub instructions: Vec<FileRef>,
    /// Settings files that apply here.
    pub configs: Vec<FileRef>,
    /// The directories skills were read from, in precedence order. Only
    /// directories that exist are listed — a harness may offer several
    /// candidates and naming the ones that are not there is noise, not an
    /// answer. (Devin alone has five documented locations.)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub skills_dirs: Vec<String>,
    pub skills: Vec<Skill>,
    pub mcp: Vec<McpServer>,
    /// Whether cctop's own hooks are installed for this harness.
    pub hooks: Vec<HookState>,
    /// Tools this session has actually used, most-used first.
    pub tools: Vec<ToolCount>,
    /// Paths it wrote lately, newest first.
    pub writes: Vec<String>,
    /// A limit of this harness worth stating rather than leaving as a gap.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<&'static str>,
}

/// A file that shapes a session, whether or not it exists.
///
/// Absent files are listed too, and on purpose: "there is no project CLAUDE.md"
/// is the answer to a question people ask, and a list that silently omits it
/// cannot be told from one that never looked.
#[derive(Debug, Serialize)]
pub struct FileRef {
    /// Spelled with `~`, since the browser may not be on this machine.
    pub path: String,
    /// `user`, `project`, or `local` — the last for the personal `.local.`
    /// overrides a repository asks git to ignore.
    pub scope: &'static str,
    pub present: bool,
    pub bytes: u64,
    /// The head of it, capped at [`MAX_FILE_CHARS`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub head: Option<String>,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub clipped: bool,
}

#[derive(Debug, Serialize)]
pub struct Skill {
    pub name: String,
    pub description: String,
}

#[derive(Debug, Serialize)]
pub struct McpServer {
    pub name: String,
    /// `user`, `project`, or `local`, which is the difference between a server
    /// this machine gives every session, one this repository asked for, and
    /// one only this checkout's owner asked for.
    pub scope: &'static str,
    /// The command that starts it, when the config names one. A remote server
    /// configured by URL has none, and inventing one would be a lie about where
    /// the agent's tool calls are going.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
}

/// Whether cctop hears from this harness, per file it installs into.
#[derive(Debug, Serialize)]
pub struct HookState {
    pub harness: String,
    pub scope: &'static str,
    pub path: String,
    /// One word: `installed`, `absent`, `partial`, `other`, `broken`.
    pub state: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct ToolCount {
    pub name: String,
    pub count: u64,
}

/// Read everything in scope for `session`.
///
/// `data` is the extraction if the caller already has it — the tool counts come
/// from there and nowhere else. Absent, everything else is still reported: the
/// files on disk are the expensive half of the answer and they do not need it.
pub fn build(session: &Session, data: Option<&SessionData>) -> Access {
    let cwd = Path::new(&session.label_source);
    let has_cwd = !session.label_source.is_empty();
    let root = claude_root(session);

    let mut access = Access {
        cwd: util::tildify(&session.label_source),
        cwd_exists: has_cwd && cwd.is_dir(),
        branch: crate::ui::columns::branch_of(session),
        harness: session.surface.label(session.provider).to_string(),
        model: session.model.clone(),
        permission: session.permission.map(|p| p.label().to_string()),
        permission_detail: session.permission.map(describe_permission),
        pid: session.root_pid(),
        ..Access::default()
    };

    // A row from another machine names paths on that machine. Reading them here
    // would report whatever sits at the same path locally, which is the failure
    // `Session::remote` exists to prevent.
    if let Some(remote) = &session.remote {
        access.note = Some("this session is on another machine — run cctop serve there");
        access.branch = remote.branch.clone();
        return access;
    }

    let (instructions, configs, skills_dirs, note) = layout(session, &root);
    access.instructions = instructions
        .into_iter()
        .map(|(path, scope)| file_ref(&path, scope))
        .collect();
    access.configs = configs
        .into_iter()
        .map(|(path, scope)| file_ref(&path, scope))
        .collect();
    access.skills_dirs = skills_dirs
        .iter()
        .filter(|dir| dir.is_dir())
        .map(|dir| util::tildify(&dir.to_string_lossy()))
        .collect();
    access.skills = skills_dirs.iter().flat_map(|dir| skills(dir)).collect();
    access.mcp = mcp_servers(session, &root);
    access.hooks = hooks(session, cwd);
    access.note = note;

    if let Some(data) = data {
        let mut tools: Vec<ToolCount> = data
            .metrics
            .tools
            .iter()
            .map(|(name, count)| ToolCount {
                name: util::pretty_mcp_name(name),
                count: *count,
            })
            .collect();
        // Most-used first, then by name, so a refresh does not reshuffle the
        // ties a `HashMap` hands over in a different order every time.
        tools.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.name.cmp(&b.name)));
        tools.truncate(MAX_TOOLS);
        access.tools = tools;
    }
    access.writes = session
        .recent_writes
        .iter()
        .take(MAX_WRITES)
        .map(|p| util::tildify(p))
        .collect();

    access
}

/// Which Claude directory this session belongs to: a profile's, a Claude for Mac
/// session's, or the default.
fn claude_root(session: &Session) -> PathBuf {
    match (session.surface.is_desktop(), &session.mac_meta) {
        (true, Some(meta)) => meta.session_dir.join(".claude"),
        _ => crate::config::CLAUDE_CONFIG_DIR.clone(),
    }
}

type Layout = (
    Vec<(PathBuf, &'static str)>,
    Vec<(PathBuf, &'static str)>,
    Vec<PathBuf>,
    Option<&'static str>,
);

/// The files and directories one harness reads, for a session in `cwd`.
///
/// This is the map the terminal panel and the web page share. Adding a harness
/// means adding an arm here and both surfaces learn about it.
fn layout(session: &Session, root: &Path) -> Layout {
    let cwd = Path::new(&session.label_source);
    let project = |name: &str| match session.label_source.is_empty() {
        true => None,
        false => Some((cwd.join(name), "project")),
    };
    let mut instructions: Vec<(PathBuf, &'static str)> = Vec::new();
    let mut configs: Vec<(PathBuf, &'static str)> = Vec::new();
    let mut skills = Vec::new();
    let mut note = None;

    match session.provider {
        Provider::Claude => {
            instructions.push((root.join("CLAUDE.md"), "user"));
            instructions.extend(project("CLAUDE.md"));
            configs.push((root.join("settings.json"), "user"));
            // A project's settings live one directory down, which is also where
            // its `settings.local.json` sits — that one is a personal override
            // and is deliberately not listed as if the repository asked for it.
            if !session.label_source.is_empty() {
                configs.push((cwd.join(".claude").join("settings.json"), "project"));
            }
            skills = vec![root.join("skills")];
        }
        Provider::Codex => {
            instructions.push((crate::config::CODEX_HOME.join("AGENTS.md"), "user"));
            instructions.extend(project("AGENTS.md"));
            configs.push((crate::config::CODEX_HOME.join("config.toml"), "user"));
            skills = vec![crate::config::CODEX_HOME.join("skills")];
        }
        Provider::OpenCode => {
            instructions.extend(project("AGENTS.md"));
            configs.push((
                crate::config::OPENCODE_CONFIG_DIR.join("opencode.json"),
                "user",
            ));
        }
        Provider::Pi => {
            instructions.push((crate::config::PI_AGENT_DIR.join("AGENTS.md"), "user"));
            instructions.extend(project("AGENTS.md"));
            configs.push((crate::config::PI_AGENT_DIR.join("settings.json"), "user"));
            skills = vec![crate::config::PI_AGENT_DIR.join("skills")];
        }
        Provider::Gemini => {
            instructions.push((crate::config::GEMINI_HOME.join("GEMINI.md"), "user"));
            instructions.extend(project("GEMINI.md"));
            configs.push((crate::config::GEMINI_HOME.join("settings.json"), "user"));
            skills = vec![crate::config::GEMINI_HOME.join("skills")];
        }
        Provider::Devin => {
            let files = devin_layout(&session.label_source);
            instructions = files.instructions;
            configs = files.configs;
            skills = files.skills_dirs;
            // `.windsurf/global_rules.md` is only a fallback for
            // `.devin/global_rules.md`, so whether it applies cannot be said
            // without checking the other file — it is noted rather than listed.
            note = Some(
                "a `.windsurf/global_rules.md` applies only when \
                 `.devin/global_rules.md` does not, so it is not listed",
            );
        }
        Provider::Cursor => {
            instructions.extend(project(".cursorrules"));
            note = Some(
                "Cursor keeps its rules and its model settings in the editor, \
                 so only a project's own rules file is readable here",
            );
        }
        Provider::Windsurf => {
            instructions.extend(project(".windsurfrules"));
            note = Some(
                "Windsurf's global rules live in the editor's settings UI \
                 rather than in a file, so only the workspace rules are listed",
            );
        }
    }
    (instructions, configs, skills, note)
}

/// Devin CLI's documented file layout for a session running in `label_source`.
///
/// Shared by [`layout`] and the terminal panel — the two surfaces drifted
/// once already, both pointing at Devin's session-*data* directory
/// (`~/.local/share/devin/cli`) rather than its config directory
/// (`~/.config/devin`), which is how the panel came to look for a
/// `config.toml` that has never existed. One map is how they stay honest.
pub struct DevinLayout {
    pub instructions: Vec<(PathBuf, &'static str)>,
    pub configs: Vec<(PathBuf, &'static str)>,
    pub skills_dirs: Vec<PathBuf>,
    /// Dedicated `mcpServers` files — every top-level key is a server.
    pub mcp_files: Vec<(PathBuf, &'static str)>,
    /// `config.json` files that may still carry a pre-v3000.3 `mcpServers`
    /// key (the CLI migrates it out on startup). Only that key may be read:
    /// treating the whole file as a server map reports `agent`,
    /// `permissions` and every other config section as a server.
    pub legacy_mcp_files: Vec<(PathBuf, &'static str)>,
}

/// The map itself: user scope first, then the project's.
pub fn devin_layout(label_source: &str) -> DevinLayout {
    let cfg = &*crate::config::DEVIN_CONFIG_DIR;
    let home_devin = crate::config::HOME.join(".devin");
    let cwd = Path::new(label_source);
    let has_cwd = !label_source.is_empty();

    let mut instructions = vec![
        (cfg.join("AGENTS.md"), "user"),
        (home_devin.join("global_rules.md"), "user"),
    ];
    rules_in(&home_devin.join("rules"), "user", &mut instructions);
    let mut configs = vec![(cfg.join("config.json"), "user")];
    let mut skills_dirs = vec![
        cfg.join("skills"),
        crate::config::HOME.join(".agents").join("skills"),
    ];
    for channel in ["windsurf", "windsurf-next", "windsurf-insiders"] {
        skills_dirs.push(
            crate::config::HOME
                .join(".codeium")
                .join(channel)
                .join("skills"),
        );
    }
    let mut mcp_files = vec![(cfg.join("mcp_config.json"), "user")];
    let mut legacy_mcp_files = vec![(cfg.join("config.json"), "user")];

    if has_cwd {
        let devin = cwd.join(".devin");
        instructions.extend([
            (cwd.join("AGENTS.md"), "project"),
            (cwd.join("AGENTS.local.md"), "local"),
            (devin.join("global_rules.md"), "project"),
        ]);
        rules_in(&devin.join("rules"), "project", &mut instructions);
        rules_in(
            &cwd.join(".windsurf").join("rules"),
            "project",
            &mut instructions,
        );
        configs.extend([
            (devin.join("config.json"), "project"),
            (devin.join("config.local.json"), "local"),
        ]);
        skills_dirs.extend([
            devin.join("skills"),
            cwd.join(".agents").join("skills"),
            cwd.join(".windsurf").join("skills"),
        ]);
        mcp_files.extend([
            (devin.join("mcp_config.json"), "project"),
            (devin.join("mcp_config.local.json"), "local"),
        ]);
        legacy_mcp_files.extend([
            (devin.join("config.json"), "project"),
            (devin.join("config.local.json"), "local"),
        ]);
    }

    DevinLayout {
        instructions,
        configs,
        skills_dirs,
        mcp_files,
        legacy_mcp_files,
    }
}

/// Each `*.md` file in a rules directory, appended to `out`.
///
/// Rule files only exist to be listed, so unlike the fixed entries above
/// them, a directory that is absent adds nothing — not even a "not here".
fn rules_in(dir: &Path, scope: &'static str, out: &mut Vec<(PathBuf, &'static str)>) {
    for entry in crate::config::list_dir(dir) {
        if entry.ends_with(".md") {
            out.push((dir.join(&entry), scope));
        }
    }
}

/// One file, read if it is there.
fn file_ref(path: &Path, scope: &'static str) -> FileRef {
    let bytes = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
    let text = util::read_head(path, MAX_FILE_CHARS * 4);
    let (head, clipped) = match &text {
        Some(body) => {
            let clipped = body.chars().count() > MAX_FILE_CHARS;
            let head: String = match clipped {
                true => body.chars().take(MAX_FILE_CHARS).collect(),
                false => body.clone(),
            };
            (Some(head), clipped || (bytes as usize) > MAX_FILE_CHARS * 4)
        }
        None => (None, false),
    };
    FileRef {
        path: util::tildify(&path.to_string_lossy()),
        scope,
        present: text.is_some(),
        bytes,
        head,
        clipped,
    }
}

/// Skill names and descriptions out of each `SKILL.md` front matter.
///
/// The front matter is read as lines rather than parsed as YAML: two keys are
/// wanted out of a file whose body is markdown, and a parser would have to be
/// told where the front matter ends anyway.
pub fn skills(dir: &Path) -> Vec<Skill> {
    if !dir.is_dir() {
        return Vec::new();
    }
    let mut out = Vec::new();
    for entry in crate::config::list_dir(dir) {
        let (mut name, mut description) = (entry.clone(), String::new());
        if let Some(text) = util::read_head(&dir.join(&entry).join("SKILL.md"), 4096) {
            for line in text.lines().take(20) {
                if let Some(v) = line.strip_prefix("name:") {
                    name = v.trim().to_string();
                } else if let Some(v) = line.strip_prefix("description:") {
                    description = v.trim().to_string();
                }
            }
        }
        out.push(Skill { name, description });
        if out.len() >= MAX_SKILLS {
            break;
        }
    }
    out
}

/// Every MCP server configured for this session, user scope first.
///
/// The two readers exist because the files come in two shapes: a dedicated
/// MCP file (`.mcp.json`, `mcp_config.json`) is a server map that may or may
/// not sit under an `mcpServers` key, while a general config file
/// (`settings.json`, `opencode.json`, `config.json`) names its servers under
/// one key and everything else it holds is *not* a server. Reading the
/// second shape with the first reader lists `permissions`, `hooks` and every
/// other object-valued setting as a server — which is what a Claude
/// `settings.json` without an `mcpServers` key used to show.
fn mcp_servers(session: &Session, root: &Path) -> Vec<McpServer> {
    let cwd = Path::new(&session.label_source);
    let mut out = Vec::new();
    match session.provider {
        Provider::Claude => {
            out.extend(mcp_from_config(
                &root.join("settings.json"),
                "mcpServers",
                "user",
            ));
            if !session.label_source.is_empty() {
                // A project's `.mcp.json` is the file a repository uses to hand
                // every clone of itself the same servers.
                out.extend(mcp_from_json(&cwd.join(".mcp.json"), "project"));
            }
        }
        Provider::Codex => out.extend(mcp_from_toml(
            &crate::config::CODEX_HOME.join("config.toml"),
        )),
        Provider::Gemini => {
            out.extend(mcp_from_config(
                &crate::config::GEMINI_HOME.join("settings.json"),
                "mcpServers",
                "user",
            ));
        }
        Provider::Pi => {
            out.extend(mcp_from_config(
                &crate::config::PI_AGENT_DIR.join("settings.json"),
                "mcpServers",
                "user",
            ));
        }
        Provider::OpenCode => {
            out.extend(mcp_from_config(
                &crate::config::OPENCODE_CONFIG_DIR.join("opencode.json"),
                "mcp",
                "user",
            ));
        }
        Provider::Devin => {
            let files = devin_layout(&session.label_source);
            for (path, scope) in &files.mcp_files {
                out.extend(mcp_from_json(path, scope));
            }
            for (path, scope) in &files.legacy_mcp_files {
                out.extend(mcp_from_config(path, "mcpServers", scope));
            }
        }
        Provider::Cursor | Provider::Windsurf => {}
    }
    out
}

/// Servers out of a dedicated MCP file, whether they sit under `mcpServers` or
/// at the top level — a project `.mcp.json` and Devin's `mcp_config.json` use
/// either. For a file whose other contents are *not* servers, use
/// [`mcp_from_config`] instead.
pub fn mcp_from_json(path: &Path, scope: &'static str) -> Vec<McpServer> {
    let Some(text) = util::read_head(path, 64 * 1024) else {
        return Vec::new();
    };
    let Ok(value) = serde_json::from_str::<Value>(&text) else {
        return Vec::new();
    };
    servers_from(value.get("mcpServers").unwrap_or(&value), scope)
}

/// Servers out of one key of a general config file — `mcpServers` for Claude,
/// Gemini and Pi settings, `mcp` for OpenCode's `opencode.json`.
pub fn mcp_from_config(path: &Path, key: &str, scope: &'static str) -> Vec<McpServer> {
    let Some(text) = util::read_head(path, 64 * 1024) else {
        return Vec::new();
    };
    let Ok(value) = serde_json::from_str::<Value>(&text) else {
        return Vec::new();
    };
    let Some(servers) = value.get(key) else {
        return Vec::new();
    };
    servers_from(servers, scope)
}

fn servers_from(servers: &Value, scope: &'static str) -> Vec<McpServer> {
    let Some(map) = servers.as_object() else {
        return Vec::new();
    };
    map.iter()
        .filter(|(_, cfg)| cfg.is_object())
        .map(|(name, cfg)| McpServer {
            name: name.clone(),
            scope,
            command: command_of(cfg),
        })
        .collect()
}

/// How a server is reached, spelled for a reader.
///
/// `command` is a string in most configs but an argv array in OpenCode's —
/// `"command": ["docker", "run", …]` — and a remote server has a `url`
/// instead. Joining the array is still the truth about where tool calls go;
/// reporting neither would be the same lie the field exists to prevent.
fn command_of(cfg: &Value) -> Option<String> {
    match cfg.get("command") {
        Some(command) => command
            .as_str()
            .map(str::to_string)
            .or_else(|| {
                command.as_array().map(|argv| {
                    argv.iter()
                        .filter_map(Value::as_str)
                        .collect::<Vec<_>>()
                        .join(" ")
                })
            })
            .or_else(|| cfg.get("url").and_then(Value::as_str).map(str::to_string)),
        None => cfg.get("url").and_then(Value::as_str).map(str::to_string),
    }
}

/// Servers out of Codex's `config.toml`, by table header.
///
/// Scanning headers rather than parsing the file: the whole question is which
/// `[mcp_servers.<name>]` tables exist, and a TOML parse of a file that may hold
/// anything is more ways to fail for the same answer.
pub fn mcp_from_toml(path: &Path) -> Vec<McpServer> {
    let Some(text) = util::read_head(path, 64 * 1024) else {
        return Vec::new();
    };
    text.lines()
        .filter_map(|line| {
            line.trim()
                .strip_prefix("[mcp_servers.")
                .and_then(|rest| rest.strip_suffix(']'))
                .map(|name| McpServer {
                    name: name.trim_matches('"').to_string(),
                    scope: "user",
                    command: None,
                })
        })
        .collect()
}

/// Whether cctop's hooks are installed for this session's harness.
///
/// Both scopes, because the answer differs between them and a session in a
/// directory with its own settings file is governed by that one. A harness cctop
/// does not integrate with — Pi and Windsurf so far — reports nothing rather
/// than reporting "absent", which would read as a thing to fix.
fn hooks(session: &Session, cwd: &Path) -> Vec<HookState> {
    let Some(harness) = harness_for(session.provider) else {
        return Vec::new();
    };
    let mut scopes = vec![Scope::User];
    if !session.label_source.is_empty() && cwd.is_dir() {
        scopes.push(Scope::Project(cwd.to_path_buf()));
    }
    scopes
        .into_iter()
        .flat_map(|scope| hook::harness_status(harness, scope))
        .map(|status| {
            let (state, detail) = match &status.health {
                Health::Installed => ("installed", None),
                Health::Absent => ("absent", None),
                Health::Partial(missing) => {
                    ("partial", Some(format!("missing {}", missing.join(", "))))
                }
                Health::Other { exe, .. } => ("other", Some(format!("installed at {exe}"))),
                Health::Broken(exe) => ("broken", Some(format!("points at {exe}, which is gone"))),
                Health::Unreadable(why) => ("unreadable", Some(why.clone())),
            };
            HookState {
                harness: status.harness.label().to_string(),
                scope: status.scope.label(),
                path: util::tildify(&status.path.to_string_lossy()),
                state,
                detail: detail.or_else(|| status.note.map(str::to_string)),
            }
        })
        .collect()
}

/// The hook harness matching a provider, where cctop integrates with one.
fn harness_for(provider: Provider) -> Option<hook::Harness> {
    match provider {
        Provider::Claude => Some(hook::Harness::Claude),
        Provider::Codex => Some(hook::Harness::Codex),
        Provider::Cursor => Some(hook::Harness::Cursor),
        Provider::Gemini => Some(hook::Harness::Gemini),
        Provider::OpenCode => Some(hook::Harness::OpenCode),
        // Devin has its own hooks.v1.json, but `cctop hook` does not speak its
        // event dialect yet — registering it would install hooks that decode
        // nothing, which is worse than installing none.
        Provider::Devin | Provider::Pi | Provider::Windsurf => None,
    }
}

/// What a permission mode means, spelled out.
///
/// The column has room for one word and the difference between two of those
/// words is whether an agent can write to the disk without being asked, which is
/// worth a sentence somewhere.
fn describe_permission(permission: hook::Permission) -> &'static str {
    match permission {
        hook::Permission::Ask => "asks before anything it is not already allowed to do",
        hook::Permission::AcceptEdits => "writes files without asking; everything else still asks",
        hook::Permission::Plan => "reading and planning only — it cannot act yet",
        hook::Permission::Bypass => "asks about nothing at all",
    }
}

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

    fn session_in(dir: &Path, provider: Provider) -> Session {
        let mut session = Session::new(provider, "s1".into());
        session.label_source = dir.to_string_lossy().into_owned();
        session
    }

    #[test]
    fn a_project_instruction_file_is_read_and_a_missing_one_is_still_listed() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("CLAUDE.md"), "always run the gate").unwrap();
        let access = build(&session_in(dir.path(), Provider::Claude), None);

        let project = access
            .instructions
            .iter()
            .find(|f| f.scope == "project")
            .expect("the project instruction file should be listed");
        assert!(project.present);
        assert_eq!(project.head.as_deref(), Some("always run the gate"));
        // The user-scope file is listed whether or not this machine has one.
        assert!(access.instructions.iter().any(|f| f.scope == "user"));
    }

    /// The absent entry is the answer to "is there a project CLAUDE.md", and a
    /// list that dropped it could not be told from one that never looked.
    #[test]
    fn a_file_that_is_not_there_is_reported_as_absent_rather_than_omitted() {
        let dir = tempfile::tempdir().unwrap();
        let access = build(&session_in(dir.path(), Provider::Claude), None);
        let project = access
            .instructions
            .iter()
            .find(|f| f.scope == "project")
            .unwrap();
        assert!(!project.present);
        assert!(project.head.is_none());
    }

    #[test]
    fn a_long_instruction_file_is_cut_and_says_so() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("CLAUDE.md"),
            "x".repeat(MAX_FILE_CHARS + 500),
        )
        .unwrap();
        let access = build(&session_in(dir.path(), Provider::Claude), None);
        let project = access
            .instructions
            .iter()
            .find(|f| f.scope == "project")
            .unwrap();
        assert!(project.clipped);
        assert_eq!(
            project.head.as_deref().unwrap().chars().count(),
            MAX_FILE_CHARS
        );
    }

    #[test]
    fn skills_come_back_named_and_described_from_their_front_matter() {
        let dir = tempfile::tempdir().unwrap();
        let skill = dir.path().join("run-cctop");
        fs::create_dir_all(&skill).unwrap();
        fs::write(
            skill.join("SKILL.md"),
            "---\nname: run-cctop\ndescription: Build, run and screenshot cctop\n---\n",
        )
        .unwrap();
        let found = skills(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "run-cctop");
        assert_eq!(found[0].description, "Build, run and screenshot cctop");
    }

    #[test]
    fn a_skill_directory_that_does_not_exist_is_empty_not_an_error() {
        assert!(skills(Path::new("/nonexistent/skills")).is_empty());
    }

    #[test]
    fn mcp_servers_are_read_from_either_shape_of_json() {
        let dir = tempfile::tempdir().unwrap();
        let wrapped = dir.path().join("settings.json");
        fs::write(
            &wrapped,
            r#"{"mcpServers":{"linear":{"command":"npx linear-mcp"}}}"#,
        )
        .unwrap();
        let bare = dir.path().join(".mcp.json");
        fs::write(&bare, r#"{"sentry":{"url":"https://mcp.sentry.dev"}}"#).unwrap();

        let user = mcp_from_json(&wrapped, "user");
        assert_eq!(user.len(), 1);
        assert_eq!(user[0].name, "linear");
        assert_eq!(user[0].command.as_deref(), Some("npx linear-mcp"));

        let project = mcp_from_json(&bare, "project");
        assert_eq!(project.len(), 1);
        assert_eq!(project[0].scope, "project");
        // A remote server has a URL and no command, and reporting a command it
        // does not have would misstate where its tool calls go.
        assert_eq!(
            project[0].command.as_deref(),
            Some("https://mcp.sentry.dev")
        );
    }

    /// A `settings.json` with no `mcpServers` key is a config file, not a
    /// server map — reading it as one once listed `hooks`, `permissions` and
    /// every other object-valued setting as an MCP server.
    #[test]
    fn a_config_file_without_the_key_is_not_a_server_map() {
        let dir = tempfile::tempdir().unwrap();
        let settings = dir.path().join("settings.json");
        fs::write(
            &settings,
            r#"{"hooks":{"PreToolUse":[]},"permissions":{"allow":[]},"model":"opus"}"#,
        )
        .unwrap();
        assert!(mcp_from_config(&settings, "mcpServers", "user").is_empty());
    }

    /// OpenCode keeps its servers under `mcp`, not `mcpServers`, and spells a
    /// command as an argv array rather than a string.
    #[test]
    fn opencode_servers_come_from_the_mcp_key_with_argv_commands() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("opencode.json");
        fs::write(
            &config,
            r#"{"agent":{},"mcp":{"docs":{"type":"local","command":["docker","run","docs-mcp"]},"web":{"type":"remote","url":"https://mcp.example.dev"}}}"#,
        )
        .unwrap();
        let servers = mcp_from_config(&config, "mcp", "user");
        assert_eq!(servers.len(), 2);
        let docs = servers.iter().find(|s| s.name == "docs").unwrap();
        assert_eq!(docs.command.as_deref(), Some("docker run docs-mcp"));
        let web = servers.iter().find(|s| s.name == "web").unwrap();
        assert_eq!(web.command.as_deref(), Some("https://mcp.example.dev"));
    }

    /// Devin's files live under `~/.config/devin` and `.devin/` — for a while
    /// this reader looked for a `config.toml` in the *session data* directory,
    /// a path that cannot exist, and reported nothing.
    #[test]
    fn devin_files_come_from_the_config_directories_not_the_data_one() {
        let dir = tempfile::tempdir().unwrap();
        let files = devin_layout(&dir.path().to_string_lossy());
        let all: Vec<&Path> = files
            .instructions
            .iter()
            .chain(&files.configs)
            .chain(&files.mcp_files)
            .chain(&files.legacy_mcp_files)
            .map(|(p, _)| p.as_path())
            .chain(files.skills_dirs.iter().map(PathBuf::as_path))
            .collect();
        for path in &all {
            let spelled = path.to_string_lossy();
            assert!(
                !spelled.contains(".local/share") && !spelled.ends_with("config.toml"),
                "Devin keeps no config in its data directory: {spelled}"
            );
        }
        let project_paths: Vec<String> = all
            .iter()
            .filter(|p| p.starts_with(dir.path()))
            .map(|p| p.to_string_lossy().into_owned())
            .collect();
        for expected in [
            ".devin/config.json",
            ".devin/config.local.json",
            ".devin/mcp_config.json",
            ".devin/mcp_config.local.json",
            "AGENTS.md",
            "AGENTS.local.md",
        ] {
            assert!(
                project_paths.iter().any(|p| p.ends_with(expected)),
                "{expected} should be in the Devin layout"
            );
        }
    }

    /// A project's `.devin/mcp_config.json` is read as a server map, and an
    /// unmigrated `mcpServers` key inside `config.json` is still found —
    /// without mistaking the rest of the config for servers.
    #[test]
    fn devin_mcp_servers_come_from_their_own_files_and_the_legacy_key() {
        let dir = tempfile::tempdir().unwrap();
        let devin = dir.path().join(".devin");
        fs::create_dir_all(&devin).unwrap();
        fs::write(
            devin.join("mcp_config.json"),
            r#"{"mcpServers":{"linear":{"command":"npx linear-mcp"}}}"#,
        )
        .unwrap();
        fs::write(
            devin.join("config.json"),
            r#"{"agent":{"model":"swe"},"mcpServers":{"sentry":{"url":"https://mcp.sentry.dev"}}}"#,
        )
        .unwrap();
        let access = build(&session_in(dir.path(), Provider::Devin), None);
        let names: Vec<&str> = access.mcp.iter().map(|s| s.name.as_str()).collect();
        // The project files are the deterministic part — a real user-scope
        // config on the machine running this test may legitimately add more.
        assert!(names.contains(&"linear"));
        assert!(names.contains(&"sentry"));
        // `agent` is a config section, not a server.
        assert!(!names.contains(&"agent"));
    }

    #[test]
    fn codex_mcp_servers_come_from_their_table_headers() {
        let dir = tempfile::tempdir().unwrap();
        let toml = dir.path().join("config.toml");
        fs::write(
            &toml,
            "model = \"gpt-5\"\n\n[mcp_servers.playwright]\ncommand = \"npx\"\n\n[mcp_servers.docs]\n",
        )
        .unwrap();
        let servers = mcp_from_toml(&toml);
        let names: Vec<&str> = servers.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["playwright", "docs"]);
    }

    /// A remote row's paths belong to another filesystem. Reading them here
    /// would report a local file as that machine's configuration.
    #[test]
    fn a_remote_session_reports_nothing_off_this_disk() {
        let dir = tempfile::tempdir().unwrap();
        let mut session = session_in(dir.path(), Provider::Claude);
        fs::write(dir.path().join("CLAUDE.md"), "local file").unwrap();
        session.remote = Some(crate::session::Remote {
            host: "build-box".into(),
            branch: Some("main".into()),
        });
        let access = build(&session, None);
        assert!(access.instructions.is_empty());
        assert!(access.mcp.is_empty());
        assert_eq!(access.branch.as_deref(), Some("main"));
        assert!(access.note.is_some_and(|n| n.contains("another machine")));
    }

    #[test]
    fn tools_used_are_ranked_and_mcp_names_made_readable() {
        let dir = tempfile::tempdir().unwrap();
        let mut data = SessionData::default();
        data.metrics.tools.insert("Read".into(), 3);
        data.metrics
            .tools
            .insert("mcp__linear__list_issues".into(), 9);
        let access = build(&session_in(dir.path(), Provider::Claude), Some(&data));
        assert_eq!(access.tools[0].count, 9);
        assert!(
            !access.tools[0].name.contains("mcp__"),
            "an MCP tool should be spelled for a reader: {}",
            access.tools[0].name
        );
        assert_eq!(access.tools[1].name, "Read");
    }

    /// Cursor and Windsurf keep most of this where cctop cannot read it, and
    /// saying so is better than an empty panel that looks like a bug.
    #[test]
    fn a_harness_that_hides_its_rules_says_where_they_are() {
        let dir = tempfile::tempdir().unwrap();
        let access = build(&session_in(dir.path(), Provider::Windsurf), None);
        assert!(access.note.is_some_and(|n| n.contains("settings UI")));
        // And no hook lines, since cctop does not install into Windsurf at all.
        assert!(access.hooks.is_empty());
    }
}