mars-agents 0.2.8

Agent package manager for .agents/ directories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! `mars add <dependency>` — add or update a dependency, then sync.

use crate::config::{DependencyEntry, FilterConfig};
use crate::error::{ConfigError, MarsError};
use crate::source::parse;
use crate::sync::{
    ConfigMutation, DependencyUpsertChange, ResolutionMode, SyncOptions, SyncRequest,
};
use crate::types::{ItemName, SourceName, SourceSubpath};

use super::output;

/// Arguments for `mars add`.
#[derive(Debug, clap::Args)]
pub struct AddArgs {
    /// Source specifiers (one or more): owner/repo, owner/repo@version, URL, or local path.
    #[arg(required = true)]
    pub sources: Vec<String>,

    /// Root the fetched source at a package subdirectory.
    #[arg(long)]
    pub subpath: Option<String>,

    /// Only install specific agents from this source.
    #[arg(long, value_delimiter = ',')]
    pub agents: Vec<String>,

    /// Only install specific skills from this source.
    #[arg(long, value_delimiter = ',')]
    pub skills: Vec<String>,

    /// Exclude specific items from this source.
    #[arg(long, value_delimiter = ',')]
    pub exclude: Vec<String>,

    /// Install only skills from this source (no agents).
    #[arg(long)]
    pub only_skills: bool,

    /// Install only agents (plus their transitive skill deps) from this source.
    #[arg(long)]
    pub only_agents: bool,
}

/// Parsed dependency specifier.
#[derive(Debug)]
struct ParsedDependency {
    name: SourceName,
    entry: DependencyEntry,
}

/// Run `mars add`.
pub fn run(args: &AddArgs, ctx: &super::MarsContext, json: bool) -> Result<i32, MarsError> {
    // Validate: filters require exactly one source
    let has_filters = !args.agents.is_empty()
        || !args.skills.is_empty()
        || !args.exclude.is_empty()
        || args.only_skills
        || args.only_agents;

    if has_filters && args.sources.len() > 1 {
        return Err(MarsError::InvalidRequest {
            message: "filters may only be used when adding exactly one source".to_string(),
        });
    }
    if args.subpath.is_some() && args.sources.len() != 1 {
        return Err(MarsError::InvalidRequest {
            message: "--subpath requires exactly one source argument".to_string(),
        });
    }

    // Validate filter flag combinations early
    let filter_config = build_filter_config(args);
    crate::config::validate_filter(&filter_config, "cli")?;

    // Build mutations for all sources
    let mutations: Vec<(SourceName, DependencyEntry)> = args
        .sources
        .iter()
        .map(|source| {
            let parsed = parse_dependency_specifier(source, args.subpath.as_deref())?;
            let entry = DependencyEntry {
                url: parsed.entry.url,
                path: parsed.entry.path,
                subpath: parsed.entry.subpath,
                version: parsed.entry.version,
                filter: filter_config.clone(),
            };
            Ok((parsed.name, entry))
        })
        .collect::<Result<Vec<_>, MarsError>>()?;

    // For single source, use direct mutation path
    // For multi-source, apply mutations sequentially then run one sync
    if mutations.len() == 1 {
        let (name, entry) = mutations.into_iter().next().unwrap();

        let request = SyncRequest {
            resolution: ResolutionMode::Normal,
            mutation: Some(ConfigMutation::UpsertDependency {
                name: name.clone(),
                entry,
            }),
            options: SyncOptions {
                force: false,
                dry_run: false,
                frozen: false,
                no_refresh_models: false,
            },
        };

        let report = crate::sync::execute(ctx, &request)?;

        if !json {
            print_dependency_messages(&report.dependency_changes);
        }

        output::print_sync_report(&report, json, true);
        return if report.has_conflicts() { Ok(1) } else { Ok(0) };
    }

    // Multi-source: send one batch mutation through sync pipeline.
    let request = SyncRequest {
        resolution: ResolutionMode::Normal,
        mutation: Some(ConfigMutation::BatchUpsert(mutations)),
        options: SyncOptions {
            force: false,
            dry_run: false,
            frozen: false,
            no_refresh_models: false,
        },
    };

    let report = crate::sync::execute(ctx, &request)?;

    if !json {
        print_dependency_messages(&report.dependency_changes);
    }

    output::print_sync_report(&report, json, true);
    if report.has_conflicts() { Ok(1) } else { Ok(0) }
}

/// Build FilterConfig from CLI args.
fn build_filter_config(args: &AddArgs) -> FilterConfig {
    FilterConfig {
        agents: if args.agents.is_empty() {
            None
        } else {
            Some(
                args.agents
                    .iter()
                    .map(|v| ItemName::from(v.as_str()))
                    .collect(),
            )
        },
        skills: if args.skills.is_empty() {
            None
        } else {
            Some(
                args.skills
                    .iter()
                    .map(|v| ItemName::from(v.as_str()))
                    .collect(),
            )
        },
        exclude: if args.exclude.is_empty() {
            None
        } else {
            Some(
                args.exclude
                    .iter()
                    .map(|v| ItemName::from(v.as_str()))
                    .collect(),
            )
        },
        rename: None,
        only_skills: args.only_skills,
        only_agents: args.only_agents,
    }
}

/// Parse a dependency specifier string into a name + DependencyEntry.
///
/// Formats:
/// - `owner/repo` → GitHub shorthand (no `.` in first segment, exactly one `/`)
/// - `owner/repo@version` → GitHub shorthand with version
/// - `github.com/owner/repo` → full git URL
/// - `https://github.com/owner/repo.git` → full git URL
/// - `./path` or `../path` or `/absolute` → local path
fn parse_dependency_specifier(
    spec: &str,
    explicit_subpath: Option<&str>,
) -> Result<ParsedDependency, MarsError> {
    let parsed = parse::parse(spec).map_err(|e| {
        MarsError::Config(ConfigError::Invalid {
            message: e.to_string(),
        })
    })?;

    let explicit_subpath = explicit_subpath
        .map(|value| {
            SourceSubpath::new(value).map_err(|e| {
                MarsError::Config(ConfigError::Invalid {
                    message: e.to_string(),
                })
            })
        })
        .transpose()?;
    let subpath = merge_subpath(parsed.subpath.clone(), explicit_subpath)?;
    let name = derive_dependency_name(&parsed, subpath.as_ref())?;

    Ok(ParsedDependency {
        name: SourceName::from(name),
        entry: DependencyEntry {
            url: parsed.url,
            path: parsed.path,
            subpath,
            version: parsed.version,
            filter: FilterConfig::default(),
        },
    })
}

fn merge_subpath(
    parsed_subpath: Option<SourceSubpath>,
    explicit_subpath: Option<SourceSubpath>,
) -> Result<Option<SourceSubpath>, MarsError> {
    match (parsed_subpath, explicit_subpath) {
        (Some(parsed), Some(explicit)) if parsed != explicit => Err(MarsError::InvalidRequest {
            message: format!(
                "conflicting subpath input: source provides `{parsed}` but --subpath provides `{explicit}`"
            ),
        }),
        (Some(parsed), Some(_)) => Ok(Some(parsed)),
        (Some(parsed), None) => Ok(Some(parsed)),
        (None, Some(explicit)) => Ok(Some(explicit)),
        (None, None) => Ok(None),
    }
}

fn derive_dependency_name(
    parsed: &parse::ParsedSourceSpec,
    subpath: Option<&SourceSubpath>,
) -> Result<String, MarsError> {
    let root_name = parsed.name.split('/').next().ok_or_else(|| {
        MarsError::Config(ConfigError::Invalid {
            message: format!("cannot derive dependency name from `{}`", parsed.raw),
        })
    })?;

    Ok(match subpath {
        Some(subpath) => format!("{root_name}/{}", subpath.as_str()),
        None => root_name.to_string(),
    })
}

fn print_dependency_messages(changes: &[DependencyUpsertChange]) {
    for change in changes {
        if change.already_exists {
            output::print_warn(&format!(
                "dependency `{}` already exists — updated",
                change.name
            ));
            if let Some(old_filter) = &change.old_filter
                && old_filter != &change.new_filter
            {
                output::print_info(&format!(
                    "filters changed: {}{}",
                    format_filter(old_filter),
                    format_filter(&change.new_filter)
                ));
            }
        } else {
            output::print_info(&format!("added dependency `{}`", change.name));
        }
    }
}

fn format_filter(filter: &FilterConfig) -> String {
    if filter.only_skills {
        return "only_skills=true".to_string();
    }
    if filter.only_agents {
        return "only_agents=true".to_string();
    }

    let mut parts = Vec::new();
    if let Some(agents) = &filter.agents {
        parts.push(format!("agents=[{}]", format_item_names(agents)));
    }
    if let Some(skills) = &filter.skills {
        parts.push(format!("skills=[{}]", format_item_names(skills)));
    }
    if let Some(exclude) = &filter.exclude {
        parts.push(format!("exclude=[{}]", format_item_names(exclude)));
    }

    if parts.is_empty() {
        "all".to_string()
    } else {
        parts.join(", ")
    }
}

fn format_item_names(items: &[ItemName]) -> String {
    items
        .iter()
        .map(|item| item.to_string())
        .collect::<Vec<_>>()
        .join(",")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sync::DependencyUpsertChange;
    use std::path::Path;

    #[test]
    fn parse_github_shorthand() {
        let parsed = parse_dependency_specifier("meridian-flow/meridian-base", None).unwrap();
        assert_eq!(parsed.name, "meridian-base");
        assert_eq!(
            parsed.entry.url.as_deref(),
            Some("https://github.com/meridian-flow/meridian-base")
        );
        assert!(parsed.entry.path.is_none());
        assert!(parsed.entry.version.is_none());
    }

    #[test]
    fn parse_github_shorthand_with_version() {
        let parsed =
            parse_dependency_specifier("meridian-flow/meridian-base@v0.5.0", None).unwrap();
        assert_eq!(parsed.name, "meridian-base");
        assert_eq!(
            parsed.entry.url.as_deref(),
            Some("https://github.com/meridian-flow/meridian-base")
        );
        assert_eq!(parsed.entry.version.as_deref(), Some("v0.5.0"));
    }

    #[test]
    fn parse_full_url() {
        let parsed =
            parse_dependency_specifier("github.com/meridian-flow/meridian-dev-workflow@v2", None)
                .unwrap();
        assert_eq!(parsed.name, "meridian-dev-workflow");
        assert_eq!(
            parsed.entry.url.as_deref(),
            Some("https://github.com/meridian-flow/meridian-dev-workflow")
        );
        assert_eq!(parsed.entry.version.as_deref(), Some("v2"));
    }

    #[test]
    fn parse_https_url() {
        let parsed =
            parse_dependency_specifier("https://github.com/someone/cool-agents.git", None).unwrap();
        assert_eq!(parsed.name, "cool-agents");
        assert_eq!(
            parsed.entry.url.as_deref(),
            Some("https://github.com/someone/cool-agents")
        );
    }

    #[test]
    fn parse_ssh_url() {
        let parsed =
            parse_dependency_specifier("git@github.com:someone/cool-agents.git", None).unwrap();
        assert_eq!(parsed.name, "cool-agents");
        assert_eq!(
            parsed.entry.url.as_deref(),
            Some("git@github.com:someone/cool-agents.git")
        );
        assert!(parsed.entry.version.is_none());
    }

    #[test]
    fn parse_ssh_url_keeps_at_suffix_in_path() {
        let parsed =
            parse_dependency_specifier("git@github.com:someone/cool-agents.git@v2", None).unwrap();
        assert_eq!(parsed.name, "cool-agents");
        assert_eq!(
            parsed.entry.url.as_deref(),
            Some("git@github.com:someone/cool-agents.git")
        );
        assert_eq!(parsed.entry.version.as_deref(), Some("v2"));
    }

    #[test]
    fn parse_local_path_relative() {
        let parsed = parse_dependency_specifier("./my-agents", None).unwrap();
        assert_eq!(parsed.name, "my-agents");
        assert!(parsed.entry.url.is_none());
        assert_eq!(parsed.entry.path.as_deref(), Some(Path::new("./my-agents")));
    }

    #[test]
    fn parse_local_path_parent() {
        let parsed = parse_dependency_specifier("../meridian-dev-workflow", None).unwrap();
        assert_eq!(parsed.name, "meridian-dev-workflow");
        assert!(parsed.entry.url.is_none());
        assert_eq!(
            parsed.entry.path.as_deref(),
            Some(Path::new("../meridian-dev-workflow"))
        );
    }

    #[test]
    fn parse_local_path_absolute() {
        let parsed = parse_dependency_specifier("/home/dev/agents", None).unwrap();
        assert_eq!(parsed.name, "agents");
        assert!(parsed.entry.url.is_none());
        assert_eq!(
            parsed.entry.path.as_deref(),
            Some(Path::new("/home/dev/agents"))
        );
    }

    #[test]
    fn parse_source_embedded_subpath() {
        let parsed = parse_dependency_specifier("owner/repo/plugins/foo", None).unwrap();
        assert_eq!(parsed.name, "repo/plugins/foo");
        assert_eq!(
            parsed.entry.subpath.as_ref().map(SourceSubpath::as_str),
            Some("plugins/foo")
        );
    }

    #[test]
    fn parse_explicit_subpath_merges_when_source_has_none() {
        let parsed =
            parse_dependency_specifier("gitlab:group/subgroup/repo", Some("plugins/foo")).unwrap();
        assert_eq!(parsed.name, "repo/plugins/foo");
        assert_eq!(
            parsed.entry.subpath.as_ref().map(SourceSubpath::as_str),
            Some("plugins/foo")
        );
    }

    #[test]
    fn conflicting_subpath_is_rejected() {
        let err =
            parse_dependency_specifier("owner/repo/plugins/foo", Some("plugins/bar")).unwrap_err();
        assert!(matches!(err, MarsError::InvalidRequest { .. }));
    }

    #[test]
    fn format_filter_all() {
        assert_eq!(format_filter(&FilterConfig::default()), "all");
    }

    #[test]
    fn format_filter_only_modes() {
        assert_eq!(
            format_filter(&FilterConfig {
                only_skills: true,
                ..FilterConfig::default()
            }),
            "only_skills=true"
        );
        assert_eq!(
            format_filter(&FilterConfig {
                only_agents: true,
                ..FilterConfig::default()
            }),
            "only_agents=true"
        );
    }

    #[test]
    fn format_filter_lists() {
        assert_eq!(
            format_filter(&FilterConfig {
                agents: Some(vec!["reviewer".into(), "planner".into()]),
                ..FilterConfig::default()
            }),
            "agents=[reviewer,planner]"
        );
        assert_eq!(
            format_filter(&FilterConfig {
                exclude: Some(vec!["legacy".into()]),
                ..FilterConfig::default()
            }),
            "exclude=[legacy]"
        );
    }

    #[test]
    fn detects_filter_change_for_message() {
        let old_filter = FilterConfig {
            agents: Some(vec!["reviewer".into()]),
            ..FilterConfig::default()
        };
        let change = DependencyUpsertChange {
            name: "ops".into(),
            already_exists: true,
            old_version: Some("v0.1.0".into()),
            new_version: Some("v0.1.0".into()),
            old_filter: Some(old_filter.clone()),
            new_filter: FilterConfig {
                only_skills: true,
                ..FilterConfig::default()
            },
        };
        assert_ne!(change.old_filter.as_ref(), Some(&change.new_filter));
        assert_eq!(format_filter(&old_filter), "agents=[reviewer]");
        assert_eq!(format_filter(&change.new_filter), "only_skills=true");
    }
}