use crate::skills::{self, Found, Root, Source, SKILL_FILE, SUPPORT_DIRS};
use crate::tools::{replace_file, str_arg, Tool, ToolError};
use crate::tools_patch as patch_tool;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::io::Write;
use std::path::PathBuf;
const MAX_WRITE_BYTES: usize = 256 * 1024;
const MAX_NAME_CHARS: usize = 64;
fn failed(message: String) -> ToolError {
ToolError::Failed(message)
}
fn invalid(message: String) -> ToolError {
ToolError::InvalidArgs(message)
}
fn available(report: &skills::Report) -> String {
let mut names: Vec<&str> = report.active().map(|(f, _)| f.name.as_str()).collect();
names.sort_unstable();
if names.is_empty() {
"none".into()
} else {
names.join(", ")
}
}
pub struct SkillViewTool {
roots: Vec<Root>,
only: Option<Vec<String>>,
}
impl SkillViewTool {
pub fn new(roots: Vec<Root>) -> Self {
Self { roots, only: None }
}
pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
self.only = only;
self
}
}
#[async_trait]
impl Tool for SkillViewTool {
fn name(&self) -> &str {
"skill_view"
}
fn description(&self) -> &str {
"Load a saved skill by name: its instructions, and the list of files it links. Pass \
`path` (for example `references/api.md`) to read one of those files instead. A skill's scripts \
are run with the `shell` tool, with `cwd` set to the skill's directory."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The skill's name, as listed in the skills index"
},
"path": {
"type": "string",
"description": "A file the skill links, relative to its directory: references/…, scripts/… or templates/…. Omit to read the skill itself."
}
},
"required": ["name"]
})
}
fn describe_call(&self, args: &Value) -> String {
let name = args["name"].as_str().unwrap_or("?");
match args["path"].as_str() {
Some(path) => format!("skill_view {name} {path}"),
None => format!("skill_view {name}"),
}
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let name = str_arg(&args, "name")?;
let report = skills::discover_only(&self.roots, self.only.as_deref());
let found = report.get(name).ok_or_else(|| {
failed(format!(
"no skill named {name:?}. Available: {}",
available(&report)
))
})?;
if let Some(reason) = found.broken_reason() {
return Err(failed(format!(
"skill {name:?} is broken and cannot be loaded: {reason} ({})",
found.path.display()
)));
}
match args.get("path").filter(|v| !v.is_null()) {
None => Ok(render_skill(found)),
Some(Value::String(path)) => read_linked(found, path),
Some(_) => Err(invalid("`path` must be a string".into())),
}
}
}
fn render_skill(found: &Found) -> String {
let body = found.skill().map(|s| s.body.as_str()).unwrap_or_default();
let mut out = format!(
"# skill: {} ({}, {})\n\n{body}\n",
found.name,
found.source.label(),
found.dir.display()
);
let linked = skills::linked_files(&found.dir);
if !linked.is_empty() {
out.push_str("\nLinked files (read one with `skill_view` and `path`):\n");
for file in &linked {
out.push_str(&format!("- {file}\n"));
}
}
out
}
fn read_linked(found: &Found, path: &str) -> Result<String, ToolError> {
let refuse = |why: String| failed(format!("skill {:?}: refused {path:?}: {why}", found.name));
let resolved = skills::resolve_inside(&found.dir, path).map_err(refuse)?;
let meta = std::fs::metadata(&resolved).map_err(|e| {
let linked = skills::linked_files(&found.dir);
let hint = if linked.is_empty() {
"this skill links no files".to_string()
} else {
format!("it links: {}", linked.join(", "))
};
refuse(format!("cannot read it ({e}); {hint}"))
})?;
if !meta.is_file() {
return Err(refuse("it is not a regular file".into()));
}
if meta.len() > skills::MAX_SKILL_FILE_BYTES {
return Err(refuse(format!(
"it is {} bytes and the limit for a file a skill loads is {}",
meta.len(),
skills::MAX_SKILL_FILE_BYTES
)));
}
let bytes = std::fs::read(&resolved).map_err(|e| refuse(format!("cannot read it: {e}")))?;
let text = String::from_utf8(bytes).map_err(|_| refuse("it is not UTF-8 text".into()))?;
Ok(format!("# skill: {} — {path}\n\n{text}", found.name))
}
pub const SKILL_SEARCH: &str = "skill_search";
const SEARCH_DEFAULT_LIMIT: usize = 8;
const SEARCH_MAX_LIMIT: usize = 20;
pub struct SkillSearchTool {
roots: Vec<Root>,
only: Option<Vec<String>>,
}
impl SkillSearchTool {
pub fn new(roots: Vec<Root>) -> Self {
Self { roots, only: None }
}
pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
self.only = only;
self
}
fn ranked<'a>(
&self,
active: &'a [(&'a Found, &'a skills::Skill)],
query: &str,
) -> Vec<&'a Found> {
let query = query.trim().to_lowercase();
let words: Vec<&str> = query.split_whitespace().collect();
let mut scored: Vec<(u8, std::cmp::Reverse<usize>, &Found)> = Vec::new();
for (found, skill) in active {
let name = found.name.to_lowercase();
let description = skill.meta.description.to_lowercase();
let tags = skill.meta.tags.join(" ").to_lowercase();
let text = format!("{name} {description} {tags}");
if words.is_empty() {
scored.push((5, std::cmp::Reverse(0), found));
continue;
}
let in_name = words.iter().filter(|w| name.contains(**w)).count();
let in_text = words.iter().filter(|w| text.contains(**w)).count();
let in_tags = words.iter().filter(|w| tags.contains(**w)).count();
let tier = if name.contains(&query) {
0
} else if in_name == words.len() {
1
} else if in_text == words.len() {
2
} else if in_tags > 0 {
3
} else if in_text > 0 {
4
} else {
continue;
};
scored.push((tier, std::cmp::Reverse(in_name + in_text), found));
}
scored.sort_by(|a, b| {
a.0.cmp(&b.0)
.then(a.1.cmp(&b.1))
.then(a.2.name.cmp(&b.2.name))
});
scored.into_iter().map(|(_, _, found)| found).collect()
}
}
#[async_trait]
impl Tool for SkillSearchTool {
fn name(&self) -> &str {
SKILL_SEARCH
}
fn description(&self) -> &str {
"Find a skill the index did not have room to list: keyword search over every skill's \
name, description and tags. Use it when the index says skills were left out, then call \
`skill_view` on the one that fits. A skill already named in the index needs neither."
}
fn parameters(&self) -> Value {
json!({"type":"object","properties":{
"query":{"type":"string","description":"Words from the task: a subject, a tool name, a format. Empty lists every skill that loaded."},
"limit":{"type":"integer","description":format!("How many to return at most. Default {SEARCH_DEFAULT_LIMIT}, maximum {SEARCH_MAX_LIMIT}.")}
},"required":[]})
}
fn describe_call(&self, args: &Value) -> String {
format!(
"skill_search {:?}",
args["query"].as_str().unwrap_or("(everything)")
)
}
fn needs_approval(&self, _args: &Value) -> bool {
false
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
let query = args["query"].as_str().unwrap_or("").to_string();
let limit = args["limit"]
.as_u64()
.map(|n| (n as usize).clamp(1, SEARCH_MAX_LIMIT))
.unwrap_or(SEARCH_DEFAULT_LIMIT);
let report = skills::discover_only(&self.roots, self.only.as_deref());
let active: Vec<(&Found, &skills::Skill)> = report.active().collect();
if active.is_empty() {
return Ok(format!(
"No skills loaded from {} root(s), so there is nothing to find.",
self.roots.len()
));
}
let found = self.ranked(&active, &query);
if found.is_empty() {
return Ok(format!(
"Nothing matched {query:?} among {} skill(s) that loaded. Try fewer words, or \
the name of the tool or format the task uses.",
active.len()
));
}
let mut out = format!("{} of {} skill(s) matched", found.len(), active.len());
if found.len() > limit {
out.push_str(&format!(" ({limit} shown)"));
}
out.push(':');
for found in found.iter().take(limit) {
let skill = found.skill().expect("active() yields loaded skills only");
out.push('\n');
out.push_str(&skills::entry_line(&skill.meta));
}
out.push_str("\n\n`skill_view` loads one by name.");
Ok(out)
}
}
pub struct SkillManageTool {
roots: Vec<Root>,
only: Option<Vec<String>>,
}
impl SkillManageTool {
pub fn new(roots: Vec<Root>) -> Self {
Self { roots, only: None }
}
pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
self.only = only;
self
}
fn create(&self, args: &Value) -> Result<String, ToolError> {
let name = str_arg(args, "name")?;
let description = str_arg(args, "description")?;
let body = str_arg(args, "body")?;
validate_name(name)?;
if description.trim().is_empty() || description.contains(['\n', '\r']) {
return Err(invalid(
"`description` must be one non-empty line: it is what the skills index shows"
.into(),
));
}
if body.len() > MAX_WRITE_BYTES {
return Err(invalid(format!(
"`body` is {} bytes; the limit is {MAX_WRITE_BYTES}",
body.len()
)));
}
let root = skills::user_root(&self.roots).ok_or_else(|| {
failed("cannot create a skill: there is no user skills directory (is HOME set?)".into())
})?;
let report = skills::discover_only(&self.roots, self.only.as_deref());
if let Some(existing) = report.found.iter().find(|f| f.name == name) {
return Err(failed(format!(
"a skill named {name:?} already exists at {} ({}); `create` never overwrites. \
Use `patch` to change it, or choose another name",
existing.path.display(),
existing.source.label()
)));
}
let text = format!(
"---\nname: {name}\ndescription: \"{}\"\n---\n\n{}\n",
description.replace('\\', "\\\\").replace('"', "\\\""),
body.trim()
);
match skills::parse(&text) {
Ok(skill)
if skill.meta.name == name && skill.meta.description == description.trim() => {}
Ok(_) => {
return Err(invalid(
"the description did not survive being written as frontmatter; simplify it"
.into(),
))
}
Err(reason) => return Err(invalid(format!("this would be a broken skill: {reason}"))),
}
let dir = root.dir.join(name);
std::fs::create_dir_all(&root.dir)
.map_err(|e| failed(format!("cannot create {}: {e}", root.dir.display())))?;
std::fs::create_dir(&dir).map_err(|e| {
failed(format!(
"cannot create {}: {e} (a directory of that name may already exist)",
dir.display()
))
})?;
let path = dir.join(SKILL_FILE);
let written = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.and_then(|mut f| f.write_all(text.as_bytes()));
if let Err(e) = written {
let _ = std::fs::remove_dir(&dir);
return Err(failed(format!("cannot write {}: {e}", path.display())));
}
Ok(format!(
"created skill {name:?} ({}) at {}\nIt is loadable now with `skill_view`; the skills index in the prompt picks it up next session.",
root.source.label(),
path.display()
))
}
fn patch(&self, args: &Value) -> Result<String, ToolError> {
let name = str_arg(args, "name")?;
let old = str_arg(args, "old")?;
let new = match args.get("new").filter(|v| !v.is_null()) {
None => "",
Some(Value::String(new)) => new.as_str(),
Some(_) => {
return Err(invalid(
"`new` must be a string; omit it to delete `old`".into(),
))
}
};
let rel = match args.get("path").filter(|v| !v.is_null()) {
None => SKILL_FILE,
Some(Value::String(rel)) => rel.as_str(),
Some(_) => return Err(invalid("`path` must be a string".into())),
};
if old.is_empty() {
return Err(invalid("`old` must not be empty".into()));
}
let (found, target) = self.writable(name, rel)?;
let current = std::fs::read(&target)
.map_err(|e| failed(format!("cannot read {}: {e}", target.display())))?;
let current = String::from_utf8(current)
.map_err(|_| failed(format!("{} is not UTF-8 text", target.display())))?;
let locations = patch_tool::hits(¤t, old);
match locations.len() {
1 => {}
0 => {
return Err(failed(format!(
"`old` does not occur in {} (skill {name:?}); view it with `skill_view` and copy the text exactly",
target.display()
)))
}
n => {
return Err(failed(format!(
"`old` occurs {n} times in {} (skill {name:?}); include more surrounding text so it matches once",
target.display()
)))
}
}
let updated = patch_tool::splice(¤t, &locations, new);
if rel == SKILL_FILE {
match skills::parse(&updated) {
Err(reason) if found.skill().is_some() => {
return Err(failed(format!(
"refused: this patch would break skill {name:?}: {reason}. Nothing was written"
)))
}
Ok(skill) if skill.meta.name != found.name => {
return Err(failed(format!(
"refused: this patch would rename skill {name:?} to {:?}. Nothing was written",
skill.meta.name
)))
}
_ => {}
}
}
replace_file(&target, &updated)?;
Ok(format!(
"patched {rel} of skill {name:?}: wrote {}",
target.display()
))
}
fn write_file(&self, args: &Value) -> Result<String, ToolError> {
let name = str_arg(args, "name")?;
let rel = str_arg(args, "path")?;
let content = str_arg(args, "content")?;
if content.len() > MAX_WRITE_BYTES {
return Err(invalid(format!(
"`content` is {} bytes; the limit is {MAX_WRITE_BYTES}",
content.len()
)));
}
let (found, target) = self.writable(name, rel)?;
if rel == SKILL_FILE {
return Err(invalid(
"use `patch` to change SKILL.md; `write_file` is for references/, scripts/ and templates/".into(),
));
}
let existed = match std::fs::symlink_metadata(&target) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(failed(format!(
"skill {:?}: refused {rel:?}: it is a symlink, and a write through one could land outside the skill",
found.name
)))
}
Ok(meta) if meta.is_dir() => {
return Err(failed(format!(
"skill {:?}: refused {rel:?}: it is a directory",
found.name
)))
}
Ok(_) => true,
Err(_) => false,
};
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| failed(format!("cannot create {}: {e}", parent.display())))?;
}
replace_file(&target, content)?;
Ok(format!(
"{} {rel} of skill {name:?} ({} bytes): wrote {}",
if existed { "replaced" } else { "created" },
content.len(),
target.display()
))
}
fn writable(&self, name: &str, rel: &str) -> Result<(Found, PathBuf), ToolError> {
let report = skills::discover_only(&self.roots, self.only.as_deref());
let found = report.get(name).ok_or_else(|| {
failed(format!(
"no skill named {name:?}. Available: {}. Use `create` to make one",
available(&report)
))
})?;
if let Source::Plugin(plugin) = &found.source {
return Err(failed(format!(
"skill {name:?} belongs to plugin {plugin:?} ({}); a plugin's files are not edited from here",
found.dir.display()
)));
}
let refuse = |why: &str| failed(format!("skill {name:?}: refused {rel:?}: {why}"));
let normalised = rel.replace('\\', "/");
let mut parts = normalised.split('/').filter(|p| !p.is_empty() && *p != ".");
let first = parts.next().unwrap_or("");
let rest = parts.count();
let allowed =
(first == SKILL_FILE && rest == 0) || (SUPPORT_DIRS.contains(&first) && rest >= 1);
if !allowed {
return Err(refuse(
"only SKILL.md and files under references/, scripts/ and templates/ can be written",
));
}
let target = skills::resolve_inside(&found.dir, rel).map_err(|why| refuse(&why))?;
Ok((found.clone(), target))
}
}
#[async_trait]
impl Tool for SkillManageTool {
fn name(&self) -> &str {
"skill_manage"
}
fn description(&self) -> &str {
"Save or improve a skill — a reusable procedure for a kind of task. `create` makes a new \
skill (name, description, body); it refuses a name that exists. `patch` replaces one exact \
occurrence of `old` with `new` in SKILL.md or in a supporting file. `write_file` writes a file \
under the skill's references/, scripts/ or templates/. Each reports the path it wrote."
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["create", "patch", "write_file"],
"description": "create a new skill; patch text in an existing one; or write a supporting file"
},
"name": {
"type": "string",
"description": "The skill's name: letters, digits, `-` and `_`"
},
"description": {
"type": "string",
"description": "For create: one line saying what the skill is for and when to use it"
},
"body": {
"type": "string",
"description": "For create: the instructions, in Markdown"
},
"old": {
"type": "string",
"description": "For patch: the exact text to replace; it must occur once"
},
"new": {
"type": "string",
"description": "For patch: the replacement (omit to delete `old`)"
},
"path": {
"type": "string",
"description": "For patch: the file to change (default SKILL.md). For write_file: where to write, under references/, scripts/ or templates/"
},
"content": {
"type": "string",
"description": "For write_file: the file's whole content"
}
},
"required": ["action", "name"]
})
}
fn describe_call(&self, args: &Value) -> String {
let action = args["action"].as_str().unwrap_or("?");
let name = args["name"].as_str().unwrap_or("?");
let short =
|key: &str| -> String { args[key].as_str().unwrap_or("").chars().take(60).collect() };
match action {
"create" => {
let at = skills::user_root(&self.roots)
.map(|r| r.dir.join(name).join(SKILL_FILE).display().to_string())
.unwrap_or_else(|| "?".into());
let body = args["body"].as_str().unwrap_or("");
format!(
"skill_manage create {name} at {at} ({:?}, {} chars of body, opens {:?})",
short("description"),
body.chars().count(),
opening(body, 80)
)
}
"patch" => format!(
"skill_manage patch {name} {}: {:?} -> {:?}",
args["path"].as_str().unwrap_or(SKILL_FILE),
short("old"),
short("new")
),
"write_file" => {
let path = args["path"].as_str().unwrap_or("?");
let content = args["content"].as_str().unwrap_or("");
let runs = if path.starts_with("scripts/") || path.ends_with(".sh") {
" — a script: `shell` can run it without asking again"
} else {
""
};
format!(
"skill_manage write_file {name} {path} ({} bytes, opens {:?}){runs}",
content.len(),
opening(content, 80)
)
}
_ => format!("skill_manage {action} {name}"),
}
}
async fn call(&self, args: Value) -> Result<String, ToolError> {
match str_arg(&args, "action")? {
"create" => self.create(&args),
"patch" => self.patch(&args),
"write_file" => self.write_file(&args),
other => Err(invalid(format!(
"unknown action {other:?}: use create, patch or write_file"
))),
}
}
}
fn opening(content: &str, max: usize) -> String {
let collapsed = content.split_whitespace().collect::<Vec<_>>().join(" ");
let mut clipped: String = collapsed.chars().take(max).collect();
if collapsed.chars().count() > max {
clipped.push('…');
}
clipped
}
fn validate_name(name: &str) -> Result<(), ToolError> {
let ok = !name.is_empty()
&& name.chars().count() <= MAX_NAME_CHARS
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
if ok {
Ok(())
} else {
Err(invalid(format!(
"{name:?} is not a usable skill name: use 1 to {MAX_NAME_CHARS} letters, digits, `-` or `_`"
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
fn root(dir: &Path) -> Vec<Root> {
vec![Root {
source: Source::Shared,
dir: dir.join("skills"),
}]
}
fn write(path: &Path, body: &str) {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(path, body).unwrap();
}
fn backup(dir: &Path) {
let skill = dir.join("skills/backup");
write(
&skill.join("SKILL.md"),
"---\nname: backup\ndescription: back things up\n---\nRun the script.\n",
);
write(&skill.join("references/layout.md"), "the layout");
write(&skill.join("scripts/backup.sh"), "echo hi");
}
fn err(result: Result<String, ToolError>) -> String {
result.unwrap_err().to_string()
}
#[tokio::test]
async fn skill_search_finds_a_skill_the_index_could_not_name_and_says_what_it_scanned() {
let tmp = tempfile::tempdir().unwrap();
for (name, description) in [
("pipeline-step-01", "stage one of the media pipeline"),
("pipeline-step-31", "stage thirty-one of the media pipeline"),
("pipeline-step-40", "the last stage of the media pipeline"),
("ledger", "write a ledger entry"),
] {
write(
&tmp.path().join(format!("skills/{name}/SKILL.md")),
&format!(
"---\nname: {name}\ndescription: {description}\ntags: [media]\n---\nBody.\n"
),
);
}
let tool = SkillSearchTool::new(root(tmp.path()));
let (index, _) = skills::index(
&skills::discover(&root(tmp.path())),
skills::PREAMBLE.chars().count() + 60,
);
let listed = index.map(|i| i.names).unwrap_or_default();
assert!(
!listed.iter().any(|n| n == "pipeline-step-31"),
"{listed:?}"
);
let out = tool
.call(json!({"query": "media pipeline stage thirty-one"}))
.await
.unwrap();
assert!(out.contains("pipeline-step-31"), "{out}");
assert!(out.contains("of 4 skill(s) matched"), "the count: {out}");
let out = tool.call(json!({"query": "media"})).await.unwrap();
assert_eq!(out.matches("pipeline-step").count(), 3, "{out}");
let out = tool.call(json!({"query": "ledger"})).await.unwrap();
assert!(out.starts_with("1 of 4"), "{out}");
let out = tool.call(json!({"query": "kubernetes"})).await.unwrap();
assert!(out.contains("Nothing matched"), "{out}");
assert!(out.contains("among 4 skill(s)"), "{out}");
}
#[tokio::test]
async fn viewing_a_skill_returns_its_body_and_lists_the_files_it_links() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let out = SkillViewTool::new(root(tmp.path()))
.call(json!({"name": "backup"}))
.await
.unwrap();
assert!(out.contains("Run the script."), "{out}");
assert!(
!out.contains("description:"),
"the frontmatter is not the body: {out}"
);
assert!(out.contains("- references/layout.md"), "{out}");
assert!(out.contains("- scripts/backup.sh"), "{out}");
}
#[tokio::test]
async fn a_linked_file_is_readable_and_parent_traversal_is_refused_naming_the_skill() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
write(&tmp.path().join("secret.txt"), "not yours");
let tool = SkillViewTool::new(root(tmp.path()));
let out = tool
.call(json!({"name": "backup", "path": "references/layout.md"}))
.await
.unwrap();
assert!(out.contains("the layout"), "{out}");
for path in ["../../secret.txt", "references/../../../secret.txt"] {
let message = err(tool.call(json!({"name": "backup", "path": path})).await);
assert!(message.contains("backup"), "names the skill: {message}");
assert!(message.contains("`..`"), "gives the reason: {message}");
}
let message = err(tool
.call(json!({"name": "backup", "path": "/etc/passwd"}))
.await);
assert!(message.contains("absolute"), "{message}");
}
#[tokio::test]
async fn a_symlink_that_leaves_the_skill_directory_is_refused() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let outside = tmp.path().join("outside");
write(&outside.join("loot.txt"), "loot");
let skill = tmp.path().join("skills/backup");
std::os::unix::fs::symlink(&outside, skill.join("references/out")).unwrap();
std::os::unix::fs::symlink(outside.join("loot.txt"), skill.join("references/loot"))
.unwrap();
let tool = SkillViewTool::new(root(tmp.path()));
for path in ["references/out/loot.txt", "references/loot"] {
let message = err(tool.call(json!({"name": "backup", "path": path})).await);
assert!(
message.contains("outside the skill's directory"),
"{message}"
);
}
}
#[tokio::test]
async fn an_unknown_skill_lists_what_exists_and_a_broken_one_says_why() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
write(
&tmp.path().join("skills/bad/SKILL.md"),
"---\ndescription: x\n---\nbody\n",
);
let tool = SkillViewTool::new(root(tmp.path()));
let message = err(tool.call(json!({"name": "nope"})).await);
assert!(message.contains("Available: backup"), "{message}");
let message = err(tool.call(json!({"name": "bad"})).await);
assert!(
message.contains("broken") && message.contains("name"),
"{message}"
);
}
#[tokio::test]
async fn a_linked_file_over_the_size_limit_is_refused_rather_than_read() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let big = tmp.path().join("skills/backup/templates/big.txt");
write(&big, &"x".repeat(skills::MAX_SKILL_FILE_BYTES as usize + 1));
let tool = SkillViewTool::new(root(tmp.path()));
let message = err(tool
.call(json!({"name": "backup", "path": "templates/big.txt"}))
.await);
assert!(message.contains("limit"), "{message}");
assert!(message.contains("backup"), "names the skill: {message}");
}
#[tokio::test]
async fn an_argument_of_the_wrong_type_is_an_error_rather_than_a_silent_default() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let view = SkillViewTool::new(root(tmp.path()));
let message = err(view.call(json!({"name": "backup", "path": 7})).await);
assert!(message.contains("`path` must be a string"), "{message}");
let manage = SkillManageTool::new(root(tmp.path()));
let before = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
let message = err(manage
.call(json!({"action": "patch", "name": "backup", "old": "Run the script.", "new": 7}))
.await);
assert!(message.contains("`new` must be a string"), "{message}");
let after = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
assert_eq!(before, after, "nothing was written");
}
#[tokio::test]
async fn creating_a_skill_writes_a_loadable_file_and_reports_the_path() {
let tmp = tempfile::tempdir().unwrap();
let manage = SkillManageTool::new(root(tmp.path()));
let out = manage
.call(json!({
"action": "create", "name": "greet",
"description": "say \"hello\": nicely",
"body": "1. Say hello."
}))
.await
.unwrap();
let path = tmp.path().join("skills/greet/SKILL.md");
assert!(out.contains(&path.display().to_string()), "{out}");
let seen = SkillViewTool::new(root(tmp.path()))
.call(json!({"name": "greet"}))
.await
.unwrap();
assert!(seen.contains("1. Say hello."), "{seen}");
let skill = skills::parse(&std::fs::read_to_string(path).unwrap()).unwrap();
assert_eq!(skill.meta.description, "say \"hello\": nicely");
}
#[tokio::test]
async fn creating_a_skill_refuses_an_existing_name_and_leaves_it_untouched() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let manage = SkillManageTool::new(root(tmp.path()));
let message = err(manage
.call(json!({
"action": "create", "name": "backup",
"description": "x", "body": "replacement"
}))
.await);
assert!(message.contains("already exists"), "{message}");
assert!(
message.contains("skills/backup/SKILL.md"),
"names the path: {message}"
);
let kept = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
assert!(kept.contains("Run the script."), "{kept}");
}
#[tokio::test]
async fn a_broken_skill_still_blocks_a_create_of_its_name() {
let tmp = tempfile::tempdir().unwrap();
write(&tmp.path().join("skills/bad/SKILL.md"), "---\nname: bad\n");
let manage = SkillManageTool::new(root(tmp.path()));
let message = err(manage
.call(json!({"action": "create", "name": "bad", "description": "x", "body": "b"}))
.await);
assert!(message.contains("already exists"), "{message}");
}
#[tokio::test]
async fn create_rejects_names_that_could_leave_the_skills_directory_and_multiline_descriptions()
{
let tmp = tempfile::tempdir().unwrap();
let manage = SkillManageTool::new(root(tmp.path()));
for name in ["../evil", "a/b", "", "has space"] {
let result = manage
.call(json!({"action": "create", "name": name, "description": "d", "body": "b"}))
.await;
assert!(matches!(result, Err(ToolError::InvalidArgs(_))), "{name:?}");
}
let result = manage
.call(json!({"action": "create", "name": "ok", "description": "a\nb", "body": "b"}))
.await;
assert!(matches!(result, Err(ToolError::InvalidArgs(_))));
let result = manage
.call(json!({"action": "create", "name": "ok", "description": "d", "body": " "}))
.await;
assert!(result.is_err(), "an empty body would be a broken skill");
assert!(!tmp.path().join("skills").exists() || !tmp.path().join("skills/ok").exists());
}
#[tokio::test]
async fn patching_replaces_exactly_one_occurrence_and_refuses_zero_or_many() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
write(
&tmp.path().join("skills/backup/references/layout.md"),
"a b a",
);
let manage = SkillManageTool::new(root(tmp.path()));
let out = manage
.call(json!({"action": "patch", "name": "backup", "old": "Run the script.", "new": "Run it twice."}))
.await
.unwrap();
assert!(out.contains("skills/backup/SKILL.md"), "{out}");
let text = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
assert!(text.contains("Run it twice."), "{text}");
let message = err(manage
.call(json!({"action": "patch", "name": "backup", "path": "references/layout.md", "old": "a", "new": "z"}))
.await);
assert!(message.contains("occurs 2 times"), "{message}");
let message = err(manage
.call(json!({"action": "patch", "name": "backup", "old": "absent", "new": "z"}))
.await);
assert!(message.contains("does not occur"), "{message}");
}
#[tokio::test]
async fn a_patch_that_would_break_or_rename_the_skill_is_refused_and_writes_nothing() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let manage = SkillManageTool::new(root(tmp.path()));
let before = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
let message = err(manage
.call(json!({"action": "patch", "name": "backup", "old": "name: backup\n", "new": ""}))
.await);
assert!(message.contains("would break"), "{message}");
let message = err(manage
.call(json!({"action": "patch", "name": "backup", "old": "name: backup", "new": "name: other"}))
.await);
assert!(message.contains("rename"), "{message}");
let after = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
assert_eq!(before, after);
}
#[tokio::test]
async fn writing_a_supporting_file_stays_inside_the_three_directories_and_the_skill() {
let tmp = tempfile::tempdir().unwrap();
backup(tmp.path());
let manage = SkillManageTool::new(root(tmp.path()));
let out = manage
.call(json!({"action": "write_file", "name": "backup", "path": "scripts/new.sh", "content": "echo new"}))
.await
.unwrap();
assert!(
out.contains("created") && out.contains("scripts/new.sh"),
"{out}"
);
let out = manage
.call(json!({"action": "write_file", "name": "backup", "path": "scripts/new.sh", "content": "echo newer"}))
.await
.unwrap();
assert!(out.contains("replaced"), "{out}");
for path in [
"../x.md",
"notes.md",
"SKILL.md",
"/tmp/x",
"scripts/../../x",
] {
let result = manage
.call(
json!({"action": "write_file", "name": "backup", "path": path, "content": "x"}),
)
.await;
assert!(result.is_err(), "{path} should be refused");
}
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, tmp.path().join("skills/backup/templates")).unwrap();
let message = err(manage
.call(json!({"action": "write_file", "name": "backup", "path": "templates/x", "content": "x"}))
.await);
assert!(
message.contains("outside the skill's directory"),
"{message}"
);
assert!(!outside.join("x").exists());
}
#[tokio::test]
async fn a_plugins_skill_cannot_be_edited_from_here() {
let tmp = tempfile::tempdir().unwrap();
write(
&tmp.path().join("plug/skills/p/SKILL.md"),
"---\nname: p\n---\nbody\n",
);
let roots = vec![
Root {
source: Source::Shared,
dir: tmp.path().join("skills"),
},
Root {
source: Source::Plugin("plug".into()),
dir: tmp.path().join("plug/skills"),
},
];
let message = err(SkillManageTool::new(roots)
.call(json!({"action": "patch", "name": "p", "old": "body", "new": "x"}))
.await);
assert!(message.contains("plugin"), "{message}");
}
#[tokio::test]
async fn with_a_profile_a_new_skill_goes_to_the_profile_directory() {
let tmp = tempfile::tempdir().unwrap();
let roots = vec![
Root {
source: Source::Shared,
dir: tmp.path().join("skills"),
},
Root {
source: Source::Profile("work".into()),
dir: tmp.path().join("profiles/work/skills"),
},
Root {
source: Source::Workspace,
dir: tmp.path().join("ws/.eclipse/skills"),
},
];
let out = SkillManageTool::new(roots)
.call(json!({"action": "create", "name": "n", "description": "d", "body": "b"}))
.await
.unwrap();
assert!(out.contains("profiles/work/skills/n/SKILL.md"), "{out}");
}
#[test]
fn the_approval_prompt_says_where_a_create_will_write() {
let tmp = tempfile::tempdir().unwrap();
let manage = SkillManageTool::new(root(tmp.path()));
let line = manage.describe_call(&json!({
"action": "create", "name": "greet", "description": "d", "body": "abc"
}));
assert!(
line.contains(
&tmp.path()
.join("skills/greet/SKILL.md")
.display()
.to_string()
),
"{line}"
);
}
#[test]
fn the_approval_prompt_shows_what_a_script_starts_with_and_says_it_runs() {
let tmp = tempfile::tempdir().unwrap();
let manage = SkillManageTool::new(root(tmp.path()));
let line = manage.describe_call(&json!({
"action": "write_file",
"name": "greet",
"path": "scripts/deploy.sh",
"content": "#!/bin/sh\nset -eu\nrm -rf build\n"
}));
assert!(line.contains("scripts/deploy.sh"), "{line}");
assert!(line.contains("#!/bin/sh set -eu rm -rf build"), "{line}");
assert!(
line.contains("`shell` can run it without asking again"),
"the summary says the file is runnable: {line}"
);
let line = manage.describe_call(&json!({
"action": "write_file",
"name": "greet",
"path": "references/api.md",
"content": "# API\n"
}));
assert!(!line.contains("can run it"), "{line}");
assert!(line.contains("# API"), "{line}");
}
#[test]
fn the_preview_clips_by_char_and_collapses_whitespace() {
assert_eq!(opening("a\n\n b\t c", 40), "a b c");
assert_eq!(opening(&"日".repeat(10), 3), "日日日…");
assert_eq!(opening("short", 40), "short");
}
}