1use std::path::PathBuf;
10
11use serde::{Deserialize, Serialize};
12
13use crate::worker::{Capability, Role};
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Plan {
18 pub goal: String,
19 #[serde(default)]
21 pub blackboard: Option<String>,
22 #[serde(default)]
24 pub mentioned: Vec<PathBuf>,
25 #[serde(default)]
26 pub budget: PlanBudget,
27 #[serde(default)]
29 pub stop_when: Option<String>,
30 pub nodes: Vec<Node>,
31}
32
33impl Plan {
34 pub fn node(&self, id: &str) -> Option<&Node> {
36 self.nodes.iter().find(|n| n.id == id)
37 }
38
39 pub fn validate(&self) -> crate::Result<()> {
43 use std::collections::HashSet;
44 if self.nodes.is_empty() {
45 return Err(crate::RinneError::Plan("plan has no nodes".into()));
46 }
47 let mut seen = HashSet::new();
48 for n in &self.nodes {
49 if !seen.insert(n.id.as_str()) {
50 return Err(crate::RinneError::Plan(format!("duplicate node id `{}`", n.id)));
51 }
52 }
53 for n in &self.nodes {
54 for dep in &n.depends_on {
55 if dep == &n.id {
56 return Err(crate::RinneError::Plan(format!(
57 "node `{}` depends on itself",
58 n.id
59 )));
60 }
61 if self.node(dep).is_none() {
62 return Err(crate::RinneError::Plan(format!(
63 "node `{}` depends on unknown node `{dep}`",
64 n.id
65 )));
66 }
67 }
68 }
69 self.check_acyclic()?;
70 Ok(())
71 }
72
73 fn check_acyclic(&self) -> crate::Result<()> {
77 use std::collections::HashMap;
78
79 let mut state: HashMap<&str, u8> = self.nodes.iter().map(|n| (n.id.as_str(), 0u8)).collect();
81
82 for start in &self.nodes {
84 if state[start.id.as_str()] != 0 {
85 continue;
86 }
87 let mut stack: Vec<(&str, usize)> = vec![(start.id.as_str(), 0)];
88 state.insert(start.id.as_str(), 1);
89 while let Some(&mut (id, ref mut idx)) = stack.last_mut() {
90 let deps = self.node(id).map(|n| n.depends_on.as_slice()).unwrap_or(&[]);
91 if *idx < deps.len() {
92 let dep = deps[*idx].as_str();
93 *idx += 1;
94 match state.get(dep).copied().unwrap_or(2) {
95 0 => {
96 state.insert(dep, 1);
97 stack.push((dep, 0));
98 }
99 1 => {
100 return Err(crate::RinneError::Plan(format!(
101 "plan has a dependency cycle involving node `{dep}`"
102 )));
103 }
104 _ => {}
105 }
106 } else {
107 state.insert(id, 2);
108 stack.pop();
109 }
110 }
111 }
112 Ok(())
113 }
114}
115
116#[derive(Debug, Clone, Default, Serialize, Deserialize)]
118pub struct PlanBudget {
119 pub minutes: Option<u64>,
120 pub max_total_iterations: Option<u32>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct Node {
126 pub id: String,
127 pub role: Role,
128 pub instruction: String,
129 #[serde(default)]
131 pub needs: Vec<Capability>,
132 #[serde(default)]
135 pub prefer: Option<String>,
136 #[serde(default)]
140 pub model: Option<String>,
141 #[serde(default)]
147 pub tools: Vec<String>,
148 #[serde(default)]
153 pub skills: Vec<String>,
154 #[serde(default)]
155 pub depends_on: Vec<String>,
156 #[serde(default)]
158 pub inputs: Vec<String>,
159 #[serde(default)]
161 pub outputs: Vec<String>,
162 #[serde(default)]
163 pub budget: NodeBudget,
164 #[serde(default)]
166 pub evaluator: Option<EvaluatorKind>,
167 #[serde(default)]
169 pub acceptance: Option<Acceptance>,
170 #[serde(default)]
172 pub test_ratchet: bool,
173 #[serde(default)]
176 pub on_fail: Option<String>,
177 #[serde(default)]
179 pub checkpoint: Option<Checkpoint>,
180 #[serde(default)]
182 pub complexity_tier: Option<ComplexityTier>,
183 #[serde(default)]
185 pub matched_exemplar: Option<String>,
186 #[serde(default)]
188 pub phase: Option<String>,
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
193#[serde(rename_all = "UPPERCASE")]
194pub enum ComplexityTier {
195 T0,
196 T1,
197 T2,
198 T3,
199 T4,
200}
201
202impl ComplexityTier {
203 pub fn label(self) -> &'static str {
204 match self {
205 ComplexityTier::T0 => "T0",
206 ComplexityTier::T1 => "T1",
207 ComplexityTier::T2 => "T2",
208 ComplexityTier::T3 => "T3",
209 ComplexityTier::T4 => "T4",
210 }
211 }
212
213 pub fn parse(s: &str) -> Option<Self> {
215 match s.trim().to_uppercase().as_str() {
216 "T0" => Some(ComplexityTier::T0),
217 "T1" => Some(ComplexityTier::T1),
218 "T2" => Some(ComplexityTier::T2),
219 "T3" => Some(ComplexityTier::T3),
220 "T4" => Some(ComplexityTier::T4),
221 _ => None,
222 }
223 }
224}
225
226#[derive(Debug, Clone, Default, Serialize, Deserialize)]
228pub struct NodeBudget {
229 pub iterations: Option<u32>,
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
234#[serde(rename_all = "lowercase")]
235pub enum EvaluatorKind {
236 Ai,
237 Tool,
238 Human,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct Acceptance {
244 pub command: String,
245 #[serde(default)]
246 pub must_exit: i32,
247}
248
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "lowercase")]
252pub enum Checkpoint {
253 Before,
254 After,
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
259pub enum OnFail {
260 LoopBack {
262 node: String,
263 critique: Option<String>,
264 },
265 LoopWith { node: String },
267 Fixer,
269 Replan,
271}
272
273impl Node {
274 pub fn parsed_on_fail(&self) -> Option<OnFail> {
278 match self.on_fail.as_deref() {
279 Some(raw) => parse_on_fail(raw).or_else(|| self.default_loop_back()),
280 None => self.default_loop_back(),
281 }
282 }
283
284 fn default_loop_back(&self) -> Option<OnFail> {
285 self.depends_on.first().map(|n| OnFail::LoopBack {
286 node: n.clone(),
287 critique: None,
288 })
289 }
290}
291
292pub fn parse_on_fail(raw: &str) -> Option<OnFail> {
296 let s = raw.trim();
297 match s {
298 "fixer" => return Some(OnFail::Fixer),
299 "replan" => return Some(OnFail::Replan),
300 _ => {}
301 }
302 let (head, inner) = s.split_once('(')?;
303 let inner = inner.strip_suffix(')')?;
304 let mut parts = inner.split(',').map(|p| p.trim());
305 let node = parts.next()?.to_string();
306 if node.is_empty() {
307 return None;
308 }
309 match head.trim() {
310 "loop_back" => {
311 let critique = parts.find_map(|p| {
312 p.strip_prefix("critique=")
313 .map(|c| c.trim().to_string())
314 });
315 Some(OnFail::LoopBack { node, critique })
316 }
317 "loop_with" => Some(OnFail::LoopWith { node }),
318 _ => None,
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 #[test]
327 fn parses_loop_back_with_critique() {
328 assert_eq!(
329 parse_on_fail("loop_back(n2, critique=artifacts/review.md)"),
330 Some(OnFail::LoopBack {
331 node: "n2".into(),
332 critique: Some("artifacts/review.md".into())
333 })
334 );
335 }
336
337 #[test]
338 fn parses_bare_forms() {
339 assert_eq!(
340 parse_on_fail("loop_back(n2)"),
341 Some(OnFail::LoopBack { node: "n2".into(), critique: None })
342 );
343 assert_eq!(parse_on_fail("loop_with(n3)"), Some(OnFail::LoopWith { node: "n3".into() }));
344 assert_eq!(parse_on_fail("fixer"), Some(OnFail::Fixer));
345 assert_eq!(parse_on_fail("replan"), Some(OnFail::Replan));
346 }
347
348 #[test]
349 fn unparseable_returns_none() {
350 assert_eq!(parse_on_fail("garbage"), None);
351 }
352
353 #[test]
354 fn rejects_empty_plan() {
355 let p: Plan = serde_json::from_str(r#"{"goal":"g","nodes":[]}"#).unwrap();
356 let err = p.validate().unwrap_err().to_string();
357 assert!(err.contains("no nodes"), "got: {err}");
358 }
359
360 #[test]
361 fn detects_multi_node_cycle() {
362 let p: Plan = serde_json::from_str(
363 r#"{"goal":"g","nodes":[
364 {"id":"a","role":"generator","instruction":"x","depends_on":["b"]},
365 {"id":"b","role":"generator","instruction":"y","depends_on":["a"]}]}"#,
366 )
367 .unwrap();
368 let err = p.validate().unwrap_err().to_string();
369 assert!(err.contains("cycle"), "got: {err}");
370 }
371
372 #[test]
373 fn accepts_a_valid_dag() {
374 let p: Plan = serde_json::from_str(
375 r#"{"goal":"g","nodes":[
376 {"id":"a","role":"generator","instruction":"x"},
377 {"id":"b","role":"evaluator","instruction":"y","depends_on":["a"]}]}"#,
378 )
379 .unwrap();
380 assert!(p.validate().is_ok());
381 }
382}