use crate::local::{Validator, frontmatter};
use serde_json::Value;
use std::sync::Arc;
const MAX_SKILL_BYTES: usize = 64 * 1024;
const MAX_INSTRUCTION_BYTES: usize = 16 * 1024;
fn line_terminator(ch: char) -> bool {
matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}
fn field<'a>(frontmatter: &'a str, key: &str) -> Option<&'a str> {
let prefix = format!("{key}:");
let starts = std::iter::once(0).chain(
frontmatter
.char_indices()
.filter(|(_, ch)| line_terminator(*ch))
.map(|(at, ch)| at + ch.len_utf8()),
);
for start in starts {
let Some(rest) = frontmatter[start..].strip_prefix(&prefix) else {
continue;
};
let skipped = rest.trim_start_matches(jsrt::string::is_space);
let line_end = skipped.find(line_terminator).unwrap_or(skipped.len());
if line_end > 0 {
return Some(jsrt::string::trim(&skipped[..line_end]));
}
let spaces = &rest[..rest.len() - skipped.len()];
if spaces.chars().any(|ch| !line_terminator(ch)) {
return Some("");
}
}
None
}
fn kebab(name: &str) -> bool {
name.split('-')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()))
}
pub fn validate_refinement_content(kind: &str, content: &Value) -> Result<bool, String> {
match kind {
"skill" => {
let text = content.as_str().ok_or("A skill refinement must be SKILL.md text")?;
if text.len() > MAX_SKILL_BYTES {
return Err("Skill content exceeds 64 KiB".into());
}
let (front, body) = frontmatter(text.trim_start_matches(jsrt::string::is_space), true)
.ok_or("Skill content needs YAML frontmatter")?;
if !field(front, "name").is_some_and(|name| !name.is_empty() && kebab(name)) {
return Err("Skill frontmatter needs a kebab-case name".into());
}
if !field(front, "description").is_some_and(|description| !description.is_empty()) {
return Err("Skill frontmatter needs a description".into());
}
if jsrt::string::trim(body).is_empty() {
return Err("Skill body is empty".into());
}
Ok(true)
}
"instruction" => {
let text = content
.as_str()
.filter(|text| !jsrt::string::trim(text).is_empty())
.ok_or("An instruction refinement must be text")?;
if text.len() > MAX_INSTRUCTION_BYTES {
return Err("Instruction exceeds 16 KiB".into());
}
Ok(true)
}
_ => Ok(true),
}
}
pub fn worker_validator() -> Validator {
Arc::new(validate_refinement_content)
}