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    /// Routing tier assigned by the conductor (T0–T4). The matrix may bump this up.
181    #[serde(default)]
182    pub complexity_tier: Option<ComplexityTier>,
183    /// Closest tier exemplar id from the library (e.g. `T2-05`).
184    #[serde(default)]
185    pub matched_exemplar: Option<String>,
186    /// Optional phase tag for human checkpoints (`build`, `tests`, …).
187    #[serde(default)]
188    pub phase: Option<String>,
189}
190
191/// Task complexity tier for routing (`CONDUCTOR_LOOP_PLAN.md` §3.1).
192#[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    /// Parse `T0`..`T4` (case-insensitive).
214    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/// Per-node loop cap (`CONTEXT.md` §10).
227#[derive(Debug, Clone, Default, Serialize, Deserialize)]
228pub struct NodeBudget {
229    pub iterations: Option<u32>,
230}
231
232/// The kind of evaluator on a node (`CONTEXT.md` §10, §11).
233#[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/// A tool evaluator's acceptance check (`CONTEXT.md` §10).
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct Acceptance {
244    pub command: String,
245    #[serde(default)]
246    pub must_exit: i32,
247}
248
249/// A human checkpoint position (`CONTEXT.md` §10).
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "lowercase")]
252pub enum Checkpoint {
253    Before,
254    After,
255}
256
257/// A parsed failure policy (`CONTEXT.md` §10 `on_fail`).
258#[derive(Debug, Clone, PartialEq, Eq)]
259pub enum OnFail {
260    /// Re-run `node`, feeding it the critique artifact at `critique` (if given).
261    LoopBack {
262        node: String,
263        critique: Option<String>,
264    },
265    /// Re-run `node` together with this evaluator.
266    LoopWith { node: String },
267    /// Route the failure to a fixer step.
268    Fixer,
269    /// Ask the conductor to amend the DAG.
270    Replan,
271}
272
273impl Node {
274    /// Parse this node's `on_fail` string into a structured policy. Defaults to
275    /// looping back to the first dependency when the field is absent or
276    /// unparseable but a dependency exists.
277    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
292/// Parse an `on_fail` expression such as:
293/// `loop_back(n2, critique=artifacts/review.md)`, `loop_back(n2)`,
294/// `loop_with(n3)`, `fixer`, or `replan`.
295pub 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}