incurs 0.10.1

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
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
//! Skill file synchronization — generates and installs skill files from commands.
//!
//! Generates SKILL.md files from the command
//! tree, installs them to agent directories, and tracks a hash for staleness
//! detection so repeated syncs are no-ops when commands haven't changed.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use crate::agents::{self, AgentInstall, InstallOptions, RemoveOptions};
use crate::skill::{self, CommandInfo, SkillFile};

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Options for [`sync`].
#[derive(Debug, Clone, Default)]
pub struct SyncOptions {
    /// Working directory for resolving include globs. Defaults to current dir.
    pub cwd: Option<String>,
    /// Grouping depth for skill files. Defaults to `1`.
    pub depth: Option<usize>,
    /// CLI description, used as the top-level group description.
    pub description: Option<String>,
    /// Install globally (`true`) or project-local (`false`). Defaults to `true`.
    pub global: bool,
    /// Glob patterns for directories containing additional SKILL.md files to include.
    pub include: Option<Vec<String>>,
}

/// A synced skill entry.
#[derive(Debug, Clone)]
pub struct SyncedSkill {
    /// Skill directory name.
    pub name: String,
    /// Description extracted from skill frontmatter.
    pub description: Option<String>,
    /// Whether this skill was included from a local file (not generated from commands).
    pub external: bool,
}

/// Result of a [`sync`] operation.
#[derive(Debug, Clone)]
pub struct SyncResult {
    /// Synced skills with metadata.
    pub skills: Vec<SyncedSkill>,
    /// Canonical install paths.
    pub paths: Vec<PathBuf>,
    /// Per-agent install details (non-universal agents only).
    pub agents: Vec<AgentInstall>,
}

/// Stored metadata for staleness detection.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct Meta {
    hash: String,
    #[serde(default)]
    skills: Vec<String>,
    #[serde(default)]
    at: String,
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Generates skill files from commands and installs them to agent directories.
///
/// Creates a temporary directory, writes SKILL.md files, installs them via
/// [`agents::install`], cleans up stale skills from previous syncs, and
/// writes a hash file for future staleness detection.
pub async fn sync(
    name: &str,
    commands: &[CommandInfo],
    options: &SyncOptions,
) -> Result<SyncResult, crate::errors::Error> {
    let depth = options.depth.unwrap_or(1);
    let is_global = options.global;

    let cwd = options.cwd.clone().unwrap_or_else(|| {
        std::env::current_dir()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|_| ".".to_string())
    });

    // Build groups from description
    let mut groups: BTreeMap<String, String> = BTreeMap::new();
    if let Some(desc) = &options.description {
        groups.insert(name.to_string(), desc.clone());
    }

    let files = skill::split(name, commands, depth, &groups);

    // Create temp directory
    let tmp_dir =
        std::env::temp_dir().join(format!("incurs-skills-{}-{}", name, std::process::id()));
    let _ = fs::create_dir_all(&tmp_dir);

    let result = sync_inner(
        name,
        commands,
        &files,
        &tmp_dir,
        &cwd,
        is_global,
        &options.include,
    );

    // Cleanup temp directory
    let _ = fs::remove_dir_all(&tmp_dir);

    result
}

fn sync_inner(
    name: &str,
    commands: &[CommandInfo],
    files: &[SkillFile],
    tmp_dir: &Path,
    cwd: &str,
    is_global: bool,
    include: &Option<Vec<String>>,
) -> Result<SyncResult, crate::errors::Error> {
    let mut skills: Vec<SyncedSkill> = Vec::new();

    for file in files {
        let file_path = if file.dir.is_empty() {
            tmp_dir.join("SKILL.md")
        } else {
            tmp_dir.join(&file.dir).join("SKILL.md")
        };
        if let Some(parent) = file_path.parent() {
            let _ = fs::create_dir_all(parent);
        }
        let content = format!("{}\n", file.content);
        let _ = fs::write(&file_path, &content);

        let desc = extract_description(&content);
        let skill_name = if file.dir.is_empty() {
            name.to_string()
        } else {
            file.dir.clone()
        };
        skills.push(SyncedSkill {
            name: skill_name,
            description: desc,
            external: false,
        });
    }

    // Include additional SKILL.md files matched by patterns
    if let Some(patterns) = include {
        for pattern in patterns {
            let is_root = pattern == "_root";
            let search_path = if is_root {
                PathBuf::from(cwd).join("SKILL.md")
            } else {
                PathBuf::from(cwd).join(pattern).join("SKILL.md")
            };

            if search_path.exists()
                && let Ok(content) = fs::read_to_string(&search_path)
            {
                let skill_name = if is_root {
                    extract_skill_name(&content).unwrap_or_else(|| name.to_string())
                } else {
                    search_path
                        .parent()
                        .and_then(|p| p.file_name())
                        .and_then(|n| n.to_str())
                        .unwrap_or(pattern)
                        .to_string()
                };

                let dest = tmp_dir.join(&skill_name).join("SKILL.md");
                if let Some(parent) = dest.parent() {
                    let _ = fs::create_dir_all(parent);
                }
                let _ = fs::write(&dest, &content);

                if !skills.iter().any(|s| s.name == skill_name) {
                    let desc = extract_description(&content);
                    skills.push(SyncedSkill {
                        name: skill_name,
                        description: desc,
                        external: true,
                    });
                }
            }
        }
    }

    // Install via agents module
    let install_result = agents::install(
        tmp_dir,
        &InstallOptions {
            global: Some(is_global),
            cwd: Some(cwd.to_string()),
            ..Default::default()
        },
    );

    // Remove stale skills from previous installs
    let current_names: std::collections::HashSet<String> = install_result
        .paths
        .iter()
        .filter_map(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .map(|s| s.to_string())
        })
        .collect();

    let prev = read_meta(name);
    if let Some(prev_meta) = prev {
        for old in &prev_meta.skills {
            if !current_names.contains(old) {
                agents::remove(
                    old,
                    &RemoveOptions {
                        global: Some(is_global),
                        cwd: Some(cwd.to_string()),
                    },
                );
            }
        }
    }

    // Write hash for staleness detection
    let hash = skill::hash(commands);
    let skill_names: Vec<String> = current_names.into_iter().collect();
    write_meta(name, &hash, &skill_names);

    Ok(SyncResult {
        skills,
        paths: install_result.paths,
        agents: install_result.agents,
    })
}

/// Reads the stored skills hash for a CLI. Returns `None` if no hash exists.
pub fn read_hash(name: &str) -> Option<String> {
    read_meta(name).map(|m| m.hash)
}

/// Returns the set of stored skill names for this CLI that are currently
/// installed (a `SKILL.md` exists under `~/.agents/skills/<skill>` or
/// `<cwd>/.agents/skills/<skill>`).
fn installed_skills(name: &str, cwd: Option<&str>) -> std::collections::HashSet<String> {
    let meta = match read_meta(name) {
        Some(m) if !m.skills.is_empty() => m,
        _ => return std::collections::HashSet::new(),
    };
    let cwd = cwd
        .map(PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .unwrap_or_default();
    let bases = [
        dirs::home_dir()
            .unwrap_or_default()
            .join(".agents")
            .join("skills"),
        cwd.join(".agents").join("skills"),
    ];
    meta.skills
        .into_iter()
        .filter(|skill| {
            bases
                .iter()
                .any(|base| base.join(skill).join("SKILL.md").exists())
        })
        .collect()
}

/// Returns `true` if any of the stored skills for this CLI are currently
/// installed.
pub fn has_installed_skills(name: &str, cwd: Option<&str>) -> bool {
    !installed_skills(name, cwd).is_empty()
}

/// A skill entry returned by [`list`].
pub struct ListedSkill {
    /// The skill name.
    pub name: String,
    /// The skill description, if any.
    pub description: Option<String>,
    /// Whether this skill is currently installed on disk.
    pub installed: bool,
}

/// Lists the skills this CLI would generate, annotated with whether each is
/// currently installed.
pub fn list(
    name: &str,
    commands: &[CommandInfo],
    depth: usize,
    description: Option<&str>,
) -> Vec<ListedSkill> {
    let mut groups: BTreeMap<String, String> = BTreeMap::new();
    if let Some(desc) = description {
        groups.insert(name.to_string(), desc.to_string());
    }
    let files = skill::split(name, commands, depth, &groups);
    let installed = installed_skills(name, None);

    let mut skills: Vec<ListedSkill> = files
        .iter()
        .map(|file| {
            let content = format!("{}\n", file.content);
            let skill_name = extract_skill_name(&content).unwrap_or_else(|| {
                if file.dir.is_empty() {
                    name.to_string()
                } else {
                    file.dir.clone()
                }
            });
            let desc = extract_description(&content);
            let is_installed = installed.contains(&skill_name);
            ListedSkill {
                name: skill_name,
                description: desc,
                installed: is_installed,
            }
        })
        .collect();
    skills.sort_by(|a, b| a.name.cmp(&b.name));
    skills
}

// ---------------------------------------------------------------------------
// Metadata persistence
// ---------------------------------------------------------------------------

/// Returns the metadata file path for a CLI.
fn meta_path(name: &str) -> PathBuf {
    let data_home = std::env::var("XDG_DATA_HOME")
        .ok()
        .filter(|s| !s.is_empty())
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            dirs::home_dir()
                .unwrap_or_default()
                .join(".local")
                .join("share")
        });
    data_home.join("incurs").join(format!("{}.json", name))
}

/// Writes the skills metadata for staleness detection and cleanup.
fn write_meta(name: &str, hash: &str, skills: &[String]) {
    let file = meta_path(name);
    if let Some(dir) = file.parent() {
        let _ = fs::create_dir_all(dir);
    }
    let meta = Meta {
        hash: hash.to_string(),
        skills: skills.to_vec(),
        at: chrono_now(),
    };
    if let Ok(json) = serde_json::to_string(&meta) {
        let _ = fs::write(&file, format!("{}\n", json));
    }
}

/// Reads the stored metadata for a CLI.
fn read_meta(name: &str) -> Option<Meta> {
    let file = meta_path(name);
    let content = fs::read_to_string(&file).ok()?;
    serde_json::from_str(&content).ok()
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Extracts the `description:` frontmatter value from SKILL.md content.
fn extract_description(content: &str) -> Option<String> {
    for line in content.lines() {
        if let Some(rest) = line.strip_prefix("description:") {
            let desc = rest.trim();
            if !desc.is_empty() {
                return Some(desc.to_string());
            }
        }
    }
    None
}

/// Extracts the `name:` frontmatter value from SKILL.md content.
fn extract_skill_name(content: &str) -> Option<String> {
    for line in content.lines() {
        if let Some(rest) = line.strip_prefix("name:") {
            let name = rest.trim();
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// Returns a basic ISO 8601 timestamp without pulling in the chrono crate.
fn chrono_now() -> String {
    // Use std SystemTime for a basic timestamp
    use std::time::SystemTime;
    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
        Ok(d) => format!("{}s", d.as_secs()),
        Err(_) => "0s".to_string(),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_extract_description() {
        let content = "---\nname: test\ndescription: A test skill\n---\n";
        assert_eq!(
            extract_description(content),
            Some("A test skill".to_string())
        );
    }

    #[test]
    fn test_extract_description_missing() {
        let content = "---\nname: test\n---\n";
        assert_eq!(extract_description(content), None);
    }

    #[test]
    fn test_extract_skill_name() {
        let content = "---\nname: my-skill\n---\n";
        assert_eq!(extract_skill_name(content), Some("my-skill".to_string()));
    }

    #[test]
    fn test_meta_path() {
        let path = meta_path("mycli");
        assert!(path.to_string_lossy().contains("incurs"));
        assert!(path.to_string_lossy().ends_with("mycli.json"));
    }

    #[test]
    fn test_read_hash_nonexistent() {
        assert_eq!(read_hash("nonexistent-test-cli-12345"), None);
    }

    // F10: has_installed_skills returns false when no meta exists.
    #[test]
    fn test_has_installed_skills_no_meta() {
        assert!(!has_installed_skills("nonexistent-cli-f10-aaa", None));
    }

    // F10: has_installed_skills returns true when a stored skill has a SKILL.md
    // under `<cwd>/.agents/skills/<skill>`.
    #[test]
    fn test_has_installed_skills_detects_installed() {
        let unique = format!("f10-cli-{}", std::process::id());
        // Record metadata (uses the ambient XDG/home data dir for this name only).
        write_meta(&unique, "abc123", std::slice::from_ref(&unique));

        // Create a temp cwd with the skill installed.
        let tmp = std::env::temp_dir().join(format!("f10-cwd-{}", std::process::id()));
        let skill_dir = tmp.join(".agents").join("skills").join(&unique);
        fs::create_dir_all(&skill_dir).unwrap();
        fs::write(skill_dir.join("SKILL.md"), "x").unwrap();

        assert!(has_installed_skills(&unique, Some(&tmp.to_string_lossy())));

        // No matching skill dir → false.
        let empty = std::env::temp_dir().join(format!("f10-empty-{}", std::process::id()));
        fs::create_dir_all(&empty).unwrap();
        assert!(!has_installed_skills(
            &unique,
            Some(&empty.to_string_lossy())
        ));

        // Cleanup
        let _ = fs::remove_file(meta_path(&unique));
        let _ = fs::remove_dir_all(&tmp);
        let _ = fs::remove_dir_all(&empty);
    }
}