1use std::collections::{BTreeMap, BTreeSet};
18use std::path::{Path, PathBuf};
19use std::sync::Arc;
20
21use crate::adapters::adapter;
22use crate::adapters::mapper::WriteCx;
23use crate::apply::ApplyEnv;
24use crate::apply::import::{self, Candidate};
25use crate::apply::ledger::{Ledger, LedgerKey};
26use crate::apply::placeholder_path;
27use crate::apply::plan::{self, Action, EntryState, PlanOptions, ScopeFilter};
28use crate::apply::render::{DesiredState, native_name, render};
29use crate::brand;
30use crate::error::CoreError;
31use crate::formats::NativeValue;
32use crate::fs::Fs;
33use crate::layering::same_path;
34use crate::model::applied::Scope;
35use crate::model::clients::ClientSelection;
36use crate::paths::normalize;
37use crate::secrets::delivery::Sharing;
38use crate::secrets::scanner::SecretMemory;
39use crate::skills::link::{CLIENT_SKILLS, LinkMethod, skills_dir};
40use crate::skills::{Entry, entry};
41
42use super::skilldock::wrapper_kind;
43use super::{Item, ItemKind, ItemStatus, Offer};
44
45#[derive(Debug, Clone, Default)]
47pub struct MigratedServer {
48 pub managed: Vec<String>,
50 pub imported_from: Vec<String>,
52}
53
54fn enabled_for(selection: Option<&ClientSelection>, client: &str) -> bool {
55 match selection {
56 Some(ClientSelection::List(ids)) => ids.iter().any(|id| id == client),
57 Some(ClientSelection::AllDetected) => true,
58 None => false,
59 }
60}
61
62fn is_read_only(client: &str) -> bool {
63 adapter(client)
64 .and_then(|spec| spec.mcp.as_ref())
65 .is_none_or(|mcp| mcp.read_only)
66}
67
68fn launch(value: &NativeValue) -> (Option<&str>, Vec<String>) {
70 let Some(map) = value.as_object() else {
71 return (None, Vec::new());
72 };
73 let command = map.get("command").and_then(NativeValue::as_str);
74 let args = map
75 .get("args")
76 .and_then(NativeValue::as_array)
77 .into_iter()
78 .flatten()
79 .filter_map(|arg| arg.as_str().map(str::to_owned))
80 .collect();
81 (command, args)
82}
83
84pub fn native_wrapper(value: &NativeValue) -> Option<&'static str> {
86 let (command, args) = launch(value);
87 wrapper_kind(command, &args)
88}
89
90pub fn adopt_identical(
94 ax: &ApplyEnv<'_>,
95 memory: Arc<SecretMemory>,
96 desired: &mut DesiredState,
97 migrated: &BTreeMap<String, MigratedServer>,
98 candidates: &[Candidate],
99) -> Vec<(String, String)> {
100 let cx = ax.render_cx(memory);
101 let mut adopted = Vec::new();
102 for candidate in candidates {
103 for source in &candidate.sources {
104 if is_read_only(source.client) {
105 continue;
106 }
107 let Some(spec) = adapter(source.client) else {
108 continue;
109 };
110 let Some(server) = desired
111 .servers
112 .values()
113 .filter(|server| migrated.contains_key(&server.id))
114 .find(|server| native_name(server, spec.id) == candidate.name)
115 else {
116 continue;
117 };
118 if enabled_for(
119 server.enable.as_ref().and_then(|e| e.clients.as_ref()),
120 spec.id,
121 ) {
122 continue;
123 }
124 let Ok(rendered) = render(&cx, desired, server, spec, Sharing::Private) else {
125 continue;
126 };
127 let mcp = spec.mcp.as_ref().expect("rendered clients have MCP");
128 let write = WriteCx {
129 os: ax.env.os(),
130 existing: Some(&source.value),
131 };
132 let Ok(native) = mcp.mapper.to_native(&rendered.server, &write) else {
133 continue;
134 };
135 if mcp.mapper.canonical(&native) != mcp.mapper.canonical(&source.value) {
136 continue;
137 }
138 let id = server.id.clone();
139 let server = desired.servers.get_mut(&id).expect("found above");
140 let enable = server.enable.get_or_insert_with(Default::default);
141 match &mut enable.clients {
142 Some(ClientSelection::List(ids)) => ids.push(spec.id.to_owned()),
143 _ => enable.clients = Some(ClientSelection::List(vec![spec.id.to_owned()])),
144 }
145 adopted.push((id, spec.id.to_owned()));
146 }
147 }
148 adopted
149}
150
151pub fn candidates(
153 ax: &ApplyEnv<'_>,
154 desired: &DesiredState,
155 ledger: &Ledger,
156) -> Result<(Vec<Candidate>, Vec<CoreError>), CoreError> {
157 import::scan(ax, desired, ledger, None)
158}
159
160#[allow(clippy::too_many_arguments)]
164pub fn mcp_entries(
165 ax: &ApplyEnv<'_>,
166 memory: Arc<SecretMemory>,
167 desired: &DesiredState,
168 ledger: &Ledger,
169 key: &LedgerKey,
170 migrated: &BTreeMap<String, MigratedServer>,
171 candidates: &[Candidate],
172 adopted: &[(String, String)],
173) -> Result<Vec<Item>, CoreError> {
174 let mut items = Vec::new();
175 if migrated.is_empty() {
176 return Ok(items);
177 }
178 let options = PlanOptions {
179 scope: ScopeFilter::System,
180 ..PlanOptions::default()
181 };
182 let plan = plan::plan(&ax.render_cx(memory), desired, ledger, key, &options)?;
183 let mut seen: BTreeSet<(String, String)> = BTreeSet::new();
184 for target in &plan.targets {
185 let file = placeholder_path(ax.env, &target.file, None);
186 let ours: Vec<_> = target
187 .entries
188 .iter()
189 .filter(|entry| {
190 entry
191 .server_id
192 .as_ref()
193 .is_some_and(|id| migrated.contains_key(id))
194 })
195 .collect();
196 if ours.is_empty() {
197 continue;
198 }
199 if let Some(problem) = &target.problem {
200 items.push(Item::new(
201 ItemKind::ClientEntry,
202 target.clients.join(", "),
203 ItemStatus::NeedsReview,
204 format!("{file} cannot be planned: {}", problem.message()),
205 Some(problem.code().as_str()),
206 ));
207 continue;
208 }
209 for entry in ours {
210 let id = entry.server_id.clone().expect("filtered above");
211 let client = entry.client.unwrap_or_default();
212 seen.insert((client.to_owned(), entry.name.clone()));
213 let name = format!("{client}/{}", entry.name);
214 let info = &migrated[&id];
215 let was_managed = info.managed.iter().any(|c| c == client);
216 let was_found = adopted.iter().any(|(s, c)| s == &id && c == client);
217 let (status, detail, code, offers) = match (entry.state, entry.action) {
218 (_, Action::Adopt) => (
219 ItemStatus::Migrated,
220 format!(
221 "identical entry in {file}{}; recorded as adopted on the first apply, \
222 without a write",
223 if was_found && !was_managed {
224 " (found by the scan)"
225 } else {
226 ""
227 }
228 ),
229 None,
230 Vec::new(),
231 ),
232 (_, Action::Create) => (
233 ItemStatus::Migrated,
234 format!("written to {file} on the first apply"),
235 None,
236 Vec::new(),
237 ),
238 (EntryState::Synced, _) => (
239 ItemStatus::Migrated,
240 format!("already in place in {file}"),
241 None,
242 Vec::new(),
243 ),
244 (EntryState::Collision, _) => {
245 let adopt = Offer::ReplaceWrapper {
246 client: client.to_owned(),
247 name: entry.name.clone(),
248 command: format!("{} adopt {name}", brand::BIN_NAME),
249 };
250 match entry.observed.as_ref().and_then(native_wrapper) {
251 Some(kind) => (
252 ItemStatus::NeedsReview,
253 format!(
254 "{file} holds SkillDock's {kind} wrapper; replace it with the \
255 native definition"
256 ),
257 Some("collision"),
258 vec![adopt],
259 ),
260 None => (
261 ItemStatus::NeedsReview,
262 format!(
263 "{file} holds a different entry{}; overwrite it, or keep the \
264 client's version with `{} adopt {name} --theirs`",
265 if was_managed {
266 " (SkillDock managed it)"
267 } else {
268 ""
269 },
270 brand::BIN_NAME
271 ),
272 Some("collision"),
273 vec![Offer::ReviewEntry {
274 client: client.to_owned(),
275 name: entry.name.clone(),
276 command: format!("{} adopt {name}", brand::BIN_NAME),
277 }],
278 ),
279 }
280 }
281 (EntryState::Blocked, _) => {
282 let problem = entry
283 .problem
284 .as_ref()
285 .map_or_else(|| "blocked".to_owned(), |p| p.message().to_owned());
286 let code = entry.problem.as_ref().map(|p| p.code().as_str());
287 match entry.observed.as_ref().and_then(native_wrapper) {
288 Some(kind) => (
291 ItemStatus::NeedsReview,
292 format!(
293 "{file} holds SkillDock's {kind} wrapper; the native definition \
294 cannot be written there yet: {problem}"
295 ),
296 code,
297 vec![Offer::ReplaceWrapper {
298 client: client.to_owned(),
299 name: entry.name.clone(),
300 command: format!("{} adopt {name}", brand::BIN_NAME),
301 }],
302 ),
303 None => (
304 ItemStatus::NeedsReview,
305 format!("not applied to {file} yet: {problem}"),
306 code,
307 Vec::new(),
308 ),
309 }
310 }
311 (state, action) => (
312 ItemStatus::NeedsReview,
313 format!(
314 "{file}: {} ({})",
315 state.as_str().replace('_', " "),
316 action.as_str()
317 ),
318 Some(state.as_str()),
319 Vec::new(),
320 ),
321 };
322 let mut item = Item::new(ItemKind::ClientEntry, name, status, detail, code);
323 item.offers = offers;
324 items.push(item);
325 }
326 }
327 for candidate in candidates {
330 for source in &candidate.sources {
331 if seen.contains(&(source.client.to_owned(), candidate.name.clone())) {
332 continue;
333 }
334 let Some(server) = desired
335 .servers
336 .values()
337 .filter(|server| migrated.contains_key(&server.id))
338 .find(|server| native_name(server, source.client) == candidate.name)
339 else {
340 continue;
341 };
342 let file = placeholder_path(ax.env, &source.file, None);
343 let name = format!("{}/{}", source.client, candidate.name);
344 let detail = match native_wrapper(&source.value) {
345 Some(kind) => format!(
346 "{file} holds SkillDock's {kind} wrapper for {:?}, which is not enabled for \
347 {}; enable it there and replace the wrapper, or remove the entry",
348 server.id, source.client
349 ),
350 None => format!(
351 "{file} holds a different {:?} entry; left foreign (enable the server for {} \
352 to manage it)",
353 server.id, source.client
354 ),
355 };
356 items.push(Item::new(
357 ItemKind::ClientEntry,
358 name,
359 ItemStatus::NeedsReview,
360 detail,
361 Some("foreign"),
362 ));
363 }
364 }
365 Ok(items)
366}
367
368#[derive(Debug, Clone)]
370pub struct FoundLink {
371 pub client: &'static str,
372 pub path: PathBuf,
374 pub display: String,
376 pub method: LinkMethod,
377 pub target: PathBuf,
379}
380
381pub fn library_links(
385 ax: &ApplyEnv<'_>,
386 library: &Path,
387) -> Result<BTreeMap<String, Vec<FoundLink>>, CoreError> {
388 let fs: &dyn Fs = ax.fs;
389 let mut out: BTreeMap<String, Vec<FoundLink>> = BTreeMap::new();
390 for client in &CLIENT_SKILLS {
391 let Ok(dir) = skills_dir(ax.env, client.client, Scope::User, None) else {
392 continue;
393 };
394 if !fs.is_dir(&dir) {
395 continue;
396 }
397 let Ok(mut paths) = fs.read_dir(&dir) else {
398 continue;
399 };
400 paths.sort();
401 for path in paths {
402 let Ok(Entry::Link(target)) = entry(fs, &path) else {
403 continue;
404 };
405 let target = normalize(&target);
406 let (Some(parent), Some(name)) = (target.parent(), target.file_name()) else {
407 continue;
408 };
409 if !same_path(parent, library) {
410 continue;
411 }
412 out.entry(name.to_string_lossy().into_owned())
413 .or_default()
414 .push(FoundLink {
415 client: client.client,
416 display: placeholder_path(ax.env, &path, None),
417 method: link_method(&path),
418 path,
419 target,
420 });
421 }
422 }
423 Ok(out)
424}
425
426#[cfg(windows)]
427fn link_method(path: &Path) -> LinkMethod {
428 if junction::exists(path).unwrap_or(false) {
429 LinkMethod::Junction
430 } else {
431 LinkMethod::Symlink
432 }
433}
434
435#[cfg(not(windows))]
436fn link_method(_path: &Path) -> LinkMethod {
437 LinkMethod::Symlink
438}