1use 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#[derive(Clone)]
40pub struct StateGraph<S: GraphState> {
41 nodes: IndexMap<NodeId, BoxedNode<S>>,
43
44 edges: Vec<Edge<S>>,
46
47 entry_point: Option<NodeId>,
49
50 interrupt_before: HashSet<NodeId>,
52
53 interrupt_after: HashSet<NodeId>,
55}
56
57impl<S: GraphState> StateGraph<S> {
58 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 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 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 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 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 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 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 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 pub fn interrupt_before(mut self, node: impl Into<NodeId>) -> Self {
174 self.interrupt_before.insert(node.into());
175 self
176 }
177
178 pub fn interrupt_after(mut self, node: impl Into<NodeId>) -> Self {
182 self.interrupt_after.insert(node.into());
183 self
184 }
185
186 pub fn node_names(&self) -> impl Iterator<Item = &NodeId> {
188 self.nodes.keys()
189 }
190
191 pub fn has_node(&self, name: &str) -> bool {
193 self.nodes.keys().any(|k| k.as_str() == name)
194 }
195
196 fn validate(&self) -> Result<()> {
198 if self.nodes.is_empty() {
200 return Err(RegulaError::NoEntryPoint);
201 }
202
203 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 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 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 #[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 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 fn collect_reachable_nodes(&self, reachable: &mut HashSet<NodeId>) {
252 let mut queue: Vec<NodeId> = Vec::new();
253
254 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 while let Some(node) = queue.pop() {
265 if node.is_end() || reachable.contains(&node) {
266 continue;
267 }
268 reachable.insert(node.clone());
269
270 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 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 for other_node in self.nodes.keys() {
291 queue.push(other_node.clone());
292 }
293 }
294 }
295 }
296 }
297 }
298 }
299
300 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#[derive(Clone, Debug, Default)]
335pub struct CompileConfig {
336 pub max_iterations: Option<usize>,
338
339 pub validate: bool,
341
342 pub debug: bool,
344}
345
346impl CompileConfig {
347 pub fn new() -> Self {
349 Self {
350 max_iterations: Some(100),
351 validate: true,
352 debug: false,
353 }
354 }
355
356 pub fn with_max_iterations(mut self, max: usize) -> Self {
358 self.max_iterations = Some(max);
359 self
360 }
361
362 pub fn without_validation(mut self) -> Self {
364 self.validate = false;
365 self
366 }
367
368 pub fn with_debug(mut self) -> Self {
370 self.debug = true;
371 self
372 }
373}
374
375#[derive(Clone)]
380pub struct CompiledStateGraph<S: GraphState> {
381 pub(crate) nodes: IndexMap<NodeId, BoxedNode<S>>,
383
384 pub(crate) edges: Vec<Edge<S>>,
386
387 pub(crate) entry_point: Option<NodeId>,
389
390 pub(crate) interrupt_before: HashSet<NodeId>,
392
393 pub(crate) interrupt_after: HashSet<NodeId>,
395
396 pub(crate) config: CompileConfig,
398}
399
400impl<S: GraphState> CompiledStateGraph<S> {
401 pub fn get_node(&self, name: &NodeId) -> Option<&BoxedNode<S>> {
403 self.nodes.get(name)
404 }
405
406 pub fn node_names(&self) -> impl Iterator<Item = &NodeId> {
408 self.nodes.keys()
409 }
410
411 pub fn edges_from(&self, node: &NodeId) -> Vec<&Edge<S>> {
413 self.edges.iter().filter(|e| e.from() == node).collect()
414 }
415
416 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 pub fn should_interrupt_before(&self, node: &NodeId) -> bool {
433 self.interrupt_before.contains(node)
434 }
435
436 pub fn should_interrupt_after(&self, node: &NodeId) -> bool {
438 self.interrupt_after.contains(node)
439 }
440
441 pub fn max_iterations(&self) -> Option<usize> {
443 self.config.max_iterations
444 }
445
446 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 edges.iter().any(|e| e.is_conditional()) {
459 return None;
460 }
461
462 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 pub fn to_mermaid(&self) -> String {
483 let mut lines = vec!["graph TD".to_string()];
484
485 for name in self.nodes.keys() {
487 lines.push(format!(" {}[{}]", name, name));
488 }
489
490 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 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); }
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") .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") .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}