mars-agents 0.12.0

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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/// Per-target compilation adapters.
///
/// Each native target root (`.claude`, `.codex`, `.opencode`, `.pi`, `.cursor`)
/// has an adapter that knows how to lower agents, format config entries, translate
/// hooks, and resolve model aliases for that target.
///
/// The deprecated `.agents` adapter remains available only for explicit legacy
/// link targets; `.mars/` is the canonical compiled store.
///
/// The adapter boundary isolates all per-target branching here, keeping shared
/// compiler code free of `if target == ...` chains.
pub mod agents;
pub mod claude;
pub mod codex;
pub mod cursor;
pub mod opencode;
pub mod pi;

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

use crate::error::MarsError;
use crate::lock::ItemKind;
#[doc(hidden)]
pub use crate::surface_ownership::retention::ConfigWrite;
use crate::surface_ownership::retention::{RemovalOperation, RemovalReport, Surface};
use crate::types::DestPath;
use indexmap::IndexMap;

const WINDOWS_INVALID_CHARS: &[char] = &[':', '*', '?', '<', '>', '|', '"', '/', '\\'];

/// A config entry to be written to a target's config file.
///
/// Adapters consume these entries to write or update target-specific config
/// files (MCP JSON, hooks in settings.json, etc.).
#[derive(Debug, Clone)]
pub enum ConfigEntry {
    /// An MCP server entry to register in the target's MCP config file.
    McpServer(McpServerEntry),
    /// A hook binding to register in the target's hook config.
    Hook(HookEntry),
}

impl ConfigEntry {
    /// Stable identity key for this entry (used by stale-cleanup logic).
    pub(crate) fn surface(&self) -> Surface {
        match self {
            Self::McpServer(_) => Surface::Mcp,
            Self::Hook(_) => Surface::Hook,
        }
    }

    pub fn key(&self) -> String {
        match self {
            ConfigEntry::McpServer(e) => format!("mcp:{}", e.name),
            ConfigEntry::Hook(e) => format!("hook:{}:{}", e.native_event, e.name),
        }
    }
}

/// An MCP server entry ready to be written into a target config file.
///
/// Env values are variable names (symbolic). Adapters translate them to the
/// target's interpolation syntax (e.g. `${VAR}` for Claude, plain name for Codex).
#[derive(Debug, Clone)]
pub struct McpServerEntry {
    /// Server name as it appears in the target config.
    pub name: String,
    /// Launch command.
    pub command: String,
    /// Launch arguments.
    pub args: Vec<String>,
    /// Env vars: config key → environment variable name (symbolic, never resolved).
    pub env: IndexMap<String, String>,
}

/// A native fragment contribution ready to be merged into a target config.
#[derive(Debug, Clone)]
pub struct HookEntry {
    /// Hook name, retained as ownership provenance.
    pub name: String,
    /// Native event name for this target.
    pub native_event: String,
    /// Opaque native entries, in author-declared order.
    pub entries: Vec<serde_json::Value>,
}

/// How a target consumes hook fragments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookFragmentMode {
    MergeJson,
    File,
}

/// Per-target compilation adapter.
///
/// Implementations encapsulate all per-target knowledge:
/// - Which item kinds this target accepts
/// - Default destination path layout
/// - Config-entry format (future: MCP, hooks, model aliases)
///
/// The trait is split into file-output surfaces and config-entry surfaces so
/// parallel pipeline lanes can own disjoint write responsibilities without
/// interfering with each other.
///
/// # Object safety
/// All methods take `&self` and return concrete types to ensure the trait can
/// be used as `dyn TargetAdapter`.
pub trait TargetAdapter: std::fmt::Debug + Send + Sync {
    /// Target root name (e.g., `.claude`, `.codex`).
    fn name(&self) -> &str;

    /// Documented native command-hook events, or `None` when this target has
    /// no declarative command-hook mechanism.
    fn known_hook_events(&self) -> Option<&'static [&'static str]> {
        None
    }

    /// Native fragment placement mechanism declared by this adapter.
    fn hook_fragment_mode(&self) -> Option<HookFragmentMode> {
        None
    }

    /// Relative destination for an opaque file-mode fragment.
    fn hook_file_dest_path(&self, _name: &str) -> Option<PathBuf> {
        None
    }

    /// Skill variant harness key used when projecting skills to this target.
    ///
    /// Native harness targets return the `variants/<key>/` directory name they
    /// consume. Full-fidelity targets that should not select skill variants
    /// return `None`.
    fn skill_variant_key(&self) -> Option<&str>;

    // -----------------------------------------------------------------------
    // Path resolution
    // -----------------------------------------------------------------------

    /// Default destination path for an item of the given kind and name.
    ///
    /// Returns `None` if this target does not accept the item kind. The
    /// compiler MUST skip items for which this returns `None`.
    fn default_dest_path(&self, kind: ItemKind, name: &str) -> Option<DestPath>;

    // -----------------------------------------------------------------------
    // Config-file writing
    // -----------------------------------------------------------------------

    /// Write config entries (MCP servers, hooks) to this target's config file.
    ///
    /// Returns the paths of files written, for lock tracking.
    /// Default: no-op — targets that don't use a config file leave this as-is.
    fn write_config_entries(
        &self,
        write: ConfigWrite<'_>,
        project_root: &Path,
    ) -> Result<Vec<PathBuf>, MarsError> {
        let (_target_dir, _entries) = write.into_parts(project_root);
        Ok(Vec::new())
    }

    /// Config files mutated by MCP entries.
    fn mcp_config_file_names(&self) -> &'static [&'static str] {
        &[]
    }

    /// Config files mutated by merge-mode hook entries.
    fn hook_config_file_names(&self) -> &'static [&'static str] {
        &[]
    }

    /// One-release legacy hook files touched only when old lock records lack
    /// structural emission data.
    fn legacy_hook_config_file_names(&self) -> &'static [&'static str] {
        &[]
    }

    /// Emit target-specific pre-write diagnostics (e.g., lossiness warnings).
    ///
    /// Called unconditionally before `write_config_entries`, even on dry runs.
    /// Default: no-op — most targets have no pre-write diagnostics.
    fn emit_pre_write_diagnostics(
        &self,
        _entries: &[ConfigEntry],
        _diag: &mut crate::diagnostic::DiagnosticCollector,
    ) {
    }

    /// Remove hook entries recorded in the previous lock by structural equality.
    fn remove_owned_hook_entries(
        &self,
        operation: RemovalOperation<'_>,
        project_root: &Path,
        _diag: &mut crate::diagnostic::DiagnosticCollector,
    ) -> RemovalReport {
        let (_, _) = operation.into_parts(project_root);
        RemovalReport::confirmed()
    }

    /// Remove stale config entries from this target's config file.
    ///
    /// `entry_keys` are the `ConfigEntry::key` values to remove.
    /// Default: no-op.
    fn remove_config_entries(
        &self,
        operation: RemovalOperation<'_>,
        project_root: &Path,
    ) -> RemovalReport {
        let (_, _) = operation.into_parts(project_root);
        RemovalReport::confirmed()
    }
}

pub(crate) fn parse_json_file(path: &Path) -> Result<serde_json::Value, MarsError> {
    let raw = std::fs::read_to_string(path)?;
    serde_json::from_str(&raw).map_err(|error| {
        MarsError::Config(crate::error::ConfigError::Invalid {
            message: format!("{} is not valid JSON: {error}", path.display()),
        })
    })
}

pub(crate) fn validate_json_config_file(path: &Path) -> Result<(), MarsError> {
    if !path.is_file() {
        return Ok(());
    }
    let root = parse_json_file(path)?;
    let object = root.as_object().ok_or_else(|| {
        MarsError::Config(crate::error::ConfigError::Invalid {
            message: format!("{} is not a JSON object", path.display()),
        })
    })?;
    if object
        .get("mcpServers")
        .is_some_and(|value| !value.is_object())
    {
        return Err(MarsError::Config(crate::error::ConfigError::Invalid {
            message: format!("{}: mcpServers is not an object", path.display()),
        }));
    }
    if let Some(hooks) = object.get("hooks") {
        let hooks = hooks.as_object().ok_or_else(|| {
            MarsError::Config(crate::error::ConfigError::Invalid {
                message: format!("{}: hooks is not an object", path.display()),
            })
        })?;
        if let Some((event, _)) = hooks.iter().find(|(_, value)| !value.is_array()) {
            return Err(MarsError::Config(crate::error::ConfigError::Invalid {
                message: format!("{}: hooks.{event} is not an array", path.display()),
            }));
        }
    }
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct JsonEventArrayUpdate {
    pub changed: bool,
    pub missing: usize,
}

pub(crate) fn append_json_event_entries(
    hooks: &mut serde_json::Map<String, serde_json::Value>,
    event: &str,
    entries: &[serde_json::Value],
    path: &Path,
) -> Result<JsonEventArrayUpdate, MarsError> {
    if entries.is_empty() {
        return Ok(JsonEventArrayUpdate {
            changed: false,
            missing: 0,
        });
    }
    let event_entries = hooks
        .entry(event.to_string())
        .or_insert_with(|| serde_json::json!([]))
        .as_array_mut()
        .ok_or_else(|| {
            MarsError::Config(crate::error::ConfigError::Invalid {
                message: format!("{}: hooks.{event} is not an array", path.display()),
            })
        })?;
    event_entries.extend(entries.iter().cloned());
    Ok(JsonEventArrayUpdate {
        changed: true,
        missing: 0,
    })
}

pub(crate) fn remove_json_event_entries(
    hooks: &mut serde_json::Map<String, serde_json::Value>,
    event: &str,
    expected: &[serde_json::Value],
) -> JsonEventArrayUpdate {
    let Some(current) = hooks
        .get_mut(event)
        .and_then(serde_json::Value::as_array_mut)
    else {
        return JsonEventArrayUpdate {
            changed: false,
            missing: expected.len(),
        };
    };
    let mut removed = 0;
    for entry in expected {
        if let Some(index) = current.iter().position(|candidate| candidate == entry) {
            current.remove(index);
            removed += 1;
        }
    }
    if removed > 0 && current.is_empty() {
        hooks.remove(event);
    }
    JsonEventArrayUpdate {
        changed: removed > 0,
        missing: expected.len() - removed,
    }
}

/// Registry of target adapters, keyed by target root name.
///
/// Constructed once per sync run. Adapters are registered at startup; no
/// dynamic registration is needed.
pub struct TargetRegistry {
    adapters: Vec<Box<dyn TargetAdapter>>,
}

impl TargetRegistry {
    /// Build a registry containing all built-in target adapters.
    pub fn new() -> Self {
        Self {
            adapters: vec![
                Box::new(agents::AgentsAdapter),
                Box::new(claude::ClaudeAdapter),
                Box::new(codex::CodexAdapter),
                Box::new(opencode::OpencodeAdapter),
                Box::new(pi::PiAdapter),
                Box::new(cursor::CursorAdapter),
            ],
        }
    }

    /// Look up an adapter by target root name.
    ///
    /// Returns `None` if no adapter is registered for the given name. Callers
    /// may fall back to a default behavior (currently: pass-through copy) when
    /// no adapter is found.
    pub fn get(&self, name: &str) -> Option<&dyn TargetAdapter> {
        self.adapters
            .iter()
            .find(|a| a.name() == name)
            .map(|a| a.as_ref())
    }
}

impl Default for TargetRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Return an error message when an agent name would create a Windows-invalid
/// native filename. Runs on every platform so generated packages stay portable.
pub fn validate_agent_filename(name: &str) -> Result<(), String> {
    if let Some(ch) = name.chars().find(|ch| WINDOWS_INVALID_CHARS.contains(ch)) {
        return Err(format!(
            "agent `{name}` contains portable filename-invalid character `{ch}`"
        ));
    }

    let stem = name
        .split('.')
        .next()
        .unwrap_or(name)
        .trim_end_matches([' ', '.'])
        .to_ascii_uppercase();

    let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
        || stem
            .strip_prefix("COM")
            .is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))
        || stem
            .strip_prefix("LPT")
            .is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));

    if reserved {
        return Err(format!(
            "agent `{name}` would create reserved Windows device filename `{stem}`"
        ));
    }

    Ok(())
}

pub fn paths_equivalent(a: &str, b: &str) -> bool {
    if cfg!(windows) {
        a.replace('\\', "/") == b.replace('\\', "/")
    } else {
        a == b
    }
}

pub fn dest_paths_equivalent(a: &str, b: &str) -> bool {
    a.replace('\\', "/") == b.replace('\\', "/")
}

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

    #[test]
    fn registry_contains_all_builtin_adapters() {
        let registry = TargetRegistry::new();

        for name in [
            ".agents",
            ".claude",
            ".codex",
            ".opencode",
            ".pi",
            ".cursor",
        ] {
            let adapter = registry
                .get(name)
                .unwrap_or_else(|| panic!("built-in target adapter `{name}` is not registered"));
            assert_eq!(adapter.name(), name);
        }
    }

    #[test]
    fn registry_get_unknown_name_returns_none() {
        let registry = TargetRegistry::new();
        assert!(registry.get(".unknown-target").is_none());
    }

    #[test]
    fn native_adapters_expose_skill_variant_keys() {
        let registry = TargetRegistry::new();
        let expected = [
            (".claude", Some("claude")),
            (".codex", Some("codex")),
            (".opencode", Some("opencode")),
            (".pi", Some("pi")),
            (".cursor", Some("cursor")),
            (".agents", None),
        ];

        for (target, key) in expected {
            let adapter = registry.get(target).unwrap();
            assert_eq!(adapter.skill_variant_key(), key);
        }
    }

    #[test]
    fn hook_event_allowlists_match_supported_command_hook_targets() {
        let registry = TargetRegistry::new();
        let claude = registry
            .get(".claude")
            .unwrap()
            .known_hook_events()
            .unwrap();
        let codex = registry.get(".codex").unwrap().known_hook_events().unwrap();
        assert_eq!(claude.len(), 29);
        assert!(claude.contains(&"SessionEnd"));
        assert_eq!(codex.len(), 10);
        assert!(!codex.contains(&"SessionEnd"));
        let cursor = registry
            .get(".cursor")
            .unwrap()
            .known_hook_events()
            .unwrap();
        assert_eq!(cursor.len(), 21);
        assert!(cursor.contains(&"beforeShellExecution"));
        assert!(cursor.contains(&"sessionStart"));

        for target in [".opencode", ".pi"] {
            assert!(registry.get(target).unwrap().known_hook_events().is_none());
        }
    }

    #[test]
    fn agents_adapter_default_dest_path_agent() {
        let registry = TargetRegistry::new();
        let adapter = registry.get(".agents").unwrap();
        let path = adapter.default_dest_path(ItemKind::Agent, "coder").unwrap();
        assert_eq!(path.as_str(), "agents/coder.md");
    }

    #[test]
    fn agents_adapter_default_dest_path_skill() {
        let registry = TargetRegistry::new();
        let adapter = registry.get(".agents").unwrap();
        let path = adapter
            .default_dest_path(ItemKind::Skill, "planning")
            .unwrap();
        assert_eq!(path.as_str(), "skills/planning");
    }

    #[test]
    fn windows_invalid_agent_filename_is_rejected() {
        assert!(validate_agent_filename("bad:name").is_err());
        assert!(validate_agent_filename("team/lead").is_err());
        assert!(validate_agent_filename(r"team\lead").is_err());
        assert!(validate_agent_filename("CON").is_err());
        assert!(validate_agent_filename("com1").is_err());
    }

    #[test]
    fn valid_agent_filename_passes() {
        assert!(validate_agent_filename("coder").is_ok());
        assert!(validate_agent_filename("deep-agent").is_ok());
    }

    #[cfg(windows)]
    #[test]
    fn path_equivalence_normalizes_separators_on_windows() {
        assert!(paths_equivalent(r"agents\coder.md", "agents/coder.md"));
    }

    #[cfg(not(windows))]
    #[test]
    fn path_equivalence_preserves_backslash_on_posix() {
        assert!(!paths_equivalent(r"agents\coder.md", "agents/coder.md"));
    }

    #[test]
    fn dest_path_equivalence_always_normalizes_separators() {
        assert!(dest_paths_equivalent(r"agents\coder.md", "agents/coder.md"));
    }
}