Skip to content

Commit e5d2b24

Browse files
feat(sleep): resolve discovered skill names through bounded local roots
Add a read-only resolver that normalizes an untrusted skill name, matches it only inside documented skill roots, refuses traversal and symlink escapes, and distinguishes found, missing, ambiguous, and rejected outcomes. Refs microsoft#120
1 parent 8a4c96a commit e5d2b24

2 files changed

Lines changed: 303 additions & 0 deletions

File tree

‎skillopt_sleep/skill_resolver.py‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
"""SkillOpt-Sleep — resolve a discovered skill name to a local ``SKILL.md``.
2+
3+
Skill names observed in transcripts are untrusted strings, so resolution is
4+
deliberately narrow: a name is normalized, matched only inside documented local
5+
skill roots, and reported. Nothing here writes, edits, or creates files.
6+
7+
Resolution outcomes are distinguishable on purpose — ``missing`` (no root has
8+
the skill) is a different signal from ``ambiguous`` (several roots do) and from
9+
``rejected`` (the name itself is unusable), so callers can fall back to the
10+
existing managed-skill behavior instead of guessing.
11+
"""
12+
from __future__ import annotations
13+
14+
import os
15+
from dataclasses import dataclass, field
16+
from typing import List, Sequence
17+
18+
SKILL_FILENAME = "SKILL.md"
19+
20+
FOUND = "found"
21+
MISSING = "missing"
22+
AMBIGUOUS = "ambiguous"
23+
REJECTED = "rejected"
24+
25+
26+
@dataclass(frozen=True)
27+
class SkillResolution:
28+
"""The outcome of resolving one skill name. Never a partial success."""
29+
30+
name: str
31+
status: str
32+
path: str = ""
33+
candidates: List[str] = field(default_factory=list)
34+
reason: str = ""
35+
36+
@property
37+
def ok(self) -> bool:
38+
return self.status == FOUND
39+
40+
41+
def normalize_skill_name(name: object) -> str:
42+
"""Return a usable skill directory name, or "" when the name is unusable.
43+
44+
Only a single path segment is accepted: no separators, no parent traversal,
45+
no absolute or home-relative paths, no control characters. The name is
46+
whitespace-trimmed but otherwise preserved, since skill directories are
47+
case- and punctuation-sensitive.
48+
"""
49+
if not isinstance(name, str):
50+
return ""
51+
candidate = name.strip()
52+
if not candidate or candidate in {os.curdir, os.pardir}:
53+
return ""
54+
if candidate.startswith("~"):
55+
return ""
56+
if os.path.isabs(candidate) or os.path.splitdrive(candidate)[0]:
57+
return ""
58+
if "/" in candidate or "\\" in candidate or os.sep in candidate:
59+
return ""
60+
if os.altsep and os.altsep in candidate:
61+
return ""
62+
if any(ord(ch) < 32 or ord(ch) == 127 for ch in candidate):
63+
return ""
64+
return candidate
65+
66+
67+
def skill_search_roots(cfg: object) -> List[str]:
68+
"""Documented local skill roots for a config: user skills, then plugin cache.
69+
70+
``<claude_home>/skills`` holds hand-written skills; installed Claude Code
71+
plugins expose theirs under ``<claude_home>/plugins/cache/*/*/skills``.
72+
Only existing directories are returned, in that fixed precedence order.
73+
"""
74+
claude_home = os.path.abspath(os.path.expanduser(str(getattr(cfg, "claude_home", ""))))
75+
if not claude_home:
76+
return []
77+
roots = [os.path.join(claude_home, "skills")]
78+
79+
cache = os.path.join(claude_home, "plugins", "cache")
80+
if os.path.isdir(cache):
81+
for marketplace in sorted(os.listdir(cache)):
82+
plugins_dir = os.path.join(cache, marketplace)
83+
if not os.path.isdir(plugins_dir):
84+
continue
85+
for plugin in sorted(os.listdir(plugins_dir)):
86+
roots.append(os.path.join(plugins_dir, plugin, "skills"))
87+
return [r for r in roots if os.path.isdir(r)]
88+
89+
90+
def _contained_skill_file(root: str, name: str) -> str:
91+
"""Return the real ``SKILL.md`` path under ``root`` for ``name``, else "".
92+
93+
Symlinks are followed and then re-checked against the real root, so a skill
94+
directory or file that points outside the root is refused rather than read.
95+
"""
96+
try:
97+
real_root = os.path.realpath(root)
98+
skill_file = os.path.realpath(os.path.join(real_root, name, SKILL_FILENAME))
99+
except OSError:
100+
return ""
101+
if not os.path.isfile(skill_file):
102+
return ""
103+
if os.path.commonpath([real_root, skill_file]) != real_root:
104+
return ""
105+
return skill_file
106+
107+
108+
def resolve_skill(name: object, roots: Sequence[str]) -> SkillResolution:
109+
"""Resolve ``name`` against ``roots`` without touching any skill content."""
110+
normalized = normalize_skill_name(name)
111+
if not normalized:
112+
return SkillResolution(
113+
name=name if isinstance(name, str) else "",
114+
status=REJECTED,
115+
reason="skill name is empty or not a single safe path segment",
116+
)
117+
118+
matches: List[str] = []
119+
for root in roots:
120+
found = _contained_skill_file(root, normalized)
121+
if found and found not in matches:
122+
matches.append(found)
123+
124+
if not matches:
125+
return SkillResolution(
126+
name=normalized,
127+
status=MISSING,
128+
reason=f"no {SKILL_FILENAME} for this skill in the configured skill roots",
129+
)
130+
if len(matches) > 1:
131+
return SkillResolution(
132+
name=normalized,
133+
status=AMBIGUOUS,
134+
candidates=matches,
135+
reason="several skill roots define this skill",
136+
)
137+
return SkillResolution(name=normalized, status=FOUND, path=matches[0], candidates=matches)

‎tests/test_sleep_skill_resolver.py‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
"""Tests for bounded skill-name resolution (issue #120).
2+
3+
Pure-stdlib (unittest), hermetic (tmpdir only), no API key, no network.
4+
Run: python -m pytest tests/test_sleep_skill_resolver.py
5+
"""
6+
from __future__ import annotations
7+
8+
import os
9+
import tempfile
10+
import unittest
11+
12+
from skillopt_sleep.config import load_config
13+
from skillopt_sleep.skill_resolver import (
14+
AMBIGUOUS,
15+
FOUND,
16+
MISSING,
17+
REJECTED,
18+
normalize_skill_name,
19+
resolve_skill,
20+
skill_search_roots,
21+
)
22+
23+
24+
def _write_skill(root, name, body="# skill\n"):
25+
path = os.path.join(root, name, "SKILL.md")
26+
os.makedirs(os.path.dirname(path), exist_ok=True)
27+
with open(path, "w", encoding="utf-8") as f:
28+
f.write(body)
29+
return path
30+
31+
32+
class TestNormalizeSkillName(unittest.TestCase):
33+
def test_trims_but_preserves_case_and_punctuation(self):
34+
self.assertEqual(normalize_skill_name(" Brand-Voice.v2 "), "Brand-Voice.v2")
35+
36+
def test_rejects_unusable_names(self):
37+
for bad in ["", " ", ".", "..", "../escape", "a/b", "a\\b", "/abs/skill",
38+
"~/skill", "bad\nname", "bad\x00name", None, 3]:
39+
self.assertEqual(normalize_skill_name(bad), "", repr(bad))
40+
41+
42+
class TestResolveSkill(unittest.TestCase):
43+
def test_resolves_a_single_local_skill(self):
44+
with tempfile.TemporaryDirectory() as tmp:
45+
expected = _write_skill(tmp, "example-skill")
46+
res = resolve_skill(" example-skill ", [tmp])
47+
self.assertEqual(res.status, FOUND)
48+
self.assertTrue(res.ok)
49+
self.assertEqual(res.path, os.path.realpath(expected))
50+
self.assertEqual(res.name, "example-skill")
51+
52+
def test_missing_skill_is_distinct_from_ambiguous(self):
53+
with tempfile.TemporaryDirectory() as tmp:
54+
_write_skill(tmp, "other-skill")
55+
res = resolve_skill("example-skill", [tmp])
56+
self.assertEqual(res.status, MISSING)
57+
self.assertEqual(res.path, "")
58+
self.assertEqual(res.candidates, [])
59+
60+
def test_directory_without_skill_file_is_missing(self):
61+
with tempfile.TemporaryDirectory() as tmp:
62+
os.makedirs(os.path.join(tmp, "example-skill"))
63+
self.assertEqual(resolve_skill("example-skill", [tmp]).status, MISSING)
64+
65+
def test_same_skill_in_two_roots_is_ambiguous(self):
66+
with tempfile.TemporaryDirectory() as tmp:
67+
local, cache = os.path.join(tmp, "local"), os.path.join(tmp, "cache")
68+
first = _write_skill(local, "example-skill")
69+
second = _write_skill(cache, "example-skill")
70+
res = resolve_skill("example-skill", [local, cache])
71+
self.assertEqual(res.status, AMBIGUOUS)
72+
self.assertEqual(res.path, "")
73+
self.assertEqual(res.candidates,
74+
[os.path.realpath(first), os.path.realpath(second)])
75+
76+
def test_repeated_root_is_not_ambiguous(self):
77+
with tempfile.TemporaryDirectory() as tmp:
78+
_write_skill(tmp, "example-skill")
79+
self.assertEqual(resolve_skill("example-skill", [tmp, tmp]).status, FOUND)
80+
81+
def test_traversal_is_rejected_without_touching_the_filesystem(self):
82+
with tempfile.TemporaryDirectory() as tmp:
83+
root = os.path.join(tmp, "roots")
84+
_write_skill(tmp, "outside-skill")
85+
os.makedirs(root, exist_ok=True)
86+
res = resolve_skill("../outside-skill", [root])
87+
self.assertEqual(res.status, REJECTED)
88+
self.assertEqual(res.path, "")
89+
90+
def test_symlinked_skill_dir_escaping_the_root_is_refused(self):
91+
with tempfile.TemporaryDirectory() as tmp:
92+
root = os.path.join(tmp, "roots")
93+
os.makedirs(root)
94+
outside = os.path.join(tmp, "outside")
95+
_write_skill(outside, "example-skill")
96+
os.symlink(os.path.join(outside, "example-skill"),
97+
os.path.join(root, "example-skill"))
98+
self.assertEqual(resolve_skill("example-skill", [root]).status, MISSING)
99+
100+
def test_symlinked_skill_file_escaping_the_root_is_refused(self):
101+
with tempfile.TemporaryDirectory() as tmp:
102+
root = os.path.join(tmp, "roots")
103+
os.makedirs(os.path.join(root, "example-skill"))
104+
elsewhere = os.path.join(tmp, "elsewhere.md")
105+
with open(elsewhere, "w", encoding="utf-8") as f:
106+
f.write("# not in the root\n")
107+
os.symlink(elsewhere, os.path.join(root, "example-skill", "SKILL.md"))
108+
self.assertEqual(resolve_skill("example-skill", [root]).status, MISSING)
109+
110+
def test_symlinked_root_itself_still_resolves(self):
111+
with tempfile.TemporaryDirectory() as tmp:
112+
real = os.path.join(tmp, "real")
113+
_write_skill(real, "example-skill")
114+
link = os.path.join(tmp, "link")
115+
os.symlink(real, link)
116+
self.assertEqual(resolve_skill("example-skill", [link]).status, FOUND)
117+
118+
def test_resolution_never_modifies_the_skill(self):
119+
with tempfile.TemporaryDirectory() as tmp:
120+
path = _write_skill(tmp, "example-skill", "# original\n")
121+
before = (os.stat(path).st_size, open(path, encoding="utf-8").read())
122+
resolve_skill("example-skill", [tmp])
123+
self.assertEqual((os.stat(path).st_size,
124+
open(path, encoding="utf-8").read()), before)
125+
126+
def test_no_roots_is_missing(self):
127+
self.assertEqual(resolve_skill("example-skill", []).status, MISSING)
128+
129+
130+
class TestSkillSearchRoots(unittest.TestCase):
131+
def test_user_skills_root_comes_first_then_plugin_cache(self):
132+
with tempfile.TemporaryDirectory() as tmp:
133+
claude_home = os.path.join(tmp, ".claude")
134+
skills = os.path.join(claude_home, "skills")
135+
os.makedirs(skills)
136+
plugin_skills = os.path.join(
137+
claude_home, "plugins", "cache", "marketplace", "plugin", "skills"
138+
)
139+
os.makedirs(plugin_skills)
140+
cfg = load_config(claude_home=claude_home)
141+
self.assertEqual(skill_search_roots(cfg), [skills, plugin_skills])
142+
143+
def test_absent_roots_are_skipped(self):
144+
with tempfile.TemporaryDirectory() as tmp:
145+
cfg = load_config(claude_home=os.path.join(tmp, ".claude"))
146+
self.assertEqual(skill_search_roots(cfg), [])
147+
148+
def test_resolution_through_config_roots_prefers_the_user_skill(self):
149+
with tempfile.TemporaryDirectory() as tmp:
150+
claude_home = os.path.join(tmp, ".claude")
151+
expected = _write_skill(os.path.join(claude_home, "skills"), "example-skill")
152+
cfg = load_config(claude_home=claude_home)
153+
res = resolve_skill("example-skill", skill_search_roots(cfg))
154+
self.assertEqual(res.status, FOUND)
155+
self.assertEqual(res.path, os.path.realpath(expected))
156+
157+
def test_legacy_target_skill_path_behavior_is_untouched(self):
158+
with tempfile.TemporaryDirectory() as tmp:
159+
target = os.path.join(tmp, "repo", "SKILL.md")
160+
cfg = load_config(claude_home=os.path.join(tmp, ".claude"),
161+
target_skill_path=target)
162+
self.assertEqual(cfg.managed_skill_path(), os.path.abspath(target))
163+
164+
165+
if __name__ == "__main__":
166+
unittest.main()

0 commit comments

Comments
 (0)