mahbot 0.4.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! Skills subsystem — loads workspace skills and injects them into prompts.
//!
//! Skills live in any of these locations (prioritised in order):
//! - `<workspace>/skills/<name>/SKILL.md`
//! - `<workspace>/.claude/skills/<name>/SKILL.md`
//! - `<workspace>/.agents/skills/<name>/SKILL.md`
//!
//! Each SKILL.md is markdown with optional YAML frontmatter for `name` and
//! `description`. Loaded skills are rendered into the system prompt as name +
//! description, with a `<location>` path the model can `read` for full content.
//!
//! Within each location, skill subdirectories are scanned in deterministic
//! byte-sorted directory-name order (never `read_dir` enumeration order), so
//! identical directories always render byte-identically — keeping the provider
//! prompt-prefix cache stable across renders.

use crate::Skill;
use anyhow::{Context, Result};
use std::collections::HashSet;
use std::fmt::Write;
use std::path::Path;

// ── Frontmatter parsing ─────────────────────────────────────────────────

#[derive(Debug, Clone, Default)]
struct SkillMarkdownMeta {
    name: Option<String>,
    description: Option<String>,
}

/// Parse a minimal YAML frontmatter block (`---` delimited) from markdown.
/// Only `name:` and `description:` keys are extracted; everything else is ignored.
fn parse_frontmatter(content: &str) -> SkillMarkdownMeta {
    /// Strip leading/trailing whitespace and surrounding quotes.
    fn strip_quotes(s: &str) -> String {
        s.trim().trim_matches('"').trim_matches('\'').to_string()
    }

    let content = content.trim();
    if !content.starts_with("---") {
        return SkillMarkdownMeta::default();
    }

    let rest = &content[3..];
    let end = rest.find("\n---").map_or(0, |i| i + 3);
    if end < 3 {
        return SkillMarkdownMeta::default();
    }

    let frontmatter = rest[..end - 3].trim();
    let mut meta = SkillMarkdownMeta::default();

    for line in frontmatter.lines() {
        let line = line.trim();
        if let Some(value) = line.strip_prefix("name:") {
            meta.name = Some(strip_quotes(value));
        } else if let Some(value) = line.strip_prefix("description:") {
            meta.description = Some(strip_quotes(value));
        }
    }

    meta
}

// ── Loading ─────────────────────────────────────────────────────────────

/// Load all skills from the workspace skills directories.
///
/// Scans three locations (in priority order):
/// 1. `<workspace>/skills/`
/// 2. `<workspace>/.claude/skills/`
/// 3. `<workspace>/.agents/skills/`
///
/// If multiple directories contain a skill with the same name, the first one wins.
#[must_use]
pub async fn load_skills(ws: &crate::Workspace) -> Vec<Skill> {
    let workspace = ws.as_path();
    let dirs = [
        workspace.join("skills"),
        workspace.join(".claude").join("skills"),
        workspace.join(".agents").join("skills"),
    ];

    let mut seen = HashSet::new();
    let mut skills = Vec::new();

    for dir in dirs {
        for skill in scan_skills_dir(&dir).await {
            if seen.insert(skill.name.clone()) {
                skills.push(skill);
            }
        }
    }

    skills
}

/// Scan a single directory for skill subdirectories (each containing `SKILL.md`).
///
/// Entries are processed in deterministic raw directory-name order (byte
/// sort), not in `read_dir` enumeration order, so identical directories always
/// render byte-identically. Directory names within a single directory are
/// unique, so the sort cannot tie — case-only differences (e.g. `A` vs `a`)
/// order cleanly and two subdirs declaring the same frontmatter name resolve
/// to the byte-earliest directory name.
async fn scan_skills_dir(dir: &Path) -> Vec<Skill> {
    let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
        return Vec::new();
    };

    let mut subdirs = Vec::new();
    while let Ok(Some(entry)) = entries.next_entry().await {
        let Ok(file_type) = entry.file_type().await else {
            continue;
        };
        if !file_type.is_dir() {
            continue;
        }

        let path = entry.path();
        if !tokio::fs::try_exists(&path.join("SKILL.md"))
            .await
            .unwrap_or(false)
        {
            continue;
        }
        subdirs.push(path);
    }
    subdirs.sort_by(|a, b| a.file_name().cmp(&b.file_name()));

    let mut skills = Vec::new();
    for path in subdirs {
        if let Ok(skill) = load_skill(&path.join("SKILL.md"), &path).await {
            skills.push(skill);
        }
    }
    skills
}

async fn load_skill(path: &Path, skill_dir: &Path) -> Result<Skill> {
    let content = tokio::fs::read_to_string(path)
        .await
        .context("failed to read SKILL.md")?;
    let meta = parse_frontmatter(&content);

    Ok(Skill {
        name: meta.name.unwrap_or_else(|| {
            skill_dir
                .file_name()
                .map_or("unnamed".to_string(), |s| s.to_string_lossy().into_owned())
        }),
        description: meta
            .description
            .unwrap_or("No description provided.".to_string()),
        location: path.to_path_buf(),
    })
}

// ── Prompt rendering ────────────────────────────────────────────────────

/// Render skills into the system prompt.
///
/// Only name and description are inlined. The LLM must use `read` with
/// the `<location>` path to get the full content.
#[must_use]
pub fn skills_to_prompt(skills: &[Skill], ws: &crate::Workspace) -> String {
    let mut skills_xml = String::new();
    for skill in skills {
        let _ = writeln!(skills_xml, "  <skill>");
        write_xml_text_element(&mut skills_xml, 4, "name", &skill.name);
        write_xml_text_element(&mut skills_xml, 4, "description", &skill.description);

        let location = render_skill_location(skill, ws.as_path());
        write_xml_text_element(&mut skills_xml, 4, "location", &location);

        let _ = writeln!(skills_xml, "  </skill>");
    }
    crate::prompt::substitute(
        &crate::prompt::load_prompt("context/skills.md"),
        &[("{{skills}}", skills_xml.trim())],
    )
}

// ── Helpers ─────────────────────────────────────────────────────────────

fn write_xml_text_element(w: &mut String, indent: usize, name: &str, value: &str) {
    let padding = " ".repeat(indent);
    let escaped = crate::util::html::escape_html(value);
    let _ = writeln!(w, "{padding}<{name}>{escaped}</{name}>");
}

fn render_skill_location(skill: &Skill, workspace: &Path) -> String {
    if let Ok(relative) = skill.location.strip_prefix(workspace) {
        return relative.display().to_string();
    }
    skill.location.display().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::workspace::test_ws;
    use std::path::PathBuf;

    #[tokio::test]
    async fn load_md_skill() {
        let dir = tempfile::tempdir().unwrap();
        let skills_dir = dir.path().join("skills");
        let sd = skills_dir.join("my-skill");
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(
            sd.join("SKILL.md"),
            "---\nname: my-skill\ndescription: A markdown skill\n---\n\n# Instructions\nDo something.",
        )
        .unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "my-skill");
        assert_eq!(skills[0].description, "A markdown skill");
    }

    #[tokio::test]
    async fn load_md_skill_without_frontmatter() {
        let dir = tempfile::tempdir().unwrap();
        let skills_dir = dir.path().join("skills");
        let sd = skills_dir.join("bare-skill");
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(sd.join("SKILL.md"), "# Instructions\nDo something.").unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "bare-skill");
        assert_eq!(skills[0].description, "No description provided.");
    }

    #[tokio::test]
    async fn empty_skills_dir_returns_empty() {
        let dir = tempfile::tempdir().unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert!(skills.is_empty());
    }

    #[tokio::test]
    async fn nonexistent_workspace_returns_empty() {
        let skills = load_skills(&test_ws(Path::new("/nonexistent"))).await;
        assert!(skills.is_empty());
    }

    #[test]
    fn parse_frontmatter_works() {
        let content = "---\nname: my-skill\ndescription: Does stuff\n---\n\nContent here";
        let meta = parse_frontmatter(content);
        assert_eq!(meta.name.as_deref(), Some("my-skill"));
        assert_eq!(meta.description.as_deref(), Some("Does stuff"));
    }

    #[test]
    fn parse_no_frontmatter() {
        let content = "# Just a heading\n\nSome content";
        let meta = parse_frontmatter(content);
        assert!(meta.name.is_none());
    }

    #[test]
    fn skills_to_prompt_shows_name_and_description() {
        let skill = Skill {
            name: "my-skill".into(),
            description: "Does stuff".into(),
            location: PathBuf::from("skills/my-skill/SKILL.md"),
        };
        let prompt = skills_to_prompt(&[skill], &test_ws(Path::new("")));
        assert!(prompt.contains("my-skill"));
        assert!(prompt.contains("Does stuff"));
        assert!(prompt.contains("skills/my-skill/SKILL.md"));
    }

    #[test]
    fn skills_to_prompt_no_instructions_inlined() {
        let skill = Skill {
            name: "quiet-skill".into(),
            description: "Does stuff".into(),
            location: PathBuf::from("skills/quiet-skill/SKILL.md"),
        };
        let prompt = skills_to_prompt(&[skill], &test_ws(Path::new("")));
        assert!(prompt.contains("quiet-skill"));
        assert!(prompt.contains("Does stuff"));
    }

    #[tokio::test]
    async fn load_skills_from_claude_skills_dir() {
        let dir = tempfile::tempdir().unwrap();
        let sd = dir.path().join(".claude").join("skills").join("my-skill");
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(
            sd.join("SKILL.md"),
            "---\nname: claude-skill\ndescription: From .claude/skills\n---\n\nContent",
        )
        .unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "claude-skill");
    }

    #[tokio::test]
    async fn load_skills_from_agents_skills_dir() {
        let dir = tempfile::tempdir().unwrap();
        let sd = dir.path().join(".agents").join("skills").join("my-skill");
        std::fs::create_dir_all(&sd).unwrap();
        std::fs::write(
            sd.join("SKILL.md"),
            "---\nname: agents-skill\ndescription: From .agents/skills\n---\n\nContent",
        )
        .unwrap();
        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].name, "agents-skill");
    }

    #[tokio::test]
    async fn load_skills_dedup_workspace_priority() {
        let dir = tempfile::tempdir().unwrap();

        // Same skill name in all three directories
        let sd1 = dir.path().join("skills").join("common");
        std::fs::create_dir_all(&sd1).unwrap();
        std::fs::write(
            sd1.join("SKILL.md"),
            "---\nname: common\ndescription: From workspace skills/\n---\n\nContent",
        )
        .unwrap();

        let sd2 = dir.path().join(".claude").join("skills").join("common");
        std::fs::create_dir_all(&sd2).unwrap();
        std::fs::write(
            sd2.join("SKILL.md"),
            "---\nname: common\ndescription: From .claude/skills\n---\n\nContent",
        )
        .unwrap();

        let sd3 = dir.path().join(".agents").join("skills").join("common");
        std::fs::create_dir_all(&sd3).unwrap();
        std::fs::write(
            sd3.join("SKILL.md"),
            "---\nname: common\ndescription: From .agents/skills\n---\n\nContent",
        )
        .unwrap();

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].description, "From workspace skills/");
    }

    #[tokio::test]
    async fn load_skills_dedup_claude_over_agents() {
        let dir = tempfile::tempdir().unwrap();

        // Same skill name in claude and agents (no workspace/skills)
        let sd2 = dir.path().join(".claude").join("skills").join("common");
        std::fs::create_dir_all(&sd2).unwrap();
        std::fs::write(
            sd2.join("SKILL.md"),
            "---\nname: common\ndescription: From .claude/skills\n---\n\nContent",
        )
        .unwrap();

        let sd3 = dir.path().join(".agents").join("skills").join("common");
        std::fs::create_dir_all(&sd3).unwrap();
        std::fs::write(
            sd3.join("SKILL.md"),
            "---\nname: common\ndescription: From .agents/skills\n---\n\nContent",
        )
        .unwrap();

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].description, "From .claude/skills");
    }

    #[tokio::test]
    async fn load_skills_returns_deterministic_order() {
        let dir = tempfile::tempdir().unwrap();
        let skills_dir = dir.path().join("skills");

        // Create subdirs in deliberately scrambled order — `read_dir` order is
        // not guaranteed, so the loader must byte-sort by directory name for a
        // stable render. This asserts the sorted order directly (a byte-identical
        // two-render test would pass even pre-fix on APFS's stable-enough order).
        for name in ["zeta", "alpha", "middle"] {
            let sd = skills_dir.join(name);
            std::fs::create_dir_all(&sd).unwrap();
            std::fs::write(
                sd.join("SKILL.md"),
                format!("---\nname: {name}\ndescription: Skill {name}\n---\n\nContent"),
            )
            .unwrap();
        }

        let skills = load_skills(&test_ws(dir.path())).await;
        let names: Vec<&str> = skills.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, ["alpha", "middle", "zeta"]);
    }

    #[tokio::test]
    async fn load_skills_duplicate_frontmatter_name_uses_sorted_dir_winner() {
        let dir = tempfile::tempdir().unwrap();
        let skills_dir = dir.path().join("skills");

        // Two subdirs declaring the same frontmatter name: the winner used to
        // be whatever `read_dir` yielded first (nondeterministic); with the
        // deterministic scan it is the byte-earliest directory name.
        let sd_late = skills_dir.join("z-late");
        std::fs::create_dir_all(&sd_late).unwrap();
        std::fs::write(
            sd_late.join("SKILL.md"),
            "---\nname: common\ndescription: From z-late\n---\n\nContent",
        )
        .unwrap();

        let sd_early = skills_dir.join("a-early");
        std::fs::create_dir_all(&sd_early).unwrap();
        std::fs::write(
            sd_early.join("SKILL.md"),
            "---\nname: common\ndescription: From a-early\n---\n\nContent",
        )
        .unwrap();

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 1);
        assert_eq!(skills[0].description, "From a-early");
    }

    #[tokio::test]
    async fn load_skills_unique_names_from_multiple_dirs() {
        let dir = tempfile::tempdir().unwrap();

        let sd1 = dir.path().join("skills").join("skill-a");
        std::fs::create_dir_all(&sd1).unwrap();
        std::fs::write(
            sd1.join("SKILL.md"),
            "---\nname: skill-a\ndescription: From workspace\n---\n\nContent",
        )
        .unwrap();

        let sd2 = dir.path().join(".claude").join("skills").join("skill-b");
        std::fs::create_dir_all(&sd2).unwrap();
        std::fs::write(
            sd2.join("SKILL.md"),
            "---\nname: skill-b\ndescription: From .claude\n---\n\nContent",
        )
        .unwrap();

        let sd3 = dir.path().join(".agents").join("skills").join("skill-c");
        std::fs::create_dir_all(&sd3).unwrap();
        std::fs::write(
            sd3.join("SKILL.md"),
            "---\nname: skill-c\ndescription: From .agents\n---\n\nContent",
        )
        .unwrap();

        let skills = load_skills(&test_ws(dir.path())).await;
        assert_eq!(skills.len(), 3);
    }

    #[test]
    fn write_xml_text_element_escapes_special_chars() {
        // Verify that `<`, `>`, `&`, `"`, and `'` are all properly escaped
        // using the shared `escape_html` from `util::html`.
        let mut out = String::new();
        write_xml_text_element(&mut out, 0, "test", "<hello> & \"world\" 'test'");
        assert_eq!(
            out,
            "<test>&lt;hello&gt; &amp; &quot;world&quot; &#39;test&#39;</test>\n"
        );
    }
}