mars-agents 0.0.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
use serde::{Deserialize, Serialize};
use std::borrow::Borrow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::path::{Path, PathBuf};

macro_rules! string_newtype {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(
            Serialize, Deserialize, Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd,
        )]
        #[serde(transparent)]
        pub struct $name(String);

        impl $name {
            pub fn new(value: impl Into<String>) -> Self {
                Self(value.into())
            }

            pub fn as_str(&self) -> &str {
                &self.0
            }

            pub fn into_inner(self) -> String {
                self.0
            }
        }

        impl From<String> for $name {
            fn from(value: String) -> Self {
                Self(value)
            }
        }

        impl From<&str> for $name {
            fn from(value: &str) -> Self {
                Self(value.to_owned())
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl Borrow<str> for $name {
            fn borrow(&self) -> &str {
                &self.0
            }
        }

        impl Deref for $name {
            type Target = str;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl From<$name> for String {
            fn from(value: $name) -> Self {
                value.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(&self.0)
            }
        }

        impl PartialEq<str> for $name {
            fn eq(&self, other: &str) -> bool {
                self.0 == other
            }
        }

        impl PartialEq<&str> for $name {
            fn eq(&self, other: &&str) -> bool {
                self.0 == *other
            }
        }

        impl PartialEq<String> for $name {
            fn eq(&self, other: &String) -> bool {
                self.0 == *other
            }
        }

        impl PartialEq<$name> for String {
            fn eq(&self, other: &$name) -> bool {
                *self == other.0
            }
        }
    };
}

string_newtype!(SourceName);
string_newtype!(ItemName);
string_newtype!(SourceUrl);
string_newtype!(CommitHash);
string_newtype!(ContentHash);

/// Where an item came from — used for lock provenance and display.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SourceOrigin {
    /// From a dependency (git or path source).
    Dependency(SourceName),
    /// From the local project's [package] declaration.
    LocalPackage,
}

impl fmt::Display for SourceOrigin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Dependency(name) => write!(f, "{name}"),
            Self::LocalPackage => write!(f, "_self"),
        }
    }
}

/// How an item should be materialized in the managed root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Materialization {
    /// Copy source content to destination (standard for dependency items).
    Copy,
    /// Create a symlink to the source (for local package items — edits propagate).
    Symlink { source_abs: PathBuf },
}

/// Kind of installable item.
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ItemKind {
    Agent,
    Skill,
}

impl fmt::Display for ItemKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ItemKind::Agent => write!(f, "agent"),
            ItemKind::Skill => write!(f, "skill"),
        }
    }
}

/// Stable identity for an installed item — decoupled from source URL.
///
/// Items are identified by `(kind, name)`, not by source URL.
/// If a package moves to a different git host, the item identity is preserved.
#[derive(Debug, Clone, Hash, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ItemId {
    pub kind: ItemKind,
    pub name: ItemName,
}

impl fmt::Display for ItemId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.kind, self.name)
    }
}

/// Relative path under the install root (`.agents/` / project root).
#[derive(Eq, PartialEq, Clone, Debug, Ord, PartialOrd)]
pub struct DestPath(PathBuf);

impl DestPath {
    pub fn new(value: impl Into<PathBuf>) -> Self {
        Self(value.into())
    }

    pub fn as_path(&self) -> &Path {
        &self.0
    }

    pub fn into_inner(self) -> PathBuf {
        self.0
    }

    /// Resolve this relative path under a root path.
    pub fn resolve(&self, root: &Path) -> PathBuf {
        root.join(&self.0)
    }
}

impl From<PathBuf> for DestPath {
    fn from(value: PathBuf) -> Self {
        Self(value)
    }
}

impl From<&Path> for DestPath {
    fn from(value: &Path) -> Self {
        Self(value.to_path_buf())
    }
}

impl From<&str> for DestPath {
    fn from(value: &str) -> Self {
        Self(PathBuf::from(value))
    }
}

impl From<String> for DestPath {
    fn from(value: String) -> Self {
        Self(PathBuf::from(value))
    }
}

impl AsRef<Path> for DestPath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

impl Borrow<Path> for DestPath {
    fn borrow(&self) -> &Path {
        &self.0
    }
}

impl Borrow<str> for DestPath {
    fn borrow(&self) -> &str {
        self.0.to_str().expect("DestPath must be valid UTF-8")
    }
}

impl Hash for DestPath {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.to_string_lossy().hash(state);
    }
}

impl Deref for DestPath {
    type Target = Path;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Display for DestPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.display())
    }
}

impl Serialize for DestPath {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.to_string_lossy().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for DestPath {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer).map(|s| Self(PathBuf::from(s)))
    }
}

/// Resolved context for a mars command — project root + managed output root.
///
/// Named fields prevent argument-order bugs that plague `(project_root, managed_root)` pairs.
#[derive(Debug, Clone)]
pub struct MarsContext {
    /// Project root containing mars.toml and mars.lock.
    pub project_root: PathBuf,
    /// Managed output directory (e.g. /project/.agents).
    pub managed_root: PathBuf,
}

#[cfg(test)]
impl MarsContext {
    /// Create a MarsContext for tests without any validation.
    pub fn for_test(project_root: PathBuf, managed_root: PathBuf) -> Self {
        MarsContext {
            project_root,
            managed_root,
        }
    }
}

/// Stable source identity used for resolver deduplication.
#[derive(Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd)]
pub enum SourceId {
    Git { url: SourceUrl },
    Path { canonical: PathBuf },
}

impl SourceId {
    pub fn git(url: SourceUrl) -> Self {
        Self::Git { url }
    }

    pub fn path(base: &Path, relative_or_absolute: &Path) -> std::io::Result<Self> {
        let candidate = if relative_or_absolute.is_absolute() {
            relative_or_absolute.to_path_buf()
        } else {
            base.join(relative_or_absolute)
        };
        let canonical = candidate.canonicalize()?;
        Ok(Self::Path { canonical })
    }
}

impl fmt::Display for SourceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Git { url } => write!(f, "git:{url}"),
            Self::Path { canonical } => write!(f, "path:{}", canonical.display()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameRule {
    pub from: ItemName,
    pub to: ItemName,
}

/// Ordered rename rules, serialized as TOML inline table/map for compatibility.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RenameMap(Vec<RenameRule>);

impl RenameMap {
    pub fn new() -> Self {
        Self(Vec::new())
    }

    pub fn insert(&mut self, from: ItemName, to: ItemName) {
        if let Some(existing) = self.0.iter_mut().find(|r| r.from == from) {
            existing.to = to;
            return;
        }
        self.0.push(RenameRule { from, to });
    }

    pub fn push(&mut self, rule: RenameRule) {
        self.insert(rule.from, rule.to);
    }

    pub fn get(&self, from: &str) -> Option<&ItemName> {
        self.0.iter().find(|r| r.from == from).map(|r| &r.to)
    }

    pub fn iter(&self) -> impl Iterator<Item = &RenameRule> {
        self.0.iter()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }
}

impl Serialize for RenameMap {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        let mut map = serializer.serialize_map(Some(self.0.len()))?;
        for rule in &self.0 {
            map.serialize_entry(rule.from.as_str(), rule.to.as_str())?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for RenameMap {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let map = indexmap::IndexMap::<String, String>::deserialize(deserializer)?;
        Ok(Self(
            map.into_iter()
                .map(|(from, to)| RenameRule {
                    from: ItemName::from(from),
                    to: ItemName::from(to),
                })
                .collect(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct Wrapper<T> {
        value: T,
    }

    #[test]
    fn dest_path_roundtrip() {
        let v = Wrapper {
            value: DestPath::from("agents/coder.md"),
        };
        let s = toml::to_string(&v).unwrap();
        let out: Wrapper<DestPath> = toml::from_str(&s).unwrap();
        assert_eq!(v, out);
    }

    #[test]
    fn rename_map_toml_roundtrip_compat() {
        #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
        struct RenameWrapper {
            rename: RenameMap,
        }

        let input = r#"rename = { "coder" = "cool-coder" }"#;
        let parsed: RenameWrapper = toml::from_str(input).unwrap();
        assert_eq!(
            parsed.rename.get("coder").map(|v| v.as_str()),
            Some("cool-coder")
        );

        let serialized = toml::to_string(&parsed).unwrap();
        let reparsed: RenameWrapper = toml::from_str(&serialized).unwrap();
        assert_eq!(parsed, reparsed);
    }
}