Skip to main content

surjection_core/apply/
import.rs

1//! Adopt and import (SPEC 8.6): native entries into the store.
2//!
3//! - [`scan_with`] lists foreign entries (no ledger record) of every
4//!   client's user files and of the project files of every project this
5//!   machine knows (trusted or not: reading changes nothing), grouped by
6//!   name. Sources with the same store definition form one variant; a
7//!   candidate with several variants is a conflict. [`scan`] reads user
8//!   files only (what `adopt --all-identical` and the migration adopt).
9//! - [`stage_import`] carries out an [`ImportRequest`]: one store server
10//!   per chosen variant (`name`, or `name-<client>` for a second variant),
11//!   with each sensitive literal extracted to the destination chosen for
12//!   it. The apply that follows adopts the native entries silently when
13//!   they render identically.
14//! - [`stage_adopt_identical`] enables existing store servers for clients
15//!   that already hold an identical entry.
16//! - [`stage_resolutions`] carries out `import` decisions of a plan ("import
17//!   their change", "respect the deletion").
18//!
19//! A read-only client (`vscode-legacy`) is a source only: what is imported
20//! from it is never enabled for it, and VS Code's `${input:...}` values are
21//! `needs_manual_secret`. A variant found only in project files becomes a
22//! store definition without enablement (a project layer comes from the
23//! project's manifests, never from a store server, SPEC 6.1); the project
24//! entry stays foreign until the project's manifest names it.
25//!
26//! Secret extraction (SPEC 11.7): every literal in `env`, `headers`,
27//! `args` and the URL goes through the classifier. An import replaces each
28//! sensitive literal by `${secret:<alias>}` and needs a destination for it
29//! ([`SecretChoice`]: the OS keyring, which receives the value read from the
30//! client file, a 1Password reference or an environment variable);
31//! without one the variant is skipped (`needs_secret_extraction`), so no
32//! value that may be a secret reaches the store. Non-sensitive literals
33//! (`LOG_LEVEL = "info"`) are imported as written. A pasted snippet
34//! ([`pasted_server`]) is extracted the same way. "Import their change"
35//! ([`server_from_native`]) still refuses sensitive literals.
36
37use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
38use std::path::PathBuf;
39
40use crate::access::ReadOnlyKind;
41use crate::adapters::caps::FieldSet;
42use crate::adapters::mapper::WriteCx;
43use crate::adapters::{ADAPTERS, AdapterSpec, Target, adapter};
44use crate::apply::ledger::{Ledger, LedgerSlot, container_pointer};
45use crate::apply::plan::{Action, EntryPlan, EntryState, Plan, read_target};
46use crate::apply::render::{DesiredState, native_name, native_to_template, render};
47use crate::apply::{
48    ApplyEnv, ApplyReport, ApplyRequest, Decision, OnConflict, PlanOptions, ScopeFilter, apply_in,
49    backup,
50};
51use crate::error::{CoreError, ErrorCode};
52use crate::formats::{Document, Format, NativeValue};
53use crate::layering::projects::{overlay_doc, unknown_project};
54use crate::layering::{ProjectStatus, TrustState, TrustStore, known_projects};
55use crate::model::TomlDocument;
56use crate::model::applied::{ApplyTrigger, Scope};
57use crate::model::clients::{ClientSelection, NATIVE_NAME_KEY};
58use crate::model::ids::{self, IdKind};
59use crate::model::server::{Enable, Meta, Server, ServerFields, ToolFilter};
60use crate::model::settings::ApplyMode;
61use crate::secrets::SecretValue;
62use crate::secrets::catalog::{Catalog, overlay_path};
63use crate::secrets::classify::{classify_args_import, classify_import};
64use crate::secrets::delivery::Sharing;
65use crate::secrets::extract::{
66    self, Aliases, Extracted, Extraction, ExtractionChoice, ExtractionTarget, Extractor,
67};
68use crate::secrets::grammar::SecretRef;
69use crate::store::{Machine, Store, Transaction, server_path};
70
71/// A native entry as store fields.
72#[derive(Debug, Clone, PartialEq)]
73pub struct ImportedDef {
74    pub fields: ServerFields,
75    pub tools: Option<ToolFilter>,
76    /// The client's allowlisted native fields, for `[client.<id>]`.
77    pub passthrough: toml::Table,
78}
79
80/// Reads a native entry of `spec`'s client as store fields: client
81/// variable syntax becomes `${env:NAME}`, other `${` becomes `$${`. A
82/// literal that may be a secret is `needs_secret_extraction` (import
83/// extracts it instead, [`read_native`]).
84pub fn server_from_native(
85    spec: &AdapterSpec,
86    key: &str,
87    value: &NativeValue,
88) -> Result<ImportedDef, CoreError> {
89    let def = read_native(spec, key, value)?;
90    match sensitive_field(&def.fields) {
91        // Named by position or key, never by value: the message may reach
92        // a UI.
93        Some(what) => Err(CoreError::new(
94            ErrorCode::NeedsSecretExtraction,
95            format!("{what} may be a secret; it needs secret extraction before import"),
96        )),
97        None => Ok(def),
98    }
99}
100
101/// A pasted snippet's entry (SPEC 13.2, #45) as the fields of store server
102/// `id`: [`read_native`] with each sensitive literal replaced by a
103/// `${secret:<alias>}` reference (aliases from `aliases`), returned with
104/// its value for the caller to route (the OS keyring, a reference, or an
105/// alias left without a value). The values stay in memory.
106pub fn pasted_server(
107    spec: &AdapterSpec,
108    key: &str,
109    value: &NativeValue,
110    id: &str,
111    aliases: &mut Aliases,
112) -> Result<(ImportedDef, Vec<Extracted>), CoreError> {
113    let mut def = read_native(spec, key, value)?;
114    let mut extractor = Extractor::new(id, aliases);
115    extractor.fields(&mut def.fields)?;
116    Ok((def, extractor.finish()))
117}
118
119/// [`server_from_native`] with sensitive literals kept as they are, for an
120/// import that extracts them. The result may hold secret values: it stays
121/// in memory and is never formatted into a message.
122pub fn read_native(
123    spec: &AdapterSpec,
124    key: &str,
125    value: &NativeValue,
126) -> Result<ImportedDef, CoreError> {
127    let mcp = spec.mcp.as_ref().ok_or_else(|| {
128        CoreError::new(
129            ErrorCode::ScopeNotSupported,
130            format!("{} has no MCP config", spec.display_name),
131        )
132    })?;
133    let def = mcp.mapper.from_native(key, value)?;
134    if def.headers_helper.is_some() {
135        return Err(CoreError::new(
136            ErrorCode::UnsupportedField,
137            "`headersHelper` has no store field yet",
138        ));
139    }
140    let caps = &mcp.caps;
141    let convert = |text: &str, field: FieldSet| {
142        native_to_template(text, caps, field).ok_or_else(|| {
143            CoreError::new(
144                ErrorCode::UnsupportedField,
145                format!(
146                    "a value uses a {} variable or command form the store cannot express",
147                    spec.display_name
148                ),
149            )
150        })
151    };
152    let native = def.fields;
153    if let Some(what) = prompted_input(&native) {
154        return Err(CoreError::new(
155            ErrorCode::NeedsManualSecret,
156            format!(
157                "{what} is a {} `${{input:...}}` value the editor prompts for; store the \
158                 value as a secret by hand (`surject secrets set`) and reference it",
159                spec.display_name
160            ),
161        ));
162    }
163    let mut fields = ServerFields {
164        transport: native.transport,
165        ..ServerFields::default()
166    };
167    if let Some(command) = &native.command {
168        fields.command = Some(convert(command, FieldSet::COMMAND)?);
169    }
170    if let Some(args) = &native.args {
171        let args = args
172            .iter()
173            .map(|arg| convert(arg, FieldSet::ARGS))
174            .collect::<Result<Vec<_>, _>>()?;
175        fields.args = (!args.is_empty()).then_some(args);
176    }
177    if let Some(cwd) = &native.cwd {
178        fields.cwd = Some(convert(cwd, FieldSet::CWD)?);
179    }
180    if let Some(url) = &native.url {
181        fields.url = Some(convert(url, FieldSet::URL)?);
182    }
183    for (field, source, target) in [
184        (FieldSet::ENV, &native.env, &mut fields.env),
185        (FieldSet::HEADERS, &native.headers, &mut fields.headers),
186    ] {
187        let mut map = BTreeMap::new();
188        for (name, value) in source.iter().flatten() {
189            map.insert(name.clone(), convert(value, field)?);
190        }
191        *target = (!map.is_empty()).then_some(map);
192    }
193    let tools = (!def.tools.is_empty()).then(|| ToolFilter {
194        allow: def.tools.allow.clone(),
195        deny: def.tools.deny.clone(),
196        extra: toml::Table::new(),
197    });
198    let mut passthrough = toml::Table::new();
199    for (name, value) in def.passthrough.iter() {
200        passthrough.insert(name.to_owned(), to_toml(value)?);
201    }
202    Ok(ImportedDef {
203        fields,
204        tools,
205        passthrough,
206    })
207}
208
209/// The first field holding a literal the classifier flags, by position or
210/// key.
211fn sensitive_field(fields: &ServerFields) -> Option<String> {
212    if let Some(index) = fields
213        .args
214        .as_deref()
215        .and_then(|args| classify_args_import(args).iter().position(Option::is_some))
216    {
217        return Some(format!("argument {}", index + 1));
218    }
219    if fields
220        .url
221        .as_deref()
222        .is_some_and(|url| classify_import(None, url).is_some())
223    {
224        return Some("the URL".to_owned());
225    }
226    [&fields.env, &fields.headers]
227        .into_iter()
228        .flat_map(|map| map.iter().flatten())
229        .find(|(name, value)| classify_import(Some(name), value).is_some())
230        .map(|(name, _)| format!("the literal value of {name:?}"))
231}
232
233/// The field holding a VS Code input variable (`${input:id}`), a value the
234/// editor prompts the user for and keeps itself, if any.
235fn prompted_input(fields: &ServerFields) -> Option<String> {
236    const INPUT: &str = "${input:";
237    let named = |field: &str, value: &str| value.contains(INPUT).then(|| field.to_owned());
238    fields
239        .command
240        .as_deref()
241        .and_then(|value| named("`command`", value))
242        .or_else(|| {
243            fields
244                .args
245                .iter()
246                .flatten()
247                .find_map(|arg| arg.contains(INPUT).then(|| format!("argument {arg:?}")))
248        })
249        .or_else(|| {
250            fields
251                .cwd
252                .as_deref()
253                .and_then(|value| named("`cwd`", value))
254        })
255        .or_else(|| {
256            fields
257                .url
258                .as_deref()
259                .and_then(|value| named("the URL", value))
260        })
261        .or_else(|| {
262            [("env", &fields.env), ("headers", &fields.headers)]
263                .into_iter()
264                .find_map(|(kind, map)| {
265                    map.iter().flatten().find_map(|(name, value)| {
266                        value
267                            .contains(INPUT)
268                            .then(|| format!("the {kind} value of {name:?}"))
269                    })
270                })
271        })
272}
273
274fn to_toml(value: &NativeValue) -> Result<toml::Value, CoreError> {
275    Ok(match value {
276        NativeValue::Null => {
277            return Err(CoreError::new(
278                ErrorCode::InvalidValue,
279                "`null` has no TOML form",
280            ));
281        }
282        NativeValue::Bool(b) => toml::Value::Boolean(*b),
283        NativeValue::Integer(n) => toml::Value::Integer(*n),
284        NativeValue::Float(n) => toml::Value::Float(*n),
285        NativeValue::String(s) => toml::Value::String(s.clone()),
286        NativeValue::Datetime(d) => d
287            .parse()
288            .map(toml::Value::Datetime)
289            .unwrap_or_else(|_| toml::Value::String(d.clone())),
290        NativeValue::Array(items) => {
291            toml::Value::Array(items.iter().map(to_toml).collect::<Result<_, _>>()?)
292        }
293        NativeValue::Object(map) => toml::Value::Table(
294            map.iter()
295                .map(|(key, item)| Ok((key.to_owned(), to_toml(item)?)))
296                .collect::<Result<_, CoreError>>()?,
297        ),
298    })
299}
300
301/// The known project whose files held a source.
302#[derive(Debug, Clone)]
303pub struct SourceProject {
304    /// The overlay key.
305    pub id: String,
306    pub root: PathBuf,
307    /// Its manifests are trusted on this machine as they are now. An
308    /// untrusted project is read like any other (reading changes nothing);
309    /// its manifest takes the entry only after a trust review.
310    pub trusted: bool,
311}
312
313/// Where a foreign entry was found.
314#[derive(Debug, Clone)]
315pub struct Source {
316    pub client: &'static str,
317    pub scope: Scope,
318    /// The project of a project file.
319    pub project: Option<SourceProject>,
320    /// Which of the client's files in its scope, when it has several: the
321    /// profile name (omp profiles), else the file's position (`2`, `3`:
322    /// a packaged mirror, an editor variant or profile). `None` for the
323    /// first file.
324    pub slot: Option<String>,
325    pub file: PathBuf,
326    /// The native entry.
327    pub value: NativeValue,
328    /// This account cannot write the file (SPEC 8.2 `read_only_target`):
329    /// the definition can be imported, but the entry is never overwritten
330    /// there.
331    pub read_only: Option<ReadOnlyKind>,
332    /// The entry as store fields, sensitive literals included (an import
333    /// extracts them), or why it cannot be imported.
334    pub def: Result<ImportedDef, CoreError>,
335}
336
337impl Source {
338    /// The source within its candidate: `<client>` for a user file,
339    /// `<client>@<project-id>` for a project file and
340    /// `<client>@<project-id>/local` for a private project file, with
341    /// `#<slot>` after the client for a client's second file in that scope
342    /// (`omp#work`, `claude-desktop#2`).
343    pub fn key(&self) -> String {
344        source_key(
345            self.client,
346            self.slot.as_deref(),
347            self.scope,
348            self.project.as_ref().map(|project| project.id.as_str()),
349        )
350    }
351
352    /// Importing this source enables the store server for its client: a
353    /// user file of a client Surjection writes.
354    pub fn enables(&self) -> bool {
355        self.scope == Scope::User && adapter(self.client).is_none_or(|spec| !is_read_only(spec))
356    }
357}
358
359/// [`Source::key`] from its parts.
360pub(crate) fn source_key(
361    client: &str,
362    slot: Option<&str>,
363    scope: Scope,
364    project_id: Option<&str>,
365) -> String {
366    let client = match slot {
367        Some(slot) => format!("{client}#{slot}"),
368        None => client.to_owned(),
369    };
370    match (project_id, scope) {
371        (None, _) => client,
372        (Some(id), Scope::ProjectLocal) => format!("{client}@{id}/local"),
373        (Some(id), _) => format!("{client}@{id}"),
374    }
375}
376
377/// Foreign entries sharing one name.
378#[derive(Debug, Clone)]
379pub struct Candidate {
380    pub name: String,
381    pub sources: Vec<Source>,
382    /// The sources grouped by definition (indexes into `sources`), in
383    /// first-seen order: sources that read as the same store fields and
384    /// tool filter share a variant; one that cannot be imported is a
385    /// variant of its own.
386    pub variants: Vec<Vec<usize>>,
387    /// One variant, and it can be imported.
388    pub identical: bool,
389    /// The store already has a server with this id.
390    pub in_store: bool,
391}
392
393impl Candidate {
394    /// The variant holding the source with key `key` ([`Source::key`]).
395    pub fn variant_of(&self, key: &str) -> Option<usize> {
396        self.variants
397            .iter()
398            .position(|v| v.iter().any(|&i| self.sources[i].key() == key))
399    }
400
401    /// The definition of variant `v`, or why it cannot be imported.
402    pub fn variant_def(&self, v: usize) -> Result<&ImportedDef, &CoreError> {
403        self.sources[self.variants[v][0]].def.as_ref()
404    }
405
406    /// The variants that can be imported.
407    pub fn importable(&self) -> Vec<usize> {
408        (0..self.variants.len())
409            .filter(|&v| self.variant_def(v).is_ok())
410            .collect()
411    }
412
413    /// Differing definitions: more than one variant can be imported.
414    pub fn conflict(&self) -> bool {
415        self.importable().len() > 1
416    }
417
418    /// Importing variant `v` enables the server for some client (it was
419    /// found in a user file); otherwise it becomes a definition only.
420    pub fn enables(&self, v: usize) -> bool {
421        self.variants[v].iter().any(|&i| self.sources[i].enables())
422    }
423
424    /// The store id each variant gets by default: the name in lower case
425    /// for the first variant that can be imported, `name-<client>` for the
426    /// others (the client of the variant's first user file, else of its
427    /// first source), numbered when two would be the same.
428    pub fn suggested_ids(&self) -> Vec<String> {
429        let base = self.name.to_ascii_lowercase();
430        let mut taken = BTreeSet::new();
431        let mut named = false;
432        let mut ids = Vec::with_capacity(self.variants.len());
433        for (v, indexes) in self.variants.iter().enumerate() {
434            let id = if !named && self.variant_def(v).is_ok() {
435                named = true;
436                base.clone()
437            } else {
438                let source = indexes
439                    .iter()
440                    .map(|&i| &self.sources[i])
441                    .find(|source| source.scope == Scope::User)
442                    .unwrap_or(&self.sources[indexes[0]]);
443                format!("{base}-{}", source.client)
444            };
445            let mut unique = id.clone();
446            let mut n = 2;
447            while !taken.insert(unique.clone()) {
448                unique = format!("{id}-{n}");
449                n += 1;
450            }
451            ids.push(unique);
452        }
453        ids
454    }
455
456    /// Importing the variant of the source with key `source`
457    /// ([`Source::key`]), else of the source found in client `source` (its
458    /// user file first), under the name, or with `rename` as
459    /// `name-<client>`.
460    pub fn choice_for(&self, source: &str, rename: bool) -> Result<VariantChoice, CoreError> {
461        let found = self
462            .sources
463            .iter()
464            .find(|candidate| candidate.key() == source)
465            .or_else(|| {
466                self.sources
467                    .iter()
468                    .filter(|candidate| candidate.client == source)
469                    .min_by_key(|candidate| candidate.scope != Scope::User)
470            })
471            .ok_or_else(|| {
472                CoreError::new(
473                    ErrorCode::NotFound,
474                    format!("{:?} was not found in {source}", self.name),
475                )
476            })?;
477        let base = self.name.to_ascii_lowercase();
478        Ok(VariantChoice {
479            name: self.name.clone(),
480            source: found.key(),
481            id: if rename {
482                format!("{base}-{}", found.client)
483            } else {
484                base
485            },
486        })
487    }
488
489    fn group(&mut self) {
490        let mut variants: Vec<Vec<usize>> = Vec::new();
491        for (index, source) in self.sources.iter().enumerate() {
492            let found = source.def.as_ref().ok().and_then(|def| {
493                variants.iter().position(|v| {
494                    matches!(&self.sources[v[0]].def,
495                        Ok(first) if first.fields == def.fields && first.tools == def.tools)
496                })
497            });
498            match found {
499                Some(v) => variants[v].push(index),
500                None => variants.push(vec![index]),
501            }
502        }
503        self.identical = variants.len() == 1 && self.sources[0].def.is_ok();
504        self.variants = variants;
505    }
506
507    fn conflict_error(&self) -> CoreError {
508        let keys: Vec<String> = self.sources.iter().map(Source::key).collect();
509        CoreError::new(
510            ErrorCode::Collision,
511            format!(
512                "{:?} differs between {}; pick one (`--pick NAME=CLIENT`) or import several \
513                 (`--as NAME=CLIENT` imports one as NAME-CLIENT)",
514                self.name,
515                keys.join(", ")
516            ),
517        )
518    }
519}
520
521/// Which files a scan reads.
522#[derive(Debug, Clone, Default, PartialEq, Eq)]
523pub enum ScanScope {
524    /// Every client's user files and every known project's files.
525    #[default]
526    All,
527    /// User files only.
528    User,
529    /// The files of every known project.
530    Projects,
531    /// The files of one known project, by id.
532    Project(String),
533}
534
535/// What a scan reads.
536#[derive(Debug, Clone, Default)]
537pub struct ScanFilter {
538    /// Only these clients (`None`: every client).
539    pub clients: Option<Vec<String>>,
540    pub scope: ScanScope,
541}
542
543/// Foreign entries of the selected clients' user files (no ledger record),
544/// grouped by name in first-seen order. Read-only.
545pub fn scan(
546    ax: &ApplyEnv<'_>,
547    desired: &DesiredState,
548    ledger: &Ledger,
549    clients: Option<&[String]>,
550) -> Result<(Vec<Candidate>, Vec<CoreError>), CoreError> {
551    let filter = ScanFilter {
552        clients: clients.map(<[String]>::to_vec),
553        scope: ScanScope::User,
554    };
555    scan_with(ax, desired, ledger, &filter)
556}
557
558/// Foreign entries (no ledger record) of the files `filter` selects: user
559/// files, and the project and private project files of the projects this
560/// machine knows (`desired`'s overlay), trusted or not. Grouped by name in
561/// first-seen order, user files first. Read-only. A project that is
562/// missing is left out, one that cannot be loaded is a warning; an unknown
563/// project id is `not_found`.
564pub fn scan_with(
565    ax: &ApplyEnv<'_>,
566    desired: &DesiredState,
567    ledger: &Ledger,
568    filter: &ScanFilter,
569) -> Result<(Vec<Candidate>, Vec<CoreError>), CoreError> {
570    let mut candidates: Vec<Candidate> = Vec::new();
571    let mut by_name: HashMap<String, usize> = HashMap::new();
572    let mut keys: HashSet<(usize, String)> = HashSet::new();
573    let mut skips = Vec::new();
574    let mut warnings = Vec::new();
575    walk(ax, desired, ledger, filter, &mut warnings, &mut |found| {
576        let Some(value) = found.doc.get(found.container, &found.name)? else {
577            return Ok(());
578        };
579        let spec = found.spec;
580        let name = found.name;
581        if let Some(reason) = spec
582            .mcp
583            .as_ref()
584            .and_then(|mcp| mcp.mapper.skipped_by_client(&value))
585        {
586            skips.push(
587                CoreError::new(
588                    ErrorCode::ClientSkipsEntry,
589                    format!(
590                        "{} entry {name:?} {reason}; importing it starts a server {} does not \
591                         run today",
592                        spec.display_name, spec.display_name
593                    ),
594                )
595                .with_path(&found.target.file),
596            );
597        }
598        let def = read_native(spec, &name, &value);
599        let source = Source {
600            client: spec.id,
601            scope: found.target.scope,
602            project: found.project.cloned(),
603            slot: found.slot,
604            file: found.target.file.clone(),
605            value,
606            read_only: None,
607            def,
608        };
609        let at = match by_name.get(&name) {
610            Some(&at) => at,
611            None => {
612                by_name.insert(name.clone(), candidates.len());
613                candidates.push(Candidate {
614                    in_store: desired.servers.contains_key(&name.to_ascii_lowercase()),
615                    name,
616                    sources: Vec::new(),
617                    variants: Vec::new(),
618                    identical: false,
619                });
620                candidates.len() - 1
621            }
622        };
623        if keys.insert((at, source.key())) {
624            candidates[at].sources.push(source);
625        }
626        Ok(())
627    })?;
628    warnings.extend(skips);
629    mark_read_only(ax, &mut candidates);
630    for candidate in &mut candidates {
631        candidate.group();
632    }
633    Ok((candidates, warnings))
634}
635
636/// Probes the files the sources were found in (SPEC 8.2
637/// `read_only_target`), all together under the probe budget.
638fn mark_read_only(ax: &ApplyEnv<'_>, candidates: &mut [Candidate]) {
639    let mut files: Vec<(PathBuf, Option<u64>)> = Vec::new();
640    for source in candidates.iter().flat_map(|candidate| &candidate.sources) {
641        if !files.iter().any(|(file, _)| *file == source.file) {
642            files.push((source.file.clone(), None));
643        }
644    }
645    if files.is_empty() {
646        return;
647    }
648    let found = crate::access::probe_files(ax.fs, &files, None);
649    for source in candidates
650        .iter_mut()
651        .flat_map(|candidate| &mut candidate.sources)
652    {
653        source.read_only = found
654            .get(&source.file)
655            .and_then(|access| access.read_only());
656    }
657}
658
659/// One foreign entry [`walk`] meets.
660pub(crate) struct Found<'a> {
661    pub spec: &'static AdapterSpec,
662    pub target: &'a Target,
663    pub project: Option<&'a SourceProject>,
664    /// [`Source::slot`].
665    pub slot: Option<String>,
666    pub doc: &'a Document,
667    pub container: &'a [&'a str],
668    pub name: String,
669}
670
671/// Calls `visit` for every foreign entry of the files `filter` selects (see
672/// [`scan_with`]), in file order. Each file is read and parsed once, however
673/// many targets it holds (`~/.claude.json`: the user container and one per
674/// project); ownership is looked up once per target.
675pub(crate) fn walk(
676    ax: &ApplyEnv<'_>,
677    desired: &DesiredState,
678    ledger: &Ledger,
679    filter: &ScanFilter,
680    warnings: &mut Vec<CoreError>,
681    visit: &mut dyn FnMut(Found<'_>) -> Result<(), CoreError>,
682) -> Result<(), CoreError> {
683    let selected: Vec<&'static AdapterSpec> = ADAPTERS
684        .iter()
685        .copied()
686        .filter(|spec| {
687            filter
688                .clients
689                .as_ref()
690                .is_none_or(|ids| ids.iter().any(|id| id == spec.id))
691        })
692        .collect();
693    let mut files = Files::default();
694    let mut read = |spec: &'static AdapterSpec,
695                    targets: &[Target],
696                    project: Option<&SourceProject>,
697                    warnings: &mut Vec<CoreError>|
698     -> Result<(), CoreError> {
699        for (index, target) in targets.iter().enumerate() {
700            let Some(doc) = files.doc(ax.fs, target, warnings)? else {
701                continue;
702            };
703            let keys = target.container_keys()?;
704            let container: Vec<&str> = keys.iter().map(String::as_str).collect();
705            let names = match doc.list(&container) {
706                Ok(names) => names,
707                Err(err) => {
708                    warnings.push(err.with_path(&target.file));
709                    continue;
710                }
711            };
712            let pointer = container_pointer(&keys);
713            let file = target.file.to_string_lossy().into_owned();
714            let owned: HashSet<&str> = ledger
715                .in_container(LedgerSlot {
716                    scope: target.scope,
717                    project_id: project.map(|project| project.id.as_str()),
718                    file: &file,
719                    container: &pointer,
720                })
721                .map(|entry| entry.key.as_str())
722                .collect();
723            let slot = target
724                .profile
725                .clone()
726                .or_else(|| (index > 0).then(|| (index + 1).to_string()));
727            for name in names {
728                if owned.contains(name.as_str()) {
729                    continue;
730                }
731                visit(Found {
732                    spec,
733                    target,
734                    project,
735                    slot: slot.clone(),
736                    doc,
737                    container: &container,
738                    name,
739                })?;
740            }
741        }
742        Ok(())
743    };
744    if matches!(filter.scope, ScanScope::All | ScanScope::User) {
745        for &spec in &selected {
746            let prefs = desired.prefs(spec.id);
747            if let Ok(targets) = spec.mcp_targets(ax.env, ax.fs, Scope::User, None, &prefs) {
748                read(spec, &targets, None, warnings)?;
749            }
750        }
751    }
752    if filter.scope != ScanScope::User {
753        let trust = TrustStore::load(ax.fs, &ax.home.state_dir()).unwrap_or_else(|err| {
754            warnings.push(err);
755            TrustStore::default()
756        });
757        let known = known_projects(ax.fs, ax.env, desired.overlay.as_ref(), &trust);
758        if let ScanScope::Project(id) = &filter.scope
759            && !known.iter().any(|project| &project.id == id)
760        {
761            return Err(unknown_project(id));
762        }
763        for project in &known {
764            if matches!(&filter.scope, ScanScope::Project(id) if *id != project.id) {
765                continue;
766            }
767            let trusted = match &project.status {
768                ProjectStatus::Missing => continue,
769                ProjectStatus::Failed(err) => {
770                    warnings.push(err.clone());
771                    continue;
772                }
773                ProjectStatus::Loaded { trust, .. } => *trust == TrustState::Trusted,
774            };
775            let source_project = SourceProject {
776                id: project.id.clone(),
777                root: project.root.clone(),
778                trusted,
779            };
780            for &spec in &selected {
781                let prefs = desired.prefs(spec.id);
782                for scope in [Scope::Project, Scope::ProjectLocal] {
783                    if let Ok(targets) =
784                        spec.mcp_targets(ax.env, ax.fs, scope, Some(&project.root), &prefs)
785                    {
786                        read(spec, &targets, Some(&source_project), warnings)?;
787                    }
788                }
789            }
790        }
791    }
792    Ok(())
793}
794
795/// The client files one scan read: each read and parsed once (a parse
796/// error is reported once, for the first target that reads the file).
797#[derive(Default)]
798struct Files {
799    docs: HashMap<(PathBuf, Format), Option<Document>>,
800}
801
802impl Files {
803    fn doc(
804        &mut self,
805        fs: &dyn crate::fs::Fs,
806        target: &Target,
807        warnings: &mut Vec<CoreError>,
808    ) -> Result<Option<&Document>, CoreError> {
809        let key = (target.file.clone(), target.format);
810        if !self.docs.contains_key(&key) {
811            let doc = match read_target(fs, &target.file)? {
812                None => None,
813                Some(bytes) => match Document::parse(&bytes, target.format) {
814                    Ok(doc) => Some(doc),
815                    Err(err) => {
816                        warnings.push(err.with_path(&target.file));
817                        None
818                    }
819                },
820            };
821            self.docs.insert(key.clone(), doc);
822        }
823        Ok(self.docs[&key].as_ref())
824    }
825}
826
827/// What a scan runs against as this machine sees the store: the desired
828/// state (an empty one when there is no store yet) with this machine's
829/// overlay, and the ledger. Read-only: creates nothing.
830pub fn store_inputs(
831    store: Option<&Store<'_>>,
832    ax: &ApplyEnv<'_>,
833) -> Result<(DesiredState, Ledger), CoreError> {
834    let state = ax.home.state_dir();
835    let machine = Machine::load(ax.fs, &state)?;
836    let desired = match store {
837        Some(store) => DesiredState::load(store, machine.as_ref().map(|m| m.id.as_str()))?,
838        None => DesiredState::empty(),
839    };
840    Ok((desired, Ledger::load(ax.fs, &state)?))
841}
842
843/// A scan as this machine sees the store: its known projects and its
844/// ledger ([`scan_with`]), with the desired state it was made against.
845pub struct StoreScan {
846    pub candidates: Vec<Candidate>,
847    pub warnings: Vec<CoreError>,
848    pub desired: DesiredState,
849}
850
851/// [`scan_with`] against `store`, or an empty desired state when there is
852/// no store yet. Read-only: creates nothing.
853pub fn scan_store(
854    store: Option<&Store<'_>>,
855    ax: &ApplyEnv<'_>,
856    filter: &ScanFilter,
857) -> Result<StoreScan, CoreError> {
858    let (desired, ledger) = store_inputs(store, ax)?;
859    let (candidates, warnings) = scan_with(ax, &desired, &ledger, filter)?;
860    Ok(StoreScan {
861        candidates,
862        warnings,
863        desired,
864    })
865}
866
867/// What importing one variant under its suggested id stores.
868#[derive(Debug, Clone)]
869pub struct VariantPreview {
870    /// [`Candidate::suggested_ids`].
871    pub id: String,
872    /// The server as it would be stored (references in place of sensitive
873    /// literals), or why the variant cannot be imported.
874    pub server: Result<Server, CoreError>,
875    /// The sensitive literals that need a destination, with suggested
876    /// aliases. No value.
877    pub extractions: Vec<Extraction>,
878}
879
880/// [`VariantPreview`]s of every variant of `candidates` (same order),
881/// aliases suggested against `catalog` and each other.
882pub fn previews(candidates: &[Candidate], catalog: &Catalog) -> Vec<Vec<VariantPreview>> {
883    let mut aliases = Aliases::new(catalog.iter().map(|alias| alias.alias.clone()));
884    candidates
885        .iter()
886        .map(|candidate| {
887            candidate
888                .suggested_ids()
889                .into_iter()
890                .enumerate()
891                .map(
892                    |(v, id)| match variant_server(candidate, v, &id, false, &mut aliases) {
893                        Ok((server, extracted)) => VariantPreview {
894                            id,
895                            server: Ok(server),
896                            extractions: extracted
897                                .into_iter()
898                                .map(|extracted| extracted.extraction)
899                                .collect(),
900                        },
901                        Err(err) => VariantPreview {
902                            id,
903                            server: Err(err),
904                            extractions: Vec::new(),
905                        },
906                    },
907                )
908                .collect()
909        })
910        .collect()
911}
912
913/// The store server variant `v` of `candidate` becomes under `id`, each
914/// sensitive literal replaced by a `${secret:<alias>}` reference (aliases
915/// from `aliases`), and the values replaced. It is enabled for the clients
916/// whose user file holds the variant, unless `only`; a variant found only
917/// in project files or read-only clients becomes a definition without
918/// enablement.
919pub fn variant_server(
920    candidate: &Candidate,
921    v: usize,
922    id: &str,
923    only: bool,
924    aliases: &mut Aliases,
925) -> Result<(Server, Vec<Extracted>), CoreError> {
926    ids::check(IdKind::Server, id)?;
927    let indexes = candidate.variants.get(v).ok_or_else(|| {
928        CoreError::new(
929            ErrorCode::NotFound,
930            format!("{:?} has no variant {v}", candidate.name),
931        )
932    })?;
933    let sources: Vec<&Source> = indexes.iter().map(|&i| &candidate.sources[i]).collect();
934    let first = sources[0].def.as_ref().map_err(Clone::clone)?;
935    let mut fields = first.fields.clone();
936    let mut extractor = Extractor::new(id, aliases);
937    extractor.fields(&mut fields)?;
938    let extracted = extractor.finish();
939    let mut server = Server::new(id.to_owned());
940    set_fields(&mut server, &fields, first.tools.clone());
941    // Read-only clients (`vscode-legacy`) and project files are sources
942    // only: no enablement, and no `[client.<id>]` table. A source in a
943    // file this account cannot write enables its client only when nothing
944    // is extracted, so the entry can be adopted as it is, without a write.
945    let enabling: Vec<&Source> = sources
946        .iter()
947        .copied()
948        .filter(|source| source.enables() && (source.read_only.is_none() || extracted.is_empty()))
949        .collect();
950    let mut clients = BTreeMap::new();
951    for source in &enabling {
952        let Ok(def) = &source.def else {
953            continue;
954        };
955        let mut table = def.passthrough.clone();
956        if candidate.name != id {
957            table.insert(
958                NATIVE_NAME_KEY.to_owned(),
959                toml::Value::String(candidate.name.clone()),
960            );
961        }
962        if !table.is_empty() {
963            clients.insert(source.client.to_owned(), table);
964        }
965    }
966    server.body.client = (!clients.is_empty()).then_some(clients);
967    server.body.meta = Some(Meta {
968        origin: Some(format!("imported:{}", sources[0].client)),
969        ..Meta::default()
970    });
971    if !only && !enabling.is_empty() {
972        server.enable = Some(Enable {
973            clients: Some(ClientSelection::List({
974                let mut ids: Vec<String> = Vec::new();
975                for source in &enabling {
976                    if !ids.iter().any(|id| id == source.client) {
977                        ids.push(source.client.to_owned());
978                    }
979                }
980                ids
981            })),
982            ..Enable::default()
983        });
984    }
985    if let Some(err) = server.validate(Some(id)).first_error(None) {
986        return Err(err);
987    }
988    Ok((server, extracted))
989}
990
991/// One variant to import: the candidate, any source of the variant
992/// ([`Source::key`]) and the store id it becomes.
993#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct VariantChoice {
995    pub name: String,
996    pub source: String,
997    pub id: String,
998}
999
1000/// Where a sensitive literal goes (SPEC 11.7).
1001#[derive(Debug, Clone, PartialEq, Eq)]
1002pub enum SecretDestination {
1003    /// The OS keyring (`keyring://surjection/<alias>`), which receives the
1004    /// value read from the client file.
1005    Keyring,
1006    /// A 1Password item (`op://...`) or Environment variable
1007    /// (`op-env://...`), or an environment variable (`env:NAME`). Nothing
1008    /// is uploaded anywhere.
1009    Reference(SecretRef),
1010}
1011
1012impl SecretDestination {
1013    /// `keyring`, `op://vault/item/field` (also written `op:op://...`),
1014    /// `op-env://<environment-id>/<NAME>` or `env:NAME`.
1015    pub fn parse(text: &str) -> Result<Self, CoreError> {
1016        let text = text.trim();
1017        if text == "keyring" {
1018            return Ok(Self::Keyring);
1019        }
1020        if let Some(name) = text.strip_prefix("env:") {
1021            return extract::env_reference(name).map(Self::Reference);
1022        }
1023        let reference = match text.strip_prefix("op:") {
1024            Some(rest) if rest.starts_with("op://") || rest.starts_with("op-env://") => rest,
1025            _ => text,
1026        };
1027        if reference.starts_with("op://") {
1028            return extract::onepassword_reference(reference).map(Self::Reference);
1029        }
1030        if reference.starts_with("op-env://")
1031            && let reference @ SecretRef::OnePasswordEnvironment { .. } =
1032                SecretRef::parse(reference)?
1033        {
1034            return Ok(Self::Reference(reference));
1035        }
1036        Err(CoreError::new(
1037            ErrorCode::InvalidValue,
1038            "a destination is keyring, op://vault/item/field, op-env://<environment>/<NAME> \
1039             or env:NAME",
1040        ))
1041    }
1042
1043    /// `keyring`, `onepassword` or `env`.
1044    pub fn kind(&self) -> &'static str {
1045        match self {
1046            Self::Keyring => "keyring",
1047            Self::Reference(SecretRef::Env { .. }) => "env",
1048            Self::Reference(_) => "onepassword",
1049        }
1050    }
1051}
1052
1053/// Where the sensitive literals of candidate `name` go: one `field`
1054/// (`env.NAME`, `headers.NAME`, `args[N]`, `url`), or with `field` `None`
1055/// every one no other choice names.
1056#[derive(Debug, Clone, PartialEq, Eq)]
1057pub struct SecretChoice {
1058    pub name: String,
1059    pub field: Option<String>,
1060    pub destination: SecretDestination,
1061}
1062
1063/// What to import (one commit).
1064#[derive(Debug, Clone, Default)]
1065pub struct ImportRequest {
1066    pub picks: Vec<VariantChoice>,
1067    pub secrets: Vec<SecretChoice>,
1068    /// Copy the definitions without enabling them (no ownership taken).
1069    pub only: bool,
1070    /// Candidates left out before staging, with the reason; reported as
1071    /// skipped.
1072    pub unchosen: Vec<(String, CoreError)>,
1073}
1074
1075impl ImportRequest {
1076    /// Every candidate (or those in `names`) with one variant that can be
1077    /// imported, under its name. A conflict, or a candidate that cannot be
1078    /// imported, is left in [`ImportRequest::unchosen`].
1079    pub fn defaults(candidates: &[Candidate], names: Option<&[String]>, only: bool) -> Self {
1080        let mut request = Self {
1081            only,
1082            ..Self::default()
1083        };
1084        for candidate in candidates
1085            .iter()
1086            .filter(|candidate| names.is_none_or(|names| names.contains(&candidate.name)))
1087        {
1088            match candidate.importable().as_slice() {
1089                [v] => request.picks.push(VariantChoice {
1090                    name: candidate.name.clone(),
1091                    source: candidate.sources[candidate.variants[*v][0]].key(),
1092                    id: candidate.name.to_ascii_lowercase(),
1093                }),
1094                [] => {
1095                    let err = candidate.sources[0]
1096                        .def
1097                        .as_ref()
1098                        .err()
1099                        .cloned()
1100                        .expect("a candidate without importable variants has a failed source");
1101                    request.unchosen.push((candidate.name.clone(), err));
1102                }
1103                _ => request
1104                    .unchosen
1105                    .push((candidate.name.clone(), candidate.conflict_error())),
1106            }
1107        }
1108        request
1109    }
1110
1111    /// Replaces what is chosen for candidate `name` by `picks` (empty:
1112    /// skip it).
1113    pub fn choose(&mut self, name: &str, picks: Vec<VariantChoice>) {
1114        self.picks.retain(|pick| pick.name != name);
1115        self.unchosen.retain(|(unchosen, _)| unchosen != name);
1116        self.picks.extend(picks);
1117    }
1118
1119    fn destination(&self, name: &str, field: &str) -> Option<&SecretDestination> {
1120        let of_name = || self.secrets.iter().filter(|choice| choice.name == name);
1121        of_name()
1122            .find(|choice| choice.field.as_deref() == Some(field))
1123            .or_else(|| of_name().find(|choice| choice.field.is_none()))
1124            .map(|choice| &choice.destination)
1125    }
1126}
1127
1128/// A secret alias an import created.
1129#[derive(Debug, Clone, PartialEq, Eq)]
1130pub struct ImportedAlias {
1131    pub alias: String,
1132    pub server: String,
1133    /// `env.NAME`, `headers.NAME`, `args[N]` or `url`.
1134    pub field: String,
1135    /// [`SecretDestination::kind`].
1136    pub destination: &'static str,
1137}
1138
1139/// Result of [`stage_import`].
1140#[derive(Debug, Clone, Default)]
1141pub struct ImportResult {
1142    /// New server ids.
1143    pub imported: Vec<String>,
1144    /// New servers found only in project files or read-only clients (not
1145    /// `only`): definitions without enablement, for a project manifest to
1146    /// name (`from`).
1147    pub definition_only: Vec<String>,
1148    /// Candidates left out, with the reason.
1149    pub skipped: Vec<(String, CoreError)>,
1150    pub aliases: Vec<ImportedAlias>,
1151    /// New server ids enabled for some client (not `only`, not definitions
1152    /// only): what [`apply_import`] plans.
1153    pub enabled: Vec<String>,
1154    /// `(client, native name)` of the user-file entries the new servers
1155    /// take over without asking: every user file of that client holds the
1156    /// imported definition ([`apply_import`]).
1157    pub entries: Vec<(String, String)>,
1158    /// The user files the enabled picks with extracted secrets come from,
1159    /// after [`apply_import`]: those that still hold an extracted value
1160    /// (M35). No apply rewrote them (review mode, an entry left a collision
1161    /// to decide, a write that failed); the apply that later rewrites them
1162    /// makes backups that are not marked.
1163    pub old_values_in_files: Vec<PathBuf>,
1164    /// The extracted values, until [`apply_import`] looks for them in the
1165    /// backups its apply made (M35); never read anywhere else.
1166    extracted: Vec<SecretValue>,
1167    /// The user files the enabled picks with extracted secrets come from.
1168    extracted_from: BTreeSet<PathBuf>,
1169}
1170
1171/// The instant apply of an import ([`apply_import`]).
1172#[derive(Debug, Clone)]
1173pub struct ImportApply {
1174    pub report: ApplyReport,
1175    /// The client files whose backup of this apply holds an extracted
1176    /// secret's old value (M35), marked in the run's result for
1177    /// [`backup::purge_old_values`].
1178    pub old_value_backups: Vec<PathBuf>,
1179}
1180
1181/// The instant apply of an import (SPEC 8.6, 8.7): in instant mode, plans
1182/// the user files of the enabled servers and takes over the entries they
1183/// were imported from. An entry that renders identically is adopted
1184/// without a write; one that does not (a literal secret now a reference)
1185/// is overwritten with the rendered entry, unless another user file of the
1186/// same client holds a different definition under that name (then it is
1187/// left a collision to decide). Project files are not planned. `None` in
1188/// review mode, where Pending changes shows those entries for a decision.
1189///
1190/// The backups the apply made of files that held an extracted value keep
1191/// that old value; they are listed in [`ImportApply::old_value_backups`].
1192/// The user files that still hold one afterwards are left in
1193/// [`ImportResult::old_values_in_files`]. The extracted values leave
1194/// `result` here either way.
1195pub fn apply_import(
1196    tx: &mut Transaction<'_>,
1197    ax: &ApplyEnv<'_>,
1198    result: &mut ImportResult,
1199) -> Result<Option<ImportApply>, CoreError> {
1200    let extracted = std::mem::take(&mut result.extracted);
1201    let sources: Vec<PathBuf> = std::mem::take(&mut result.extracted_from)
1202        .into_iter()
1203        .collect();
1204    let applied = instant_import(tx, ax, result, &extracted)?;
1205    result.old_values_in_files = backup::files_holding(ax.fs, &sources, &extracted);
1206    Ok(applied)
1207}
1208
1209/// [`apply_import`] but for the files that still hold a value.
1210fn instant_import(
1211    tx: &mut Transaction<'_>,
1212    ax: &ApplyEnv<'_>,
1213    result: &ImportResult,
1214    extracted: &[SecretValue],
1215) -> Result<Option<ImportApply>, CoreError> {
1216    if result.enabled.is_empty() {
1217        // Definitions only (`only`, project files): nothing to write.
1218        return Ok(None);
1219    }
1220    let desired = DesiredState::load(&*tx, Some(&tx.machine().id.clone()))?;
1221    if desired.apply_mode() != ApplyMode::Instant {
1222        return Ok(None);
1223    }
1224    let request = ApplyRequest {
1225        options: PlanOptions {
1226            decisions: result
1227                .entries
1228                .iter()
1229                .map(|(client, name)| Decision {
1230                    client: client.clone(),
1231                    name: name.clone(),
1232                    resolution: OnConflict::Overwrite,
1233                })
1234                .collect(),
1235            servers: Some(result.enabled.clone()),
1236            // User files only: a project entry of the same name (a
1237            // manifest's `from`) is not one the user chose to import.
1238            scope: ScopeFilter::System,
1239            ..PlanOptions::default()
1240        },
1241        trigger: ApplyTrigger::Instant,
1242    };
1243    let mut report = apply_in(tx, ax, &request)?;
1244    // The files are written: a run result that cannot be read or rewritten
1245    // is a warning, never a reason to lose the import.
1246    let old_value_backups =
1247        match backup::mark_old_values(ax.fs, &ax.home.state_dir(), &report.apply_id, extracted) {
1248            Ok(files) => files,
1249            Err(err) => {
1250                report.warnings.push(CoreError::new(
1251                    err.code(),
1252                    format!(
1253                        "cannot tell which backups of this apply hold the old secret values: {}",
1254                        err.message()
1255                    ),
1256                ));
1257                Vec::new()
1258            }
1259        };
1260    Ok(Some(ImportApply {
1261        report,
1262        old_value_backups,
1263    }))
1264}
1265
1266/// Stages `request` in `tx`: one store server per pick, each sensitive
1267/// literal stored as an alias at the destination chosen for it (keyring
1268/// values written right before the commit). A pick that cannot be staged
1269/// (gone since the scan, an id that is taken, a literal without a
1270/// destination) is skipped; the rest still import.
1271pub fn stage_import(
1272    tx: &mut Transaction<'_>,
1273    ax: &ApplyEnv<'_>,
1274    candidates: &[Candidate],
1275    request: &ImportRequest,
1276) -> Result<ImportResult, CoreError> {
1277    let mut result = ImportResult {
1278        skipped: request.unchosen.clone(),
1279        ..ImportResult::default()
1280    };
1281    let machine = tx.machine().id.clone();
1282    let catalog = Catalog::load(&*tx, Some(&machine))?;
1283    let mut aliases = Aliases::new(catalog.iter().map(|alias| alias.alias.clone()));
1284    let memory = tx.store().secret_memory().clone();
1285    let mut staged: BTreeSet<String> = BTreeSet::new();
1286    let mut picked: BTreeSet<(&str, usize)> = BTreeSet::new();
1287    let mut choices = Vec::new();
1288    for pick in &request.picks {
1289        let name = pick.name.as_str();
1290        let id = pick.id.as_str();
1291        let staged_pick = (|| {
1292            let candidate = candidates
1293                .iter()
1294                .find(|candidate| candidate.name == name)
1295                .ok_or_else(|| {
1296                    CoreError::new(
1297                        ErrorCode::NotFound,
1298                        format!("{name:?} is not a foreign entry any more; scan again"),
1299                    )
1300                })?;
1301            let v = candidate.variant_of(&pick.source).ok_or_else(|| {
1302                CoreError::new(
1303                    ErrorCode::NotFound,
1304                    format!("{name:?} has no source {:?}; scan again", pick.source),
1305                )
1306            })?;
1307            if picked.contains(&(name, v)) {
1308                return Err(CoreError::new(
1309                    ErrorCode::InvalidValue,
1310                    format!("this definition of {name:?} is chosen twice"),
1311                ));
1312            }
1313            if staged.contains(id) || tx.exists(&server_path(id)?)? {
1314                return Err(CoreError::new(
1315                    ErrorCode::AlreadyExists,
1316                    format!("server {id:?} already exists"),
1317                ));
1318            }
1319            let mut trial = aliases.clone();
1320            let (server, extracted) = variant_server(candidate, v, id, request.only, &mut trial)?;
1321            let missing: Vec<&str> = extracted
1322                .iter()
1323                .map(|extracted| extracted.extraction.field.as_str())
1324                .filter(|field| request.destination(name, field).is_none())
1325                .collect();
1326            if !missing.is_empty() {
1327                return Err(CoreError::new(
1328                    ErrorCode::NeedsSecretExtraction,
1329                    format!(
1330                        "{} may hold a secret; choose where each goes (the OS keyring, \
1331                         1Password or an environment variable)",
1332                        missing.join(", ")
1333                    ),
1334                ));
1335            }
1336            aliases = trial;
1337            Ok((candidate, v, server, extracted))
1338        })();
1339        let (candidate, v, server, extracted) = match staged_pick {
1340            Ok(staged_pick) => staged_pick,
1341            Err(err) => {
1342                result.skipped.push((pick.name.clone(), err));
1343                continue;
1344            }
1345        };
1346        picked.insert((name, v));
1347        let enabled = server.enable.is_some();
1348        tx.add_server(server)?;
1349        tx.add_entity(format!("server/{id}"));
1350        staged.insert(id.to_owned());
1351        result.imported.push(id.to_owned());
1352        if enabled {
1353            result.enabled.push(id.to_owned());
1354            // Take an entry over without asking only when every user file
1355            // of that client holds this definition; a client whose other
1356            // file (a profile, a mirror) holds another one is left to Ask.
1357            for &i in &candidate.variants[v] {
1358                let source = &candidate.sources[i];
1359                let whole_client = candidate.sources.iter().enumerate().all(|(j, other)| {
1360                    other.client != source.client
1361                        || !other.enables()
1362                        || candidate.variants[v].contains(&j)
1363                });
1364                let pair = (source.client.to_owned(), candidate.name.clone());
1365                // Never an overwrite in a file this account cannot write.
1366                let writable = source.read_only.is_none();
1367                if source.enables() && writable && whole_client && !result.entries.contains(&pair) {
1368                    result.entries.push(pair);
1369                }
1370                if source.enables() && writable && !extracted.is_empty() {
1371                    result.extracted_from.insert(source.file.clone());
1372                }
1373            }
1374        } else if !request.only {
1375            result.definition_only.push(id.to_owned());
1376        }
1377        for extracted in extracted {
1378            let destination = request
1379                .destination(name, &extracted.extraction.field)
1380                .expect("checked above");
1381            // The value stays in the client file until the apply rewrites
1382            // the entry; a store file holding it is refused.
1383            memory.record(extracted.value.expose());
1384            result.extracted.push(extracted.value.clone());
1385            let Extraction { alias, field, .. } = extracted.extraction;
1386            result.aliases.push(ImportedAlias {
1387                alias: alias.clone(),
1388                server: id.to_owned(),
1389                field,
1390                destination: destination.kind(),
1391            });
1392            choices.push(ExtractionChoice {
1393                alias,
1394                target: match destination {
1395                    SecretDestination::Keyring => ExtractionTarget::Keyring(extracted.value),
1396                    SecretDestination::Reference(reference) => {
1397                        ExtractionTarget::Reference(reference.clone())
1398                    }
1399                },
1400            });
1401        }
1402    }
1403    extract::stage_choices(tx, ax, &choices)?;
1404    Ok(result)
1405}
1406
1407fn is_read_only(spec: &AdapterSpec) -> bool {
1408    spec.mcp.as_ref().is_some_and(|mcp| mcp.read_only)
1409}
1410
1411fn set_fields(server: &mut Server, fields: &ServerFields, tools: Option<ToolFilter>) {
1412    let body = &mut server.body;
1413    body.transport = fields.transport;
1414    body.command = fields.command.clone();
1415    body.args = fields.args.clone();
1416    body.cwd = fields.cwd.clone();
1417    body.url = fields.url.clone();
1418    body.headers = fields.headers.clone();
1419    body.env = fields.env.clone();
1420    body.tools = tools;
1421}
1422
1423/// Enables store servers for clients whose user file already holds an
1424/// identical foreign entry under the server's native name, so the apply
1425/// that follows adopts them without a write. Returns `client/name` pairs.
1426pub fn stage_adopt_identical(
1427    tx: &mut Transaction<'_>,
1428    ax: &ApplyEnv<'_>,
1429    desired: &DesiredState,
1430    candidates: &[Candidate],
1431) -> Result<Vec<String>, CoreError> {
1432    let cx = ax.render_cx(tx.store().secret_memory().clone());
1433    let mut adopted = Vec::new();
1434    for candidate in candidates {
1435        // Enabling a store server reaches user files only; a project entry
1436        // comes from the project's manifests.
1437        for source in candidate.sources.iter().filter(|s| s.scope == Scope::User) {
1438            // A read-only client (`vscode-legacy`) is never enabled.
1439            let Some(spec) = adapter(source.client).filter(|spec| !is_read_only(spec)) else {
1440                continue;
1441            };
1442            let Some(server) = desired
1443                .servers
1444                .values()
1445                .find(|server| native_name(server, spec.id) == candidate.name)
1446            else {
1447                continue;
1448            };
1449            let enabled = match server.enable.as_ref().and_then(|e| e.clients.as_ref()) {
1450                Some(ClientSelection::List(ids)) => ids.iter().any(|id| id == spec.id),
1451                Some(ClientSelection::AllDetected) => true,
1452                None => false,
1453            };
1454            if enabled {
1455                continue;
1456            }
1457            let Ok(rendered) = render(&cx, desired, server, spec, Sharing::Private) else {
1458                continue;
1459            };
1460            let rendered = rendered.server;
1461            let mcp = spec.mcp.as_ref().expect("rendered clients have MCP");
1462            let cx_write = WriteCx {
1463                os: ax.env.os(),
1464                existing: Some(&source.value),
1465            };
1466            let Ok(native) = mcp.mapper.to_native(&rendered, &cx_write) else {
1467                continue;
1468            };
1469            if mcp.mapper.canonical(&native) != mcp.mapper.canonical(&source.value) {
1470                continue;
1471            }
1472            update_server(tx, &server.id, |server| enable_client(server, spec.id))?;
1473            adopted.push(format!("{}/{}", spec.id, candidate.name));
1474        }
1475    }
1476    Ok(adopted)
1477}
1478
1479/// Whether `entry` is resolved by a store edit: an `import`, or the
1480/// release of an entry that is still desired (recorded in this machine's
1481/// overlay).
1482pub fn is_store_resolution(entry: &EntryPlan) -> bool {
1483    entry.action == Action::Import || (entry.action == Action::Release && entry.desired.is_some())
1484}
1485
1486/// Carries out the store side of a plan's decisions ([`is_store_resolution`]):
1487/// a changed native entry becomes the server definition; a deleted one
1488/// stops the server from being enabled for that client (synced, SPEC 8.2
1489/// "respect deletion"); a released one is recorded in this machine's
1490/// overlay only (`[enable.released]`), so other machines keep managing
1491/// their entry. Returns the changed server ids; entries that cannot be
1492/// staged are left for the re-plan to report.
1493pub fn stage_resolutions(
1494    tx: &mut Transaction<'_>,
1495    plan: &Plan,
1496    desired: &DesiredState,
1497) -> Result<ImportResolutions, CoreError> {
1498    let mut result = ImportResolutions::default();
1499    for target in &plan.targets {
1500        for entry in target.entries.iter().filter(|e| is_store_resolution(e)) {
1501            let (Some(client), Some(id)) = (entry.client, entry.server_id.as_ref()) else {
1502                continue;
1503            };
1504            if target.project_id.is_some() {
1505                // A project entry comes from the project's manifests, never
1506                // from a store server.
1507                let message = if entry.action == Action::Release {
1508                    "a project entry cannot be released here; remove the client from the \
1509                     entry's clients in the project's manifest instead"
1510                } else {
1511                    "a project entry cannot be imported into the store; edit the project's \
1512                     manifest instead"
1513                };
1514                result.failed.push((
1515                    client.to_owned(),
1516                    entry.name.clone(),
1517                    CoreError::new(ErrorCode::ScopeNotSupported, message),
1518                ));
1519                continue;
1520            }
1521            let Some(spec) = adapter(client) else {
1522                continue;
1523            };
1524            if !desired.servers.contains_key(id) {
1525                continue;
1526            }
1527            if entry.action == Action::Release {
1528                if let Err(err) = release_client(tx, id, client) {
1529                    result
1530                        .failed
1531                        .push((client.to_owned(), entry.name.clone(), err));
1532                }
1533                continue;
1534            }
1535            let edit = match (&entry.state, &entry.observed) {
1536                (EntryState::Missing, _) => {
1537                    update_server(tx, id, |server| disable_client(server, client))
1538                }
1539                (_, Some(observed)) => {
1540                    server_from_native(spec, &entry.name, observed).and_then(|def| {
1541                        update_server(tx, id, |server| {
1542                            set_fields(server, &def.fields, def.tools.clone());
1543                            set_passthrough(server, client, &def.passthrough);
1544                            Ok(())
1545                        })
1546                    })
1547                }
1548                _ => continue,
1549            };
1550            match edit {
1551                Ok(()) if !result.changed.contains(id) => {
1552                    tx.add_entity(format!("server/{id}"));
1553                    result.changed.push(id.clone());
1554                }
1555                Ok(()) => {}
1556                Err(err) => result
1557                    .failed
1558                    .push((client.to_owned(), entry.name.clone(), err)),
1559            }
1560        }
1561    }
1562    Ok(result)
1563}
1564
1565/// Records in this machine's overlay that it released `client`'s entry of
1566/// server `id` (`[enable.released]`).
1567fn release_client(tx: &mut Transaction<'_>, id: &str, client: &str) -> Result<(), CoreError> {
1568    let mut doc = overlay_doc(tx)?;
1569    let enable = doc.value_mut().enable.get_or_insert_with(Default::default);
1570    let clients = enable
1571        .released
1572        .get_or_insert_with(BTreeMap::new)
1573        .entry(id.to_owned())
1574        .or_default();
1575    if clients.iter().any(|c| c == client) {
1576        return Ok(());
1577    }
1578    clients.push(client.to_owned());
1579    let relative = overlay_path(&tx.machine().id)?;
1580    tx.write(&relative, doc.to_text()?)?;
1581    tx.add_entity(format!("machine/{}", tx.machine().id));
1582    Ok(())
1583}
1584
1585/// Drops this machine's releases of server `id` for `clients` (they are
1586/// enabled again by an explicit choice); returns whether the overlay
1587/// changed.
1588pub fn unrelease_clients(
1589    tx: &mut Transaction<'_>,
1590    id: &str,
1591    clients: &[String],
1592) -> Result<bool, CoreError> {
1593    let mut doc = overlay_doc(tx)?;
1594    let Some(enable) = doc.value_mut().enable.as_mut() else {
1595        return Ok(false);
1596    };
1597    let Some(released) = enable.released.as_mut() else {
1598        return Ok(false);
1599    };
1600    let Some(list) = released.get_mut(id) else {
1601        return Ok(false);
1602    };
1603    let before = list.len();
1604    list.retain(|client| !clients.contains(client));
1605    if list.len() == before {
1606        return Ok(false);
1607    }
1608    if list.is_empty() {
1609        released.remove(id);
1610    }
1611    if released.is_empty() {
1612        enable.released = None;
1613    }
1614    let relative = overlay_path(&tx.machine().id)?;
1615    tx.write(&relative, doc.to_text()?)?;
1616    Ok(true)
1617}
1618
1619/// Result of [`stage_resolutions`].
1620#[derive(Debug, Clone, Default)]
1621pub struct ImportResolutions {
1622    /// Store servers changed.
1623    pub changed: Vec<String>,
1624    /// `(client, entry name, reason)` of entries that could not be imported.
1625    pub failed: Vec<(String, String, CoreError)>,
1626}
1627
1628/// Reads server `id` from the transaction, edits it and stages it back
1629/// (comments and unknown keys survive).
1630fn update_server(
1631    tx: &mut Transaction<'_>,
1632    id: &str,
1633    edit: impl FnOnce(&mut Server) -> Result<(), CoreError>,
1634) -> Result<(), CoreError> {
1635    let relative = server_path(id)?;
1636    let text = tx.read_to_string(&relative)?.ok_or_else(|| {
1637        CoreError::new(ErrorCode::NotFound, format!("server {id:?} does not exist"))
1638    })?;
1639    let mut doc = TomlDocument::<Server>::parse(&text)
1640        .map_err(|diagnostic| diagnostic.to_core_error(Some(std::path::Path::new(&relative))))?;
1641    edit(doc.value_mut())?;
1642    tx.write(&relative, doc.to_text()?)
1643}
1644
1645fn enable_client(server: &mut Server, client: &str) -> Result<(), CoreError> {
1646    let enable = server.enable.get_or_insert_with(Enable::default);
1647    match enable
1648        .clients
1649        .get_or_insert_with(|| ClientSelection::List(Vec::new()))
1650    {
1651        ClientSelection::List(ids) => {
1652            if !ids.iter().any(|id| id == client) {
1653                ids.push(client.to_owned());
1654            }
1655        }
1656        ClientSelection::AllDetected => {}
1657    }
1658    Ok(())
1659}
1660
1661fn disable_client(server: &mut Server, client: &str) -> Result<(), CoreError> {
1662    match server.enable.as_mut().and_then(|e| e.clients.as_mut()) {
1663        Some(ClientSelection::List(ids)) => {
1664            ids.retain(|id| id != client);
1665            Ok(())
1666        }
1667        Some(ClientSelection::AllDetected) => Err(CoreError::new(
1668            ErrorCode::InvalidValue,
1669            format!(
1670                "{:?} is enabled for all detected clients; list clients to leave {client} out",
1671                server.id
1672            ),
1673        )),
1674        None => Ok(()),
1675    }
1676}
1677
1678fn set_passthrough(server: &mut Server, client: &str, passthrough: &toml::Table) {
1679    let clients = server.body.client.get_or_insert_with(BTreeMap::new);
1680    let table = clients.entry(client.to_owned()).or_default();
1681    table.retain(|key, _| key == NATIVE_NAME_KEY);
1682    for (key, value) in passthrough {
1683        table.insert(key.clone(), value.clone());
1684    }
1685    if table.is_empty() {
1686        clients.remove(client);
1687    }
1688    if clients.is_empty() {
1689        server.body.client = None;
1690    }
1691}
1692
1693#[cfg(test)]
1694mod tests {
1695    use super::*;
1696
1697    #[test]
1698    fn destinations_parse() {
1699        assert_eq!(
1700            SecretDestination::parse(" keyring ").unwrap(),
1701            SecretDestination::Keyring
1702        );
1703        for text in ["op://Vault/Item/field", "op:op://Vault/Item/field"] {
1704            let destination = SecretDestination::parse(text).unwrap();
1705            assert_eq!(destination.kind(), "onepassword", "{text}");
1706            assert!(matches!(
1707                destination,
1708                SecretDestination::Reference(SecretRef::OnePassword { .. })
1709            ));
1710        }
1711        assert_eq!(
1712            SecretDestination::parse("env:CHATTY_KEY").unwrap().kind(),
1713            "env"
1714        );
1715        for bad in [
1716            "op://Vault/Item",
1717            "keyring://surjection/X",
1718            "vault",
1719            "env:not a name",
1720        ] {
1721            assert!(SecretDestination::parse(bad).is_err(), "{bad}");
1722        }
1723    }
1724}