koda-core 0.2.5

Core engine for the Koda AI coding agent (macOS and Linux only)
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! Skill discovery and loading.
//!
//! Skills are `SKILL.md` files with YAML frontmatter that inject expertise
//! into the agent's context. Unlike sub-agents, skills don't spawn a
//! separate inference loop — they're prompt injection, zero extra LLM cost.
//!
//! ## Skill file format
//!
//! ```markdown
//! ---
//! name: code-review
//! description: Expert code review with security focus
//! tags: [review, security]
//! ---
//!
//! You are a code review expert. When reviewing code:
//! 1. Check for security vulnerabilities
//! 2. Verify error handling
//! 3. Assess test coverage
//! ```
//!
//! ## Built-in skills
//!
//! - **code-review** — structured code review with security focus
//! - **security-audit** — OWASP-aligned security analysis
//!
//! ## Custom skills
//!
//! - **Project**: `.koda/skills/<name>/SKILL.md`
//! - **Global**: `~/.config/koda/skills/<name>/SKILL.md`
//!
//! Use `/skills` to browse, or ask Koda to "use the code review skill."
//!
//! Discovery order (later overrides earlier):
//! 1. Built-in skills (embedded in the binary)
//! 2. User-global skills (`~/.config/koda/skills/`)
//! 3. Project-local skills (`.koda/skills/`)

use std::collections::HashMap;
use std::path::Path;

/// Metadata from a SKILL.md frontmatter.
///
/// ## Parity with Claude Code
///
/// These fields map to Claude Code's `FrontmatterData`:
///
/// | CC field | Koda field | Notes |
/// |---|---|---|
/// | `description` | `description` | |
/// | `when_to_use` | `when_to_use` | |
/// | `allowed-tools` | `allowed_tools` | Scoped tool access |
/// | `user-invocable` | `user_invocable` | Default: `true` |
/// | `argument-hint` | `argument_hint` | Usage guidance |
#[derive(Debug, Clone)]
pub struct SkillMeta {
    /// Skill name (derived from filename or frontmatter).
    pub name: String,
    /// One-line description.
    pub description: String,
    /// Searchable tags.
    pub tags: Vec<String>,
    /// Guidance for the model on when to activate this skill.
    /// Surfaced in `ListSkills` output so the model can decide without
    /// hard-coded hints in `instructions.md`.
    pub when_to_use: Option<String>,
    /// Tool names allowed when this skill is active.
    /// Empty = all tools available (default). Non-empty = only these tools.
    /// Mirrors CC's `allowed-tools` frontmatter field.
    pub allowed_tools: Vec<String>,
    /// Whether users can invoke this skill (e.g. via `/skill-name`).
    /// `true` (default) = shown in user-facing skill list.
    /// `false` = model-only, not surfaced in `/skills` but still activatable.
    /// Mirrors CC's `user-invocable` frontmatter field.
    pub user_invocable: bool,
    /// Usage hint shown when listing the skill (e.g. `"<file_path>"`)
    /// Mirrors CC's `argument-hint` frontmatter field.
    pub argument_hint: Option<String>,
    /// Where this skill was discovered.
    pub source: SkillSource,
}

/// Where a skill was loaded from.
#[derive(Debug, Clone)]
pub enum SkillSource {
    /// Shipped with koda.
    BuiltIn,
    /// From `~/.config/koda/skills/`.
    User,
    /// From `.koda/skills/` in the project.
    Project,
}

/// A fully loaded skill (metadata + content).
#[derive(Debug, Clone)]
pub struct Skill {
    /// Skill metadata (name, description, tags, source).
    pub meta: SkillMeta,
    /// The full SKILL.md content (after frontmatter).
    pub content: String,
}

/// Registry of discovered skills.
#[derive(Debug, Default)]
pub struct SkillRegistry {
    pub(crate) skills: HashMap<String, Skill>,
}

impl SkillRegistry {
    /// Discover skills from all standard locations.
    pub fn discover(project_root: &Path) -> Self {
        let mut registry = Self::default();

        // 1. Built-in skills (embedded at compile time)
        registry.load_builtin();

        // 2. User-global skills
        if let Ok(config_dir) = crate::db::config_dir() {
            let user_dir = config_dir.join("skills");
            registry.load_directory(&user_dir, SkillSource::User);
        }

        // 3. Project-local skills
        let project_dir = project_root.join(".koda").join("skills");
        registry.load_directory(&project_dir, SkillSource::Project);

        registry
    }

    /// Load built-in skills embedded at compile time.
    fn load_builtin(&mut self) {
        let builtins: &[(&str, &str)] = &[
            (
                "code-review",
                include_str!("../skills/code-review/SKILL.md"),
            ),
            (
                "security-audit",
                include_str!("../skills/security-audit/SKILL.md"),
            ),
            ("simplify", include_str!("../skills/simplify/SKILL.md")),
            ("debug", include_str!("../skills/debug/SKILL.md")),
            ("remember", include_str!("../skills/remember/SKILL.md")),
        ];

        for (name, content) in builtins {
            if let Some(skill) = parse_skill_md(content, SkillSource::BuiltIn) {
                self.skills.insert(name.to_string(), skill);
            }
        }
    }

    /// Load skills from a directory (each subdirectory with a SKILL.md).
    fn load_directory(&mut self, dir: &Path, source: SkillSource) {
        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => return,
        };

        for entry in entries.flatten() {
            if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                continue;
            }
            let skill_file = entry.path().join("SKILL.md");
            if let Some(skill) = std::fs::read_to_string(&skill_file)
                .ok()
                .and_then(|content| parse_skill_md(&content, source.clone()))
            {
                self.skills.insert(skill.meta.name.clone(), skill);
            }
        }
    }

    /// List all discovered skills (name + description).
    pub fn list(&self) -> Vec<&SkillMeta> {
        let mut metas: Vec<&SkillMeta> = self.skills.values().map(|s| &s.meta).collect();
        metas.sort_by_key(|m| &m.name);
        metas
    }

    /// List only user-invocable skills (excludes model-only skills).
    ///
    /// Used by the `/skills` REPL command and `ListSkills` when called
    /// by the user (vs. the model discovering skills autonomously).
    pub fn list_user_invocable(&self) -> Vec<&SkillMeta> {
        let mut metas: Vec<&SkillMeta> = self
            .skills
            .values()
            .filter(|s| s.meta.user_invocable)
            .map(|s| &s.meta)
            .collect();
        metas.sort_by_key(|m| &m.name);
        metas
    }

    /// Search skills by query (matches name, description, tags).
    pub fn search(&self, query: &str) -> Vec<&SkillMeta> {
        let q = query.to_lowercase();
        let mut results: Vec<&SkillMeta> = self
            .skills
            .values()
            .filter(|s| {
                s.meta.name.to_lowercase().contains(&q)
                    || s.meta.description.to_lowercase().contains(&q)
                    || s.meta.tags.iter().any(|t| t.to_lowercase().contains(&q))
            })
            .map(|s| &s.meta)
            .collect();
        results.sort_by_key(|m| &m.name);
        results
    }

    /// Activate a skill by name — returns the full content for context injection.
    pub fn activate(&self, name: &str) -> Option<&str> {
        self.skills.get(name).map(|s| s.content.as_str())
    }

    /// Get the full skill metadata + content by name.
    ///
    /// Used when activation needs to inspect `allowed_tools` or other
    /// metadata beyond just the content string.
    pub fn get(&self, name: &str) -> Option<&Skill> {
        self.skills.get(name)
    }

    /// Inject a built-in skill programmatically (e.g. from a downstream CLI).
    ///
    /// This lets host applications (like `koda-cli`) embed their own
    /// documentation as a skill without coupling `koda-core` to any
    /// application-specific content.  Call after [`Self::discover`].
    ///
    /// `when_to_use` is shown in `ListSkills` output so the model knows
    /// when to activate this skill without hard-coded `instructions.md` hints.
    ///
    /// Overwrites any previously registered skill with the same name.
    pub fn add_builtin(
        &mut self,
        name: &str,
        description: &str,
        when_to_use: Option<&str>,
        content: &str,
    ) {
        let skill = Skill {
            meta: SkillMeta {
                name: name.to_string(),
                description: description.to_string(),
                tags: vec![],
                when_to_use: when_to_use.map(str::to_string),
                allowed_tools: vec![],
                user_invocable: true,
                argument_hint: None,
                source: SkillSource::BuiltIn,
            },
            content: content.to_string(),
        };
        self.skills.insert(name.to_string(), skill);
    }

    /// Number of discovered skills.
    pub fn len(&self) -> usize {
        self.skills.len()
    }

    /// Returns `true` if no skills were discovered.
    pub fn is_empty(&self) -> bool {
        self.skills.is_empty()
    }
}

/// Parse a SKILL.md file with YAML frontmatter.
///
/// Format:
/// ```text
/// ---
/// name: code-review
/// description: Senior code review
/// tags: [review, quality]
/// ---
///
/// # Skill content here...
/// ```
fn parse_skill_md(raw: &str, source: SkillSource) -> Option<Skill> {
    let trimmed = raw.trim_start();
    if !trimmed.starts_with("---") {
        return None;
    }

    // Find closing ---
    let after_open = &trimmed[3..];
    let close_pos = after_open.find("\n---")?;
    let frontmatter = &after_open[..close_pos].trim();
    let content = after_open[close_pos + 4..].trim_start().to_string();

    // Simple YAML parsing (no serde_yaml dependency).
    // Supported keys: name, description, tags, when_to_use, allowed_tools,
    //   user_invocable, argument_hint.
    // Multi-line YAML values and complex types are intentionally not supported.
    let mut name = String::new();
    let mut description = String::new();
    let mut tags = Vec::new();
    let mut when_to_use: Option<String> = None;
    let mut allowed_tools: Vec<String> = Vec::new();
    let mut user_invocable = true;
    let mut argument_hint: Option<String> = None;

    for line in frontmatter.lines() {
        let line = line.trim();
        if let Some(val) = line.strip_prefix("name:") {
            name = val.trim().to_string();
        } else if let Some(val) = line.strip_prefix("description:") {
            description = val.trim().to_string();
        } else if let Some(val) = line.strip_prefix("when_to_use:") {
            when_to_use = Some(val.trim().to_string());
        } else if let Some(val) = line
            .strip_prefix("allowed_tools:")
            .or_else(|| line.strip_prefix("allowed-tools:"))
        {
            // Parse [Tool1, Tool2] or comma-separated
            let val = val.trim();
            if let Some(inner) = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
                allowed_tools = inner
                    .split(',')
                    .map(|t| t.trim().to_string())
                    .filter(|t| !t.is_empty())
                    .collect();
            } else if !val.is_empty() {
                allowed_tools = val
                    .split(',')
                    .map(|t| t.trim().to_string())
                    .filter(|t| !t.is_empty())
                    .collect();
            }
        } else if let Some(val) = line
            .strip_prefix("user_invocable:")
            .or_else(|| line.strip_prefix("user-invocable:"))
        {
            user_invocable = val.trim() != "false";
        } else if let Some(val) = line
            .strip_prefix("argument_hint:")
            .or_else(|| line.strip_prefix("argument-hint:"))
        {
            let val = val.trim();
            if !val.is_empty() {
                argument_hint = Some(val.to_string());
            }
        } else if let Some(val) = line.strip_prefix("tags:") {
            // Parse [tag1, tag2, tag3]
            let val = val.trim();
            if let Some(inner) = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
                tags = inner.split(',').map(|t| t.trim().to_string()).collect();
            }
        }
    }

    if name.is_empty() {
        return None;
    }

    Some(Skill {
        meta: SkillMeta {
            name,
            description,
            tags,
            when_to_use,
            allowed_tools,
            user_invocable,
            argument_hint,
            source,
        },
        content,
    })
}

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

    #[test]
    fn test_parse_skill_md() {
        let raw = r#"---
name: code-review
description: Senior code review
tags: [review, quality]
when_to_use: Use when asked to review code or a PR.
---

# Code Review

Do the review.
"#;
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert_eq!(skill.meta.name, "code-review");
        assert_eq!(skill.meta.description, "Senior code review");
        assert_eq!(skill.meta.tags, vec!["review", "quality"]);
        assert_eq!(
            skill.meta.when_to_use.as_deref(),
            Some("Use when asked to review code or a PR.")
        );
        assert!(skill.meta.allowed_tools.is_empty());
        assert!(skill.meta.user_invocable);
        assert!(skill.meta.argument_hint.is_none());
        assert!(skill.content.contains("# Code Review"));
        assert!(skill.content.contains("Do the review."));
    }

    #[test]
    fn test_parse_allowed_tools() {
        let raw = "---\nname: scoped\ndescription: Scoped skill\ntags: []\nallowed_tools: [Read, Grep, Glob]\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert_eq!(skill.meta.allowed_tools, vec!["Read", "Grep", "Glob"]);
    }

    #[test]
    fn test_parse_allowed_tools_hyphenated() {
        let raw = "---\nname: scoped\ndescription: Scoped skill\ntags: []\nallowed-tools: [Read, Write]\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert_eq!(skill.meta.allowed_tools, vec!["Read", "Write"]);
    }

    #[test]
    fn test_parse_user_invocable_false() {
        let raw = "---\nname: model-only\ndescription: hidden\ntags: []\nuser_invocable: false\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert!(!skill.meta.user_invocable);
    }

    #[test]
    fn test_parse_user_invocable_hyphenated() {
        let raw = "---\nname: model-only\ndescription: hidden\ntags: []\nuser-invocable: false\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert!(!skill.meta.user_invocable);
    }

    #[test]
    fn test_parse_user_invocable_default_true() {
        let raw = "---\nname: visible\ndescription: shown\ntags: []\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert!(skill.meta.user_invocable);
    }

    #[test]
    fn test_parse_argument_hint() {
        let raw = "---\nname: pdf\ndescription: Generate PDF\ntags: []\nargument_hint: <file_path>\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert_eq!(skill.meta.argument_hint.as_deref(), Some("<file_path>"));
    }

    #[test]
    fn test_parse_argument_hint_hyphenated() {
        let raw = "---\nname: pdf\ndescription: Generate PDF\ntags: []\nargument-hint: <output_dir>\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert_eq!(skill.meta.argument_hint.as_deref(), Some("<output_dir>"));
    }

    #[test]
    fn test_list_user_invocable_excludes_model_only() {
        let mut registry = SkillRegistry::default();
        registry.add_builtin("user-skill", "for users", None, "content");
        // Manually insert a model-only skill
        registry.skills.insert(
            "model-skill".to_string(),
            Skill {
                meta: SkillMeta {
                    name: "model-skill".to_string(),
                    description: "model only".to_string(),
                    tags: vec![],
                    when_to_use: None,
                    allowed_tools: vec![],
                    user_invocable: false,
                    argument_hint: None,
                    source: SkillSource::BuiltIn,
                },
                content: "secret".to_string(),
            },
        );
        assert_eq!(registry.list().len(), 2);
        assert_eq!(registry.list_user_invocable().len(), 1);
        assert_eq!(registry.list_user_invocable()[0].name, "user-skill");
    }

    #[test]
    fn test_get_returns_full_skill() {
        let mut registry = SkillRegistry::default();
        registry.add_builtin("test", "desc", None, "body");
        let skill = registry.get("test").unwrap();
        assert_eq!(skill.meta.name, "test");
        assert_eq!(skill.content, "body");
    }

    #[test]
    fn test_parse_when_to_use_absent() {
        let raw = "---\nname: minimal\ndescription: minimal skill\ntags: []\n---\ncontent";
        let skill = parse_skill_md(raw, SkillSource::BuiltIn).unwrap();
        assert!(skill.meta.when_to_use.is_none());
    }

    #[test]
    fn test_parse_no_frontmatter() {
        assert!(parse_skill_md("# Just markdown", SkillSource::BuiltIn).is_none());
    }

    #[test]
    fn test_parse_no_name() {
        let raw = "---\ndescription: no name\n---\ncontent";
        assert!(parse_skill_md(raw, SkillSource::BuiltIn).is_none());
    }

    #[test]
    fn test_builtin_skills_load() {
        let mut registry = SkillRegistry::default();
        registry.load_builtin();
        assert!(registry.len() >= 2);
        assert!(registry.activate("code-review").is_some());
        assert!(registry.activate("security-audit").is_some());
        assert!(registry.activate("simplify").is_some());
        assert!(registry.activate("debug").is_some());
        assert!(registry.activate("remember").is_some());
    }

    #[test]
    fn test_search() {
        let mut registry = SkillRegistry::default();
        registry.load_builtin();

        let results = registry.search("review");
        // code-review, simplify, and remember all contain "review" in their metadata
        assert!(!results.is_empty());
        assert!(results.iter().any(|s| s.name == "code-review"));

        let results = registry.search("security");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "security-audit");
    }

    #[test]
    fn test_search_by_tag() {
        let mut registry = SkillRegistry::default();
        registry.load_builtin();

        let results = registry.search("owasp");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "security-audit");
    }

    #[test]
    fn test_add_builtin_injects_skill() {
        let mut registry = SkillRegistry::default();
        registry.add_builtin(
            "my-app-docs",
            "My app user manual",
            Some("Use when the user asks about the app."),
            "# My App\n\nDo stuff.",
        );
        assert_eq!(registry.len(), 1);
        let content = registry.activate("my-app-docs").unwrap();
        assert!(content.contains("Do stuff."));
        // Source must be BuiltIn
        let meta = registry.list();
        assert!(matches!(meta[0].source, SkillSource::BuiltIn));
        assert_eq!(
            meta[0].when_to_use.as_deref(),
            Some("Use when the user asks about the app.")
        );
    }

    #[test]
    fn test_add_builtin_overwrites_same_name() {
        let mut registry = SkillRegistry::default();
        registry.add_builtin("docs", "v1", None, "version one");
        registry.add_builtin("docs", "v2", None, "version two");
        assert_eq!(registry.len(), 1);
        assert!(registry.activate("docs").unwrap().contains("version two"));
    }

    #[test]
    fn test_list_sorted() {
        let mut registry = SkillRegistry::default();
        registry.load_builtin();

        let list = registry.list();
        let names: Vec<&str> = list.iter().map(|s| s.name.as_str()).collect();
        // Sorted alphabetically: code-review, debug, remember, security-audit, simplify
        assert!(list.len() >= 5);
        assert_eq!(names[0], "code-review");
        assert_eq!(names[1], "debug");
        assert_eq!(names[2], "remember");
        assert_eq!(names[3], "security-audit");
        assert_eq!(names[4], "simplify");
    }

    #[test]
    fn test_directory_discovery() {
        let tmp = tempfile::TempDir::new().unwrap();
        let skill_dir = tmp.path().join("my-skill");
        std::fs::create_dir_all(&skill_dir).unwrap();
        std::fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: my-skill\ndescription: test\ntags: []\n---\n# Test",
        )
        .unwrap();

        let mut registry = SkillRegistry::default();
        registry.load_directory(tmp.path(), SkillSource::Project);
        assert_eq!(registry.len(), 1);
        assert!(registry.activate("my-skill").is_some());
    }
}