agents-skills 0.28.1

A minimal, stable, easy-to-understand skill installer and manager for AI agents
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
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
//! High-level `Manager` facade: one-stop add/list/remove over an injectable [`Env`].
//!
//! The manager is pure data: it returns structured outcomes and never prints or exits;
//! the CLI layer (src/commands) is responsible for rendering.

use std::path::PathBuf;

use crate::core::agents::{AGENTS, Env, config_home, home, is_installed, is_native};
use crate::core::discover::{Skill, read_skill};
use crate::core::github::fetch_skill;
use crate::core::install::{ScannedSkill, install_skill, scan_disabled, scan_installed};
use crate::core::link::{is_agent_linked, link_agent, private_content, unlink_agent};
use crate::core::source::{SourceType, parse_source};
use crate::error::{Result, SkillsError};

use crate::manager::select::{SelectionOp, apply_selection, resolve_target_agents};
pub use crate::manager::types::{
    AddOutcome, AddRequest, AgentLinkResult, AgentOutcome, AgentRequest, AgentStatus, ListedSkill,
    SelectionOutcome, SelectionRequest,
};
mod select;
#[cfg(test)]
mod tests;
mod types;

/// The reported (frontmatter) names of scanned skills, for outcome hint lists.
fn reported_names(skills: &[ScannedSkill]) -> Vec<String> {
    skills.iter().map(|s| s.name.clone()).collect()
}

/// Skill manager: carries injectable context and runs add/list/remove/enable/disable.
///
/// This is the high-level entry point for library consumers. It resolves an [`Env`]
/// (home / config / cwd) once at construction, then every operation is a plain method
/// taking a request struct and returning a structured outcome.
///
/// # Examples
///
/// ```
/// use agents_skills::{AddRequest, Manager};
///
/// // Real environment:
/// let real = Manager::new()?;
///
/// // Or a sandboxed environment (no side effects outside the given paths):
/// let sandboxed = Manager::builder()
///     .home("/tmp/home")
///     .config("/tmp/config")
///     .cwd("/tmp/project")
///     .build()?;
///
/// let req = AddRequest::new("anthropics/skills/pdf");
/// let _ = (real, sandboxed, req);
/// # Ok::<(), agents_skills::Error>(())
/// ```
pub struct Manager {
    env: Env,
}

impl Manager {
    /// Build a manager from the real environment (home / config / cwd).
    ///
    /// Equivalent to [`Manager::builder`]`().build()`.
    ///
    /// # Errors
    ///
    /// [`SkillsError::Message`] when the platform cannot determine the home
    /// directory.
    pub fn new() -> Result<Self> {
        Self::builder().build()
    }

    /// Start customizing a manager (inject home/config/cwd/env vars).
    ///
    /// # Examples
    ///
    /// ```
    /// use agents_skills::Manager;
    ///
    /// let manager = Manager::builder()
    ///     .home("/tmp/home")
    ///     .env_var("CLAUDE_CONFIG_DIR", "/tmp/claude")
    ///     .build()?;
    /// # Ok::<(), agents_skills::Error>(())
    /// ```
    pub fn builder() -> ManagerBuilder {
        ManagerBuilder::default()
    }

    /// Access the resolved environment context.
    pub fn env(&self) -> &Env {
        &self.env
    }

    /// Add (install) exactly one skill from a source.
    ///
    /// `source` is either a local skill directory or the GitHub id `owner/repo/slug`,
    /// naming one skill on GitHub. In both cases a **skill** is a directory
    /// whose `SKILL.md` frontmatter declares a non-empty `name` — anything
    /// else is rejected or never discovered. The id's last segment is the
    /// skill's **slug** (its frontmatter `name` slugified: lowercase, spaces
    /// as dashes, `/` dropped, everything else verbatim); the repository tree
    /// is searched for the first manifest whose slugified `name` equals it,
    /// in shallowest-then-path order. A `SKILL.md` at the repository
    /// root is an ordinary candidate: when it matches, the whole
    /// repository is the skill. Pin a branch, tag, or full commit SHA with
    /// [`AddRequest::reference`]; otherwise the repository's default branch is
    /// used. A remote install is a **single request** that downloads the
    /// repository tarball from `codeload.github.com` — the GitHub REST API is
    /// never used, so there is no API rate limit. Public repositories only;
    /// Git LFS files install as their pointer stubs.
    ///
    /// The installed directory keeps the matched skill directory's own name
    /// in the source (for a root manifest, the repository name; for a local
    /// add, the local directory's own name) — while the skill's identity,
    /// what `list` reports and `remove`/`enable`/`disable` select by, is the
    /// slugified frontmatter `name`.
    ///
    /// The skill is installed into the canonical dir (the only place real files
    /// live). `add` only ever adds: when a skill of the same name is already
    /// installed — enabled *or* disabled — [`AddOutcome::skipped`] is `true` and
    /// the existing copy is left untouched, so local edits are never silently
    /// discarded. Replace an installed skill with [`Manager::remove`] followed by
    /// `add`.
    ///
    /// `add` never links any agent: use [`Manager::agent`] to expose the canonical
    /// dir to an agent afterwards.
    ///
    /// # Examples
    ///
    /// Install a local skill into a scratch environment (hermetic — no network, no
    /// real home access):
    ///
    /// ```
    /// use agents_skills::{AddRequest, Manager};
    ///
    /// let tmp = tempfile::TempDir::new().unwrap();
    /// let src = tmp.path().join("hello");
    /// std::fs::create_dir_all(&src).unwrap();
    /// std::fs::write(
    ///     src.join("SKILL.md"),
    ///     "---\nname: hello\ndescription: says hello\n---\n\n# hello\n",
    /// )
    /// .unwrap();
    ///
    /// let manager = Manager::builder()
    ///     .home(tmp.path().join("home"))
    ///     .config(tmp.path().join("config"))
    ///     .cwd(tmp.path().join("project"))
    ///     .build()?;
    ///
    /// let outcome = manager.add(&AddRequest::new(src.display().to_string()))?;
    /// assert_eq!(outcome.skill.name, "hello");
    /// # Ok::<(), agents_skills::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// - [`SkillsError::Message`] when the source syntax is invalid, the local
    ///   directory is missing or has no direct `SKILL.md`, or the named skill
    ///   does not exist in the GitHub repository.
    /// - [`SkillsError::Http`] / [`SkillsError::Io`] for transport and filesystem
    ///   failures.
    pub fn add(&self, req: &AddRequest) -> Result<AddOutcome> {
        let parsed = parse_source(&req.source)?;

        // Resolve exactly one skill. The temp dir backing a remote fetch is held
        // until the install below finishes (it drops and cleans up afterwards).
        let skill: Skill;
        let _temp: Option<tempfile::TempDir>;
        match parsed.ty {
            SourceType::Local => {
                if req.reference.is_some() {
                    return Err(SkillsError::msg(
                        "--ref can only pin a GitHub source (`owner/repo/slug`).",
                    ));
                }
                let path = parsed
                    .local_path
                    .as_ref()
                    .ok_or_else(|| SkillsError::msg("local source missing path"))?;
                if !path.exists() {
                    return Err(SkillsError::msg(format!(
                        "Local path does not exist: {}",
                        path.display()
                    )));
                }
                if !path.join("SKILL.md").is_file() {
                    return Err(SkillsError::msg(format!(
                        "Not a skill directory: \"{}\" must directly contain a SKILL.md file.",
                        path.display()
                    )));
                }
                // The slugified frontmatter `name` is the skill's identity; a
                // manifest without a non-empty `name` is not a skill.
                // A skill named by its explicit path may be internal.
                let Some(s) = read_skill(path) else {
                    return Err(SkillsError::msg(format!(
                        "Not a skill directory: \"{}\" — its SKILL.md must declare \
                         a non-empty `name` in the frontmatter.",
                        path.display()
                    )));
                };
                skill = s;
                _temp = None;
            }
            SourceType::Github => {
                let (tmp, s) = fetch_skill(
                    &parsed.owner,
                    &parsed.repo,
                    &parsed.slug,
                    req.reference.as_deref(),
                )?;
                skill = s;
                _temp = Some(tmp);
            }
        }

        // Install into the canonical dir (the only place real files live).
        // An already-installed name (enabled or disabled) is skipped unless force is true.
        let result = install_skill(&skill, req.force, &self.env)?;

        Ok(AddOutcome {
            source: parsed,
            skill,
            canonical_path: result.canonical_path,
            skipped: result.skipped,
        })
    }

    /// Link or unlink agents' skills dirs relative to the canonical dir.
    ///
    /// Connects each agent's own skills dir to the canonical dir with a
    /// directory-level symlink, so every install/update/remove is immediately
    /// visible to all linked agents. With `req.unlink`, disconnects those dirs
    /// instead — removes the symlink (only when it points at the canonical dir)
    /// and recreates an empty dir; the canonical dir and its skills are left
    /// untouched.
    ///
    /// Linking *adopts* whatever the agent dir already holds, and that is not
    /// reversible: skill dirs are moved into the canonical dir, non-skill entries
    /// are quarantined under `.misc/<agent>/` inside it, and name clashes are
    /// dropped in favour of the existing copy — the canonical copy wins, and a
    /// name disabled in the `disabled-skills` dir stays disabled instead of being
    /// re-imported (both reported via [`LinkOutcome::Linked`] `conflicts`). Legacy
    /// per-skill symlinks pointing into the canonical dir are dropped as well,
    /// since their content already lives there. Adopted content is managed by
    /// [`Manager::remove`] / [`Manager::disable`] from then on; unlinking does not
    /// move it back.
    ///
    /// Linking is refused only when the agent dir is a symlink pointing somewhere
    /// other than the canonical dir.
    ///
    /// Agents whose skills dir already is the canonical dir report
    /// [`LinkOutcome::AlreadyLinked`] (nativeness is per agent: e.g. an agent
    /// configured to read `~/.agents/skills` directly needs no link, while
    /// `~/.gemini/config/skills` does). Agents whose root dir does not exist
    /// are reported as [`LinkOutcome::Skipped`] — unless their table row sets
    /// `link_without_root` (e.g. `claude-code`).
    ///
    /// # Selection defaults
    ///
    /// - `agents` empty → auto-detect installed agents; a `"*"` entry → every
    ///   known agent.
    ///
    /// # Errors
    ///
    /// [`SkillsError::InvalidAgents`] when `agents` names an unknown agent.
    pub fn agent(&self, req: &AgentRequest) -> Result<AgentOutcome> {
        let target_agents = resolve_target_agents(&req.agents, &self.env)?;
        let results = target_agents
            .iter()
            .map(|agent| AgentLinkResult {
                agent: agent.name.to_string(),
                display: agent.display.to_string(),
                outcome: if req.unlink {
                    unlink_agent(agent, &self.env)
                } else {
                    link_agent(agent, &self.env)
                },
            })
            .collect();
        Ok(AgentOutcome { results })
    }

    /// Link status of every installed agent.
    ///
    /// Only agents detected as installed locally (or already linked) are reported.
    /// Agents that natively read the canonical dir report `canonical`; agents
    /// connected via a directory-level symlink report `linked`.
    ///
    /// For unlinked, non-canonical agents the status classifies the agent dir's
    /// private content (`internal_skills` / `internal_others`) — what linking
    /// would adopt into the canonical dir.
    ///
    /// Ordering: agents that natively use the canonical dir (`canonical: true`)
    /// come first, then the remaining agents — both groups keep the static agent
    /// table order. This is the exact order `agent --status` renders; callers do
    /// not need to sort again.
    pub fn agent_status(&self) -> Vec<AgentStatus> {
        let mut statuses: Vec<AgentStatus> = AGENTS
            .iter()
            .filter(|a| {
                is_installed(a, &self.env)
                    || (!is_native(a, &self.env) && is_agent_linked(a, &self.env))
            })
            .map(|a| {
                let canonical = is_native(a, &self.env);
                let linked = is_agent_linked(a, &self.env);
                // For unlinked, non-canonical agents, classify the private content
                // of the agent's own skills dir (canonical/linked agents share the
                // canonical dir, whose contents are shown by `list` instead).
                let (internal_skills, internal_others) = if linked || canonical {
                    (Vec::new(), Vec::new())
                } else {
                    private_content(a, &self.env)
                };
                AgentStatus {
                    name: a.name.to_string(),
                    display: a.display.to_string(),
                    linked,
                    canonical,
                    internal_skills,
                    internal_others,
                }
            })
            .collect();
        // Stable sort: canonical agents first, others keep table order.
        statuses.sort_by_key(|s| !s.canonical);
        statuses
    }

    /// List installed skills.
    ///
    /// Scans the canonical skills directory (plus the disabled dir), producing
    /// serde-serializable [`ListedSkill`] values — the same shape emitted by
    /// `list --json`. Each entry's `name` is the slugified `name` parsed from
    /// the SKILL.md frontmatter — a manifest without a non-empty `name` is not
    /// a skill and is never listed — and `path` carries the skill's real on-disk
    /// directory. Which agents see a skill is not per-skill: every linked or
    /// native agent sees all skills in the canonical dir. Use
    /// [`Manager::agent_status`] to inspect that.
    ///
    /// # Examples
    ///
    /// ```
    /// use agents_skills::Manager;
    ///
    /// let manager = Manager::new()?;
    /// let skills = manager.list()?;
    /// for skill in &skills {
    ///     println!("{} -> {}", skill.name, skill.path.display());
    /// }
    /// # Ok::<(), agents_skills::Error>(())
    /// ```
    pub fn list(&self) -> Result<Vec<ListedSkill>> {
        let mut out = Vec::new();
        for (skill, enabled) in scan_installed(&self.env)
            .into_iter()
            .map(|s| (s, true))
            .chain(scan_disabled(&self.env).into_iter().map(|s| (s, false)))
        {
            // Internal skills stay hidden from `list` unless opted in;
            // selection (remove/disable/enable) still reaches them.
            if skill.internal && !self.env.install_internal_skills() {
                continue;
            }
            out.push(ListedSkill {
                name: skill.name,
                display_name: skill.display_name,
                description: skill.description,
                path: skill.path,
                enabled,
                installed_at: skill.installed_at,
            });
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(out)
    }

    /// The on-disk directory of a listed skill.
    ///
    /// Returns the skill's real directory as scanned by [`Manager::list`] —
    /// the canonical dir when enabled, the sibling `disabled-skills` dir when
    /// disabled.
    pub fn skill_dir(&self, skill: &ListedSkill) -> PathBuf {
        skill.path.clone()
    }

    /// Disable installed skills.
    ///
    /// Moves each selected skill's directory from the canonical dir into the sibling
    /// `disabled-skills` dir, hiding it from every linked or universal agent at once.
    /// Files are preserved, so [`Manager::enable`] restores them losslessly.
    ///
    /// A copy of the same skill already parked in the disabled dir is stale — a
    /// disabled skill can be re-installed behind our back by a third-party agent —
    /// so the copy being moved wins and the stale one is discarded. One skill name
    /// therefore always maps to exactly one directory.
    ///
    /// # Selection semantics
    ///
    /// - `skills` empty and `all` false → nothing is disabled; the outcome reports the
    ///   currently enabled names (used by the CLI to print a hint).
    /// - `all` true → every currently enabled skill.
    ///
    /// # Examples
    ///
    /// Disable an installed skill in a scratch environment (hermetic — no real
    /// home access):
    ///
    /// ```
    /// use agents_skills::{Manager, SelectionRequest};
    ///
    /// let tmp = tempfile::TempDir::new().unwrap();
    /// // Simulate an installed skill in the canonical dir.
    /// let skill_dir = tmp.path().join("home/.agents/skills/pdf");
    /// std::fs::create_dir_all(&skill_dir).unwrap();
    /// std::fs::write(
    ///     skill_dir.join("SKILL.md"),
    ///     "---\nname: pdf\ndescription: pdf tools\n---\n\n# pdf\n",
    /// )
    /// .unwrap();
    ///
    /// let manager = Manager::builder()
    ///     .home(tmp.path().join("home"))
    ///     .config(tmp.path().join("config"))
    ///     .cwd(tmp.path().join("project"))
    ///     .build()?;
    ///
    /// let outcome = manager.disable(&SelectionRequest {
    ///     skills: vec!["pdf".into()],
    ///     ..Default::default()
    /// })?;
    /// assert_eq!(outcome.applied, vec!["pdf".to_string()]);
    /// # Ok::<(), agents_skills::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`SkillsError::Io`] if a directory move fails.
    pub fn disable(&self, req: &SelectionRequest) -> Result<SelectionOutcome> {
        let installed = scan_installed(&self.env);
        let disabled = scan_disabled(&self.env);
        let available = reported_names(&installed);

        if req.skills.is_empty() && !req.all {
            return Ok(SelectionOutcome {
                available,
                requested: Vec::new(),
                applied: Vec::new(),
                already: Vec::new(),
                missing: Vec::new(),
            });
        }

        let requested: Vec<String> = if req.all {
            available
        } else {
            req.skills.clone()
        };
        let (applied, already, missing) = apply_selection(
            SelectionOp::Disable,
            &requested,
            &[&installed],
            &disabled,
            &self.env,
        )?;

        Ok(SelectionOutcome {
            available: reported_names(&installed),
            requested,
            applied,
            already,
            missing,
        })
    }

    /// Enable previously disabled skills.
    ///
    /// Moves each selected skill's directory from the `disabled-skills` dir back into
    /// the canonical dir, restoring its visibility to every linked or universal agent.
    /// This is the exact inverse of [`Manager::disable`], except for which copy
    /// survives a clash: an enabled copy of the same skill — a third-party agent may
    /// re-install a skill whose copy is still parked — is discarded and replaced by
    /// the copy being moved. A name is never left present in both dirs.
    ///
    /// # Selection semantics
    ///
    /// - `skills` empty and `all` false → nothing is enabled; the outcome reports the
    ///   currently disabled names (used by the CLI to print a hint).
    /// - `all` true → every currently disabled skill.
    ///
    /// # Examples
    ///
    /// Re-enable a disabled skill in a scratch environment (hermetic — no real
    /// home access):
    ///
    /// ```
    /// use agents_skills::{Manager, SelectionRequest};
    ///
    /// let tmp = tempfile::TempDir::new().unwrap();
    /// // Simulate a disabled skill parked in the disabled-skills dir.
    /// let skill_dir = tmp.path().join("home/.agents/disabled-skills/pdf");
    /// std::fs::create_dir_all(&skill_dir).unwrap();
    /// std::fs::write(
    ///     skill_dir.join("SKILL.md"),
    ///     "---\nname: pdf\ndescription: pdf tools\n---\n\n# pdf\n",
    /// )
    /// .unwrap();
    ///
    /// let manager = Manager::builder()
    ///     .home(tmp.path().join("home"))
    ///     .config(tmp.path().join("config"))
    ///     .cwd(tmp.path().join("project"))
    ///     .build()?;
    ///
    /// let outcome = manager.enable(&SelectionRequest {
    ///     skills: vec!["pdf".into()],
    ///     ..Default::default()
    /// })?;
    /// assert_eq!(outcome.applied, vec!["pdf".to_string()]);
    /// # Ok::<(), agents_skills::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`SkillsError::Io`] if a directory move fails.
    pub fn enable(&self, req: &SelectionRequest) -> Result<SelectionOutcome> {
        let disabled = scan_disabled(&self.env);
        let installed = scan_installed(&self.env);
        let available = reported_names(&disabled);

        if req.skills.is_empty() && !req.all {
            return Ok(SelectionOutcome {
                available,
                requested: Vec::new(),
                applied: Vec::new(),
                already: Vec::new(),
                missing: Vec::new(),
            });
        }

        let requested: Vec<String> = if req.all {
            available
        } else {
            req.skills.clone()
        };
        let (applied, already, missing) = apply_selection(
            SelectionOp::Enable,
            &requested,
            &[&disabled],
            &installed,
            &self.env,
        )?;

        Ok(SelectionOutcome {
            available: reported_names(&disabled),
            requested,
            applied,
            already,
            missing,
        })
    }

    /// Remove installed skills.
    ///
    /// Deletes each skill's directory from the canonical dir, plus any parked copy in
    /// the disabled dir — including copies under a differently normalized directory
    /// name. Removal applies to every linked agent at once (they all share the
    /// canonical dir); agent links themselves are untouched — call [`Manager::agent`]
    /// with `unlink: true` to disconnect an agent instead.
    ///
    /// # Selection semantics
    ///
    /// - `skills` empty and `all` false → nothing is removed; the outcome reports the
    ///   currently enabled names (used by the CLI to print a hint).
    /// - `all` true → every installed skill (enabled or disabled).
    ///
    /// # Examples
    ///
    /// ```
    /// use agents_skills::{Manager, SelectionRequest};
    ///
    /// let tmp = tempfile::TempDir::new().unwrap();
    /// let manager = Manager::builder()
    ///     .home(tmp.path().join("home"))
    ///     .cwd(tmp.path().join("project"))
    ///     .build()?;
    ///
    /// let req = SelectionRequest {
    ///     skills: vec!["pdf".to_string()],
    ///     ..Default::default()
    /// };
    /// // Nothing installed in the scratch dir, so this is a harmless no-op.
    /// let outcome = manager.remove(&req)?;
    /// assert!(outcome.applied.is_empty());
    /// # Ok::<(), agents_skills::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`SkillsError::Io`] if a directory delete fails.
    pub fn remove(&self, req: &SelectionRequest) -> Result<SelectionOutcome> {
        // Disabled skills are still installed (parked in `disabled-skills`): scan them
        // too so `remove <name>` and `remove --all` can find and delete them.
        let installed = scan_installed(&self.env);
        let disabled = scan_disabled(&self.env);
        let available = reported_names(&installed);

        if req.skills.is_empty() && !req.all {
            return Ok(SelectionOutcome {
                available,
                requested: Vec::new(),
                applied: Vec::new(),
                already: Vec::new(),
                missing: Vec::new(),
            });
        }

        // Resolve against both dirs: a requested name parked in `disabled-skills`
        // is removed just the same.
        let requested: Vec<String> = if req.all {
            installed
                .iter()
                .chain(disabled.iter())
                .map(|s| s.name.clone())
                .collect()
        } else {
            req.skills.clone()
        };

        // Remove every copy of each selected skill: the canonical one (visible
        // to every linked agent at once) and any parked copy in the disabled
        // dir, including copies under a differently normalized directory name.
        let (applied, already, missing) = apply_selection(
            SelectionOp::Remove,
            &requested,
            &[&installed, &disabled],
            &[],
            &self.env,
        )?;

        Ok(SelectionOutcome {
            available: reported_names(&installed),
            requested,
            applied,
            already,
            missing,
        })
    }
}

/// Chained builder for [`Manager`], injecting home/config/cwd/env vars.
///
/// Every field is optional: unset fields fall back to the real environment at
/// [`build`](Self::build) time, so tests and sandboxes can override just the pieces
/// they care about.
#[derive(Default)]
pub struct ManagerBuilder {
    home: Option<PathBuf>,
    config: Option<PathBuf>,
    cwd: Option<PathBuf>,
    vars: std::collections::HashMap<String, String>,
    probe_system_dirs: Option<bool>,
}

impl ManagerBuilder {
    /// Override the home directory.
    ///
    /// Affects global skills (`~/.agents/skills`) and per-agent
    /// user-level skills directories.
    pub fn home(mut self, p: impl Into<PathBuf>) -> Self {
        self.home = Some(p.into());
        self
    }

    /// Override the config directory.
    ///
    /// Affects agent config lookup (e.g. `CLAUDE_CONFIG_DIR` resolution).
    pub fn config(mut self, p: impl Into<PathBuf>) -> Self {
        self.config = Some(p.into());
        self
    }

    /// Override the current working directory.
    ///
    /// Affects cwd-relative agent detection.
    pub fn cwd(mut self, p: impl Into<PathBuf>) -> Self {
        self.cwd = Some(p.into());
        self
    }

    /// Inject an environment variable override.
    ///
    /// Useful for redirecting agent-specific env vars (e.g. `CLAUDE_CONFIG_DIR`) that
    /// the agent directory mapping consults. Does not touch the real process env.
    pub fn env_var(mut self, k: impl Into<String>, v: impl Into<String>) -> Self {
        self.vars.insert(k.into(), v.into());
        self
    }

    /// Toggle probing of well-known system locations during agent detection.
    ///
    /// Some agents are detected via system locations outside home/config/cwd
    /// (e.g. `/Applications/ZCode.app`). Pass `false` in tests and sandboxes so
    /// detection never consults the real machine. Default: probe.
    pub fn probe_system_dirs(mut self, probe: bool) -> Self {
        self.probe_system_dirs = Some(probe);
        self
    }

    /// Build the [`Manager`], resolving defaults from the real environment.
    ///
    /// Unset fields fall back to the actual home/config/cwd of the process;
    /// the `INSTALL_INTERNAL_SKILLS` env var (or an override injected via
    /// [`Self::env_var`]) toggles visibility of internal skills.
    ///
    /// # Errors
    ///
    /// [`SkillsError::Message`] when the platform cannot determine the home
    /// directory.
    pub fn build(self) -> Result<Manager> {
        let cwd = self
            .cwd
            .or_else(|| std::env::current_dir().ok())
            .unwrap_or_default();
        let mut env = Env::new(
            match self.home {
                Some(home) => home,
                None => home()?,
            },
            match self.config {
                Some(config) => config,
                None => config_home()?,
            },
            cwd,
        );
        if !self.vars.is_empty() {
            env.set_vars(self.vars);
        }
        if let Some(v) = env.var("INSTALL_INTERNAL_SKILLS") {
            env.set_install_internal_skills(v == "1" || v == "true");
        }
        if let Some(probe) = self.probe_system_dirs {
            env.set_probe_system_dirs(probe);
        }
        Ok(Manager { env })
    }
}