capo-agent 0.8.0

Coding-agent library built on motosan-agent-loop. Composable, embeddable.
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
#![cfg_attr(test, allow(clippy::expect_used, clippy::unwrap_used))]

use std::path::Path;

use gray_matter::engine::YAML;
use gray_matter::Matter;

use crate::skills::types::{LoadSkillsResult, Skill, SkillDiagnostic, SkillSource};
use crate::skills::validate::{validate_description, validate_name};

/// Parsed frontmatter fields. `name` is optional in the file because flat
/// `.md` skills derive `name` from the filename if missing.
#[derive(Debug, Default)]
pub(super) struct ParsedFrontmatter {
    pub name: Option<String>,
    pub description: Option<String>,
    pub disable_model_invocation: bool,
}

pub(super) fn parse_frontmatter(raw: &str) -> ParsedFrontmatter {
    let matter = Matter::<YAML>::new();
    let parsed = matter.parse(raw);
    let matter_text = parsed.matter.clone();
    let map = parsed.data.and_then(|data| data.as_hashmap().ok());

    let str_field = |k: &str| -> Option<String> {
        map.as_ref()
            .and_then(|m| m.get(k))
            .and_then(|v| v.as_string().ok())
            .or_else(|| frontmatter_line_field(&matter_text, k))
    };
    let bool_field = |k: &str| -> bool {
        map.as_ref()
            .and_then(|m| m.get(k))
            .and_then(|v| v.as_bool().ok())
            .or_else(|| frontmatter_line_field(&matter_text, k).and_then(|v| v.parse().ok()))
            .unwrap_or(false)
    };

    ParsedFrontmatter {
        name: str_field("name"),
        description: str_field("description"),
        disable_model_invocation: bool_field("disable-model-invocation"),
    }
}

pub(crate) fn strip_frontmatter_body(raw: &str) -> String {
    let Some(rest) = raw.strip_prefix("---\n") else {
        return raw.to_string();
    };
    let Some(end) = rest.find("\n---\n") else {
        return raw.to_string();
    };
    rest[end + "\n---\n".len()..].to_string()
}

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

    #[test]
    fn parses_minimal_frontmatter() {
        let raw = "---\nname: foo\ndescription: bar\n---\nbody\n";
        let fm = parse_frontmatter(raw);
        assert_eq!(fm.name.as_deref(), Some("foo"));
        assert_eq!(fm.description.as_deref(), Some("bar"));
        assert!(!fm.disable_model_invocation);
    }

    #[test]
    fn parses_disable_model_invocation() {
        let raw = "---\nname: foo\ndescription: bar\ndisable-model-invocation: true\n---\nbody\n";
        let fm = parse_frontmatter(raw);
        assert!(fm.disable_model_invocation);
    }

    #[test]
    fn missing_frontmatter_returns_default() {
        let fm = parse_frontmatter("just body\n");
        assert!(fm.name.is_none());
        assert!(fm.description.is_none());
        assert!(!fm.disable_model_invocation);
    }

    #[test]
    fn strips_frontmatter_body() {
        let raw = "---\nname: foo\ndescription: bar\n---\nhello body\n";
        assert_eq!(strip_frontmatter_body(raw), "hello body\n");
    }

    #[test]
    fn passes_through_when_no_frontmatter() {
        assert_eq!(
            strip_frontmatter_body("no frontmatter here\n"),
            "no frontmatter here\n"
        );
    }
}

pub(super) fn parse_skill_file(
    file_path: &Path,
    base_dir: &Path,
    source: SkillSource,
    fallback_name: Option<&str>,
) -> Result<Skill, SkillDiagnostic> {
    let raw = std::fs::read_to_string(file_path).map_err(|err| SkillDiagnostic {
        file_path: file_path.to_path_buf(),
        message: format!("read failed: {err}"),
    })?;
    let fm = parse_frontmatter(&raw);

    let name = fm
        .name
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .or_else(|| fallback_name.map(str::to_string));
    let name = match name {
        Some(n) => n,
        None => {
            return Err(SkillDiagnostic {
                file_path: file_path.to_path_buf(),
                message: "name is required (no frontmatter `name` and no filename fallback)".into(),
            });
        }
    };

    let name_errors = validate_name(&name);
    if !name_errors.is_empty() {
        return Err(SkillDiagnostic {
            file_path: file_path.to_path_buf(),
            message: name_errors.join("; "),
        });
    }

    let desc_errors = validate_description(fm.description.as_deref());
    if !desc_errors.is_empty() {
        return Err(SkillDiagnostic {
            file_path: file_path.to_path_buf(),
            message: desc_errors.join("; "),
        });
    }

    Ok(Skill {
        name,
        description: fm.description.unwrap_or_default().trim().to_string(),
        file_path: file_path.to_path_buf(),
        base_dir: base_dir.to_path_buf(),
        disable_model_invocation: fm.disable_model_invocation,
        source,
    })
}

#[cfg(test)]
mod parse_skill_file_tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn write(dir: &Path, name: &str, body: &str) -> std::path::PathBuf {
        let p = dir.join(name);
        fs::write(&p, body).unwrap();
        p
    }

    #[test]
    fn parses_valid_skill() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "x.md",
            "---\nname: foo\ndescription: bar\n---\nbody\n",
        );
        let skill = parse_skill_file(&p, tmp.path(), SkillSource::Global, None).unwrap();
        assert_eq!(skill.name, "foo");
        assert_eq!(skill.description, "bar");
        assert!(!skill.disable_model_invocation);
        assert_eq!(skill.source, SkillSource::Global);
        assert_eq!(skill.file_path, p);
        assert_eq!(skill.base_dir, tmp.path());
    }

    #[test]
    fn flat_md_uses_fallback_name() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "quick-tip.md",
            "---\ndescription: bar\n---\nbody\n",
        );
        let skill =
            parse_skill_file(&p, tmp.path(), SkillSource::Global, Some("quick-tip")).unwrap();
        assert_eq!(skill.name, "quick-tip");
    }

    #[test]
    fn invalid_name_produces_diagnostic() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "x.md",
            "---\nname: BAD_NAME\ndescription: bar\n---\nbody\n",
        );
        let diag = parse_skill_file(&p, tmp.path(), SkillSource::Global, None).unwrap_err();
        assert!(
            diag.message.contains("invalid characters"),
            "{}",
            diag.message
        );
        assert_eq!(diag.file_path, p);
    }

    #[test]
    fn missing_description_produces_diagnostic() {
        let tmp = tempdir().unwrap();
        let p = write(tmp.path(), "x.md", "---\nname: foo\n---\nbody\n");
        let diag = parse_skill_file(&p, tmp.path(), SkillSource::Global, None).unwrap_err();
        assert!(
            diag.message.contains("description is required"),
            "{}",
            diag.message
        );
    }

    #[test]
    fn missing_name_with_no_fallback_produces_diagnostic() {
        let tmp = tempdir().unwrap();
        let p = write(tmp.path(), "x.md", "---\ndescription: bar\n---\nbody\n");
        let diag = parse_skill_file(&p, tmp.path(), SkillSource::Global, None).unwrap_err();
        assert!(
            diag.message.contains("name is required"),
            "{}",
            diag.message
        );
    }

    #[test]
    fn disable_model_invocation_flag_propagates() {
        let tmp = tempdir().unwrap();
        let p = write(
            tmp.path(),
            "x.md",
            "---\nname: foo\ndescription: bar\ndisable-model-invocation: true\n---\nbody\n",
        );
        let skill = parse_skill_file(&p, tmp.path(), SkillSource::Global, None).unwrap();
        assert!(skill.disable_model_invocation);
    }
}

/// Load every skill under `dir`. Entries that are `<name>/SKILL.md` or
/// flat `<name>.md` become skills. Other entries are ignored. Invalid
/// skills produce diagnostics (non-fatal). Missing `dir` returns empty.
pub fn load_from_dir(dir: &Path, source: SkillSource) -> LoadSkillsResult {
    let mut result = LoadSkillsResult::default();
    let entries = match std::fs::read_dir(dir) {
        Ok(it) => it,
        Err(_) => return result,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };

        if file_type.is_dir() {
            let skill_md = path.join("SKILL.md");
            if !skill_md.is_file() {
                result.diagnostics.push(SkillDiagnostic {
                    file_path: path.clone(),
                    message: "skill directory missing SKILL.md; skipped".into(),
                });
                continue;
            }
            match parse_skill_file(&skill_md, &path, source, file_stem(&path).as_deref()) {
                Ok(skill) => result.skills.push(skill),
                Err(d) => result.diagnostics.push(d),
            }
        } else if file_type.is_file() {
            if path.extension().and_then(|s| s.to_str()) != Some("md") {
                continue;
            }
            let fallback = file_stem(&path);
            match parse_skill_file(&path, dir, source, fallback.as_deref()) {
                Ok(skill) => result.skills.push(skill),
                Err(d) => result.diagnostics.push(d),
            }
        }
    }
    result
}

fn frontmatter_line_field(matter: &str, key: &str) -> Option<String> {
    matter.lines().find_map(|line| {
        let (k, v) = line.split_once(':')?;
        (k.trim() == key).then(|| v.trim().to_string())
    })
}

fn file_stem(p: &Path) -> Option<String> {
    p.file_stem()
        .and_then(|s| s.to_str())
        .map(|s| s.trim_start_matches('.').to_string())
}

#[cfg(test)]
mod load_from_dir_tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn touch(p: &Path, body: &str) {
        if let Some(parent) = p.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(p, body).unwrap();
    }

    #[test]
    fn missing_dir_returns_empty() {
        let r = load_from_dir(Path::new("/no/such/path/for-test"), SkillSource::Global);
        assert!(r.skills.is_empty() && r.diagnostics.is_empty());
    }

    #[test]
    fn loads_directory_skill_via_skill_md() {
        let tmp = tempdir().unwrap();
        touch(
            &tmp.path().join("foo").join("SKILL.md"),
            "---\nname: foo\ndescription: d\n---\nbody\n",
        );
        let r = load_from_dir(tmp.path(), SkillSource::Global);
        assert_eq!(r.skills.len(), 1);
        assert!(r.diagnostics.is_empty());
        assert_eq!(r.skills[0].name, "foo");
        assert_eq!(r.skills[0].base_dir, tmp.path().join("foo"));
    }

    #[test]
    fn loads_flat_md_skill() {
        let tmp = tempdir().unwrap();
        touch(
            &tmp.path().join("quick-tip.md"),
            "---\ndescription: d\n---\nbody\n",
        );
        let r = load_from_dir(tmp.path(), SkillSource::Global);
        assert_eq!(r.skills.len(), 1, "{r:?}");
        assert_eq!(r.skills[0].name, "quick-tip");
    }

    #[test]
    fn directory_without_skill_md_emits_diagnostic() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("empty-dir")).unwrap();
        let r = load_from_dir(tmp.path(), SkillSource::Global);
        assert!(r.skills.is_empty());
        assert_eq!(r.diagnostics.len(), 1);
        assert!(r.diagnostics[0].message.contains("SKILL.md"));
    }

    #[test]
    fn invalid_skill_emits_diagnostic_and_continues() {
        let tmp = tempdir().unwrap();
        touch(&tmp.path().join("good.md"), "---\ndescription: d\n---\n");
        touch(
            &tmp.path().join("bad.md"),
            "---\nname: BAD\ndescription: d\n---\n",
        );
        let r = load_from_dir(tmp.path(), SkillSource::Global);
        assert_eq!(r.skills.len(), 1);
        assert_eq!(r.diagnostics.len(), 1);
        assert!(r.diagnostics[0].file_path.ends_with("bad.md"));
    }

    #[test]
    fn ignores_non_md_files() {
        let tmp = tempdir().unwrap();
        touch(&tmp.path().join("README.txt"), "ignored");
        touch(&tmp.path().join(".hidden.md"), "---\ndescription:d\n---\n");
        let r = load_from_dir(tmp.path(), SkillSource::Global);
        // .hidden.md is loadable (flat md, name="hidden")
        assert_eq!(r.skills.len(), 1);
    }
}

/// Load skills from `agent_dir/skills/` (global) then `cwd/.capo/skills/`
/// (project). Project entries with the same `name` replace global; a
/// diagnostic is emitted noting the override.
pub fn load_all(cwd: &Path, agent_dir: &Path) -> LoadSkillsResult {
    let mut result = LoadSkillsResult::default();
    let global = load_from_dir(&agent_dir.join("skills"), SkillSource::Global);
    let project = load_from_dir(&cwd.join(".capo").join("skills"), SkillSource::Project);

    let project_names: std::collections::HashSet<_> =
        project.skills.iter().map(|s| s.name.clone()).collect();

    for s in global.skills {
        if project_names.contains(&s.name) {
            result.diagnostics.push(SkillDiagnostic {
                file_path: s.file_path.clone(),
                message: format!(
                    "global skill `{}` overridden by project (project/.capo/skills wins)",
                    s.name
                ),
            });
        } else {
            result.skills.push(s);
        }
    }
    result.skills.extend(project.skills);
    result.diagnostics.extend(global.diagnostics);
    result.diagnostics.extend(project.diagnostics);
    result
}

#[cfg(test)]
mod load_all_tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    #[test]
    fn project_overrides_global_same_name() {
        let agent_dir = tempdir().unwrap();
        let cwd = tempdir().unwrap();

        let global = agent_dir.path().join("skills");
        fs::create_dir_all(&global).unwrap();
        fs::write(global.join("foo.md"), "---\ndescription: GLOBAL\n---\n").unwrap();

        let project = cwd.path().join(".capo").join("skills");
        fs::create_dir_all(&project).unwrap();
        fs::write(project.join("foo.md"), "---\ndescription: PROJECT\n---\n").unwrap();

        let r = load_all(cwd.path(), agent_dir.path());
        let names: Vec<_> = r
            .skills
            .iter()
            .map(|s| (&s.name, &s.description, s.source))
            .collect();
        assert_eq!(names.len(), 1);
        assert_eq!(names[0].0, "foo");
        assert_eq!(names[0].1, "PROJECT");
        assert_eq!(names[0].2, SkillSource::Project);
        assert!(r
            .diagnostics
            .iter()
            .any(|d| d.message.contains("overridden by project")));
    }

    #[test]
    fn global_and_project_skills_coexist_when_distinct_names() {
        let agent_dir = tempdir().unwrap();
        let cwd = tempdir().unwrap();

        let global = agent_dir.path().join("skills");
        fs::create_dir_all(&global).unwrap();
        fs::write(global.join("a.md"), "---\ndescription: A\n---\n").unwrap();

        let project = cwd.path().join(".capo").join("skills");
        fs::create_dir_all(&project).unwrap();
        fs::write(project.join("b.md"), "---\ndescription: B\n---\n").unwrap();

        let r = load_all(cwd.path(), agent_dir.path());
        let names: Vec<&str> = r.skills.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"a"));
        assert!(names.contains(&"b"));
    }

    #[test]
    fn missing_dirs_return_empty() {
        let agent_dir = tempdir().unwrap();
        let cwd = tempdir().unwrap();
        let r = load_all(cwd.path(), agent_dir.path());
        assert!(r.skills.is_empty() && r.diagnostics.is_empty());
    }
}