Skip to main content

mars_agents/cli/
check.rs

1//! `mars check [PATH]` — validate a source package before publishing.
2//!
3//! Scans a directory as a mars source package
4//! (`agents/*.md`, `skills/*/SKILL.md`, or a flat root `SKILL.md`)
5//! and validates structure, frontmatter, and internal skill dependencies.
6//! No config or lock file needed — works on raw source directories.
7
8use std::collections::{HashMap, HashSet};
9use std::path::{Path, PathBuf};
10
11use serde::Serialize;
12
13use crate::discover;
14use crate::error::MarsError;
15use crate::frontmatter;
16
17use super::output;
18
19/// Arguments for `mars check`.
20#[derive(Debug, clap::Args)]
21pub struct CheckArgs {
22    /// Directory to validate as a source package (default: current directory).
23    pub path: Option<PathBuf>,
24}
25
26#[derive(Debug, Serialize)]
27pub(crate) struct CheckReport {
28    agents: usize,
29    skills: usize,
30    pub(crate) errors: Vec<String>,
31    warnings: Vec<String>,
32}
33
34/// Run `mars check`.
35pub fn run(args: &CheckArgs, json: bool) -> Result<i32, MarsError> {
36    let base = match &args.path {
37        Some(p) => {
38            if p.is_absolute() {
39                p.clone()
40            } else {
41                std::env::current_dir()?.join(p)
42            }
43        }
44        None => std::env::current_dir()?,
45    };
46
47    if !base.is_dir() {
48        return Err(MarsError::Config(crate::error::ConfigError::Invalid {
49            message: format!("{} is not a directory", base.display()),
50        }));
51    }
52
53    let report = check_dir(&base)?;
54
55    if json {
56        output::print_json(&report);
57    } else {
58        println!("  {} agents, {} skills", report.agents, report.skills);
59        println!(
60            "  source package validates for .mars/ canonical store and native harness targets"
61        );
62        println!();
63
64        if report.errors.is_empty() && report.warnings.is_empty() {
65            output::print_success("all checks passed");
66        } else {
67            for e in &report.errors {
68                output::print_error(e);
69            }
70            for w in &report.warnings {
71                output::print_warn(w);
72            }
73            if !report.errors.is_empty() {
74                println!();
75                println!("  {} error(s) found", report.errors.len());
76            }
77        }
78    }
79
80    if report.errors.is_empty() {
81        Ok(0)
82    } else {
83        Ok(1)
84    }
85}
86
87pub(crate) fn check_dir(base: &Path) -> Result<CheckReport, MarsError> {
88    let skills_dir = base.join("skills");
89
90    let mut errors: Vec<String> = Vec::new();
91    let mut warnings: Vec<String> = Vec::new();
92
93    let discovered = discover::discover_resolved_source(base, None)?;
94
95    // ── Validate discovered agents/skills ────────────────────────────
96    let mut agent_names: HashMap<String, PathBuf> = HashMap::new();
97    let mut agent_skill_refs: Vec<(String, Vec<String>)> = Vec::new();
98    let mut skill_names: HashMap<String, PathBuf> = HashMap::new();
99
100    for item in discovered {
101        let path = base.join(&item.source_path);
102        match item.id.kind {
103            crate::lock::ItemKind::Agent => {
104                if super::is_symlink(&path) {
105                    let name = path
106                        .file_stem()
107                        .and_then(|n| n.to_str())
108                        .unwrap_or_default();
109                    warnings.push(format!(
110                        "skipping symlinked agent `{name}` — source packages should not contain symlinks"
111                    ));
112                    continue;
113                }
114
115                let filename = path
116                    .file_stem()
117                    .and_then(|n| n.to_str())
118                    .unwrap_or_default()
119                    .to_string();
120
121                match std::fs::read_to_string(&path) {
122                    Ok(content) => match frontmatter::parse(&content) {
123                        Ok(fm) => {
124                            let name = fm
125                                .name()
126                                .map(str::to_string)
127                                .unwrap_or_else(|| filename.clone());
128
129                            let mut agent_diags = Vec::new();
130                            let _profile =
131                                crate::compiler::agents::parse_agent_profile(&fm, &mut agent_diags);
132                            for diagnostic in agent_diags {
133                                let message = format!("agent `{name}`: {}", diagnostic.message());
134                                if diagnostic.is_error() {
135                                    errors.push(message);
136                                } else {
137                                    warnings.push(message);
138                                }
139                            }
140
141                            if fm.name().is_none() {
142                                warnings.push(format!(
143                                    "agent `{filename}` has no `name` in frontmatter"
144                                ));
145                            }
146
147                            if fm.get("description").and_then(|v| v.as_str()).is_none() {
148                                warnings.push(format!("agent `{name}` has no `description`"));
149                            }
150
151                            if fm.name().is_some() && name != filename {
152                                warnings.push(format!(
153                                    "agent filename `{filename}.md` doesn't match name `{name}` in frontmatter"
154                                ));
155                            }
156
157                            if let Some(existing) = agent_names.get(&name) {
158                                errors.push(format!(
159                                    "duplicate agent name `{name}` in {} and {}",
160                                    existing.display(),
161                                    path.display()
162                                ));
163                            } else {
164                                agent_names.insert(name.clone(), path.clone());
165                            }
166
167                            let skills = fm.skills();
168                            if !skills.is_empty() {
169                                agent_skill_refs.push((name, skills));
170                            }
171                        }
172                        Err(e) => {
173                            errors.push(format!("agent `{filename}` has invalid frontmatter: {e}"));
174                        }
175                    },
176                    Err(e) => {
177                        errors.push(format!("cannot read {}: {e}", path.display()));
178                    }
179                }
180            }
181            crate::lock::ItemKind::Skill => {
182                let (dirname, skill_md, duplicate_path) = if item.source_path
183                    == std::path::Path::new(".")
184                {
185                    let dirname = item.id.name.to_string();
186                    (dirname, base.join("SKILL.md"), base.join("SKILL.md"))
187                } else {
188                    if super::is_symlink(&path) {
189                        let name = path
190                            .file_name()
191                            .and_then(|n| n.to_str())
192                            .unwrap_or_default();
193                        warnings.push(format!(
194                            "skipping symlinked skill `{name}` — source packages should not contain symlinks"
195                        ));
196                        continue;
197                    }
198                    let dirname = path
199                        .file_name()
200                        .and_then(|n| n.to_str())
201                        .unwrap_or_default()
202                        .to_string();
203                    (dirname, path.join("SKILL.md"), path.clone())
204                };
205
206                match std::fs::read_to_string(&skill_md) {
207                    Ok(content) => match frontmatter::parse(&content) {
208                        Ok(fm) => {
209                            let name = fm
210                                .name()
211                                .map(str::to_string)
212                                .unwrap_or_else(|| dirname.clone());
213
214                            if fm.name().is_none() {
215                                warnings.push(format!(
216                                    "skill `{dirname}` has no `name` in frontmatter"
217                                ));
218                            }
219
220                            if fm.get("description").and_then(|v| v.as_str()).is_none() {
221                                warnings.push(format!("skill `{name}` has no `description`"));
222                            }
223
224                            if fm.name().is_some() && name != dirname {
225                                warnings.push(format!(
226                                    "skill dirname `{dirname}` doesn't match name `{name}` in frontmatter"
227                                ));
228                            }
229
230                            if let Some(existing) = skill_names.get(&name) {
231                                errors.push(format!(
232                                    "duplicate skill name `{name}` in {} and {}",
233                                    existing.display(),
234                                    duplicate_path.display()
235                                ));
236                            } else {
237                                skill_names.insert(name, duplicate_path);
238                            }
239                        }
240                        Err(e) => {
241                            errors.push(format!("skill `{dirname}` has invalid frontmatter: {e}"));
242                        }
243                    },
244                    Err(e) => {
245                        errors.push(format!("cannot read {}: {e}", skill_md.display()));
246                    }
247                }
248            }
249            // New kinds not yet subject to source-package checks.
250            crate::lock::ItemKind::Hook
251            | crate::lock::ItemKind::McpServer
252            | crate::lock::ItemKind::BootstrapDoc => {}
253        }
254    }
255
256    // Structural validation for nested skill layout:
257    // if skills/* directories exist, each must contain SKILL.md.
258    if skills_dir.is_dir() {
259        let mut entries: Vec<_> = std::fs::read_dir(&skills_dir)?
260            .filter_map(|e| e.ok())
261            .filter(|e| e.path().is_dir())
262            .collect();
263        entries.sort_by_key(|e| e.file_name());
264        for entry in entries {
265            let path = entry.path();
266            let dirname = path
267                .file_name()
268                .and_then(|n| n.to_str())
269                .unwrap_or_default();
270            if !path.join("SKILL.md").exists() {
271                errors.push(format!("skill `{dirname}` is missing SKILL.md"));
272            }
273        }
274    }
275
276    let agent_count = agent_names.len();
277    let skill_count = skill_names.len();
278
279    // ── Empty package check ──────────────────────────────────────────
280    if agent_count == 0 && skill_count == 0 {
281        errors.push("no agents or skills found — is this a mars source package?".to_string());
282    }
283
284    // ── Skill dependency check ───────────────────────────────────────
285    let available: HashSet<&str> = skill_names.keys().map(|s| s.as_str()).collect();
286
287    match has_package_dependencies(base) {
288        Ok(true) => {
289            // Graph-backed validation: resolve deps fresh from constraints, check
290            // skill refs against local skills + all resolved dependency packages.
291            match resolve_available_skills(base) {
292                Ok(graph_skills) => {
293                    for (agent_name, skills) in &agent_skill_refs {
294                        for skill in skills {
295                            if !available.contains(skill.as_str())
296                                && !graph_skills.contains_key(skill)
297                            {
298                                errors.push(format!(
299                                    "agent `{agent_name}` references skill `{skill}` not found in local package or dependencies\n  searched: {}\n  hint: add the skill's source package as a dependency, or remove the skill reference",
300                                    format_searched_packages(&graph_skills)
301                                ));
302                            }
303                        }
304                    }
305                }
306                Err(resolve_err) => {
307                    errors.push(format!(
308                        "dependency graph resolution failed: {resolve_err}\n  hint: check network access, or use `mars version --force` to bypass the publish gate"
309                    ));
310                }
311            }
312        }
313        Ok(false) => {
314            // No [dependencies] — local-only validation, emit warnings for external refs.
315            for (agent_name, skills) in &agent_skill_refs {
316                for skill in skills {
317                    if !available.contains(skill.as_str()) {
318                        warnings.push(format!(
319                            "external dependency: `{skill}` (referenced by: {agent_name})"
320                        ));
321                    }
322                }
323            }
324        }
325        Err(config_err) => {
326            errors.push(format!(
327                "failed to load mars.toml for dependency checks: {config_err}\n  hint: fix mars.toml syntax (Windows paths in TOML must use `/` or escaped `\\\\`)"
328            ));
329        }
330    }
331
332    // ── Output ───────────────────────────────────────────────────────
333    Ok(CheckReport {
334        agents: agent_count,
335        skills: skill_count,
336        errors,
337        warnings,
338    })
339}
340
341/// Check if mars.toml has `[package]` and at least one `[dependencies]` entry.
342///
343/// Both are required to trigger graph-backed validation: `[package]` indicates
344/// this is a publishable source package, and `[dependencies]` means there are
345/// skills that could come from external packages.
346fn has_package_dependencies(base: &Path) -> Result<bool, MarsError> {
347    match crate::config::load(base) {
348        Ok(config) => Ok(config.package.is_some() && !config.dependencies.is_empty()),
349        Err(MarsError::Config(crate::error::ConfigError::NotFound { .. })) => Ok(false),
350        Err(err) => Err(err),
351    }
352}
353
354/// Resolve the dependency graph and collect available skills, respecting package filters.
355///
356/// Returns a map of `skill_name → (source_name, version_string)`.
357/// Fails closed — if resolution cannot complete, returns an error.
358///
359/// Uses only `[dependencies]` from mars.toml — excludes `[local-dependencies]` (dev-only)
360/// and ignores mars.local.toml overrides (local dev paths). This matches what consumers
361/// see when they depend on this package.
362fn resolve_available_skills(base: &Path) -> Result<HashMap<String, (String, String)>, MarsError> {
363    use crate::resolve::{ResolveOptions, resolve};
364    use crate::source::GlobalCache;
365    use crate::sync::provider::RealSourceProvider;
366
367    let config = crate::config::load(base)?;
368    // Publish gate: use only mars.toml [dependencies].
369    // Strip [local-dependencies] (dev-only, not exported to consumers) and skip
370    // mars.local.toml (local dev path overrides that don't exist on consumers).
371    let mut publish_config = config.clone();
372    publish_config.local_dependencies.clear();
373    let effective = crate::config::merge(publish_config, crate::config::LocalConfig::default())?;
374
375    let cache = GlobalCache::new()?;
376    let provider = RealSourceProvider::new(&cache, base);
377    let mut diag = crate::diagnostic::DiagnosticCollector::new();
378    let options = ResolveOptions::default(); // no lock, not frozen, not maximizing
379
380    let graph = resolve(&effective, &provider, None, &options, &mut diag)?;
381
382    let mut skills: HashMap<String, (String, String)> = HashMap::new();
383    for (source_name, node) in &graph.nodes {
384        let discovered =
385            crate::discover::discover_resolved_source(&node.rooted_ref.package_root, None)?;
386        let package_filters = graph.filters.get(source_name);
387        for item in &discovered {
388            if item.id.kind == crate::lock::ItemKind::Skill
389                && item_passes_filters(item, package_filters)
390            {
391                let version_str = node
392                    .resolved_ref
393                    .version
394                    .as_ref()
395                    .map(|v| v.to_string())
396                    .unwrap_or_else(|| "unknown".to_string());
397                skills.insert(
398                    item.id.name.to_string(),
399                    (source_name.to_string(), version_str),
400                );
401            }
402        }
403    }
404
405    Ok(skills)
406}
407
408/// Returns true if a skill item would be installed given the accumulated filter constraints.
409///
410/// Filters are accumulated with OR semantics: an item passes if ANY filter in the list
411/// would include it (multiple requests for the same package may each install different
412/// subsets, and a skill available from any of them is usable).
413///
414/// Matches real install semantics from `seed_items_for_request`: `Exclude` checks both
415/// skill name and source path so path-based excludes are honoured in the publish gate.
416fn item_passes_filters(
417    item: &crate::discover::DiscoveredItem,
418    filters: Option<&Vec<crate::config::FilterMode>>,
419) -> bool {
420    let Some(filters) = filters else {
421        return true; // no filter constraint → all items pass
422    };
423    filters.iter().any(|filter| match filter {
424        crate::config::FilterMode::All => true,
425        crate::config::FilterMode::Include { skills, .. } => skills.contains(&item.id.name),
426        crate::config::FilterMode::Exclude(excluded) => {
427            let source_path = item.source_path.to_string_lossy();
428            !excluded.iter().any(|e| {
429                *e == item.id.name || crate::target::paths_equivalent(e.as_ref(), &source_path)
430            })
431        }
432        crate::config::FilterMode::OnlySkills => true,
433        crate::config::FilterMode::OnlyAgents => false,
434    })
435}
436
437fn format_searched_packages(graph_skills: &HashMap<String, (String, String)>) -> String {
438    let mut packages: Vec<(&str, &str)> = graph_skills
439        .values()
440        .map(|(name, ver)| (name.as_str(), ver.as_str()))
441        .collect();
442    packages.sort();
443    packages.dedup();
444    if packages.is_empty() {
445        "no dependency packages resolved".to_string()
446    } else {
447        packages
448            .iter()
449            .map(|(name, ver)| format!("{name}@{ver}"))
450            .collect::<Vec<_>>()
451            .join(", ")
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use std::path::Path;
458
459    use tempfile::TempDir;
460
461    fn write_agent(path: &Path, filename: &str, skills: &[&str]) {
462        let agents = path.join("agents");
463        std::fs::create_dir_all(&agents).unwrap();
464        let skills_str = skills.join(", ");
465        std::fs::write(
466            agents.join(format!("{filename}.md")),
467            format!(
468                "---\nname: {filename}\ndescription: test agent\nskills: [{skills_str}]\n---\n# Agent"
469            ),
470        )
471        .unwrap();
472    }
473
474    fn write_agent_content(path: &Path, filename: &str, content: &str) {
475        let agents = path.join("agents");
476        std::fs::create_dir_all(&agents).unwrap();
477        std::fs::write(agents.join(format!("{filename}.md")), content).unwrap();
478    }
479
480    /// Create a minimal path-dep source package with the given skills.
481    fn write_dep_package(path: &Path, name: &str, version: &str, skills: &[&str]) {
482        std::fs::create_dir_all(path).unwrap();
483        std::fs::write(
484            path.join("mars.toml"),
485            format!("[package]\nname = \"{name}\"\nversion = \"{version}\"\n\n[dependencies]\n"),
486        )
487        .unwrap();
488        for skill_name in skills {
489            let skill_dir = path.join("skills").join(skill_name);
490            std::fs::create_dir_all(&skill_dir).unwrap();
491            std::fs::write(
492                skill_dir.join("SKILL.md"),
493                format!("---\nname: {skill_name}\ndescription: test skill\n---\n# Skill"),
494            )
495            .unwrap();
496        }
497    }
498
499    fn toml_path(path: &Path) -> String {
500        path.to_string_lossy().replace('\\', "/")
501    }
502
503    // ── Structural checks (unchanged) ─────────────────────────────────
504
505    #[cfg(unix)]
506    #[test]
507    fn check_skips_symlinked_agent() {
508        let dir = TempDir::new().unwrap();
509        let agents = dir.path().join("agents");
510        std::fs::create_dir_all(&agents).unwrap();
511
512        std::fs::write(
513            agents.join("real.md"),
514            "---\nname: real\ndescription: real agent\n---\n# Real",
515        )
516        .unwrap();
517        std::os::unix::fs::symlink(agents.join("real.md"), agents.join("linked.md")).unwrap();
518
519        let args = super::CheckArgs {
520            path: Some(dir.path().to_path_buf()),
521        };
522        let code = super::run(&args, true).unwrap();
523        assert_eq!(code, 0);
524    }
525
526    #[cfg(unix)]
527    #[test]
528    fn check_skips_symlinked_skill() {
529        let dir = TempDir::new().unwrap();
530        let skills = dir.path().join("skills");
531        let real_skill = skills.join("real-skill");
532        std::fs::create_dir_all(&real_skill).unwrap();
533        std::fs::write(
534            real_skill.join("SKILL.md"),
535            "---\nname: real-skill\ndescription: a skill\n---\n# Skill",
536        )
537        .unwrap();
538        std::os::unix::fs::symlink(&real_skill, skills.join("linked-skill")).unwrap();
539
540        let agents = dir.path().join("agents");
541        std::fs::create_dir_all(&agents).unwrap();
542        std::fs::write(
543            agents.join("coder.md"),
544            "---\nname: coder\ndescription: agent\n---\n# Coder",
545        )
546        .unwrap();
547
548        let args = super::CheckArgs {
549            path: Some(dir.path().to_path_buf()),
550        };
551        let code = super::run(&args, true).unwrap();
552        assert_eq!(code, 0);
553    }
554
555    #[test]
556    fn check_accepts_flat_skill_repo() {
557        let dir = TempDir::new().unwrap();
558        std::fs::write(
559            dir.path().join("SKILL.md"),
560            "---\nname: flat-skill\ndescription: flat layout\n---\n# Flat skill",
561        )
562        .unwrap();
563
564        let args = super::CheckArgs {
565            path: Some(dir.path().to_path_buf()),
566        };
567        let code = super::run(&args, true).unwrap();
568        assert_eq!(code, 0);
569    }
570
571    // ── P3: No [dependencies] → local-only path, external refs are warnings ──
572
573    #[test]
574    fn check_no_dependencies_warns_for_external_skill() {
575        // No mars.toml → has_package_dependencies returns false → warning path.
576        let dir = TempDir::new().unwrap();
577        write_agent(dir.path(), "coder", &["missing-skill"]);
578
579        let report = super::check_dir(dir.path()).unwrap();
580        assert!(
581            report.errors.is_empty(),
582            "expected no errors in local-only mode: {:?}",
583            report.errors
584        );
585        let has_warning = report
586            .warnings
587            .iter()
588            .any(|w| w.contains("external dependency: `missing-skill`"));
589        assert!(
590            has_warning,
591            "expected warning for missing-skill: {:?}",
592            report.warnings
593        );
594    }
595
596    #[test]
597    fn check_warns_for_truly_missing_external_skill() {
598        // No mars.toml → local-only path → skill ref that isn't local → warning.
599        let dir = TempDir::new().unwrap();
600        write_agent(dir.path(), "coder", &["missing-skill"]);
601
602        let report = super::check_dir(dir.path()).unwrap();
603        let has_missing_warning = report
604            .warnings
605            .iter()
606            .any(|w| w.contains("external dependency: `missing-skill`"));
607
608        assert!(
609            has_missing_warning,
610            "expected missing external dependency warning, got: {:?}",
611            report.warnings
612        );
613    }
614
615    #[test]
616    fn check_errors_for_malformed_agent_model_policy() {
617        let dir = TempDir::new().unwrap();
618        write_agent_content(
619            dir.path(),
620            "browser-tester",
621            "---\nname: browser-tester\ndescription: browser test\nmodel-policies:\n  - match:\n      alias: gpt55\n      model: gpt-5.5\n---\n# Browser Tester",
622        );
623
624        let report = super::check_dir(dir.path()).unwrap();
625
626        let joined = report.errors.join("\n");
627        assert!(
628            joined.contains("model-policies[1].match"),
629            "expected model-policies match error: {joined}"
630        );
631    }
632
633    // ── P1 + P4 + P9: [dependencies] present, resolution fails → error with hint ─
634
635    #[test]
636    fn check_with_unresolvable_dep_fails_closed_with_remediation_hint() {
637        // P1: mars.toml with [dependencies] triggers graph resolution.
638        // P4: resolution fails (non-existent path) → fail-closed error.
639        // P9: error message includes remediation ("mars version --force").
640        let dir = TempDir::new().unwrap();
641        write_agent(dir.path(), "coder", &["some-skill"]);
642        std::fs::write(
643            dir.path().join("mars.toml"),
644            // [package] required to trigger graph-backed validation.
645            // Absolute path that does not exist — resolution must fail.
646            "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = { path = \"/nonexistent-mars-dep-xyz-abc\" }\n",
647        )
648        .unwrap();
649
650        let report = super::check_dir(dir.path()).unwrap();
651        assert!(
652            !report.errors.is_empty(),
653            "expected errors when dep cannot be resolved"
654        );
655        let joined = report.errors.join("\n");
656        assert!(
657            joined.contains("mars version --force"),
658            "error must include remediation hint: {joined}"
659        );
660    }
661
662    // ── P2 + P8: [dependencies] resolve, skill missing from graph → error ────────
663
664    #[test]
665    fn check_missing_skill_in_resolved_graph_is_error() {
666        // P2: skill not in graph → error (not warning).
667        // P8: error message includes agent name, skill name, searched packages.
668        let dir = TempDir::new().unwrap();
669        let dep_dir = TempDir::new().unwrap();
670
671        // Path dep provides "provided-skill", NOT "missing-skill".
672        write_dep_package(dep_dir.path(), "dep-pkg", "0.1.0", &["provided-skill"]);
673
674        write_agent(dir.path(), "coder", &["missing-skill"]);
675        std::fs::write(
676            dir.path().join("mars.toml"),
677            format!(
678                "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = {{ path = \"{}\" }}\n",
679                toml_path(dep_dir.path())
680            ),
681        )
682        .unwrap();
683
684        let report = super::check_dir(dir.path()).unwrap();
685        assert!(
686            !report.errors.is_empty(),
687            "expected error for missing skill, got: {:?}",
688            report.errors
689        );
690        let joined = report.errors.join("\n");
691        // P8: error includes agent name, skill name, searched packages, and remediation.
692        assert!(
693            joined.contains("coder"),
694            "error must name the agent: {joined}"
695        );
696        assert!(
697            joined.contains("missing-skill"),
698            "error must name the missing skill: {joined}"
699        );
700        assert!(
701            joined.contains("searched:"),
702            "error must list searched packages: {joined}"
703        );
704        assert!(
705            joined.contains("hint:"),
706            "error must include remediation guidance: {joined}"
707        );
708        // Warnings must NOT contain missing-skill (it is now an error).
709        let has_warning = report.warnings.iter().any(|w| w.contains("missing-skill"));
710        assert!(
711            !has_warning,
712            "missing skill must be error, not warning: {:?}",
713            report.warnings
714        );
715    }
716
717    // ── Skill provided by path dep passes (graph-backed success) ─────────────────
718
719    #[test]
720    fn check_skill_provided_by_path_dep_passes() {
721        // When the skill is found in a resolved path dependency, no error.
722        let dir = TempDir::new().unwrap();
723        let dep_dir = TempDir::new().unwrap();
724
725        write_dep_package(dep_dir.path(), "dep-pkg", "0.1.0", &["ext-skill"]);
726        write_agent(dir.path(), "coder", &["ext-skill"]);
727        std::fs::write(
728            dir.path().join("mars.toml"),
729            format!(
730                "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = {{ path = \"{}\" }}\n",
731                toml_path(dep_dir.path())
732            ),
733        )
734        .unwrap();
735
736        let report = super::check_dir(dir.path()).unwrap();
737        assert!(
738            report.errors.is_empty(),
739            "expected no errors when skill is in dep: {:?}",
740            report.errors
741        );
742    }
743
744    // ── Fix 1: Filter bypass — excluded skill must not satisfy a ref ──────────────
745
746    #[test]
747    fn check_excluded_skill_in_dep_is_not_available() {
748        // A skill that exists in the dep package but is excluded via filter
749        // must not satisfy an agent skill reference — the filter bypass is the bug.
750        let dir = TempDir::new().unwrap();
751        let dep_dir = TempDir::new().unwrap();
752
753        // Dep provides "ext-skill" and "other-skill", but consumer excludes "ext-skill".
754        write_dep_package(
755            dep_dir.path(),
756            "dep-pkg",
757            "0.1.0",
758            &["ext-skill", "other-skill"],
759        );
760        write_agent(dir.path(), "coder", &["ext-skill"]);
761        std::fs::write(
762            dir.path().join("mars.toml"),
763            format!(
764                "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = {{ path = \"{}\", exclude = [\"ext-skill\"] }}\n",
765                toml_path(dep_dir.path())
766            ),
767        )
768        .unwrap();
769
770        let report = super::check_dir(dir.path()).unwrap();
771        assert!(
772            !report.errors.is_empty(),
773            "excluded skill must not satisfy ref — expected error, got none: {:?}",
774            report.errors
775        );
776        let joined = report.errors.join("\n");
777        assert!(
778            joined.contains("ext-skill"),
779            "error must mention the missing skill: {joined}"
780        );
781    }
782
783    #[test]
784    fn check_only_agents_filter_makes_skills_unavailable() {
785        // only_agents = true means skills are NOT installed from the dep.
786        let dir = TempDir::new().unwrap();
787        let dep_dir = TempDir::new().unwrap();
788
789        write_dep_package(dep_dir.path(), "dep-pkg", "0.1.0", &["ext-skill"]);
790        write_agent(dir.path(), "coder", &["ext-skill"]);
791        std::fs::write(
792            dir.path().join("mars.toml"),
793            format!(
794                "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = {{ path = \"{}\", only_agents = true }}\n",
795                toml_path(dep_dir.path())
796            ),
797        )
798        .unwrap();
799
800        let report = super::check_dir(dir.path()).unwrap();
801        assert!(
802            !report.errors.is_empty(),
803            "only_agents filter must make skills unavailable — expected error: {:?}",
804            report.errors
805        );
806    }
807
808    // ── Fix 2: Local config leakage — local-dependencies must not satisfy refs ────
809
810    #[test]
811    fn check_local_dependency_skill_does_not_satisfy_ref() {
812        // Skills from [local-dependencies] are dev-only and must not satisfy
813        // skill references in the publish gate check.
814        let dir = TempDir::new().unwrap();
815        let local_dep_dir = TempDir::new().unwrap();
816
817        write_dep_package(local_dep_dir.path(), "local-dep", "0.1.0", &["local-skill"]);
818        write_agent(dir.path(), "coder", &["local-skill"]);
819        // [package] + [local-dependencies] only, no [dependencies]
820        std::fs::write(
821            dir.path().join("mars.toml"),
822            format!(
823                "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\n\n[local-dependencies]\nlocal-dep = {{ path = \"{}\" }}\n",
824                toml_path(local_dep_dir.path())
825            ),
826        )
827        .unwrap();
828
829        // has_package_dependencies checks config.dependencies (not local_dependencies),
830        // so this will be false → falls through to local-only warning path.
831        // That's the correct behavior: local-only validation, external ref → warning.
832        let report = super::check_dir(dir.path()).unwrap();
833        // local-skill is not in the local package, so it should warn (not error)
834        // since we're in local-only mode (no [dependencies]).
835        let has_warning = report.warnings.iter().any(|w| w.contains("local-skill"));
836        assert!(
837            has_warning,
838            "local-skill from [local-dependencies] must not satisfy ref in publish gate — expected warning: {:?}",
839            report.warnings
840        );
841    }
842
843    #[test]
844    fn check_local_dep_skill_not_available_when_regular_dep_present() {
845        // Fix 2 code path: [dependencies] is non-empty (triggers resolve_available_skills),
846        // skill is only in [local-dependencies]. Before the fix, local-deps were included
847        // in the resolved graph and could silently satisfy refs. After the fix, they are
848        // stripped and the missing skill is correctly flagged as an error.
849        let dir = TempDir::new().unwrap();
850        let regular_dep_dir = TempDir::new().unwrap();
851        let local_dep_dir = TempDir::new().unwrap();
852
853        // Regular dep provides an unrelated skill — exists only to satisfy has_package_dependencies.
854        write_dep_package(
855            regular_dep_dir.path(),
856            "regular-dep",
857            "0.1.0",
858            &["unrelated-skill"],
859        );
860        // Local dep has the skill the agent references.
861        write_dep_package(
862            local_dep_dir.path(),
863            "local-dep",
864            "0.1.0",
865            &["local-only-skill"],
866        );
867        write_agent(dir.path(), "coder", &["local-only-skill"]);
868        std::fs::write(
869            dir.path().join("mars.toml"),
870            format!(
871                "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\nregular = {{ path = \"{}\" }}\n\n[local-dependencies]\nlocal = {{ path = \"{}\" }}\n",
872                toml_path(regular_dep_dir.path()),
873                toml_path(local_dep_dir.path())
874            ),
875        )
876        .unwrap();
877
878        let report = super::check_dir(dir.path()).unwrap();
879        assert!(
880            !report.errors.is_empty(),
881            "skill from [local-dependencies] must not satisfy ref in publish gate — expected error: {:?}",
882            report.errors
883        );
884        let joined = report.errors.join("\n");
885        assert!(
886            joined.contains("local-only-skill"),
887            "error must name the missing skill: {joined}"
888        );
889    }
890
891    #[test]
892    fn check_invalid_config_reports_error_instead_of_falling_back_to_local_only() {
893        let dir = TempDir::new().unwrap();
894        write_agent(dir.path(), "coder", &["missing-skill"]);
895        // Intentionally invalid TOML (Windows-style path escapes in basic string).
896        std::fs::write(
897            dir.path().join("mars.toml"),
898            "[package]\nname = \"test-pkg\"\nversion = \"0.1.0\"\n\n[dependencies]\ndep = { path = \"C:\\Users\\dev\\dep\" }\n",
899        )
900        .unwrap();
901
902        let report = super::check_dir(dir.path()).unwrap();
903        let joined = report.errors.join("\n");
904        assert!(
905            joined.contains("failed to load mars.toml for dependency checks"),
906            "expected config parse/load error to surface: {joined}"
907        );
908        let has_local_warning = report
909            .warnings
910            .iter()
911            .any(|w| w.contains("external dependency: `missing-skill`"));
912        assert!(
913            !has_local_warning,
914            "must not silently fall back to local-only warnings on invalid config: {:?}",
915            report.warnings
916        );
917    }
918}