Skip to main content

surjection_core/layering/
effective.rs

1//! The effective view (SPEC 6.4): for a folder `F` and a client `C`, every
2//! server name `C` loads in `F`, which file it comes from and what it
3//! shadows.
4//!
5//! Computed from the client files as they are plus the entries the plan
6//! would create. A name is a candidate in every file and container `C`
7//! reads: first `C`'s own layers in [`Caps::precedence`] order (the user
8//! file is `system`, the shared project file `project`, the private target
9//! `project-local`; an entry Surjection does not own is `foreign:<file>`),
10//! then the other tools' files of [`Caps::compat_reads`]
11//! (`client-compat:<file>`); a compatibility file that one host of `C`
12//! prefers ([`CompatSource::outranks`]: VS Code's `.vscode/mcp.json` for
13//! Copilot) comes right before the layer it outranks. The first candidate
14//! wins and the others are shadowed. For a client whose own layers coexist
15//! ([`ProjectSemantics::Coexist`]: Cursor), every live entry of its own
16//! files is a loaded row of its own, and these rows carry
17//! `duplicate_across_layers`. An entry the plan cannot write (`blocked`)
18//! never wins over one that is there; a name only such entries hold is
19//! reported with `loaded: false`.
20//!
21//! [`Caps::precedence`]: crate::adapters::caps::Caps::precedence
22//! [`Caps::compat_reads`]: crate::adapters::caps::Caps::compat_reads
23
24use std::cell::RefCell;
25use std::collections::{BTreeMap, HashMap};
26use std::fmt;
27use std::path::{Path, PathBuf};
28
29use serde::ser::SerializeStruct;
30use serde::{Serialize, Serializer};
31
32use crate::access::ReadOnlyKind;
33use crate::adapters::caps::{CompatSource, Outrank, ProjectDisable, ProjectSemantics, Source};
34use crate::adapters::detect::replacing_extension;
35use crate::adapters::{ADAPTERS, AdapterSpec, adapter};
36use crate::apply::cache::CachedPlan;
37use crate::apply::exec::PlanInputs;
38use crate::apply::ledger::{EntryKind, LedgerEntry, container_pointer};
39use crate::apply::plan::{
40    self, Action, EntryPlan, EntryState, Plan, PlanOptions, ProjectSelection, ScopeFilter,
41    TargetPlan, client_enable_required, list_members, read_target, unset_not_expressible,
42};
43use crate::apply::render::{Detected, RenderCx, server_transport, writable};
44use crate::apply::{ApplyEnv, placeholder_path};
45use crate::env::Os;
46use crate::error::{CoreError, ErrorCode};
47use crate::formats::{Document, Format, NativeValue};
48use crate::layering::merge::{EntryBody, ProjectEntry, project_entries, suppression_mechanism};
49use crate::layering::{Project, TrustStore, discover, same_path, trust_required};
50use crate::model::applied::Scope;
51use crate::paths::STATE_DIR;
52use crate::store::Store;
53
54/// Where an entry a client loads lives (SPEC 6.4).
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum Layer {
57    /// The client's user file, an entry Surjection owns.
58    System,
59    /// The client's shared project file, an entry Surjection owns.
60    Project,
61    /// The client's private project target, an entry Surjection owns.
62    ProjectLocal,
63    /// An entry Surjection does not own in one of the client's files (the
64    /// file, as in [`Winner::file`]).
65    Foreign(String),
66    /// An entry the client reads from another tool's file.
67    ClientCompat(String),
68}
69
70impl fmt::Display for Layer {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        match self {
73            Layer::System => f.write_str("system"),
74            Layer::Project => f.write_str("project"),
75            Layer::ProjectLocal => f.write_str("project-local"),
76            Layer::Foreign(file) => write!(f, "foreign:{file}"),
77            Layer::ClientCompat(file) => write!(f, "client-compat:{file}"),
78        }
79    }
80}
81
82impl Serialize for Layer {
83    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
84        serializer.collect_str(self)
85    }
86}
87
88/// The entry a client uses for a name.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
90pub struct Winner {
91    pub layer: Layer,
92    /// The file with a placeholder root (`~/.claude.json`, `<P>/.mcp.json`).
93    pub file: String,
94    /// `store:<id>` (a system entry), `store:<id>+project` (a project
95    /// override with `from`, or a suppression), `project:<name>` (defined
96    /// by the project only) or `foreign`.
97    pub source: String,
98    /// This account cannot write the file (SPEC 8.2 `read_only_target`).
99    #[serde(serialize_with = "crate::access::read_only_json")]
100    pub read_only: Option<ReadOnlyKind>,
101}
102
103/// A same-named entry the winner hides (or, for a client that merges
104/// project entries field by field, merges over).
105#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
106pub struct Shadowed {
107    pub layer: Layer,
108    pub file: String,
109    #[serde(serialize_with = "crate::access::read_only_json")]
110    pub read_only: Option<ReadOnlyKind>,
111}
112
113/// One server name a client loads, or would load, in the folder.
114#[derive(Debug, Clone, Serialize)]
115pub struct EffectiveEntry {
116    pub name: String,
117    /// Whether the client starts it: not suppressed, not disabled, and not
118    /// only planned in a blocked target.
119    pub loaded: bool,
120    pub winner: Winner,
121    pub shadowed: Vec<Shadowed>,
122    /// Other clients with an adapter that read the winner's file and
123    /// container (SPEC 6.5), by id.
124    pub also_visible_to: Vec<&'static str>,
125    /// The winner's plan state, when Surjection plans its file; `foreign` for
126    /// an entry it does not own.
127    #[serde(serialize_with = "state_json")]
128    pub status: Option<EntryState>,
129    /// `duplicate_via_compat`, `duplicate_across_layers`,
130    /// `cannot_suppress_in_project`,
131    /// `unset_not_expressible`, `trust_required`,
132    /// `client_mcp_replaced_by_extension`, `client_enable_required` and the
133    /// problems the plan has with this name's entries.
134    #[serde(serialize_with = "warnings_json")]
135    pub warnings: Vec<CoreError>,
136    /// The winner's native entry as its file writes it, under the
137    /// innermost container key, with the values the plan writes or held
138    /// inline masked ([`TargetPlan::snippet`]); `None` when it cannot be
139    /// rendered. Other literals are the caller's to mask before showing
140    /// it. Not part of the JSON view.
141    #[serde(skip)]
142    pub snippet: Option<String>,
143}
144
145/// The project of the folder.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
147pub struct ProjectRef {
148    pub id: String,
149    pub root: PathBuf,
150}
151
152/// The effective view of a folder.
153#[derive(Debug, Clone, Serialize)]
154pub struct EffectiveView {
155    /// The nearest project at or above the folder, if any.
156    pub project: Option<ProjectRef>,
157    /// Entries per client id, by name; a client whose own layers coexist
158    /// (Cursor) has one row per file for a name in several of them.
159    pub clients: BTreeMap<&'static str, Vec<EffectiveEntry>>,
160    /// Files that could not be read or parsed, and other problems outside
161    /// any entry.
162    #[serde(skip)]
163    pub warnings: Vec<CoreError>,
164}
165
166fn state_json<S: Serializer>(state: &Option<EntryState>, serializer: S) -> Result<S::Ok, S::Error> {
167    match state {
168        Some(state) => serializer.serialize_str(state.as_str()),
169        None => serializer.serialize_none(),
170    }
171}
172
173fn warnings_json<S: Serializer>(warnings: &[CoreError], serializer: S) -> Result<S::Ok, S::Error> {
174    struct Warning<'a>(&'a CoreError);
175    impl Serialize for Warning<'_> {
176        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
177            let mut out = serializer.serialize_struct("Warning", 2)?;
178            out.serialize_field("code", self.0.code().as_str())?;
179            out.serialize_field("message", self.0.message())?;
180            out.end()
181        }
182    }
183    serializer.collect_seq(warnings.iter().map(Warning))
184}
185
186/// The effective view of `folder` for `clients` (every client with MCP
187/// support on this OS that Surjection writes when `None`). Plans the user
188/// files and, when the folder's project is known on this machine, that
189/// project, against the store's working tree; reads files and never writes
190/// anything.
191///
192/// Errors: `unknown_client`, `no_adapter` or `not_supported_on_os` for a
193/// requested client; an invalid manifest; a store that does not load.
194pub fn effective(
195    store: Option<&Store<'_>>,
196    ax: &ApplyEnv<'_>,
197    folder: &Path,
198    clients: Option<&[String]>,
199) -> Result<EffectiveView, CoreError> {
200    let specs = selected(ax, clients)?;
201    let inputs = PlanInputs::load(store, ax)?;
202    view_of(ax, &inputs, specs, folder, None)
203}
204
205/// [`effective`] from a plan of every scope and project made already (the
206/// app's cached plan, [`crate::apply::cache`]), so the view plans nothing.
207pub fn effective_planned(
208    ax: &ApplyEnv<'_>,
209    cached: &CachedPlan,
210    folder: &Path,
211    clients: Option<&[String]>,
212) -> Result<EffectiveView, CoreError> {
213    let specs = selected(ax, clients)?;
214    view_of(ax, &cached.inputs, specs, folder, Some(&cached.plan))
215}
216
217/// The clients of a view: `clients`, or every client with MCP support on
218/// this OS that Surjection writes.
219fn selected(
220    ax: &ApplyEnv<'_>,
221    clients: Option<&[String]>,
222) -> Result<Vec<&'static AdapterSpec>, CoreError> {
223    let os = ax.env.os();
224    match clients {
225        Some(ids) => ids.iter().map(|id| writable(id, ax.env)).collect(),
226        None => Ok(ADAPTERS
227            .iter()
228            .copied()
229            .filter(|spec| on_os(spec, os) && !read_only(spec))
230            .collect()),
231    }
232}
233
234/// The view of `folder` for `specs` from `inputs`: from `full`, a plan of
235/// every scope and project, when given; else from one planner run for the
236/// user files and the folder's project.
237fn view_of(
238    ax: &ApplyEnv<'_>,
239    inputs: &PlanInputs,
240    specs: Vec<&'static AdapterSpec>,
241    folder: &Path,
242    full: Option<&Plan>,
243) -> Result<EffectiveView, CoreError> {
244    let cx = ax.render_cx(inputs.memory.clone());
245    let mut warnings = Vec::new();
246    // The project, at the path this machine knows it by when it does (the
247    // overlay's spelling), so that planned files compare equal; and the
248    // ids this machine knows at that folder.
249    let mut known: Vec<&str> = Vec::new();
250    let project = match discover(ax.env, ax.fs, folder) {
251        Some(found) => {
252            let projects = inputs
253                .desired
254                .overlay
255                .as_ref()
256                .and_then(|overlay| overlay.projects.as_ref());
257            let root = projects.and_then(|projects| {
258                projects
259                    .values()
260                    .map(|project| PathBuf::from(&project.path))
261                    .find(|path| same_path(path, &found))
262            });
263            if let (Some(root), Some(projects)) = (&root, projects) {
264                known = projects
265                    .iter()
266                    .filter(|(_, project)| same_path(Path::new(&project.path), root))
267                    .map(|(id, _)| id.as_str())
268                    .collect();
269            }
270            Project::load(ax.fs, root.as_deref().unwrap_or(&found))?
271        }
272        None => None,
273    };
274
275    let mut selections = vec![PlanOptions {
276        scope: ScopeFilter::System,
277        ..PlanOptions::default()
278    }];
279    if let Some(project) = project.as_ref().filter(|_| !known.is_empty()) {
280        selections.push(PlanOptions {
281            scope: ScopeFilter::Project,
282            projects: ProjectSelection::Only(project.root.clone()),
283            ..PlanOptions::default()
284        });
285    }
286    let plans = match full {
287        Some(_) => Vec::new(),
288        None => plan::plan_each(
289            &cx,
290            &inputs.desired,
291            &inputs.ledger,
292            &inputs.key,
293            &selections,
294        )?,
295    };
296    let planned: Vec<&TargetPlan> = match full {
297        // What the two plans hold, in the same order (user files first):
298        // the user targets, and those of the folder's project, which a plan
299        // of the folder selects by the ids known there.
300        Some(full) => full
301            .targets
302            .iter()
303            .filter(|target| {
304                target.scope == Scope::User
305                    || (selections.len() > 1
306                        && target
307                            .project_id
308                            .as_deref()
309                            .is_some_and(|id| known.contains(&id)))
310            })
311            .collect(),
312        None => plans.iter().flat_map(|plan| &plan.targets).collect(),
313    };
314    let mut entries = Vec::new();
315    let mut trust = None;
316    if let Some(project) = &project {
317        warnings.extend(project.warnings.iter().cloned());
318        let state_dir = ax.home.path.join(STATE_DIR);
319        let store = TrustStore::load(ax.fs, &state_dir).unwrap_or_else(|err| {
320            warnings.push(err);
321            TrustStore::default()
322        });
323        trust = trust_required(project, &project.root, store.state(project));
324        entries = project_entries(
325            project,
326            &inputs.desired.servers,
327            ax.env,
328            inputs.desired.overlay.as_ref(),
329        );
330    }
331
332    let mut view = View {
333        cx: &cx,
334        inputs,
335        root: project.as_ref().map(|project| project.root.as_path()),
336        planned,
337        owners: Owners::of(&inputs.ledger.entries),
338        entries: &entries,
339        trust,
340        docs: BTreeMap::new(),
341        displayed: RefCell::new(HashMap::new()),
342        detected: Detected::default(),
343        readers: None,
344        warnings,
345    };
346    let mut out = BTreeMap::new();
347    for spec in specs {
348        let rows = view.client(spec);
349        out.insert(spec.id, rows);
350    }
351    view.mark_read_only(&mut out);
352    let warnings = view.warnings;
353    Ok(EffectiveView {
354        project: project.map(|project| ProjectRef {
355            id: project.id,
356            root: project.root,
357        }),
358        clients: out,
359        warnings,
360    })
361}
362
363fn on_os(spec: &AdapterSpec, os: Os) -> bool {
364    spec.mcp.as_ref().is_some_and(|mcp| mcp.oses.contains(&os))
365}
366
367/// A client Surjection only reads (`vscode-legacy`): never a row of its own,
368/// only a compatibility source of others.
369fn read_only(spec: &AdapterSpec) -> bool {
370    spec.mcp.as_ref().is_some_and(|mcp| mcp.read_only)
371}
372
373const fn scope_of(source: Source) -> Scope {
374    match source {
375        Source::User => Scope::User,
376        Source::Project => Scope::Project,
377        Source::ProjectLocal => Scope::ProjectLocal,
378    }
379}
380
381/// One file and container a client reads entries from.
382struct SourceFile {
383    scope: Scope,
384    /// Another tool's file (SPEC 6.4 `client-compat`).
385    compat: bool,
386    /// Where another tool's file ranks, when above one of the client's own
387    /// layers.
388    outrank: Option<Outrank>,
389    file: PathBuf,
390    format: Format,
391    keys: Vec<String>,
392    pointer: String,
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
396enum Presence {
397    /// In the file now.
398    File,
399    /// Not there yet; the plan creates it.
400    Planned,
401    /// Not there; the plan cannot write it.
402    Blocked,
403}
404
405/// One entry of a name in one source.
406struct Candidate {
407    layer: Layer,
408    file: PathBuf,
409    pointer: String,
410    compat: bool,
411    outrank: Option<Outrank>,
412    presence: Presence,
413    value: Option<NativeValue>,
414    source: String,
415    status: Option<EntryState>,
416    problem: Option<CoreError>,
417    snippet: Option<String>,
418}
419
420/// What a client's rows share, by entry name.
421struct ClientCx {
422    /// Names hidden through a list (Claude Code `disabledMcpServers`).
423    suppressed: Vec<String>,
424    member_problems: Vec<(String, CoreError)>,
425    project_warnings: Vec<(String, CoreError)>,
426    /// `client_mcp_replaced_by_extension`, for every row.
427    extension: Option<CoreError>,
428}
429
430/// A client id and the files and containers (pointers) it reads.
431type Readers = Vec<(&'static str, Vec<(PathBuf, String)>)>;
432
433/// The first ledger entry of each file, container and key, whatever its
434/// slot: one pass over the ledger instead of one per candidate (#14).
435struct Owners<'a>(HashMap<(&'a str, &'a str, &'a str), &'a LedgerEntry>);
436
437impl<'a> Owners<'a> {
438    /// Server entries (not list members) of `entries`.
439    fn of(entries: &'a [LedgerEntry]) -> Self {
440        let mut map = HashMap::new();
441        for row in entries.iter().filter(|row| row.kind == EntryKind::McpEntry) {
442            map.entry((row.file.as_str(), row.container.as_str(), row.key.as_str()))
443                .or_insert(row);
444        }
445        Self(map)
446    }
447
448    fn get(&self, file: &str, container: &str, key: &str) -> Option<&'a LedgerEntry> {
449        self.0.get(&(file, container, key)).copied()
450    }
451}
452
453struct View<'a> {
454    cx: &'a RenderCx<'a>,
455    inputs: &'a PlanInputs,
456    root: Option<&'a Path>,
457    /// The planned targets of the user files and the folder's project.
458    planned: Vec<&'a TargetPlan>,
459    owners: Owners<'a>,
460    entries: &'a [ProjectEntry],
461    /// `trust_required` when the folder's project is not trusted as it is.
462    trust: Option<CoreError>,
463    /// Parsed files; `None` for a file that does not exist or does not
464    /// parse.
465    docs: BTreeMap<PathBuf, Option<Document>>,
466    /// [`View::display`] of each file shown so far.
467    displayed: RefCell<HashMap<PathBuf, String>>,
468    detected: Detected,
469    /// The files and containers each client reads (also visible to).
470    readers: Option<Readers>,
471    warnings: Vec<CoreError>,
472}
473
474impl<'a> View<'a> {
475    /// The entries of `spec`, by name.
476    fn client(&mut self, spec: &'static AdapterSpec) -> Vec<EffectiveEntry> {
477        let mcp = spec
478            .mcp
479            .as_ref()
480            .expect("selected clients have MCP support");
481        let sources = self.sources(spec, true);
482        let mut rows: BTreeMap<String, Vec<Candidate>> = BTreeMap::new();
483        for source in &sources {
484            self.candidates(source, &mut rows);
485        }
486        let (suppressed, member_problems) = self.suppressed(spec);
487        let has_project_files = !mcp.project.is_empty() || !mcp.project_local.is_empty();
488        let cx = ClientCx {
489            suppressed,
490            member_problems,
491            project_warnings: self.project_warnings(spec, has_project_files),
492            // An extension replacing the client's MCP support (Pi
493            // `pi-mcp-adapter`), installed for the user or for this project.
494            extension: replacing_extension(spec, self.cx.env, self.cx.fs, self.root),
495        };
496        let coexist = mcp.caps.project_semantics == ProjectSemantics::Coexist;
497
498        let mut out = Vec::with_capacity(rows.len());
499        for (name, candidates) in rows {
500            let live = |candidate: &&Candidate| candidate.presence != Presence::Blocked;
501            let first = candidates.iter().find(live).unwrap_or(&candidates[0]);
502            // The entries the client runs: the first live one and, for a
503            // client whose own layers coexist (Cursor), every other live
504            // entry of its own files too, each as a server of its own.
505            let mut heads = vec![first];
506            if coexist {
507                heads.extend(
508                    candidates
509                        .iter()
510                        .filter(live)
511                        .filter(|candidate| !candidate.compat && !std::ptr::eq(*candidate, first)),
512                );
513            }
514            for (index, winner) in heads.iter().copied().enumerate() {
515                // A further head is a row of its own; the first row holds
516                // every other candidate.
517                let group: Vec<&Candidate> = if index == 0 {
518                    candidates
519                        .iter()
520                        .filter(|candidate| {
521                            !heads[1..]
522                                .iter()
523                                .any(|head| std::ptr::eq(*head, *candidate))
524                        })
525                        .collect()
526                } else {
527                    vec![winner]
528                };
529                let entry = self.row(spec, &cx, &name, winner, &group, &heads);
530                out.push(entry);
531            }
532        }
533        out
534    }
535
536    /// The row of `name` whose entry `winner` the client runs; `group` holds
537    /// it and the candidates it shadows (or blocks), `heads` every entry of
538    /// the name the client runs.
539    fn row(
540        &mut self,
541        spec: &'static AdapterSpec,
542        cx: &ClientCx,
543        name: &str,
544        winner: &Candidate,
545        group: &[&Candidate],
546        heads: &[&Candidate],
547    ) -> EffectiveEntry {
548        let mcp = spec
549            .mcp
550            .as_ref()
551            .expect("selected clients have MCP support");
552        let live: Vec<&Candidate> = group
553            .iter()
554            .copied()
555            .filter(|candidate| candidate.presence != Presence::Blocked)
556            .collect();
557        let enabled = if mcp.caps.project_semantics == ProjectSemantics::DeepMerge {
558            // Fields merge across the client's own layers: the highest one
559            // that sets `enabled` decides.
560            live.iter()
561                .filter(|candidate| !candidate.compat)
562                .find_map(|candidate| enabled_of(candidate.value.as_ref()))
563                .or_else(|| enabled_of(winner.value.as_ref()))
564        } else {
565            enabled_of(winner.value.as_ref())
566        };
567        let loaded = winner.presence != Presence::Blocked
568            && enabled != Some(false)
569            && !cx.suppressed.iter().any(|member| member == name);
570
571        let mut warnings: Vec<CoreError> = Vec::new();
572        let native = live.iter().find(|candidate| !candidate.compat);
573        let compat = live.iter().find(|candidate| candidate.compat);
574        if let (Some(native), Some(compat)) = (native, compat) {
575            let message = match winner.outrank.filter(|_| winner.compat) {
576                // One host runs the compatibility entry, the others the
577                // client's own (VS Code and the Copilot CLI, gate V2 VSL-3).
578                Some(outrank) => format!(
579                    "{} runs {name:?} from {} over the same-named entry in {}; {} reads only \
580                     {} of the two and runs that entry",
581                    outrank.host,
582                    self.display(&winner.file),
583                    self.display(&native.file),
584                    outrank.others,
585                    self.display(&native.file)
586                ),
587                None => format!(
588                    "{} loads {name:?} from {} and also, as a compatibility source, from {}",
589                    spec.display_name,
590                    self.display(&native.file),
591                    self.display(&compat.file)
592                ),
593            };
594            push_unique(
595                &mut warnings,
596                CoreError::new(ErrorCode::DuplicateViaCompat, message).with_path(&compat.file),
597            );
598        }
599        if heads.len() > 1 {
600            let files: Vec<String> = heads.iter().map(|head| self.display(&head.file)).collect();
601            push_unique(
602                &mut warnings,
603                CoreError::new(
604                    ErrorCode::DuplicateAcrossLayers,
605                    format!(
606                        "{} runs a separate server named {name:?} from each of {}: same-named \
607                         entries of its own files do not replace each other",
608                        spec.display_name,
609                        files.join(" and ")
610                    ),
611                )
612                .with_path(&winner.file),
613            );
614        }
615        for problem in group.iter().filter_map(|c| c.problem.as_ref()) {
616            push_unique(&mut warnings, problem.clone());
617        }
618        for (member, problem) in &cx.member_problems {
619            if member == name {
620                push_unique(&mut warnings, problem.clone());
621            }
622        }
623        for (entry, warning) in &cx.project_warnings {
624            if entry == name {
625                push_unique(&mut warnings, warning.clone());
626            }
627        }
628        if let Some(extension) = &cx.extension {
629            push_unique(&mut warnings, extension.clone());
630        }
631        // Surjection's own project entry of a client that lists new project
632        // servers as disabled (Cursor): "loaded" assumes the user enabled it
633        // there once.
634        if loaded
635            && !winner.compat
636            && matches!(winner.layer, Layer::Project | Layer::ProjectLocal)
637            && let Some(hint) = client_enable_required(spec, &[name], &winner.file)
638        {
639            push_unique(&mut warnings, hint);
640        }
641
642        let shadowed = live
643            .iter()
644            .filter(|candidate| !std::ptr::eq(**candidate, winner))
645            .map(|candidate| Shadowed {
646                layer: candidate.layer.clone(),
647                file: self.display(&candidate.file),
648                read_only: None,
649            })
650            .collect();
651        let also_visible_to = self.readers_of(spec.id, &winner.file, &winner.pointer);
652        EffectiveEntry {
653            name: name.to_owned(),
654            loaded,
655            winner: Winner {
656                layer: winner.layer.clone(),
657                file: self.display(&winner.file),
658                source: winner.source.clone(),
659                read_only: None,
660            },
661            shadowed,
662            also_visible_to,
663            status: winner.status,
664            warnings,
665            snippet: winner.snippet.clone(),
666        }
667    }
668
669    /// The files and containers `spec` reads, highest precedence first:
670    /// its own layers, each after the compatibility sources that outrank
671    /// it, then its other compatibility sources (those with an adapter in
672    /// this build). Problems are reported when `warn`.
673    fn sources(&mut self, spec: &'static AdapterSpec, warn: bool) -> Vec<SourceFile> {
674        let Some(mcp) = spec.mcp.as_ref() else {
675            return Vec::new();
676        };
677        let mut out = Vec::new();
678        for source in mcp.caps.precedence {
679            for compat in mcp.caps.compat_reads {
680                if compat
681                    .outranks
682                    .is_some_and(|outrank| outrank.source == *source)
683                {
684                    self.push_compat(compat, &mut out);
685                }
686            }
687            self.push_sources(spec, scope_of(*source), false, None, warn, &mut out);
688        }
689        for compat in mcp.caps.compat_reads {
690            if compat.outranks.is_none() {
691                self.push_compat(compat, &mut out);
692            }
693        }
694        out
695    }
696
697    /// Adds the files and containers of compatibility source `compat`.
698    fn push_compat(&mut self, compat: &CompatSource, out: &mut Vec<SourceFile>) {
699        if let Some(other) = adapter(compat.client) {
700            let scope = scope_of(compat.source);
701            self.push_sources(other, scope, true, compat.outranks, false, out);
702        }
703    }
704
705    /// Adds the files and containers of `spec` in `scope`: another tool's
706    /// file when `compat`, ranked as `outrank` says.
707    fn push_sources(
708        &mut self,
709        spec: &'static AdapterSpec,
710        scope: Scope,
711        compat: bool,
712        outrank: Option<Outrank>,
713        warn: bool,
714        out: &mut Vec<SourceFile>,
715    ) {
716        let os = self.cx.env.os();
717        let Some(mcp) = spec.mcp.as_ref().filter(|_| on_os(spec, os)) else {
718            return;
719        };
720        let root = match (scope, self.root) {
721            (Scope::User, _) => None,
722            (_, Some(root)) => Some(root),
723            (_, None) => return,
724        };
725        let prefs = self.inputs.desired.prefs(spec.id);
726        let target = match spec.mcp_targets(self.cx.env, self.cx.fs, scope, root, &prefs) {
727            // The first user file: the default profile (omp), never an MSIX
728            // copy.
729            Ok(mut targets) if !targets.is_empty() => targets.swap_remove(0),
730            Ok(_) => return,
731            Err(err) => {
732                if warn {
733                    push_unique(&mut self.warnings, err);
734                }
735                return;
736            }
737        };
738        let legacy = match scope {
739            Scope::ProjectLocal => &[][..],
740            Scope::User | Scope::Project => mcp.legacy_containers,
741        };
742        for container in std::iter::once(target.container).chain(legacy.iter().copied()) {
743            let keys = match container.keys(os, root) {
744                Ok(keys) => keys,
745                Err(err) => {
746                    if warn {
747                        push_unique(&mut self.warnings, err.with_path(&target.file));
748                    }
749                    continue;
750                }
751            };
752            let pointer = container_pointer(&keys);
753            if out
754                .iter()
755                .any(|source| source.file == target.file && source.pointer == pointer)
756            {
757                continue;
758            }
759            out.push(SourceFile {
760                scope,
761                compat,
762                outrank,
763                file: target.file.clone(),
764                format: target.format,
765                keys,
766                pointer,
767            });
768        }
769    }
770
771    /// Adds the candidates of `source`: the entries in the file, then the
772    /// entries the plan creates there or cannot write.
773    fn candidates(&mut self, source: &SourceFile, rows: &mut BTreeMap<String, Vec<Candidate>>) {
774        let present = self.entries_in(source);
775        let file = source.file.to_string_lossy();
776        let targets = self.targets(&source.file, &source.pointer, EntryKind::McpEntry);
777        // The first planned entry of each name, by target, then entry.
778        let mut planned_entries: HashMap<&str, (&TargetPlan, &EntryPlan)> = HashMap::new();
779        for target in &targets {
780            for entry in &target.entries {
781                planned_entries
782                    .entry(entry.name.as_str())
783                    .or_insert((*target, entry));
784            }
785        }
786        let planned_entry = |name: &str| planned_entries.get(name).copied();
787        let display = self.display(&source.file);
788        for (name, value) in &present {
789            let planned = planned_entry(name);
790            // Any slot: a file the client reads may be owned through another
791            // client's scope (a compatibility source).
792            let owned = self.owners.get(&file, &source.pointer, name);
793            // Surjection's entry: owned, or desired here and equal to what is
794            // there (adopted on apply).
795            let ours: Option<(Scope, String)> = match (owned, planned) {
796                (Some(row), _) => Some((
797                    row.scope,
798                    row.server_id.clone().unwrap_or_else(|| name.clone()),
799                )),
800                (None, Some((target, entry)))
801                    if entry.desired.is_some() && entry.state != EntryState::Collision =>
802                {
803                    Some((
804                        target.scope,
805                        entry.server_id.clone().unwrap_or_else(|| name.clone()),
806                    ))
807                }
808                _ => None,
809            };
810            let status = match (planned, &ours) {
811                (Some((_, entry)), _) => Some(entry.state),
812                (None, None) => Some(EntryState::Foreign),
813                (None, Some(_)) => None,
814            };
815            // Masked by the file's plan when Surjection plans this file.
816            let snippet = match planned
817                .map(|(target, _)| target)
818                .or(targets.first().copied())
819            {
820                Some(target) => target.snippet(name, value),
821                None => unplanned_snippet(source, name, value),
822            };
823            rows.entry(name.clone()).or_default().push(Candidate {
824                layer: layer(source, ours.is_some(), &display),
825                file: source.file.clone(),
826                pointer: source.pointer.clone(),
827                compat: source.compat,
828                outrank: source.outrank,
829                presence: Presence::File,
830                value: Some(value.clone()),
831                source: ours.as_ref().map_or_else(
832                    || "foreign".to_owned(),
833                    |(scope, id)| self.source_name(*scope, id),
834                ),
835                status,
836                problem: planned.and_then(|(_, entry)| entry.problem.clone()),
837                snippet,
838            });
839        }
840        for target in &targets {
841            for entry in &target.entries {
842                if present.iter().any(|(name, _)| *name == entry.name) {
843                    continue;
844                }
845                let presence = if entry.action == Action::Create {
846                    Presence::Planned
847                } else if entry.state == EntryState::Blocked {
848                    Presence::Blocked
849                } else {
850                    continue;
851                };
852                let id = entry.server_id.as_deref().unwrap_or(&entry.name);
853                let snippet = entry
854                    .written
855                    .as_ref()
856                    .and_then(|value| target.snippet(&entry.name, value));
857                rows.entry(entry.name.clone()).or_default().push(Candidate {
858                    layer: layer(source, true, &display),
859                    file: source.file.clone(),
860                    pointer: source.pointer.clone(),
861                    compat: source.compat,
862                    outrank: source.outrank,
863                    presence,
864                    value: entry.written.clone(),
865                    source: self.source_name(target.scope, id),
866                    status: Some(entry.state),
867                    problem: entry.problem.clone(),
868                    snippet,
869                });
870            }
871        }
872    }
873
874    /// Reads and parses `file` once; a file that cannot be read or parsed
875    /// is reported and counts as empty.
876    fn load(&mut self, file: &Path, format: Format) {
877        if self.docs.contains_key(file) {
878            return;
879        }
880        let doc = read_target(self.cx.fs, file)
881            .and_then(|bytes| {
882                bytes
883                    .map(|bytes| Document::parse(&bytes, format))
884                    .transpose()
885            })
886            .unwrap_or_else(|err| {
887                push_unique(&mut self.warnings, err.with_path(file));
888                None
889            });
890        self.docs.insert(file.to_path_buf(), doc);
891    }
892
893    /// The entries in `source` now, in file order.
894    fn entries_in(&mut self, source: &SourceFile) -> Vec<(String, NativeValue)> {
895        self.load(&source.file, source.format);
896        let Some(Some(doc)) = self.docs.get(&source.file) else {
897            return Vec::new();
898        };
899        let keys: Vec<&str> = source.keys.iter().map(String::as_str).collect();
900        let listed = doc.list(&keys).and_then(|names| {
901            let mut out = Vec::with_capacity(names.len());
902            for name in names {
903                if let Some(value) = doc.get(&keys, &name)? {
904                    out.push((name, value));
905                }
906            }
907            Ok(out)
908        });
909        listed.unwrap_or_else(|err| {
910            push_unique(&mut self.warnings, err.with_path(&source.file));
911            Vec::new()
912        })
913    }
914
915    /// The planned targets of `file` and `pointer` of `kind`.
916    fn targets(&self, file: &Path, pointer: &str, kind: EntryKind) -> Vec<&'a TargetPlan> {
917        self.planned
918            .iter()
919            .copied()
920            .filter(|target| {
921                target.file == file && target.pointer == pointer && target.kind == kind
922            })
923            .collect()
924    }
925
926    /// The `source` of an entry Surjection owns or plans for server `id` in
927    /// `scope`.
928    fn source_name(&self, scope: Scope, id: &str) -> String {
929        if scope == Scope::User {
930            return format!("store:{id}");
931        }
932        match self.entries.iter().find(|entry| entry.name == id) {
933            Some(ProjectEntry {
934                body: EntryBody::Suppression,
935                ..
936            }) => format!("store:{id}+project"),
937            Some(ProjectEntry {
938                from: Some(from), ..
939            }) => format!("store:{from}+project"),
940            _ => format!("project:{id}"),
941        }
942    }
943
944    /// Names `spec` hides in the folder through a list (Claude Code
945    /// `disabledMcpServers`): the members there now plus those the plan
946    /// adds; and the problems of members the plan cannot add.
947    fn suppressed(
948        &mut self,
949        spec: &'static AdapterSpec,
950    ) -> (Vec<String>, Vec<(String, CoreError)>) {
951        let mut members = Vec::new();
952        let mut problems = Vec::new();
953        let Some(root) = self.root else {
954            return (members, problems);
955        };
956        let listed = spec
957            .mcp
958            .as_ref()
959            .and_then(|mcp| mcp.caps.project_disable)
960            .is_some_and(|mechanism| matches!(mechanism, ProjectDisable::ListMember(_)));
961        if !listed {
962            return (members, problems);
963        }
964        let prefs = self.inputs.desired.prefs(spec.id);
965        let target = match spec.suppression_target(self.cx.env, self.cx.fs, root, &prefs) {
966            Ok(Some(target)) => target,
967            Ok(None) => return (members, problems),
968            Err(err) => {
969                push_unique(&mut self.warnings, err);
970                return (members, problems);
971            }
972        };
973        let keys = match target.container_keys() {
974            Ok(keys) => keys,
975            Err(err) => {
976                push_unique(&mut self.warnings, err.with_path(&target.file));
977                return (members, problems);
978            }
979        };
980        let pointer = container_pointer(&keys);
981        self.load(&target.file, target.format);
982        if let Some(Some(doc)) = self.docs.get(&target.file) {
983            let list: Vec<&str> = keys.iter().map(String::as_str).collect();
984            match list_members(doc, &list) {
985                Ok(listed) => members = listed,
986                Err(err) => push_unique(&mut self.warnings, err.with_path(&target.file)),
987            }
988        }
989        for target in self.targets(&target.file, &pointer, EntryKind::ListMember) {
990            for entry in &target.entries {
991                if entry.action == Action::Create && !members.contains(&entry.name) {
992                    members.push(entry.name.clone());
993                }
994                if let Some(problem) = &entry.problem {
995                    problems.push((entry.name.clone(), problem.clone()));
996                }
997            }
998        }
999        (members, problems)
1000    }
1001
1002    /// Warnings the folder's project raises for `spec`, by entry name:
1003    /// `trust_required` and `unset_not_expressible` for a client with
1004    /// project files, `cannot_suppress_in_project` for a suppression it
1005    /// cannot express.
1006    fn project_warnings(
1007        &mut self,
1008        spec: &'static AdapterSpec,
1009        has_project_files: bool,
1010    ) -> Vec<(String, CoreError)> {
1011        let mut out = Vec::new();
1012        let Some(root) = self.root else {
1013            return out;
1014        };
1015        let entries = self.entries;
1016        for entry in entries {
1017            let transport = match &entry.body {
1018                EntryBody::Server(Ok(server)) => server_transport(server, self.cx.env),
1019                EntryBody::Server(Err(_)) => None,
1020                EntryBody::Suppression => self
1021                    .inputs
1022                    .desired
1023                    .servers
1024                    .get(&entry.name)
1025                    .and_then(|server| server_transport(server, self.cx.env)),
1026            };
1027            let selected = self
1028                .detected
1029                .select(self.cx, &self.inputs.desired, &entry.clients, transport)
1030                .iter()
1031                .any(|client| client == spec.id);
1032            if !selected {
1033                continue;
1034            }
1035            if let EntryBody::Suppression = entry.body
1036                && let Err(warning) = suppression_mechanism(spec, &entry.name)
1037            {
1038                out.push((entry.name.clone(), warning));
1039            }
1040            if !has_project_files {
1041                continue;
1042            }
1043            if let Some(trust) = &self.trust {
1044                out.push((entry.name.clone(), trust.clone()));
1045            }
1046            let deep_merge = spec
1047                .mcp
1048                .as_ref()
1049                .is_some_and(|mcp| mcp.caps.project_semantics == ProjectSemantics::DeepMerge);
1050            if deep_merge
1051                && !entry.unset.is_empty()
1052                && matches!(entry.body, EntryBody::Server(Ok(_)))
1053            {
1054                let prefs = self.inputs.desired.prefs(spec.id);
1055                let file = spec
1056                    .mcp_targets(self.cx.env, self.cx.fs, Scope::Project, Some(root), &prefs)
1057                    .ok()
1058                    .and_then(|targets| targets.into_iter().next())
1059                    .map_or_else(|| root.to_path_buf(), |target| target.file);
1060                out.extend(
1061                    unset_not_expressible(spec, entry, &file)
1062                        .map(|warning| (entry.name.clone(), warning)),
1063                );
1064            }
1065        }
1066        out
1067    }
1068
1069    /// Other clients that read `file` and `pointer`, by id.
1070    fn readers_of(&mut self, client: &str, file: &Path, pointer: &str) -> Vec<&'static str> {
1071        if self.readers.is_none() {
1072            let os = self.cx.env.os();
1073            let mut readers = Vec::new();
1074            for spec in ADAPTERS.iter().copied().filter(|spec| on_os(spec, os)) {
1075                let files = self
1076                    .sources(spec, false)
1077                    .into_iter()
1078                    .map(|source| (source.file, source.pointer))
1079                    .collect();
1080                readers.push((spec.id, files));
1081            }
1082            self.readers = Some(readers);
1083        }
1084        let mut out: Vec<&'static str> = self
1085            .readers
1086            .iter()
1087            .flatten()
1088            .filter(|(id, files)| {
1089                *id != client
1090                    && files
1091                        .iter()
1092                        .any(|(other, at)| other == file && at == pointer)
1093            })
1094            .map(|(id, _)| *id)
1095            .collect();
1096        out.sort_unstable();
1097        out
1098    }
1099
1100    /// `file` with a placeholder root (`~`, `<P>`, `%APPDATA%`).
1101    fn display(&self, file: &Path) -> String {
1102        self.displayed
1103            .borrow_mut()
1104            .entry(file.to_path_buf())
1105            .or_insert_with(|| placeholder_path(self.cx.env, file, self.root))
1106            .clone()
1107    }
1108
1109    /// Fills in which files of `out` this account cannot write: from the
1110    /// plan for a planned file, else from a probe of the file (SPEC 8.2
1111    /// `read_only_target`).
1112    fn mark_read_only(&self, out: &mut BTreeMap<&'static str, Vec<EffectiveEntry>>) {
1113        let displayed = self.displayed.borrow();
1114        let mut kinds: HashMap<&str, Option<ReadOnlyKind>> = HashMap::new();
1115        let mut unplanned: Vec<(PathBuf, Option<u64>)> = Vec::new();
1116        for (file, shown) in displayed.iter() {
1117            match self.planned.iter().find(|target| target.file == *file) {
1118                Some(target) => {
1119                    kinds.insert(shown.as_str(), target.read_only);
1120                }
1121                None => unplanned.push((file.clone(), None)),
1122            }
1123        }
1124        if !unplanned.is_empty() {
1125            let found = crate::access::probe_files(self.cx.fs, &unplanned, None);
1126            for (file, _) in &unplanned {
1127                let kind = found.get(file).and_then(|access| access.read_only());
1128                kinds.insert(displayed[file].as_str(), kind);
1129            }
1130        }
1131        for entry in out.values_mut().flatten() {
1132            entry.winner.read_only = kinds.get(entry.winner.file.as_str()).copied().flatten();
1133            for shadowed in &mut entry.shadowed {
1134                shadowed.read_only = kinds.get(shadowed.file.as_str()).copied().flatten();
1135            }
1136        }
1137    }
1138}
1139
1140/// The layer of an entry in `source`: Surjection's own (`ours`) by scope,
1141/// else foreign; any entry of another tool's file is `client-compat`.
1142fn layer(source: &SourceFile, ours: bool, display: &str) -> Layer {
1143    if source.compat {
1144        return Layer::ClientCompat(display.to_owned());
1145    }
1146    if !ours {
1147        return Layer::Foreign(display.to_owned());
1148    }
1149    match source.scope {
1150        Scope::User => Layer::System,
1151        Scope::Project => Layer::Project,
1152        Scope::ProjectLocal => Layer::ProjectLocal,
1153    }
1154}
1155
1156/// The snippet of an entry in a file Surjection does not plan: rendered as
1157/// the file writes it under the innermost container key, unmasked.
1158fn unplanned_snippet(source: &SourceFile, name: &str, value: &NativeValue) -> Option<String> {
1159    let keys: Vec<&str> = source.keys.last().map(String::as_str).into_iter().collect();
1160    let mut doc = Document::empty(source.format);
1161    doc.upsert(&keys, name, value).ok()?;
1162    Some(String::from_utf8_lossy(&doc.to_bytes()).into_owned())
1163}
1164
1165/// The `enabled` key of a native entry, when it holds a boolean.
1166fn enabled_of(value: Option<&NativeValue>) -> Option<bool> {
1167    match value?.as_object()?.get("enabled")? {
1168        NativeValue::Bool(enabled) => Some(*enabled),
1169        _ => None,
1170    }
1171}
1172
1173fn push_unique(warnings: &mut Vec<CoreError>, warning: CoreError) {
1174    if !warnings
1175        .iter()
1176        .any(|w| w.code() == warning.code() && w.message() == warning.message())
1177    {
1178        warnings.push(warning);
1179    }
1180}