1use std::collections::HashMap;
13use std::io::Write;
14use std::path::{Path, PathBuf};
15
16use serde::Serialize;
17use serde_json::Value;
18
19use crate::error::{SkillError, SkillResult};
20
21const MAX_NAME_LEN: usize = 64;
23
24const SKILLS_DIR: &str = ".skills";
26
27pub fn validate_skill_name(name: &str) -> SkillResult<()> {
49 if name.is_empty() {
50 return Err(SkillError::Validation("skill name must not be empty".to_string()));
51 }
52
53 if name.chars().count() > MAX_NAME_LEN {
54 return Err(SkillError::Validation(format!(
55 "skill name must be at most {MAX_NAME_LEN} characters, got {}",
56 name.chars().count()
57 )));
58 }
59
60 if let Some(bad) = name.chars().find(|c| !matches!(c, 'a'..='z' | '0'..='9' | '-')) {
61 return Err(SkillError::Validation(format!(
62 "skill name must contain only lowercase letters, digits, and hyphens; found {bad:?} \
63 in {name:?}"
64 )));
65 }
66
67 if name.starts_with('-') || name.ends_with('-') {
68 return Err(SkillError::Validation(format!(
69 "skill name must not begin or end with a hyphen: {name:?}"
70 )));
71 }
72
73 Ok(())
74}
75
76#[derive(Debug, Serialize)]
81struct FrontmatterOut<'a> {
82 name: &'a str,
83 description: &'a str,
84 #[serde(skip_serializing_if = "Option::is_none")]
85 version: &'a Option<String>,
86 #[serde(skip_serializing_if = "Option::is_none")]
87 license: &'a Option<String>,
88 #[serde(skip_serializing_if = "Option::is_none")]
89 compatibility: &'a Option<String>,
90 #[serde(skip_serializing_if = "Vec::is_empty")]
91 tags: &'a Vec<String>,
92 #[serde(rename = "allowed-tools", skip_serializing_if = "Vec::is_empty")]
93 allowed_tools: &'a Vec<String>,
94 #[serde(skip_serializing_if = "Vec::is_empty")]
95 references: &'a Vec<String>,
96 #[serde(skip_serializing_if = "is_false")]
97 trigger: bool,
98 #[serde(skip_serializing_if = "Option::is_none")]
99 hint: &'a Option<String>,
100 #[serde(skip_serializing_if = "HashMap::is_empty")]
101 metadata: &'a HashMap<String, Value>,
102 #[serde(skip_serializing_if = "Vec::is_empty")]
103 triggers: &'a Vec<String>,
104}
105
106fn is_false(value: &bool) -> bool {
107 !*value
108}
109
110#[derive(Debug, Clone, Default)]
128pub struct SkillDraft {
129 name: String,
130 description: String,
131 body: String,
132 version: Option<String>,
133 license: Option<String>,
134 compatibility: Option<String>,
135 tags: Vec<String>,
136 allowed_tools: Vec<String>,
137 references: Vec<String>,
138 trigger: bool,
139 hint: Option<String>,
140 metadata: HashMap<String, Value>,
141 triggers: Vec<String>,
142}
143
144impl SkillDraft {
145 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
147 Self { name: name.into(), description: description.into(), ..Default::default() }
148 }
149
150 pub fn with_body(mut self, body: impl Into<String>) -> Self {
152 self.body = body.into();
153 self
154 }
155
156 pub fn with_version(mut self, version: impl Into<String>) -> Self {
158 self.version = Some(version.into());
159 self
160 }
161
162 pub fn with_license(mut self, license: impl Into<String>) -> Self {
164 self.license = Some(license.into());
165 self
166 }
167
168 pub fn with_compatibility(mut self, compatibility: impl Into<String>) -> Self {
170 self.compatibility = Some(compatibility.into());
171 self
172 }
173
174 pub fn with_tags<I, S>(mut self, tags: I) -> Self
176 where
177 I: IntoIterator<Item = S>,
178 S: Into<String>,
179 {
180 self.tags = tags.into_iter().map(Into::into).collect();
181 self
182 }
183
184 pub fn with_allowed_tools<I, S>(mut self, tools: I) -> Self
186 where
187 I: IntoIterator<Item = S>,
188 S: Into<String>,
189 {
190 self.allowed_tools = tools.into_iter().map(Into::into).collect();
191 self
192 }
193
194 pub fn with_references<I, S>(mut self, references: I) -> Self
196 where
197 I: IntoIterator<Item = S>,
198 S: Into<String>,
199 {
200 self.references = references.into_iter().map(Into::into).collect();
201 self
202 }
203
204 pub fn with_trigger(mut self, trigger: bool) -> Self {
206 self.trigger = trigger;
207 self
208 }
209
210 pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
212 self.hint = Some(hint.into());
213 self
214 }
215
216 pub fn with_metadata(mut self, metadata: HashMap<String, Value>) -> Self {
221 self.metadata = metadata;
222 self
223 }
224
225 pub fn with_metadata_entry(mut self, key: impl Into<String>, value: Value) -> Self {
227 self.metadata.insert(key.into(), value);
228 self
229 }
230
231 pub fn with_triggers<I, S>(mut self, triggers: I) -> Self
233 where
234 I: IntoIterator<Item = S>,
235 S: Into<String>,
236 {
237 self.triggers = triggers.into_iter().map(Into::into).collect();
238 self
239 }
240
241 pub fn name(&self) -> &str {
243 &self.name
244 }
245
246 pub fn validate(&self) -> SkillResult<()> {
252 validate_skill_name(&self.name)?;
253
254 if self.description.trim().is_empty() {
255 return Err(SkillError::Validation(format!(
256 "skill {:?} must have a non-empty description; it is what an agent matches on",
257 self.name
258 )));
259 }
260
261 Ok(())
262 }
263
264 pub fn to_markdown(&self) -> SkillResult<String> {
274 self.validate()?;
275
276 let frontmatter = serde_saphyr::to_string(&FrontmatterOut {
277 name: &self.name,
278 description: &self.description,
279 version: &self.version,
280 license: &self.license,
281 compatibility: &self.compatibility,
282 tags: &self.tags,
283 allowed_tools: &self.allowed_tools,
284 references: &self.references,
285 trigger: self.trigger,
286 hint: &self.hint,
287 metadata: &self.metadata,
288 triggers: &self.triggers,
289 })
290 .map_err(|error| SkillError::Yaml { message: error.to_string() })?;
291
292 Ok(format!("---\n{}---\n\n{}\n", frontmatter, self.body.trim()))
293 }
294}
295
296#[derive(Debug, Clone)]
319pub struct SkillWriter {
320 root: PathBuf,
321}
322
323impl SkillWriter {
324 pub fn new(root: impl Into<PathBuf>) -> Self {
328 Self { root: root.into() }
329 }
330
331 pub fn skills_dir(&self) -> PathBuf {
333 self.root.join(SKILLS_DIR)
334 }
335
336 pub fn path_for(&self, name: &str) -> SkillResult<PathBuf> {
342 validate_skill_name(name)?;
343 Ok(self.skills_dir().join(format!("{name}.md")))
344 }
345
346 pub fn write(&self, draft: &SkillDraft) -> SkillResult<PathBuf> {
357 let rendered = draft.to_markdown()?;
358 let path = self.path_for(&draft.name)?;
359
360 let dir = self.skills_dir();
361 std::fs::create_dir_all(&dir)?;
362
363 let mut temporary = tempfile::NamedTempFile::new_in(&dir)?;
366 temporary.write_all(rendered.as_bytes())?;
367 temporary.as_file().sync_all()?;
368 temporary.persist(&path).map_err(|error| SkillError::Io(error.error))?;
369
370 #[cfg(unix)]
374 std::fs::File::open(&dir)?.sync_all()?;
375
376 tracing::debug!(skill = %draft.name, path = %path.display(), "wrote skill");
377 Ok(path)
378 }
379
380 pub fn remove(&self, name: &str) -> SkillResult<bool> {
387 let path = self.path_for(name)?;
388
389 match std::fs::remove_file(&path) {
390 Ok(()) => {
391 tracing::debug!(skill = %name, "removed skill");
392 Ok(true)
393 }
394 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
395 Err(err) => Err(SkillError::Io(err)),
396 }
397 }
398
399 pub fn exists(&self, name: &str) -> SkillResult<bool> {
405 Ok(self.path_for(name)?.is_file())
406 }
407
408 pub fn root(&self) -> &Path {
410 &self.root
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use crate::index::load_skill_index;
418 use crate::parser::parse_skill_markdown;
419
420 #[test]
421 fn valid_names_are_accepted() {
422 for name in ["a", "disk-triage", "sweep-2", "0", &"x".repeat(MAX_NAME_LEN)] {
423 assert!(validate_skill_name(name).is_ok(), "should accept {name:?}");
424 }
425 }
426
427 #[test]
428 fn invalid_names_are_rejected() {
429 for name in [
430 "",
431 "Disk-Triage",
432 "disk triage",
433 "disk_triage",
434 "-leading",
435 "trailing-",
436 "../escape",
437 "nested/name",
438 "dot.name",
439 &"x".repeat(MAX_NAME_LEN + 1),
440 ] {
441 assert!(validate_skill_name(name).is_err(), "should reject {name:?}");
442 }
443 }
444
445 #[test]
446 fn a_draft_round_trips_through_the_parser() {
447 let draft = SkillDraft::new("disk-triage", "Diagnose low disk space")
448 .with_body("1. Check largest directories.\n2. Report growth rate.")
449 .with_version("1.2.3")
450 .with_license("Apache-2.0")
451 .with_compatibility("Requires read access to the filesystem")
452 .with_tags(["ops", "storage"])
453 .with_allowed_tools(["read_file", "run_command"])
454 .with_references(["references/thresholds.md"])
455 .with_trigger(true)
456 .with_hint("name a mount point")
457 .with_triggers(["*.log"])
458 .with_metadata_entry("incident", Value::from("INC-42"));
459
460 let rendered = draft.to_markdown().expect("renders");
461 let parsed = parse_skill_markdown(Path::new("disk-triage.md"), &rendered).expect("parses");
462
463 assert_eq!(parsed.name, "disk-triage");
464 assert_eq!(parsed.description, "Diagnose low disk space");
465 assert_eq!(parsed.version.as_deref(), Some("1.2.3"));
466 assert_eq!(parsed.license.as_deref(), Some("Apache-2.0"));
467 assert_eq!(parsed.compatibility.as_deref(), Some("Requires read access to the filesystem"));
468 assert_eq!(parsed.tags, vec!["ops", "storage"]);
469 assert_eq!(parsed.allowed_tools, vec!["read_file", "run_command"]);
470 assert_eq!(parsed.references, vec!["references/thresholds.md"]);
471 assert!(parsed.trigger);
472 assert_eq!(parsed.hint.as_deref(), Some("name a mount point"));
473 assert_eq!(parsed.triggers, vec!["*.log"]);
474 assert_eq!(parsed.metadata.get("incident"), Some(&Value::from("INC-42")));
475 assert_eq!(parsed.body, "1. Check largest directories.\n2. Report growth rate.");
476 }
477
478 #[test]
479 fn yaml_significant_text_round_trips_through_the_parser() {
480 let draft = SkillDraft::new("yaml-hostile", "Fix: \"quoted\" text, # not a comment")
481 .with_body("Body.")
482 .with_version("1.0")
483 .with_license("no")
484 .with_tags(["- dash", "key: value", "null", "üñíçødé"])
485 .with_hint("[brackets] and {braces}")
486 .with_metadata_entry(
487 "nested",
488 serde_json::json!({ "list": [1, "two"], "flag": false }),
489 );
490
491 let rendered = draft.to_markdown().expect("renders");
492 let parsed =
493 parse_skill_markdown(Path::new("yaml-hostile.md"), &rendered).expect("parses back");
494
495 assert_eq!(parsed.description, "Fix: \"quoted\" text, # not a comment");
496 assert_eq!(
497 parsed.version.as_deref(),
498 Some("1.0"),
499 "a numeric-looking string stays a string"
500 );
501 assert_eq!(parsed.license.as_deref(), Some("no"));
502 assert_eq!(parsed.tags, vec!["- dash", "key: value", "null", "üñíçødé"]);
503 assert_eq!(parsed.hint.as_deref(), Some("[brackets] and {braces}"));
504 assert_eq!(
505 parsed.metadata.get("nested"),
506 Some(&serde_json::json!({ "list": [1, "two"], "flag": false }))
507 );
508 }
509
510 #[test]
511 fn a_minimal_draft_omits_unset_fields() {
512 let rendered = SkillDraft::new("minimal", "Only the required fields")
513 .with_body("Body.")
514 .to_markdown()
515 .expect("renders");
516
517 for absent in ["version:", "license:", "tags:", "allowed-tools:", "trigger:", "metadata:"] {
518 assert!(!rendered.contains(absent), "{absent} should be omitted from:\n{rendered}");
519 }
520 assert!(parse_skill_markdown(Path::new("minimal.md"), &rendered).is_ok());
521 }
522
523 #[test]
524 fn an_empty_description_is_rejected() {
525 let error = SkillDraft::new("named", " ")
526 .with_body("Body.")
527 .to_markdown()
528 .expect_err("an empty description must not be written");
529
530 assert!(error.to_string().contains("description"), "got {error}");
531 }
532
533 #[test]
534 fn an_invalid_name_is_rejected_before_any_file_is_touched() {
535 let root = tempfile::tempdir().expect("tempdir");
536 let writer = SkillWriter::new(root.path());
537
538 assert!(writer.write(&SkillDraft::new("../escape", "Traversal attempt")).is_err());
539 assert!(
540 !root.path().join(SKILLS_DIR).exists(),
541 "a rejected name must not create the skills directory"
542 );
543 }
544
545 #[test]
546 fn a_written_skill_is_discovered_by_the_index() {
547 let root = tempfile::tempdir().expect("tempdir");
548 let writer = SkillWriter::new(root.path());
549
550 let path = writer
551 .write(
552 &SkillDraft::new("disk-triage", "Diagnose low disk space")
553 .with_body("Check the largest directories."),
554 )
555 .expect("writes");
556
557 assert!(path.is_file());
558 let index = load_skill_index(root.path()).expect("index loads");
559 let found = index.find_by_name("disk-triage").expect("skill is indexed");
560 assert_eq!(found.description, "Diagnose low disk space");
561 assert_eq!(found.body, "Check the largest directories.");
562 }
563
564 #[test]
565 fn writing_the_same_name_replaces_the_previous_skill() {
566 let root = tempfile::tempdir().expect("tempdir");
567 let writer = SkillWriter::new(root.path());
568
569 writer.write(&SkillDraft::new("sweep", "First").with_body("One.")).expect("first write");
570 writer.write(&SkillDraft::new("sweep", "Second").with_body("Two.")).expect("second write");
571
572 let index = load_skill_index(root.path()).expect("index loads");
573 assert_eq!(index.len(), 1, "replacing must not leave a duplicate");
574 assert_eq!(index.find_by_name("sweep").expect("present").description, "Second");
575 }
576
577 #[test]
578 fn concurrent_writers_do_not_share_a_temporary_path() {
579 let root = tempfile::tempdir().expect("tempdir");
580 let writer = SkillWriter::new(root.path());
581
582 std::thread::scope(|scope| {
583 let first = writer.clone();
584 scope.spawn(move || {
585 first
586 .write(&SkillDraft::new("first", "First skill").with_body("One."))
587 .expect("first write");
588 });
589 let second = writer.clone();
590 scope.spawn(move || {
591 second
592 .write(&SkillDraft::new("second", "Second skill").with_body("Two."))
593 .expect("second write");
594 });
595 });
596
597 let index = load_skill_index(root.path()).expect("index loads");
598 assert!(index.find_by_name("first").is_some());
599 assert!(index.find_by_name("second").is_some());
600 }
601
602 #[test]
603 fn writing_leaves_no_temporary_file_behind() {
604 let root = tempfile::tempdir().expect("tempdir");
605 let writer = SkillWriter::new(root.path());
606 writer.write(&SkillDraft::new("sweep", "Description").with_body("Body.")).expect("writes");
607
608 let leftovers: Vec<_> = std::fs::read_dir(writer.skills_dir())
609 .expect("read dir")
610 .filter_map(|entry| entry.ok())
611 .map(|entry| entry.file_name().to_string_lossy().to_string())
612 .filter(|name| name.ends_with(".tmp"))
613 .collect();
614
615 assert!(leftovers.is_empty(), "found temporary files: {leftovers:?}");
616 }
617
618 #[test]
619 fn remove_reports_whether_a_skill_was_present() {
620 let root = tempfile::tempdir().expect("tempdir");
621 let writer = SkillWriter::new(root.path());
622 writer.write(&SkillDraft::new("sweep", "Description").with_body("Body.")).expect("writes");
623
624 assert!(writer.exists("sweep").expect("exists"));
625 assert!(writer.remove("sweep").expect("removes"), "the skill was present");
626 assert!(!writer.remove("sweep").expect("second remove"), "already gone");
627 assert!(!writer.exists("sweep").expect("exists"));
628 }
629
630 #[test]
631 fn remove_rejects_an_invalid_name() {
632 let root = tempfile::tempdir().expect("tempdir");
633 let writer = SkillWriter::new(root.path());
634
635 assert!(writer.remove("../escape").is_err());
636 }
637}