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
//! Skill Registry
//!
//! Manages skill registration, loading, and lookup.
//! Integrates with `SkillValidator` as a safety gate for externally loaded skills.
use super::validator::SkillValidator;
use super::{Skill, SkillKind};
use anyhow::Context;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use thiserror::Error;
#[derive(Debug, Error)]
pub(crate) enum SkillRegistrySnapshotError {
#[error("projected skill name '{name}' conflicts with the compatibility registry")]
NameConflict { name: String },
#[error("projected skill '{name}' failed Session validation: {message}")]
Validation { name: String, message: String },
}
/// Skill registry for managing available skills
///
/// Provides skill registration, loading from directories, and lookup by name.
/// Optionally validates skills before registration.
pub struct SkillRegistry {
skills: Arc<RwLock<HashMap<String, Arc<Skill>>>>,
builtin_names: Arc<RwLock<HashSet<String>>>,
validator: Arc<RwLock<Option<Arc<dyn SkillValidator>>>>,
}
impl SkillRegistry {
/// Create a new empty skill registry
pub fn new() -> Self {
Self {
skills: Arc::new(RwLock::new(HashMap::new())),
builtin_names: Arc::new(RwLock::new(HashSet::new())),
validator: Arc::new(RwLock::new(None)),
}
}
/// Create a registry with built-in skills.
///
/// Built-in skills have been removed, so this is a compatibility alias for
/// [`Self::new`]. Load reusable skills through skill directories, inline
/// skills, or explicit registration.
pub fn with_builtins() -> Self {
let registry = Self::new();
for skill in super::builtin::builtin_skills() {
registry.register_builtin(skill);
}
registry
}
/// Fork this registry into an independent copy.
///
/// The fork shares no state with the original — skills added to the fork
/// do not affect the source registry. The validator is preserved so
/// that session and delegated-agent registries keep the same safety policy.
pub fn fork(&self) -> Self {
let skills = self.skills.read().unwrap().clone();
let builtin_names = self.builtin_names.read().unwrap().clone();
Self {
skills: Arc::new(RwLock::new(skills)),
builtin_names: Arc::new(RwLock::new(builtin_names)),
validator: Arc::new(RwLock::new(self.validator.read().unwrap().clone())),
}
}
/// Freeze the compatibility registry and add one external generation.
/// Existing names fail closed; no projected Skill may silently shadow a
/// built-in, host, or session registration.
pub(crate) fn snapshot_with_external_skills(
&self,
external: impl IntoIterator<Item = Arc<Skill>>,
) -> Result<Self, SkillRegistrySnapshotError> {
let mut skills = self.skills.read().unwrap().clone();
let builtin_names = self.builtin_names.read().unwrap().clone();
let validator = self.validator.read().unwrap().clone();
for skill in external {
let name = skill.name.clone();
if skills.contains_key(&name) {
return Err(SkillRegistrySnapshotError::NameConflict { name });
}
if let Some(validator) = &validator {
validator.validate(&skill).map_err(|error| {
SkillRegistrySnapshotError::Validation {
name: name.clone(),
message: error.to_string(),
}
})?;
}
skills.insert(name, skill);
}
Ok(Self {
skills: Arc::new(RwLock::new(skills)),
builtin_names: Arc::new(RwLock::new(builtin_names)),
validator: Arc::new(RwLock::new(validator)),
})
}
/// Set the skill validator (safety gate)
pub fn set_validator(&self, validator: Arc<dyn SkillValidator>) {
*self.validator.write().unwrap() = Some(validator);
}
/// Register a skill with validation
///
/// If a validator is set, the skill must pass validation before registration.
/// Returns an error if validation fails.
pub fn register(
&self,
skill: Arc<Skill>,
) -> Result<(), super::validator::SkillValidationError> {
// Run validator if set
if let Some(ref validator) = *self.validator.read().unwrap() {
validator.validate(&skill)?;
}
self.register_unchecked(skill);
Ok(())
}
/// Register a skill without validation.
///
/// If a future embedded skill set contains the same name, this replacement
/// is treated as external for global tool-restriction purposes.
pub fn register_unchecked(&self, skill: Arc<Skill>) {
let mut skills = self.skills.write().unwrap();
self.builtin_names.write().unwrap().remove(&skill.name);
skills.insert(skill.name.clone(), skill);
}
/// Register a validated, lifecycle-owned skill and return the registration
/// it shadowed.
///
/// The lookup and replacement happen under one write lock so a live
/// session can later restore the exact prior skill by pointer identity.
/// Built-in skills remain protected from live replacement.
pub(crate) fn register_with_shadow(
&self,
skill: Arc<Skill>,
) -> Result<(bool, Option<Arc<Skill>>), super::validator::SkillValidationError> {
if let Some(ref validator) = *self.validator.read().unwrap() {
validator.validate(&skill)?;
}
let name = skill.name.clone();
let mut skills = self.skills.write().unwrap();
let builtin_names = self.builtin_names.read().unwrap();
if builtin_names.contains(&name) {
tracing::warn!(
skill = %name,
"Rejected live skill registration because a built-in owns the name"
);
return Ok((false, None));
}
Ok((true, skills.insert(name, skill)))
}
/// Restore a shadowed skill only while `expected` still owns the name.
///
/// This compare-and-replace prevents one lifecycle source from deleting or
/// overwriting a skill installed later by another source.
pub(crate) fn restore_if_same(
&self,
name: &str,
expected: &Arc<Skill>,
replacement: Option<Arc<Skill>>,
) -> bool {
let mut skills = self.skills.write().unwrap();
let Some(current) = skills.get(name) else {
return false;
};
if !Arc::ptr_eq(current, expected) {
return false;
}
match replacement {
Some(skill) => {
skills.insert(name.to_string(), skill);
}
None => {
skills.remove(name);
}
}
true
}
fn register_builtin(&self, skill: Arc<Skill>) {
let name = skill.name.clone();
self.skills.write().unwrap().insert(name.clone(), skill);
self.builtin_names.write().unwrap().insert(name);
}
/// Register a host-owned skill and protect the name from later replacement.
pub fn register_host(&self, skill: Arc<Skill>) {
self.register_builtin(skill);
}
/// Get a skill by name
pub fn get(&self, name: &str) -> Option<Arc<Skill>> {
let skills = self.skills.read().unwrap();
skills.get(name).cloned()
}
/// List all registered skill names
pub fn list(&self) -> Vec<String> {
let skills = self.skills.read().unwrap();
let mut names = skills.keys().cloned().collect::<Vec<_>>();
names.sort();
names
}
/// Get all registered skills
pub fn all(&self) -> Vec<Arc<Skill>> {
let skills = self.skills.read().unwrap();
let mut values = skills.values().cloned().collect::<Vec<_>>();
values.sort_by(|a, b| a.name.cmp(&b.name));
values
}
/// Load skills from a directory
///
/// Recursively scans the directory for skill files and attempts to parse them.
///
/// Supported layouts:
/// - `path/to/skill.md`
/// - `path/to/skill/SKILL.md`
///
/// Candidate files are processed in deterministic sorted order. A symlink
/// whose resolved path leaves this directory is not loaded. Files that
/// fail to parse are skipped with debug logging; validation failures are
/// logged as warnings.
pub fn load_from_dir(&self, dir: impl AsRef<Path>) -> anyhow::Result<usize> {
let dir = dir.as_ref();
if !dir.exists() {
return Ok(0);
}
if !dir.is_dir() {
anyhow::bail!("Path is not a directory: {}", dir.display());
}
let mut loaded = 0;
for candidate in Self::collect_skill_candidates(dir)? {
match Skill::from_file(&candidate) {
Ok(skill) => {
let name = skill.name.clone();
if skill.allowed_tools.is_none() {
tracing::warn!(
skill = %name,
path = %candidate.display(),
"Skill omits allowed-tools; Skill invocation is fail-secure and will deny tool use until allowed-tools is declared"
);
} else if skill.uses_legacy_allowed_tools_syntax() {
tracing::warn!(
skill = %name,
path = %candidate.display(),
"Skill uses legacy whitespace-separated allowed-tools; use comma-separated permissions such as Read(*), Write(*), Bash(*) or a YAML list"
);
}
let skill = Arc::new(skill);
if self.get(&name).is_some() {
tracing::warn!(
skill = %name,
path = %candidate.display(),
"Duplicate skill name encountered during directory load — overriding previous definition"
);
}
match self.register(skill) {
Ok(()) => loaded += 1,
Err(e) => {
tracing::warn!(
"Skill validation failed for {}: {}",
candidate.display(),
e
);
}
}
}
Err(e) => {
tracing::debug!("Skipped {}: {}", candidate.display(), e);
}
}
}
Ok(loaded)
}
fn collect_skill_candidates(dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
/// Bound nested skill trees; symlink cycles are stopped by `seen`.
const MAX_DEPTH: usize = 64;
fn stays_in_root(root: &Path, path: &Path) -> bool {
let Ok(root) = std::fs::canonicalize(root) else {
return false;
};
std::fs::canonicalize(path)
.map(|canonical| canonical.starts_with(root))
.unwrap_or(false)
}
fn visit(
dir: &Path,
root: &Path,
out: &mut Vec<PathBuf>,
seen: &mut HashSet<PathBuf>,
depth: usize,
) -> anyhow::Result<()> {
if depth > MAX_DEPTH {
tracing::debug!(
path = %dir.display(),
max_depth = MAX_DEPTH,
"Skipping skill directory past max walk depth"
);
return Ok(());
}
if !stays_in_root(root, dir) {
return Ok(());
}
// Canonicalize so symlink cycles (a→b→a) share one seen key.
let identity = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
if !seen.insert(identity) {
return Ok(());
}
let mut entries = std::fs::read_dir(dir)
.with_context(|| format!("Failed to read directory: {}", dir.display()))?
.collect::<Result<Vec<_>, std::io::Error>>()?;
entries.sort_by_key(|entry| entry.path());
for entry in entries {
let path = entry.path();
if !stays_in_root(root, &path) {
continue;
}
if path.is_dir() {
// Resolve before collecting so `parent/loop -> sibling` does
// not push a second path to the same SKILL.md.
let child_identity =
std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if !seen.insert(child_identity) {
continue;
}
let skill_md = path.join("SKILL.md");
if skill_md.is_file() && stays_in_root(root, &skill_md) {
out.push(skill_md);
}
// Directory already marked seen; walk children only.
visit_children(&path, root, out, seen, depth + 1)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("md") {
out.push(path);
}
}
Ok(())
}
fn visit_children(
dir: &Path,
root: &Path,
out: &mut Vec<PathBuf>,
seen: &mut HashSet<PathBuf>,
depth: usize,
) -> anyhow::Result<()> {
if depth > MAX_DEPTH || !stays_in_root(root, dir) {
return Ok(());
}
let mut entries = std::fs::read_dir(dir)
.with_context(|| format!("Failed to read directory: {}", dir.display()))?
.collect::<Result<Vec<_>, std::io::Error>>()?;
entries.sort_by_key(|entry| entry.path());
for entry in entries {
let path = entry.path();
if !stays_in_root(root, &path) {
continue;
}
if path.is_dir() {
let child_identity =
std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
if !seen.insert(child_identity) {
continue;
}
let skill_md = path.join("SKILL.md");
if skill_md.is_file() && stays_in_root(root, &skill_md) {
out.push(skill_md);
}
visit_children(&path, root, out, seen, depth + 1)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("md") {
out.push(path);
}
}
Ok(())
}
let root = std::fs::canonicalize(dir)
.with_context(|| format!("Failed to resolve skill directory: {}", dir.display()))?;
let mut out = Vec::new();
let mut seen = HashSet::new();
visit(dir, &root, &mut out, &mut seen, 0)?;
out.sort();
out.dedup();
Ok(out)
}
/// Load a single skill from a file
pub fn load_from_file(&self, path: impl AsRef<Path>) -> anyhow::Result<Arc<Skill>> {
let skill = Skill::from_file(path)?;
let skill = Arc::new(skill);
self.register(skill.clone())
.map_err(|e| anyhow::anyhow!("Skill validation failed: {}", e))?;
Ok(skill)
}
/// Remove a skill by name
pub fn remove(&self, name: &str) -> Option<Arc<Skill>> {
let mut skills = self.skills.write().unwrap();
skills.remove(name)
}
/// Clear all skills
pub fn clear(&self) {
let mut skills = self.skills.write().unwrap();
skills.clear();
}
/// Get the number of registered skills
pub fn len(&self) -> usize {
let skills = self.skills.read().unwrap();
skills.len()
}
/// Check if the registry is empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Get all skills of a specific kind
pub fn by_kind(&self, kind: super::SkillKind) -> Vec<Arc<Skill>> {
let skills = self.skills.read().unwrap();
let mut values = skills
.values()
.filter(|s| s.kind == kind)
.cloned()
.collect::<Vec<_>>();
values.sort_by(|a, b| a.name.cmp(&b.name));
values
}
/// Instruction skills that actively constrain normal session tool use.
///
/// Embedded skills, when present, can have local allowlists for explicit
/// `Skill` invocation, but those allowlists must not make the default
/// registry globally read-only. User-registered skills remain external.
pub fn global_tool_restricting_skills(&self) -> Vec<Arc<Skill>> {
let skills = self.skills.read().unwrap();
let builtin_names = self.builtin_names.read().unwrap();
let mut values = skills
.values()
.filter(|skill| {
skill.kind == SkillKind::Instruction
&& skill.allowed_tools.is_some()
&& !builtin_names.contains(&skill.name)
})
.cloned()
.collect::<Vec<_>>();
values.sort_by(|a, b| a.name.cmp(&b.name));
values
}
/// Get all skills with a specific tag
pub fn by_tag(&self, tag: &str) -> Vec<Arc<Skill>> {
let skills = self.skills.read().unwrap();
let mut values = skills
.values()
.filter(|s| s.tags.iter().any(|t| t == tag))
.cloned()
.collect::<Vec<_>>();
values.sort_by(|a, b| a.name.cmp(&b.name));
values
}
/// Get all persona-kind skills
///
/// Personas are session-level system prompts bound at session creation.
/// They are NOT injected into the global system prompt via `to_system_prompt()`.
pub fn personas(&self) -> Vec<Arc<Skill>> {
self.by_kind(super::SkillKind::Persona)
}
/// Search discoverable instruction/tool skills by name, tag, description, or content.
pub fn search(&self, query: &str, limit: usize) -> Vec<Arc<Skill>> {
let skills = self.skills.read().unwrap();
let query_lower = query.to_lowercase();
let query_tokens: Vec<&str> = query_lower
.split_whitespace()
.map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()))
.filter(|w| w.len() >= 2)
.collect();
let mut scored: Vec<(u32, String, Arc<Skill>)> = skills
.values()
.filter(|s| Self::is_discoverable_skill(s))
.filter_map(|skill| {
let score = Self::skill_search_score(skill, &query_lower, &query_tokens);
if score == 0 {
None
} else {
Some((score, skill.name.clone(), Arc::clone(skill)))
}
})
.collect();
scored.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
scored
.into_iter()
.take(limit.max(1))
.map(|(_, _, skill)| skill)
.collect()
}
fn is_discoverable_skill(skill: &Skill) -> bool {
// `disable-model-invocation` is the Claude Skills contract for
// host/user-only skills: keep them registered, but hide them from
// model search/catalog and from Skill-tool invocation.
!skill.disable_model_invocation
&& (skill.kind == super::SkillKind::Instruction || skill.kind == super::SkillKind::Tool)
}
fn skill_search_score(skill: &Skill, query_lower: &str, query_tokens: &[&str]) -> u32 {
if query_lower.trim().is_empty() {
return 1;
}
let name = skill.name.to_lowercase();
let description = skill.description.to_lowercase();
let tags: Vec<String> = skill.tags.iter().map(|t| t.to_lowercase()).collect();
let content = skill.content.to_lowercase();
let mut score = 0;
if query_lower.contains(&name) {
score += 100;
}
if tags.iter().any(|tag| query_lower.contains(tag)) {
score += 80;
}
for token in query_tokens {
if name.contains(token) {
score += 20;
}
if tags.iter().any(|tag| tag.contains(token)) {
score += 15;
}
if description.contains(token) {
score += 8;
}
if content.contains(token) {
score += 2;
}
}
score
}
/// Generate system prompt content from all instruction skills
///
/// Concatenates the content of all instruction-type skills for injection
/// into the system prompt.
/// Persona-kind skills are excluded — they are bound per-session, not globally.
/// Generate the system prompt fragment for this registry.
///
/// Emits only the catalog header telling the model to use `search_skills`
/// then `Skill`. Full skill bodies are never auto-injected into the main
/// prompt; they load only when the model invokes `Skill`.
///
/// `match_skills` remains a helper for hosts that want keyword injection,
/// but the default agent loop does not call it.
pub fn to_system_prompt(&self) -> String {
let skills = self.skills.read().unwrap();
let has_discoverable_skill = skills.values().any(|s| Self::is_discoverable_skill(s));
if !has_discoverable_skill {
return String::new();
}
String::from(crate::prompts::SKILLS_CATALOG_HEADER)
}
/// Return the full content of skills relevant to the given user input.
///
/// Matches by checking if any skill name or tag appears in the input (case-insensitive).
/// Returns an empty string if no skills match — caller should not inject anything.
pub fn match_skills(&self, user_input: &str) -> String {
let matched = self.search(user_input, 3);
if matched.is_empty() {
return String::new();
}
let mut out = String::from("# Skill Instructions\n\n");
for skill in matched {
out.push_str(&skill.to_system_prompt());
out.push_str("\n\n---\n\n");
}
out
}
}
impl Default for SkillRegistry {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
#[path = "registry/tests.rs"]
mod tests;