1use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result, bail};
11use serde::Serialize;
12use serde_json::{Map, Value, json};
13
14pub const NAME: &str = "rust-anything";
16
17pub const SKILL: &str = include_str!("../skills/rust-anything/SKILL.md");
19pub(crate) const SKILL_FILES: &[(&str, &str)] = &[
20 ("SKILL.md", SKILL),
21 (
22 "whole-app.md",
23 include_str!("../skills/rust-anything/whole-app.md"),
24 ),
25];
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
28#[serde(rename_all = "lowercase")]
29pub enum Agent {
30 Claude,
32 Codex,
34 Cursor,
36 Gemini,
38 #[value(name = "opencode")]
40 OpenCode,
41}
42
43impl Agent {
44 pub const ALL: [Agent; 5] = [
45 Agent::Claude,
46 Agent::Codex,
47 Agent::Cursor,
48 Agent::Gemini,
49 Agent::OpenCode,
50 ];
51
52 pub fn name(self) -> &'static str {
53 match self {
54 Agent::Claude => "Claude Code",
55 Agent::Codex => "Codex",
56 Agent::Cursor => "Cursor",
57 Agent::Gemini => "Gemini CLI",
58 Agent::OpenCode => "OpenCode",
59 }
60 }
61
62 fn markers(self) -> (&'static str, &'static str) {
64 match self {
65 Agent::Claude => (".claude", "claude"),
66 Agent::Codex => (".codex", "codex"),
67 Agent::Cursor => (".cursor", "cursor"),
68 Agent::Gemini => (".gemini", "gemini"),
69 Agent::OpenCode => (".config/opencode", "opencode"),
70 }
71 }
72
73 pub(crate) fn config(self, home: &Path) -> PathBuf {
75 home.join(match self {
76 Agent::Claude => ".claude.json",
77 Agent::Codex => ".codex/config.toml",
78 Agent::Cursor => ".cursor/mcp.json",
79 Agent::Gemini => ".gemini/settings.json",
80 Agent::OpenCode => ".config/opencode/opencode.json",
81 })
82 }
83
84 pub(crate) fn skill_dir(self, home: &Path) -> Option<PathBuf> {
86 match self {
87 Agent::Claude => Some(home.join(".claude/skills").join(NAME)),
88 Agent::Codex => Some(home.join(".codex/skills").join(NAME)),
89 Agent::OpenCode => Some(home.join(".config/opencode/skills").join(NAME)),
90 Agent::Cursor | Agent::Gemini => None,
91 }
92 }
93
94 pub(crate) fn present(self, home: &Path) -> bool {
96 let (dir, command) = self.markers();
97 home.join(dir).is_dir() || on_path(command)
98 }
99}
100
101fn on_path(command: &str) -> bool {
102 std::env::var_os("PATH").is_some_and(|paths| {
103 std::env::split_paths(&paths).any(|dir| {
104 let file = dir.join(command);
105 file.is_file()
106 || file.with_extension("exe").is_file()
107 || file.with_extension("cmd").is_file()
108 })
109 })
110}
111
112pub struct Options<'a> {
113 pub home: &'a Path,
114 pub agents: Vec<Agent>,
116 pub command: PathBuf,
118 pub remove: bool,
119 pub dry_run: bool,
120}
121
122#[derive(Debug, Serialize)]
124pub struct Change {
125 pub agent: Agent,
126 pub file: PathBuf,
127 pub action: &'static str,
129 #[serde(skip_serializing_if = "Option::is_none")]
131 pub backup: Option<PathBuf>,
132}
133
134#[derive(Debug, Serialize)]
135pub struct Report {
136 pub command: PathBuf,
137 pub agents: Vec<Agent>,
138 pub changes: Vec<Change>,
139 pub dry_run: bool,
140}
141
142pub fn home() -> Result<PathBuf> {
144 std::env::var_os("HOME")
145 .or_else(|| std::env::var_os("USERPROFILE"))
146 .map(PathBuf::from)
147 .context("no home directory (HOME is not set)")
148}
149
150pub fn setup(opts: &Options) -> Result<Report> {
151 let agents: Vec<Agent> = if opts.agents.is_empty() {
152 Agent::ALL
153 .into_iter()
154 .filter(|a| a.present(opts.home))
155 .collect()
156 } else {
157 opts.agents.clone()
158 };
159 if agents.is_empty() {
160 bail!(
161 "no coding agent found (looked for ~/.claude, ~/.codex, ~/.cursor, ~/.gemini, ~/.config/opencode and their commands); \
162 name one with --agent claude|codex|cursor|gemini|opencode"
163 );
164 }
165 let command = opts.command.to_string_lossy().into_owned();
166 let mut changes = Vec::new();
167 for &agent in &agents {
168 let config = agent.config(opts.home);
169 changes.push(match agent {
170 Agent::Codex => codex_server(agent, &config, &command, opts)?,
171 Agent::OpenCode => opencode_server(agent, &config, &command, opts)?,
172 _ => json_server(agent, &config, &command, opts, agent == Agent::Claude)?,
173 });
174 if let Some(dir) = agent.skill_dir(opts.home) {
175 changes.push(skill(agent, &dir, opts)?);
176 }
177 }
178 Ok(Report {
179 command: opts.command.clone(),
180 agents,
181 changes,
182 dry_run: opts.dry_run,
183 })
184}
185
186fn backup(path: &Path) -> Result<Option<PathBuf>> {
188 if !path.is_file() {
189 return Ok(None);
190 }
191 let mut name = path.file_name().unwrap_or_default().to_os_string();
192 name.push(".rust-anything.bak");
193 let copy = path.with_file_name(name);
194 std::fs::copy(path, ©).with_context(|| format!("backing up {}", path.display()))?;
195 Ok(Some(copy))
196}
197
198fn write(path: &Path, text: &str) -> Result<()> {
200 if let Some(dir) = path.parent() {
201 std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
202 }
203 let tmp = path.with_extension("rust-anything.tmp");
204 std::fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
205 std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
206}
207
208fn json_server(
210 agent: Agent,
211 path: &Path,
212 command: &str,
213 opts: &Options,
214 stdio_type: bool,
215) -> Result<Change> {
216 let text = match std::fs::read_to_string(path) {
217 Ok(t) => Some(t),
218 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
219 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
220 };
221 let mut doc: Value = match text.as_deref().map(str::trim) {
222 None | Some("") => json!({}),
223 Some(t) => serde_json::from_str(t).with_context(|| {
224 format!(
225 "{} is not valid JSON; fix it or add the server by hand",
226 path.display()
227 )
228 })?,
229 };
230 let Some(root) = doc.as_object_mut() else {
231 bail!(
232 "{} is not a JSON object; add the server by hand",
233 path.display()
234 );
235 };
236 let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
237 let Some(servers) = servers.as_object_mut() else {
238 bail!(
239 "`mcpServers` in {} is not an object; add the server by hand",
240 path.display()
241 );
242 };
243 let action = if opts.remove {
244 if servers.shift_remove(NAME).is_some() {
245 "removed"
246 } else {
247 "absent"
248 }
249 } else {
250 let existing = servers.get(NAME);
251 let mut entry = existing
252 .and_then(Value::as_object)
253 .cloned()
254 .unwrap_or_default();
255 entry.insert("command".into(), json!(command));
256 entry.insert("args".into(), json!(["mcp"]));
257 if stdio_type || entry.contains_key("type") {
258 entry.insert("type".into(), json!("stdio"));
259 }
260 if stdio_type {
261 entry.entry("env").or_insert_with(|| json!({}));
262 }
263 entry.shift_remove("url");
264 let entry = Value::Object(entry);
265 if existing == Some(&entry) {
266 "unchanged"
267 } else {
268 let action = if existing.is_some() {
269 "updated"
270 } else {
271 "added"
272 };
273 servers.insert(NAME.into(), entry);
274 action
275 }
276 };
277 let mut saved = None;
278 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
279 saved = backup(path)?;
280 write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
281 }
282 Ok(Change {
283 agent,
284 file: path.to_path_buf(),
285 action,
286 backup: saved,
287 })
288}
289
290fn opencode_servers<'a>(
294 mcp: &'a mut Map<String, Value>,
295 path: &Path,
296) -> Result<&'a mut Map<String, Value>> {
297 if mcp.is_empty() || matches!(mcp.get("servers"), Some(Value::Object(_))) {
298 let servers = mcp.entry("servers").or_insert_with(|| json!({}));
299 return servers.as_object_mut().with_context(|| {
300 format!(
301 "`mcp.servers` in {} is not an object; add the server by hand",
302 path.display()
303 )
304 });
305 }
306 Ok(mcp)
307}
308
309fn opencode_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
312 let text = match std::fs::read_to_string(path) {
313 Ok(t) => Some(t),
314 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
315 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
316 };
317 let mut doc: Value = match text.as_deref().map(str::trim) {
318 None | Some("") => json!({}),
319 Some(t) => serde_json::from_str(t).with_context(|| {
320 format!(
321 "{} is not valid JSON; fix it or add the server by hand",
322 path.display()
323 )
324 })?,
325 };
326 let Some(root) = doc.as_object_mut() else {
327 bail!(
328 "{} is not a JSON object; add the server by hand",
329 path.display()
330 );
331 };
332 let mcp = root.entry("mcp").or_insert_with(|| json!({}));
333 let Some(mcp) = mcp.as_object_mut() else {
334 bail!(
335 "`mcp` in {} is not an object; add the server by hand",
336 path.display()
337 );
338 };
339 let servers = opencode_servers(mcp, path)?;
340 let action = if opts.remove {
341 if servers.shift_remove(NAME).is_some() {
342 "removed"
343 } else {
344 "absent"
345 }
346 } else {
347 let existing = servers.get(NAME);
348 let mut entry = existing
349 .and_then(Value::as_object)
350 .cloned()
351 .unwrap_or_default();
352 entry.insert("type".into(), json!("local"));
353 entry.insert("command".into(), json!([command, "mcp"]));
354 entry.shift_remove("disabled");
357 entry.shift_remove("enabled");
358 entry.shift_remove("url");
359 let entry = Value::Object(entry);
360 if existing == Some(&entry) {
361 "unchanged"
362 } else {
363 let action = if existing.is_some() {
364 "updated"
365 } else {
366 "added"
367 };
368 servers.insert(NAME.into(), entry);
369 action
370 }
371 };
372 let mut saved = None;
373 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
374 saved = backup(path)?;
375 write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
376 }
377 Ok(Change {
378 agent,
379 file: path.to_path_buf(),
380 action,
381 backup: saved,
382 })
383}
384
385fn codex_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
387 let text = match std::fs::read_to_string(path) {
388 Ok(t) => t,
389 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
390 Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
391 };
392 let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| {
393 format!(
394 "{} is not valid TOML; fix it or add the server by hand",
395 path.display()
396 )
397 })?;
398 let servers = doc
399 .entry("mcp_servers")
400 .or_insert_with(|| {
401 let mut t = toml_edit::Table::new();
402 t.set_implicit(true);
403 toml_edit::Item::Table(t)
404 })
405 .as_table_mut()
406 .with_context(|| format!("`mcp_servers` in {} is not a table", path.display()))?;
407 let same = servers
408 .get(NAME)
409 .and_then(|t| t.as_table())
410 .is_some_and(|t| {
411 t.get("command").and_then(|c| c.as_str()) == Some(command)
412 && t.get("url").is_none()
413 && t.get("args").and_then(|a| a.as_array()).is_some_and(|a| {
414 a.iter().map(|v| v.as_str()).collect::<Vec<_>>() == [Some("mcp")]
415 })
416 });
417 let action = if opts.remove {
418 if servers.remove(NAME).is_some() {
419 "removed"
420 } else {
421 "absent"
422 }
423 } else if same {
424 "unchanged"
425 } else {
426 let had = servers.contains_key(NAME);
427 let mut entry = servers
428 .get(NAME)
429 .and_then(toml_edit::Item::as_table)
430 .cloned()
431 .unwrap_or_default();
432 entry["command"] = toml_edit::value(command);
433 let mut args = toml_edit::Array::new();
434 args.push("mcp");
435 entry["args"] = toml_edit::value(args);
436 entry.remove("url");
437 servers.insert(NAME, toml_edit::Item::Table(entry));
438 if had { "updated" } else { "added" }
439 };
440 let mut saved = None;
441 if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
442 saved = backup(path)?;
443 write(path, &doc.to_string())?;
444 }
445 Ok(Change {
446 agent,
447 file: path.to_path_buf(),
448 action,
449 backup: saved,
450 })
451}
452
453fn skill(agent: Agent, dir: &Path, opts: &Options) -> Result<Change> {
455 let current: Vec<Option<String>> = SKILL_FILES
456 .iter()
457 .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
458 .collect();
459 let action = if opts.remove {
460 if current.iter().any(Option::is_some) {
461 "removed"
462 } else {
463 "absent"
464 }
465 } else if current.iter().all(Option::is_none) {
466 "added"
467 } else if current
468 .iter()
469 .zip(SKILL_FILES)
470 .all(|(have, (_, want))| have.as_deref() == Some(*want))
471 {
472 "unchanged"
473 } else {
474 "updated"
475 };
476 if !opts.dry_run {
477 for (name, text) in SKILL_FILES {
478 let path = dir.join(name);
479 match action {
480 "added" | "updated" => write(&path, text)?,
481 "removed" if path.exists() => {
482 std::fs::remove_file(&path)
483 .with_context(|| format!("removing {}", path.display()))?;
484 }
485 _ => {}
486 }
487 }
488 if action == "removed" {
489 let _ = std::fs::remove_dir(dir);
491 }
492 }
493 Ok(Change {
494 agent,
495 file: dir.join("SKILL.md"),
496 action,
497 backup: None,
498 })
499}
500
501pub fn text(r: &Report) -> String {
503 let mut out = String::new();
504 let verb = if r.dry_run { "Would set up" } else { "Set up" };
505 let names: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
506 out.push_str(&format!("{verb} rust-anything for {}\n", names.join(", ")));
507 for c in &r.changes {
508 out.push_str(&format!(
509 " {:<10} {:<9} {}\n",
510 c.agent.name(),
511 c.action,
512 c.file.display()
513 ));
514 if let Some(b) = &c.backup {
515 out.push_str(&format!(" {:<10} {:<9} {}\n", "", "backup", b.display()));
516 }
517 }
518 if !r.dry_run
519 && r.changes
520 .iter()
521 .any(|c| c.action != "removed" && c.action != "absent")
522 {
523 out.push_str(&format!(
524 "\nThe agents run `{} mcp`. Restart them, then ask, for example:\n \
525 \"Profile this repo's slowest workflow with rust-anything and move the hot loop to Rust.\"\n",
526 r.command.display()
527 ));
528 }
529 out
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535
536 fn temp_home(name: &str) -> PathBuf {
537 let dir =
538 std::env::temp_dir().join(format!("rust-anything-setup-{name}-{}", std::process::id()));
539 let _ = std::fs::remove_dir_all(&dir);
540 std::fs::create_dir_all(&dir).unwrap();
541 dir
542 }
543
544 fn opts(home: &Path, agents: Vec<Agent>) -> Options<'_> {
545 Options {
546 home,
547 agents,
548 command: PathBuf::from("/opt/bin/rust-anything"),
549 remove: false,
550 dry_run: false,
551 }
552 }
553
554 #[test]
555 fn adds_keeps_and_removes_entries() {
556 let home = temp_home("all");
557 std::fs::write(
559 home.join(".claude.json"),
560 r#"{"zeta": 1, "mcpServers": {"other": {"command": "x"}}, "alpha": true}"#,
561 )
562 .unwrap();
563 std::fs::create_dir_all(home.join(".codex")).unwrap();
564 std::fs::write(
565 home.join(".codex/config.toml"),
566 "model = \"o4\"\n\n[mcp_servers.other]\ncommand = \"x\"\n",
567 )
568 .unwrap();
569
570 let all = Agent::ALL.to_vec();
571 let r = setup(&opts(&home, all.clone())).unwrap();
572 assert!(
573 r.changes.iter().all(|c| c.action == "added"),
574 "{:?}",
575 r.changes
576 );
577
578 let claude: Value =
579 serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
580 .unwrap();
581 assert_eq!(
582 claude["mcpServers"]["rust-anything"]["args"],
583 json!(["mcp"])
584 );
585 assert_eq!(claude["mcpServers"]["other"]["command"], "x");
586 let saved = r.changes[0]
588 .backup
589 .clone()
590 .expect("an existing file is backed up");
591 assert!(
592 std::fs::read_to_string(saved)
593 .unwrap()
594 .starts_with(r#"{"zeta": 1"#)
595 );
596 assert!(r.changes.iter().any(|c| c.backup.is_none()));
597 let keys: Vec<&String> = claude.as_object().unwrap().keys().collect();
598 assert_eq!(keys, ["zeta", "mcpServers", "alpha"], "key order kept");
599 let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
600 assert!(codex.starts_with("model = \"o4\""), "{codex}");
601 assert!(codex.contains("[mcp_servers.rust-anything]\ncommand = \"/opt/bin/rust-anything\"\nargs = [\"mcp\"]"), "{codex}");
602 assert!(codex.contains("[mcp_servers.other]"));
603 assert_eq!(
604 std::fs::read_to_string(home.join(".claude/skills/rust-anything/SKILL.md")).unwrap(),
605 SKILL
606 );
607 assert!(
608 home.join(".codex/skills/rust-anything/whole-app.md")
609 .exists()
610 );
611 let cursor: Value =
612 serde_json::from_str(&std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap())
613 .unwrap();
614 assert_eq!(
615 cursor["mcpServers"]["rust-anything"]["command"],
616 "/opt/bin/rust-anything"
617 );
618 assert!(home.join(".gemini/settings.json").exists());
619
620 let again = setup(&opts(&home, all.clone())).unwrap();
622 assert!(
623 again.changes.iter().all(|c| c.action == "unchanged"),
624 "{:?}",
625 again.changes
626 );
627
628 let mut moved = opts(&home, vec![Agent::Codex]);
630 moved.command = PathBuf::from("/usr/local/bin/rust-anything");
631 let r = setup(&moved).unwrap();
632 assert_eq!(r.changes[0].action, "updated");
633
634 let mut remove = opts(&home, all);
636 remove.remove = true;
637 setup(&remove).unwrap();
638 let claude: Value =
639 serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
640 .unwrap();
641 assert!(claude["mcpServers"].get("rust-anything").is_none());
642 assert_eq!(claude["mcpServers"]["other"]["command"], "x");
643 assert!(!home.join(".claude/skills/rust-anything").exists());
644 let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
645 assert!(
646 !codex.contains("rust-anything") && codex.contains("[mcp_servers.other]"),
647 "{codex}"
648 );
649 std::fs::remove_dir_all(&home).unwrap();
650 }
651
652 #[test]
653 fn reinstall_preserves_custom_options_for_the_same_server() {
654 let home = temp_home("custom-entry");
655 let cursor = home.join(".cursor/mcp.json");
656 let codex = home.join(".codex/config.toml");
657 std::fs::create_dir_all(cursor.parent().unwrap()).unwrap();
658 std::fs::create_dir_all(codex.parent().unwrap()).unwrap();
659 std::fs::write(&cursor, r#"{"mcpServers":{"rust-anything":{"command":"old","args":["mcp"],"env":{"MODE":"custom"}}}}"#).unwrap();
660 std::fs::write(&codex, "[mcp_servers.rust-anything]\ncommand = \"old\"\nargs = [\"mcp\"]\ntool_timeout_sec = 120\n").unwrap();
661
662 let options = opts(&home, vec![Agent::Cursor, Agent::Codex]);
663 setup(&options).unwrap();
664 let cursor: Value =
665 serde_json::from_str(&std::fs::read_to_string(cursor).unwrap()).unwrap();
666 let codex: toml_edit::DocumentMut =
667 std::fs::read_to_string(codex).unwrap().parse().unwrap();
668 let again = setup(&options).unwrap();
669 std::fs::remove_dir_all(home).unwrap();
670 assert_eq!(cursor["mcpServers"][NAME]["env"]["MODE"], "custom");
671 assert_eq!(
672 cursor["mcpServers"][NAME]["command"],
673 "/opt/bin/rust-anything"
674 );
675 assert_eq!(
676 codex["mcp_servers"][NAME]["tool_timeout_sec"].as_integer(),
677 Some(120)
678 );
679 assert!(again.changes.iter().all(|c| c.action == "unchanged"));
680 }
681
682 #[test]
683 fn opencode_gets_a_local_server_and_the_skill() {
684 let home = temp_home("opencode");
685 let config = home.join(".config/opencode/opencode.json");
686 std::fs::create_dir_all(config.parent().unwrap()).unwrap();
687 std::fs::write(
689 &config,
690 r#"{"$schema":"https://opencode.ai/config.json","mcp":{"servers":{"other":{"type":"local","command":["x"]}}},"model":"a/b"}"#,
691 )
692 .unwrap();
693
694 let mut options = opts(&home, vec![Agent::OpenCode]);
695 setup(&options).unwrap();
696 let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
697 let entry = &doc["mcp"]["servers"][NAME];
698 assert_eq!(entry["type"], "local");
699 assert_eq!(entry["command"], json!(["/opt/bin/rust-anything", "mcp"]));
700 assert!(entry.get("disabled").is_none(), "{entry}");
701 assert_eq!(doc["mcp"]["servers"]["other"]["command"], json!(["x"]));
702 assert_eq!(doc["model"], "a/b");
703 let keys: Vec<&String> = doc.as_object().unwrap().keys().collect();
704 assert_eq!(keys, ["$schema", "mcp", "model"], "key order kept");
705 assert_eq!(
706 std::fs::read_to_string(home.join(".config/opencode/skills/rust-anything/SKILL.md"))
707 .unwrap(),
708 SKILL
709 );
710
711 let again = setup(&options).unwrap();
713 assert!(
714 again.changes.iter().all(|c| c.action == "unchanged"),
715 "{:?}",
716 again.changes
717 );
718
719 let mut doc: Value =
721 serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
722 doc["mcp"]["servers"][NAME]["disabled"] = json!(true);
723 std::fs::write(&config, serde_json::to_string(&doc).unwrap()).unwrap();
724 let r = setup(&options).unwrap();
725 assert_eq!(r.changes[0].action, "updated");
726 let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
727 assert!(doc["mcp"]["servers"][NAME].get("disabled").is_none());
728
729 options.command = PathBuf::from("/usr/local/bin/rust-anything");
731 let r = setup(&options).unwrap();
732 assert_eq!(r.changes[0].action, "updated");
733
734 options.remove = true;
736 setup(&options).unwrap();
737 let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
738 assert!(doc["mcp"]["servers"].get(NAME).is_none());
739 assert_eq!(doc["mcp"]["servers"]["other"]["command"], json!(["x"]));
740 assert!(!home.join(".config/opencode/skills/rust-anything").exists());
741
742 let flat = temp_home("opencode-flat");
744 let flat_config = flat.join(".config/opencode/opencode.json");
745 std::fs::create_dir_all(flat_config.parent().unwrap()).unwrap();
746 std::fs::write(
747 &flat_config,
748 r#"{"mcp":{"other":{"type":"local","command":["x"]},"rust-anything":{"type":"local","command":["/old/rust-anything","mcp"],"enabled":true}}}"#,
749 )
750 .unwrap();
751 setup(&opts(&flat, vec![Agent::OpenCode])).unwrap();
752 let doc: Value =
753 serde_json::from_str(&std::fs::read_to_string(&flat_config).unwrap()).unwrap();
754 let entry = &doc["mcp"][NAME];
755 assert_eq!(entry["command"], json!(["/opt/bin/rust-anything", "mcp"]));
756 assert!(entry.get("enabled").is_none(), "{entry}");
757 assert!(entry.get("disabled").is_none(), "{entry}");
758 assert!(
759 doc["mcp"].get("servers").is_none(),
760 "shapes never mix: {doc}"
761 );
762 assert_eq!(doc["mcp"]["other"]["command"], json!(["x"]));
763 std::fs::remove_dir_all(&flat).unwrap();
764
765 std::fs::write(&config, "{ not json").unwrap();
767 let err = setup(&opts(&home, vec![Agent::OpenCode])).unwrap_err();
768 assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
769 assert_eq!(std::fs::read_to_string(&config).unwrap(), "{ not json");
770 std::fs::remove_dir_all(&home).unwrap();
771 }
772
773 #[test]
774 fn finds_agents_and_never_breaks_a_bad_file() {
775 let home = temp_home("detect");
776 std::fs::create_dir_all(home.join(".cursor")).unwrap();
777 std::fs::write(home.join(".cursor/mcp.json"), "{ not json").unwrap();
778 let found: Vec<Agent> = Agent::ALL
780 .into_iter()
781 .filter(|a| a.present(&home))
782 .collect();
783 assert!(found.contains(&Agent::Cursor));
784 let err = setup(&opts(&home, vec![Agent::Cursor])).unwrap_err();
785 assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
786 assert_eq!(
787 std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap(),
788 "{ not json"
789 );
790
791 let mut dry = opts(&home, vec![Agent::Gemini]);
793 dry.dry_run = true;
794 let r = setup(&dry).unwrap();
795 assert_eq!(r.changes[0].action, "added");
796 assert!(!home.join(".gemini").exists());
797 std::fs::remove_dir_all(&home).unwrap();
798 }
799}