skillc 0.2.1

A development kit for Agent Skills - the open format for extending AI agent capabilities
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
//! Sources command per [[RFC-0002:C-SOURCES]]

use crate::config::get_cwd;
use crate::error::{Result, SkillcError};
use crate::logging::{LogEntry, get_run_id, init_log_db, log_access_with_fallback};
use crate::resolver::{ResolvedSkill, resolve_skill};
use crate::{OutputFormat, verbose};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;
use walkdir::WalkDir;

/// Execute the sources command per [[RFC-0002:C-SOURCES]].
///
/// Lists source files in a tree-style format or JSON.
pub fn sources(
    skill: &str,
    depth: Option<usize>,
    dir: Option<&str>,
    limit: usize,
    pattern: Option<&str>,
    format: OutputFormat,
) -> Result<String> {
    let start = Instant::now();
    let resolved = resolve_skill(skill)?;
    let run_id = get_run_id();

    verbose!(
        "sources: skill={} depth={:?} dir={:?} limit={} pattern={:?}",
        skill,
        depth,
        dir,
        limit,
        pattern
    );

    // Initialize logging
    let log_conn = init_log_db(&resolved.runtime_dir);

    let args = serde_json::json!({
        "depth": depth,
        "dir": dir,
        "limit": limit,
        "pattern": pattern,
    });

    let result = do_sources(&resolved, depth, dir, limit, pattern, &format);

    verbose!("sources: completed in {:?}", start.elapsed());

    // Log access (with automatic fallback for sandboxed environments)
    log_access_with_fallback(
        log_conn.as_ref(),
        &LogEntry {
            run_id,
            command: "sources".to_string(),
            skill: resolved.name.clone(),
            skill_path: resolved.source_dir.to_string_lossy().to_string(),
            cwd: get_cwd(),
            args: args.to_string(),
            error: result.as_ref().err().map(|e| e.to_string()),
        },
    );

    result
}

fn do_sources(
    resolved: &ResolvedSkill,
    max_depth: Option<usize>,
    subdir: Option<&str>,
    limit: usize,
    pattern: Option<&str>,
    format: &OutputFormat,
) -> Result<String> {
    // Determine root directory (skill root or subdirectory)
    let root = if let Some(dir_path) = subdir {
        // Path safety check
        if dir_path.contains("..") {
            let full_path = resolved.source_dir.join(dir_path);
            if let Ok(canonical) = full_path.canonicalize() {
                if !canonical.starts_with(&resolved.source_dir) {
                    return Err(SkillcError::PathEscapesRoot(dir_path.to_string()));
                }
            } else {
                return Err(SkillcError::DirectoryNotFound(dir_path.to_string()));
            }
        }

        let dir_full = resolved.source_dir.join(dir_path);
        if !dir_full.exists() {
            return Err(SkillcError::DirectoryNotFound(dir_path.to_string()));
        }
        if !dir_full.is_dir() {
            return Err(SkillcError::InvalidPath(format!(
                "{} is not a directory",
                dir_path
            )));
        }

        // Validate after canonicalization
        let canonical = dir_full.canonicalize()?;
        if !canonical.starts_with(&resolved.source_dir) {
            return Err(SkillcError::PathEscapesRoot(dir_path.to_string()));
        }

        dir_full
    } else {
        resolved.source_dir.clone()
    };

    // Compile glob pattern if provided
    let glob_pattern = pattern
        .map(glob::Pattern::new)
        .transpose()
        .map_err(|e| SkillcError::InvalidPath(format!("invalid glob pattern: {}", e)))?;

    match format {
        OutputFormat::Json => {
            // JSON format: flat list of entries
            let mut entries = Vec::new();
            let mut count = 0;

            for entry in WalkDir::new(&root)
                .min_depth(1)
                .max_depth(max_depth.unwrap_or(usize::MAX))
                .into_iter()
                .filter_map(|e| e.ok())
            {
                if count >= limit {
                    break;
                }

                let rel_path = entry
                    .path()
                    .strip_prefix(&resolved.source_dir)
                    .unwrap_or(entry.path());

                // Skip hidden files
                if rel_path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(|s| s.starts_with('.'))
                    .unwrap_or(false)
                {
                    continue;
                }

                // Apply glob filter if specified
                if let Some(ref pat) = glob_pattern
                    && let Some(name) = rel_path.file_name().and_then(|n| n.to_str())
                    && !pat.matches(name)
                {
                    continue;
                }

                let entry_type = if entry.file_type().is_dir() {
                    "dir"
                } else {
                    "file"
                };

                entries.push(serde_json::json!({
                    "path": rel_path.to_string_lossy(),
                    "type": entry_type
                }));
                count += 1;
            }

            Ok(serde_json::to_string_pretty(&entries)?)
        }
        OutputFormat::Text => {
            // Text format: tree display
            let entries =
                collect_tree_entries(&root, &resolved.source_dir, max_depth, &glob_pattern)?;
            Ok(format_tree(&resolved.name, &entries, limit))
        }
    }
}

/// A tree entry for display
#[derive(Debug)]
struct TreeEntry {
    /// Relative path from skill root
    path: PathBuf,
    /// Depth in tree (0 = root level)
    depth: usize,
    /// Is this a directory?
    is_dir: bool,
    /// For unexpanded directories, count of files inside
    file_count: Option<usize>,
    /// Is this the last entry at its level?
    is_last: bool,
}

/// Collect tree entries, respecting depth limit and glob pattern
fn collect_tree_entries(
    root: &Path,
    skill_root: &Path,
    max_depth: Option<usize>,
    pattern: &Option<glob::Pattern>,
) -> Result<Vec<TreeEntry>> {
    let mut entries = Vec::new();
    collect_entries_recursive(root, skill_root, 0, max_depth, pattern, &mut entries)?;

    // Mark last entries at each depth level
    mark_last_entries(&mut entries);

    Ok(entries)
}

fn collect_entries_recursive(
    dir: &Path,
    skill_root: &Path,
    current_depth: usize,
    max_depth: Option<usize>,
    pattern: &Option<glob::Pattern>,
    entries: &mut Vec<TreeEntry>,
) -> Result<()> {
    // Read directory entries
    let mut dir_entries: Vec<_> = fs::read_dir(dir)?
        .filter_map(|e| e.ok())
        .filter(|e| {
            // Skip hidden files/directories
            !e.file_name().to_string_lossy().starts_with('.')
        })
        .collect();

    // Sort: directories first, then lexicographically by name
    dir_entries.sort_by(|a, b| {
        let a_is_dir = a.file_type().map(|t| t.is_dir()).unwrap_or(false);
        let b_is_dir = b.file_type().map(|t| t.is_dir()).unwrap_or(false);
        match (a_is_dir, b_is_dir) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => a.file_name().cmp(&b.file_name()),
        }
    });

    for entry in dir_entries {
        let path = entry.path();
        let relative = path.strip_prefix(skill_root).unwrap_or(&path).to_path_buf();
        let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);

        // Apply glob filter (only to files, or to dir names)
        if let Some(pat) = pattern
            && !is_dir
        {
            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if !pat.matches(file_name) {
                continue;
            }
        }

        if is_dir {
            // Check if we should expand this directory
            let should_expand = max_depth.map(|d| current_depth < d).unwrap_or(true);

            if should_expand {
                // Add directory entry
                entries.push(TreeEntry {
                    path: relative.clone(),
                    depth: current_depth,
                    is_dir: true,
                    file_count: None,
                    is_last: false,
                });
                // Recurse
                collect_entries_recursive(
                    &path,
                    skill_root,
                    current_depth + 1,
                    max_depth,
                    pattern,
                    entries,
                )?;
            } else {
                // Count files in unexpanded directory
                let count = count_files_in_dir(&path, pattern)?;
                entries.push(TreeEntry {
                    path: relative,
                    depth: current_depth,
                    is_dir: true,
                    file_count: Some(count),
                    is_last: false,
                });
            }
        } else {
            entries.push(TreeEntry {
                path: relative,
                depth: current_depth,
                is_dir: false,
                file_count: None,
                is_last: false,
            });
        }
    }

    Ok(())
}

/// Count files in a directory (recursively), respecting glob pattern
fn count_files_in_dir(dir: &Path, pattern: &Option<glob::Pattern>) -> Result<usize> {
    let mut count = 0;
    for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) {
        if entry.file_type().is_file() {
            // Skip hidden files
            if entry.file_name().to_string_lossy().starts_with('.') {
                continue;
            }
            // Apply pattern filter
            if let Some(pat) = pattern {
                let file_name = entry.file_name().to_string_lossy();
                if !pat.matches(&file_name) {
                    continue;
                }
            }
            count += 1;
        }
    }
    Ok(count)
}

/// Mark the last entry at each depth level - O(n) algorithm
///
/// An entry is "last" if there are no more sibling entries at the same depth
/// within the same parent subtree.
fn mark_last_entries(entries: &mut [TreeEntry]) {
    if entries.is_empty() {
        return;
    }

    let n = entries.len();

    // For each entry, scan forward to determine if it's the last at its depth
    // within its parent's subtree. An entry is "last" if:
    // - There are no more entries at the same depth before we exit the subtree (depth < current)
    // - OR we reach the end of entries
    //
    // O(n) approach: process in reverse, tracking next sibling at each depth
    let mut next_at_depth: Vec<Option<usize>> = vec![None; 20]; // Max reasonable depth

    for i in (0..n).rev() {
        let depth = entries[i].depth;

        // Check if there's a next sibling at this depth
        entries[i].is_last = next_at_depth.get(depth).copied().flatten().is_none();

        // Update: this entry is now the "next" entry for its depth
        if depth < next_at_depth.len() {
            next_at_depth[depth] = Some(i);
        }

        // Clear deeper levels (we've exited those subtrees going backwards)
        for slot in next_at_depth.iter_mut().skip(depth + 1) {
            *slot = None;
        }
    }
}

/// Format tree with box-drawing characters, returning a string
fn format_tree(skill_name: &str, entries: &[TreeEntry], limit: usize) -> String {
    let mut output = format!("{}/\n", skill_name);
    let mut ancestors_last: Vec<bool> = Vec::new();

    for (printed, entry) in entries.iter().enumerate() {
        if printed >= limit {
            let remaining = entries.len() - printed;
            if remaining > 0 {
                output.push_str(&format!("... ({} more)\n", remaining));
            }
            break;
        }

        // Adjust ancestors_last to current depth
        while ancestors_last.len() > entry.depth {
            ancestors_last.pop();
        }

        // Build prefix
        let mut prefix = String::new();
        for &ancestor_is_last in &ancestors_last {
            if ancestor_is_last {
                prefix.push_str("    ");
            } else {
                prefix.push_str("│   ");
            }
        }

        // Add branch character
        if entry.is_last {
            prefix.push_str("└── ");
        } else {
            prefix.push_str("├── ");
        }

        // Format entry
        let name = entry
            .path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("?");

        if entry.is_dir {
            if let Some(count) = entry.file_count {
                output.push_str(&format!("{}{name}/ ({count} files)\n", prefix));
            } else {
                output.push_str(&format!("{}{name}/\n", prefix));
            }
        } else {
            output.push_str(&format!("{}{name}\n", prefix));
        }

        // Update ancestors for next iteration
        if entry.is_dir && entry.file_count.is_none() {
            // This directory is expanded, add to ancestors
            while ancestors_last.len() < entry.depth {
                ancestors_last.push(false);
            }
            ancestors_last.push(entry.is_last);
        }
    }

    // Remove trailing newline
    if output.ends_with('\n') {
        output.pop();
    }

    output
}

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

    fn setup_test_skill() -> TempDir {
        let temp = TempDir::new().expect("failed to create temp dir");
        let skill_dir = temp.path();

        fs::write(
            skill_dir.join("SKILL.md"),
            "---\nname: test-skill\n---\n# Test",
        )
        .expect("write");

        fs::create_dir_all(skill_dir.join("docs")).expect("mkdir");
        fs::write(skill_dir.join("docs").join("guide.md"), "# Guide").expect("write");

        temp
    }

    #[test]
    fn test_format_tree_output() {
        let entries = vec![
            TreeEntry {
                path: PathBuf::from("docs"),
                depth: 0,
                is_dir: true,
                file_count: None,
                is_last: false,
            },
            TreeEntry {
                path: PathBuf::from("docs/guide.md"),
                depth: 1,
                is_dir: false,
                file_count: None,
                is_last: true,
            },
            TreeEntry {
                path: PathBuf::from("README.md"),
                depth: 0,
                is_dir: false,
                file_count: None,
                is_last: true,
            },
        ];

        let output = format_tree("my-skill", &entries, 100);
        assert!(output.contains("my-skill/"));
        assert!(output.contains("docs"));
        assert!(output.contains("guide.md"));
        assert!(output.contains("README.md"));
    }

    #[test]
    fn test_format_tree_with_limit() {
        let entries: Vec<TreeEntry> = (0..10)
            .map(|i| TreeEntry {
                path: PathBuf::from(format!("file{}.md", i)),
                depth: 0,
                is_dir: false,
                file_count: None,
                is_last: i == 9,
            })
            .collect();

        let output = format_tree("skill", &entries, 3);
        assert!(output.contains("file0.md"));
        assert!(output.contains("file1.md"));
        assert!(output.contains("file2.md"));
        assert!(output.contains("... (7 more)"));
        assert!(!output.contains("file9.md"));
    }

    #[test]
    fn test_mark_last_entries() {
        let mut entries = vec![
            TreeEntry {
                path: PathBuf::from("a"),
                depth: 0,
                is_dir: false,
                file_count: None,
                is_last: false,
            },
            TreeEntry {
                path: PathBuf::from("b"),
                depth: 0,
                is_dir: false,
                file_count: None,
                is_last: false,
            },
            TreeEntry {
                path: PathBuf::from("c"),
                depth: 0,
                is_dir: false,
                file_count: None,
                is_last: false,
            },
        ];

        mark_last_entries(&mut entries);
        assert!(!entries[0].is_last);
        assert!(!entries[1].is_last);
        assert!(entries[2].is_last);
    }

    #[test]
    fn test_count_files_in_dir() {
        let temp = setup_test_skill();

        let count = count_files_in_dir(temp.path(), &None).expect("failed to count files");
        assert!(count >= 2); // At least SKILL.md and docs/guide.md
    }

    #[test]
    fn test_count_files_with_pattern() {
        let temp = setup_test_skill();
        let pattern = glob::Pattern::new("*.md").expect("invalid pattern");

        let count = count_files_in_dir(temp.path(), &Some(pattern)).expect("failed to count files");
        assert!(count >= 2); // .md files only
    }
}