Skip to main content

rinne_types/
dag.rs

1//! The JSON DAG: the plan the loop executes (`CONTEXT.md` §10).
2//!
3//! Nodes plus dependency edges. A generator-evaluator pair is not a separate
4//! structure — it is two nodes with a loop-back policy. Phase 3 parses and
5//! executes the full shape; the evaluator/loop-back/checkpoint *semantics* land
6//! in Phase 5, but the fields are modeled here so a complete `plan.json` round
7//! trips losslessly.
8
9use std::path::PathBuf;
10
11use serde::{Deserialize, Serialize};
12
13use crate::worker::{Capability, Role};
14
15/// A complete plan (`CONTEXT.md` §10).
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct Plan {
18    pub goal: String,
19    /// Blackboard directory, conventionally `.rinne/`.
20    #[serde(default)]
21    pub blackboard: Option<String>,
22    /// Pinned context anchors resolved from `@`-mentions (`CONTEXT.md` §6).
23    #[serde(default)]
24    pub mentioned: Vec<PathBuf>,
25    #[serde(default)]
26    pub budget: PlanBudget,
27    /// Human-readable stop condition (e.g. "n4 passes and n3 passes").
28    #[serde(default)]
29    pub stop_when: Option<String>,
30    pub nodes: Vec<Node>,
31}
32
33impl Plan {
34    /// Find a node by id.
35    pub fn node(&self, id: &str) -> Option<&Node> {
36        self.nodes.iter().find(|n| n.id == id)
37    }
38
39    /// Validate structural invariants: a non-empty node set, unique ids, every
40    /// `depends_on` edge pointing at a real node, and no dependency cycles (which
41    /// would otherwise leave the scheduler unable to ever run a node).
42    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    /// Detect a dependency cycle via DFS, returning a clear error naming a node
74    /// on the cycle. A multi-node cycle (`a → b → a`) would otherwise pass the
75    /// edge checks and then surface only as a mysterious "blocked" run.
76    fn check_acyclic(&self) -> crate::Result<()> {
77        use std::collections::HashMap;
78
79        // 0 = unvisited, 1 = on the current DFS stack, 2 = fully explored.
80        let mut state: HashMap<&str, u8> = self.nodes.iter().map(|n| (n.id.as_str(), 0u8)).collect();
81
82        // Iterative DFS so a deep chain can't blow the stack.
83        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/// Run-level budget (`CONTEXT.md` §10).
117#[derive(Debug, Clone, Default, Serialize, Deserialize)]
118pub struct PlanBudget {
119    pub minutes: Option<u64>,
120    pub max_total_iterations: Option<u32>,
121}
122
123/// One node in the DAG (`CONTEXT.md` §10 field reference).
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct Node {
126    pub id: String,
127    pub role: Role,
128    pub instruction: String,
129    /// Capability requirements the scheduler resolves to a worker.
130    #[serde(default)]
131    pub needs: Vec<Capability>,
132    /// Optional preferred worker, soft, overridable at dispatch
133    /// (e.g. `harness:claude-code`, `api:gpt-5.5`, `tool:npm-test`).
134    #[serde(default)]
135    pub prefer: Option<String>,
136    /// Optional model for the chosen harness (e.g. `sonnet`, `opus`,
137    /// `grok-composer-2.5-fast`). The conductor picks the cheapest model that
138    /// fits the node; resolved against config defaults at dispatch.
139    #[serde(default)]
140    pub model: Option<String>,
141    /// MCP tools this node is scoped to use, as `server.tool` ids (e.g.
142    /// `postgres.query`). The host path sends these as function definitions; the
143    /// provision path provisions exactly these into the harness
144    /// (`MCP_SKILLS.md` §7 per-node scoping). Only this node's tools, never the
145    /// global catalog.
146    #[serde(default)]
147    pub tools: Vec<String>,
148    /// Skills attached to this node, by name (e.g. `migration-safety`). The
149    /// skill's `SKILL.md` body is injected for this node only; the conductor
150    /// sees only names + descriptions until then (`MCP_SKILLS.md` §11 progressive
151    /// disclosure).
152    #[serde(default)]
153    pub skills: Vec<String>,
154    #[serde(default)]
155    pub depends_on: Vec<String>,
156    /// Named blackboard artifacts consumed, plus the special `diff`.
157    #[serde(default)]
158    pub inputs: Vec<String>,
159    /// Named blackboard artifacts produced, plus the special `diff`.
160    #[serde(default)]
161    pub outputs: Vec<String>,
162    #[serde(default)]
163    pub budget: NodeBudget,
164    /// Present on evaluator nodes (`CONTEXT.md` §10, §11). Semantics land in P5.
165    #[serde(default)]
166    pub evaluator: Option<EvaluatorKind>,
167    /// For tool evaluators: a command and required exit code.
168    #[serde(default)]
169    pub acceptance: Option<Acceptance>,
170    /// Block any diff that weakens or deletes tests.
171    #[serde(default)]
172    pub test_ratchet: bool,
173    /// Failure policy. Stored raw in P3 (e.g. "loop_back(n2, critique=...)");
174    /// parsed and acted on in P5.
175    #[serde(default)]
176    pub on_fail: Option<String>,
177    /// A human gate before or after this node.
178    #[serde(default)]
179    pub checkpoint: Option<Checkpoint>,
180}
181
182/// Per-node loop cap (`CONTEXT.md` §10).
183#[derive(Debug, Clone, Default, Serialize, Deserialize)]
184pub struct NodeBudget {
185    pub iterations: Option<u32>,
186}
187
188/// The kind of evaluator on a node (`CONTEXT.md` §10, §11).
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(rename_all = "lowercase")]
191pub enum EvaluatorKind {
192    Ai,
193    Tool,
194    Human,
195}
196
197/// A tool evaluator's acceptance check (`CONTEXT.md` §10).
198#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct Acceptance {
200    pub command: String,
201    #[serde(default)]
202    pub must_exit: i32,
203}
204
205/// A human checkpoint position (`CONTEXT.md` §10).
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(rename_all = "lowercase")]
208pub enum Checkpoint {
209    Before,
210    After,
211}
212
213/// A parsed failure policy (`CONTEXT.md` §10 `on_fail`).
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub enum OnFail {
216    /// Re-run `node`, feeding it the critique artifact at `critique` (if given).
217    LoopBack {
218        node: String,
219        critique: Option<String>,
220    },
221    /// Re-run `node` together with this evaluator.
222    LoopWith { node: String },
223    /// Route the failure to a fixer step.
224    Fixer,
225    /// Ask the conductor to amend the DAG.
226    Replan,
227}
228
229impl Node {
230    /// Parse this node's `on_fail` string into a structured policy. Defaults to
231    /// looping back to the first dependency when the field is absent or
232    /// unparseable but a dependency exists.
233    pub fn parsed_on_fail(&self) -> Option<OnFail> {
234        match self.on_fail.as_deref() {
235            Some(raw) => parse_on_fail(raw).or_else(|| self.default_loop_back()),
236            None => self.default_loop_back(),
237        }
238    }
239
240    fn default_loop_back(&self) -> Option<OnFail> {
241        self.depends_on.first().map(|n| OnFail::LoopBack {
242            node: n.clone(),
243            critique: None,
244        })
245    }
246}
247
248/// Parse an `on_fail` expression such as:
249/// `loop_back(n2, critique=artifacts/review.md)`, `loop_back(n2)`,
250/// `loop_with(n3)`, `fixer`, or `replan`.
251pub fn parse_on_fail(raw: &str) -> Option<OnFail> {
252    let s = raw.trim();
253    match s {
254        "fixer" => return Some(OnFail::Fixer),
255        "replan" => return Some(OnFail::Replan),
256        _ => {}
257    }
258    let (head, inner) = s.split_once('(')?;
259    let inner = inner.strip_suffix(')')?;
260    let mut parts = inner.split(',').map(|p| p.trim());
261    let node = parts.next()?.to_string();
262    if node.is_empty() {
263        return None;
264    }
265    match head.trim() {
266        "loop_back" => {
267            let critique = parts.find_map(|p| {
268                p.strip_prefix("critique=")
269                    .map(|c| c.trim().to_string())
270            });
271            Some(OnFail::LoopBack { node, critique })
272        }
273        "loop_with" => Some(OnFail::LoopWith { node }),
274        _ => None,
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn parses_loop_back_with_critique() {
284        assert_eq!(
285            parse_on_fail("loop_back(n2, critique=artifacts/review.md)"),
286            Some(OnFail::LoopBack {
287                node: "n2".into(),
288                critique: Some("artifacts/review.md".into())
289            })
290        );
291    }
292
293    #[test]
294    fn parses_bare_forms() {
295        assert_eq!(
296            parse_on_fail("loop_back(n2)"),
297            Some(OnFail::LoopBack { node: "n2".into(), critique: None })
298        );
299        assert_eq!(parse_on_fail("loop_with(n3)"), Some(OnFail::LoopWith { node: "n3".into() }));
300        assert_eq!(parse_on_fail("fixer"), Some(OnFail::Fixer));
301        assert_eq!(parse_on_fail("replan"), Some(OnFail::Replan));
302    }
303
304    #[test]
305    fn unparseable_returns_none() {
306        assert_eq!(parse_on_fail("garbage"), None);
307    }
308
309    #[test]
310    fn rejects_empty_plan() {
311        let p: Plan = serde_json::from_str(r#"{"goal":"g","nodes":[]}"#).unwrap();
312        let err = p.validate().unwrap_err().to_string();
313        assert!(err.contains("no nodes"), "got: {err}");
314    }
315
316    #[test]
317    fn detects_multi_node_cycle() {
318        let p: Plan = serde_json::from_str(
319            r#"{"goal":"g","nodes":[
320                {"id":"a","role":"generator","instruction":"x","depends_on":["b"]},
321                {"id":"b","role":"generator","instruction":"y","depends_on":["a"]}]}"#,
322        )
323        .unwrap();
324        let err = p.validate().unwrap_err().to_string();
325        assert!(err.contains("cycle"), "got: {err}");
326    }
327
328    #[test]
329    fn accepts_a_valid_dag() {
330        let p: Plan = serde_json::from_str(
331            r#"{"goal":"g","nodes":[
332                {"id":"a","role":"generator","instruction":"x"},
333                {"id":"b","role":"evaluator","instruction":"y","depends_on":["a"]}]}"#,
334        )
335        .unwrap();
336        assert!(p.validate().is_ok());
337    }
338}