saferskills 0.2.0

Every AI capability, independently scanned — install Skills & MCP servers with a verified SaferSkills trust score.
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! The eight per-agent config writers.
//!
//! Each agent module documents its config-key + URL-field landmines (the
//! load-bearing per-agent differences) and constructs a writer
//! over the shared engine in [`super::writer`]. Seven agents map-merge JSON via a
//! [`JsonMcpWriter`] parameterised by a [`KeyShape`]; Codex map-merges TOML via
//! [`CodexWriter`]. Pinned known-good schemas + the live-verification checklist
//! for the volatile writers live in `SCHEMAS.md`.

pub mod claude_code;
pub mod cline;
pub mod codex;
pub mod copilot;
pub mod cursor;
pub mod gemini;
pub mod openclaw;
pub mod render;
pub mod windsurf;

use std::path::{Path, PathBuf};

use serde_json::Value;

use self::render::{render_skill, SkillRender};
use super::writer::{
    install_plugin, install_rules_file, kind_supported, merge_json_hook, merge_json_mcp,
    merge_marker_block, merge_toml_mcp, openclaw_key, reject_project_if_unsupported,
    revert_changes, verify_hook, verify_json_mcp, verify_plugin, verify_toml_mcp,
    write_file_change, Confidence, ConfigWriter, ResolvedItem, VerifyStatus,
};
use super::{AgentId, DetectedAgent, Scope};
use crate::core::error::{SsError, ERR_WRITER_UNSUPPORTED};
use crate::core::registry::InstallChange;

/// Resolve the writer for an agent id (used by the install lifecycle).
pub fn writer_for(id: AgentId) -> Box<dyn ConfigWriter> {
    match id {
        AgentId::ClaudeCode => claude_code::writer(),
        AgentId::Cursor => cursor::writer(),
        AgentId::Codex => codex::writer(),
        AgentId::Copilot => copilot::writer(),
        AgentId::Windsurf => windsurf::writer(),
        AgentId::Cline => cline::writer(),
        AgentId::Gemini => gemini::writer(),
        AgentId::Openclaw => openclaw::writer(),
    }
}

/// How an agent's MCP container key is resolved.
#[derive(Debug, Clone, Copy)]
pub enum KeyShape {
    /// A fixed key path, e.g. `["mcpServers"]`.
    Fixed(&'static [&'static str]),
    /// OpenClaw — probe the existing file for `mcpServers` vs nested `mcp.servers`.
    Openclaw,
    /// Copilot — `servers` on the VS Code surface (`.vscode/mcp.json`),
    /// `mcpServers` on the CLI surface (`~/.copilot/mcp-config.json`).
    CopilotSurface,
}

impl KeyShape {
    fn resolve(self, path: &Path) -> Vec<&'static str> {
        match self {
            KeyShape::Fixed(p) => p.to_vec(),
            KeyShape::Openclaw => openclaw_key(path),
            KeyShape::CopilotSurface => {
                let is_vscode = path.components().any(|c| c.as_os_str() == ".vscode");
                if is_vscode {
                    vec!["servers"]
                } else {
                    vec!["mcpServers"]
                }
            }
        }
    }
}

/// The generic JSON map-merge writer shared by every agent but Codex.
pub struct JsonMcpWriter {
    pub id: AgentId,
    pub confidence: Confidence,
    pub key: KeyShape,
    /// The URL field name for a remote/URL-transport MCP entry (landmine):
    /// `serverUrl` (Windsurf), `httpUrl`/`url` (Gemini), `url` (everyone else).
    pub url_field: &'static str,
    pub supports_project: bool,
    /// The per-agent rules-file extension (`.mdc` Cursor, `.md` Windsurf/Cline,
    /// `.instructions.md` Copilot). Empty for agents with no rules surface.
    pub rules_ext: &'static str,
}

/// Rename a generic `"url"` field to the agent's URL-field name (landmine). A
/// command-based entry (no `"url"`) passes through unchanged.
fn remap_url_field(entry: &Value, url_field: &str) -> Value {
    if url_field == "url" {
        return entry.clone();
    }
    if let Value::Object(map) = entry {
        if map.contains_key("url") && !map.contains_key(url_field) {
            let mut m = map.clone();
            if let Some(u) = m.remove("url") {
                m.insert(url_field.to_string(), u);
            }
            return Value::Object(m);
        }
    }
    entry.clone()
}

fn no_entry_err(id: AgentId) -> SsError {
    SsError::new(
        ERR_WRITER_UNSUPPORTED,
        format!("No MCP launch spec resolved for {}.", id.display_name()),
    )
}

fn no_skill_dir_err(id: AgentId) -> SsError {
    SsError::new(
        ERR_WRITER_UNSUPPORTED,
        format!(
            "{} has no skills directory for a skill install.",
            id.display_name()
        ),
    )
    .with_suggestion("This capability can't be auto-installed for this agent; copy it in manually.")
}

fn no_rules_dir_err(id: AgentId) -> SsError {
    SsError::new(
        ERR_WRITER_UNSUPPORTED,
        format!(
            "{} has no rules directory for a rules install.",
            id.display_name()
        ),
    )
    .with_suggestion("This capability can't be auto-installed for this agent; copy it in manually.")
}

fn no_hooks_err(id: AgentId) -> SsError {
    SsError::new(
        ERR_WRITER_UNSUPPORTED,
        format!(
            "{} has no settings file for a hook install.",
            id.display_name()
        ),
    )
}

fn no_plugin_dir_err(id: AgentId) -> SsError {
    SsError::new(
        ERR_WRITER_UNSUPPORTED,
        format!(
            "{} has no plugins directory for a plugin install.",
            id.display_name()
        ),
    )
}

/// The rules file name an agent writes for capability `name` (`<name><ext>`).
fn rules_file_name(name: &str, ext: &str) -> String {
    let stem: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
                c
            } else {
                '-'
            }
        })
        .collect();
    let stem = stem.trim_matches('-');
    format!("{}{ext}", if stem.is_empty() { "rules" } else { stem })
}

/// The hook event names carried on a resolved item's `hook_entry` block (its keys).
fn hook_event_names(item: &ResolvedItem) -> Vec<String> {
    item.hook_entry
        .as_ref()
        .and_then(|v| v.as_object())
        .map(|o| o.keys().cloned().collect())
        .unwrap_or_default()
}

/// Agents whose skill form is a marker block merged into a shared `AGENTS.md` /
/// `GEMINI.md` (no skills dir, no rules dir of their own for a skill) — Codex,
/// Copilot, Gemini. Used by both `render_skill` dispatch and `kind_supported`,
/// and by `uninstall::agent_dirs` to scope the shared-host change to its owners.
pub(crate) fn is_agents_md_agent(id: AgentId) -> bool {
    matches!(id, AgentId::Codex | AgentId::Copilot | AgentId::Gemini)
}

/// Reject a capability `name` that is not a safe single path segment before it is
/// joined into an install path. `name` is server-provided (`display_name` from the
/// public catalog), so a crafted value like `../../.ssh/authorized_keys` must never
/// escape the agent's skills/rules dir (path-traversal guard — the renderer writes
/// to the user's filesystem). Allowed: 1–64 chars of `[A-Za-z0-9_-]` (a superset of
/// the Agent Skills `name` grammar); everything else — separators, `.`/`..`, a
/// leading dot, spaces, control bytes — is rejected.
fn validate_skill_name(name: &str) -> Result<(), SsError> {
    let safe = !name.is_empty()
        && name.len() <= 64
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
    if safe {
        Ok(())
    } else {
        Err(SsError::new(
            ERR_WRITER_UNSUPPORTED,
            format!(
                "Refusing to install: unsafe capability name {name:?} \
                 (skills must be 1–64 chars of letters, digits, '-' or '_')."
            ),
        ))
    }
}

/// The standalone-file destination for a `SkillRender::File` form (plan 02), keyed
/// by the capability `name` (the renderer is GENERAL — D1 — never a hardcoded
/// "saferskills"). The `name` is path-validated first (traversal guard):
/// - Claude Code / OpenClaw → `<skill_dir>/<name>/SKILL.md` (verbatim).
/// - Cursor → `<rules_dir>/<name>.mdc` (Agent-Requested `.mdc`).
/// - Cline / Windsurf → `<rules_dir>/<name>.md` (always-on rules).
fn skill_target_path(id: AgentId, agent: &DetectedAgent, name: &str) -> Result<PathBuf, SsError> {
    validate_skill_name(name)?;
    match id {
        AgentId::ClaudeCode | AgentId::Openclaw => agent
            .skill_dir
            .as_ref()
            .map(|d| d.join(name).join("SKILL.md"))
            .ok_or_else(|| no_skill_dir_err(id)),
        AgentId::Cursor => agent
            .rules_dir
            .as_ref()
            .map(|d| d.join(format!("{name}.mdc")))
            .ok_or_else(|| no_rules_dir_err(id)),
        AgentId::Cline | AgentId::Windsurf => agent
            .rules_dir
            .as_ref()
            .map(|d| d.join(format!("{name}.md")))
            .ok_or_else(|| no_rules_dir_err(id)),
        // Codex/Copilot/Gemini render a Block, never a File — unreachable in the
        // dispatch, but keep the match total with a clear error.
        AgentId::Codex | AgentId::Copilot | AgentId::Gemini => Err(no_skill_dir_err(id)),
    }
}

/// The shared host file a `SkillRender::Block` merges into (plan 02, Module D).
/// `GEMINI.md`/`AGENTS.md` at the project root (the file Codex + Copilot both
/// read — shared, idempotent) or in the agent's home dir for a global install.
pub(crate) fn agents_md_path(id: AgentId, agent: &DetectedAgent) -> Result<PathBuf, SsError> {
    let file = if id == AgentId::Gemini {
        "GEMINI.md"
    } else {
        "AGENTS.md"
    };
    match agent.scope {
        Scope::Project => Ok(std::env::current_dir()
            .map_err(|e| {
                SsError::new(
                    ERR_WRITER_UNSUPPORTED,
                    format!("Cannot resolve the project directory: {e}"),
                )
            })?
            .join(file)),
        // Global: the agent's home (skill_dir parent: ~/.codex, ~/.gemini, ~/.copilot).
        Scope::Global => agent
            .skill_dir
            .as_ref()
            .and_then(|d| d.parent())
            .map(|p| p.join(file))
            .ok_or_else(|| no_skill_dir_err(id)),
    }
}

/// Verify a rendered skill install (plan 02) — the standalone `<skill_dir>/<name>`
/// /`<rules_dir>/<name>.<ext>` file exists, or the shared `AGENTS.md` / `GEMINI.md`
/// carries our marker block. Keyed by the capability `name` so it checks the same
/// path `install_skill_rendered` wrote (the doctor/verify `ResolvedItem` carries
/// `name`, derived from the slug — `skill_md` is not needed here).
fn verify_skill_rendered(id: AgentId, agent: &DetectedAgent, name: &str) -> VerifyStatus {
    if is_agents_md_agent(id) {
        let Ok(host) = agents_md_path(id, agent) else {
            return VerifyStatus::Missing;
        };
        // Require a COMPLETE block — a lone orphan start is NOT a valid install.
        match std::fs::read_to_string(&host) {
            Ok(s) if super::writer::has_complete_marker_block(&s) => VerifyStatus::Ok,
            _ => VerifyStatus::Missing,
        }
    } else {
        match skill_target_path(id, agent, name) {
            Ok(dest) if dest.exists() => VerifyStatus::Ok,
            _ => VerifyStatus::Missing,
        }
    }
}

/// Dispatch a resolved skill to its native form for `id`/`agent` and write it,
/// returning the recorded change(s). Shared by both writers' `"skill"` arm.
fn install_skill_rendered(
    id: AgentId,
    item: &ResolvedItem,
    agent: &DetectedAgent,
    dry_run: bool,
) -> Result<Vec<InstallChange>, SsError> {
    let skill_md = item.skill_md.as_ref().ok_or_else(|| no_entry_err(id))?;
    match render_skill(skill_md, id)? {
        SkillRender::File { content } => {
            let dest = skill_target_path(id, agent, &item.name)?;
            Ok(vec![write_file_change(&dest, content.as_bytes(), dry_run)?])
        }
        SkillRender::Block { block } => {
            let host = agents_md_path(id, agent)?;
            Ok(vec![merge_marker_block(&host, &block, dry_run)?])
        }
    }
}

impl ConfigWriter for JsonMcpWriter {
    fn id(&self) -> AgentId {
        self.id
    }
    fn confidence(&self) -> Confidence {
        self.confidence
    }
    fn supports_kind(&self, kind: &str, agent: &DetectedAgent) -> bool {
        kind_supported(kind, agent)
    }

    fn install(
        &self,
        item: &ResolvedItem,
        agent: &DetectedAgent,
        dry_run: bool,
    ) -> Result<Vec<InstallChange>, SsError> {
        reject_project_if_unsupported(self.supports_project, agent)?;
        match item.kind.as_str() {
            "mcp_server" => {
                let entry = item
                    .mcp_entry
                    .as_ref()
                    .ok_or_else(|| no_entry_err(self.id))?;
                let entry = remap_url_field(entry, self.url_field);
                let path = &agent.mcp_config_path;
                let key = self.key.resolve(path);
                let change = merge_json_mcp(path, &key, &item.name, &entry, dry_run)?;
                Ok(vec![change])
            }
            "skill" => install_skill_rendered(self.id, item, agent, dry_run),
            "rules" => {
                let rules_dir = agent
                    .rules_dir
                    .as_ref()
                    .ok_or_else(|| no_rules_dir_err(self.id))?;
                let body = item
                    .rules_body
                    .as_ref()
                    .ok_or_else(|| no_entry_err(self.id))?;
                let file = rules_file_name(&item.name, self.rules_ext);
                Ok(vec![install_rules_file(rules_dir, &file, body, dry_run)?])
            }
            "hook" => {
                let settings = agent
                    .hooks_path
                    .as_ref()
                    .ok_or_else(|| no_hooks_err(self.id))?;
                let entry = item
                    .hook_entry
                    .as_ref()
                    .ok_or_else(|| no_entry_err(self.id))?;
                merge_json_hook(settings, entry, dry_run)
            }
            "plugin" => {
                let plugins_root = agent
                    .plugin_dir
                    .as_ref()
                    .ok_or_else(|| no_plugin_dir_err(self.id))?;
                let zip = item
                    .plugin_zip
                    .as_ref()
                    .ok_or_else(|| no_entry_err(self.id))?;
                let mp = item.plugin_marketplace.as_deref().unwrap_or("saferskills");
                let version = item.plugin_version.as_deref().unwrap_or("0.0.0");
                let component = item.component_path.as_deref().unwrap_or("");
                install_plugin(
                    plugins_root,
                    mp,
                    &item.name,
                    version,
                    component,
                    zip,
                    dry_run,
                )
            }
            other => Err(SsError::new(
                ERR_WRITER_UNSUPPORTED,
                format!(
                    "{} cannot install a `{other}` capability.",
                    self.id.display_name()
                ),
            )),
        }
    }

    fn uninstall(&self, changes: &[InstallChange]) -> Result<(), SsError> {
        revert_changes(changes)
    }

    fn verify(&self, item: &ResolvedItem, agent: &DetectedAgent) -> VerifyStatus {
        match item.kind.as_str() {
            "mcp_server" => {
                let key = self.key.resolve(&agent.mcp_config_path);
                verify_json_mcp(&agent.mcp_config_path, &key, &item.name)
            }
            "skill" => verify_skill_rendered(self.id, agent, &item.name),
            "rules" => match agent.rules_dir.as_ref() {
                Some(dir)
                    if dir
                        .join(rules_file_name(&item.name, self.rules_ext))
                        .exists() =>
                {
                    VerifyStatus::Ok
                }
                _ => VerifyStatus::Missing,
            },
            "hook" => match agent.hooks_path.as_ref() {
                Some(p) => verify_hook(p, &hook_event_names(item)),
                None => VerifyStatus::Missing,
            },
            "plugin" => match agent.plugin_dir.as_ref() {
                Some(root) => verify_plugin(
                    root,
                    item.plugin_marketplace.as_deref().unwrap_or("saferskills"),
                    &item.name,
                    item.plugin_version.as_deref().unwrap_or("0.0.0"),
                ),
                None => VerifyStatus::Missing,
            },
            _ => VerifyStatus::Missing,
        }
    }
}

/// Codex map-merges TOML (`[mcp_servers.<name>]`) — its own writer.
pub struct CodexWriter {
    pub confidence: Confidence,
}

impl ConfigWriter for CodexWriter {
    fn id(&self) -> AgentId {
        AgentId::Codex
    }
    fn confidence(&self) -> Confidence {
        self.confidence
    }
    fn supports_kind(&self, kind: &str, agent: &DetectedAgent) -> bool {
        kind_supported(kind, agent)
    }

    fn install(
        &self,
        item: &ResolvedItem,
        agent: &DetectedAgent,
        dry_run: bool,
    ) -> Result<Vec<InstallChange>, SsError> {
        match item.kind.as_str() {
            "mcp_server" => {
                let entry = item
                    .mcp_entry
                    .as_ref()
                    .ok_or_else(|| no_entry_err(AgentId::Codex))?;
                Ok(vec![merge_toml_mcp(
                    &agent.mcp_config_path,
                    &item.name,
                    entry,
                    dry_run,
                )?])
            }
            "skill" => install_skill_rendered(AgentId::Codex, item, agent, dry_run),
            other => Err(SsError::new(
                ERR_WRITER_UNSUPPORTED,
                format!("Codex cannot install a `{other}` capability."),
            )),
        }
    }

    fn uninstall(&self, changes: &[InstallChange]) -> Result<(), SsError> {
        revert_changes(changes)
    }

    fn verify(&self, item: &ResolvedItem, agent: &DetectedAgent) -> VerifyStatus {
        match item.kind.as_str() {
            "mcp_server" => verify_toml_mcp(&agent.mcp_config_path, &item.name),
            "skill" => verify_skill_rendered(AgentId::Codex, agent, &item.name),
            _ => VerifyStatus::Missing,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn writer_for_every_agent() {
        for id in super::super::ALL_AGENTS {
            let w = writer_for(id);
            assert_eq!(w.id(), id);
        }
    }

    #[test]
    fn validate_skill_name_blocks_path_traversal() {
        // Spec-legal shapes are accepted.
        for ok in ["demo", "saferskills", "my-skill_1", "A1"] {
            assert!(validate_skill_name(ok).is_ok(), "{ok:?} should be allowed");
        }
        // A server-provided name must never escape the target dir or be a
        // non-flat segment: separators, `.`/`..`, leading dot, NUL, spaces.
        for bad in [
            "", "..", ".", ".hidden", "a/b", "../evil", "..\\evil", "a\0b", "a b", "foo.bar",
        ] {
            assert!(
                validate_skill_name(bad).is_err(),
                "{bad:?} must be rejected"
            );
        }
        assert!(validate_skill_name(&"x".repeat(64)).is_ok());
        assert!(validate_skill_name(&"x".repeat(65)).is_err());
    }

    #[test]
    fn copilot_surface_picks_servers_for_vscode() {
        assert_eq!(
            KeyShape::CopilotSurface.resolve(Path::new("/repo/.vscode/mcp.json")),
            vec!["servers"]
        );
        assert_eq!(
            KeyShape::CopilotSurface.resolve(Path::new("/home/u/.copilot/mcp-config.json")),
            vec!["mcpServers"]
        );
    }

    #[test]
    fn url_field_remap_renames_only_url_entries() {
        let url_entry = serde_json::json!({"url": "https://x"});
        let out = remap_url_field(&url_entry, "serverUrl");
        assert!(out.get("serverUrl").is_some());
        assert!(out.get("url").is_none());
        // command entry untouched
        let cmd = serde_json::json!({"command": "npx"});
        assert_eq!(remap_url_field(&cmd, "serverUrl"), cmd);
    }
}