1use crate::local::{Validator, frontmatter};
7use serde_json::Value;
8use std::sync::Arc;
9
10const MAX_SKILL_BYTES: usize = 64 * 1024;
11const MAX_INSTRUCTION_BYTES: usize = 16 * 1024;
12
13fn line_terminator(ch: char) -> bool {
14 matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
15}
16
17fn field<'a>(frontmatter: &'a str, key: &str) -> Option<&'a str> {
19 let prefix = format!("{key}:");
20 let starts = std::iter::once(0).chain(
21 frontmatter
22 .char_indices()
23 .filter(|(_, ch)| line_terminator(*ch))
24 .map(|(at, ch)| at + ch.len_utf8()),
25 );
26 for start in starts {
27 let Some(rest) = frontmatter[start..].strip_prefix(&prefix) else {
28 continue;
29 };
30 let skipped = rest.trim_start_matches(jsrt::string::is_space);
32 let line_end = skipped.find(line_terminator).unwrap_or(skipped.len());
33 if line_end > 0 {
34 return Some(jsrt::string::trim(&skipped[..line_end]));
35 }
36 let spaces = &rest[..rest.len() - skipped.len()];
38 if spaces.chars().any(|ch| !line_terminator(ch)) {
39 return Some("");
40 }
41 }
42 None
43}
44
45fn kebab(name: &str) -> bool {
47 name.split('-')
48 .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
49}
50
51pub fn validate_refinement_content(kind: &str, content: &Value) -> Result<bool, String> {
54 match kind {
55 "skill" => {
56 let text = content.as_str().ok_or("A skill refinement must be SKILL.md text")?;
57 if text.len() > MAX_SKILL_BYTES {
58 return Err("Skill content exceeds 64 KiB".into());
59 }
60 let (front, body) = frontmatter(text.trim_start_matches(jsrt::string::is_space), true)
61 .ok_or("Skill content needs YAML frontmatter")?;
62 if !field(front, "name").is_some_and(|name| !name.is_empty() && kebab(name)) {
63 return Err("Skill frontmatter needs a kebab-case name".into());
64 }
65 if !field(front, "description").is_some_and(|description| !description.is_empty()) {
66 return Err("Skill frontmatter needs a description".into());
67 }
68 if jsrt::string::trim(body).is_empty() {
69 return Err("Skill body is empty".into());
70 }
71 Ok(true)
72 }
73 "instruction" => {
74 let text = content
75 .as_str()
76 .filter(|text| !jsrt::string::trim(text).is_empty())
77 .ok_or("An instruction refinement must be text")?;
78 if text.len() > MAX_INSTRUCTION_BYTES {
79 return Err("Instruction exceeds 16 KiB".into());
80 }
81 Ok(true)
82 }
83 _ => Ok(true),
84 }
85}
86
87pub fn worker_validator() -> Validator {
88 Arc::new(validate_refinement_content)
89}