1use std::path::{Component, Path, PathBuf};
10
11use anyhow::{Context, Result, bail};
12use serde::{Deserialize, Serialize};
13
14use crate::core::benchmark_spec::types::{is_safe_relative_file, is_safe_shell_test};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Domain {
20 Qa,
22 Code,
24}
25
26impl Domain {
27 pub fn label(self) -> &'static str {
29 match self {
30 Domain::Qa => "qa",
31 Domain::Code => "code",
32 }
33 }
34}
35
36fn is_safe_relative_workspace(value: &str) -> bool {
37 let path = Path::new(value);
38 !value.trim().is_empty()
39 && !value.as_bytes().contains(&0)
40 && !path.is_absolute()
41 && path
42 .components()
43 .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
44}
45
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
49pub struct Task {
50 pub id: String,
52 pub domain: Domain,
54 pub prompt: String,
56 pub workspace: String,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub retrieval_query: Option<String>,
62
63 #[serde(default, skip_serializing_if = "Vec::is_empty")]
66 pub answers: Vec<String>,
67
68 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub target_file: Option<String>,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub test_cmd: Option<String>,
75}
76
77impl Task {
78 pub fn query(&self) -> &str {
80 self.retrieval_query.as_deref().unwrap_or(&self.prompt)
81 }
82
83 pub fn workspace_path(&self, suite_dir: &Path) -> PathBuf {
85 let p = Path::new(&self.workspace);
86 if p.is_absolute() {
87 p.to_path_buf()
88 } else {
89 suite_dir.join(p)
90 }
91 }
92
93 pub(crate) fn resolve_workspace_path(&self, suite_dir: &Path) -> Result<PathBuf> {
95 if let Err(reason) = self.validate() {
96 bail!("invalid task {}: {reason}", self.id);
97 }
98 let root = std::fs::canonicalize(suite_dir)
99 .with_context(|| format!("canonicalizing suite directory {}", suite_dir.display()))?;
100 let workspace = std::fs::canonicalize(root.join(&self.workspace))
101 .with_context(|| format!("canonicalizing workspace {}", self.workspace))?;
102 if !workspace.starts_with(&root) {
103 bail!(
104 "task {}: workspace {} escapes suite directory",
105 self.id,
106 self.workspace
107 );
108 }
109 if !workspace.is_dir() {
110 bail!(
111 "task {}: workspace {} is not a directory",
112 self.id,
113 workspace.display()
114 );
115 }
116 Ok(workspace)
117 }
118
119 pub(crate) fn validate(&self) -> std::result::Result<(), String> {
121 if self.id.trim().is_empty() {
122 return Err("task id is empty".into());
123 }
124 if self.prompt.trim().is_empty() {
125 return Err(format!("task {}: prompt is empty", self.id));
126 }
127 if !is_safe_relative_workspace(&self.workspace) {
128 return Err(format!(
129 "task {}: workspace must be a safe relative path",
130 self.id
131 ));
132 }
133 match self.domain {
134 Domain::Qa => {
135 if self.answers.iter().all(|a| a.trim().is_empty()) {
136 return Err(format!(
137 "task {}: qa task has no non-empty answers",
138 self.id
139 ));
140 }
141 }
142 Domain::Code => self.validate_code_evaluation()?,
143 }
144 Ok(())
145 }
146
147 pub(crate) fn validate_code_evaluation(&self) -> std::result::Result<(), String> {
149 if self.domain != Domain::Code {
150 return Err(format!(
151 "task {}: code evaluator requires a code task",
152 self.id
153 ));
154 }
155 if self.target_file.as_deref().unwrap_or("").trim().is_empty() {
156 return Err(format!("task {}: code task needs target_file", self.id));
157 }
158 if !self
159 .target_file
160 .as_deref()
161 .is_some_and(is_safe_relative_file)
162 {
163 return Err(format!(
164 "task {}: target_file must be a safe relative file path",
165 self.id
166 ));
167 }
168 if self.test_cmd.as_deref().unwrap_or("").trim().is_empty() {
169 return Err(format!("task {}: code task needs test_cmd", self.id));
170 }
171 if !self.test_cmd.as_deref().is_some_and(is_safe_shell_test) {
172 return Err(format!(
173 "task {}: test_cmd must be exactly `sh <relative .sh file>`",
174 self.id
175 ));
176 }
177 Ok(())
178 }
179}
180
181#[derive(Debug, Clone)]
183pub struct EvalSuite {
184 pub dir: PathBuf,
186 pub tasks: Vec<Task>,
188}
189
190impl EvalSuite {
191 pub fn load(path: &Path) -> Result<Self> {
193 let raw = std::fs::read_to_string(path)
194 .with_context(|| format!("reading suite {}", path.display()))?;
195 let dir = path
196 .parent()
197 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
198 Self::parse(&raw, dir)
199 }
200
201 pub fn parse(raw: &str, dir: PathBuf) -> Result<Self> {
203 let mut tasks = Vec::new();
204 for (lineno, line) in raw.lines().enumerate() {
205 let trimmed = line.trim();
206 if trimmed.is_empty() || trimmed.starts_with('#') {
207 continue;
208 }
209 let task: Task = serde_json::from_str(trimmed)
210 .with_context(|| format!("parsing task on line {}", lineno + 1))?;
211 if let Err(reason) = task.validate() {
212 bail!("invalid task on line {}: {reason}", lineno + 1);
213 }
214 tasks.push(task);
215 }
216 if tasks.is_empty() {
217 bail!("suite contains no tasks");
218 }
219 let mut seen = std::collections::HashSet::new();
221 for t in &tasks {
222 if !seen.insert(t.id.as_str()) {
223 bail!("duplicate task id: {}", t.id);
224 }
225 }
226 Ok(Self { dir, tasks })
227 }
228
229 pub(crate) fn validate(&self) -> Result<()> {
231 if self.tasks.is_empty() {
232 bail!("suite contains no tasks");
233 }
234 let mut seen = std::collections::HashSet::new();
235 for task in &self.tasks {
236 if let Err(reason) = task.validate() {
237 bail!("invalid task: {reason}");
238 }
239 if !seen.insert(task.id.as_str()) {
240 bail!("duplicate task id: {}", task.id);
241 }
242 }
243 Ok(())
244 }
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 fn qa_line() -> &'static str {
252 r#"{"id":"q1","domain":"qa","prompt":"What stores does consolidation write to?","workspace":"corpus","answers":["bm25, graph, knowledge, session"]}"#
253 }
254
255 fn code_line() -> &'static str {
256 r#"{"id":"c1","domain":"code","prompt":"Implement add","workspace":"code","target_file":"solution.sh","test_cmd":"sh test.sh"}"#
257 }
258
259 #[test]
260 fn parses_qa_and_code_skipping_comments_and_blanks() {
261 let raw = format!("# header\n\n{}\n{}\n", qa_line(), code_line());
262 let suite = EvalSuite::parse(&raw, PathBuf::from("/suites")).unwrap();
263 assert_eq!(suite.tasks.len(), 2);
264 assert_eq!(suite.tasks[0].domain, Domain::Qa);
265 assert_eq!(suite.tasks[1].domain, Domain::Code);
266 assert_eq!(suite.tasks[0].query(), suite.tasks[0].prompt);
267 }
268
269 #[test]
270 fn relative_workspace_resolves_against_suite_dir() {
271 let suite = EvalSuite::parse(qa_line(), PathBuf::from("/suites")).unwrap();
272 assert_eq!(
273 suite.tasks[0].workspace_path(&suite.dir),
274 PathBuf::from("/suites/corpus")
275 );
276 }
277
278 #[test]
279 fn rejects_qa_without_answers() {
280 let bad = r#"{"id":"q","domain":"qa","prompt":"p","workspace":"w"}"#;
281 assert!(EvalSuite::parse(bad, PathBuf::from(".")).is_err());
282 }
283
284 #[test]
285 fn rejects_code_without_test_cmd() {
286 let bad = r#"{"id":"c","domain":"code","prompt":"p","workspace":"w","target_file":"f"}"#;
287 assert!(EvalSuite::parse(bad, PathBuf::from(".")).is_err());
288 }
289
290 #[test]
291 fn rejects_duplicate_ids() {
292 let raw = format!("{}\n{}", qa_line(), qa_line());
293 assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
294 }
295
296 #[test]
297 fn rejects_empty_suite() {
298 assert!(EvalSuite::parse("# only comments\n\n", PathBuf::from(".")).is_err());
299 }
300
301 #[test]
302 fn rejects_unsafe_workload_and_code_paths() {
303 for workspace in ["/tmp/outside", "../outside", "nested/../../outside"] {
304 let raw = format!(
305 r#"{{"id":"q","domain":"qa","prompt":"p","workspace":"{workspace}","answers":["a"]}}"#
306 );
307 assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
308 }
309 for target_file in [
310 "/tmp/solution.sh",
311 "../solution.sh",
312 "nested/../../solution.sh",
313 ] {
314 let raw = format!(
315 r#"{{"id":"c","domain":"code","prompt":"p","workspace":".","target_file":"{target_file}","test_cmd":"sh test.sh"}}"#
316 );
317 assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
318 }
319 for test_cmd in [
320 "sh ../test.sh",
321 "sh test.sh; touch /tmp/pwned",
322 "cat /etc/passwd",
323 ] {
324 let raw = format!(
325 r#"{{"id":"c","domain":"code","prompt":"p","workspace":".","target_file":"solution.sh","test_cmd":"{test_cmd}"}}"#
326 );
327 assert!(EvalSuite::parse(&raw, PathBuf::from(".")).is_err());
328 }
329 }
330
331 #[cfg(unix)]
332 #[test]
333 fn canonical_workspace_rejects_symlink_escape() {
334 let root = tempfile::tempdir().unwrap();
335 let suite_root = root.path().join("suite");
336 let outside = tempfile::tempdir().unwrap();
337 std::fs::create_dir_all(&suite_root).unwrap();
338 std::os::unix::fs::symlink(outside.path(), suite_root.join("link")).unwrap();
339 let raw = r#"{"id":"q","domain":"qa","prompt":"p","workspace":"link","answers":["a"]}"#;
340 let suite = EvalSuite::parse(raw, suite_root.clone()).unwrap();
341 assert!(suite.tasks[0].resolve_workspace_path(&suite.dir).is_err());
342 }
343
344 #[test]
345 fn canonical_workspace_preserves_dot_fixture() {
346 let root = tempfile::tempdir().unwrap();
347 let raw = r#"{"id":"q","domain":"qa","prompt":"p","workspace":".","answers":["a"]}"#;
348 let suite = EvalSuite::parse(raw, root.path().to_path_buf()).unwrap();
349 assert_eq!(
350 suite.tasks[0].resolve_workspace_path(&suite.dir).unwrap(),
351 std::fs::canonicalize(root.path()).unwrap()
352 );
353 }
354}