skillfile 1.4.2

Tool-agnostic AI skill & agent manager - the Brewfile for your AI tooling
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use std::io::Write as IoWrite;
use std::path::Path;

use skillfile_core::conflict::read_conflict;
use skillfile_core::error::SkillfileError;
use skillfile_core::lock::{lock_key, read_lock};
use skillfile_core::models::{short_sha, Entry};
use skillfile_core::parser::{find_entry_in, parse_manifest, MANIFEST_NAME};
use skillfile_core::progress;
use skillfile_deploy::paths::{installed_dir_files, installed_path};
use skillfile_sources::strategy::{content_file, is_dir_entry};
use skillfile_sources::sync::vendor_dir_for;

use crate::patch::walkdir;

fn diff_local_single(entry: &Entry, sha: &str, repo_root: &Path) -> Result<(), SkillfileError> {
    let manifest = crate::config::parse_and_resolve(&repo_root.join(MANIFEST_NAME))?;
    let vdir = vendor_dir_for(entry, repo_root);
    let cf = content_file(entry);
    if cf.is_empty() {
        return Err(SkillfileError::Manifest(format!(
            "'{}' is not cached — run `skillfile install` first",
            entry.name
        )));
    }
    let cache_file = vdir.join(&cf);
    if !cache_file.exists() {
        return Err(SkillfileError::Manifest(format!(
            "'{}' is not cached — run `skillfile install` first",
            entry.name
        )));
    }

    let dest = installed_path(entry, &manifest, repo_root)?;
    if !dest.exists() {
        return Err(SkillfileError::Manifest(format!(
            "'{}' is not installed — run `skillfile install` first",
            entry.name
        )));
    }

    let upstream = std::fs::read_to_string(&cache_file)?;
    let installed_text = std::fs::read_to_string(&dest)?;

    let diff_text = similar::TextDiff::from_lines(upstream.as_str(), installed_text.as_str());
    let formatted = diff_text
        .unified_diff()
        .context_radius(3)
        .header(
            &format!("a/{}.md (upstream sha={})", entry.name, short_sha(sha)),
            &format!("b/{}.md (installed)", entry.name),
        )
        .to_string();

    if formatted.is_empty() {
        println!("'{}' is clean — no local modifications", entry.name);
    } else {
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        out.write_all(formatted.as_bytes())?;
    }

    Ok(())
}

fn diff_local_dir(entry: &Entry, sha: &str, repo_root: &Path) -> Result<(), SkillfileError> {
    let manifest = crate::config::parse_and_resolve(&repo_root.join(MANIFEST_NAME))?;
    let vdir = vendor_dir_for(entry, repo_root);
    if !vdir.is_dir() {
        return Err(SkillfileError::Manifest(format!(
            "'{}' is not cached — run `skillfile install` first",
            entry.name
        )));
    }

    let installed = installed_dir_files(entry, &manifest, repo_root)?;
    if installed.is_empty() {
        return Err(SkillfileError::Manifest(format!(
            "'{}' is not installed — run `skillfile install` first",
            entry.name
        )));
    }

    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    let mut any_diff = false;

    for cache_file in walkdir(&vdir) {
        if cache_file.file_name().is_some_and(|n| n == ".meta") {
            continue;
        }
        let filename = match cache_file.strip_prefix(&vdir).ok().and_then(|p| p.to_str()) {
            Some(f) => f.to_string(),
            None => continue,
        };
        let Some(inst_path) = installed.get(&filename) else {
            continue;
        };
        if !inst_path.exists() {
            continue;
        }

        let original_text = std::fs::read_to_string(&cache_file)?;
        let installed_text = std::fs::read_to_string(inst_path)?;
        let diff_text =
            similar::TextDiff::from_lines(original_text.as_str(), installed_text.as_str());
        let formatted = diff_text
            .unified_diff()
            .context_radius(3)
            .header(
                &format!(
                    "a/{}/{filename} (upstream sha={})",
                    entry.name,
                    short_sha(sha)
                ),
                &format!("b/{}/{filename} (installed)", entry.name),
            )
            .to_string();

        if !formatted.is_empty() {
            any_diff = true;
            out.write_all(formatted.as_bytes())?;
        }
    }

    if !any_diff {
        println!("'{}' is clean — no local modifications", entry.name);
    }

    Ok(())
}

pub fn cmd_diff(name: &str, repo_root: &Path) -> Result<(), SkillfileError> {
    let manifest_path = repo_root.join(MANIFEST_NAME);
    let result = parse_manifest(&manifest_path)?;
    let entry = find_entry_in(name, &result.manifest)?;

    // Check if there's a pending conflict for this entry
    let conflict = read_conflict(repo_root)?;
    if let Some(ref c) = conflict {
        if c.entry == name {
            return diff_conflict(entry, c, repo_root);
        }
    }

    if entry.source_type() == "local" {
        println!("'{name}' is a local entry — nothing to diff");
        return Ok(());
    }

    let locked = read_lock(repo_root)?;
    let key = lock_key(entry);
    if !locked.contains_key(&key) {
        return Err(SkillfileError::Manifest(format!(
            "'{name}' is not locked — run `skillfile install` first"
        )));
    }
    let sha = locked[&key].sha.clone();

    if is_dir_entry(entry) {
        diff_local_dir(entry, &sha, repo_root)
    } else {
        diff_local_single(entry, &sha, repo_root)
    }
}

fn diff_conflict(
    entry: &Entry,
    conflict: &skillfile_core::models::ConflictState,
    _repo_root: &Path,
) -> Result<(), SkillfileError> {
    // Conflict mode: fetch old and new upstream, show upstream delta
    // This requires network access
    progress!(
        "  fetching upstream at old sha={} ...",
        short_sha(&conflict.old_sha)
    );
    let client = skillfile_sources::http::UreqClient::new();

    if is_dir_entry(entry) {
        diff_conflict_dir(entry, conflict, &client)?;
    } else {
        diff_conflict_single(entry, conflict, &client)?;
    }
    Ok(())
}

fn diff_conflict_single(
    entry: &Entry,
    conflict: &skillfile_core::models::ConflictState,
    client: &dyn skillfile_sources::http::HttpClient,
) -> Result<(), SkillfileError> {
    let old_content = skillfile_sources::sync::fetch_file_at_sha(client, entry, &conflict.old_sha)?;
    progress!("done");
    progress!(
        "  fetching upstream at new sha={} ...",
        short_sha(&conflict.new_sha)
    );
    let new_content = skillfile_sources::sync::fetch_file_at_sha(client, entry, &conflict.new_sha)?;
    progress!("done\n");

    let diff_text = similar::TextDiff::from_lines(old_content.as_str(), new_content.as_str());
    let formatted = diff_text
        .unified_diff()
        .context_radius(3)
        .header(
            &format!(
                "{}.md (old upstream sha={})",
                entry.name,
                short_sha(&conflict.old_sha)
            ),
            &format!(
                "{}.md (new upstream sha={})",
                entry.name,
                short_sha(&conflict.new_sha)
            ),
        )
        .to_string();

    if formatted.is_empty() {
        println!("No upstream changes detected (patch conflict may be due to local file drift).");
    } else {
        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        out.write_all(formatted.as_bytes())?;
    }
    Ok(())
}

fn diff_conflict_dir(
    entry: &Entry,
    conflict: &skillfile_core::models::ConflictState,
    client: &dyn skillfile_sources::http::HttpClient,
) -> Result<(), SkillfileError> {
    let old_files = skillfile_sources::sync::fetch_dir_at_sha(client, entry, &conflict.old_sha)?;
    progress!("done");
    progress!(
        "  fetching upstream at new sha={} ...",
        short_sha(&conflict.new_sha)
    );
    let new_files = skillfile_sources::sync::fetch_dir_at_sha(client, entry, &conflict.new_sha)?;
    progress!("done\n");

    let mut all_filenames: Vec<String> = old_files
        .keys()
        .chain(new_files.keys())
        .cloned()
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();
    all_filenames.sort();

    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    let mut any_diff = false;

    for filename in &all_filenames {
        let old_content = old_files.get(filename).map_or("", String::as_str);
        let new_content = new_files.get(filename).map_or("", String::as_str);
        let diff_text = similar::TextDiff::from_lines(old_content, new_content);
        let formatted = diff_text
            .unified_diff()
            .context_radius(3)
            .header(
                &format!(
                    "{}/{filename} (old upstream sha={})",
                    entry.name,
                    short_sha(&conflict.old_sha)
                ),
                &format!(
                    "{}/{filename} (new upstream sha={})",
                    entry.name,
                    short_sha(&conflict.new_sha)
                ),
            )
            .to_string();
        if !formatted.is_empty() {
            any_diff = true;
            out.write_all(formatted.as_bytes())?;
        }
    }

    if !any_diff {
        println!("No upstream changes detected (patch conflict may be due to local file drift).");
    }
    Ok(())
}

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

    fn write_manifest(dir: &Path, content: &str) {
        std::fs::write(dir.join(MANIFEST_NAME), content).unwrap();
    }

    fn write_lock_file(dir: &Path, content: &str) {
        std::fs::write(dir.join("Skillfile.lock"), content).unwrap();
    }

    fn make_lock_json(name: &str, entity_type: &str) -> String {
        format!(
            r#"{{
  "github/{entity_type}/{name}": {{
    "sha": "abc123def456abcdef",
    "raw_url": "https://raw.githubusercontent.com/owner/repo/abc123/test.md"
  }}
}}"#
        )
    }

    #[test]
    fn diff_no_manifest_errors() {
        let dir = tempfile::tempdir().unwrap();
        let result = cmd_diff("foo", dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn diff_local_entry_prints_message() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(dir.path(), "local  skill  skills/foo.md\n");
        // cmd_diff will print "local entry — nothing to diff"
        // Since it goes to stdout which we can't capture in unit tests easily,
        // just verify it doesn't error
        // The cmd_diff function looks up the entry in the manifest
        // We need the manifest to have the "foo" entry with local source
        let result = cmd_diff("foo", dir.path());
        // "foo" is not in the manifest (it's inferred as "foo" from "skills/foo.md")
        assert!(result.is_ok());
    }

    #[test]
    fn diff_not_locked_errors() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(dir.path(), "github  skill  owner/repo  skills/test.md\n");
        write_lock_file(dir.path(), "{}");
        let result = cmd_diff("test", dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not locked"));
    }

    #[test]
    fn diff_not_cached_errors() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  owner/repo  skills/test.md\n",
        );
        write_lock_file(dir.path(), &make_lock_json("test", "skill"));
        // no cache files
        let result = cmd_diff("test", dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not cached"));
    }

    #[test]
    fn diff_not_installed_errors() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  owner/repo  skills/test.md\n",
        );
        write_lock_file(dir.path(), &make_lock_json("test", "skill"));

        // Create cache but not installed
        let vdir = dir.path().join(".skillfile/cache/skills/test");
        std::fs::create_dir_all(&vdir).unwrap();
        std::fs::write(vdir.join("test.md"), "content\n").unwrap();

        let result = cmd_diff("test", dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not installed"));
    }

    #[test]
    fn diff_clean_shows_clean() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  owner/repo  skills/test.md\n",
        );
        write_lock_file(dir.path(), &make_lock_json("test", "skill"));

        let content = "# Test\n\nContent.\n";
        let vdir = dir.path().join(".skillfile/cache/skills/test");
        std::fs::create_dir_all(&vdir).unwrap();
        std::fs::write(vdir.join("test.md"), content).unwrap();

        let installed_dir = dir.path().join(".claude/skills");
        std::fs::create_dir_all(&installed_dir).unwrap();
        std::fs::write(installed_dir.join("test.md"), content).unwrap();

        // Should succeed (prints "is clean")
        let result = cmd_diff("test", dir.path());
        assert!(result.is_ok());
    }

    #[test]
    fn diff_modified_produces_output() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  owner/repo  skills/test.md\n",
        );
        write_lock_file(dir.path(), &make_lock_json("test", "skill"));

        let vdir = dir.path().join(".skillfile/cache/skills/test");
        std::fs::create_dir_all(&vdir).unwrap();
        std::fs::write(vdir.join("test.md"), "original\n").unwrap();

        let installed_dir = dir.path().join(".claude/skills");
        std::fs::create_dir_all(&installed_dir).unwrap();
        std::fs::write(installed_dir.join("test.md"), "modified\n").unwrap();

        // Should succeed (diff goes to stdout)
        let result = cmd_diff("test", dir.path());
        assert!(result.is_ok());
    }

    // -----------------------------------------------------------------------
    // Dir entry helpers
    // -----------------------------------------------------------------------

    /// Build a lock JSON string for a dir entry (path_in_repo has no .md suffix).
    fn make_dir_lock_json(name: &str, entity_type: &str) -> String {
        format!(
            r#"{{
  "github/{entity_type}/{name}": {{
    "sha": "abc123def456abcdef",
    "raw_url": "https://api.github.com/repos/owner/repo/contents/skills/{name}?ref=abc123def456abcdef"
  }}
}}"#
        )
    }

    struct DirContents<'a> {
        name: &'a str,
        file1: &'a str,
        file2: &'a str,
    }

    /// Create the vendor cache directory for a dir entry with two files.
    fn setup_dir_cache(dir: &Path, c: &DirContents<'_>) {
        let vdir = dir.join(format!(".skillfile/cache/skills/{}", c.name));
        std::fs::create_dir_all(&vdir).unwrap();
        std::fs::write(vdir.join("file1.md"), c.file1).unwrap();
        std::fs::write(vdir.join("file2.md"), c.file2).unwrap();
    }

    /// Create the installed dir for a dir entry under .claude/skills/<name>/
    /// (claude-code + local scope + skill entity type → Nested mode).
    fn setup_installed_dir(dir: &Path, c: &DirContents<'_>) {
        let installed = dir.join(format!(".claude/skills/{}", c.name));
        std::fs::create_dir_all(&installed).unwrap();
        std::fs::write(installed.join("file1.md"), c.file1).unwrap();
        std::fs::write(installed.join("file2.md"), c.file2).unwrap();
    }

    // -----------------------------------------------------------------------
    // diff_local_dir — entry name not found in manifest
    // -----------------------------------------------------------------------

    #[test]
    fn diff_entry_name_not_found() {
        let dir = tempfile::tempdir().unwrap();
        // Manifest has "my-dir" but we ask for "nonexistent"
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  my-dir  owner/repo  skills/my-dir  main\n",
        );
        write_lock_file(dir.path(), &make_dir_lock_json("my-dir", "skill"));

        let result = cmd_diff("nonexistent", dir.path());
        assert!(result.is_err());
        // find_entry_in produces an error message containing the name
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("nonexistent"),
            "error should mention the missing entry name: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // diff_local_dir — vendor cache missing → "not cached" error
    // -----------------------------------------------------------------------

    #[test]
    fn diff_dir_entry_not_cached() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  my-dir  owner/repo  skills/my-dir  main\n",
        );
        write_lock_file(dir.path(), &make_dir_lock_json("my-dir", "skill"));
        // No vendor cache directory created → is_dir_entry is true, vdir.is_dir() is false

        let result = cmd_diff("my-dir", dir.path());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("not cached"),
            "expected 'not cached' in error, got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // diff_local_dir — cache exists but no installed files → "not installed" error
    // -----------------------------------------------------------------------

    #[test]
    fn diff_dir_entry_not_installed() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  my-dir  owner/repo  skills/my-dir  main\n",
        );
        write_lock_file(dir.path(), &make_dir_lock_json("my-dir", "skill"));

        // Vendor cache exists with content
        setup_dir_cache(
            dir.path(),
            &DirContents {
                name: "my-dir",
                file1: "content1\n",
                file2: "content2\n",
            },
        );
        // But no installed dir → installed_dir_files returns empty map

        let result = cmd_diff("my-dir", dir.path());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("not installed"),
            "expected 'not installed' in error, got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // diff_local_dir — cache and installed files have identical content → clean
    // -----------------------------------------------------------------------

    #[test]
    fn diff_dir_entry_clean() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  my-dir  owner/repo  skills/my-dir  main\n",
        );
        write_lock_file(dir.path(), &make_dir_lock_json("my-dir", "skill"));

        let content = "# Skill content\n\nSame in both places.\n";
        let dc = DirContents {
            name: "my-dir",
            file1: content,
            file2: content,
        };
        setup_dir_cache(dir.path(), &dc);
        setup_installed_dir(dir.path(), &dc);

        // Should succeed: both cache and installed are identical → prints "is clean"
        let result = cmd_diff("my-dir", dir.path());
        assert!(result.is_ok(), "expected Ok but got: {result:?}");
    }

    // -----------------------------------------------------------------------
    // diff_local_dir — installed files differ from cache → produces diff output
    // -----------------------------------------------------------------------

    #[test]
    fn diff_dir_entry_modified() {
        let dir = tempfile::tempdir().unwrap();
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  my-dir  owner/repo  skills/my-dir  main\n",
        );
        write_lock_file(dir.path(), &make_dir_lock_json("my-dir", "skill"));

        // Cache has original content; installed has modified content for file1
        setup_dir_cache(
            dir.path(),
            &DirContents {
                name: "my-dir",
                file1: "original line\n",
                file2: "unchanged\n",
            },
        );
        setup_installed_dir(
            dir.path(),
            &DirContents {
                name: "my-dir",
                file1: "modified line\n",
                file2: "unchanged\n",
            },
        );

        // Should succeed: diff output is written to stdout (we just verify no error)
        let result = cmd_diff("my-dir", dir.path());
        assert!(result.is_ok(), "expected Ok but got: {result:?}");
    }

    // -----------------------------------------------------------------------
    // cmd_diff dispatching — github dir entry detected via is_dir_entry
    // -----------------------------------------------------------------------

    #[test]
    fn cmd_diff_dispatches_to_dir_path_for_dir_entry() {
        let dir = tempfile::tempdir().unwrap();
        // path_in_repo = "skills/my-dir" (no .md) → is_dir_entry returns true
        write_manifest(
            dir.path(),
            "install  claude-code  local\ngithub  skill  my-dir  owner/repo  skills/my-dir  main\n",
        );
        write_lock_file(dir.path(), &make_dir_lock_json("my-dir", "skill"));

        // Set up cache and installed with matching content so the dir path succeeds
        let content = "# Dir skill\n";
        let dc = DirContents {
            name: "my-dir",
            file1: content,
            file2: content,
        };
        setup_dir_cache(dir.path(), &dc);
        setup_installed_dir(dir.path(), &dc);

        // cmd_diff must route to diff_local_dir (not diff_local_single)
        // and succeed without error
        let result = cmd_diff("my-dir", dir.path());
        assert!(
            result.is_ok(),
            "expected Ok for dir entry dispatch: {result:?}"
        );
    }
}