rtango 0.5.0

Package manager for AI agent skills, agents, and system instruction files
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
use std::fs;
use std::path::{Path, PathBuf};

use ignore::WalkBuilder;

use crate::agent::{
    self,
    frontmatter::{FrontMatter, FrontMatterMapper, split_frontmatter, tokenize_tools},
};
use crate::spec::{Rule, RuleKind, Source};

use super::{
    ExpandedItem, ExpandedKind, SystemFile, fetch_github, hash_content, read_collection_spec,
};

/// Expand a single rule into its constituent items by reading source files.
///
/// - `Skill` / `Agent`: produces one item (single file).
/// - `SkillSet` / `AgentSet`: produces N items (one per source file in the directory).
pub fn expand_rule(root: &Path, rule: &Rule) -> anyhow::Result<Vec<ExpandedItem>> {
    match &rule.kind {
        RuleKind::Collection {
            include,
            exclude,
            schema_override,
        } => expand_collection(root, rule, include, exclude, schema_override),
        _ => expand_local_or_github(root, rule),
    }
}

/// Handle the non-collection kinds (skill, agent, skill-set, agent-set, system).
fn expand_local_or_github(root: &Path, rule: &Rule) -> anyhow::Result<Vec<ExpandedItem>> {
    let (_, abs_path) = materialize(root, &rule.source)?;

    match &rule.kind {
        RuleKind::SkillSet { include, exclude } => {
            expand_skill_set(rule, &abs_path, include, exclude)
        }
        RuleKind::AgentSet { include, exclude } => {
            expand_agent_set(rule, &abs_path, include, exclude)
        }
        RuleKind::Skill {
            name,
            description,
            allowed_tools,
        } => expand_single_skill(
            rule,
            &abs_path,
            name.as_deref(),
            description.as_deref(),
            allowed_tools.as_deref(),
        ),
        RuleKind::Agent {
            name,
            description,
            allowed_tools,
        } => expand_single_agent(
            rule,
            &abs_path,
            name.as_deref(),
            description.as_deref(),
            allowed_tools.as_deref(),
        ),
        RuleKind::System => expand_single_system(rule, &abs_path),
        RuleKind::Collection { .. } => unreachable!("handled in expand_rule"),
    }
}

/// Expand a Collection rule: fetch the remote repo, parse its spec.yaml,
/// and expand each matching rule. Imported rules get their id prefixed with
/// `<collection_rule_id>/` to avoid collisions with local rules.
fn expand_collection(
    root: &Path,
    rule: &Rule,
    include: &[String],
    exclude: &[String],
    schema_override: &Option<crate::spec::AgentName>,
) -> anyhow::Result<Vec<ExpandedItem>> {
    // Resolve the source to an on-disk root, exactly as non-collection rules do.
    let collection_root = match &rule.source {
        Source::Local(rel) => {
            let abs = if rel.is_absolute() {
                rel.clone()
            } else {
                root.join(rel)
            };
            if !abs.is_dir() {
                anyhow::bail!(
                    "collection '{}': source directory not found: {}",
                    rule.id,
                    abs.display()
                );
            }
            abs
        }
        Source::Github(g) => fetch_github(g)?,
    };
    let remote_spec = read_collection_spec(&collection_root)?;

    let mut all_items = Vec::new();
    for remote_rule in &remote_spec.rules {
        if !collection_passes_filter(&remote_rule.id, include, exclude) {
            continue;
        }
        // Build a synthetic rule that uses the remote rule's definition,
        // but with an optional schema_agent override from the local collection rule.
        let effective_schema = schema_override
            .clone()
            .unwrap_or_else(|| remote_rule.schema_agent.clone());

        let synthetic = Rule {
            id: format!("{}/{}", rule.id, remote_rule.id),
            source: remote_rule.source.clone(),
            schema_agent: effective_schema,
            on_target_modified: rule.on_target_modified,
            kind: remote_rule.kind.clone(),
        };

        // Expand the synthetic rule using the cache root as the project root
        let items = expand_local_or_github(&collection_root, &synthetic)?;

        // Re-tag the items so they carry the collection's source for lock tracking
        for mut item in items {
            item.rule_id = synthetic.id.clone();
            all_items.push(item);
        }
    }
    Ok(all_items)
}

/// Check if a remote rule id passes the collection's include/exclude filter.
fn collection_passes_filter(rule_id: &str, include: &[String], exclude: &[String]) -> bool {
    if !include.is_empty() {
        return include.iter().any(|p| p == rule_id);
    }
    !exclude.iter().any(|p| p == rule_id)
}

/// Decide whether an entry named `name` passes the include/exclude filter.
/// Include wins if set (whitelist); otherwise exclude drops matches.
/// Include/exclude are mutually exclusive — validated at the CLI layer.
fn passes_filter(name: &str, include: &[String], exclude: &[String]) -> bool {
    if !include.is_empty() {
        return include.iter().any(|p| p == name);
    }
    !exclude.iter().any(|p| p == name)
}

/// Apply CLI-level overrides from the rule to a parsed `FrontMatter`.
fn apply_overrides(
    fm: &mut FrontMatter,
    mapper: &dyn FrontMatterMapper,
    name: Option<&str>,
    description: Option<&str>,
    allowed_tools: Option<&str>,
) {
    if let Some(n) = name {
        fm.name = Some(n.to_string());
    }
    if let Some(d) = description {
        fm.description = Some(d.to_string());
    }
    if let Some(t) = allowed_tools {
        fm.allowed_tools = tokenize_tools(t)
            .into_iter()
            .map(|tok| mapper.parse_permission(&tok))
            .collect();
    }
}

/// Resolve a source to (project_root, filter_path) on disk.
///
/// `project_root` is what gets handed to agent parsers (which internally append
/// `.claude/skills`, `.agent/skills`, etc.). `filter_path` is what the
/// `expand_*_set` helpers use to narrow the parser's results to a subtree.
fn materialize(root: &Path, source: &Source) -> anyhow::Result<(PathBuf, PathBuf)> {
    match source {
        Source::Local(rel) => Ok((root.to_path_buf(), root.join(rel))),
        Source::Github(g) => {
            let cache_root = fetch_github(g)?;
            let filter = if g.path.is_empty() {
                cache_root.clone()
            } else {
                cache_root.join(&g.path)
            };
            Ok((cache_root, filter))
        } // Collection rules are dispatched before reaching materialize.
          // The Source variants (Local/Github) are handled above for all other kinds.
    }
}

fn expand_skill_set(
    rule: &Rule,
    abs_path: &Path,
    include: &[String],
    exclude: &[String],
) -> anyhow::Result<Vec<ExpandedItem>> {
    // Read directly from the rule's `source` path. The schema agent's
    // canonical folder (e.g. `.claude/skills`) is irrelevant here — a
    // `SkillSet` rule may point at any folder.
    let mapper = agent::frontmatter_mapper(&rule.schema_agent)
        .ok_or_else(|| anyhow::anyhow!("unknown agent: {}", rule.schema_agent))?;
    let skills = agent::parse_standard_skills(abs_path, mapper.as_ref())?;
    let mut items = Vec::new();
    for skill in &skills {
        if !passes_filter(&skill.name, include, exclude) {
            continue;
        }
        let content = fs::read_to_string(&skill.file)?;
        let hash = hash_content(&content);
        items.push(ExpandedItem {
            rule_id: rule.id.clone(),
            source: rule.source.clone(),
            source_content: content,
            source_hash: hash,
            kind: ExpandedKind::Skill(skill.clone()),
        });
        items.extend(expand_skill_assets(rule, &skill.name, &skill.dir)?);
    }
    Ok(items)
}

fn expand_agent_set(
    rule: &Rule,
    abs_path: &Path,
    include: &[String],
    exclude: &[String],
) -> anyhow::Result<Vec<ExpandedItem>> {
    // Read directly from the rule's `source` path. See expand_skill_set.
    let mapper = agent::frontmatter_mapper(&rule.schema_agent)
        .ok_or_else(|| anyhow::anyhow!("unknown agent: {}", rule.schema_agent))?;
    let agents = if rule.schema_agent.as_str() == "pi" {
        agent::PiParser::parse_agents_in(abs_path, mapper.as_ref())?
    } else {
        agent::parse_standard_agents(abs_path, mapper.as_ref())?
    };
    let mut items = Vec::new();
    for ag in &agents {
        if !passes_filter(&ag.name, include, exclude) {
            continue;
        }
        let content = fs::read_to_string(&ag.file)?;
        let hash = hash_content(&content);
        items.push(ExpandedItem {
            rule_id: rule.id.clone(),
            source: rule.source.clone(),
            source_content: content,
            source_hash: hash,
            kind: ExpandedKind::Agent(ag.clone()),
        });
    }
    Ok(items)
}

fn expand_skill_assets(
    rule: &Rule,
    skill_name: &str,
    skill_dir: &Path,
) -> anyhow::Result<Vec<ExpandedItem>> {
    let walker = WalkBuilder::new(skill_dir)
        .hidden(false)
        .git_ignore(true)
        .git_exclude(false)
        .git_global(false)
        .parents(true)
        .require_git(false)
        .build();

    let mut files = Vec::new();
    for entry in walker {
        let entry = entry?;
        let path = entry.path();
        if path == skill_dir || path == skill_dir.join("SKILL.md") {
            continue;
        }
        if entry.file_type().is_some_and(|kind| kind.is_file()) {
            files.push(path.to_path_buf());
        }
    }
    files.sort();

    let mut items = Vec::new();
    for file in files {
        let relative_path = file.strip_prefix(skill_dir)?.to_path_buf();
        let content = fs::read_to_string(&file)?;
        let hash = hash_content(&content);
        items.push(ExpandedItem {
            rule_id: rule.id.clone(),
            source: rule.source.clone(),
            source_content: content.clone(),
            source_hash: hash,
            kind: ExpandedKind::SkillAsset(super::SkillAsset {
                skill_name: skill_name.to_string(),
                source_file: file,
                relative_path,
                content,
            }),
        });
    }

    Ok(items)
}

fn expand_single_skill(
    rule: &Rule,
    abs_path: &Path,
    override_name: Option<&str>,
    override_description: Option<&str>,
    override_allowed_tools: Option<&str>,
) -> anyhow::Result<Vec<ExpandedItem>> {
    let mapper = agent::frontmatter_mapper(&rule.schema_agent)
        .ok_or_else(|| anyhow::anyhow!("unknown agent: {}", rule.schema_agent))?;

    let skill_file = abs_path.join("SKILL.md");
    if !skill_file.is_file() {
        anyhow::bail!("skill file not found: {}", skill_file.display());
    }
    let name = abs_path
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("skill path has no name"))?
        .to_string_lossy()
        .into_owned();
    let content = fs::read_to_string(&skill_file)?;
    let (yaml, body) = split_frontmatter(&content);
    let mut front_matter = match yaml {
        Some(y) => mapper.parse_frontmatter(y)?,
        None => FrontMatter::default(),
    };
    apply_overrides(
        &mut front_matter,
        mapper.as_ref(),
        override_name,
        override_description,
        override_allowed_tools,
    );
    let hash = hash_content(&content);
    let skill = crate::agent::Skill {
        name: name.clone(),
        dir: abs_path.to_path_buf(),
        file: skill_file,
        front_matter,
        body: body.to_string(),
    };
    let mut items = vec![ExpandedItem {
        rule_id: rule.id.clone(),
        source: rule.source.clone(),
        source_content: content,
        source_hash: hash,
        kind: ExpandedKind::Skill(skill),
    }];
    items.extend(expand_skill_assets(rule, &name, abs_path)?);
    Ok(items)
}

fn expand_single_system(rule: &Rule, abs_path: &Path) -> anyhow::Result<Vec<ExpandedItem>> {
    if !abs_path.is_file() {
        anyhow::bail!("system file not found: {}", abs_path.display());
    }
    let content = fs::read_to_string(abs_path)?;
    let hash = hash_content(&content);
    let system = SystemFile {
        file: abs_path.to_path_buf(),
        body: content.clone(),
    };
    Ok(vec![ExpandedItem {
        rule_id: rule.id.clone(),
        source: rule.source.clone(),
        source_content: content,
        source_hash: hash,
        kind: ExpandedKind::System(system),
    }])
}

fn expand_single_agent(
    rule: &Rule,
    abs_path: &Path,
    override_name: Option<&str>,
    override_description: Option<&str>,
    override_allowed_tools: Option<&str>,
) -> anyhow::Result<Vec<ExpandedItem>> {
    let mapper = agent::frontmatter_mapper(&rule.schema_agent)
        .ok_or_else(|| anyhow::anyhow!("unknown agent: {}", rule.schema_agent))?;

    if !abs_path.is_file() {
        anyhow::bail!("agent file not found: {}", abs_path.display());
    }
    let file_name = abs_path
        .file_name()
        .ok_or_else(|| anyhow::anyhow!("agent path has no file name"))?
        .to_string_lossy();
    let agent_name = if rule.schema_agent.as_str() == "pi" {
        file_name
            .strip_suffix(".md")
            .ok_or_else(|| anyhow::anyhow!("pi agent file must end with .md: {}", file_name))?
            .to_owned()
    } else {
        file_name
            .strip_suffix(".agent.md")
            .ok_or_else(|| anyhow::anyhow!("agent file must end with .agent.md: {}", file_name))?
            .to_owned()
    };
    let content = fs::read_to_string(abs_path)?;
    let (yaml, body) = split_frontmatter(&content);
    let mut front_matter = match yaml {
        Some(y) => mapper.parse_frontmatter(y)?,
        None => FrontMatter::default(),
    };
    apply_overrides(
        &mut front_matter,
        mapper.as_ref(),
        override_name,
        override_description,
        override_allowed_tools,
    );
    let hash = hash_content(&content);
    let agent = crate::agent::Agent {
        name: agent_name,
        file: abs_path.to_path_buf(),
        front_matter,
        body: body.to_string(),
    };
    Ok(vec![ExpandedItem {
        rule_id: rule.id.clone(),
        source: rule.source.clone(),
        source_content: content,
        source_hash: hash,
        kind: ExpandedKind::Agent(agent),
    }])
}