skillcask 0.5.0

A lockfile-first package manager for AI agent skills (SKILL.md), backed by Composer repositories
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! On-disk layout: the store, agent links, the managed `.gitignore` block, the git index.

use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
use std::process::Command;

use crate::bail;
use crate::error::{Error, IO, MANIFEST, Result};
use crate::scope::Scope;
use crate::skill::SKILL_MD;

pub const STORE: &str = ".agents/skills";
const BEGIN: &str = "# >>> skillcask managed block, regenerated by skillcask";
const END: &str = "# <<< skillcask managed block";
/// Marks a directory copied in place of a link (Windows without symlink permission).
pub const COPY_MARKER: &str = ".skillcask-copy";
/// Exec bits of installed files as `<skill>/<path>` lines, for filesystems without them (Windows).
const MODES: &str = ".skillcask-modes";
const TMP: &str = ".skillcask-tmp-";
const OLD: &str = ".skillcask-old-";
/// `<store>/.skillcask-run-<pid>`, locked while that run lives: temp dirs named with its pid are its own.
const RUN: &str = ".skillcask-run-";

static RUNS: std::sync::Mutex<Vec<(PathBuf, std::fs::File)>> = std::sync::Mutex::new(Vec::new());

/// Nearest ancestor holding `skills.toml`, else the current directory.
pub fn find_root() -> Result<PathBuf> {
    let cwd = std::env::current_dir()?;
    let root = cwd.ancestors().find(|d| d.join(crate::manifest::FILE).is_file()).unwrap_or(&cwd);
    check_root(root)?;
    Ok(root.to_path_buf())
}

/// Refuses home and the global config dir as a project root: both belong to `--global`, and
/// `~/.gitignore` is often the user's global excludes file.
pub fn check_root(root: &Path) -> Result<()> {
    let canon = |p: &Path| std::fs::canonicalize(p).ok();
    let Some(r) = canon(root) else { return Ok(()) };
    if crate::scope::home().and_then(|h| canon(&h)).as_ref() == Some(&r) {
        return Err(Error::new(MANIFEST, "the home directory is the global scope, not a project")
            .hint("manage personal skills with --global, e.g. skillcask --global install"));
    }
    if Scope::global().ok().and_then(|g| canon(&g.config)).as_ref() == Some(&r) {
        return Err(Error::new(MANIFEST, format!("{} is the global config directory, not a project", root.display()))
            .hint("manage personal skills with --global, e.g. skillcask --global install"));
    }
    Ok(())
}

pub fn store_dir(s: &Scope, name: &str) -> PathBuf {
    s.root.join(STORE).join(name)
}

/// Skill directories in the store, excluding temp dirs.
pub fn store_names(s: &Scope) -> Result<Vec<String>> {
    let mut out = Vec::new();
    match std::fs::read_dir(s.root.join(STORE)) {
        Ok(rd) => {
            for e in rd {
                let e = e?;
                let name = e.file_name().to_string_lossy().into_owned();
                if !name.starts_with('.') && e.path().join(SKILL_MD).is_file() {
                    out.push(name);
                }
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(e.into()),
    }
    out.sort();
    Ok(out)
}

/// Refuses when `sub` or any of its parents below `root` is a symlink. A repository can commit
/// `.agents/skills -> ~/.config`, and skillcask would then write and delete outside the project.
/// Skipped in the global scope: home belongs to the user, and dotfile managers symlink `~/.claude`.
pub fn no_symlink(s: &Scope, sub: &str) -> Result<()> {
    if s.global {
        return Ok(());
    }
    let mut p = s.root.clone();
    for c in Path::new(sub).components() {
        p.push(c);
        if p.symlink_metadata().is_ok_and(|m| m.file_type().is_symlink()) {
            bail!(
                MANIFEST,
                "{} is a symlink; skillcask only writes inside the project, replace it with a real file or directory",
                rel(&s.root, &p)
            );
        }
    }
    Ok(())
}

/// Writes through a temp file and a rename in the same dir, so an interrupted write leaves the old
/// file or the new one. A symlinked file (dotfiles) is written at its target, keeping the link.
pub fn write_atomic(path: &Path, text: &str) -> Result<()> {
    use std::io::Write;
    let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
    std::fs::create_dir_all(dir)?;
    let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    let mut tmp = tempfile::Builder::new().prefix(&format!(".{name}{TMP}")).tempfile_in(dir)?;
    tmp.write_all(text.as_bytes())?;
    match std::fs::metadata(&path) {
        Ok(m) => tmp.as_file().set_permissions(m.permissions())?,
        #[cfg(unix)]
        Err(_) => {
            use std::os::unix::fs::PermissionsExt;
            tmp.as_file().set_permissions(std::fs::Permissions::from_mode(0o644))?
        }
        #[cfg(not(unix))]
        Err(_) => {}
    }
    tmp.persist(&path).map_err(|e| e.error)?;
    Ok(())
}

/// A sibling temp dir in the store, so the final rename stays on one filesystem.
pub fn temp_dir(s: &Scope) -> Result<tempfile::TempDir> {
    no_symlink(s, STORE)?;
    let store = s.root.join(STORE);
    std::fs::create_dir_all(&store)?;
    let mut runs = RUNS.lock().unwrap_or_else(|e| e.into_inner());
    if !runs.iter().any(|(p, _)| *p == store) {
        // No live run has our pid, so whatever is there is stale, and a planted symlink must not
        // make the create truncate its target.
        let path = store.join(format!("{RUN}{}", std::process::id()));
        match std::fs::remove_file(&path) {
            Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
            _ => {}
        }
        let f = std::fs::File::create_new(path)?;
        f.lock()?;
        runs.push((store.clone(), f));
    }
    Ok(tempfile::Builder::new().prefix(&format!("{TMP}{}-", std::process::id())).tempdir_in(store)?)
}

/// Copies `src` into a fresh temp dir, then swaps it into the store by rename.
pub fn place(s: &Scope, name: &str, src: &Path) -> Result<()> {
    let staged = temp_dir(s)?;
    copy_dir(src, staged.path())?;
    let dest = store_dir(s, name);
    let old = s.root.join(STORE).join(format!("{OLD}{name}-{}", std::process::id()));
    if old.symlink_metadata().is_ok() {
        std::fs::remove_dir_all(&old)?;
    }
    // symlink_metadata: a dangling link must be moved away too, and exists() follows links.
    if dest.symlink_metadata().is_ok() {
        std::fs::rename(&dest, &old)?;
    }
    let staged = staged.keep();
    if let Err(e) = std::fs::rename(&staged, &dest) {
        if old.symlink_metadata().is_ok() {
            let _ = std::fs::rename(&old, &dest);
        }
        let _ = std::fs::remove_dir_all(&staged);
        return Err(e.into());
    }
    if old.symlink_metadata().is_ok() {
        std::fs::remove_dir_all(&old)?;
    }
    Ok(())
}

/// Removes temp dirs that a crashed or interrupted run left in the store, except `keep`.
pub fn clean_leftovers(s: &Scope, keep: &[&Path]) -> Result<()> {
    let store = s.root.join(STORE);
    let Ok(rd) = std::fs::read_dir(&store) else { return Ok(()) };
    let me = std::process::id().to_string();
    // The run lock of `pid` is free: no live process owns its dirs.
    let gone = |pid: &str| std::fs::File::open(store.join(format!("{RUN}{pid}"))).ok().map(|f| f.try_lock().is_ok());
    let mut runs = Vec::new();
    for e in rd.flatten() {
        let n = e.file_name().to_string_lossy().into_owned();
        let p = e.path();
        if let Some(pid) = n.strip_prefix(RUN) {
            if pid != me && gone(pid) == Some(true) {
                runs.push(p);
            }
            continue;
        }
        let pid = match (n.strip_prefix(TMP), n.strip_prefix(OLD)) {
            (Some(rest), _) => rest.split('-').next(),
            (_, Some(rest)) => rest.rsplit('-').next(),
            _ => continue,
        };
        if keep.contains(&p.as_path()) || pid == Some(me.as_str()) {
            continue;
        }
        // Without a run lock (left by an older skillcask), only an old one is surely not in use.
        let stale = || e.metadata().and_then(|m| m.modified()).is_ok_and(|t| t.elapsed().is_ok_and(|age| age.as_secs() > 3600));
        if pid.and_then(gone).unwrap_or_else(stale) {
            if e.file_type()?.is_dir() { std::fs::remove_dir_all(p)? } else { std::fs::remove_file(p)? }
        }
    }
    for p in runs {
        std::fs::remove_file(p)?;
    }
    Ok(())
}

pub fn copy_dir(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst)?;
    for e in std::fs::read_dir(src)? {
        let e = e?;
        let to = dst.join(e.file_name());
        if e.file_type()?.is_dir() {
            copy_dir(&e.path(), &to)?;
        } else {
            std::fs::copy(e.path(), &to)?;
        }
    }
    Ok(())
}

/// Relative link from `<at>/<name>` to `<source>/<name>`, e.g. `../../.agents/skills/<name>` for
/// `.claude/skills`; absolute in the global scope, where `~/.claude` may be a symlink into dotfiles.
/// Built segment by segment: Windows does not resolve `/` in link targets.
pub fn link_target(s: &Scope, at: &str, source: &str, name: &str) -> PathBuf {
    if s.global {
        let mut p = s.root.clone();
        p.extend(source.split('/'));
        p.push(name);
        return p;
    }
    let depth = Path::new(at).components().count();
    let mut p: PathBuf = std::iter::repeat_n("..", depth).collect();
    p.extend(source.split('/'));
    p.push(name);
    p
}

#[derive(Debug, PartialEq)]
pub enum LinkState {
    Ok,
    Missing,
    /// A symlink pointing elsewhere, or a stale copy.
    Wrong,
    /// A real file or directory not created by skillcask.
    Foreign,
}

/// In home, `~/.claude/skills -> ~/.agents/skills` is common: the entry then is the store dir itself.
fn is_store_itself(s: &Scope, at: &str, name: &str) -> bool {
    let path = s.root.join(at).join(name);
    s.global
        && path.symlink_metadata().is_ok_and(|m| !m.file_type().is_symlink())
        && matches!((std::fs::canonicalize(&path), std::fs::canonicalize(store_dir(s, name))), (Ok(a), Ok(b)) if a == b)
}

pub fn link_state(s: &Scope, at: &str, source: &str, name: &str) -> LinkState {
    let path = s.root.join(at).join(name);
    let Ok(meta) = path.symlink_metadata() else { return LinkState::Missing };
    if at != STORE && is_store_itself(s, at, name) {
        return LinkState::Ok;
    }
    if meta.file_type().is_symlink() {
        let to_store = if s.global {
            matches!((std::fs::canonicalize(&path), std::fs::canonicalize(s.root.join(source).join(name))), (Ok(a), Ok(b)) if a == b)
        } else {
            std::fs::read_link(&path).is_ok_and(|t| t == link_target(s, at, source, name))
        };
        let ok = to_store && path.join(SKILL_MD).is_file();
        return if ok { LinkState::Ok } else { LinkState::Wrong };
    }
    if meta.is_dir() && path.join(COPY_MARKER).is_file() {
        let hash = |p: &Path| {
            crate::skill::scan_dir(p).ok().map(|mut e| {
                e.retain(|f| f.path != COPY_MARKER);
                crate::skill::tree_hash(&e)
            })
        };
        let fresh = hash(&s.root.join(source).join(name));
        return if fresh.is_some() && fresh == hash(&path) { LinkState::Ok } else { LinkState::Wrong };
    }
    LinkState::Foreign
}

/// Whether the symlink at `path` leads under `<root>/<dir>`, also when it dangles.
pub fn points_into(s: &Scope, path: &Path, dir: &str) -> bool {
    let base = s.root.join(dir);
    if let (Ok(a), Ok(b)) = (std::fs::canonicalize(path), std::fs::canonicalize(&base))
        && a.starts_with(b)
    {
        return true;
    }
    let Ok(target) = std::fs::read_link(path) else { return false };
    let mut p = path.parent().map(Path::to_path_buf).unwrap_or_default();
    for c in target.components() {
        match c {
            Component::ParentDir => {
                p.pop();
            }
            Component::CurDir => {}
            c => p.push(c),
        }
    }
    p.starts_with(base)
}

fn force_copy() -> bool {
    std::env::var("SKILLCASK_LINK_MODE").is_ok_and(|v| v == "copy")
}

/// Creates or repairs `<at>/<name>` pointing to `<source>/<name>`. Returns true when a copy was
/// made instead of a link.
pub fn link(s: &Scope, at: &str, source: &str, name: &str) -> Result<bool> {
    let path = s.root.join(at).join(name);
    match link_state(s, at, source, name) {
        LinkState::Ok => return Ok(!is_store_itself(s, at, name) && path.symlink_metadata().is_ok_and(|m| !m.file_type().is_symlink())),
        LinkState::Foreign => bail!(MANIFEST, "{} exists and was not created by skillcask; move it away", s.show(&format!("{at}/{name}"))),
        LinkState::Wrong => unlink(s, at, name)?,
        LinkState::Missing => {}
    }
    std::fs::create_dir_all(s.root.join(at))?;
    if !force_copy() {
        match symlink(&link_target(s, at, source, name), &path) {
            Ok(()) => return Ok(false),
            Err(e) if !cfg!(windows) => return Err(e.into()),
            Err(_) => {}
        }
    }
    copy_dir(&s.root.join(source).join(name), &path)?;
    std::fs::write(path.join(COPY_MARKER), "")?;
    Ok(true)
}

/// Project skills: directories with a SKILL.md under `local` (default `.skills`).
pub fn local_names(s: &Scope, local: &str) -> Result<BTreeSet<String>> {
    let mut out = BTreeSet::new();
    if s.global {
        return Ok(out);
    }
    let Ok(rd) = std::fs::read_dir(s.root.join(local)) else { return Ok(out) };
    for e in rd {
        let e = e?;
        let name = e.file_name().to_string_lossy().into_owned();
        if name.starts_with('.') || !e.path().join(SKILL_MD).is_file() {
            continue;
        }
        if !crate::skill::valid_name(&name) {
            bail!(MANIFEST, "{local}/{name}: skill directory names must match [a-z0-9][a-z0-9-]*");
        }
        out.insert(name);
    }
    Ok(out)
}

/// Store links (or copies) of project skills that are gone from `local`.
pub fn stale_local_links(s: &Scope, local: &str, live: &BTreeSet<String>) -> Result<Vec<String>> {
    if s.global {
        return Ok(Vec::new());
    }
    let block = read_block(s)?;
    let Ok(rd) = std::fs::read_dir(s.root.join(STORE)) else { return Ok(Vec::new()) };
    Ok(rd
        .flatten()
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| !live.contains(n) && made_by_skillcask(s, STORE, local, n, &block))
        .collect())
}

/// `<at>/<name>` is a link skillcask made to `<source>/<name>`, or a copy the block lists. A
/// package or a user may ship the copy marker, so the marker alone proves nothing.
pub fn made_by_skillcask(s: &Scope, at: &str, source: &str, name: &str, block: &[String]) -> bool {
    let path = s.root.join(at).join(name);
    std::fs::read_link(&path).is_ok_and(|t| t == link_target(s, at, source, name))
        || (block.contains(&format!("/{at}/{name}")) && path.join(COPY_MARKER).is_file())
}

#[cfg(unix)]
fn symlink(target: &Path, at: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, at)
}

#[cfg(windows)]
fn symlink(target: &Path, at: &Path) -> std::io::Result<()> {
    std::os::windows::fs::symlink_dir(target, at)
}

/// Removes a link or a copy made by skillcask; leaves anything else alone.
pub fn unlink(s: &Scope, at: &str, name: &str) -> Result<()> {
    let path = s.root.join(at).join(name);
    let Ok(meta) = path.symlink_metadata() else { return Ok(()) };
    if at != STORE && is_store_itself(s, at, name) {
        return Ok(());
    }
    if meta.file_type().is_symlink() {
        std::fs::remove_file(&path).or_else(|_| std::fs::remove_dir(&path))?;
    } else if meta.is_dir() && path.join(COPY_MARKER).is_file() {
        std::fs::remove_dir_all(&path)?;
    }
    Ok(())
}

pub fn rel(root: &Path, p: &Path) -> String {
    p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/")
}

/// Lines of the managed block: store dirs and links of locked skills, plus copies of hand-written ones.
pub fn block_lines(managed: &BTreeSet<String>, targets: &[String], copies: &BTreeSet<String>) -> Vec<String> {
    let mut lines = BTreeSet::new();
    for n in managed {
        lines.insert(format!("/{STORE}/{n}/"));
        for t in targets {
            lines.insert(format!("/{t}/{n}"));
        }
    }
    lines.extend(copies.iter().cloned());
    // The modes file, the record, temp dirs and temp files (`write_atomic`) a crashed run left behind.
    if !lines.is_empty() {
        lines.insert(format!("/{STORE}/.skillcask-*"));
        lines.insert(format!("/.*{TMP}*"));
    }
    lines.into_iter().collect()
}

pub fn read_modes(s: &Scope) -> BTreeSet<String> {
    std::fs::read_to_string(s.root.join(STORE).join(MODES)).unwrap_or_default().lines().map(String::from).collect()
}

/// Only written where the filesystem cannot keep exec bits itself.
pub fn write_modes(s: &Scope, modes: &BTreeSet<String>) -> Result<()> {
    if cfg!(unix) {
        return Ok(());
    }
    let path = s.root.join(STORE).join(MODES);
    if modes.is_empty() {
        if path.exists() {
            std::fs::remove_file(path)?;
        }
        return Ok(());
    }
    let text: String = modes.iter().map(|l| format!("{l}\n")).collect();
    if std::fs::read_to_string(&path).ok().as_deref() != Some(text.as_str()) {
        std::fs::write(path, text)?;
    }
    Ok(())
}

/// `.gitignore` split into lines outside the block, the index of the first block, and block lines.
struct Gitignore {
    text: String,
    eol: &'static str,
    kept: Vec<String>,
    at: Option<usize>,
    block: Vec<String>,
}

const INSTALLED: &str = ".skillcask-installed";

/// In global it sits next to the store, not in the config dir: that one may be synced between
/// machines, and a synced list would claim hand-written skills on another one.
fn ignore_file(s: &Scope) -> PathBuf {
    if s.global { s.root.join(STORE).join(INSTALLED) } else { s.root.join(".gitignore") }
}

/// The file holding the managed block, as messages name it.
pub fn block_file(s: &Scope) -> String {
    if s.global { s.show(&format!("{STORE}/{INSTALLED}")) } else { ".gitignore".into() }
}

/// Project scope: what skillcask placed in the store on this machine, unlike the committed block.
/// The same file and format as the global managed list, holding only store lines.
fn record_file(s: &Scope) -> (PathBuf, String) {
    (s.root.join(STORE).join(INSTALLED), s.show(&format!("{STORE}/{INSTALLED}")))
}

fn read_gitignore(s: &Scope) -> Result<Gitignore> {
    read_block_file(&ignore_file(s), &block_file(s))
}

fn read_block_file(path: &Path, shown: &str) -> Result<Gitignore> {
    // Treating an unreadable file as empty would rewrite it with only the block.
    let text = match std::fs::read_to_string(path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => bail!(IO, "{shown}: {e}; skillcask only rewrites a readable UTF-8 file"),
    };
    let eol = if text.split_once('\n').is_some_and(|(l, _)| l.ends_with('\r')) { "\r\n" } else { "\n" };
    let (mut kept, mut block) = (Vec::new(), Vec::new());
    let mut inside = false;
    let mut at = None;
    for l in text.lines() {
        match l.trim_end() {
            BEGIN => {
                inside = true;
                at.get_or_insert(kept.len());
            }
            END if inside => inside = false,
            b if inside => {
                if !b.is_empty() {
                    block.push(b.to_string());
                }
            }
            _ => kept.push(l.to_string()),
        }
    }
    // Without END every user line after BEGIN would count as managed and be dropped on rewrite.
    if inside {
        bail!(MANIFEST, "{shown}: the skillcask block has no end line {END:?}; restore it by hand");
    }
    Ok(Gitignore { text, eol, kept, at, block })
}

pub fn read_block(s: &Scope) -> Result<Vec<String>> {
    Ok(read_gitignore(s)?.block)
}

/// Skill names that the current block marks as managed.
pub fn block_managed(s: &Scope) -> Result<BTreeSet<String>> {
    Ok(store_lines(&read_block(s)?))
}

fn store_lines(block: &[String]) -> BTreeSet<String> {
    let prefix = format!("/{STORE}/");
    // The block is user-editable; only plain skill names may reach remove_dir_all.
    block
        .iter()
        .filter_map(|l| l.strip_prefix(&prefix)?.strip_suffix('/'))
        .filter(|n| crate::skill::valid_name(n))
        .map(String::from)
        .collect()
}

/// Skills that skillcask installed on this machine. In global that is the managed list itself.
/// `None` in a project that 0.1.2 installed: it wrote no record.
pub fn installed_here(s: &Scope) -> Result<Option<BTreeSet<String>>> {
    if s.global {
        return block_managed(s).map(Some);
    }
    let (path, shown) = record_file(s);
    if path.symlink_metadata().is_err() {
        return Ok(None);
    }
    Ok(Some(store_lines(&read_block_file(&path, &shown)?.block)))
}

/// Every `tree-sha256` that skills.lock had in the git history; empty outside a repository.
pub fn lock_history_hashes(s: &Scope) -> BTreeSet<String> {
    let o = match git(s).args(["log", "-p", "--format=", "--", crate::lock::FILE]).output() {
        Ok(o) if o.status.success() => o,
        _ => return BTreeSet::new(),
    };
    String::from_utf8_lossy(&o.stdout)
        .split("tree-sha256 = \"")
        .skip(1)
        .filter_map(|r| r.get(..64).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit()) && r[64..].starts_with('"')))
        .map(String::from)
        .collect()
}

/// Records `names` as installed on this machine; in global `write_block` already does.
pub fn write_installed_here(s: &Scope, names: &BTreeSet<String>) -> Result<()> {
    if s.global {
        return Ok(());
    }
    no_symlink(s, STORE)?;
    let (path, shown) = record_file(s);
    let lines: Vec<String> = names.iter().map(|n| format!("/{STORE}/{n}/")).collect();
    write_block_file(&path, &shown, &lines)?;
    Ok(())
}

/// Rewrites the block in place (or appends it); drops it when empty. Returns true if the file changed.
pub fn write_block(s: &Scope, lines: &[String]) -> Result<bool> {
    no_symlink(s, ".gitignore")?;
    write_block_file(&ignore_file(s), &block_file(s), lines)
}

fn write_block_file(path: &Path, shown: &str, lines: &[String]) -> Result<bool> {
    let Gitignore { text, eol, mut kept, at, .. } = read_block_file(path, shown)?;
    let mut block = Vec::new();
    if !lines.is_empty() {
        block.push(BEGIN.to_string());
        block.extend(lines.iter().cloned());
        block.push(END.to_string());
    }
    let at = match at {
        Some(i) => i,
        None => {
            if !block.is_empty() && kept.last().is_some_and(|l| !l.is_empty()) {
                kept.push(String::new());
            }
            kept.len()
        }
    };
    kept.splice(at..at, block);
    while kept.last().is_some_and(String::is_empty) {
        kept.pop();
    }
    let new = if kept.is_empty() { String::new() } else { kept.join(eol) + eol };
    if new == text || (new.is_empty() && !path.exists()) {
        return Ok(false);
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir)?;
    }
    std::fs::write(path, new)?;
    Ok(true)
}

/// Git for the project's own repository: inherited GIT_DIR and the like would point it at another,
/// and paths are literal, not globs.
fn git(s: &Scope) -> Command {
    let mut c = Command::new("git");
    c.arg("-C").arg(&s.root).arg("--literal-pathspecs");
    c.env_remove("GIT_DIR").env_remove("GIT_INDEX_FILE").env_remove("GIT_WORK_TREE");
    c
}

/// Tracked paths among `paths` (relative, `/`-separated). Empty outside a git work tree.
pub fn git_tracked(s: &Scope, paths: &[String]) -> Vec<String> {
    if s.global || paths.is_empty() {
        return Vec::new();
    }
    let out = git(s).args(["ls-files", "-z", "--"]).args(paths).output();
    match out {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).split('\0').filter(|s| !s.is_empty()).map(String::from).collect(),
        _ => Vec::new(),
    }
}

/// `git rm --cached`: drops paths from the index, never from the working tree. `-f` because
/// staged changes would otherwise stop it; with `--cached` it still keeps the files.
pub fn git_untrack(s: &Scope, paths: &[String]) -> Result<()> {
    if s.global || paths.is_empty() {
        return Ok(());
    }
    let st = git(s).args(["rm", "--cached", "-f", "-r", "-q", "--"]).args(paths).status()?;
    if !st.success() {
        bail!(IO, "git rm --cached failed for {}", paths.join(", "));
    }
    Ok(())
}

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

    #[test]
    fn relative_link_target() {
        let s = Scope::project(PathBuf::new());
        assert_eq!(link_target(&s, ".claude/skills", STORE, "x"), Path::new("../../.agents/skills/x"));
        assert_eq!(link_target(&s, "skills", STORE, "x"), Path::new("../.agents/skills/x"));
        assert_eq!(link_target(&s, STORE, ".skills", "x"), Path::new("../../.skills/x"));
    }

    #[test]
    fn gitignore_block_rewrite() {
        let dir = tempfile::tempdir().unwrap();
        let s = Scope::project(dir.path().to_path_buf());
        let root = &s.root;
        std::fs::write(root.join(".gitignore"), "/target\n").unwrap();
        let managed: BTreeSet<String> = ["b".to_string(), "a".to_string()].into();
        let lines = block_lines(&managed, &[".claude/skills".into()], &BTreeSet::new());
        assert!(write_block(&s, &lines).unwrap());
        let text = std::fs::read_to_string(root.join(".gitignore")).unwrap();
        assert_eq!(
            text,
            format!(
                "/target\n\n{BEGIN}\n/.*.skillcask-tmp-*\n/.agents/skills/.skillcask-*\n/.agents/skills/a/\n/.agents/skills/b/\n/.claude/skills/a\n/.claude/skills/b\n{END}\n"
            )
        );
        assert!(!write_block(&s, &lines).unwrap());
        assert_eq!(block_managed(&s).unwrap(), managed);
        std::fs::write(root.join(".gitignore"), format!("{BEGIN}\n/.agents/skills/../../home/\n/.agents/skills/ok/\n{END}\n")).unwrap();
        assert_eq!(block_managed(&s).unwrap(), BTreeSet::from(["ok".to_string()]), "traversal in the editable block is ignored");
        std::fs::write(root.join(".gitignore"), &text).unwrap();

        std::fs::write(root.join(".gitignore"), format!("{text}/after\n")).unwrap();
        write_block(&s, &lines[2..3]).unwrap();
        let text = std::fs::read_to_string(root.join(".gitignore")).unwrap();
        assert_eq!(text, format!("/target\n\n{BEGIN}\n/.agents/skills/a/\n{END}\n/after\n"));
        write_block(&s, &[]).unwrap();
        assert_eq!(std::fs::read_to_string(root.join(".gitignore")).unwrap(), "/target\n\n/after\n");
    }

    #[test]
    fn place_survives_a_stale_old_dir() {
        let dir = tempfile::tempdir().unwrap();
        let s = Scope::project(dir.path().to_path_buf());
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src).unwrap();
        std::fs::write(src.join(SKILL_MD), "new").unwrap();
        std::fs::create_dir_all(store_dir(&s, "x")).unwrap();
        let stale = s.root.join(STORE).join(format!("{OLD}x-{}", std::process::id()));
        std::fs::create_dir_all(&stale).unwrap();
        std::fs::write(stale.join("f"), "").unwrap();
        place(&s, "x", &src).unwrap();
        assert_eq!(std::fs::read_to_string(store_dir(&s, "x").join(SKILL_MD)).unwrap(), "new");
        assert!(!stale.exists());
    }

    #[cfg(unix)]
    #[test]
    fn links_and_refuses_foreign() {
        let dir = tempfile::tempdir().unwrap();
        let s = Scope::project(dir.path().to_path_buf());
        let root = &s.root;
        std::fs::create_dir_all(store_dir(&s, "x")).unwrap();
        std::fs::write(store_dir(&s, "x").join(SKILL_MD), "s").unwrap();
        assert_eq!(link_state(&s, ".claude/skills", STORE, "x"), LinkState::Missing);
        assert!(!link(&s, ".claude/skills", STORE, "x").unwrap());
        assert_eq!(link_state(&s, ".claude/skills", STORE, "x"), LinkState::Ok);
        assert_eq!(std::fs::read_to_string(root.join(".claude/skills/x/SKILL.md")).unwrap(), "s");
        std::fs::create_dir_all(root.join(".junie/skills/x")).unwrap();
        assert!(link(&s, ".junie/skills", STORE, "x").is_err());
        unlink(&s, ".claude/skills", "x").unwrap();
        assert_eq!(link_state(&s, ".claude/skills", STORE, "x"), LinkState::Missing);
    }

    /// A repository may commit `.skillcask-run-<pid>` symlinks; creating the run lock once
    /// truncated their targets.
    #[cfg(unix)]
    #[test]
    fn a_planted_run_lock_symlink_leaves_its_target_alone() {
        let dir = tempfile::tempdir().unwrap();
        let s = Scope::project(dir.path().to_path_buf());
        let victim = dir.path().join("victim");
        std::fs::write(&victim, "precious").unwrap();
        std::fs::create_dir_all(dir.path().join(STORE)).unwrap();
        std::os::unix::fs::symlink(&victim, dir.path().join(STORE).join(format!("{RUN}{}", std::process::id()))).unwrap();
        temp_dir(&s).unwrap();
        assert_eq!(std::fs::read_to_string(&victim).unwrap(), "precious");
    }

    fn global_scope(home: &Path) -> Scope {
        Scope { root: home.to_path_buf(), config: home.join(".config/skillcask"), global: true }
    }

    #[cfg(unix)]
    #[test]
    fn global_links_are_absolute_and_survive_symlinked_parents() {
        let home = tempfile::tempdir().unwrap();
        let s = global_scope(home.path());
        std::fs::create_dir_all(store_dir(&s, "x")).unwrap();
        std::fs::write(store_dir(&s, "x").join(SKILL_MD), "s").unwrap();
        let dotfiles = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink(dotfiles.path(), home.path().join(".claude")).unwrap();
        no_symlink(&s, ".claude/skills").unwrap();
        assert!(!link(&s, ".claude/skills", STORE, "x").unwrap());
        assert_eq!(std::fs::read_link(home.path().join(".claude/skills/x")).unwrap(), home.path().join(".agents/skills/x"));
        assert_eq!(link_state(&s, ".claude/skills", STORE, "x"), LinkState::Ok);
        assert_eq!(std::fs::read_to_string(dotfiles.path().join("skills/x/SKILL.md")).unwrap(), "s");

        // A relative link made by another tool that reaches the same store dir is fine too.
        std::fs::create_dir_all(home.path().join(".junie/skills")).unwrap();
        std::os::unix::fs::symlink("../../.agents/skills/x", home.path().join(".junie/skills/x")).unwrap();
        assert_eq!(link_state(&s, ".junie/skills", STORE, "x"), LinkState::Ok);
    }

    #[cfg(unix)]
    #[test]
    fn global_target_symlinked_to_the_store_is_the_store() {
        let home = tempfile::tempdir().unwrap();
        let s = global_scope(home.path());
        std::fs::create_dir_all(store_dir(&s, "x")).unwrap();
        std::fs::write(store_dir(&s, "x").join(SKILL_MD), "s").unwrap();
        std::fs::create_dir_all(home.path().join(".claude")).unwrap();
        std::os::unix::fs::symlink("../.agents/skills", home.path().join(".claude/skills")).unwrap();
        assert_eq!(link_state(&s, ".claude/skills", STORE, "x"), LinkState::Ok);
        assert!(!link(&s, ".claude/skills", STORE, "x").unwrap());
        unlink(&s, ".claude/skills", "x").unwrap();
        assert!(store_dir(&s, "x").join(SKILL_MD).is_file());
        // A package may ship the copy marker; the store must still not be taken for a copy.
        std::fs::write(store_dir(&s, "x").join(COPY_MARKER), "").unwrap();
        unlink(&s, ".claude/skills", "x").unwrap();
        assert!(store_dir(&s, "x").join(SKILL_MD).is_file());
    }

    #[test]
    fn global_block_lives_in_the_store() {
        let home = tempfile::tempdir().unwrap();
        let s = global_scope(home.path());
        let managed: BTreeSet<String> = ["a".to_string()].into();
        assert!(write_block(&s, &block_lines(&managed, &[".claude/skills".into()], &BTreeSet::new())).unwrap());
        assert!(!home.path().join(".gitignore").exists());
        assert!(!s.config.exists(), "the config dir may be synced between machines; the managed list is machine-local");
        assert!(std::fs::read_to_string(home.path().join(".agents/skills/.skillcask-installed")).unwrap().contains("/.agents/skills/a/"));
        assert_eq!(block_managed(&s).unwrap(), managed);
        assert_eq!(store_names(&s).unwrap(), Vec::<String>::new());
        std::fs::write(ignore_file(&s), format!("{BEGIN}\n/.agents/skills/a/\n")).unwrap();
        let e = block_managed(&s).unwrap_err().to_string();
        assert!(e.contains("~/.agents/skills/.skillcask-installed: the skillcask block has no end line"), "{e}");
        assert!(git_tracked(&s, &["x".into()]).is_empty());
        std::fs::create_dir_all(home.path().join("p")).unwrap();
        std::fs::write(home.path().join("p/SKILL.md"), "").unwrap();
        assert!(local_names(&s, "").unwrap().is_empty(), "the global scope has no project skills");
    }
}