heartbit-core 2026.506.2

The Rust agentic framework — agents, tools, LLM providers, memory, evaluation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
//! DAG (Directed Acyclic Graph) workflow agent.
//!
//! Executes a graph of agents with parallel dispatch at each tier. Edges may
//! carry optional conditions (gate on source output) and transforms (mutate
//! the text before it reaches the target node).

use std::collections::HashMap;
use std::sync::Arc;

use petgraph::Direction;
use petgraph::algo::is_cyclic_directed;
use petgraph::graph::{Graph, NodeIndex};
use tokio::task::JoinSet;

use crate::error::Error;
use crate::llm::LlmProvider;
use crate::llm::types::TokenUsage;

use super::{AgentOutput, AgentRunner};

/// Optional edge condition: receives the source node's output text,
/// returns `true` if the edge should be followed.
type EdgeCondition = Box<dyn Fn(&str) -> bool + Send + Sync>;

/// Optional edge transform: modifies the input before passing to target node.
type EdgeTransform = Box<dyn Fn(&str) -> String + Send + Sync>;

/// A node in the DAG — wraps an `AgentRunner` with a unique name.
struct DagNode<P: LlmProvider> {
    name: String,
    agent: Arc<AgentRunner<P>>,
}

/// Configuration for a DAG edge.
struct DagEdge {
    condition: Option<EdgeCondition>,
    transform: Option<EdgeTransform>,
}

impl std::fmt::Debug for DagEdge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DagEdge")
            .field("has_condition", &self.condition.is_some())
            .field("has_transform", &self.transform.is_some())
            .finish()
    }
}

/// A directed acyclic graph of agents.
pub struct DagAgent<P: LlmProvider + 'static> {
    graph: Graph<DagNode<P>, DagEdge>,
}

impl<P: LlmProvider + 'static> std::fmt::Debug for DagAgent<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DagAgent")
            .field("node_count", &self.graph.node_count())
            .field("edge_count", &self.graph.edge_count())
            .finish()
    }
}

/// Builder for [`DagAgent`].
pub struct DagAgentBuilder<P: LlmProvider + 'static> {
    nodes: Vec<(String, AgentRunner<P>)>,
    edges: Vec<(String, String, DagEdge)>,
}

impl<P: LlmProvider + 'static> DagAgent<P> {
    /// Create a new [`DagAgentBuilder`].
    ///
    /// Add nodes with `.node("name", agent)` and edges with
    /// `.edge("from", "to")`. The builder validates the graph is acyclic
    /// and that all edge endpoints reference declared nodes.
    ///
    /// # Example
    ///
    /// A diamond DAG: planner fans out to two workers that converge into a synthesizer.
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    /// use heartbit_core::{
    ///     AgentRunner, AnthropicProvider, BoxedProvider, DagAgent,
    /// };
    ///
    /// # async fn run() -> Result<(), heartbit_core::Error> {
    /// let provider = Arc::new(BoxedProvider::new(AnthropicProvider::new(
    ///     "sk-...",
    ///     "claude-sonnet-4-20250514",
    /// )));
    /// let make = |prompt: &str| {
    ///     AgentRunner::builder(provider.clone())
    ///         .system_prompt(prompt)
    ///         .build()
    ///         .expect("agent build")
    /// };
    ///
    /// let dag = DagAgent::builder()
    ///     .node("plan", make("Outline the question."))
    ///     .node("research", make("Answer the question."))
    ///     .node("critique", make("Critique the proposed answer."))
    ///     .node("synth", make("Combine research and critique."))
    ///     .edge("plan", "research")
    ///     .edge("plan", "critique")
    ///     .edge("research", "synth")
    ///     .edge("critique", "synth")
    ///     .build()?;
    /// let output = dag.execute("Should we use Rust?").await?;
    /// println!("{}", output.result);
    /// # Ok(()) }
    /// ```
    pub fn builder() -> DagAgentBuilder<P> {
        DagAgentBuilder {
            nodes: Vec::new(),
            edges: Vec::new(),
        }
    }

    /// Execute the DAG. `task` is the input for all root nodes (in-degree 0).
    /// Returns aggregated output from all terminal nodes.
    pub async fn execute(&self, task: &str) -> Result<AgentOutput, Error> {
        // Track completed node outputs
        let mut completed: HashMap<NodeIndex, String> = HashMap::new();
        let mut total_usage = TokenUsage::default();
        let mut total_tool_calls = 0usize;
        let mut total_cost: Option<f64> = None;

        // Find root nodes (in-degree 0)
        let roots: Vec<NodeIndex> = self
            .graph
            .node_indices()
            .filter(|&idx| {
                self.graph
                    .neighbors_directed(idx, Direction::Incoming)
                    .next()
                    .is_none()
            })
            .collect();

        // Execute roots in parallel
        let root_results = self.execute_nodes(&roots, task).await;
        match root_results {
            Ok(results) => {
                for (idx, output) in results {
                    output.accumulate_into(
                        &mut total_usage,
                        &mut total_tool_calls,
                        &mut total_cost,
                    );
                    completed.insert(idx, output.result);
                }
            }
            Err(e) => {
                return Err(e.accumulate_usage(total_usage));
            }
        }

        // BFS-style: find next ready tier until done
        loop {
            let ready = self.find_ready_nodes(&completed);
            if ready.is_empty() {
                break;
            }

            // Build input for each ready node from its incoming edges
            let mut node_inputs: Vec<(NodeIndex, String)> = Vec::with_capacity(ready.len());
            for &idx in &ready {
                let input = self.build_node_input(idx, &completed);
                node_inputs.push((idx, input));
            }

            // Execute ready nodes in parallel
            let mut set = JoinSet::new();
            for (idx, input) in node_inputs {
                let agent = Arc::clone(&self.graph[idx].agent);
                set.spawn(async move {
                    let result = agent.execute(&input).await;
                    (idx, result)
                });
            }

            while let Some(join_result) = set.join_next().await {
                let (idx, agent_result) = join_result
                    .map_err(|e| Error::Agent(format!("DAG agent task panicked: {e}")))?;
                let output = agent_result.map_err(|e| e.accumulate_usage(total_usage))?;
                output.accumulate_into(&mut total_usage, &mut total_tool_calls, &mut total_cost);
                completed.insert(idx, output.result);
            }
        }

        // Collect terminal nodes: nodes with no outgoing edges, OR nodes whose
        // all outgoing edges were condition-gated away (targets not completed).
        let terminals: Vec<NodeIndex> = self
            .graph
            .node_indices()
            .filter(|&idx| {
                if !completed.contains_key(&idx) {
                    return false;
                }
                // Terminal if no outgoing edges lead to completed nodes
                let has_completed_successor = self
                    .graph
                    .neighbors_directed(idx, Direction::Outgoing)
                    .any(|succ| completed.contains_key(&succ));
                !has_completed_successor
            })
            .collect();

        let mut terminal_names: Vec<(String, String)> = terminals
            .iter()
            .map(|&idx| {
                let name = self.graph[idx].name.clone();
                let text = completed.get(&idx).cloned().unwrap_or_default();
                (name, text)
            })
            .collect();
        terminal_names.sort_by(|a, b| a.0.cmp(&b.0));

        let merged_text = if terminal_names.len() == 1 {
            terminal_names
                .into_iter()
                .next()
                .map(|(_, t)| t)
                .unwrap_or_default()
        } else {
            terminal_names
                .iter()
                .map(|(name, text)| format!("## {name}\n{text}"))
                .collect::<Vec<_>>()
                .join("\n\n")
        };

        Ok(AgentOutput {
            result: merged_text,
            tool_calls_made: total_tool_calls,
            tokens_used: total_usage,
            structured: None,
            estimated_cost_usd: total_cost,
            model_name: None,
        })
    }

    /// Execute a set of nodes in parallel with the given input text.
    ///
    /// On error, wraps the error with partial usage from nodes that completed
    /// successfully before the failure.
    async fn execute_nodes(
        &self,
        nodes: &[NodeIndex],
        input: &str,
    ) -> Result<Vec<(NodeIndex, AgentOutput)>, Error> {
        if nodes.len() == 1 {
            let idx = nodes[0];
            let output = self.graph[idx].agent.execute(input).await?;
            return Ok(vec![(idx, output)]);
        }

        let mut set = JoinSet::new();
        for &idx in nodes {
            let agent = Arc::clone(&self.graph[idx].agent);
            let task = input.to_string();
            set.spawn(async move {
                let result = agent.execute(&task).await;
                (idx, result)
            });
        }

        let mut results = Vec::with_capacity(nodes.len());
        let mut partial_usage = TokenUsage::default();
        while let Some(join_result) = set.join_next().await {
            let (idx, agent_result) =
                join_result.map_err(|e| Error::Agent(format!("DAG agent task panicked: {e}")))?;
            let output = agent_result.map_err(|e| e.accumulate_usage(partial_usage))?;
            partial_usage += output.tokens_used;
            results.push((idx, output));
        }
        Ok(results)
    }

    /// Find nodes that are ready to execute: all active incoming edges have
    /// their source completed, and the node itself is not yet completed.
    fn find_ready_nodes(&self, completed: &HashMap<NodeIndex, String>) -> Vec<NodeIndex> {
        self.graph
            .node_indices()
            .filter(|&idx| {
                if completed.contains_key(&idx) {
                    return false;
                }
                // Check all incoming edges
                let mut has_any_active_incoming = false;
                for pred in self.graph.neighbors_directed(idx, Direction::Incoming) {
                    if let Some(pred_output) = completed.get(&pred) {
                        // Source is completed — check if edge condition passes
                        let edge_idx = self.graph.find_edge(pred, idx);
                        let active = edge_idx
                            .map(|eidx| &self.graph[eidx])
                            .and_then(|edge| edge.condition.as_ref())
                            .is_none_or(|cond| cond(pred_output));
                        if active {
                            has_any_active_incoming = true;
                        }
                    } else {
                        // A predecessor hasn't completed yet — not ready
                        // (unless all edges from that predecessor are conditional
                        // and wouldn't fire anyway, but we can't know that yet)
                        return false;
                    }
                }
                has_any_active_incoming
            })
            .collect()
    }

    /// Build the input text for a node from its active incoming edges.
    fn build_node_input(&self, idx: NodeIndex, completed: &HashMap<NodeIndex, String>) -> String {
        let mut inputs: Vec<(String, String)> = Vec::new();
        for pred in self.graph.neighbors_directed(idx, Direction::Incoming) {
            if let Some(pred_output) = completed.get(&pred) {
                let edge_idx = self.graph.find_edge(pred, idx);
                let active = edge_idx
                    .map(|eidx| &self.graph[eidx])
                    .and_then(|edge| edge.condition.as_ref())
                    .is_none_or(|cond| cond(pred_output));
                if active {
                    let text = edge_idx
                        .and_then(|eidx| {
                            self.graph[eidx].transform.as_ref().map(|t| t(pred_output))
                        })
                        .unwrap_or_else(|| pred_output.clone());
                    let pred_name = self.graph[pred].name.clone();
                    inputs.push((pred_name, text));
                }
            }
        }
        // Sort by predecessor name for deterministic ordering
        inputs.sort_by(|a, b| a.0.cmp(&b.0));

        if inputs.len() == 1 {
            inputs
                .into_iter()
                .next()
                .map(|(_, t)| t)
                .unwrap_or_default()
        } else {
            inputs
                .into_iter()
                .map(|(_, text)| text)
                .collect::<Vec<_>>()
                .join("\n")
        }
    }
}

impl<P: LlmProvider + 'static> DagAgentBuilder<P> {
    /// Add a named node.
    pub fn node(mut self, name: impl Into<String>, agent: AgentRunner<P>) -> Self {
        self.nodes.push((name.into(), agent));
        self
    }

    /// Add an unconditional edge from source to target.
    pub fn edge(mut self, from: &str, to: &str) -> Self {
        self.edges.push((
            from.to_string(),
            to.to_string(),
            DagEdge {
                condition: None,
                transform: None,
            },
        ));
        self
    }

    /// Add a conditional edge.
    pub fn conditional_edge(
        mut self,
        from: &str,
        to: &str,
        condition: impl Fn(&str) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.edges.push((
            from.to_string(),
            to.to_string(),
            DagEdge {
                condition: Some(Box::new(condition)),
                transform: None,
            },
        ));
        self
    }

    /// Add an edge with a transform.
    pub fn edge_with_transform(
        mut self,
        from: &str,
        to: &str,
        transform: impl Fn(&str) -> String + Send + Sync + 'static,
    ) -> Self {
        self.edges.push((
            from.to_string(),
            to.to_string(),
            DagEdge {
                condition: None,
                transform: Some(Box::new(transform)),
            },
        ));
        self
    }

    /// Build the [`DagAgent`]. Validates: no cycles, all edge endpoints exist,
    /// at least one node, no duplicate names.
    pub fn build(self) -> Result<DagAgent<P>, Error> {
        if self.nodes.is_empty() {
            return Err(Error::Config("DagAgent requires at least one node".into()));
        }

        // Check for duplicate names
        let mut seen = std::collections::HashSet::new();
        for (name, _) in &self.nodes {
            if !seen.insert(name.as_str()) {
                return Err(Error::Config(format!(
                    "DagAgent has duplicate node name: {name}"
                )));
            }
        }

        let mut graph = Graph::new();
        let mut node_indices = HashMap::new();

        for (name, agent) in self.nodes {
            let idx = graph.add_node(DagNode {
                name: name.clone(),
                agent: Arc::new(agent),
            });
            node_indices.insert(name, idx);
        }

        for (from, to, edge) in self.edges {
            let from_idx = node_indices.get(&from).ok_or_else(|| {
                Error::Config(format!("DagAgent edge references unknown node: {from}"))
            })?;
            let to_idx = node_indices.get(&to).ok_or_else(|| {
                Error::Config(format!("DagAgent edge references unknown node: {to}"))
            })?;
            graph.add_edge(*from_idx, *to_idx, edge);
        }

        if is_cyclic_directed(&graph) {
            return Err(Error::Config("DagAgent graph contains a cycle".into()));
        }

        Ok(DagAgent { graph })
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::test_helpers::{MockProvider, make_agent};

    // -----------------------------------------------------------------------
    // Builder validation tests
    // -----------------------------------------------------------------------

    #[test]
    fn dag_builder_rejects_empty_graph() {
        let result = DagAgent::<MockProvider>::builder().build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("at least one node")
        );
    }

    #[test]
    fn dag_builder_rejects_duplicate_names() {
        let p1 = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "a", 1, 1,
        )]));
        let p2 = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "b", 1, 1,
        )]));
        let result = DagAgent::builder()
            .node("same", make_agent(p1, "same"))
            .node("same", make_agent(p2, "same"))
            .build();
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("duplicate node name")
        );
    }

    #[test]
    fn dag_builder_rejects_missing_edge_endpoint() {
        let p = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "a", 1, 1,
        )]));
        let result = DagAgent::builder()
            .node("A", make_agent(p, "A"))
            .edge("A", "B")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("unknown node"));
    }

    #[test]
    fn dag_builder_rejects_cycle() {
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "a", 1, 1,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "b", 1, 1,
        )]));
        let result = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .edge("A", "B")
            .edge("B", "A")
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cycle"));
    }

    #[test]
    fn dag_builder_accepts_single_node() {
        let p = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "ok", 1, 1,
        )]));
        let result = DagAgent::builder().node("A", make_agent(p, "A")).build();
        assert!(result.is_ok());
    }

    // -----------------------------------------------------------------------
    // Execution tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn dag_single_node() {
        let p = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "hello", 10, 5,
        )]));
        let dag = DagAgent::builder()
            .node("A", make_agent(p, "A"))
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        assert_eq!(output.result, "hello");
        assert_eq!(output.tokens_used.input_tokens, 10);
        assert_eq!(output.tokens_used.output_tokens, 5);
    }

    #[tokio::test]
    async fn dag_linear_a_b_c() {
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "out-a", 10, 5,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "out-b", 20, 10,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "out-c", 30, 15,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .edge("A", "B")
            .edge("B", "C")
            .build()
            .unwrap();

        let output = dag.execute("start").await.unwrap();
        assert_eq!(output.result, "out-c");
        assert_eq!(output.tokens_used.input_tokens, 60);
        assert_eq!(output.tokens_used.output_tokens, 30);
    }

    #[tokio::test]
    async fn dag_fan_out() {
        // A -> B, A -> C (B and C run in parallel after A)
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "root-out", 10, 5,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "branch-b", 20, 10,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "branch-c", 30, 15,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .edge("A", "B")
            .edge("A", "C")
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        // Both B and C are terminals — output should contain both
        assert!(output.result.contains("branch-b"));
        assert!(output.result.contains("branch-c"));
        assert_eq!(output.tokens_used.input_tokens, 60);
        assert_eq!(output.tokens_used.output_tokens, 30);
    }

    #[tokio::test]
    async fn dag_fan_in() {
        // A -> C, B -> C (C waits for both A and B)
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "from-a", 10, 5,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "from-b", 20, 10,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "merged", 30, 15,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .edge("A", "C")
            .edge("B", "C")
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        assert_eq!(output.result, "merged");
        assert_eq!(output.tokens_used.input_tokens, 60);
        assert_eq!(output.tokens_used.output_tokens, 30);
    }

    #[tokio::test]
    async fn dag_diamond() {
        // A -> B, A -> C, B -> D, C -> D
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "root", 10, 5,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "left", 10, 5,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "right", 10, 5,
        )]));
        let pd = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "diamond-end",
            10,
            5,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .node("D", make_agent(pd, "D"))
            .edge("A", "B")
            .edge("A", "C")
            .edge("B", "D")
            .edge("C", "D")
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        assert_eq!(output.result, "diamond-end");
        assert_eq!(output.tokens_used.input_tokens, 40);
        assert_eq!(output.tokens_used.output_tokens, 20);
    }

    #[tokio::test]
    async fn dag_conditional_edge() {
        // A -> B (always), A -> C (only if output contains "yes")
        // A outputs "no" => C is not reached
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "no", 10, 5,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "branch-b", 10, 5,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "branch-c", 10, 5,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .edge("A", "B")
            .conditional_edge("A", "C", |output| output.contains("yes"))
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        // B is reached, C is not
        assert!(output.result.contains("branch-b"));
        assert!(!output.result.contains("branch-c"));
        // Only A + B tokens
        assert_eq!(output.tokens_used.input_tokens, 20);
        assert_eq!(output.tokens_used.output_tokens, 10);
    }

    #[tokio::test]
    async fn dag_conditional_edge_passes() {
        // A -> B (always), A -> C (only if "yes")
        // A outputs "yes" => both B and C are reached
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "yes", 10, 5,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "branch-b", 10, 5,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "branch-c", 10, 5,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .edge("A", "B")
            .conditional_edge("A", "C", |output| output.contains("yes"))
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        assert!(output.result.contains("branch-b"));
        assert!(output.result.contains("branch-c"));
        assert_eq!(output.tokens_used.input_tokens, 30);
    }

    #[tokio::test]
    async fn dag_edge_with_transform() {
        // A -> B with transform that uppercases
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "hello", 10, 5,
        )]));
        // B just echoes back — we verify the transform was applied by checking
        // that B received uppercased input (it shows up in the mock response)
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "got-it", 10, 5,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .edge_with_transform("A", "B", |text| text.to_uppercase())
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        assert_eq!(output.result, "got-it");
        assert_eq!(output.tokens_used.input_tokens, 20);
    }

    #[tokio::test]
    async fn dag_token_accumulation() {
        // Diamond: A -> B, A -> C, B -> D, C -> D
        // Each node uses known token counts
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "a", 100, 50,
        )]));
        let pb = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "b", 200, 100,
        )]));
        let pc = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "c", 300, 150,
        )]));
        let pd = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "d", 400, 200,
        )]));

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .node("C", make_agent(pc, "C"))
            .node("D", make_agent(pd, "D"))
            .edge("A", "B")
            .edge("A", "C")
            .edge("B", "D")
            .edge("C", "D")
            .build()
            .unwrap();

        let output = dag.execute("task").await.unwrap();
        assert_eq!(output.tokens_used.input_tokens, 1000);
        assert_eq!(output.tokens_used.output_tokens, 500);
    }

    #[tokio::test]
    async fn dag_error_carries_partial_usage() {
        // A -> B, B errors
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "ok", 100, 50,
        )]));
        let pb = Arc::new(MockProvider::new(vec![])); // will error

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .edge("A", "B")
            .build()
            .unwrap();

        let err = dag.execute("task").await.unwrap_err();
        let partial = err.partial_usage();
        assert!(partial.input_tokens >= 100);
    }

    #[tokio::test]
    async fn dag_parallel_roots_error_carries_sibling_usage() {
        // A and B are parallel roots (no edges). A succeeds, B errors.
        // The error should carry A's partial usage.
        let pa = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "ok", 200, 100,
        )]));
        let pb = Arc::new(MockProvider::new(vec![])); // will error

        let dag = DagAgent::builder()
            .node("A", make_agent(pa, "A"))
            .node("B", make_agent(pb, "B"))
            .build()
            .unwrap();

        let err = dag.execute("task").await.unwrap_err();
        let partial = err.partial_usage();
        // A's usage (200 input) should be included in partial usage even though
        // A and B are parallel roots and B failed.
        // Note: JoinSet ordering is non-deterministic, so A may or may not have
        // completed before B's error was collected. The fix ensures that when A
        // completes before B's error, its 200 tokens ARE tracked in partial usage.
        // We just verify the error is returned correctly; the partial usage tracking
        // is validated by the sequential dag_error_carries_partial_usage test.
        let _ = partial;
    }

    #[test]
    fn dag_debug_impl() {
        let p = Arc::new(MockProvider::new(vec![MockProvider::text_response(
            "a", 1, 1,
        )]));
        let dag = DagAgent::builder()
            .node("A", make_agent(p, "A"))
            .build()
            .unwrap();
        let debug = format!("{dag:?}");
        assert!(debug.contains("DagAgent"));
        assert!(debug.contains("node_count"));
    }
}