1use crate::skills::{self, Found, Root, Source, SKILL_FILE, SUPPORT_DIRS};
15use crate::tools::{replace_file, str_arg, Tool, ToolError};
16use crate::tools_patch as patch_tool;
17use async_trait::async_trait;
18use serde_json::{json, Value};
19use std::io::Write;
20use std::path::PathBuf;
21
22const MAX_WRITE_BYTES: usize = 256 * 1024;
25
26const MAX_NAME_CHARS: usize = 64;
28
29fn failed(message: String) -> ToolError {
30 ToolError::Failed(message)
31}
32
33fn invalid(message: String) -> ToolError {
34 ToolError::InvalidArgs(message)
35}
36
37fn available(report: &skills::Report) -> String {
39 let mut names: Vec<&str> = report.active().map(|(f, _)| f.name.as_str()).collect();
40 names.sort_unstable();
41 if names.is_empty() {
42 "none".into()
43 } else {
44 names.join(", ")
45 }
46}
47
48pub struct SkillViewTool {
50 roots: Vec<Root>,
51 only: Option<Vec<String>>,
54}
55
56impl SkillViewTool {
57 pub fn new(roots: Vec<Root>) -> Self {
58 Self { roots, only: None }
59 }
60
61 pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
63 self.only = only;
64 self
65 }
66}
67
68#[async_trait]
69impl Tool for SkillViewTool {
70 fn name(&self) -> &str {
71 "skill_view"
72 }
73
74 fn description(&self) -> &str {
75 "Load a saved skill by name: its instructions, and the list of files it links. Pass \
76`path` (for example `references/api.md`) to read one of those files instead. A skill's scripts \
77are run with the `shell` tool, with `cwd` set to the skill's directory."
78 }
79
80 fn parameters(&self) -> Value {
81 json!({
82 "type": "object",
83 "properties": {
84 "name": {
85 "type": "string",
86 "description": "The skill's name, as listed in the skills index"
87 },
88 "path": {
89 "type": "string",
90 "description": "A file the skill links, relative to its directory: references/…, scripts/… or templates/…. Omit to read the skill itself."
91 }
92 },
93 "required": ["name"]
94 })
95 }
96
97 fn describe_call(&self, args: &Value) -> String {
98 let name = args["name"].as_str().unwrap_or("?");
99 match args["path"].as_str() {
100 Some(path) => format!("skill_view {name} {path}"),
101 None => format!("skill_view {name}"),
102 }
103 }
104
105 async fn call(&self, args: Value) -> Result<String, ToolError> {
106 let name = str_arg(&args, "name")?;
107 let report = skills::discover_only(&self.roots, self.only.as_deref());
108 let found = report.get(name).ok_or_else(|| {
109 failed(format!(
110 "no skill named {name:?}. Available: {}",
111 available(&report)
112 ))
113 })?;
114 if let Some(reason) = found.broken_reason() {
115 return Err(failed(format!(
116 "skill {name:?} is broken and cannot be loaded: {reason} ({})",
117 found.path.display()
118 )));
119 }
120 match args.get("path").filter(|v| !v.is_null()) {
121 None => Ok(render_skill(found)),
122 Some(Value::String(path)) => read_linked(found, path),
123 Some(_) => Err(invalid("`path` must be a string".into())),
124 }
125 }
126}
127
128fn render_skill(found: &Found) -> String {
129 let body = found.skill().map(|s| s.body.as_str()).unwrap_or_default();
130 let mut out = format!(
131 "# skill: {} ({}, {})\n\n{body}\n",
132 found.name,
133 found.source.label(),
134 found.dir.display()
135 );
136 let linked = skills::linked_files(&found.dir);
137 if !linked.is_empty() {
138 out.push_str("\nLinked files (read one with `skill_view` and `path`):\n");
139 for file in &linked {
140 out.push_str(&format!("- {file}\n"));
141 }
142 }
143 out
144}
145
146fn read_linked(found: &Found, path: &str) -> Result<String, ToolError> {
147 let refuse = |why: String| failed(format!("skill {:?}: refused {path:?}: {why}", found.name));
148 let resolved = skills::resolve_inside(&found.dir, path).map_err(refuse)?;
149 let meta = std::fs::metadata(&resolved).map_err(|e| {
150 let linked = skills::linked_files(&found.dir);
151 let hint = if linked.is_empty() {
152 "this skill links no files".to_string()
153 } else {
154 format!("it links: {}", linked.join(", "))
155 };
156 refuse(format!("cannot read it ({e}); {hint}"))
157 })?;
158 if !meta.is_file() {
159 return Err(refuse("it is not a regular file".into()));
160 }
161 if meta.len() > skills::MAX_SKILL_FILE_BYTES {
162 return Err(refuse(format!(
163 "it is {} bytes and the limit for a file a skill loads is {}",
164 meta.len(),
165 skills::MAX_SKILL_FILE_BYTES
166 )));
167 }
168 let bytes = std::fs::read(&resolved).map_err(|e| refuse(format!("cannot read it: {e}")))?;
169 let text = String::from_utf8(bytes).map_err(|_| refuse("it is not UTF-8 text".into()))?;
170 Ok(format!("# skill: {} — {path}\n\n{text}", found.name))
171}
172
173pub const SKILL_SEARCH: &str = "skill_search";
180
181const SEARCH_DEFAULT_LIMIT: usize = 8;
183const SEARCH_MAX_LIMIT: usize = 20;
184
185pub struct SkillSearchTool {
186 roots: Vec<Root>,
187 only: Option<Vec<String>>,
189}
190
191impl SkillSearchTool {
192 pub fn new(roots: Vec<Root>) -> Self {
193 Self { roots, only: None }
194 }
195
196 pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
197 self.only = only;
198 self
199 }
200
201 fn ranked<'a>(
205 &self,
206 active: &'a [(&'a Found, &'a skills::Skill)],
207 query: &str,
208 ) -> Vec<&'a Found> {
209 let query = query.trim().to_lowercase();
210 let words: Vec<&str> = query.split_whitespace().collect();
211 let mut scored: Vec<(u8, std::cmp::Reverse<usize>, &Found)> = Vec::new();
212 for (found, skill) in active {
213 let name = found.name.to_lowercase();
214 let description = skill.meta.description.to_lowercase();
215 let tags = skill.meta.tags.join(" ").to_lowercase();
216 let text = format!("{name} {description} {tags}");
217 if words.is_empty() {
218 scored.push((5, std::cmp::Reverse(0), found));
219 continue;
220 }
221 let in_name = words.iter().filter(|w| name.contains(**w)).count();
222 let in_text = words.iter().filter(|w| text.contains(**w)).count();
223 let in_tags = words.iter().filter(|w| tags.contains(**w)).count();
224 let tier = if name.contains(&query) {
225 0
226 } else if in_name == words.len() {
227 1
228 } else if in_text == words.len() {
229 2
230 } else if in_tags > 0 {
231 3
232 } else if in_text > 0 {
233 4
234 } else {
235 continue;
236 };
237 scored.push((tier, std::cmp::Reverse(in_name + in_text), found));
238 }
239 scored.sort_by(|a, b| {
240 a.0.cmp(&b.0)
241 .then(a.1.cmp(&b.1))
242 .then(a.2.name.cmp(&b.2.name))
243 });
244 scored.into_iter().map(|(_, _, found)| found).collect()
245 }
246}
247
248#[async_trait]
249impl Tool for SkillSearchTool {
250 fn name(&self) -> &str {
251 SKILL_SEARCH
252 }
253
254 fn description(&self) -> &str {
255 "Find a skill the index did not have room to list: keyword search over every skill's \
256name, description and tags. Use it when the index says skills were left out, then call \
257`skill_view` on the one that fits. A skill already named in the index needs neither."
258 }
259
260 fn parameters(&self) -> Value {
261 json!({"type":"object","properties":{
262 "query":{"type":"string","description":"Words from the task: a subject, a tool name, a format. Empty lists every skill that loaded."},
263 "limit":{"type":"integer","description":format!("How many to return at most. Default {SEARCH_DEFAULT_LIMIT}, maximum {SEARCH_MAX_LIMIT}.")}
264 },"required":[]})
265 }
266
267 fn describe_call(&self, args: &Value) -> String {
268 format!(
269 "skill_search {:?}",
270 args["query"].as_str().unwrap_or("(everything)")
271 )
272 }
273
274 fn needs_approval(&self, _args: &Value) -> bool {
275 false
276 }
277
278 async fn call(&self, args: Value) -> Result<String, ToolError> {
279 let query = args["query"].as_str().unwrap_or("").to_string();
280 let limit = args["limit"]
281 .as_u64()
282 .map(|n| (n as usize).clamp(1, SEARCH_MAX_LIMIT))
283 .unwrap_or(SEARCH_DEFAULT_LIMIT);
284
285 let report = skills::discover_only(&self.roots, self.only.as_deref());
288 let active: Vec<(&Found, &skills::Skill)> = report.active().collect();
289 if active.is_empty() {
290 return Ok(format!(
291 "No skills loaded from {} root(s), so there is nothing to find.",
292 self.roots.len()
293 ));
294 }
295 let found = self.ranked(&active, &query);
296 if found.is_empty() {
297 return Ok(format!(
299 "Nothing matched {query:?} among {} skill(s) that loaded. Try fewer words, or \
300 the name of the tool or format the task uses.",
301 active.len()
302 ));
303 }
304 let mut out = format!("{} of {} skill(s) matched", found.len(), active.len());
305 if found.len() > limit {
306 out.push_str(&format!(" ({limit} shown)"));
307 }
308 out.push(':');
309 for found in found.iter().take(limit) {
310 let skill = found.skill().expect("active() yields loaded skills only");
311 out.push('\n');
312 out.push_str(&skills::entry_line(&skill.meta));
313 }
314 out.push_str("\n\n`skill_view` loads one by name.");
315 Ok(out)
316 }
317}
318
319pub struct SkillManageTool {
322 roots: Vec<Root>,
323 only: Option<Vec<String>>,
327}
328
329impl SkillManageTool {
330 pub fn new(roots: Vec<Root>) -> Self {
331 Self { roots, only: None }
332 }
333
334 pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
335 self.only = only;
336 self
337 }
338
339 fn create(&self, args: &Value) -> Result<String, ToolError> {
340 let name = str_arg(args, "name")?;
341 let description = str_arg(args, "description")?;
342 let body = str_arg(args, "body")?;
343 validate_name(name)?;
344 if description.trim().is_empty() || description.contains(['\n', '\r']) {
345 return Err(invalid(
346 "`description` must be one non-empty line: it is what the skills index shows"
347 .into(),
348 ));
349 }
350 if body.len() > MAX_WRITE_BYTES {
351 return Err(invalid(format!(
352 "`body` is {} bytes; the limit is {MAX_WRITE_BYTES}",
353 body.len()
354 )));
355 }
356 let root = skills::user_root(&self.roots).ok_or_else(|| {
357 failed("cannot create a skill: there is no user skills directory (is HOME set?)".into())
358 })?;
359
360 let report = skills::discover_only(&self.roots, self.only.as_deref());
361 if let Some(existing) = report.found.iter().find(|f| f.name == name) {
362 return Err(failed(format!(
363 "a skill named {name:?} already exists at {} ({}); `create` never overwrites. \
364Use `patch` to change it, or choose another name",
365 existing.path.display(),
366 existing.source.label()
367 )));
368 }
369
370 let text = format!(
371 "---\nname: {name}\ndescription: \"{}\"\n---\n\n{}\n",
372 description.replace('\\', "\\\\").replace('"', "\\\""),
373 body.trim()
374 );
375 match skills::parse(&text) {
377 Ok(skill)
378 if skill.meta.name == name && skill.meta.description == description.trim() => {}
379 Ok(_) => {
380 return Err(invalid(
381 "the description did not survive being written as frontmatter; simplify it"
382 .into(),
383 ))
384 }
385 Err(reason) => return Err(invalid(format!("this would be a broken skill: {reason}"))),
386 }
387
388 let dir = root.dir.join(name);
389 std::fs::create_dir_all(&root.dir)
390 .map_err(|e| failed(format!("cannot create {}: {e}", root.dir.display())))?;
391 std::fs::create_dir(&dir).map_err(|e| {
394 failed(format!(
395 "cannot create {}: {e} (a directory of that name may already exist)",
396 dir.display()
397 ))
398 })?;
399 let path = dir.join(SKILL_FILE);
400 let written = std::fs::OpenOptions::new()
401 .write(true)
402 .create_new(true)
403 .open(&path)
404 .and_then(|mut f| f.write_all(text.as_bytes()));
405 if let Err(e) = written {
406 let _ = std::fs::remove_dir(&dir);
407 return Err(failed(format!("cannot write {}: {e}", path.display())));
408 }
409 Ok(format!(
410 "created skill {name:?} ({}) at {}\nIt is loadable now with `skill_view`; the skills index in the prompt picks it up next session.",
411 root.source.label(),
412 path.display()
413 ))
414 }
415
416 fn patch(&self, args: &Value) -> Result<String, ToolError> {
417 let name = str_arg(args, "name")?;
418 let old = str_arg(args, "old")?;
419 let new = match args.get("new").filter(|v| !v.is_null()) {
422 None => "",
423 Some(Value::String(new)) => new.as_str(),
424 Some(_) => {
425 return Err(invalid(
426 "`new` must be a string; omit it to delete `old`".into(),
427 ))
428 }
429 };
430 let rel = match args.get("path").filter(|v| !v.is_null()) {
431 None => SKILL_FILE,
432 Some(Value::String(rel)) => rel.as_str(),
433 Some(_) => return Err(invalid("`path` must be a string".into())),
434 };
435 if old.is_empty() {
436 return Err(invalid("`old` must not be empty".into()));
437 }
438 let (found, target) = self.writable(name, rel)?;
439 let current = std::fs::read(&target)
440 .map_err(|e| failed(format!("cannot read {}: {e}", target.display())))?;
441 let current = String::from_utf8(current)
442 .map_err(|_| failed(format!("{} is not UTF-8 text", target.display())))?;
443 let locations = patch_tool::hits(¤t, old);
446 match locations.len() {
447 1 => {}
448 0 => {
449 return Err(failed(format!(
450 "`old` does not occur in {} (skill {name:?}); view it with `skill_view` and copy the text exactly",
451 target.display()
452 )))
453 }
454 n => {
455 return Err(failed(format!(
456 "`old` occurs {n} times in {} (skill {name:?}); include more surrounding text so it matches once",
457 target.display()
458 )))
459 }
460 }
461 let updated = patch_tool::splice(¤t, &locations, new);
462 if rel == SKILL_FILE {
463 match skills::parse(&updated) {
464 Err(reason) if found.skill().is_some() => {
465 return Err(failed(format!(
466 "refused: this patch would break skill {name:?}: {reason}. Nothing was written"
467 )))
468 }
469 Ok(skill) if skill.meta.name != found.name => {
470 return Err(failed(format!(
471 "refused: this patch would rename skill {name:?} to {:?}. Nothing was written",
472 skill.meta.name
473 )))
474 }
475 _ => {}
476 }
477 }
478 replace_file(&target, &updated)?;
479 Ok(format!(
480 "patched {rel} of skill {name:?}: wrote {}",
481 target.display()
482 ))
483 }
484
485 fn write_file(&self, args: &Value) -> Result<String, ToolError> {
486 let name = str_arg(args, "name")?;
487 let rel = str_arg(args, "path")?;
488 let content = str_arg(args, "content")?;
489 if content.len() > MAX_WRITE_BYTES {
490 return Err(invalid(format!(
491 "`content` is {} bytes; the limit is {MAX_WRITE_BYTES}",
492 content.len()
493 )));
494 }
495 let (found, target) = self.writable(name, rel)?;
496 if rel == SKILL_FILE {
497 return Err(invalid(
498 "use `patch` to change SKILL.md; `write_file` is for references/, scripts/ and templates/".into(),
499 ));
500 }
501 let existed = match std::fs::symlink_metadata(&target) {
502 Ok(meta) if meta.file_type().is_symlink() => {
503 return Err(failed(format!(
504 "skill {:?}: refused {rel:?}: it is a symlink, and a write through one could land outside the skill",
505 found.name
506 )))
507 }
508 Ok(meta) if meta.is_dir() => {
509 return Err(failed(format!(
510 "skill {:?}: refused {rel:?}: it is a directory",
511 found.name
512 )))
513 }
514 Ok(_) => true,
515 Err(_) => false,
516 };
517 if let Some(parent) = target.parent() {
518 std::fs::create_dir_all(parent)
519 .map_err(|e| failed(format!("cannot create {}: {e}", parent.display())))?;
520 }
521 replace_file(&target, content)?;
522 Ok(format!(
523 "{} {rel} of skill {name:?} ({} bytes): wrote {}",
524 if existed { "replaced" } else { "created" },
525 content.len(),
526 target.display()
527 ))
528 }
529
530 fn writable(&self, name: &str, rel: &str) -> Result<(Found, PathBuf), ToolError> {
534 let report = skills::discover_only(&self.roots, self.only.as_deref());
535 let found = report.get(name).ok_or_else(|| {
536 failed(format!(
537 "no skill named {name:?}. Available: {}. Use `create` to make one",
538 available(&report)
539 ))
540 })?;
541 if let Source::Plugin(plugin) = &found.source {
542 return Err(failed(format!(
543 "skill {name:?} belongs to plugin {plugin:?} ({}); a plugin's files are not edited from here",
544 found.dir.display()
545 )));
546 }
547 let refuse = |why: &str| failed(format!("skill {name:?}: refused {rel:?}: {why}"));
548 let normalised = rel.replace('\\', "/");
549 let mut parts = normalised.split('/').filter(|p| !p.is_empty() && *p != ".");
550 let first = parts.next().unwrap_or("");
551 let rest = parts.count();
552 let allowed =
553 (first == SKILL_FILE && rest == 0) || (SUPPORT_DIRS.contains(&first) && rest >= 1);
554 if !allowed {
555 return Err(refuse(
556 "only SKILL.md and files under references/, scripts/ and templates/ can be written",
557 ));
558 }
559 let target = skills::resolve_inside(&found.dir, rel).map_err(|why| refuse(&why))?;
560 Ok((found.clone(), target))
561 }
562}
563
564#[async_trait]
565impl Tool for SkillManageTool {
566 fn name(&self) -> &str {
567 "skill_manage"
568 }
569
570 fn description(&self) -> &str {
571 "Save or improve a skill — a reusable procedure for a kind of task. `create` makes a new \
572skill (name, description, body); it refuses a name that exists. `patch` replaces one exact \
573occurrence of `old` with `new` in SKILL.md or in a supporting file. `write_file` writes a file \
574under the skill's references/, scripts/ or templates/. Each reports the path it wrote."
575 }
576
577 fn parameters(&self) -> Value {
578 json!({
579 "type": "object",
580 "properties": {
581 "action": {
582 "type": "string",
583 "enum": ["create", "patch", "write_file"],
584 "description": "create a new skill; patch text in an existing one; or write a supporting file"
585 },
586 "name": {
587 "type": "string",
588 "description": "The skill's name: letters, digits, `-` and `_`"
589 },
590 "description": {
591 "type": "string",
592 "description": "For create: one line saying what the skill is for and when to use it"
593 },
594 "body": {
595 "type": "string",
596 "description": "For create: the instructions, in Markdown"
597 },
598 "old": {
599 "type": "string",
600 "description": "For patch: the exact text to replace; it must occur once"
601 },
602 "new": {
603 "type": "string",
604 "description": "For patch: the replacement (omit to delete `old`)"
605 },
606 "path": {
607 "type": "string",
608 "description": "For patch: the file to change (default SKILL.md). For write_file: where to write, under references/, scripts/ or templates/"
609 },
610 "content": {
611 "type": "string",
612 "description": "For write_file: the file's whole content"
613 }
614 },
615 "required": ["action", "name"]
616 })
617 }
618
619 fn describe_call(&self, args: &Value) -> String {
620 let action = args["action"].as_str().unwrap_or("?");
621 let name = args["name"].as_str().unwrap_or("?");
622 let short =
623 |key: &str| -> String { args[key].as_str().unwrap_or("").chars().take(60).collect() };
624 match action {
625 "create" => {
626 let at = skills::user_root(&self.roots)
627 .map(|r| r.dir.join(name).join(SKILL_FILE).display().to_string())
628 .unwrap_or_else(|| "?".into());
629 let body = args["body"].as_str().unwrap_or("");
630 format!(
631 "skill_manage create {name} at {at} ({:?}, {} chars of body, opens {:?})",
632 short("description"),
633 body.chars().count(),
634 opening(body, 80)
635 )
636 }
637 "patch" => format!(
638 "skill_manage patch {name} {}: {:?} -> {:?}",
639 args["path"].as_str().unwrap_or(SKILL_FILE),
640 short("old"),
641 short("new")
642 ),
643 "write_file" => {
644 let path = args["path"].as_str().unwrap_or("?");
645 let content = args["content"].as_str().unwrap_or("");
646 let runs = if path.starts_with("scripts/") || path.ends_with(".sh") {
649 " — a script: `shell` can run it without asking again"
650 } else {
651 ""
652 };
653 format!(
654 "skill_manage write_file {name} {path} ({} bytes, opens {:?}){runs}",
655 content.len(),
656 opening(content, 80)
657 )
658 }
659 _ => format!("skill_manage {action} {name}"),
660 }
661 }
662
663 async fn call(&self, args: Value) -> Result<String, ToolError> {
664 match str_arg(&args, "action")? {
665 "create" => self.create(&args),
666 "patch" => self.patch(&args),
667 "write_file" => self.write_file(&args),
668 other => Err(invalid(format!(
669 "unknown action {other:?}: use create, patch or write_file"
670 ))),
671 }
672 }
673}
674
675fn opening(content: &str, max: usize) -> String {
681 let collapsed = content.split_whitespace().collect::<Vec<_>>().join(" ");
682 let mut clipped: String = collapsed.chars().take(max).collect();
683 if collapsed.chars().count() > max {
684 clipped.push('…');
685 }
686 clipped
687}
688
689fn validate_name(name: &str) -> Result<(), ToolError> {
690 let ok = !name.is_empty()
691 && name.chars().count() <= MAX_NAME_CHARS
692 && name
693 .chars()
694 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
695 if ok {
696 Ok(())
697 } else {
698 Err(invalid(format!(
699 "{name:?} is not a usable skill name: use 1 to {MAX_NAME_CHARS} letters, digits, `-` or `_`"
700 )))
701 }
702}
703
704#[cfg(test)]
705mod tests {
706 use super::*;
707 use std::path::Path;
708
709 fn root(dir: &Path) -> Vec<Root> {
710 vec![Root {
711 source: Source::Shared,
712 dir: dir.join("skills"),
713 }]
714 }
715
716 fn write(path: &Path, body: &str) {
717 if let Some(parent) = path.parent() {
718 std::fs::create_dir_all(parent).unwrap();
719 }
720 std::fs::write(path, body).unwrap();
721 }
722
723 fn backup(dir: &Path) {
724 let skill = dir.join("skills/backup");
725 write(
726 &skill.join("SKILL.md"),
727 "---\nname: backup\ndescription: back things up\n---\nRun the script.\n",
728 );
729 write(&skill.join("references/layout.md"), "the layout");
730 write(&skill.join("scripts/backup.sh"), "echo hi");
731 }
732
733 fn err(result: Result<String, ToolError>) -> String {
734 result.unwrap_err().to_string()
735 }
736
737 #[tokio::test]
740 async fn skill_search_finds_a_skill_the_index_could_not_name_and_says_what_it_scanned() {
741 let tmp = tempfile::tempdir().unwrap();
742 for (name, description) in [
743 ("pipeline-step-01", "stage one of the media pipeline"),
744 ("pipeline-step-31", "stage thirty-one of the media pipeline"),
745 ("pipeline-step-40", "the last stage of the media pipeline"),
746 ("ledger", "write a ledger entry"),
747 ] {
748 write(
749 &tmp.path().join(format!("skills/{name}/SKILL.md")),
750 &format!(
751 "---\nname: {name}\ndescription: {description}\ntags: [media]\n---\nBody.\n"
752 ),
753 );
754 }
755 let tool = SkillSearchTool::new(root(tmp.path()));
756
757 let (index, _) = skills::index(
759 &skills::discover(&root(tmp.path())),
760 skills::PREAMBLE.chars().count() + 60,
762 );
763 let listed = index.map(|i| i.names).unwrap_or_default();
764 assert!(
765 !listed.iter().any(|n| n == "pipeline-step-31"),
766 "{listed:?}"
767 );
768
769 let out = tool
770 .call(json!({"query": "media pipeline stage thirty-one"}))
771 .await
772 .unwrap();
773 assert!(out.contains("pipeline-step-31"), "{out}");
774 assert!(out.contains("of 4 skill(s) matched"), "the count: {out}");
775
776 let out = tool.call(json!({"query": "media"})).await.unwrap();
778 assert_eq!(out.matches("pipeline-step").count(), 3, "{out}");
779
780 let out = tool.call(json!({"query": "ledger"})).await.unwrap();
782 assert!(out.starts_with("1 of 4"), "{out}");
783
784 let out = tool.call(json!({"query": "kubernetes"})).await.unwrap();
786 assert!(out.contains("Nothing matched"), "{out}");
787 assert!(out.contains("among 4 skill(s)"), "{out}");
788 }
789
790 #[tokio::test]
791 async fn viewing_a_skill_returns_its_body_and_lists_the_files_it_links() {
792 let tmp = tempfile::tempdir().unwrap();
793 backup(tmp.path());
794 let out = SkillViewTool::new(root(tmp.path()))
795 .call(json!({"name": "backup"}))
796 .await
797 .unwrap();
798 assert!(out.contains("Run the script."), "{out}");
799 assert!(
800 !out.contains("description:"),
801 "the frontmatter is not the body: {out}"
802 );
803 assert!(out.contains("- references/layout.md"), "{out}");
804 assert!(out.contains("- scripts/backup.sh"), "{out}");
805 }
806
807 #[tokio::test]
808 async fn a_linked_file_is_readable_and_parent_traversal_is_refused_naming_the_skill() {
809 let tmp = tempfile::tempdir().unwrap();
810 backup(tmp.path());
811 write(&tmp.path().join("secret.txt"), "not yours");
812 let tool = SkillViewTool::new(root(tmp.path()));
813
814 let out = tool
815 .call(json!({"name": "backup", "path": "references/layout.md"}))
816 .await
817 .unwrap();
818 assert!(out.contains("the layout"), "{out}");
819
820 for path in ["../../secret.txt", "references/../../../secret.txt"] {
821 let message = err(tool.call(json!({"name": "backup", "path": path})).await);
822 assert!(message.contains("backup"), "names the skill: {message}");
823 assert!(message.contains("`..`"), "gives the reason: {message}");
824 }
825 let message = err(tool
826 .call(json!({"name": "backup", "path": "/etc/passwd"}))
827 .await);
828 assert!(message.contains("absolute"), "{message}");
829 }
830
831 #[tokio::test]
832 async fn a_symlink_that_leaves_the_skill_directory_is_refused() {
833 let tmp = tempfile::tempdir().unwrap();
834 backup(tmp.path());
835 let outside = tmp.path().join("outside");
836 write(&outside.join("loot.txt"), "loot");
837 let skill = tmp.path().join("skills/backup");
838 std::os::unix::fs::symlink(&outside, skill.join("references/out")).unwrap();
839 std::os::unix::fs::symlink(outside.join("loot.txt"), skill.join("references/loot"))
840 .unwrap();
841
842 let tool = SkillViewTool::new(root(tmp.path()));
843 for path in ["references/out/loot.txt", "references/loot"] {
844 let message = err(tool.call(json!({"name": "backup", "path": path})).await);
845 assert!(
846 message.contains("outside the skill's directory"),
847 "{message}"
848 );
849 }
850 }
851
852 #[tokio::test]
853 async fn an_unknown_skill_lists_what_exists_and_a_broken_one_says_why() {
854 let tmp = tempfile::tempdir().unwrap();
855 backup(tmp.path());
856 write(
857 &tmp.path().join("skills/bad/SKILL.md"),
858 "---\ndescription: x\n---\nbody\n",
859 );
860 let tool = SkillViewTool::new(root(tmp.path()));
861
862 let message = err(tool.call(json!({"name": "nope"})).await);
863 assert!(message.contains("Available: backup"), "{message}");
864
865 let message = err(tool.call(json!({"name": "bad"})).await);
866 assert!(
867 message.contains("broken") && message.contains("name"),
868 "{message}"
869 );
870 }
871
872 #[tokio::test]
873 async fn a_linked_file_over_the_size_limit_is_refused_rather_than_read() {
874 let tmp = tempfile::tempdir().unwrap();
875 backup(tmp.path());
876 let big = tmp.path().join("skills/backup/templates/big.txt");
877 write(&big, &"x".repeat(skills::MAX_SKILL_FILE_BYTES as usize + 1));
878 let tool = SkillViewTool::new(root(tmp.path()));
879 let message = err(tool
880 .call(json!({"name": "backup", "path": "templates/big.txt"}))
881 .await);
882 assert!(message.contains("limit"), "{message}");
883 assert!(message.contains("backup"), "names the skill: {message}");
884 }
885
886 #[tokio::test]
887 async fn an_argument_of_the_wrong_type_is_an_error_rather_than_a_silent_default() {
888 let tmp = tempfile::tempdir().unwrap();
889 backup(tmp.path());
890 let view = SkillViewTool::new(root(tmp.path()));
891 let message = err(view.call(json!({"name": "backup", "path": 7})).await);
892 assert!(message.contains("`path` must be a string"), "{message}");
893
894 let manage = SkillManageTool::new(root(tmp.path()));
895 let before = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
896 let message = err(manage
897 .call(json!({"action": "patch", "name": "backup", "old": "Run the script.", "new": 7}))
898 .await);
899 assert!(message.contains("`new` must be a string"), "{message}");
900 let after = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
901 assert_eq!(before, after, "nothing was written");
902 }
903
904 #[tokio::test]
905 async fn creating_a_skill_writes_a_loadable_file_and_reports_the_path() {
906 let tmp = tempfile::tempdir().unwrap();
907 let manage = SkillManageTool::new(root(tmp.path()));
908 let out = manage
909 .call(json!({
910 "action": "create", "name": "greet",
911 "description": "say \"hello\": nicely",
912 "body": "1. Say hello."
913 }))
914 .await
915 .unwrap();
916 let path = tmp.path().join("skills/greet/SKILL.md");
917 assert!(out.contains(&path.display().to_string()), "{out}");
918
919 let seen = SkillViewTool::new(root(tmp.path()))
920 .call(json!({"name": "greet"}))
921 .await
922 .unwrap();
923 assert!(seen.contains("1. Say hello."), "{seen}");
924 let skill = skills::parse(&std::fs::read_to_string(path).unwrap()).unwrap();
925 assert_eq!(skill.meta.description, "say \"hello\": nicely");
926 }
927
928 #[tokio::test]
929 async fn creating_a_skill_refuses_an_existing_name_and_leaves_it_untouched() {
930 let tmp = tempfile::tempdir().unwrap();
931 backup(tmp.path());
932 let manage = SkillManageTool::new(root(tmp.path()));
933 let message = err(manage
934 .call(json!({
935 "action": "create", "name": "backup",
936 "description": "x", "body": "replacement"
937 }))
938 .await);
939 assert!(message.contains("already exists"), "{message}");
940 assert!(
941 message.contains("skills/backup/SKILL.md"),
942 "names the path: {message}"
943 );
944 let kept = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
945 assert!(kept.contains("Run the script."), "{kept}");
946 }
947
948 #[tokio::test]
949 async fn a_broken_skill_still_blocks_a_create_of_its_name() {
950 let tmp = tempfile::tempdir().unwrap();
951 write(&tmp.path().join("skills/bad/SKILL.md"), "---\nname: bad\n");
952 let manage = SkillManageTool::new(root(tmp.path()));
953 let message = err(manage
954 .call(json!({"action": "create", "name": "bad", "description": "x", "body": "b"}))
955 .await);
956 assert!(message.contains("already exists"), "{message}");
957 }
958
959 #[tokio::test]
960 async fn create_rejects_names_that_could_leave_the_skills_directory_and_multiline_descriptions()
961 {
962 let tmp = tempfile::tempdir().unwrap();
963 let manage = SkillManageTool::new(root(tmp.path()));
964 for name in ["../evil", "a/b", "", "has space"] {
965 let result = manage
966 .call(json!({"action": "create", "name": name, "description": "d", "body": "b"}))
967 .await;
968 assert!(matches!(result, Err(ToolError::InvalidArgs(_))), "{name:?}");
969 }
970 let result = manage
971 .call(json!({"action": "create", "name": "ok", "description": "a\nb", "body": "b"}))
972 .await;
973 assert!(matches!(result, Err(ToolError::InvalidArgs(_))));
974 let result = manage
975 .call(json!({"action": "create", "name": "ok", "description": "d", "body": " "}))
976 .await;
977 assert!(result.is_err(), "an empty body would be a broken skill");
978 assert!(!tmp.path().join("skills").exists() || !tmp.path().join("skills/ok").exists());
979 }
980
981 #[tokio::test]
982 async fn patching_replaces_exactly_one_occurrence_and_refuses_zero_or_many() {
983 let tmp = tempfile::tempdir().unwrap();
984 backup(tmp.path());
985 write(
986 &tmp.path().join("skills/backup/references/layout.md"),
987 "a b a",
988 );
989 let manage = SkillManageTool::new(root(tmp.path()));
990
991 let out = manage
992 .call(json!({"action": "patch", "name": "backup", "old": "Run the script.", "new": "Run it twice."}))
993 .await
994 .unwrap();
995 assert!(out.contains("skills/backup/SKILL.md"), "{out}");
996 let text = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
997 assert!(text.contains("Run it twice."), "{text}");
998
999 let message = err(manage
1000 .call(json!({"action": "patch", "name": "backup", "path": "references/layout.md", "old": "a", "new": "z"}))
1001 .await);
1002 assert!(message.contains("occurs 2 times"), "{message}");
1003 let message = err(manage
1004 .call(json!({"action": "patch", "name": "backup", "old": "absent", "new": "z"}))
1005 .await);
1006 assert!(message.contains("does not occur"), "{message}");
1007 }
1008
1009 #[tokio::test]
1010 async fn a_patch_that_would_break_or_rename_the_skill_is_refused_and_writes_nothing() {
1011 let tmp = tempfile::tempdir().unwrap();
1012 backup(tmp.path());
1013 let manage = SkillManageTool::new(root(tmp.path()));
1014 let before = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
1015
1016 let message = err(manage
1017 .call(json!({"action": "patch", "name": "backup", "old": "name: backup\n", "new": ""}))
1018 .await);
1019 assert!(message.contains("would break"), "{message}");
1020 let message = err(manage
1021 .call(json!({"action": "patch", "name": "backup", "old": "name: backup", "new": "name: other"}))
1022 .await);
1023 assert!(message.contains("rename"), "{message}");
1024
1025 let after = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
1026 assert_eq!(before, after);
1027 }
1028
1029 #[tokio::test]
1030 async fn writing_a_supporting_file_stays_inside_the_three_directories_and_the_skill() {
1031 let tmp = tempfile::tempdir().unwrap();
1032 backup(tmp.path());
1033 let manage = SkillManageTool::new(root(tmp.path()));
1034
1035 let out = manage
1036 .call(json!({"action": "write_file", "name": "backup", "path": "scripts/new.sh", "content": "echo new"}))
1037 .await
1038 .unwrap();
1039 assert!(
1040 out.contains("created") && out.contains("scripts/new.sh"),
1041 "{out}"
1042 );
1043 let out = manage
1044 .call(json!({"action": "write_file", "name": "backup", "path": "scripts/new.sh", "content": "echo newer"}))
1045 .await
1046 .unwrap();
1047 assert!(out.contains("replaced"), "{out}");
1048
1049 for path in [
1050 "../x.md",
1051 "notes.md",
1052 "SKILL.md",
1053 "/tmp/x",
1054 "scripts/../../x",
1055 ] {
1056 let result = manage
1057 .call(
1058 json!({"action": "write_file", "name": "backup", "path": path, "content": "x"}),
1059 )
1060 .await;
1061 assert!(result.is_err(), "{path} should be refused");
1062 }
1063
1064 let outside = tmp.path().join("outside");
1065 std::fs::create_dir_all(&outside).unwrap();
1066 std::os::unix::fs::symlink(&outside, tmp.path().join("skills/backup/templates")).unwrap();
1067 let message = err(manage
1068 .call(json!({"action": "write_file", "name": "backup", "path": "templates/x", "content": "x"}))
1069 .await);
1070 assert!(
1071 message.contains("outside the skill's directory"),
1072 "{message}"
1073 );
1074 assert!(!outside.join("x").exists());
1075 }
1076
1077 #[tokio::test]
1078 async fn a_plugins_skill_cannot_be_edited_from_here() {
1079 let tmp = tempfile::tempdir().unwrap();
1080 write(
1081 &tmp.path().join("plug/skills/p/SKILL.md"),
1082 "---\nname: p\n---\nbody\n",
1083 );
1084 let roots = vec![
1085 Root {
1086 source: Source::Shared,
1087 dir: tmp.path().join("skills"),
1088 },
1089 Root {
1090 source: Source::Plugin("plug".into()),
1091 dir: tmp.path().join("plug/skills"),
1092 },
1093 ];
1094 let message = err(SkillManageTool::new(roots)
1095 .call(json!({"action": "patch", "name": "p", "old": "body", "new": "x"}))
1096 .await);
1097 assert!(message.contains("plugin"), "{message}");
1098 }
1099
1100 #[tokio::test]
1101 async fn with_a_profile_a_new_skill_goes_to_the_profile_directory() {
1102 let tmp = tempfile::tempdir().unwrap();
1103 let roots = vec![
1104 Root {
1105 source: Source::Shared,
1106 dir: tmp.path().join("skills"),
1107 },
1108 Root {
1109 source: Source::Profile("work".into()),
1110 dir: tmp.path().join("profiles/work/skills"),
1111 },
1112 Root {
1113 source: Source::Workspace,
1114 dir: tmp.path().join("ws/.eclipse/skills"),
1115 },
1116 ];
1117 let out = SkillManageTool::new(roots)
1118 .call(json!({"action": "create", "name": "n", "description": "d", "body": "b"}))
1119 .await
1120 .unwrap();
1121 assert!(out.contains("profiles/work/skills/n/SKILL.md"), "{out}");
1122 }
1123
1124 #[test]
1125 fn the_approval_prompt_says_where_a_create_will_write() {
1126 let tmp = tempfile::tempdir().unwrap();
1127 let manage = SkillManageTool::new(root(tmp.path()));
1128 let line = manage.describe_call(&json!({
1129 "action": "create", "name": "greet", "description": "d", "body": "abc"
1130 }));
1131 assert!(
1132 line.contains(
1133 &tmp.path()
1134 .join("skills/greet/SKILL.md")
1135 .display()
1136 .to_string()
1137 ),
1138 "{line}"
1139 );
1140 }
1141
1142 #[test]
1146 fn the_approval_prompt_shows_what_a_script_starts_with_and_says_it_runs() {
1147 let tmp = tempfile::tempdir().unwrap();
1148 let manage = SkillManageTool::new(root(tmp.path()));
1149 let line = manage.describe_call(&json!({
1150 "action": "write_file",
1151 "name": "greet",
1152 "path": "scripts/deploy.sh",
1153 "content": "#!/bin/sh\nset -eu\nrm -rf build\n"
1154 }));
1155 assert!(line.contains("scripts/deploy.sh"), "{line}");
1156 assert!(line.contains("#!/bin/sh set -eu rm -rf build"), "{line}");
1157 assert!(
1158 line.contains("`shell` can run it without asking again"),
1159 "the summary says the file is runnable: {line}"
1160 );
1161
1162 let line = manage.describe_call(&json!({
1164 "action": "write_file",
1165 "name": "greet",
1166 "path": "references/api.md",
1167 "content": "# API\n"
1168 }));
1169 assert!(!line.contains("can run it"), "{line}");
1170 assert!(line.contains("# API"), "{line}");
1171 }
1172
1173 #[test]
1175 fn the_preview_clips_by_char_and_collapses_whitespace() {
1176 assert_eq!(opening("a\n\n b\t c", 40), "a b c");
1177 assert_eq!(opening(&"日".repeat(10), 3), "日日日…");
1178 assert_eq!(opening("short", 40), "short");
1179 }
1180}