1use std::collections::{HashMap, HashSet};
28use std::fmt;
29use std::future::Future;
30use std::pin::Pin;
31use std::sync::Arc;
32
33use serde::{Deserialize, Serialize};
34use serde_json::Value;
35
36use crate::error::{Result, RustyError};
37use crate::node::Node;
38use crate::state::State;
39
40pub const END: &str = "__end__";
46
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Route {
51 Node(String),
53 Send(Vec<Send>),
58 End,
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub struct Send {
71 pub node: String,
73 pub state: Value,
76}
77
78impl Send {
79 pub fn new(node: impl Into<String>, state: Value) -> Self {
81 Self {
82 node: node.into(),
83 state,
84 }
85 }
86}
87
88pub type ConditionalRouter = Arc<
96 dyn Fn(State) -> Pin<Box<dyn Future<Output = Result<Route>> + std::marker::Send>>
97 + std::marker::Send
98 + Sync,
99>;
100
101#[derive(Clone)]
103pub enum Edge {
104 Direct { from: String, to: String },
108 Conditional {
111 from: String,
112 router: ConditionalRouter,
113 },
114}
115
116impl Edge {
117 pub fn from(&self) -> &str {
119 match self {
120 Edge::Direct { from, .. } | Edge::Conditional { from, .. } => from,
121 }
122 }
123}
124
125impl fmt::Debug for Edge {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 match self {
128 Edge::Direct { from, to } => write!(f, "Edge::Direct({from} -> {to})"),
129 Edge::Conditional { from, .. } => write!(f, "Edge::Conditional({from} -> ?)"),
130 }
131 }
132}
133
134struct GraphInner {
136 nodes: HashMap<String, Arc<dyn Node>>,
137 edges: Vec<Edge>,
138 entry_point: String,
139}
140
141pub struct Graph {
146 inner: Arc<GraphInner>,
147}
148
149impl Clone for Graph {
150 fn clone(&self) -> Self {
151 Self {
152 inner: Arc::clone(&self.inner),
153 }
154 }
155}
156
157impl fmt::Debug for Graph {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.debug_struct("Graph")
160 .field("nodes", &self.inner.nodes.keys().collect::<Vec<_>>())
161 .field("edges", &self.inner.edges)
162 .field("entry_point", &self.inner.entry_point)
163 .finish()
164 }
165}
166
167impl Graph {
168 pub fn entry_point(&self) -> &str {
170 &self.inner.entry_point
171 }
172
173 pub fn node(&self, name: &str) -> Option<Arc<dyn Node>> {
175 self.inner.nodes.get(name).cloned()
176 }
177
178 pub fn has_node(&self, name: &str) -> bool {
180 self.inner.nodes.contains_key(name)
181 }
182
183 pub fn node_names(&self) -> impl Iterator<Item = &str> {
185 self.inner.nodes.keys().map(String::as_str)
186 }
187
188 pub fn outgoing_edges(&self, from: &str) -> Vec<&Edge> {
190 self.inner
191 .edges
192 .iter()
193 .filter(|e| e.from() == from)
194 .collect()
195 }
196
197 pub fn edges(&self) -> &[Edge] {
199 &self.inner.edges
200 }
201
202 pub fn node_count(&self) -> usize {
204 self.inner.nodes.len()
205 }
206
207 pub fn topology_hash(&self) -> String {
218 let mut lines: Vec<String> =
219 Vec::with_capacity(self.inner.nodes.len() + self.inner.edges.len());
220 lines.extend(self.inner.nodes.keys().map(|name| format!("node:{name}")));
221 lines.extend(self.inner.edges.iter().map(|edge| match edge {
222 Edge::Direct { from, to } => format!("edge:{from}>{to}"),
223 Edge::Conditional { from, .. } => format!("edge:{from}>?"),
224 }));
225 lines.push(format!("entry:{}", self.inner.entry_point));
226 lines.sort_unstable();
227 crate::record::sha256_hex(lines.join("\n").as_bytes())
228 }
229}
230
231#[derive(Default)]
234pub struct GraphBuilder {
235 nodes: HashMap<String, Arc<dyn Node>>,
236 edges: Vec<Edge>,
237 entry_point: Option<String>,
238}
239
240impl GraphBuilder {
241 pub fn new() -> Self {
243 Self::default()
244 }
245
246 pub fn add_node<N>(&mut self, name: impl Into<String>, node: N) -> &mut Self
252 where
253 N: Node + 'static,
254 {
255 self.nodes.insert(name.into(), Arc::new(node));
256 self
257 }
258
259 pub fn add_edge(&mut self, from: impl Into<String>, to: impl Into<String>) -> &mut Self {
269 self.edges.push(Edge::Direct {
270 from: from.into(),
271 to: to.into(),
272 });
273 self
274 }
275
276 pub fn add_conditional_edges<F, Fut>(&mut self, from: impl Into<String>, router: F) -> &mut Self
293 where
294 F: Fn(State) -> Fut + std::marker::Send + Sync + 'static,
295 Fut: Future<Output = Result<Route>> + std::marker::Send + 'static,
296 {
297 let router: ConditionalRouter = Arc::new(move |state| Box::pin(router(state)));
298 self.edges.push(Edge::Conditional {
299 from: from.into(),
300 router,
301 });
302 self
303 }
304
305 pub fn set_entry_point(&mut self, name: impl Into<String>) -> &mut Self {
307 self.entry_point = Some(name.into());
308 self
309 }
310
311 pub fn compile(self) -> Result<Graph> {
330 if self.nodes.is_empty() {
331 return Err(RustyError::Graph(
332 "cannot compile an empty graph: register at least one node".into(),
333 ));
334 }
335
336 for name in self.nodes.keys() {
337 if name == END || name.starts_with("__") {
338 return Err(RustyError::Graph(format!(
339 "node name `{name}` is reserved (`{END}` and `__`-prefixed names \
340 form the engine's sentinel namespace)"
341 )));
342 }
343 }
344
345 let entry_point = self.entry_point.ok_or_else(|| {
346 RustyError::Graph("no entry point set: call set_entry_point()".into())
347 })?;
348 if !self.nodes.contains_key(&entry_point) {
349 return Err(RustyError::Graph(format!(
350 "entry point `{entry_point}` does not reference a known node"
351 )));
352 }
353
354 let mut direct_edges: HashSet<(&str, &str)> = HashSet::new();
355 let mut direct_sources: HashSet<&str> = HashSet::new();
356 let mut conditional_sources: HashSet<&str> = HashSet::new();
357
358 for edge in &self.edges {
359 let from = edge.from();
360 if !self.nodes.contains_key(from) {
361 return Err(RustyError::Graph(format!(
362 "edge source `{from}` does not reference a known node"
363 )));
364 }
365 match edge {
366 Edge::Direct { to, .. } => {
367 if !self.nodes.contains_key(to) {
368 return Err(RustyError::Graph(format!(
369 "edge target `{to}` (from `{from}`) does not reference a known node"
370 )));
371 }
372 if !direct_edges.insert((from, to.as_str())) {
373 return Err(RustyError::Graph(format!(
374 "duplicate edge `{from} -> {to}`: the target would be \
375 activated twice in one super-step"
376 )));
377 }
378 direct_sources.insert(from);
379 }
380 Edge::Conditional { .. } => {
381 if !conditional_sources.insert(from) {
382 return Err(RustyError::Graph(format!(
383 "node `{from}` has multiple conditional edges; only one \
384 router per source node is allowed"
385 )));
386 }
387 }
388 }
389 }
390
391 if let Some(from) = direct_sources.intersection(&conditional_sources).next() {
392 return Err(RustyError::Graph(format!(
393 "node `{from}` has both static and conditional edges; routing would \
394 be ambiguous — use one kind per source node"
395 )));
396 }
397
398 Ok(Graph {
399 inner: Arc::new(GraphInner {
400 nodes: self.nodes,
401 edges: self.edges,
402 entry_point,
403 }),
404 })
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::node::NodeOutput;
412 use serde_json::json;
413
414 async fn ok_node(_ctx: crate::node::NodeContext) -> Result<NodeOutput> {
415 Ok(NodeOutput::empty())
416 }
417
418 #[test]
419 fn compile_rejects_empty_graph() {
420 let err = GraphBuilder::new().compile().unwrap_err();
421 assert!(matches!(err, RustyError::Graph(_)));
422 }
423
424 #[test]
425 fn compile_rejects_missing_entry_point() {
426 let mut b = GraphBuilder::new();
427 b.add_node("a", ok_node);
428 let err = b.compile().unwrap_err();
429 assert!(matches!(err, RustyError::Graph(_)));
430 }
431
432 #[test]
433 fn compile_rejects_unknown_entry_point() {
434 let mut b = GraphBuilder::new();
435 b.add_node("a", ok_node);
436 b.set_entry_point("nope");
437 assert!(b.compile().is_err());
438 }
439
440 #[test]
441 fn compile_rejects_dangling_edges() {
442 let mut b = GraphBuilder::new();
443 b.add_node("a", ok_node);
444 b.set_entry_point("a");
445 b.add_edge("a", "ghost");
446 assert!(b.compile().is_err());
447
448 let mut b = GraphBuilder::new();
449 b.add_node("a", ok_node);
450 b.set_entry_point("a");
451 b.add_conditional_edges("ghost", |_s| async { Ok(Route::End) });
452 assert!(b.compile().is_err());
453 }
454
455 #[tokio::test]
456 async fn compile_accepts_valid_graph() {
457 let mut b = GraphBuilder::new();
458 b.add_node("agent", ok_node);
459 b.add_node("tools", ok_node);
460 b.set_entry_point("agent");
461 b.add_edge("tools", "agent");
462 b.add_conditional_edges("agent", |state| async move {
463 Ok(if state.contains("done") {
464 Route::End
465 } else {
466 Route::Node("tools".into())
467 })
468 });
469 let graph = b.compile().unwrap();
470 assert_eq!(graph.entry_point(), "agent");
471 assert_eq!(graph.node_count(), 2);
472 assert!(graph.has_node("tools"));
473 assert_eq!(graph.outgoing_edges("agent").len(), 1);
474 assert_eq!(graph.outgoing_edges("tools").len(), 1);
475
476 let g2 = graph.clone();
478 assert!(g2.node("agent").is_some());
479
480 let edges = graph.outgoing_edges("agent");
482 let route = match edges[0] {
483 Edge::Conditional { router, .. } => {
484 router(State::from_value(json!({"done": true})).unwrap()).await
485 }
486 _ => panic!("expected conditional edge"),
487 };
488 assert_eq!(route.unwrap(), Route::End);
489 }
490
491 #[test]
492 fn compile_rejects_duplicate_direct_edges() {
493 let mut b = GraphBuilder::new();
494 b.add_node("a", ok_node);
495 b.add_node("b", ok_node);
496 b.set_entry_point("a");
497 b.add_edge("a", "b");
498 b.add_edge("a", "b");
499 let err = b.compile().unwrap_err();
500 assert!(matches!(err, RustyError::Graph(_)));
501 }
502
503 #[test]
504 fn compile_rejects_duplicate_conditional_edges() {
505 let mut b = GraphBuilder::new();
506 b.add_node("a", ok_node);
507 b.set_entry_point("a");
508 b.add_conditional_edges("a", |_s| async { Ok(Route::End) });
509 b.add_conditional_edges("a", |_s| async { Ok(Route::End) });
510 let err = b.compile().unwrap_err();
511 assert!(matches!(err, RustyError::Graph(_)));
512 }
513
514 #[test]
515 fn compile_rejects_mixed_static_and_conditional_edges() {
516 let mut b = GraphBuilder::new();
517 b.add_node("a", ok_node);
518 b.add_node("b", ok_node);
519 b.set_entry_point("a");
520 b.add_edge("a", "b");
521 b.add_conditional_edges("a", |_s| async { Ok(Route::End) });
522 let err = b.compile().unwrap_err();
523 assert!(matches!(err, RustyError::Graph(_)));
524 }
525
526 #[test]
527 fn compile_rejects_reserved_node_names() {
528 for name in [END, "__internal"] {
529 let mut b = GraphBuilder::new();
530 b.add_node(name, ok_node);
531 b.set_entry_point(name);
532 let err = b.compile().unwrap_err();
533 assert!(matches!(err, RustyError::Graph(_)), "name: {name}");
534 }
535 }
536}