Skip to main content

surjection_core/apply/
plan.rs

1//! The planner (SPEC 8.3): desired state, native files and the ledger in;
2//! per-file operations, the resulting text and a state per entry out.
3//! Planning reads files and never writes anything.
4
5use std::cell::OnceCell;
6use std::collections::{BTreeMap, HashMap, HashSet};
7use std::path::{Path, PathBuf};
8
9use similar::TextDiff;
10
11use crate::access::{self, ReadOnlyKind, WriteAccess};
12use crate::adapters::caps::{
13    DisableMech, ProjectDisable, ProjectSemantics, TimeUnit, TimeoutField, TrustGate,
14};
15use crate::adapters::detect::replacing_extension;
16use crate::adapters::mapper::{Canonical, EntryMapper, WriteCx};
17use crate::adapters::spec::{ContainerPath, McpSpec};
18use crate::adapters::{ADAPTERS, AdapterSpec, Target, adapter};
19use crate::apply::ledger::{
20    EntryKind, Ledger, LedgerEntry, LedgerKey, LedgerSlot, container_pointer,
21};
22use crate::apply::render::{
23    DesiredEntry, DesiredState, Detected, RenderCx, RenderTarget, Rendering, native_name,
24    render_for, system_entries, writable,
25};
26use crate::env::{Env, Os};
27use crate::error::{CoreError, ErrorCode};
28use crate::formats::{Document, Format, NativeValue};
29use crate::layering::manifest::normalize_path_text;
30use crate::layering::{
31    self, EntryBody, EntryLayer, KnownProject, Project, ProjectEntry, ProjectRepo, ProjectStatus,
32    TrustStore,
33};
34use crate::model::applied::Scope;
35use crate::model::clients::ClientSelection;
36use crate::model::server::Server;
37use crate::paths::STATE_DIR;
38use crate::secrets::SecretValue;
39use crate::secrets::delivery::Sharing;
40
41/// What an entry is, compared with what is desired and what was written
42/// (SPEC 8.2).
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum EntryState {
45    /// Native equals desired and equals what was written.
46    Synced,
47    PendingCreate,
48    PendingUpdate,
49    PendingRemove,
50    /// Owned, changed since it was written, desired unchanged.
51    Drifted,
52    /// Owned and desired, but someone deleted it.
53    Missing,
54    /// Changed since it was written, and desired changed too.
55    Conflict,
56    /// Not owned; never touched.
57    Foreign,
58    /// A foreign entry where a desired entry should go.
59    Collision,
60    /// Cannot be planned; see [`EntryPlan::problem`].
61    Blocked,
62}
63
64impl EntryState {
65    pub const fn as_str(self) -> &'static str {
66        match self {
67            EntryState::Synced => "synced",
68            EntryState::PendingCreate => "pending_create",
69            EntryState::PendingUpdate => "pending_update",
70            EntryState::PendingRemove => "pending_remove",
71            EntryState::Drifted => "drifted",
72            EntryState::Missing => "missing",
73            EntryState::Conflict => "conflict",
74            EntryState::Foreign => "foreign",
75            EntryState::Collision => "collision",
76            EntryState::Blocked => "blocked",
77        }
78    }
79
80    /// States `surject status --check` reports as pending or drift.
81    pub const fn is_pending(self) -> bool {
82        !matches!(
83            self,
84            EntryState::Synced | EntryState::Foreign | EntryState::Blocked
85        )
86    }
87}
88
89/// What the executor does with an entry.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
91pub enum Action {
92    /// Nothing.
93    None,
94    /// Write a new entry; the ledger records it as created.
95    Create,
96    /// Rewrite an owned entry.
97    Update,
98    /// Delete an owned, unchanged entry.
99    Remove,
100    /// Disable an owned entry natively (`enabled = false`).
101    Disable,
102    /// Record an identical foreign entry in the ledger; no write.
103    Adopt,
104    /// Overwrite a colliding foreign entry and record it as adopted.
105    AdoptOverwrite,
106    /// Record the current hash of an entry that already equals desired.
107    Refresh,
108    /// Drop the ledger record of an entry that no longer exists.
109    Forget,
110    /// Drop the ledger record and leave the entry to the user.
111    Release,
112    /// Turn the native entry into the store's desired state (a store edit);
113    /// for a deleted entry, stop enabling the server for that client.
114    Import,
115    /// A decision is needed or was declined; nothing happens.
116    Skip,
117}
118
119impl Action {
120    pub const fn as_str(self) -> &'static str {
121        match self {
122            Action::None => "none",
123            Action::Create => "create",
124            Action::Update => "update",
125            Action::Remove => "remove",
126            Action::Disable => "disable",
127            Action::Adopt => "adopt",
128            Action::AdoptOverwrite => "adopt_overwrite",
129            Action::Refresh => "refresh",
130            Action::Forget => "forget",
131            Action::Release => "release",
132            Action::Import => "import",
133            Action::Skip => "skip",
134        }
135    }
136
137    /// Whether the action changes the file.
138    pub const fn writes(self) -> bool {
139        matches!(
140            self,
141            Action::Create
142                | Action::Update
143                | Action::Remove
144                | Action::Disable
145                | Action::AdoptOverwrite
146        )
147    }
148}
149
150/// How to resolve entries that need a decision (`collision`, `conflict`,
151/// `drifted`, and `missing` for `import`): CLI `--on-conflict`.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
153pub enum OnConflict {
154    /// Leave them and report them as unresolved (exit code 4).
155    #[default]
156    Ask,
157    /// Leave them; resolved by declining.
158    Skip,
159    /// Write desired over them (adopting a collision); remove a drifted
160    /// orphan anyway.
161    Overwrite,
162    /// Take the native entry into the store; release a drifted orphan;
163    /// for a deleted entry, respect the deletion.
164    Import,
165    /// Release ownership of a drifted or conflicting entry: the entry
166    /// stays in the file as the user left it, Surjection forgets it, and a
167    /// store server stops being enabled for that client (so the entry is
168    /// foreign from then on); a drifted orphan is released. Not offered by
169    /// `--on-conflict`; a per-entry decision (the drift resolver, SPEC
170    /// 13.4). Collisions and deleted entries have nothing to release and
171    /// are skipped.
172    Release,
173}
174
175impl OnConflict {
176    pub const fn as_str(self) -> &'static str {
177        match self {
178            OnConflict::Ask => "ask",
179            OnConflict::Skip => "skip",
180            OnConflict::Overwrite => "overwrite",
181            OnConflict::Import => "import",
182            OnConflict::Release => "release",
183        }
184    }
185}
186
187/// A resolution for one entry (`surject adopt <client>/<name>`).
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Decision {
190    pub client: String,
191    pub name: String,
192    pub resolution: OnConflict,
193}
194
195/// Which scopes a plan covers (CLI `--scope`).
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
197pub enum ScopeFilter {
198    /// User files only.
199    System,
200    /// Project and project-local targets only.
201    Project,
202    #[default]
203    All,
204}
205
206impl ScopeFilter {
207    pub const fn as_str(self) -> &'static str {
208        match self {
209            ScopeFilter::System => "system",
210            ScopeFilter::Project => "project",
211            ScopeFilter::All => "all",
212        }
213    }
214
215    const fn system(self) -> bool {
216        matches!(self, ScopeFilter::System | ScopeFilter::All)
217    }
218
219    const fn project(self) -> bool {
220        matches!(self, ScopeFilter::Project | ScopeFilter::All)
221    }
222}
223
224/// Which projects a plan covers (CLI `apply [PATH]`).
225#[derive(Debug, Clone, PartialEq, Eq, Default)]
226pub enum ProjectSelection {
227    /// User scope and every known project whose folder exists here; owned
228    /// entries of projects this machine no longer knows are removed.
229    #[default]
230    All,
231    /// Only the targets of the known project rooted at this folder.
232    Only(PathBuf),
233}
234
235/// One target file a plan may be narrowed to (the GUI's "Apply selected").
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct TargetFilter {
238    pub scope: Scope,
239    /// The project folder of a project or project-local target; `None` for
240    /// a user file and for the clean-up target of a project this machine no
241    /// longer knows.
242    pub project: Option<PathBuf>,
243    pub file: PathBuf,
244}
245
246impl TargetFilter {
247    fn matches(&self, target: &Target) -> bool {
248        self.scope == target.scope
249            && layering::same_path(&self.file, &target.file)
250            && match (&self.project, &target.project) {
251                (None, None) => true,
252                (Some(a), Some(b)) => layering::same_path(a, b),
253                _ => false,
254            }
255    }
256}
257
258/// Inputs that select and steer a plan.
259#[derive(Debug, Clone, Default)]
260pub struct PlanOptions {
261    /// Only these clients; all when `None`.
262    pub clients: Option<Vec<String>>,
263    pub on_conflict: OnConflict,
264    /// Per-entry resolutions; they win over [`PlanOptions::on_conflict`].
265    pub decisions: Vec<Decision>,
266    pub scope: ScopeFilter,
267    pub projects: ProjectSelection,
268    /// Only these target files (within the other filters); all when
269    /// `None`.
270    pub targets: Option<Vec<TargetFilter>>,
271    /// Only the targets these store servers touch (within the other
272    /// filters): those that hold or own entries of them, and those of
273    /// project entries that start from them (`from`); all when `None`. The
274    /// instant apply of a server change plans these (#15).
275    pub servers: Option<Vec<String>>,
276    /// Only these entries are acted on; every other entry of the planned
277    /// targets, and every list member, is held as it is (`surject migrate
278    /// loadout` repairs launchers without applying anything else).
279    pub entries: Option<Vec<EntryFilter>>,
280}
281
282/// One entry of [`PlanOptions::entries`]: its target (scope, project,
283/// file), the container it sits in ([`TargetPlan::pointer`]) and its name.
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub struct EntryFilter {
286    pub target: TargetFilter,
287    pub pointer: String,
288    pub name: String,
289}
290
291impl PlanOptions {
292    fn selects_entry(&self, target: &Target, pointer: &str, name: &str) -> bool {
293        self.entries.as_ref().is_none_or(|entries| {
294            entries.iter().any(|entry| {
295                entry.name == name && entry.pointer == pointer && entry.target.matches(target)
296            })
297        })
298    }
299
300    fn resolution(&self, client: Option<&str>, name: &str) -> OnConflict {
301        self.decisions
302            .iter()
303            .find(|decision| Some(decision.client.as_str()) == client && decision.name == name)
304            .map_or(self.on_conflict, |decision| decision.resolution)
305    }
306
307    fn selects(&self, client: &str) -> bool {
308        self.clients
309            .as_ref()
310            .is_none_or(|clients| clients.iter().any(|id| id == client))
311    }
312
313    fn selects_target(&self, target: &Target) -> bool {
314        self.targets
315            .as_ref()
316            .is_none_or(|targets| targets.iter().any(|filter| filter.matches(target)))
317    }
318
319    /// [`PlanOptions::servers`] for `input`, whose entries `ledger` may own.
320    /// `derived` names the project entries (project id, entry name) that
321    /// start from one of the servers: what they own is selected too, even
322    /// where they are no longer desired (a transport the client cannot run).
323    fn selects_servers(
324        &self,
325        input: &TargetInput,
326        ledger: &Ledger,
327        derived: &[(String, String)],
328    ) -> bool {
329        let Some(ids) = &self.servers else {
330            return true;
331        };
332        let named = |id: &str| ids.iter().any(|named| named == id);
333        if input.desired.iter().any(|entry| named(&entry.server_id))
334            || input.members.iter().any(|member| named(&member.server_id))
335            || input.sources.iter().any(|from| named(from))
336        {
337            return true;
338        }
339        let Ok(keys) = input.container_keys() else {
340            // Planned as blocked; nothing a server change could alter.
341            return false;
342        };
343        let file = input.target.file.to_string_lossy();
344        let pointer = container_pointer(&keys);
345        let slot = LedgerSlot {
346            scope: input.target.scope,
347            project_id: input.project_id.as_deref(),
348            file: &file,
349            container: &pointer,
350        };
351        ledger.slot_entries(&slot).iter().any(|row| {
352            row.server_id.as_deref().is_some_and(|id| {
353                named(id)
354                    || derived.iter().any(|(project, name)| {
355                        row.project_id.as_deref() == Some(project.as_str()) && name == id
356                    })
357            })
358        })
359    }
360
361    /// Whether user files are planned.
362    fn plans_user(&self) -> bool {
363        self.scope.system() && self.projects == ProjectSelection::All
364    }
365
366    /// Whether the known project `project` is planned.
367    fn plans_project(&self, project: &KnownProject) -> bool {
368        self.scope.project()
369            && match &self.projects {
370                ProjectSelection::All => !matches!(project.status, ProjectStatus::Missing),
371                ProjectSelection::Only(root) => layering::same_path(&project.root, root),
372            }
373    }
374}
375
376/// One entry of a target.
377#[derive(Debug, Clone)]
378pub struct EntryPlan {
379    /// The native entry key.
380    pub name: String,
381    /// The client the entry is desired for or owned by; `None` for a
382    /// foreign entry.
383    pub client: Option<&'static str>,
384    pub server_id: Option<String>,
385    pub state: EntryState,
386    pub action: Action,
387    /// The entry needs a decision that was not given.
388    pub unresolved: bool,
389    /// Why the entry is blocked, or what it collides with.
390    pub problem: Option<CoreError>,
391    /// The entry as desired, in native form.
392    pub desired: Option<NativeValue>,
393    /// The entry in the file now.
394    pub observed: Option<NativeValue>,
395    /// What the ledger records once the action is done.
396    pub written: Option<NativeValue>,
397    pub delivery: Option<&'static str>,
398}
399
400/// One native file and container.
401#[derive(Debug, Clone)]
402pub struct TargetPlan {
403    /// Every client whose entries go to this container, in table order.
404    pub clients: Vec<&'static str>,
405    pub scope: Scope,
406    /// The project of a project or project-local target.
407    pub project_id: Option<String>,
408    /// The project folder `<P>`, when known.
409    pub project: Option<PathBuf>,
410    /// Server entries of a container, or members of a list (Claude Code
411    /// `disabledMcpServers`).
412    pub kind: EntryKind,
413    pub file: PathBuf,
414    /// Container keys in the file.
415    pub container: Vec<String>,
416    /// [`container_pointer`] of [`TargetPlan::container`].
417    pub pointer: String,
418    /// The file bytes planned against; `None` when it does not exist.
419    pub before: Option<Vec<u8>>,
420    /// The bytes to write; `None` when the file stays as it is.
421    pub after: Option<Vec<u8>>,
422    pub entries: Vec<EntryPlan>,
423    /// The whole target is blocked (`parse_error`, `unexpected_shape`,
424    /// `trust_required`).
425    pub problem: Option<CoreError>,
426    pub warnings: Vec<CoreError>,
427    /// This account cannot write the file (or create it): what the write
428    /// probe found while planning (SPEC 8.2 `read_only_target`). Entries
429    /// that would write it are blocked; the target is listed all the same.
430    pub read_only: Option<ReadOnlyKind>,
431    /// Values the file holds now in entries written inline, masked in
432    /// [`TargetPlan::diff`].
433    pub(crate) masked: Vec<SecretValue>,
434    pub(crate) input: TargetInput,
435}
436
437/// What a target was planned from, kept so the executor can re-plan a file
438/// that changed underneath (SPEC 8.4 step 1).
439#[derive(Debug, Clone)]
440pub(crate) struct TargetInput {
441    pub(crate) target: Target,
442    pub(crate) clients: Vec<&'static str>,
443    pub(crate) desired: Vec<DesiredEntry>,
444    /// Desired list members, for a [`EntryKind::ListMember`] target.
445    pub(crate) members: Vec<DesiredMember>,
446    pub(crate) native_disable: BTreeMap<&'static str, bool>,
447    pub(crate) invalid_servers: Vec<String>,
448    pub(crate) project_id: Option<String>,
449    pub(crate) kind: EntryKind,
450    /// Container keys recorded in the ledger, for a target planned only to
451    /// clean up owned entries; `None` resolves [`Target::container_keys`].
452    pub(crate) keys: Option<Vec<String>>,
453    /// Blocks the whole target (`trust_required`).
454    pub(crate) blocked: Option<CoreError>,
455    /// Hide the file through the project repository's `info/exclude` once
456    /// it is written (a private entry in an untracked project file, SPEC
457    /// 6.5).
458    pub(crate) exclude: bool,
459    /// The store servers the target's project entries start from (`from`),
460    /// for [`PlanOptions::servers`].
461    pub(crate) sources: Vec<String>,
462    /// What the write probe found for the file; kept for a re-plan.
463    pub(crate) access: WriteAccess,
464}
465
466/// A string a list target should hold (a server name in Claude Code's
467/// `disabledMcpServers`).
468#[derive(Debug, Clone)]
469pub(crate) struct DesiredMember {
470    pub(crate) client: &'static str,
471    pub(crate) server_id: String,
472    pub(crate) name: String,
473}
474
475impl TargetInput {
476    fn new(target: Target, client: &'static str, native_disable: bool) -> Self {
477        Self {
478            target,
479            clients: vec![client],
480            desired: Vec::new(),
481            members: Vec::new(),
482            native_disable: BTreeMap::from([(client, native_disable)]),
483            invalid_servers: Vec::new(),
484            project_id: None,
485            kind: EntryKind::McpEntry,
486            keys: None,
487            blocked: None,
488            exclude: false,
489            sources: Vec::new(),
490            access: WriteAccess::Unknown,
491        }
492    }
493
494    /// The container keys entries go in.
495    fn container_keys(&self) -> Result<Vec<String>, CoreError> {
496        match &self.keys {
497            Some(keys) => Ok(keys.clone()),
498            None => self.target.container_keys(),
499        }
500    }
501
502    /// Whether `target` is the same file and container (for the same
503    /// project and kind).
504    fn same(&self, target: &Target, kind: EntryKind) -> bool {
505        self.kind == kind
506            && self.target.file == target.file
507            && self.target.container == target.container
508            && self.target.project == target.project
509    }
510
511    /// Adds `client`'s share of a target that `same` matched.
512    fn join(&mut self, client: &'static str, native_disable: bool, warnings: Vec<CoreError>) {
513        if !self.clients.contains(&client) {
514            self.clients.push(client);
515            self.target.warnings.extend(warnings);
516        }
517        self.native_disable.insert(client, native_disable);
518    }
519
520    /// Drops the clients `ejected` covers (`surject eject`): their desired
521    /// entries and list members go too. Returns whether a client is left.
522    fn without_ejected(&mut self, ejected: &crate::eject::Ejected) -> bool {
523        let project = self.project_id.clone();
524        let covered = |client: &str| ejected.covers(client, project.as_deref());
525        self.clients.retain(|client| !covered(client));
526        self.desired.retain(|entry| !covered(entry.client));
527        self.members.retain(|member| !covered(member.client));
528        self.native_disable.retain(|client, _| !covered(client));
529        if let Some(&first) = self.clients.first() {
530            self.target.client = first;
531        }
532        !self.clients.is_empty()
533    }
534}
535
536impl EntryPlan {
537    /// Whether the entry is blocked because a secret cannot be had on this
538    /// machine (SPEC 11.9, 14 exit code 5).
539    pub fn blocked_by_secret(&self) -> bool {
540        self.problem.as_ref().is_some_and(|err| {
541            matches!(
542                err.code(),
543                ErrorCode::MissingSecret
544                    | ErrorCode::SecretLocked
545                    | ErrorCode::ProviderUnavailable
546                    | ErrorCode::ProviderTooOld
547            )
548        })
549    }
550}
551
552impl TargetPlan {
553    /// The client named in reports: the first one.
554    pub fn client(&self) -> &'static str {
555        self.clients[0]
556    }
557
558    /// Counts of planned write actions: create, update, remove, disable.
559    pub fn counts(&self) -> OpCounts {
560        let mut counts = OpCounts::default();
561        for entry in &self.entries {
562            match entry.action {
563                Action::Create | Action::AdoptOverwrite => counts.create += 1,
564                Action::Update => counts.update += 1,
565                Action::Remove => counts.remove += 1,
566                Action::Disable => counts.disable += 1,
567                _ => {}
568            }
569        }
570        counts
571    }
572
573    /// Whether anything (file or ledger) would change.
574    pub fn has_work(&self) -> bool {
575        self.after.is_some()
576            || self.entries.iter().any(|entry| {
577                matches!(
578                    entry.action,
579                    Action::Adopt
580                        | Action::Refresh
581                        | Action::Forget
582                        | Action::Release
583                        | Action::Import
584                )
585            })
586    }
587
588    /// Entries that need a decision that was not given.
589    pub fn unresolved(&self) -> usize {
590        self.entries.iter().filter(|entry| entry.unresolved).count()
591    }
592
593    /// Whether some entry or the whole target is blocked.
594    pub fn is_blocked(&self) -> bool {
595        self.problem.is_some()
596            || self
597                .entries
598                .iter()
599                .any(|entry| entry.state == EntryState::Blocked)
600    }
601
602    /// The change as a unified diff of the file text; empty when the file
603    /// stays as it is. Values written by `inline` delivery are masked
604    /// (SPEC 8.3).
605    pub fn diff(&self) -> String {
606        let Some(after) = &self.after else {
607            return String::new();
608        };
609        let before = self.mask(&String::from_utf8_lossy(
610            self.before.as_deref().unwrap_or_default(),
611        ));
612        let after = self.mask(&String::from_utf8_lossy(after));
613        let name = self.file.to_string_lossy();
614        let old = if self.before.is_some() {
615            format!("a/{name}")
616        } else {
617            "/dev/null".to_owned()
618        };
619        TextDiff::from_lines(before.as_str(), after.as_str())
620            .unified_diff()
621            .context_radius(3)
622            .header(&old, &format!("b/{name}"))
623            .to_string()
624    }
625
626    /// `text` with every value to hide replaced, as written and as a JSON
627    /// or TOML string escape: the inline values this plan writes become
628    /// `********`; the values an inline entry holds now that this plan does
629    /// not write again (a rotation, a mode change, a removal) become
630    /// `******** (before)`, so a changed value still shows as a change.
631    /// Values shorter than four characters are left alone: masking them
632    /// would garble the diff without hiding anything.
633    pub fn mask(&self, text: &str) -> String {
634        let mut text = text.to_owned();
635        let writes = self.input.desired.iter().flat_map(|entry| &entry.inline);
636        let values = writes
637            .map(|value| (value, "********"))
638            .chain(self.masked.iter().map(|value| (value, "******** (before)")));
639        for (value, placeholder) in values {
640            let raw = value.expose();
641            if raw.chars().count() < 4 {
642                continue;
643            }
644            let escaped = serde_json::to_string(raw).expect("a string serializes");
645            let escaped = &escaped[1..escaped.len() - 1];
646            for form in [escaped, raw] {
647                text = text.replace(form, placeholder);
648            }
649        }
650        text
651    }
652
653    /// Entry `name` with native value `value`, alone under the innermost
654    /// key of this target's container, as the file format writes it
655    /// (`{"mcpServers": {...}}`, `[mcp_servers.x]`), with
656    /// [`TargetPlan::mask`] applied: the snippet the effective view and the
657    /// drift resolver show. Outer container keys are left out (Claude
658    /// Code's per-project map is keyed by the folder path). `None` when the
659    /// format cannot hold it.
660    pub fn snippet(&self, name: &str, value: &NativeValue) -> Option<String> {
661        let keys: Vec<&str> = self
662            .container
663            .last()
664            .map(String::as_str)
665            .into_iter()
666            .collect();
667        let mut doc = Document::empty(self.input.target.format);
668        doc.upsert(&keys, name, value).ok()?;
669        Some(self.mask(&String::from_utf8_lossy(&doc.to_bytes())))
670    }
671}
672
673/// Of an entry that is or was written inline, the values its current
674/// native form may hold in plain text: every string under an environment
675/// or header map, and every other string the desired entry does not hold
676/// as it is.
677fn old_inline_values(entry: &EntryPlan) -> Vec<SecretValue> {
678    let Some(observed) = &entry.observed else {
679        return Vec::new();
680    };
681    let mut kept = Vec::new();
682    if let Some(desired) = &entry.desired {
683        leaves(desired, false, &mut |text, _| kept.push(text.to_owned()));
684    }
685    let mut out = Vec::new();
686    leaves(observed, false, &mut |text, secret_map| {
687        if secret_map || !kept.iter().any(|k| k == text) {
688            out.push(SecretValue::new(text));
689        }
690    });
691    out
692}
693
694/// Calls `f` with every string leaf of `value` and whether it sits in an
695/// environment or header map.
696fn leaves(value: &NativeValue, secret_map: bool, f: &mut dyn FnMut(&str, bool)) {
697    match value {
698        NativeValue::String(text) => f(text, secret_map),
699        NativeValue::Array(items) => {
700            for item in items {
701                leaves(item, secret_map, f);
702            }
703        }
704        NativeValue::Object(map) => {
705            for (key, item) in map.iter() {
706                let secret =
707                    secret_map || matches!(key, "env" | "headers" | "http_headers" | "environment");
708                leaves(item, secret, f);
709            }
710        }
711        _ => {}
712    }
713}
714
715/// Planned create, update, remove and disable operations.
716#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
717pub struct OpCounts {
718    pub create: u32,
719    pub update: u32,
720    pub remove: u32,
721    pub disable: u32,
722}
723
724impl OpCounts {
725    pub fn total(&self) -> u32 {
726        self.create + self.update + self.remove + self.disable
727    }
728}
729
730/// A whole plan.
731#[derive(Debug, Clone, Default)]
732pub struct Plan {
733    pub targets: Vec<TargetPlan>,
734    /// Problems outside any target: clients that cannot be written here,
735    /// server files that do not load.
736    pub warnings: Vec<CoreError>,
737    /// The first `base` warnings are the system layer's (rendering, server
738    /// files), the next `user` ones the user files'; the project planner's
739    /// follow. See [`Plan::scope_part`].
740    base: usize,
741    user: usize,
742}
743
744impl Plan {
745    /// Targets whose file would change.
746    pub fn writes(&self) -> usize {
747        self.targets
748            .iter()
749            .filter(|target| target.after.is_some())
750            .count()
751    }
752
753    pub fn unresolved(&self) -> usize {
754        self.targets.iter().map(TargetPlan::unresolved).sum()
755    }
756
757    /// Whether applying it would change anything (files or ledger).
758    pub fn has_work(&self) -> bool {
759        self.targets.iter().any(TargetPlan::has_work)
760    }
761
762    /// Of a plan of every scope and project ([`PlanOptions::default`]),
763    /// the plan of `scope` alone: the same targets, in the same order, and
764    /// the same warnings as planning with `scope` gives (#15: the app plans
765    /// once and shows the parts).
766    pub fn scope_part(&self, scope: ScopeFilter) -> Plan {
767        let (base, user) = (self.base, self.base + self.user);
768        let warnings: Vec<CoreError> = match scope {
769            ScopeFilter::All => self.warnings.clone(),
770            ScopeFilter::System => self.warnings[..user].to_vec(),
771            ScopeFilter::Project => self.warnings[..base]
772                .iter()
773                .chain(&self.warnings[user..])
774                .cloned()
775                .collect(),
776        };
777        Plan {
778            targets: self
779                .targets
780                .iter()
781                .filter(|target| match scope {
782                    ScopeFilter::All => true,
783                    ScopeFilter::System => target.scope == Scope::User,
784                    ScopeFilter::Project => target.scope != Scope::User,
785                })
786                .cloned()
787                .collect(),
788            base: self.base,
789            user: if scope == ScopeFilter::Project {
790                0
791            } else {
792                self.user
793            },
794            warnings,
795        }
796    }
797}
798
799/// Plans the selected scopes: the user files of every selected client that
800/// has desired or owned entries on this machine, and the project and
801/// project-local targets of the selected known projects (SPEC 6).
802pub fn plan(
803    cx: &RenderCx<'_>,
804    desired: &DesiredState,
805    ledger: &Ledger,
806    key: &LedgerKey,
807    options: &PlanOptions,
808) -> Result<Plan, CoreError> {
809    let mut plans = plan_each(cx, desired, ledger, key, std::slice::from_ref(options))?;
810    Ok(plans.pop().expect("one plan per selection"))
811}
812
813/// [`plan`] for each of `selections`, in one run: the system layer is
814/// rendered once, and each file read and parsed once for all of them.
815pub(crate) fn plan_each(
816    cx: &RenderCx<'_>,
817    desired: &DesiredState,
818    ledger: &Ledger,
819    key: &LedgerKey,
820    selections: &[PlanOptions],
821) -> Result<Vec<Plan>, CoreError> {
822    let rendering = system_entries(cx, desired);
823    let mut files = Files::default();
824    selections
825        .iter()
826        .map(|options| plan_one(cx, desired, &rendering, ledger, key, options, &mut files))
827        .collect()
828}
829
830/// Target files read and parsed during one planner run. Each file is read
831/// and parsed once, however many targets it holds (`~/.claude.json`: the
832/// user container, one per project and the `disabledMcpServers` lists);
833/// every target plans against its own copy.
834#[derive(Default)]
835struct Files {
836    bytes: HashMap<PathBuf, Option<Vec<u8>>>,
837    docs: HashMap<(PathBuf, Format), Result<Document, CoreError>>,
838    /// Write probe results (SPEC 8.2 `read_only_target`).
839    access: HashMap<PathBuf, WriteAccess>,
840}
841
842impl Files {
843    /// The bytes of `target`'s file, and its document when it exists.
844    #[allow(clippy::type_complexity)]
845    fn of(
846        &mut self,
847        fs: &dyn crate::fs::Fs,
848        target: &Target,
849    ) -> Result<(Option<Vec<u8>>, Option<Result<Document, CoreError>>), CoreError> {
850        let file = &target.file;
851        let bytes = match self.bytes.get(file) {
852            Some(bytes) => bytes.clone(),
853            None => {
854                let bytes = read_target(fs, file)?;
855                self.bytes.insert(file.clone(), bytes.clone());
856                bytes
857            }
858        };
859        let parsed = bytes.as_ref().map(|bytes| {
860            self.docs
861                .entry((file.clone(), target.format))
862                .or_insert_with(|| Document::parse(bytes, target.format))
863                .clone()
864        });
865        Ok((bytes, parsed))
866    }
867
868    /// Probes whether this account can write each target file not probed
869    /// yet in this run, all together under the probe budget
870    /// ([`crate::access::probe_files`]); results are keyed by each file's
871    /// content fingerprint in `cx.probes` when given.
872    fn probe(&mut self, cx: &RenderCx<'_>, inputs: &[TargetInput]) -> Result<(), CoreError> {
873        let mut wanted: Vec<(PathBuf, Option<u64>)> = Vec::new();
874        for input in inputs {
875            let file = &input.target.file;
876            if self.access.contains_key(file) || wanted.iter().any(|(path, _)| path == file) {
877                continue;
878            }
879            let (bytes, _) = self.of(cx.fs, &input.target)?;
880            wanted.push((file.clone(), access::fingerprint(bytes.as_deref())));
881        }
882        if !wanted.is_empty() {
883            self.access
884                .extend(access::probe_files(cx.fs, &wanted, cx.probes));
885        }
886        Ok(())
887    }
888}
889
890fn plan_one(
891    cx: &RenderCx<'_>,
892    desired: &DesiredState,
893    rendering: &Rendering,
894    ledger: &Ledger,
895    key: &LedgerKey,
896    options: &PlanOptions,
897    files: &mut Files,
898) -> Result<Plan, CoreError> {
899    let mut plan = Plan {
900        targets: Vec::new(),
901        warnings: rendering.warnings.clone(),
902        base: 0,
903        user: 0,
904    };
905    for (id, err) in &desired.invalid {
906        plan.warnings.push(CoreError::new(
907            err.code(),
908            format!("server {id:?} is not applied, and entries it owns are left alone: {err}"),
909        ));
910    }
911    plan.base = plan.warnings.len();
912    let mut inputs: Vec<TargetInput> = Vec::new();
913    if options.plans_user() {
914        user_inputs(
915            cx,
916            desired,
917            rendering,
918            ledger,
919            options,
920            &mut plan,
921            &mut inputs,
922        );
923    }
924    plan.user = plan.warnings.len() - plan.base;
925    let mut derived = Vec::new();
926    if options.scope.project() {
927        let mut planner = ProjectPlanner {
928            cx,
929            desired,
930            rendering,
931            ledger,
932            options,
933            detected: Detected::default(),
934            warnings: Vec::new(),
935            inputs: Vec::new(),
936            derived: Vec::new(),
937        };
938        planner.plan_projects();
939        plan.warnings.append(&mut planner.warnings);
940        inputs.append(&mut planner.inputs);
941        derived = planner.derived;
942    }
943    inputs.retain(|input| {
944        options.selects_target(&input.target) && options.selects_servers(input, ledger, &derived)
945    });
946    // Clients this machine stopped managing are never planned (M57).
947    if let Some(ejected) = crate::eject::status_at(cx.fs, &cx.surjection_home.join(STATE_DIR))? {
948        inputs.retain_mut(|input| input.without_ejected(&ejected));
949    }
950    files.probe(cx, &inputs)?;
951    for mut input in inputs {
952        let (bytes, parsed) = files.of(cx.fs, &input.target)?;
953        input.access = files
954            .access
955            .get(&input.target.file)
956            .copied()
957            .unwrap_or(WriteAccess::Unknown);
958        plan.targets.push(plan_target_in(
959            cx, input, bytes, parsed, ledger, key, options,
960        ));
961    }
962    Ok(plan)
963}
964
965/// The user-file targets (SPEC 6.1 system layer).
966fn user_inputs(
967    cx: &RenderCx<'_>,
968    desired: &DesiredState,
969    rendering: &Rendering,
970    ledger: &Ledger,
971    options: &PlanOptions,
972    plan: &mut Plan,
973    inputs: &mut Vec<TargetInput>,
974) {
975    let owned: Vec<&str> = ledger
976        .entries
977        .iter()
978        .filter(|entry| entry.kind == EntryKind::McpEntry && entry.scope == Scope::User)
979        .map(|entry| entry.client.as_str())
980        .collect();
981    let clients: Vec<&'static AdapterSpec> = ADAPTERS
982        .iter()
983        .copied()
984        .filter(|spec| rendering.clients.contains(&spec.id) || owned.contains(&spec.id))
985        .filter(|spec| options.selects(spec.id))
986        .collect();
987
988    for spec in clients {
989        let prefs = desired.prefs(spec.id);
990        let targets = match spec.mcp_targets(cx.env, cx.fs, Scope::User, None, &prefs) {
991            Ok(targets) => targets,
992            Err(err) => {
993                plan.warnings.push(err);
994                continue;
995            }
996        };
997        let desired_here: Vec<DesiredEntry> = rendering
998            .entries
999            .iter()
1000            .filter(|entry| entry.client == spec.id)
1001            .cloned()
1002            .collect();
1003        let native_disable = prefs.native_disable == Some(true);
1004        let extension = replacing_extension(spec, cx.env, cx.fs, None);
1005        for mut target in targets {
1006            target.warnings.extend(extension.clone());
1007            match inputs
1008                .iter_mut()
1009                .find(|input| input.same(&target, EntryKind::McpEntry))
1010            {
1011                Some(input) => {
1012                    input.join(spec.id, native_disable, target.warnings);
1013                    input.desired.extend(desired_here.iter().cloned());
1014                }
1015                None => {
1016                    let mut input = TargetInput::new(target, spec.id, native_disable);
1017                    input.desired = desired_here.clone();
1018                    input.invalid_servers = desired.invalid.keys().cloned().collect();
1019                    inputs.push(input);
1020                }
1021            }
1022        }
1023    }
1024}
1025
1026/// Builds the project and project-local targets of the selected known
1027/// projects, and the clean-up targets of projects this machine no longer
1028/// knows.
1029struct ProjectPlanner<'a, 'c> {
1030    cx: &'a RenderCx<'c>,
1031    desired: &'a DesiredState,
1032    /// The system layer, for suppressions (only of servers enabled at
1033    /// system scope) and their renderings.
1034    rendering: &'a Rendering,
1035    ledger: &'a Ledger,
1036    options: &'a PlanOptions,
1037    detected: Detected,
1038    warnings: Vec<CoreError>,
1039    inputs: Vec<TargetInput>,
1040    /// Project entries (project id, name) that start from one of
1041    /// [`PlanOptions::servers`].
1042    derived: Vec<(String, String)>,
1043}
1044
1045/// One project being planned.
1046struct ProjectCx<'p> {
1047    id: &'p str,
1048    root: &'p Path,
1049    /// `trust_required` when the manifests are not trusted as they are.
1050    blocked: Option<CoreError>,
1051}
1052
1053impl ProjectPlanner<'_, '_> {
1054    fn plan_projects(&mut self) {
1055        let state_dir = self.cx.surjection_home.join(STATE_DIR);
1056        let trust = TrustStore::load(self.cx.fs, &state_dir).unwrap_or_else(|err| {
1057            // Nothing is trusted then: every project is blocked, user files
1058            // still apply.
1059            self.warnings.push(err);
1060            TrustStore::default()
1061        });
1062        let known = layering::known_projects(
1063            self.cx.fs,
1064            self.cx.env,
1065            self.desired.overlay.as_ref(),
1066            &trust,
1067        );
1068        if let ProjectSelection::Only(root) = &self.options.projects {
1069            match known
1070                .iter()
1071                .find(|project| layering::same_path(&project.root, root))
1072            {
1073                None => self.warnings.push(
1074                    CoreError::new(
1075                        ErrorCode::NotFound,
1076                        "this folder is not a project known on this machine",
1077                    )
1078                    .with_path(root),
1079                ),
1080                Some(project) if matches!(project.status, ProjectStatus::Missing) => {
1081                    self.warnings.push(
1082                        CoreError::new(ErrorCode::NotFound, "the project folder does not exist")
1083                            .with_path(root),
1084                    );
1085                }
1086                Some(_) => {}
1087            }
1088        }
1089        let options = self.options;
1090        for project in known
1091            .iter()
1092            .filter(|project| options.plans_project(project))
1093        {
1094            match &project.status {
1095                ProjectStatus::Missing => {}
1096                ProjectStatus::Failed(err) => self.warnings.push(err.clone()),
1097                ProjectStatus::Loaded {
1098                    project: loaded, ..
1099                } => {
1100                    self.warnings.extend(loaded.warnings.iter().cloned());
1101                    let pcx = ProjectCx {
1102                        id: &project.id,
1103                        root: &project.root,
1104                        blocked: project.trust_error(),
1105                    };
1106                    let start = self.inputs.len();
1107                    let mut held = self.plan_project(&pcx, loaded);
1108                    // What a server that does not load owns here (its
1109                    // overrides, its suppressions) is left alone too.
1110                    held.extend(self.desired.invalid.keys().cloned());
1111                    for input in &mut self.inputs[start..] {
1112                        input.project_id = Some(project.id.clone());
1113                        input.blocked.clone_from(&pcx.blocked);
1114                        input.invalid_servers.extend(held.iter().cloned());
1115                    }
1116                    self.cleanup(
1117                        |id| id == project.id,
1118                        Some(&project.root),
1119                        pcx.blocked.as_ref(),
1120                        &held,
1121                    );
1122                }
1123            }
1124        }
1125        if self.options.projects == ProjectSelection::All {
1126            let known_ids: Vec<&str> = known.iter().map(|project| project.id.as_str()).collect();
1127            let invalid: Vec<String> = self.desired.invalid.keys().cloned().collect();
1128            self.cleanup(|id| !known_ids.contains(&id), None, None, &invalid);
1129        }
1130    }
1131
1132    /// The targets of a loaded project's entries. Returns the names of
1133    /// entries that cannot be resolved: what this project owns for them is
1134    /// left alone (never removed) until they are fixed.
1135    fn plan_project(&mut self, pcx: &ProjectCx<'_>, project: &Project) -> Vec<String> {
1136        let entries = layering::project_entries(
1137            project,
1138            &self.desired.servers,
1139            self.cx.env,
1140            self.desired.overlay.as_ref(),
1141        );
1142        let mut warned: Vec<String> = Vec::new();
1143        let mut held = Vec::new();
1144        for entry in &entries {
1145            let from_selected = [Some(entry), entry.shared.as_deref()]
1146                .into_iter()
1147                .flatten()
1148                .filter_map(|entry| entry.from.as_deref())
1149                .any(|from| {
1150                    self.options
1151                        .servers
1152                        .as_ref()
1153                        .is_some_and(|ids| ids.iter().any(|id| id == from))
1154                });
1155            if from_selected {
1156                self.derived.push((pcx.id.to_owned(), entry.name.clone()));
1157            }
1158            if matches!(entry.body, EntryBody::Server(Err(_))) {
1159                held.push(entry.name.clone());
1160            }
1161            self.plan_entry(pcx, entry, false, &mut warned);
1162            // A client holding the merged entry privately keeps the shared
1163            // definition in the shared file, which stays as committed.
1164            if let Some(shared) = entry
1165                .shared
1166                .as_deref()
1167                .filter(|shared| matches!(shared.body, EntryBody::Server(_)))
1168            {
1169                self.plan_entry(pcx, shared, true, &mut warned);
1170            }
1171        }
1172        held
1173    }
1174
1175    /// Plans `entry` for each of its clients; with `private_only`, only for
1176    /// clients that have a private project target.
1177    fn plan_entry(
1178        &mut self,
1179        pcx: &ProjectCx<'_>,
1180        entry: &ProjectEntry,
1181        private_only: bool,
1182        warned: &mut Vec<String>,
1183    ) {
1184        let clients = match &entry.body {
1185            EntryBody::Server(Err(_)) => self.error_clients(pcx, entry),
1186            EntryBody::Server(Ok(_)) | EntryBody::Suppression => {
1187                self.detected
1188                    .project_selection(self.cx, self.desired, entry)
1189            }
1190        };
1191        for client in clients {
1192            if !self.options.selects(&client) || self.desired.excluded(&client) {
1193                continue;
1194            }
1195            let spec = match writable(&client, self.cx.env) {
1196                Ok(spec) => spec,
1197                Err(err) => {
1198                    if !warned.contains(&client) {
1199                        warned.push(client);
1200                        self.warnings.push(err);
1201                    }
1202                    continue;
1203                }
1204            };
1205            if private_only
1206                && spec
1207                    .mcp
1208                    .as_ref()
1209                    .is_none_or(|mcp| mcp.project_local.is_empty())
1210            {
1211                continue;
1212            }
1213            match &entry.body {
1214                EntryBody::Server(server) => self.server_entry(pcx, entry, server, spec),
1215                EntryBody::Suppression => self.suppression(pcx, entry, spec),
1216            }
1217        }
1218    }
1219
1220    /// The clients of an entry that cannot be resolved, so it is reported
1221    /// blocked wherever it would go: its client list, or for
1222    /// `all-detected` the detected clients with project files (no
1223    /// transport to fit), plus every client this project owns an entry of
1224    /// that name for.
1225    fn error_clients(&mut self, pcx: &ProjectCx<'_>, entry: &ProjectEntry) -> Vec<String> {
1226        let mut clients = match &entry.clients {
1227            ClientSelection::List(ids) => ids.clone(),
1228            ClientSelection::AllDetected => {
1229                let mut ids = Vec::new();
1230                for spec in ADAPTERS.iter().copied() {
1231                    let has_files = spec.mcp.as_ref().is_some_and(|mcp| {
1232                        !mcp.read_only
1233                            && mcp.oses.contains(&self.cx.env.os())
1234                            && !(mcp.project.is_empty() && mcp.project_local.is_empty())
1235                    });
1236                    if has_files && self.detected.detected(self.cx, self.desired, spec) {
1237                        ids.push(spec.id.to_owned());
1238                    }
1239                }
1240                ids
1241            }
1242        };
1243        for row in &self.ledger.entries {
1244            let owns = row.kind == EntryKind::McpEntry
1245                && row.project_id.as_deref() == Some(pcx.id)
1246                && (row.server_id.as_deref() == Some(entry.name.as_str()) || row.key == entry.name);
1247            if owns && !clients.contains(&row.client) {
1248                clients.push(row.client.clone());
1249            }
1250        }
1251        clients
1252    }
1253
1254    /// The target file of an entry from `layer` for `spec` (SPEC 6.1, 6.5):
1255    /// the shared project file for a shared entry; the private target for
1256    /// a local one, else the project file written privately. `None` (with
1257    /// a warning) when the client has no such file.
1258    fn placement(
1259        &mut self,
1260        pcx: &ProjectCx<'_>,
1261        spec: &'static AdapterSpec,
1262        mcp: &McpSpec,
1263        layer: EntryLayer,
1264    ) -> Option<(Target, Sharing)> {
1265        let (scope, sharing) = match layer {
1266            EntryLayer::Shared => (Scope::Project, Sharing::Shared),
1267            EntryLayer::Local if mcp.project_local.is_empty() => (Scope::Project, Sharing::Private),
1268            EntryLayer::Local => (Scope::ProjectLocal, Sharing::Private),
1269        };
1270        let prefs = self.desired.prefs(spec.id);
1271        match spec.mcp_targets(self.cx.env, self.cx.fs, scope, Some(pcx.root), &prefs) {
1272            Ok(mut targets) if !targets.is_empty() => {
1273                let mut target = targets.swap_remove(0);
1274                // A user or project install of an extension replacing the
1275                // client's MCP support (Pi `pi-mcp-adapter`, gate V2 PI-8).
1276                target.warnings.extend(replacing_extension(
1277                    spec,
1278                    self.cx.env,
1279                    self.cx.fs,
1280                    Some(pcx.root),
1281                ));
1282                Some((target, sharing))
1283            }
1284            Ok(_) => None,
1285            Err(err) => {
1286                self.warnings.push(err);
1287                None
1288            }
1289        }
1290    }
1291
1292    /// SPEC 6.5 for a private entry in `target`, a project file: blocked
1293    /// with `private_in_tracked_file` when the project's repository tracks
1294    /// the file; otherwise whether to hide it through `info/exclude`. git2
1295    /// reads the repository directly, so the files that decide it are
1296    /// noted on `fs` ([`crate::fs::Fs::note_dependency`]).
1297    fn private_file(
1298        fs: &dyn crate::fs::Fs,
1299        pcx: &ProjectCx<'_>,
1300        spec: &AdapterSpec,
1301        target: &Target,
1302    ) -> Result<bool, CoreError> {
1303        if target.scope != Scope::Project {
1304            return Ok(false);
1305        }
1306        fs.note_dependency(&pcx.root.join(".git"));
1307        let Some(repo) = ProjectRepo::discover(pcx.root)? else {
1308            return Ok(false);
1309        };
1310        for file in repo.state_files(&target.file) {
1311            fs.note_dependency(&file);
1312        }
1313        if repo.is_tracked(&target.file)? {
1314            let file = repo
1315                .relative(&target.file)
1316                .unwrap_or_else(|| target.file.to_string_lossy().into_owned());
1317            return Err(CoreError::new(
1318                ErrorCode::PrivateInTrackedFile,
1319                format!(
1320                    "a project.local.toml entry would go to {file}, which git tracks; remove {} \
1321                     from this entry's clients, or untrack {file}",
1322                    spec.id
1323                ),
1324            )
1325            .with_path(&target.file));
1326        }
1327        Ok(!repo.is_ignored(&target.file)?)
1328    }
1329
1330    fn server_entry(
1331        &mut self,
1332        pcx: &ProjectCx<'_>,
1333        entry: &ProjectEntry,
1334        server: &Result<Box<Server>, CoreError>,
1335        spec: &'static AdapterSpec,
1336    ) {
1337        let mcp = spec
1338            .mcp
1339            .as_ref()
1340            .expect("writable clients have MCP support");
1341        // Claude Desktop has no project files: it never gets project
1342        // entries.
1343        if mcp.project.is_empty() && mcp.project_local.is_empty() {
1344            return;
1345        }
1346        let Some((target, sharing)) = self.placement(pcx, spec, mcp, entry.layer) else {
1347            return;
1348        };
1349        let mut exclude = false;
1350        let mut want = DesiredEntry {
1351            client: spec.id,
1352            server_id: entry.name.clone(),
1353            name: server.as_ref().map_or_else(
1354                |_| entry.name.clone(),
1355                |server| native_name(server, spec.id),
1356            ),
1357            server: Err(CoreError::new(ErrorCode::InvalidValue, "not rendered")),
1358            delivery: None,
1359            inline: Vec::new(),
1360            warnings: Vec::new(),
1361            native: None,
1362        };
1363        let ready = match (&pcx.blocked, server) {
1364            (Some(err), _) | (None, Err(err)) => Err(err.clone()),
1365            (None, Ok(server)) => match entry.layer {
1366                EntryLayer::Local => {
1367                    Self::private_file(self.cx.fs, pcx, spec, &target).map(|hide| {
1368                        exclude = hide;
1369                        server
1370                    })
1371                }
1372                EntryLayer::Shared => Ok(server),
1373            },
1374        };
1375        want.server = ready.and_then(|server| {
1376            let out = render_for(
1377                self.cx,
1378                self.desired,
1379                server,
1380                spec,
1381                RenderTarget {
1382                    sharing,
1383                    project: Some(pcx.root),
1384                    overlay: false,
1385                },
1386            )?;
1387            want.delivery = out.delivery.map(|mode| mode.as_str());
1388            want.inline = out.inline;
1389            want.warnings = out.warnings;
1390            let mut rendered = out.server;
1391            rendered.enabled = entry.enabled;
1392            Ok(rendered)
1393        });
1394        if want.server.is_ok() && mcp.caps.project_semantics == ProjectSemantics::DeepMerge {
1395            want.warnings
1396                .extend(unset_not_expressible(spec, entry, &target.file));
1397        }
1398        let native_disable = self.desired.prefs(spec.id).native_disable == Some(true);
1399        let input = self.input_for(target, spec.id, native_disable, EntryKind::McpEntry);
1400        input.exclude |= exclude;
1401        input.desired.push(want);
1402        input.sources.extend(entry.from.clone());
1403    }
1404
1405    /// SPEC 6.3: hides system server `entry.name` from `spec` in this
1406    /// project, when the server is enabled for it at system scope.
1407    fn suppression(
1408        &mut self,
1409        pcx: &ProjectCx<'_>,
1410        entry: &ProjectEntry,
1411        spec: &'static AdapterSpec,
1412    ) {
1413        let Some(server) = self.desired.servers.get(&entry.name) else {
1414            return;
1415        };
1416        let Some(system) = self
1417            .rendering
1418            .entries
1419            .iter()
1420            .find(|want| want.client == spec.id && want.server_id == entry.name)
1421        else {
1422            return;
1423        };
1424        let mechanism = match layering::suppression_mechanism(spec, &entry.name) {
1425            Ok(mechanism) => mechanism,
1426            Err(warning) => {
1427                self.warnings.push(warning);
1428                return;
1429            }
1430        };
1431        let mcp = spec
1432            .mcp
1433            .as_ref()
1434            .expect("writable clients have MCP support");
1435        let native_disable = self.desired.prefs(spec.id).native_disable == Some(true);
1436        let name = native_name(server, spec.id);
1437        match mechanism {
1438            ProjectDisable::ListMember(_) => {
1439                let prefs = self.desired.prefs(spec.id);
1440                let target =
1441                    match spec.suppression_target(self.cx.env, self.cx.fs, pcx.root, &prefs) {
1442                        Ok(Some(target)) => target,
1443                        Ok(None) => return,
1444                        Err(err) => {
1445                            self.warnings.push(err);
1446                            return;
1447                        }
1448                    };
1449                // A private suppression listed in a shared project file
1450                // (Gemini `mcp.excluded`, SPEC 6.5).
1451                let mut exclude = false;
1452                if pcx.blocked.is_none() && matches!(entry.layer, EntryLayer::Local) {
1453                    match Self::private_file(self.cx.fs, pcx, spec, &target) {
1454                        Ok(hide) => exclude = hide,
1455                        Err(err) => {
1456                            self.warnings.push(err);
1457                            return;
1458                        }
1459                    }
1460                }
1461                let input = self.input_for(target, spec.id, native_disable, EntryKind::ListMember);
1462                input.exclude |= exclude;
1463                input.members.push(DesiredMember {
1464                    client: spec.id,
1465                    server_id: entry.name.clone(),
1466                    name,
1467                });
1468            }
1469            ProjectDisable::EnabledFalse { partial } => {
1470                let Some((target, sharing)) = self.placement(pcx, spec, mcp, entry.layer) else {
1471                    return;
1472                };
1473                let mut exclude = false;
1474                let mut want = DesiredEntry {
1475                    client: spec.id,
1476                    server_id: entry.name.clone(),
1477                    name,
1478                    server: Err(CoreError::new(ErrorCode::InvalidValue, "not rendered")),
1479                    delivery: None,
1480                    inline: Vec::new(),
1481                    warnings: Vec::new(),
1482                    native: None,
1483                };
1484                let ready = match (&pcx.blocked, entry.layer) {
1485                    (Some(err), _) => Err(err.clone()),
1486                    (None, EntryLayer::Local) => Self::private_file(self.cx.fs, pcx, spec, &target)
1487                        .map(|hide| exclude = hide),
1488                    (None, EntryLayer::Shared) => Ok(()),
1489                };
1490                want.server = ready.and_then(|()| match (&system.server, partial) {
1491                    // A partial entry holds nothing of the server.
1492                    (Ok(rendered), true) => Ok(rendered.clone()),
1493                    _ => {
1494                        let out = render_for(
1495                            self.cx,
1496                            self.desired,
1497                            server,
1498                            spec,
1499                            RenderTarget {
1500                                sharing,
1501                                project: Some(pcx.root),
1502                                overlay: true,
1503                            },
1504                        )?;
1505                        want.delivery = out.delivery.map(|mode| mode.as_str());
1506                        want.inline = out.inline;
1507                        want.warnings = out.warnings;
1508                        Ok(out.server)
1509                    }
1510                });
1511                if let Ok(rendered) = &want.server {
1512                    match mcp.suppression_entry(rendered, self.cx.env.os()) {
1513                        Ok(native) => want.native = native,
1514                        Err(err) => want.server = Err(err.into()),
1515                    }
1516                }
1517                if partial {
1518                    want.delivery = None;
1519                    want.inline.clear();
1520                }
1521                let input = self.input_for(target, spec.id, native_disable, EntryKind::McpEntry);
1522                input.exclude |= exclude;
1523                input.desired.push(want);
1524            }
1525        }
1526    }
1527
1528    /// The input of `target`, joining one planned already.
1529    fn input_for(
1530        &mut self,
1531        target: Target,
1532        client: &'static str,
1533        native_disable: bool,
1534        kind: EntryKind,
1535    ) -> &mut TargetInput {
1536        let index = match self
1537            .inputs
1538            .iter()
1539            .position(|input| input.same(&target, kind))
1540        {
1541            Some(index) => {
1542                self.inputs[index].join(client, native_disable, target.warnings);
1543                index
1544            }
1545            None => {
1546                let mut input = TargetInput::new(target, client, native_disable);
1547                input.kind = kind;
1548                self.inputs.push(input);
1549                self.inputs.len() - 1
1550            }
1551        };
1552        &mut self.inputs[index]
1553    }
1554
1555    /// Targets for owned project entries that no planned target covers:
1556    /// entries of a project this machine no longer knows (`root` is
1557    /// `None`), or left in a file the project no longer uses. Unchanged
1558    /// owned entries are removed there, like any entry no longer desired,
1559    /// except those of the `held` names (entries that cannot be resolved
1560    /// now), which are left alone. A planned target of a shared file (SPEC
1561    /// 6.5) that covers an entry another client owns gets that client
1562    /// joined, so its entries there are cleaned up too.
1563    fn cleanup(
1564        &mut self,
1565        project: impl Fn(&str) -> bool,
1566        root: Option<&Path>,
1567        blocked: Option<&CoreError>,
1568        held: &[String],
1569    ) {
1570        type Covered = (Scope, Option<String>, String, String, EntryKind);
1571        let covered: Vec<Covered> = self
1572            .inputs
1573            .iter()
1574            .map(|input| {
1575                let pointer = input
1576                    .container_keys()
1577                    .map(|keys| container_pointer(&keys))
1578                    .unwrap_or_default();
1579                (
1580                    input.target.scope,
1581                    input.project_id.clone(),
1582                    input.target.file.to_string_lossy().into_owned(),
1583                    pointer,
1584                    input.kind,
1585                )
1586            })
1587            .collect();
1588        let mut orphans: Vec<TargetInput> = Vec::new();
1589        for row in &self.ledger.entries {
1590            let Some(id) = row.project_id.as_deref() else {
1591                continue;
1592            };
1593            if row.scope == Scope::User || !project(id) {
1594                continue;
1595            }
1596            let Some(spec) = adapter(&row.client) else {
1597                continue;
1598            };
1599            let Some(mcp) = spec.mcp.as_ref() else {
1600                continue;
1601            };
1602            if !self.options.selects(spec.id) {
1603                continue;
1604            }
1605            let native_disable = self.desired.prefs(spec.id).native_disable == Some(true);
1606            let covering = covered
1607                .iter()
1608                .position(|(scope, project_id, file, pointer, kind)| {
1609                    *scope == row.scope
1610                        && project_id.as_deref() == Some(id)
1611                        && *file == row.file
1612                        && !pointer.is_empty()
1613                        && *pointer == row.container
1614                        && *kind == row.kind
1615                });
1616            if let Some(index) = covering {
1617                self.inputs[index].join(spec.id, native_disable, Vec::new());
1618                continue;
1619            }
1620            let same = orphans.iter_mut().find(|input| {
1621                input.target.scope == row.scope
1622                    && input.project_id.as_deref() == Some(id)
1623                    && input.target.file.to_string_lossy() == row.file
1624                    && input.keys.as_deref().map(container_pointer).as_deref()
1625                        == Some(row.container.as_str())
1626                    && input.kind == row.kind
1627            });
1628            if let Some(input) = same {
1629                input.join(spec.id, native_disable, Vec::new());
1630                continue;
1631            }
1632            let target = Target {
1633                client: spec.id,
1634                scope: row.scope,
1635                os: self.cx.env.os(),
1636                file: PathBuf::from(&row.file),
1637                format: mcp.format,
1638                container: match row.scope {
1639                    Scope::ProjectLocal => mcp.project_local_container,
1640                    _ => mcp.container,
1641                },
1642                project: root.map(Path::to_path_buf),
1643                profile: None,
1644                skeleton: mcp.skeleton,
1645                warnings: Vec::new(),
1646            };
1647            let mut input = TargetInput::new(target, spec.id, native_disable);
1648            input.kind = row.kind;
1649            input.keys = Some(pointer_keys(&row.container));
1650            input.project_id = Some(id.to_owned());
1651            input.blocked = blocked.cloned();
1652            input.invalid_servers = held.to_vec();
1653            orphans.push(input);
1654        }
1655        self.inputs.append(&mut orphans);
1656    }
1657}
1658
1659/// `unset_not_expressible` for `entry` on `spec` (SPEC 6.3): a client that
1660/// merges project entries over user entries field by field cannot drop
1661/// what the user entry sets. `None` when the entry unsets nothing.
1662pub(crate) fn unset_not_expressible(
1663    spec: &AdapterSpec,
1664    entry: &ProjectEntry,
1665    file: &Path,
1666) -> Option<CoreError> {
1667    if entry.unset.is_empty() {
1668        return None;
1669    }
1670    Some(
1671        CoreError::new(
1672            ErrorCode::UnsetNotExpressible,
1673            format!(
1674                "{} merges project entries over user entries field by field, so `unset` ({}) \
1675                 of {:?} cannot remove what the user entry sets; the entry is written anyway",
1676                spec.display_name,
1677                entry.unset.join(", "),
1678                entry.name
1679            ),
1680        )
1681        .with_path(file),
1682    )
1683}
1684
1685/// `client_enable_required` for `names` in a project file of `spec`, when
1686/// the client lists new project servers as disabled until each is enabled
1687/// once in its UI (Cursor, gate V2 CUR-2). `None` for any other client or
1688/// no names.
1689pub(crate) fn client_enable_required(
1690    spec: &AdapterSpec,
1691    names: &[&str],
1692    file: &Path,
1693) -> Option<CoreError> {
1694    let TrustGate::ClientEnable(place) = spec.mcp.as_ref()?.caps.trust_gate? else {
1695        return None;
1696    };
1697    if names.is_empty() {
1698        return None;
1699    }
1700    let names: Vec<String> = names.iter().map(|name| format!("{name:?}")).collect();
1701    Some(
1702        CoreError::new(
1703            ErrorCode::ClientEnableRequired,
1704            format!(
1705                "{} lists new servers of this project file as Disabled until each is enabled \
1706                 in {place} (once per server; Surjection cannot read that toggle): {}",
1707                spec.display_name,
1708                names.join(", ")
1709            ),
1710        )
1711        .with_path(file),
1712    )
1713}
1714
1715/// [`client_enable_required`] for each client of a project target, naming
1716/// the entries Surjection writes or keeps owning there.
1717fn client_enable_hints(plan: &TargetPlan) -> Vec<CoreError> {
1718    if plan.scope == Scope::User {
1719        return Vec::new();
1720    }
1721    plan.clients
1722        .iter()
1723        .filter_map(|&client| {
1724            let names: Vec<&str> = plan
1725                .entries
1726                .iter()
1727                .filter(|entry| {
1728                    entry.client == Some(client)
1729                        && entry.desired.is_some()
1730                        && entry.state != EntryState::Blocked
1731                        && !matches!(
1732                            entry.action,
1733                            Action::Skip | Action::Import | Action::Release
1734                        )
1735                })
1736                .map(|entry| entry.name.as_str())
1737                .collect();
1738            client_enable_required(adapter(client)?, &names, &plan.file)
1739        })
1740        .collect()
1741}
1742
1743/// The keys of an RFC 6901 JSON pointer ([`container_pointer`] reversed).
1744fn pointer_keys(pointer: &str) -> Vec<String> {
1745    pointer
1746        .split('/')
1747        .skip(1)
1748        .map(|key| key.replace("~1", "/").replace("~0", "~"))
1749        .collect()
1750}
1751
1752/// Whether two Claude Code project keys name the same folder: equal after
1753/// unifying separators, a trailing separator and, on Windows, case.
1754fn same_folder(os: Os, a: &str, b: &str) -> bool {
1755    let windows = os == Os::Windows;
1756    normalize_path_text(windows, a) == normalize_path_text(windows, b)
1757}
1758
1759/// The bytes of a target file; `None` when it does not exist.
1760pub(crate) fn read_target(
1761    fs: &dyn crate::fs::Fs,
1762    file: &std::path::Path,
1763) -> Result<Option<Vec<u8>>, CoreError> {
1764    if !fs.exists(file) {
1765        return Ok(None);
1766    }
1767    fs.read(file).map(Some).map_err(|err| {
1768        CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(file)
1769    })
1770}
1771
1772fn mapper_of(client: &str) -> Option<&'static dyn EntryMapper> {
1773    adapter(client)
1774        .and_then(|spec| spec.mcp.as_ref())
1775        .map(|mcp| mcp.mapper)
1776}
1777
1778/// Plans one target against `bytes`, the current file content.
1779pub(crate) fn plan_target(
1780    cx: &RenderCx<'_>,
1781    input: TargetInput,
1782    bytes: Option<Vec<u8>>,
1783    ledger: &Ledger,
1784    key: &LedgerKey,
1785    options: &PlanOptions,
1786) -> TargetPlan {
1787    plan_target_in(cx, input, bytes, None, ledger, key, options)
1788}
1789
1790/// [`plan_target_body`], then a read-only file's writes blocked
1791/// ([`read_only_blocks`]).
1792fn plan_target_in(
1793    cx: &RenderCx<'_>,
1794    input: TargetInput,
1795    bytes: Option<Vec<u8>>,
1796    parsed: Option<Result<Document, CoreError>>,
1797    ledger: &Ledger,
1798    key: &LedgerKey,
1799    options: &PlanOptions,
1800) -> TargetPlan {
1801    read_only_blocks(plan_target_body(
1802        cx, input, bytes, parsed, ledger, key, options,
1803    ))
1804}
1805
1806/// SPEC 8.2 `read_only_target`: in a file the probe found read only, every
1807/// entry that would write it is blocked (no decision is asked for a write
1808/// that cannot happen) and the file stays as it is. Ledger-only work
1809/// (adopting an identical entry, refreshing a hash, forgetting a deleted
1810/// one) and decisions that need no write (import theirs, release) remain.
1811fn read_only_blocks(mut plan: TargetPlan) -> TargetPlan {
1812    let Some(kind) = plan.read_only else {
1813        return plan;
1814    };
1815    if plan.problem.is_some() {
1816        return plan;
1817    }
1818    let err = access::read_only_target(kind, &plan.file);
1819    for entry in &mut plan.entries {
1820        if entry.action.writes() {
1821            entry.state = EntryState::Blocked;
1822            entry.action = Action::None;
1823            entry.unresolved = false;
1824            entry.problem = Some(err.clone());
1825        }
1826    }
1827    plan.after = None;
1828    plan
1829}
1830
1831/// [`plan_target`], with `bytes` already parsed as the target's format
1832/// when `parsed` is given.
1833fn plan_target_body(
1834    cx: &RenderCx<'_>,
1835    input: TargetInput,
1836    bytes: Option<Vec<u8>>,
1837    parsed: Option<Result<Document, CoreError>>,
1838    ledger: &Ledger,
1839    key: &LedgerKey,
1840    options: &PlanOptions,
1841) -> TargetPlan {
1842    let target = &input.target;
1843    let mut plan = TargetPlan {
1844        clients: input.clients.clone(),
1845        scope: target.scope,
1846        project_id: input.project_id.clone(),
1847        project: target.project.clone(),
1848        kind: input.kind,
1849        file: target.file.clone(),
1850        container: Vec::new(),
1851        pointer: String::new(),
1852        before: bytes.clone(),
1853        after: None,
1854        entries: Vec::new(),
1855        problem: None,
1856        warnings: target
1857            .warnings
1858            .iter()
1859            .chain(input.desired.iter().flat_map(|entry| &entry.warnings))
1860            .cloned()
1861            .collect(),
1862        masked: Vec::new(),
1863        read_only: input.access.read_only(),
1864        input: input.clone(),
1865    };
1866    let keys = match input.container_keys() {
1867        Ok(keys) => keys,
1868        Err(err) => return blocked_target(plan, err.with_path(&target.file)),
1869    };
1870    plan.pointer = container_pointer(&keys);
1871    plan.container = keys.clone();
1872    if let Some(err) = &input.blocked {
1873        return blocked_target(plan, err.clone());
1874    }
1875    let parsed = match (&bytes, parsed) {
1876        (Some(_), Some(parsed)) => parsed,
1877        (Some(bytes), None) => Document::parse(bytes, target.format),
1878        (None, _) => Ok(target.new_document()),
1879    };
1880    let mut doc = match parsed {
1881        Ok(doc) => doc,
1882        Err(err) => return blocked_target(plan, err.with_path(&target.file)),
1883    };
1884    if let Some(warning) = key_spelling(target, &doc, &keys) {
1885        plan.warnings.push(warning);
1886    }
1887    if input.kind == EntryKind::ListMember {
1888        return plan_list(plan, doc, bytes, ledger, options);
1889    }
1890    let container: Vec<&str> = keys.iter().map(String::as_str).collect();
1891    let observed_names = match doc.list(&container) {
1892        Ok(names) => names,
1893        Err(err) => return blocked_target(plan, err.with_path(&target.file)),
1894    };
1895    let file = target.file.to_string_lossy().into_owned();
1896    let (pointer, project_id) = (plan.pointer.clone(), plan.project_id.clone());
1897    let slot = LedgerSlot {
1898        scope: plan.scope,
1899        project_id: project_id.as_deref(),
1900        file: &file,
1901        container: &pointer,
1902    };
1903
1904    // Names in file order, then new desired names, then ledger-only names.
1905    let owned_here = ledger.slot_entries(&slot);
1906    let observed_set: HashSet<&str> = observed_names.iter().map(String::as_str).collect();
1907    let mut names: Vec<String> = observed_names.clone();
1908    let mut listed: HashSet<String> = observed_names.iter().cloned().collect();
1909    for entry in &input.desired {
1910        if listed.insert(entry.name.clone()) {
1911            names.push(entry.name.clone());
1912        }
1913    }
1914    for entry in owned_here.iter() {
1915        if entry.kind == EntryKind::McpEntry && listed.insert(entry.key.clone()) {
1916            names.push(entry.key.clone());
1917        }
1918    }
1919    let foreign_names: Vec<String> = observed_names
1920        .iter()
1921        .filter(|name| owned_here.get(name).is_none())
1922        .cloned()
1923        .collect();
1924    let readers = OnceCell::new();
1925
1926    for name in names {
1927        let observed = if observed_set.contains(name.as_str()) {
1928            match doc.get(&container, &name) {
1929                Ok(value) => value,
1930                Err(err) => {
1931                    plan.entries.push(blocked_entry(&name, None, None, err));
1932                    continue;
1933                }
1934            }
1935        } else {
1936            None
1937        };
1938        let owned = owned_here
1939            .get(&name)
1940            .filter(|entry| entry.kind == EntryKind::McpEntry);
1941        let wanted: Vec<&DesiredEntry> = input
1942            .desired
1943            .iter()
1944            .filter(|entry| entry.name == name)
1945            .collect();
1946        let entry = plan_entry(
1947            cx,
1948            &input,
1949            &name,
1950            &foreign_names,
1951            wanted,
1952            observed,
1953            owned,
1954            key,
1955            options,
1956            &readers,
1957        );
1958        if let Some(mut entry) = entry {
1959            if !options.selects_entry(&input.target, &pointer, &entry.name) {
1960                // Held: planned for the report, but nothing about it is
1961                // done in this run (it stays pending).
1962                entry.action = Action::None;
1963                entry.written = None;
1964                entry.unresolved = false;
1965            }
1966            let was_inline = owned.and_then(|l| l.delivery.as_deref()) == Some("inline");
1967            if was_inline || entry.delivery == Some("inline") {
1968                plan.masked.extend(old_inline_values(&entry));
1969            }
1970            plan.entries.push(entry);
1971        }
1972    }
1973
1974    // Apply the write actions to the document.
1975    let mut changed = false;
1976    for entry in &plan.entries {
1977        let result = match entry.action {
1978            Action::Create | Action::Update | Action::AdoptOverwrite | Action::Disable => {
1979                let value = entry.written.as_ref().expect("write actions carry a value");
1980                doc.upsert(&container, &entry.name, value)
1981            }
1982            Action::Remove => doc.remove(&container, &entry.name),
1983            _ => Ok(false),
1984        };
1985        match result {
1986            Ok(edited) => changed |= edited,
1987            Err(err) => return blocked_target(plan, err.with_path(&target.file)),
1988        }
1989    }
1990    if changed {
1991        let after = doc.to_bytes();
1992        if bytes.as_deref() != Some(after.as_slice()) {
1993            plan.after = Some(after);
1994        }
1995    }
1996    plan.warnings.extend(client_enable_hints(&plan));
1997    plan
1998}
1999
2000/// The clients that read a user file, with their timeout fields.
2001type TimeoutReaders = Vec<(&'static str, &'static [TimeoutField])>;
2002
2003/// `timeout_unit_conflict` when `native` sets a timeout key that the
2004/// clients reading `target`'s user file take in different units: with
2005/// `PI_CODING_AGENT_DIR` set, omp and Pi read one `mcp.json`, omp's
2006/// `timeout` in milliseconds and Pi's in seconds (gate V2 OMP-10). The
2007/// readers of the file are worked out once per target (`readers`).
2008fn timeout_unit_conflict(
2009    env: &Env,
2010    target: &Target,
2011    native: &NativeValue,
2012    readers: &OnceCell<TimeoutReaders>,
2013) -> Option<CoreError> {
2014    let entry = native.as_object()?;
2015    if target.scope != Scope::User {
2016        return None;
2017    }
2018    let readers = readers.get_or_init(|| {
2019        ADAPTERS
2020            .iter()
2021            .filter_map(|spec| {
2022                let mcp = spec.mcp.as_ref()?;
2023                let reads = mcp.oses.contains(&env.os())
2024                    && mcp
2025                        .user
2026                        .iter()
2027                        .filter_map(|location| location.resolve(env, None))
2028                        .any(|file| layering::same_path(&file, &target.file));
2029                reads.then_some((spec.id, mcp.caps.timeouts))
2030            })
2031            .collect()
2032    });
2033    let mut keys = readers
2034        .iter()
2035        .flat_map(|(_, timeouts)| timeouts.iter())
2036        .map(|timeout| timeout.key)
2037        .filter(|key| entry.contains_key(key));
2038    keys.find_map(|key| {
2039        let units: Vec<(&str, TimeUnit)> = readers
2040            .iter()
2041            .filter_map(|(client, timeouts)| {
2042                let field = timeouts.iter().find(|timeout| timeout.key == key)?;
2043                Some((*client, field.unit))
2044            })
2045            .collect();
2046        if units.iter().all(|(_, unit)| *unit == units[0].1) {
2047            return None;
2048        }
2049        let clients: Vec<&str> = units.iter().map(|(client, _)| *client).collect();
2050        let described: Vec<String> = units
2051            .iter()
2052            .map(|(client, unit)| format!("{client} in {}", unit.name()))
2053            .collect();
2054        Some(
2055            CoreError::new(
2056                ErrorCode::TimeoutUnitConflict,
2057                format!(
2058                    "clients {} read this file and take `{key}` in different units ({}); \
2059                     remove `{key}` from this server's `[client.<id>]` tables, or give the \
2060                     clients separate files",
2061                    clients.join(" and "),
2062                    described.join(", ")
2063                ),
2064            )
2065            .with_path(&target.file),
2066        )
2067    })
2068}
2069
2070#[allow(clippy::too_many_arguments)]
2071fn plan_entry(
2072    cx: &RenderCx<'_>,
2073    input: &TargetInput,
2074    name: &str,
2075    foreign_names: &[String],
2076    wanted: Vec<&DesiredEntry>,
2077    observed: Option<NativeValue>,
2078    owned: Option<&LedgerEntry>,
2079    key: &LedgerKey,
2080    options: &PlanOptions,
2081    readers: &OnceCell<TimeoutReaders>,
2082) -> Option<EntryPlan> {
2083    let os = cx.env.os();
2084    let mut entry = EntryPlan {
2085        name: name.to_owned(),
2086        client: None,
2087        server_id: None,
2088        state: EntryState::Foreign,
2089        action: Action::None,
2090        unresolved: false,
2091        problem: None,
2092        desired: None,
2093        observed: observed.clone(),
2094        written: None,
2095        delivery: None,
2096    };
2097
2098    // The desired native entry, if any.
2099    let mut desired: Option<(&'static str, NativeValue)> = None;
2100    if let Some(first) = wanted.first() {
2101        entry.client = Some(first.client);
2102        entry.server_id = Some(first.server_id.clone());
2103        entry.delivery = first.delivery;
2104        let mut natives = Vec::new();
2105        for want in &wanted {
2106            let native = match (&want.server, &want.native) {
2107                (Ok(_), Some(native)) => Ok(native.clone()),
2108                (Ok(server), None) => mapper_of(want.client)
2109                    .ok_or_else(|| CoreError::new(ErrorCode::NoAdapter, "no mapper"))
2110                    .and_then(|mapper| {
2111                        mapper
2112                            .to_native(
2113                                server,
2114                                &WriteCx {
2115                                    os,
2116                                    existing: observed.as_ref(),
2117                                },
2118                            )
2119                            .map_err(CoreError::from)
2120                    }),
2121                (Err(err), _) => Err(err.clone()),
2122            };
2123            match native {
2124                Ok(native) => natives.push((want.client, native)),
2125                Err(err) => {
2126                    entry.state = EntryState::Blocked;
2127                    entry.problem = Some(err);
2128                    return Some(entry);
2129                }
2130            }
2131        }
2132        if let Some(problem) = natives
2133            .iter()
2134            .find_map(|(_, native)| timeout_unit_conflict(cx.env, &input.target, native, readers))
2135        {
2136            entry.state = EntryState::Blocked;
2137            entry.problem = Some(problem);
2138            return Some(entry);
2139        }
2140        let (client, native) = natives.remove(0);
2141        if natives.iter().any(|(_, other)| *other != native) {
2142            entry.state = EntryState::Blocked;
2143            entry.problem = Some(CoreError::new(
2144                ErrorCode::Collision,
2145                format!(
2146                    "clients {} share this file and want different entries named {name:?}",
2147                    wanted
2148                        .iter()
2149                        .map(|w| w.client)
2150                        .collect::<Vec<_>>()
2151                        .join(", ")
2152                ),
2153            ));
2154            return Some(entry);
2155        }
2156        // A shared file keeps the bare launcher it was written with: an
2157        // entry Loadout 1.0.x wrote starting `loadout` stays as it is, so
2158        // teammates still on 1.0.x keep working (new entries get `surject`).
2159        let native = match &observed {
2160            Some(observed)
2161                if input.target.scope == Scope::Project
2162                    && crate::migrate::loadout::legacy_bare_launcher(observed, &native) =>
2163            {
2164                observed.clone()
2165            }
2166            _ => native,
2167        };
2168        entry.desired = Some(native.clone());
2169        desired = Some((client, native));
2170    }
2171
2172    let resolution = |entry: &EntryPlan| options.resolution(entry.client, name);
2173    match (desired, observed, owned) {
2174        (Some((client, d)), None, None) => {
2175            // A foreign entry the client counts as the same server (Pi).
2176            let collisions = adapter(client)
2177                .map(|spec| spec.name_collisions(name, foreign_names))
2178                .unwrap_or_default();
2179            if let Some(collision) = collisions.into_iter().next() {
2180                entry.state = EntryState::Collision;
2181                entry.action = Action::Skip;
2182                entry.unresolved = resolution(&entry) == OnConflict::Ask;
2183                entry.problem = Some(collision);
2184            } else {
2185                entry.state = EntryState::PendingCreate;
2186                entry.action = Action::Create;
2187                entry.written = Some(d);
2188            }
2189        }
2190        (Some((_, d)), None, Some(_)) => {
2191            entry.state = EntryState::Missing;
2192            match resolution(&entry) {
2193                OnConflict::Skip | OnConflict::Release => entry.action = Action::Skip,
2194                OnConflict::Import => entry.action = Action::Import,
2195                OnConflict::Ask | OnConflict::Overwrite => {
2196                    entry.action = Action::Create;
2197                    entry.written = Some(d);
2198                }
2199            }
2200        }
2201        (Some((client, d)), Some(o), None) => {
2202            let mapper = mapper_of(client)?;
2203            if mapper.canonical(&o) == mapper.canonical(&d) {
2204                entry.state = EntryState::Synced;
2205                entry.action = Action::Adopt;
2206                entry.written = Some(o);
2207            } else {
2208                entry.state = EntryState::Collision;
2209                let resolved = resolution(&entry);
2210                decide(&mut entry, resolved, Action::AdoptOverwrite, d, false);
2211            }
2212        }
2213        (Some((client, d)), Some(o), Some(l)) => {
2214            let mapper = mapper_of(client)?;
2215            let (canon_o, canon_d) = (mapper.canonical(&o), mapper.canonical(&d));
2216            let hash_o = key.hash(&canon_o);
2217            if Some(&hash_o) == l.written_hash.as_ref() {
2218                if canon_o == canon_d {
2219                    entry.state = EntryState::Synced;
2220                } else {
2221                    entry.state = EntryState::PendingUpdate;
2222                    entry.action = Action::Update;
2223                    entry.written = Some(d);
2224                }
2225            } else if canon_o == canon_d {
2226                entry.state = EntryState::Synced;
2227                entry.action = Action::Refresh;
2228                entry.written = Some(o);
2229            } else {
2230                entry.state = if l.written_hash.as_ref() == Some(&key.hash(&canon_d)) {
2231                    EntryState::Drifted
2232                } else {
2233                    EntryState::Conflict
2234                };
2235                let resolved = resolution(&entry);
2236                decide(&mut entry, resolved, Action::Update, d, true);
2237            }
2238        }
2239        (None, Some(o), Some(l)) => {
2240            entry.client = adapter(&l.client).map(|spec| spec.id);
2241            entry.server_id = l.server_id.clone();
2242            let client = entry.client?;
2243            if !input.clients.contains(&client) {
2244                return None;
2245            }
2246            if l.server_id
2247                .as_ref()
2248                .is_some_and(|id| input.invalid_servers.contains(id))
2249            {
2250                entry.state = EntryState::Blocked;
2251                entry.problem = Some(not_loading(l.server_id.as_deref()));
2252                return Some(entry);
2253            }
2254            let mapper = mapper_of(client)?;
2255            let canon_o = mapper.canonical(&o);
2256            if Some(&key.hash(&canon_o)) == l.written_hash.as_ref() {
2257                let disabled = input
2258                    .native_disable
2259                    .get(client)
2260                    .copied()
2261                    .unwrap_or(false)
2262                    .then(|| disabled_value(client, &o))
2263                    .flatten();
2264                match disabled {
2265                    Some(value) if mapper.canonical(&value) == canon_o => {
2266                        entry.state = EntryState::Synced;
2267                    }
2268                    Some(value) => {
2269                        entry.state = EntryState::PendingRemove;
2270                        entry.action = Action::Disable;
2271                        entry.written = Some(value);
2272                    }
2273                    None => {
2274                        entry.state = EntryState::PendingRemove;
2275                        entry.action = Action::Remove;
2276                    }
2277                }
2278            } else {
2279                entry.state = EntryState::Drifted;
2280                match resolution(&entry) {
2281                    OnConflict::Overwrite => entry.action = Action::Remove,
2282                    OnConflict::Import | OnConflict::Release => entry.action = Action::Release,
2283                    OnConflict::Skip => entry.action = Action::Skip,
2284                    OnConflict::Ask => {
2285                        entry.action = Action::Skip;
2286                        entry.unresolved = true;
2287                    }
2288                }
2289            }
2290        }
2291        (None, None, Some(l)) => {
2292            entry.client = adapter(&l.client).map(|spec| spec.id);
2293            entry.server_id = l.server_id.clone();
2294            if !entry
2295                .client
2296                .is_some_and(|client| input.clients.contains(&client))
2297            {
2298                return None;
2299            }
2300            entry.state = EntryState::Synced;
2301            entry.action = Action::Forget;
2302        }
2303        (None, Some(_), None) => {
2304            entry.state = EntryState::Foreign;
2305        }
2306        (None, None, None) => return None,
2307    }
2308    Some(entry)
2309}
2310
2311/// Sets the action of an entry that needs a decision; `owned` when
2312/// Surjection owns it (drifted, conflict), so it can be released.
2313fn decide(
2314    entry: &mut EntryPlan,
2315    resolution: OnConflict,
2316    overwrite: Action,
2317    desired: NativeValue,
2318    owned: bool,
2319) {
2320    match resolution {
2321        OnConflict::Overwrite => {
2322            entry.action = overwrite;
2323            entry.written = Some(desired);
2324        }
2325        OnConflict::Import => entry.action = Action::Import,
2326        OnConflict::Release if owned => entry.action = Action::Release,
2327        OnConflict::Skip | OnConflict::Release => entry.action = Action::Skip,
2328        OnConflict::Ask => {
2329            entry.action = Action::Skip;
2330            entry.unresolved = true;
2331        }
2332    }
2333}
2334
2335/// `value` disabled through the client's native mechanism; `None` when the
2336/// client has none that lives in the entry.
2337fn disabled_value(client: &str, value: &NativeValue) -> Option<NativeValue> {
2338    let mech = adapter(client)?.mcp.as_ref()?.caps.native_disable?;
2339    let mut entry = value.as_object()?.clone();
2340    match mech {
2341        DisableMech::EnabledFalse => {
2342            entry.insert("enabled", NativeValue::Bool(false));
2343        }
2344        DisableMech::DisabledTrue => {
2345            entry.insert("disabled", NativeValue::Bool(true));
2346        }
2347        DisableMech::ListMember(_) => return None,
2348    }
2349    Some(NativeValue::Object(entry))
2350}
2351
2352/// Plans a list target (Claude Code `disabledMcpServers`): desired members
2353/// are added and owned, owned members no longer desired are removed.
2354/// Members the user added are left alone and not reported.
2355fn plan_list(
2356    mut plan: TargetPlan,
2357    mut doc: Document,
2358    bytes: Option<Vec<u8>>,
2359    ledger: &Ledger,
2360    options: &PlanOptions,
2361) -> TargetPlan {
2362    let keys = plan.container.clone();
2363    let list: Vec<&str> = keys.iter().map(String::as_str).collect();
2364    let observed = match list_members(&doc, &list) {
2365        Ok(members) => members,
2366        Err(err) => {
2367            let err = err.with_path(&plan.file);
2368            return blocked_target(plan, err);
2369        }
2370    };
2371    let file = plan.file.to_string_lossy().into_owned();
2372    let (pointer, project_id) = (plan.pointer.clone(), plan.project_id.clone());
2373    let slot = LedgerSlot {
2374        scope: plan.scope,
2375        project_id: project_id.as_deref(),
2376        file: &file,
2377        container: &pointer,
2378    };
2379    let owned_here = ledger.slot_entries(&slot);
2380    let mut names: Vec<String> = Vec::new();
2381    for member in &plan.input.members {
2382        if !names.contains(&member.name) {
2383            names.push(member.name.clone());
2384        }
2385    }
2386    for row in owned_here.iter() {
2387        if row.kind == EntryKind::ListMember && !names.contains(&row.key) {
2388            names.push(row.key.clone());
2389        }
2390    }
2391    for name in names {
2392        let want = plan.input.members.iter().find(|member| member.name == name);
2393        let owned = owned_here
2394            .get(&name)
2395            .filter(|row| row.kind == EntryKind::ListMember);
2396        let client = match (want, owned) {
2397            (Some(member), _) => Some(member.client),
2398            (None, Some(row)) => adapter(&row.client)
2399                .map(|spec| spec.id)
2400                .filter(|client| plan.input.clients.contains(client)),
2401            (None, None) => None,
2402        };
2403        let Some(client) = client else {
2404            continue;
2405        };
2406        let present = observed.contains(&name);
2407        let member = NativeValue::String(name.clone());
2408        let mut entry = EntryPlan {
2409            name: name.clone(),
2410            client: Some(client),
2411            server_id: want
2412                .map(|member| member.server_id.clone())
2413                .or_else(|| owned.and_then(|row| row.server_id.clone())),
2414            state: EntryState::Synced,
2415            action: Action::None,
2416            unresolved: false,
2417            problem: None,
2418            desired: want.map(|_| member.clone()),
2419            observed: present.then(|| member.clone()),
2420            written: None,
2421            delivery: None,
2422        };
2423        match (want.is_some(), present, owned.is_some()) {
2424            (true, true, false) => {
2425                entry.action = Action::Adopt;
2426                entry.written = Some(member);
2427            }
2428            (true, true, true) => {}
2429            (true, false, false) => {
2430                entry.state = EntryState::PendingCreate;
2431                entry.action = Action::Create;
2432                entry.written = Some(member);
2433            }
2434            (true, false, true) => {
2435                entry.state = EntryState::Missing;
2436                // A member has nothing to import: write it again unless
2437                // the entry is skipped.
2438                if options.resolution(Some(client), &name) == OnConflict::Skip {
2439                    entry.action = Action::Skip;
2440                } else {
2441                    entry.action = Action::Create;
2442                    entry.written = Some(member);
2443                }
2444            }
2445            (false, true, true)
2446                if entry
2447                    .server_id
2448                    .as_ref()
2449                    .is_some_and(|id| plan.input.invalid_servers.contains(id)) =>
2450            {
2451                entry.state = EntryState::Blocked;
2452                entry.problem = Some(not_loading(entry.server_id.as_deref()));
2453            }
2454            (false, true, true) => {
2455                entry.state = EntryState::PendingRemove;
2456                entry.action = Action::Remove;
2457            }
2458            (false, false, true) => entry.action = Action::Forget,
2459            (false, _, false) => continue,
2460        }
2461        if options.entries.is_some() {
2462            // A run limited to named entries never changes a list.
2463            entry.action = Action::None;
2464            entry.written = None;
2465            entry.unresolved = false;
2466        }
2467        plan.entries.push(entry);
2468    }
2469    let mut changed = false;
2470    for entry in &plan.entries {
2471        let result = match entry.action {
2472            Action::Create => doc.set_list_member(&list, &entry.name, true),
2473            Action::Remove => doc.set_list_member(&list, &entry.name, false),
2474            _ => Ok(false),
2475        };
2476        match result {
2477            Ok(edited) => changed |= edited,
2478            Err(err) => {
2479                let err = err.with_path(&plan.file);
2480                return blocked_target(plan, err);
2481            }
2482        }
2483    }
2484    if changed {
2485        let after = doc.to_bytes();
2486        if bytes.as_deref() != Some(after.as_slice()) {
2487            plan.after = Some(after);
2488        }
2489    }
2490    plan
2491}
2492
2493/// The string members of the list at `list`; empty when it is absent.
2494pub(crate) fn list_members(doc: &Document, list: &[&str]) -> Result<Vec<String>, CoreError> {
2495    let Some((last, parent)) = list.split_last() else {
2496        return Ok(Vec::new());
2497    };
2498    match doc.get(parent, last)? {
2499        None => Ok(Vec::new()),
2500        Some(NativeValue::Array(items)) => Ok(items
2501            .iter()
2502            .filter_map(|item| item.as_str().map(str::to_owned))
2503            .collect()),
2504        Some(_) => Err(CoreError::new(
2505            ErrorCode::UnexpectedShape,
2506            format!("`{}` is not a list", list.join(".")),
2507        )),
2508    }
2509}
2510
2511/// Gate V1 FB-1: `project_key_spelling` when the map a project-keyed
2512/// container lives in already holds the same folder under another key.
2513fn key_spelling(target: &Target, doc: &Document, keys: &[String]) -> Option<CoreError> {
2514    let index = target
2515        .container
2516        .segments()
2517        .iter()
2518        .position(|segment| *segment == ContainerPath::PROJECT_KEY)?;
2519    let ours = keys.get(index)?;
2520    let parent: Vec<&str> = keys[..index].iter().map(String::as_str).collect();
2521    let other = doc
2522        .list(&parent)
2523        .ok()?
2524        .into_iter()
2525        .find(|key| key != ours && same_folder(target.os, key, ours))?;
2526    Some(
2527        CoreError::new(
2528            ErrorCode::ProjectKeySpelling,
2529            format!(
2530                "`{}` holds this folder as {other:?} too; {} writes {ours:?}, and the client \
2531                 may read the other key",
2532                parent.join("."),
2533                crate::brand::PRODUCT_NAME
2534            ),
2535        )
2536        .with_path(&target.file),
2537    )
2538}
2539
2540fn blocked_target(mut plan: TargetPlan, err: CoreError) -> TargetPlan {
2541    let input = &plan.input;
2542    plan.entries = input
2543        .desired
2544        .iter()
2545        .map(|want| {
2546            let mut entry = blocked_entry(
2547                &want.name,
2548                Some(want.client),
2549                Some(&want.server_id),
2550                err.clone(),
2551            );
2552            entry.delivery = want.delivery;
2553            entry
2554        })
2555        .chain(input.members.iter().map(|member| {
2556            blocked_entry(
2557                &member.name,
2558                Some(member.client),
2559                Some(&member.server_id),
2560                err.clone(),
2561            )
2562        }))
2563        .collect();
2564    plan.problem = Some(err);
2565    plan.after = None;
2566    plan
2567}
2568
2569/// Why an owned entry of server `id` is left alone: its file does not
2570/// load, so whether it is still wanted is unknown.
2571fn not_loading(id: Option<&str>) -> CoreError {
2572    CoreError::new(
2573        ErrorCode::ParseError,
2574        format!(
2575            "server {:?} does not load; its entry is left alone",
2576            id.unwrap_or_default()
2577        ),
2578    )
2579}
2580
2581fn blocked_entry(
2582    name: &str,
2583    client: Option<&'static str>,
2584    server_id: Option<&String>,
2585    err: CoreError,
2586) -> EntryPlan {
2587    EntryPlan {
2588        name: name.to_owned(),
2589        client,
2590        server_id: server_id.cloned(),
2591        state: EntryState::Blocked,
2592        action: Action::None,
2593        unresolved: false,
2594        problem: Some(err),
2595        desired: None,
2596        observed: None,
2597        written: None,
2598        delivery: None,
2599    }
2600}
2601
2602/// The canonical form a client's mapper gives `value`.
2603pub fn canonical(client: &str, value: &NativeValue) -> Option<Canonical> {
2604    mapper_of(client).map(|mapper| mapper.canonical(value))
2605}