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!(
51                    "duplicate node id `{}`",
52                    n.id
53                )));
54            }
55        }
56        for n in &self.nodes {
57            for dep in &n.depends_on {
58                if dep == &n.id {
59                    return Err(crate::RinneError::Plan(format!(
60                        "node `{}` depends on itself",
61                        n.id
62                    )));
63                }
64                if self.node(dep).is_none() {
65                    return Err(crate::RinneError::Plan(format!(
66                        "node `{}` depends on unknown node `{dep}`",
67                        n.id
68                    )));
69                }
70            }
71        }
72        self.check_acyclic()?;
73        Ok(())
74    }
75
76    /// Detect a dependency cycle via DFS, returning a clear error naming a node
77    /// on the cycle. A multi-node cycle (`a → b → a`) would otherwise pass the
78    /// edge checks and then surface only as a mysterious "blocked" run.
79    fn check_acyclic(&self) -> crate::Result<()> {
80        use std::collections::HashMap;
81
82        // 0 = unvisited, 1 = on the current DFS stack, 2 = fully explored.
83        let mut state: HashMap<&str, u8> =
84            self.nodes.iter().map(|n| (n.id.as_str(), 0u8)).collect();
85
86        // Iterative DFS so a deep chain can't blow the stack.
87        for start in &self.nodes {
88            if state[start.id.as_str()] != 0 {
89                continue;
90            }
91            let mut stack: Vec<(&str, usize)> = vec![(start.id.as_str(), 0)];
92            state.insert(start.id.as_str(), 1);
93            while let Some(&mut (id, ref mut idx)) = stack.last_mut() {
94                let deps = self
95                    .node(id)
96                    .map(|n| n.depends_on.as_slice())
97                    .unwrap_or(&[]);
98                if *idx < deps.len() {
99                    let dep = deps[*idx].as_str();
100                    *idx += 1;
101                    match state.get(dep).copied().unwrap_or(2) {
102                        0 => {
103                            state.insert(dep, 1);
104                            stack.push((dep, 0));
105                        }
106                        1 => {
107                            return Err(crate::RinneError::Plan(format!(
108                                "plan has a dependency cycle involving node `{dep}`"
109                            )));
110                        }
111                        _ => {}
112                    }
113                } else {
114                    state.insert(id, 2);
115                    stack.pop();
116                }
117            }
118        }
119        Ok(())
120    }
121}
122
123/// Run-level budget (`CONTEXT.md` §10).
124#[derive(Debug, Clone, Default, Serialize, Deserialize)]
125pub struct PlanBudget {
126    pub minutes: Option<u64>,
127    pub max_total_iterations: Option<u32>,
128}
129
130/// One node in the DAG (`CONTEXT.md` §10 field reference).
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct Node {
133    pub id: String,
134    pub role: Role,
135    pub instruction: String,
136    /// Capability requirements the scheduler resolves to a worker.
137    #[serde(default)]
138    pub needs: Vec<Capability>,
139    /// Optional preferred worker, soft, overridable at dispatch
140    /// (e.g. `harness:claude-code`, `api:gpt-5.5`, `tool:npm-test`).
141    #[serde(default)]
142    pub prefer: Option<String>,
143    /// Optional model for the chosen harness (e.g. `sonnet`, `opus`,
144    /// `grok-composer-2.5-fast`). The conductor picks the cheapest model that
145    /// fits the node; resolved against config defaults at dispatch.
146    #[serde(default)]
147    pub model: Option<String>,
148    /// MCP tools this node is scoped to use, as `server.tool` ids (e.g.
149    /// `postgres.query`). The host path sends these as function definitions; the
150    /// provision path provisions exactly these into the harness
151    /// (`MCP_SKILLS.md` §7 per-node scoping). Only this node's tools, never the
152    /// global catalog.
153    #[serde(default)]
154    pub tools: Vec<String>,
155    /// Skills attached to this node, by name (e.g. `migration-safety`). The
156    /// skill's `SKILL.md` body is injected for this node only; the conductor
157    /// sees only names + descriptions until then (`MCP_SKILLS.md` §11 progressive
158    /// disclosure).
159    #[serde(default)]
160    pub skills: Vec<String>,
161    #[serde(default)]
162    pub depends_on: Vec<String>,
163    /// Named blackboard artifacts consumed, plus the special `diff`.
164    #[serde(default)]
165    pub inputs: Vec<String>,
166    /// Named blackboard artifacts produced, plus the special `diff`.
167    #[serde(default)]
168    pub outputs: Vec<String>,
169    #[serde(default)]
170    pub budget: NodeBudget,
171    /// Present on evaluator nodes (`CONTEXT.md` §10, §11). Semantics land in P5.
172    #[serde(default)]
173    pub evaluator: Option<EvaluatorKind>,
174    /// For tool evaluators: a command and required exit code.
175    #[serde(default)]
176    pub acceptance: Option<Acceptance>,
177    /// Block any diff that weakens or deletes tests.
178    #[serde(default)]
179    pub test_ratchet: bool,
180    /// Failure policy. Stored raw in P3 (e.g. "loop_back(n2, critique=...)");
181    /// parsed and acted on in P5.
182    #[serde(default)]
183    pub on_fail: Option<String>,
184    /// A human gate before or after this node.
185    #[serde(default)]
186    pub checkpoint: Option<Checkpoint>,
187    /// Routing tier assigned by the conductor (T0–T4). The matrix may bump this up.
188    #[serde(default)]
189    pub complexity_tier: Option<ComplexityTier>,
190    /// Closest tier exemplar id from the library (e.g. `T2-05`).
191    #[serde(default)]
192    pub matched_exemplar: Option<String>,
193    /// Optional phase tag for human checkpoints (`build`, `tests`, …).
194    #[serde(default)]
195    pub phase: Option<String>,
196}
197
198/// Task complexity tier for routing (`CONDUCTOR_LOOP_PLAN.md` §3.1).
199#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
200#[serde(rename_all = "UPPERCASE")]
201pub enum ComplexityTier {
202    T0,
203    T1,
204    T2,
205    T3,
206    T4,
207}
208
209impl ComplexityTier {
210    pub fn label(self) -> &'static str {
211        match self {
212            ComplexityTier::T0 => "T0",
213            ComplexityTier::T1 => "T1",
214            ComplexityTier::T2 => "T2",
215            ComplexityTier::T3 => "T3",
216            ComplexityTier::T4 => "T4",
217        }
218    }
219
220    /// Parse `T0`..`T4` (case-insensitive).
221    pub fn parse(s: &str) -> Option<Self> {
222        match s.trim().to_uppercase().as_str() {
223            "T0" => Some(ComplexityTier::T0),
224            "T1" => Some(ComplexityTier::T1),
225            "T2" => Some(ComplexityTier::T2),
226            "T3" => Some(ComplexityTier::T3),
227            "T4" => Some(ComplexityTier::T4),
228            _ => None,
229        }
230    }
231}
232
233/// Per-node loop cap (`CONTEXT.md` §10).
234#[derive(Debug, Clone, Default, Serialize, Deserialize)]
235pub struct NodeBudget {
236    pub iterations: Option<u32>,
237}
238
239/// The kind of evaluator on a node (`CONTEXT.md` §10, §11).
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(rename_all = "lowercase")]
242pub enum EvaluatorKind {
243    Ai,
244    Tool,
245    Human,
246}
247
248/// A tool evaluator's acceptance check (`CONTEXT.md` §10).
249#[derive(Debug, Clone, Serialize, Deserialize)]
250pub struct Acceptance {
251    pub command: String,
252    #[serde(default)]
253    pub must_exit: i32,
254}
255
256/// A human checkpoint position (`CONTEXT.md` §10).
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(rename_all = "lowercase")]
259pub enum Checkpoint {
260    Before,
261    After,
262}
263
264/// A parsed failure policy (`CONTEXT.md` §10 `on_fail`).
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub enum OnFail {
267    /// Re-run `node`, feeding it the critique artifact at `critique` (if given).
268    LoopBack {
269        node: String,
270        critique: Option<String>,
271    },
272    /// Re-run `node` together with this evaluator.
273    LoopWith { node: String },
274    /// Route the failure to a fixer step.
275    Fixer,
276    /// Ask the conductor to amend the DAG.
277    Replan,
278}
279
280impl Node {
281    /// Parse this node's `on_fail` string into a structured policy. Defaults to
282    /// looping back to the first dependency when the field is absent or
283    /// unparseable but a dependency exists.
284    pub fn parsed_on_fail(&self) -> Option<OnFail> {
285        match self.on_fail.as_deref() {
286            Some(raw) => parse_on_fail(raw).or_else(|| self.default_loop_back()),
287            None => self.default_loop_back(),
288        }
289    }
290
291    fn default_loop_back(&self) -> Option<OnFail> {
292        self.depends_on.first().map(|n| OnFail::LoopBack {
293            node: n.clone(),
294            critique: None,
295        })
296    }
297}
298
299/// Parse an `on_fail` expression such as:
300/// `loop_back(n2, critique=artifacts/review.md)`, `loop_back(n2)`,
301/// `loop_with(n3)`, `fixer`, or `replan`.
302pub fn parse_on_fail(raw: &str) -> Option<OnFail> {
303    let s = raw.trim();
304    match s {
305        "fixer" => return Some(OnFail::Fixer),
306        "replan" => return Some(OnFail::Replan),
307        _ => {}
308    }
309    let (head, inner) = s.split_once('(')?;
310    let inner = inner.strip_suffix(')')?;
311    let mut parts = inner.split(',').map(|p| p.trim());
312    let node = parts.next()?.to_string();
313    if node.is_empty() {
314        return None;
315    }
316    match head.trim() {
317        "loop_back" => {
318            let critique =
319                parts.find_map(|p| p.strip_prefix("critique=").map(|c| c.trim().to_string()));
320            Some(OnFail::LoopBack { node, critique })
321        }
322        "loop_with" => Some(OnFail::LoopWith { node }),
323        _ => None,
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn parses_loop_back_with_critique() {
333        assert_eq!(
334            parse_on_fail("loop_back(n2, critique=artifacts/review.md)"),
335            Some(OnFail::LoopBack {
336                node: "n2".into(),
337                critique: Some("artifacts/review.md".into())
338            })
339        );
340    }
341
342    #[test]
343    fn parses_bare_forms() {
344        assert_eq!(
345            parse_on_fail("loop_back(n2)"),
346            Some(OnFail::LoopBack {
347                node: "n2".into(),
348                critique: None
349            })
350        );
351        assert_eq!(
352            parse_on_fail("loop_with(n3)"),
353            Some(OnFail::LoopWith { node: "n3".into() })
354        );
355        assert_eq!(parse_on_fail("fixer"), Some(OnFail::Fixer));
356        assert_eq!(parse_on_fail("replan"), Some(OnFail::Replan));
357    }
358
359    #[test]
360    fn unparseable_returns_none() {
361        assert_eq!(parse_on_fail("garbage"), None);
362    }
363
364    #[test]
365    fn rejects_empty_plan() {
366        let p: Plan = serde_json::from_str(r#"{"goal":"g","nodes":[]}"#).unwrap();
367        let err = p.validate().unwrap_err().to_string();
368        assert!(err.contains("no nodes"), "got: {err}");
369    }
370
371    #[test]
372    fn detects_multi_node_cycle() {
373        let p: Plan = serde_json::from_str(
374            r#"{"goal":"g","nodes":[
375                {"id":"a","role":"generator","instruction":"x","depends_on":["b"]},
376                {"id":"b","role":"generator","instruction":"y","depends_on":["a"]}]}"#,
377        )
378        .unwrap();
379        let err = p.validate().unwrap_err().to_string();
380        assert!(err.contains("cycle"), "got: {err}");
381    }
382
383    #[test]
384    fn accepts_a_valid_dag() {
385        let p: Plan = serde_json::from_str(
386            r#"{"goal":"g","nodes":[
387                {"id":"a","role":"generator","instruction":"x"},
388                {"id":"b","role":"evaluator","instruction":"y","depends_on":["a"]}]}"#,
389        )
390        .unwrap();
391        assert!(p.validate().is_ok());
392    }
393}