Skip to content
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,41 @@ public List<String> getAllSkillNames() {

@Override
public List<AgentSkill> getAllSkills() {
// If baseDir itself is a skill directory, return only that skill
Path baseDirKey = baseDir.toAbsolutePath().normalize();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root branch is ~35 lines copied from the container loop below (stat → mtime+size compare → loadSkillFromDirectory(..., !lazy) → skillCache.put), and it returns before skillCache.keySet().retainAll(seenDirs) at line 253, so root and container mode handle cache eviction differently. Concretely: a repository that was in container mode accumulates per-skill snapshots, and once baseDir gains a root SKILL.md those entries are never pruned again, because every subsequent call takes this early return.

Worth also deciding what this branch is meant to return when the root file fails to parse: the container branch skips one bad skill and keeps the others, while this branch yields List.of() for the whole repository — a defensible choice, but it is the only place a single malformed SKILL.md blanks the repository, so it should be stated in the javadoc.

Extracting the shared body into private Optional<AgentSkill> loadWithCache(Path dir) used by both branches would remove the copy-paste and the eviction asymmetry in one go.

Path baseSkillFile = baseDirKey.resolve(SKILL_FILE_NAME);
if (Files.exists(baseSkillFile)) {
try {
BasicFileAttributes attrs =
Files.readAttributes(baseSkillFile, BasicFileAttributes.class);
long mtime = attrs.lastModifiedTime().toMillis();
long size = attrs.size();
Snapshot cached = skillCache.get(baseDirKey);
if (cached != null && cached.mtime == mtime && cached.size == size) {
return List.of(cached.skill);
}
AgentSkill skill =
SkillFileSystemHelper.loadSkillFromDirectory(
baseDirKey, getSource(), !lazy);
skillCache.put(baseDirKey, new Snapshot(mtime, size, skill));
return List.of(skill);
} catch (IOException e) {
logger.warn(
"Failed to stat SKILL.md for baseDir '{}': {}",
baseDirKey,
e.getMessage(),
e);
return List.of();
} catch (Exception e) {
logger.warn(
"Failed to load skill from baseDir '{}': {}",
baseDirKey,
e.getMessage(),
e);
return List.of();
}
}

List<AgentSkill> out = new ArrayList<>();
Set<Path> seenDirs = new HashSet<>();
try (Stream<Path> subdirs = Files.list(baseDir)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,22 @@ public static AgentSkill loadSkillFromDirectory(
/**
* Retrieves all skill names by parsing SKILL.md metadata in each skill folder.
*
* <p>If {@code baseDir} itself contains a {@code SKILL.md} file, it is treated as a single
* skill directory and only that skill's name is returned. Otherwise, subdirectories are
* scanned for skills.
*
* @param baseDir The base directory containing skill folders
* @return A list of skill names sorted alphabetically
*/
public static List<String> getAllSkillNames(Path baseDir) {
// If baseDir itself is a skill directory, return only that skill
if (hasSkillFile(baseDir)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Root vs container mode is inferred from hasSkillFile(baseDir) on every call, and hasSkillFile (line 407) is Files.walk(dir, 1).anyMatch(name equals "SKILL.md") — it also returns true for a directory named SKILL.md, and it costs a directory listing instead of one Files.isRegularFile(baseDir.resolve("SKILL.md")) stat. FileSystemSkillRepository.getAllSkills() uses Files.exists(baseDir/SKILL.md) for the same decision, so the two implementations infer the mode slightly differently.

Two consequences of inferring rather than configuring:

  1. An existing container-mode repository that gains a SKILL.md at its root (easy to do by accident — a saved skill, a doc file) instantly hides all of its sub-skills, with no warning.
  2. After deleteSkill removes the root SKILL.md, the mode flips back to container, and any leftover resource subdirectory that happens to contain a SKILL.md now surfaces as a skill — i.e. deleted skill data can come back into getAllSkills().

A singleSkillDirectory flag (explicit opt-in on the repository/helper entry points) plus one shared isRootSkillDir(Path) predicate would make the mode deterministic, cheaper, and consistent with FileSystemSkillRepository. The call count also matters in the save path: hasSkillFile(baseDir) runs once per skill in the list.

List<String> names = new ArrayList<>();
readSkillName(baseDir).ifPresent(names::add);
names.sort(String::compareTo);
return names;
}

List<String> skillNames = new ArrayList<>();

try (Stream<Path> subdirs = Files.list(baseDir)) {
Expand Down Expand Up @@ -160,6 +172,10 @@ public static List<AgentSkill> getAllSkills(Path baseDir, String source) {
/**
* Retrieves all skills from the base directory.
*
* <p>If {@code baseDir} itself contains a {@code SKILL.md} file, it is treated as a single
* skill directory and only that skill is returned. Otherwise, subdirectories are scanned for
* skills.
*
* @param baseDir The base directory containing skill folders
* @param source The source identifier for created skills
* @param includeResources when {@code false}, each skill's resource map is left empty and
Expand All @@ -168,6 +184,17 @@ public static List<AgentSkill> getAllSkills(Path baseDir, String source) {
*/
public static List<AgentSkill> getAllSkills(
Path baseDir, String source, boolean includeResources) {
// If baseDir itself is a skill directory, return only that skill
if (hasSkillFile(baseDir)) {
List<AgentSkill> skills = new ArrayList<>();
try {
skills.add(loadSkillFromDirectory(baseDir, source, includeResources));
} catch (Exception e) {
logger.warn("Failed to load skill from '{}': {}", baseDir, e.getMessage(), e);
}
return skills;
}

List<AgentSkill> skills = new ArrayList<>();

try (Stream<Path> subdirs = Files.list(baseDir)) {
Expand Down Expand Up @@ -213,38 +240,74 @@ public static boolean saveSkills(Path baseDir, List<AgentSkill> skills, boolean
try {
for (AgentSkill skill : skills) {
String skillName = skill.getName();
Path skillDir = validateAndResolvePath(baseDir, skillName);

if (Files.exists(skillDir)) {
if (!force) {
logger.info(
"Skill directory already exists and force=false: {}", skillName);
continue; // Skip to the next skill if force=false
} else {
logger.info("Overwriting existing skill directory: {}", skillName);
deleteDirectory(skillDir);

Path skillDir;
Path skillFile;
// Root-level skill: baseDir itself contains SKILL.md
if (hasSkillFile(baseDir)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mode is re-decided inside the for (AgentSkill skill : skills) loop. When baseDir itself is the skill, every iteration resolves to the same baseDir/SKILL.md, so a batch save destroys all but the last skill:

Path root = ...;                       // root/SKILL.md exists (name = "A")
saveSkills(root, List.of(skillA, skillB), true);
// iter A: hasSkillFile(root) -> skillFile exists -> walk root, delete everything -> write A
// iter B: hasSkillFile(root) -> skillFile exists -> walk root, delete everything (incl. A)
//         -> write B
// returns allSaved == true; A's SKILL.md and resources are gone silently

With force=false the second skill hits continue at line 250, so saveCount != size and the method returns false — the first skill was still written, and the caller cannot tell which one failed.

Since a root-level repository can hold exactly one skill by definition, the guard belongs above the loop: if hasSkillFile(baseDir) and skills.size() > 1, throw IllegalArgumentException (or fall back to the subdirectory layout) instead of letting iterations overwrite each other.

skillDir = baseDir.toAbsolutePath().normalize();
skillFile = skillDir.resolve(SKILL_FILE_NAME);
if (Files.exists(skillFile)) {
if (!force) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root branch never validates or even uses skillName, which drops two guarantees the subdirectory branch relies on:

  • validateAndResolvePath (line 383) normalizes the name and rejects .. escapes. Nothing equivalent runs here, so the write target is unconditional.
  • The name is not compared with the existing root skill's name. Saving a skill called other into a repository whose root SKILL.md is named A overwrites A's content; the file's front matter then says other, getAllSkillNames returns ["other"], and every consumer that cached A (skill caches, sub-agent skill references) silently resolves to different content. loadSkill is strict about this exact mismatch — testLoadSkill_RootLevelSkillNameMismatch asserts IllegalArgumentException — so saveSkills being permissive is inconsistent with the read path.

Comparing skillName with readSkillName(baseDir) and rejecting a mismatch (or writing the skill into a subdirectory instead) would line the two paths up.

logger.info("Root skill already exists and force=false: {}", skillName);
continue;
} else {
logger.info("Overwriting existing root skill: {}", skillName);
// Delete all contents except baseDir itself

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

force=true in the root branch deletes the entire content of baseDir, not the files this skill owns:

try (Stream<Path> paths = Files.walk(skillDir)) {          // skillDir == baseDir here
    paths.sorted(Comparator.reverseOrder())
         .filter(path -> !path.equals(skillDir))
         .forEach(path -> Files.delete(path));
}

baseDir is supplied by the embedding application — a skills directory under a user's workspace, a mounted repo root, a directory someone also keeps READMEs, dotfiles or an existing sub/SKILL.md in. The subdirectory branch is scoped to validateAndResolvePath(baseDir, skillName) and only ever deletes that one skill folder; the root branch has no such bound. If a Files.delete fails partway (permission, read-only file), the RuntimeException at line 262 leaves baseDir half-emptied, and the caller has no way to recover.

Could the cleanup be limited to what the previous root skill actually owned — its SKILL.md plus the resource keys recorded for that skill (mirroring SkillFileSystemHelper.loadResources) — with a hard refusal to delete any path outside that set? And a log line per deleted path so a half-emptied directory is diagnosable after the fact.

try (Stream<Path> paths = Files.walk(skillDir)) {
paths.sorted(Comparator.reverseOrder())
.filter(path -> !path.equals(skillDir))
.forEach(
path -> {
try {
Files.delete(path);
} catch (IOException e) {
throw new RuntimeException(
"Failed to delete: " + path, e);
}
});
} catch (IOException e) {
throw new RuntimeException(
"Failed to clean root skill directory", e);
}
}
}
} else {
// Subdirectory skill: create a new subdirectory
skillDir = validateAndResolvePath(baseDir, skillName);
if (Files.exists(skillDir)) {
if (!force) {
logger.info(
"Skill directory already exists and force=false: {}",
skillName);
continue; // Skip to the next skill if force=false
} else {
logger.info("Overwriting existing skill directory: {}", skillName);
deleteDirectory(skillDir);
}
}
Files.createDirectories(skillDir);
skillFile = skillDir.resolve(SKILL_FILE_NAME);
}

Files.createDirectories(skillDir);

String skillMdContent =
MarkdownSkillParser.generate(skill.getMetadata(), skill.getSkillContent());

Path skillFile = skillDir.resolve(SKILL_FILE_NAME);
Files.writeString(skillFile, skillMdContent, StandardCharsets.UTF_8);

Map<String, String> resources = skill.getResources();
for (Map.Entry<String, String> entry : resources.entrySet()) {
Path resourceFile = skillDir.resolve(entry.getKey());
Files.createDirectories(resourceFile.getParent());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resource keys are still resolved without containment checks — skillDir.resolve(entry.getKey()) accepts .. and absolute paths, so Map.of("../../../../tmp/x", "...") writes outside the skill directory. The same guard the name path already has would fix it:

Path abs = skillDir.toAbsolutePath().normalize();
Path target = abs.resolve(entry.getKey()).normalize();
if (!target.startsWith(abs)) {
    throw new IllegalArgumentException("resource path escapes skill directory: " + entry.getKey());
}

This pre-dates the PR, but root mode changes the blast radius: skillDir is now the caller's baseDir rather than a per-skill folder, so an escaping key writes next to baseDir instead of next to one skill inside it. Since skills can be loaded from a git repository or an archive (this PR's stated use case is exactly "a skill repo checked out as baseDir"), the resource map is not trusted input.

Small related nit on the same hunk: Files.createDirectories(resourceFile.getParent()) runs before the new content != null check, so a null-content resource now creates an empty directory and writes nothing. Moving the createDirectories inside the null guard keeps the tree clean.

String content = entry.getValue();
if (content != null && content.startsWith("base64:")) {
String base64 = content.substring("base64:".length());
byte[] bytes = Base64.getDecoder().decode(base64);
Files.write(resourceFile, bytes);
} else {
Files.writeString(resourceFile, content, StandardCharsets.UTF_8);
if (content != null) {
if (content.startsWith("base64:")) {
String base64 = content.substring("base64:".length());
byte[] bytes = Base64.getDecoder().decode(base64);
Files.write(resourceFile, bytes);
} else {
Files.writeString(resourceFile, content, StandardCharsets.UTF_8);
}
}
}

Expand Down Expand Up @@ -277,8 +340,16 @@ public static boolean deleteSkill(Path baseDir, String skillName) {
return false;
}

Path dirToDelete = skillDir.get().toAbsolutePath().normalize();
Path absoluteBaseDir = baseDir.toAbsolutePath().normalize();

try {
deleteDirectory(skillDir.get());
if (dirToDelete.equals(absoluteBaseDir)) {
// Root-level skill: only remove SKILL.md, keep other files intact
Files.deleteIfExists(dirToDelete.resolve(SKILL_FILE_NAME));
} else {
deleteDirectory(dirToDelete);
}
logger.info("Successfully deleted skill: {}", skillName);
return true;
} catch (IOException e) {
Expand Down Expand Up @@ -463,6 +534,16 @@ private static Optional<Path> findSkillDirectoryByName(Path baseDir, String skil
return Optional.empty();
}

// Check if baseDir itself is the skill
if (hasSkillFile(baseDir)) {
String rootName = readSkillName(baseDir).orElse(null);
if (skillName.equals(rootName)) {
return Optional.of(baseDir);
}
// baseDir is a single skill directory; no subdirectory skills to scan
return Optional.empty();
}

try (Stream<Path> subdirs = Files.list(baseDir)) {
return subdirs.filter(Files::isDirectory)
.filter(SkillFileSystemHelper::hasSkillFile)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,61 @@ void testSave_SourceHasNoColon() {
assertTrue(source.startsWith("filesystem-"));
}

// ==================== Root-Level Skill Tests ====================

@Test
@DisplayName("Should return root skill when baseDir itself has SKILL.md")
void testGetAllSkills_RootLevelSkill() throws IOException {
Path rootDir = tempDir.resolve("root-repo");
Files.createDirectories(rootDir);
Files.writeString(
rootDir.resolve("SKILL.md"),
"---\nname: my-root-skill\ndescription: Root Skill\n---\nContent",
StandardCharsets.UTF_8);

FileSystemSkillRepository repo = new FileSystemSkillRepository(rootDir);
List<AgentSkill> skills = repo.getAllSkills();

assertEquals(1, skills.size());
assertEquals("my-root-skill", skills.get(0).getName());
}

@Test
@DisplayName("Should load root skill by name via getSkill")
void testGetSkill_RootLevelSkill() throws IOException {
Path rootDir = tempDir.resolve("root-repo2");
Files.createDirectories(rootDir);
Files.writeString(
rootDir.resolve("SKILL.md"),
"---\nname: my-root-skill\ndescription: Root Skill\n---\nContent",
StandardCharsets.UTF_8);

FileSystemSkillRepository repo = new FileSystemSkillRepository(rootDir);
AgentSkill skill = repo.getSkill("my-root-skill");

assertNotNull(skill);
assertEquals("my-root-skill", skill.getName());
}

@Test
@DisplayName("Should find root skill via skillExists and getAllSkillNames")
void testSkillExistsAndGetNames_RootLevelSkill() throws IOException {
Path rootDir = tempDir.resolve("root-repo3");
Files.createDirectories(rootDir);
Files.writeString(
rootDir.resolve("SKILL.md"),
"---\nname: my-root-skill\ndescription: Root Skill\n---\nContent",
StandardCharsets.UTF_8);

FileSystemSkillRepository repo = new FileSystemSkillRepository(rootDir);

assertTrue(repo.skillExists("my-root-skill"));
assertFalse(repo.skillExists("nonexistent"));
assertEquals(List.of("my-root-skill"), repo.getAllSkillNames());
}

// ==================== Helper Methods ====================

private void createSampleSkill(String name, String description, String content)
throws IOException {
Path skillDir = skillsBaseDir.resolve(name);
Expand Down
Loading
Loading