Skip to main content

regula_core/
graph.rs

1//! StateGraph builder and compilation.
2//!
3//! The `StateGraph` struct provides a fluent builder API for constructing
4//! graphs. Once built, `compile()` validates the graph and produces a
5//! `CompiledStateGraph` ready for execution.
6
7use crate::constants::{end, start, NodeId};
8use crate::edge::{Edge, EdgeRouter};
9use crate::error::{RegulaError, Result};
10use crate::node::{BoxedNode, Node};
11use crate::state::GraphState;
12use indexmap::IndexMap;
13use std::collections::{HashMap, HashSet};
14use std::sync::Arc;
15
16/// Builder for state graphs.
17///
18/// Use the fluent API to add nodes, edges, and compile the graph.
19///
20/// # Examples
21///
22/// ```ignore
23/// use regula_core::{StateGraph, start, end, node_fn, router_fn, RouteOutput};
24///
25/// let graph = StateGraph::<MyState>::new()
26///     .add_node("agent", agent_node)
27///     .add_node("tools", tools_node)
28///     .add_edge(start(), "agent")
29///     .add_conditional_edges("agent", router_fn(|state| {
30///         if state.done {
31///             RouteOutput::end()
32///         } else {
33///             RouteOutput::one("tools")
34///         }
35///     }))
36///     .add_edge("tools", "agent")
37///     .compile(Default::default())?;
38/// ```
39#[derive(Clone)]
40pub struct StateGraph<S: GraphState> {
41    /// Nodes in the graph, keyed by name.
42    nodes: IndexMap<NodeId, BoxedNode<S>>,
43
44    /// Edges in the graph.
45    edges: Vec<Edge<S>>,
46
47    /// Entry point node (if set explicitly).
48    entry_point: Option<NodeId>,
49
50    /// Nodes to interrupt before execution.
51    interrupt_before: HashSet<NodeId>,
52
53    /// Nodes to interrupt after execution.
54    interrupt_after: HashSet<NodeId>,
55}
56
57impl<S: GraphState> StateGraph<S> {
58    /// Create a new empty state graph.
59    pub fn new() -> Self {
60        Self {
61            nodes: IndexMap::new(),
62            edges: Vec::new(),
63            entry_point: None,
64            interrupt_before: HashSet::new(),
65            interrupt_after: HashSet::new(),
66        }
67    }
68
69    /// Add a node to the graph.
70    ///
71    /// # Arguments
72    ///
73    /// - `name`: The unique name for this node.
74    /// - `node`: The node implementation.
75    ///
76    /// # Returns
77    ///
78    /// The builder for chaining.
79    ///
80    /// # Panics
81    ///
82    /// Panics if a node with this name already exists. Use `try_add_node`
83    /// for fallible insertion.
84    pub fn add_node<N: Node<S> + 'static>(mut self, name: impl Into<NodeId>, node: N) -> Self {
85        let name = name.into();
86        if self.nodes.contains_key(&name) {
87            panic!("Node '{}' already exists in graph", name);
88        }
89        self.nodes.insert(name, Arc::new(node));
90        self
91    }
92
93    /// Try to add a node to the graph.
94    ///
95    /// Returns an error if a node with this name already exists.
96    pub fn try_add_node<N: Node<S> + 'static>(
97        mut self,
98        name: impl Into<NodeId>,
99        node: N,
100    ) -> Result<Self> {
101        let name = name.into();
102        if self.nodes.contains_key(&name) {
103            return Err(RegulaError::DuplicateNode(name.to_string()));
104        }
105        self.nodes.insert(name, Arc::new(node));
106        Ok(self)
107    }
108
109    /// Add a normal (fixed) edge between two nodes.
110    ///
111    /// # Arguments
112    ///
113    /// - `from`: The source node (or `start()` for entry point).
114    /// - `to`: The target node (or `end()` for termination).
115    pub fn add_edge(mut self, from: impl Into<NodeId>, to: impl Into<NodeId>) -> Self {
116        self.edges.push(Edge::normal(from, to));
117        self
118    }
119
120    /// Add conditional edges with a router function.
121    ///
122    /// The router determines the next node(s) based on the current state.
123    ///
124    /// # Arguments
125    ///
126    /// - `from`: The source node.
127    /// - `router`: The routing logic.
128    pub fn add_conditional_edges<R: EdgeRouter<S> + 'static>(
129        mut self,
130        from: impl Into<NodeId>,
131        router: R,
132    ) -> Self {
133        self.edges.push(Edge::conditional(from, router));
134        self
135    }
136
137    /// Add conditional edges with a path map.
138    ///
139    /// The path map translates router string outputs to node IDs.
140    pub fn add_conditional_edges_with_map<R: EdgeRouter<S> + 'static>(
141        mut self,
142        from: impl Into<NodeId>,
143        router: R,
144        path_map: HashMap<String, NodeId>,
145    ) -> Self {
146        self.edges
147            .push(Edge::conditional_with_map(from, router, path_map));
148        self
149    }
150
151    /// Set the entry point explicitly.
152    ///
153    /// This is equivalent to `add_edge(start(), node)`.
154    pub fn set_entry_point(mut self, node: impl Into<NodeId>) -> Self {
155        let node_id = node.into();
156        self.entry_point = Some(node_id.clone());
157        self.edges.push(Edge::normal(start(), node_id));
158        self
159    }
160
161    /// Set a finish point explicitly.
162    ///
163    /// This is equivalent to `add_edge(node, end())`.
164    pub fn set_finish_point(mut self, node: impl Into<NodeId>) -> Self {
165        self.edges.push(Edge::normal(node, end()));
166        self
167    }
168
169    /// Add a node to interrupt before execution.
170    ///
171    /// When the graph reaches this node, it will pause before executing
172    /// and return to the caller.
173    pub fn interrupt_before(mut self, node: impl Into<NodeId>) -> Self {
174        self.interrupt_before.insert(node.into());
175        self
176    }
177
178    /// Add a node to interrupt after execution.
179    ///
180    /// When this node completes, the graph will pause and return to the caller.
181    pub fn interrupt_after(mut self, node: impl Into<NodeId>) -> Self {
182        self.interrupt_after.insert(node.into());
183        self
184    }
185
186    /// Get the list of node names.
187    pub fn node_names(&self) -> impl Iterator<Item = &NodeId> {
188        self.nodes.keys()
189    }
190
191    /// Check if a node exists.
192    pub fn has_node(&self, name: &str) -> bool {
193        self.nodes.keys().any(|k| k.as_str() == name)
194    }
195
196    /// Validate the graph structure.
197    fn validate(&self) -> Result<()> {
198        // Check for at least one node
199        if self.nodes.is_empty() {
200            return Err(RegulaError::NoEntryPoint);
201        }
202
203        // Check for entry point
204        let has_entry = self.edges.iter().any(|e| e.from().is_start());
205        if !has_entry && self.entry_point.is_none() {
206            return Err(RegulaError::NoEntryPoint);
207        }
208
209        // Check all edge sources and targets exist
210        for edge in &self.edges {
211            let from = edge.from();
212            if !from.is_start() && !self.nodes.contains_key(from) {
213                return Err(RegulaError::InvalidEdgeSource(from.to_string()));
214            }
215
216            if let Edge::Normal { to, .. } = edge {
217                if !to.is_end() && !self.nodes.contains_key(to) {
218                    return Err(RegulaError::InvalidEdgeTarget(to.to_string()));
219                }
220            }
221        }
222
223        // Check all non-sentinel nodes have at least one outgoing edge
224        for node_id in self.nodes.keys() {
225            let has_outgoing = self.edges.iter().any(|e| e.from() == node_id);
226            if !has_outgoing {
227                // Node has no outgoing edges - this could be valid if it uses Command
228                // to specify routing, so we just warn in debug mode
229                #[cfg(debug_assertions)]
230                tracing::debug!(
231                    "Node '{}' has no outgoing edges - ensure it returns a Command with goto",
232                    node_id
233                );
234            }
235        }
236
237        // Check for unreachable nodes
238        let mut reachable = HashSet::new();
239        self.collect_reachable_nodes(&mut reachable);
240
241        for node_id in self.nodes.keys() {
242            if !reachable.contains(node_id) {
243                return Err(RegulaError::UnreachableNode(node_id.to_string()));
244            }
245        }
246
247        Ok(())
248    }
249
250    /// Collect all nodes reachable from START.
251    fn collect_reachable_nodes(&self, reachable: &mut HashSet<NodeId>) {
252        let mut queue: Vec<NodeId> = Vec::new();
253
254        // Start from entry points
255        for edge in &self.edges {
256            if edge.from().is_start() {
257                if let Edge::Normal { to, .. } = edge {
258                    queue.push(to.clone());
259                }
260            }
261        }
262
263        // BFS to find all reachable nodes
264        while let Some(node) = queue.pop() {
265            if node.is_end() || reachable.contains(&node) {
266                continue;
267            }
268            reachable.insert(node.clone());
269
270            // Find outgoing edges
271            for edge in &self.edges {
272                if edge.from() == &node {
273                    match edge {
274                        Edge::Normal { to, .. } => {
275                            if !to.is_end() {
276                                queue.push(to.clone());
277                            }
278                        }
279                        Edge::Conditional { path_map, .. } => {
280                            // For conditional edges, include all possible targets from path_map
281                            if let Some(map) = path_map {
282                                for target in map.values() {
283                                    if !target.is_end() {
284                                        queue.push(target.clone());
285                                    }
286                                }
287                            }
288                            // Note: We can't statically determine all router outputs,
289                            // so we assume all nodes might be reachable through conditional edges
290                            for other_node in self.nodes.keys() {
291                                queue.push(other_node.clone());
292                            }
293                        }
294                    }
295                }
296            }
297        }
298    }
299
300    /// Compile the graph into an executable form.
301    ///
302    /// This validates the graph structure and produces a `CompiledStateGraph`
303    /// ready for execution.
304    pub fn compile(self, config: CompileConfig) -> Result<CompiledStateGraph<S>> {
305        self.validate()?;
306        Ok(CompiledStateGraph {
307            nodes: self.nodes,
308            edges: self.edges,
309            entry_point: self.entry_point,
310            interrupt_before: self.interrupt_before,
311            interrupt_after: self.interrupt_after,
312            config,
313        })
314    }
315}
316
317impl<S: GraphState> Default for StateGraph<S> {
318    fn default() -> Self {
319        Self::new()
320    }
321}
322
323impl<S: GraphState> std::fmt::Debug for StateGraph<S> {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        f.debug_struct("StateGraph")
326            .field("nodes", &self.nodes.keys().collect::<Vec<_>>())
327            .field("edges", &self.edges)
328            .field("entry_point", &self.entry_point)
329            .finish()
330    }
331}
332
333/// Configuration for graph compilation.
334#[derive(Clone, Debug, Default)]
335pub struct CompileConfig {
336    /// Maximum iterations before timeout.
337    pub max_iterations: Option<usize>,
338
339    /// Whether to validate the graph structure.
340    pub validate: bool,
341
342    /// Enable debug mode with extra tracing.
343    pub debug: bool,
344}
345
346impl CompileConfig {
347    /// Create a new compile configuration with defaults.
348    pub fn new() -> Self {
349        Self {
350            max_iterations: Some(100),
351            validate: true,
352            debug: false,
353        }
354    }
355
356    /// Set maximum iterations.
357    pub fn with_max_iterations(mut self, max: usize) -> Self {
358        self.max_iterations = Some(max);
359        self
360    }
361
362    /// Disable validation.
363    pub fn without_validation(mut self) -> Self {
364        self.validate = false;
365        self
366    }
367
368    /// Enable debug mode.
369    pub fn with_debug(mut self) -> Self {
370        self.debug = true;
371        self
372    }
373}
374
375/// A compiled state graph ready for execution.
376///
377/// This is the output of `StateGraph::compile()`. Use the runtime crate
378/// to execute this graph.
379#[derive(Clone)]
380pub struct CompiledStateGraph<S: GraphState> {
381    /// Nodes in the graph.
382    pub(crate) nodes: IndexMap<NodeId, BoxedNode<S>>,
383
384    /// Edges in the graph.
385    pub(crate) edges: Vec<Edge<S>>,
386
387    /// Entry point node.
388    pub(crate) entry_point: Option<NodeId>,
389
390    /// Nodes to interrupt before.
391    pub(crate) interrupt_before: HashSet<NodeId>,
392
393    /// Nodes to interrupt after.
394    pub(crate) interrupt_after: HashSet<NodeId>,
395
396    /// Compilation configuration.
397    pub(crate) config: CompileConfig,
398}
399
400impl<S: GraphState> CompiledStateGraph<S> {
401    /// Get a node by name.
402    pub fn get_node(&self, name: &NodeId) -> Option<&BoxedNode<S>> {
403        self.nodes.get(name)
404    }
405
406    /// Get all node names.
407    pub fn node_names(&self) -> impl Iterator<Item = &NodeId> {
408        self.nodes.keys()
409    }
410
411    /// Get the edges for a node.
412    pub fn edges_from(&self, node: &NodeId) -> Vec<&Edge<S>> {
413        self.edges.iter().filter(|e| e.from() == node).collect()
414    }
415
416    /// Get the entry points (nodes with edges from START).
417    pub fn entry_points(&self) -> Vec<NodeId> {
418        self.edges
419            .iter()
420            .filter_map(|e| {
421                if e.from().is_start() {
422                    if let Edge::Normal { to, .. } = e {
423                        return Some(to.clone());
424                    }
425                }
426                None
427            })
428            .collect()
429    }
430
431    /// Check if a node should interrupt before execution.
432    pub fn should_interrupt_before(&self, node: &NodeId) -> bool {
433        self.interrupt_before.contains(node)
434    }
435
436    /// Check if a node should interrupt after execution.
437    pub fn should_interrupt_after(&self, node: &NodeId) -> bool {
438        self.interrupt_after.contains(node)
439    }
440
441    /// Get the maximum iterations setting.
442    pub fn max_iterations(&self) -> Option<usize> {
443        self.config.max_iterations
444    }
445
446    /// Find the next nodes to execute after a given node completes.
447    ///
448    /// For normal edges, returns the fixed target.
449    /// For conditional edges, returns None (router must be invoked at runtime).
450    pub fn next_nodes(&self, from: &NodeId) -> Option<Vec<NodeId>> {
451        let edges: Vec<_> = self.edges_from(from);
452        
453        if edges.is_empty() {
454            return None;
455        }
456
457        // If there's a conditional edge, we can't determine next statically
458        if edges.iter().any(|e| e.is_conditional()) {
459            return None;
460        }
461
462        // Collect all normal edge targets
463        let targets: Vec<NodeId> = edges
464            .iter()
465            .filter_map(|e| {
466                if let Edge::Normal { to, .. } = e {
467                    Some(to.clone())
468                } else {
469                    None
470                }
471            })
472            .collect();
473
474        if targets.is_empty() {
475            None
476        } else {
477            Some(targets)
478        }
479    }
480
481    /// Generate a Mermaid diagram of the graph.
482    pub fn to_mermaid(&self) -> String {
483        let mut lines = vec!["graph TD".to_string()];
484
485        // Add nodes
486        for name in self.nodes.keys() {
487            lines.push(format!("    {}[{}]", name, name));
488        }
489
490        // Add edges
491        for edge in &self.edges {
492            match edge {
493                Edge::Normal { from, to } => {
494                    let from_str = if from.is_start() {
495                        "START"
496                    } else {
497                        from.as_str()
498                    };
499                    let to_str = if to.is_end() { "END" } else { to.as_str() };
500                    lines.push(format!("    {} --> {}", from_str, to_str));
501                }
502                Edge::Conditional { from, .. } => {
503                    lines.push(format!("    {} -.-> |?| ...", from));
504                }
505            }
506        }
507
508        // Add special nodes
509        lines.push("    START((START))".to_string());
510        lines.push("    END((END))".to_string());
511
512        lines.join("\n")
513    }
514}
515
516impl<S: GraphState> std::fmt::Debug for CompiledStateGraph<S> {
517    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518        f.debug_struct("CompiledStateGraph")
519            .field("nodes", &self.nodes.keys().collect::<Vec<_>>())
520            .field("edges", &self.edges.len())
521            .field("entry_point", &self.entry_point)
522            .finish()
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use crate::channel::ChannelSpec;
530    use crate::edge::router_fn;
531    use crate::node::{node_fn, NodeOutput};
532    use crate::RunnableConfig;
533
534    #[derive(Clone, serde::Serialize, serde::Deserialize)]
535    struct TestState {
536        counter: i32,
537        done: bool,
538    }
539
540    impl GraphState for TestState {
541        fn channels() -> HashMap<String, ChannelSpec> {
542            let mut channels = HashMap::new();
543            channels.insert("counter".to_string(), ChannelSpec::LastValue);
544            channels.insert("done".to_string(), ChannelSpec::LastValue);
545            channels
546        }
547    }
548
549    #[test]
550    fn test_state_graph_new() {
551        let graph = StateGraph::<TestState>::new();
552        assert_eq!(graph.nodes.len(), 0);
553        assert_eq!(graph.edges.len(), 0);
554    }
555
556    #[test]
557    fn test_state_graph_add_node() {
558        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
559            Ok(NodeOutput::none())
560        });
561
562        let graph = StateGraph::<TestState>::new().add_node("agent", node);
563        assert!(graph.has_node("agent"));
564    }
565
566    #[test]
567    #[should_panic(expected = "already exists")]
568    fn test_state_graph_duplicate_node() {
569        let node1 = node_fn(|_: &TestState, _: &RunnableConfig| async {
570            Ok(NodeOutput::none())
571        });
572        let node2 = node_fn(|_: &TestState, _: &RunnableConfig| async {
573            Ok(NodeOutput::none())
574        });
575
576        let _ = StateGraph::<TestState>::new()
577            .add_node("agent", node1)
578            .add_node("agent", node2); // Should panic
579    }
580
581    #[test]
582    fn test_state_graph_try_add_node_duplicate() {
583        let node1 = node_fn(|_: &TestState, _: &RunnableConfig| async {
584            Ok(NodeOutput::none())
585        });
586        let node2 = node_fn(|_: &TestState, _: &RunnableConfig| async {
587            Ok(NodeOutput::none())
588        });
589
590        let result = StateGraph::<TestState>::new()
591            .add_node("agent", node1)
592            .try_add_node("agent", node2);
593
594        assert!(result.is_err());
595    }
596
597    #[test]
598    fn test_state_graph_add_edges() {
599        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
600            Ok(NodeOutput::none())
601        });
602
603        let graph = StateGraph::<TestState>::new()
604            .add_node("agent", node)
605            .add_edge(start(), "agent")
606            .add_edge("agent", end());
607
608        assert_eq!(graph.edges.len(), 2);
609    }
610
611    #[test]
612    fn test_state_graph_conditional_edges() {
613        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
614            Ok(NodeOutput::none())
615        });
616
617        let router = router_fn(|state: &TestState| {
618            if state.done {
619                RouteOutput::end()
620            } else {
621                RouteOutput::one("agent")
622            }
623        });
624
625        let graph = StateGraph::<TestState>::new()
626            .add_node("agent", node)
627            .add_edge(start(), "agent")
628            .add_conditional_edges("agent", router);
629
630        assert_eq!(graph.edges.len(), 2);
631    }
632
633    #[test]
634    fn test_state_graph_compile_success() {
635        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
636            Ok(NodeOutput::none())
637        });
638
639        let result = StateGraph::<TestState>::new()
640            .add_node("agent", node)
641            .add_edge(start(), "agent")
642            .add_edge("agent", end())
643            .compile(Default::default());
644
645        assert!(result.is_ok());
646    }
647
648    #[test]
649    fn test_state_graph_compile_no_entry() {
650        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
651            Ok(NodeOutput::none())
652        });
653
654        let result = StateGraph::<TestState>::new()
655            .add_node("agent", node)
656            .add_edge("agent", end())
657            .compile(Default::default());
658
659        assert!(result.is_err());
660    }
661
662    #[test]
663    fn test_state_graph_compile_invalid_edge_source() {
664        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
665            Ok(NodeOutput::none())
666        });
667
668        let result = StateGraph::<TestState>::new()
669            .add_node("agent", node)
670            .add_edge(start(), "agent")
671            .add_edge("nonexistent", "agent") // Invalid source
672            .compile(Default::default());
673
674        assert!(result.is_err());
675    }
676
677    #[test]
678    fn test_state_graph_compile_invalid_edge_target() {
679        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
680            Ok(NodeOutput::none())
681        });
682
683        let result = StateGraph::<TestState>::new()
684            .add_node("agent", node)
685            .add_edge(start(), "agent")
686            .add_edge("agent", "nonexistent") // Invalid target
687            .compile(Default::default());
688
689        assert!(result.is_err());
690    }
691
692    #[test]
693    fn test_compiled_graph_entry_points() {
694        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
695            Ok(NodeOutput::none())
696        });
697
698        let graph = StateGraph::<TestState>::new()
699            .add_node("agent", node)
700            .add_edge(start(), "agent")
701            .add_edge("agent", end())
702            .compile(Default::default())
703            .unwrap();
704
705        let entry_points = graph.entry_points();
706        assert_eq!(entry_points.len(), 1);
707        assert_eq!(entry_points[0], "agent");
708    }
709
710    #[test]
711    fn test_compiled_graph_to_mermaid() {
712        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
713            Ok(NodeOutput::none())
714        });
715
716        let graph = StateGraph::<TestState>::new()
717            .add_node("agent", node)
718            .add_edge(start(), "agent")
719            .add_edge("agent", end())
720            .compile(Default::default())
721            .unwrap();
722
723        let mermaid = graph.to_mermaid();
724        assert!(mermaid.contains("graph TD"));
725        assert!(mermaid.contains("START"));
726        assert!(mermaid.contains("END"));
727        assert!(mermaid.contains("agent"));
728    }
729
730    #[test]
731    fn test_set_entry_point() {
732        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
733            Ok(NodeOutput::none())
734        });
735
736        let graph = StateGraph::<TestState>::new()
737            .add_node("agent", node)
738            .set_entry_point("agent")
739            .add_edge("agent", end())
740            .compile(Default::default())
741            .unwrap();
742
743        assert_eq!(graph.entry_points(), vec![NodeId::from("agent")]);
744    }
745
746    #[test]
747    fn test_interrupt_points() {
748        let node = node_fn(|_: &TestState, _: &RunnableConfig| async {
749            Ok(NodeOutput::none())
750        });
751
752        let graph = StateGraph::<TestState>::new()
753            .add_node("agent", node)
754            .add_edge(start(), "agent")
755            .add_edge("agent", end())
756            .interrupt_before("agent")
757            .interrupt_after("agent")
758            .compile(Default::default())
759            .unwrap();
760
761        assert!(graph.should_interrupt_before(&NodeId::from("agent")));
762        assert!(graph.should_interrupt_after(&NodeId::from("agent")));
763    }
764}