1use std::path::{Path, PathBuf};
4
5use serde::Serialize;
6
7use crate::config::Config;
8use crate::error::MarsError;
9use crate::local_source;
10use crate::lock::ItemKind;
11use crate::sync::{ResolutionMode, SyncOptions, SyncRequest};
12use crate::types::{DestPath, MarsContext};
13
14use super::output;
15
16#[derive(Debug, clap::Args)]
17pub struct AdoptArgs {
18 pub path: PathBuf,
20
21 #[arg(long)]
23 pub dry_run: bool,
24}
25
26#[derive(Debug)]
27struct AdoptPlan {
28 kind: ItemKind,
29 name: String,
30 source_abs: PathBuf,
31 source_display: String,
32 dest_abs: PathBuf,
33 dest_display: String,
34}
35
36#[derive(Debug, Serialize)]
37struct AdoptJson<'a> {
38 ok: bool,
39 kind: &'a str,
40 name: &'a str,
41 source_path: &'a str,
42 dest_path: &'a str,
43 #[serde(skip_serializing_if = "Option::is_none")]
44 sync: Option<serde_json::Value>,
45}
46
47pub fn run(args: &AdoptArgs, ctx: &MarsContext, json: bool) -> Result<i32, MarsError> {
48 let config = crate::config::load(&ctx.project_root)?;
49
50 let lock = crate::lock::load(&ctx.project_root)?;
51 let source_abs = resolve_cli_path(&args.path)?;
52 let source_display = relative_display(&ctx.project_root, &source_abs);
53
54 if source_abs.symlink_metadata().is_err() {
55 return Err(MarsError::InvalidRequest {
56 message: format!("path not found: {source_display}"),
57 });
58 }
59
60 let (target_name, target_rel) = source_target_membership(ctx, &config, &source_abs)?;
61 let target_dest = DestPath::new(target_rel.to_string_lossy().as_ref()).map_err(|e| {
62 MarsError::InvalidRequest {
63 message: format!(
64 "{} resolves to invalid managed target item `{}`: {e}",
65 source_display,
66 target_rel.display()
67 ),
68 }
69 })?;
70 if lock.contains_output(&target_name, target_dest.as_str()) {
71 return Err(MarsError::InvalidRequest {
72 message: format!(
73 "{source_display} is already managed by Mars (target `{target_name}` item `{}`)",
74 target_rel.display()
75 ),
76 });
77 }
78
79 let plan = build_plan(ctx, &source_abs, &source_display)?;
80
81 if args.dry_run {
82 return print_dry_run(&plan, json);
83 }
84
85 move_item(&plan.source_abs, &plan.dest_abs)?;
86
87 let request = SyncRequest {
88 resolution: ResolutionMode::Normal,
89 mutation: None,
90 options: SyncOptions::default(),
91 };
92 let report = crate::sync::execute(ctx, &request)?;
93
94 if json {
95 output::print_json(&AdoptJson {
96 ok: true,
97 kind: kind_name(plan.kind),
98 name: &plan.name,
99 source_path: &plan.source_display,
100 dest_path: &plan.dest_display,
101 sync: Some(output::sync_report_json(&report)),
102 });
103 } else {
104 output::print_success(&format!(
105 "adopted {} `{}`: {} -> {}",
106 kind_name(plan.kind),
107 plan.name,
108 plan.source_display,
109 plan.dest_display
110 ));
111 output::print_sync_report(&report, false, true);
112 }
113
114 Ok(if report.has_conflicts() { 1 } else { 0 })
115}
116
117fn resolve_cli_path(path: &Path) -> Result<PathBuf, MarsError> {
118 let absolute = if path.is_absolute() {
119 path.to_path_buf()
120 } else {
121 std::env::current_dir()?.join(path)
122 };
123 Ok(absolute)
124}
125
126fn source_target_membership(
127 ctx: &MarsContext,
128 config: &Config,
129 source_abs: &Path,
130) -> Result<(String, PathBuf), MarsError> {
131 let source_canon = dunce::canonicalize(source_abs)?;
132 for target_name in config.settings.managed_targets() {
133 let target_root = ctx.project_root.join(&target_name);
134 let Ok(target_canon) = dunce::canonicalize(&target_root) else {
135 continue;
136 };
137 if let Ok(relative) = source_canon.strip_prefix(&target_canon) {
138 return Ok((target_name, relative.to_path_buf()));
139 }
140 }
141
142 Err(MarsError::InvalidRequest {
143 message: format!(
144 "{} is not inside a managed target directory",
145 relative_display(&ctx.project_root, source_abs)
146 ),
147 })
148}
149
150fn build_plan(
151 ctx: &MarsContext,
152 source_abs: &Path,
153 source_display: &str,
154) -> Result<AdoptPlan, MarsError> {
155 let metadata = source_abs.symlink_metadata()?;
156 let preferred_root = local_source::preferred_local_source_root(&ctx.project_root);
157
158 let (kind, name, dest_abs) = if metadata.is_dir() {
159 if !source_abs.join("SKILL.md").is_file() {
160 return Err(MarsError::InvalidRequest {
161 message: format!(
162 "{source_display} is not a valid skill directory (expected a directory containing SKILL.md)"
163 ),
164 });
165 }
166 let name = source_abs
167 .file_name()
168 .and_then(|name| name.to_str())
169 .ok_or_else(|| MarsError::InvalidRequest {
170 message: format!("could not derive skill name from {source_display}"),
171 })?
172 .to_string();
173 (
174 ItemKind::Skill,
175 name.clone(),
176 preferred_root.join("skills").join(&name),
177 )
178 } else if metadata.is_file() {
179 let is_agent = source_abs.extension().and_then(|ext| ext.to_str()) == Some("md")
180 && source_abs
181 .parent()
182 .and_then(|path| path.file_name())
183 .and_then(|name| name.to_str())
184 == Some("agents");
185 if !is_agent {
186 return Err(MarsError::InvalidRequest {
187 message: format!(
188 "{source_display} is not a valid agent file (expected a .md file inside agents/)"
189 ),
190 });
191 }
192 let name = source_abs
193 .file_stem()
194 .and_then(|name| name.to_str())
195 .ok_or_else(|| MarsError::InvalidRequest {
196 message: format!("could not derive agent name from {source_display}"),
197 })?
198 .to_string();
199 (
200 ItemKind::Agent,
201 name.clone(),
202 preferred_root.join("agents").join(format!("{name}.md")),
203 )
204 } else {
205 return Err(MarsError::InvalidRequest {
206 message: format!(
207 "{source_display} is not a valid item (expected a skill directory or agent markdown file)"
208 ),
209 });
210 };
211
212 if dest_abs.symlink_metadata().is_ok() {
213 return Err(MarsError::InvalidRequest {
214 message: format!(
215 "{} already exists; refusing to overwrite local source content",
216 relative_display(&ctx.project_root, &dest_abs)
217 ),
218 });
219 }
220
221 Ok(AdoptPlan {
222 kind,
223 name,
224 source_abs: source_abs.to_path_buf(),
225 source_display: source_display.to_string(),
226 dest_display: relative_display(&ctx.project_root, &dest_abs),
227 dest_abs,
228 })
229}
230
231fn print_dry_run(plan: &AdoptPlan, json: bool) -> Result<i32, MarsError> {
232 if json {
233 output::print_json(&serde_json::json!({
234 "ok": true,
235 "dry_run": true,
236 "kind": kind_name(plan.kind),
237 "name": plan.name,
238 "source_path": plan.source_display,
239 "dest_path": plan.dest_display,
240 "sync": serde_json::Value::Null,
241 }));
242 } else {
243 output::print_info(&format!(
244 "would adopt {} `{}`: {} -> {}",
245 kind_name(plan.kind),
246 plan.name,
247 plan.source_display,
248 plan.dest_display
249 ));
250 }
251 Ok(0)
252}
253
254fn move_item(source: &Path, dest: &Path) -> Result<(), MarsError> {
255 if let Some(parent) = dest.parent() {
256 std::fs::create_dir_all(parent)?;
257 }
258
259 match std::fs::rename(source, dest) {
260 Ok(()) => Ok(()),
261 Err(err) if is_cross_device_rename(&err) => Err(MarsError::InvalidRequest {
262 message: format!(
263 "cannot adopt {} across filesystems in MVP; move it onto the same filesystem as the repo first",
264 source.display()
265 ),
266 }),
267 Err(err) => Err(err.into()),
268 }
269}
270
271fn kind_name(kind: ItemKind) -> &'static str {
272 match kind {
273 ItemKind::Agent => "agent",
274 ItemKind::Skill => "skill",
275 ItemKind::Hook => "hook",
276 ItemKind::McpServer => "mcp-server",
277 ItemKind::BootstrapDoc => "bootstrap-doc",
278 }
279}
280
281fn relative_display(project_root: &Path, path: &Path) -> String {
282 path.strip_prefix(project_root)
283 .unwrap_or(path)
284 .display()
285 .to_string()
286}
287
288#[cfg(unix)]
289fn is_cross_device_rename(err: &std::io::Error) -> bool {
290 err.raw_os_error() == Some(libc::EXDEV)
291}
292
293#[cfg(windows)]
294fn is_cross_device_rename(err: &std::io::Error) -> bool {
295 const ERROR_NOT_SAME_DEVICE: i32 = 17;
296 err.raw_os_error() == Some(ERROR_NOT_SAME_DEVICE)
297}
298
299#[cfg(not(any(unix, windows)))]
300fn is_cross_device_rename(_err: &std::io::Error) -> bool {
301 false
302}