Skip to main content

rinne_core/
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: unique ids, and every `depends_on` edge
40    /// points at a real node with no self-loop.
41    pub fn validate(&self) -> crate::Result<()> {
42        use std::collections::HashSet;
43        let mut seen = HashSet::new();
44        for n in &self.nodes {
45            if !seen.insert(n.id.as_str()) {
46                return Err(crate::RinneError::Plan(format!("duplicate node id `{}`", n.id)));
47            }
48        }
49        for n in &self.nodes {
50            for dep in &n.depends_on {
51                if dep == &n.id {
52                    return Err(crate::RinneError::Plan(format!(
53                        "node `{}` depends on itself",
54                        n.id
55                    )));
56                }
57                if self.node(dep).is_none() {
58                    return Err(crate::RinneError::Plan(format!(
59                        "node `{}` depends on unknown node `{dep}`",
60                        n.id
61                    )));
62                }
63            }
64        }
65        Ok(())
66    }
67}
68
69/// Run-level budget (`CONTEXT.md` §10).
70#[derive(Debug, Clone, Default, Serialize, Deserialize)]
71pub struct PlanBudget {
72    pub minutes: Option<u64>,
73    pub max_total_iterations: Option<u32>,
74}
75
76/// One node in the DAG (`CONTEXT.md` §10 field reference).
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct Node {
79    pub id: String,
80    pub role: Role,
81    pub instruction: String,
82    /// Capability requirements the scheduler resolves to a worker.
83    #[serde(default)]
84    pub needs: Vec<Capability>,
85    /// Optional preferred worker, soft, overridable at dispatch
86    /// (e.g. `harness:claude-code`, `api:gpt-5.5`, `tool:npm-test`).
87    #[serde(default)]
88    pub prefer: Option<String>,
89    /// Optional model for the chosen harness (e.g. `sonnet`, `opus`,
90    /// `grok-composer-2.5-fast`). The conductor picks the cheapest model that
91    /// fits the node; resolved against config defaults at dispatch.
92    #[serde(default)]
93    pub model: Option<String>,
94    #[serde(default)]
95    pub depends_on: Vec<String>,
96    /// Named blackboard artifacts consumed, plus the special `diff`.
97    #[serde(default)]
98    pub inputs: Vec<String>,
99    /// Named blackboard artifacts produced, plus the special `diff`.
100    #[serde(default)]
101    pub outputs: Vec<String>,
102    #[serde(default)]
103    pub budget: NodeBudget,
104    /// Present on evaluator nodes (`CONTEXT.md` §10, §11). Semantics land in P5.
105    #[serde(default)]
106    pub evaluator: Option<EvaluatorKind>,
107    /// For tool evaluators: a command and required exit code.
108    #[serde(default)]
109    pub acceptance: Option<Acceptance>,
110    /// Block any diff that weakens or deletes tests.
111    #[serde(default)]
112    pub test_ratchet: bool,
113    /// Failure policy. Stored raw in P3 (e.g. "loop_back(n2, critique=...)");
114    /// parsed and acted on in P5.
115    #[serde(default)]
116    pub on_fail: Option<String>,
117    /// A human gate before or after this node.
118    #[serde(default)]
119    pub checkpoint: Option<Checkpoint>,
120}
121
122/// Per-node loop cap (`CONTEXT.md` §10).
123#[derive(Debug, Clone, Default, Serialize, Deserialize)]
124pub struct NodeBudget {
125    pub iterations: Option<u32>,
126}
127
128/// The kind of evaluator on a node (`CONTEXT.md` §10, §11).
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "lowercase")]
131pub enum EvaluatorKind {
132    Ai,
133    Tool,
134    Human,
135}
136
137/// A tool evaluator's acceptance check (`CONTEXT.md` §10).
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct Acceptance {
140    pub command: String,
141    #[serde(default)]
142    pub must_exit: i32,
143}
144
145/// A human checkpoint position (`CONTEXT.md` §10).
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
147#[serde(rename_all = "lowercase")]
148pub enum Checkpoint {
149    Before,
150    After,
151}
152
153/// A parsed failure policy (`CONTEXT.md` §10 `on_fail`).
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub enum OnFail {
156    /// Re-run `node`, feeding it the critique artifact at `critique` (if given).
157    LoopBack {
158        node: String,
159        critique: Option<String>,
160    },
161    /// Re-run `node` together with this evaluator.
162    LoopWith { node: String },
163    /// Route the failure to a fixer step.
164    Fixer,
165    /// Ask the conductor to amend the DAG.
166    Replan,
167}
168
169impl Node {
170    /// Parse this node's `on_fail` string into a structured policy. Defaults to
171    /// looping back to the first dependency when the field is absent or
172    /// unparseable but a dependency exists.
173    pub fn parsed_on_fail(&self) -> Option<OnFail> {
174        match self.on_fail.as_deref() {
175            Some(raw) => parse_on_fail(raw).or_else(|| self.default_loop_back()),
176            None => self.default_loop_back(),
177        }
178    }
179
180    fn default_loop_back(&self) -> Option<OnFail> {
181        self.depends_on.first().map(|n| OnFail::LoopBack {
182            node: n.clone(),
183            critique: None,
184        })
185    }
186}
187
188/// Parse an `on_fail` expression such as:
189/// `loop_back(n2, critique=artifacts/review.md)`, `loop_back(n2)`,
190/// `loop_with(n3)`, `fixer`, or `replan`.
191pub fn parse_on_fail(raw: &str) -> Option<OnFail> {
192    let s = raw.trim();
193    match s {
194        "fixer" => return Some(OnFail::Fixer),
195        "replan" => return Some(OnFail::Replan),
196        _ => {}
197    }
198    let (head, inner) = s.split_once('(')?;
199    let inner = inner.strip_suffix(')')?;
200    let mut parts = inner.split(',').map(|p| p.trim());
201    let node = parts.next()?.to_string();
202    if node.is_empty() {
203        return None;
204    }
205    match head.trim() {
206        "loop_back" => {
207            let critique = parts.find_map(|p| {
208                p.strip_prefix("critique=")
209                    .map(|c| c.trim().to_string())
210            });
211            Some(OnFail::LoopBack { node, critique })
212        }
213        "loop_with" => Some(OnFail::LoopWith { node }),
214        _ => None,
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn parses_loop_back_with_critique() {
224        assert_eq!(
225            parse_on_fail("loop_back(n2, critique=artifacts/review.md)"),
226            Some(OnFail::LoopBack {
227                node: "n2".into(),
228                critique: Some("artifacts/review.md".into())
229            })
230        );
231    }
232
233    #[test]
234    fn parses_bare_forms() {
235        assert_eq!(
236            parse_on_fail("loop_back(n2)"),
237            Some(OnFail::LoopBack { node: "n2".into(), critique: None })
238        );
239        assert_eq!(parse_on_fail("loop_with(n3)"), Some(OnFail::LoopWith { node: "n3".into() }));
240        assert_eq!(parse_on_fail("fixer"), Some(OnFail::Fixer));
241        assert_eq!(parse_on_fail("replan"), Some(OnFail::Replan));
242    }
243
244    #[test]
245    fn unparseable_returns_none() {
246        assert_eq!(parse_on_fail("garbage"), None);
247    }
248}