oneai-workflow 1.0.0

OneAI workflow compiler, DAG, validator, executor, StateGraph, and StateGraphExecutor
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! StateGraph executor — walks cyclic graph, evaluates edge conditions, handles interrupts.
//!
//! Unlike WorkflowDag (which is acyclic and runs levels sequentially),
//! StateGraph supports cyclic edges for iterative agent patterns like ReAct loops.
//! The executor walks the graph from the entry point, executing each node's action,
//! evaluating outgoing edge conditions to route to the next node, and handling
//! interrupt points where execution can pause for human intervention.
//!
//! Key features:
//! - Walks graph from `entry_point` through conditional edges
//! - Executes 6 NodeAction variants (LlmInfer, ToolCall, Delegate, HumanApproval, ConditionCheck, SwitchParadigm)
//! - Evaluates 9 EdgeCondition variants for dynamic routing (including ParadigmEquals, IterationExceeds)
//! - Handles interrupt points (nodes with `interrupt: true`)
//! - Bounded by `max_iterations` to prevent infinite loops
//! - Supports `{{variable}}` template interpolation in tool_name and args_template
//!
//! P2-2: GraphActionExecutor bridge
//! ------------------------------
//! The `GraphActionExecutor` trait enables AgentLoop integration — when a
//! concrete implementation (from `oneai-agent`) is provided, LlmInfer and
//! ToolCall nodes delegate to the AgentLoop's full pipeline (hooks, permission,
//! domain pack, tool definitions). This makes StateGraph execution a first-class
//! execution mode of the AgentLoop, not a separate disconnected system.
//!
//! The `DirectProviderActionExecutor` provides backward-compatible behavior
//! (direct provider.infer() + tool.execute() without AgentLoop integration).

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

use oneai_core::error::{OneAIError, Result};
use oneai_core::traits::{InteractionGate, LlmProvider, Tool};
use oneai_core::{InferenceRequest, InferenceResponse, Message, Role};

use crate::state_graph::{
    StateGraph, GraphState, GraphEdge, NodeAction, EdgeCondition, GraphExecutionResult,
};

// ─── Delegate Action Trait ────────────────────────────────────────────────────

/// Trait for executing delegate actions in StateGraph nodes.
///
/// This is a lightweight abstraction that avoids a cyclic dependency
/// with `oneai-agent`. The `oneai-agent` crate provides a concrete
/// implementation that wraps `SubAgentFactory`.
///
/// When no delegate factory is available, use `NoopDelegateFactory`
/// which returns an error for all delegate requests.
#[async_trait::async_trait]
pub trait DelegateFactory: Send + Sync {
    /// Execute a delegate action with the given agent kind and task.
    async fn delegate(&self, agent_kind: &str, task: &str) -> Result<String>;
}

/// A no-op delegate factory that returns errors for all requests.
/// Used when no sub-agent delegation is available.
pub struct NoopDelegateFactory;

#[async_trait::async_trait]
impl DelegateFactory for NoopDelegateFactory {
    async fn delegate(&self, agent_kind: &str, _task: &str) -> Result<String> {
        Err(OneAIError::Workflow(format!(
            "Delegate action '{}' not supported — no DelegateFactory configured", agent_kind
        )))
    }
}

// ─── ActionResult ────────────────────────────────────────────────────────────

/// The result of executing a single node action.
#[derive(Debug, Clone)]
pub struct ActionResult {
    /// The output content from this action.
    pub output: String,
    /// Error message if the action failed.
    pub error: Option<String>,
}

// ─── GraphActionExecutor Trait ──────────────────────────────────────────────────

/// Trait for executing graph node actions with full AgentLoop integration.
///
/// This is the P2-2 bridge — when a concrete implementation (from `oneai-agent`)
/// is provided, the StateGraphExecutor delegates LlmInfer and ToolCall nodes
/// to the AgentLoop's full pipeline instead of directly calling provider.infer()
/// and tool.execute(). This means:
///
/// - **LlmInfer**: Gets proper tool definitions (filtered by paradigm config),
///   domain pack tool decorators, PreInfer/PostInfer hooks, context assembly,
///   and the OutputParser for decision parsing.
/// - **ToolCall**: Gets PreToolUse/PostToolUse hooks, domain permission checks,
///   approval gate interaction, and error recovery.
/// - **SwitchParadigm**: Changes the active paradigm (updates tool filter
///   and system prompt for subsequent nodes).
///
/// The `DirectProviderActionExecutor` provides backward-compatible behavior
/// (direct provider + tool execution, no AgentLoop integration). It's used
/// when no AgentLoop is available (e.g., standalone StateGraph execution).
#[async_trait::async_trait]
pub trait GraphActionExecutor: Send + Sync {
    /// Execute an LLM inference node — using full AgentLoop infrastructure.
    ///
    /// When `include_tool_definitions` is true, builds tool definitions based on
    /// `tool_filter_override` or the active paradigm's tool set. This is critical
    /// for ReAct loops — the model needs tools to decide whether to call them.
    ///
    /// After inference, the response is parsed into a `GraphDecision` and stored
    /// in `state.parsed_decision` for edge condition routing.
    async fn execute_llm_infer(
        &self,
        action: &NodeAction,
        state: &mut GraphState,
    ) -> Result<ActionResult>;

    /// Execute a tool call node — using AgentLoop's permission and hooks.
    ///
    /// When a GraphActionExecutor from `oneai-agent` is used, this method
    /// runs PreToolUse hooks, checks domain permissions, interacts with the
    /// approval gate, executes the tool, runs PostToolUse hooks, and handles
    /// error recovery.
    async fn execute_tool_call(
        &self,
        tool_name: &str,
        args: &serde_json::Value,
        state: &mut GraphState,
    ) -> Result<ActionResult>;

    /// Execute a paradigm switch node.
    ///
    /// Updates `state.active_paradigm` and clears `state.parsed_decision`.
    /// Subsequent LlmInfer nodes will use the new paradigm's tool set
    /// and system prompt.
    async fn execute_paradigm_switch(
        &self,
        paradigm: &str,
        state: &mut GraphState,
    ) -> Result<ActionResult>;

    /// Parse an LLM response into a GraphDecision.
    ///
    /// Uses the same OutputParser as the AgentLoop for consistent
    /// decision parsing. Stores the result in `state.parsed_decision`.
    async fn parse_decision(
        &self,
        response: &InferenceResponse,
        state: &mut GraphState,
    ) -> Result<oneai_core::GraphDecision>;
}

// ─── DirectProviderActionExecutor ──────────────────────────────────────────────

/// Backward-compatible GraphActionExecutor that directly calls provider + tools.
///
/// This is the "no AgentLoop integration" path — used when StateGraphExecutor
/// is constructed via `with_direct_provider()`. It mimics the original behavior:
/// - LlmInfer: calls provider.infer() with a basic request (no hooks, no domain pack)
/// - ToolCall: calls tool.execute() directly (no permission, no hooks)
/// - SwitchParadigm: updates state.active_paradigm (no paradigm config)
/// - parse_decision: simple ContentBlock-based parsing
///
/// For full AgentLoop integration, use `AgentLoopGraphActionExecutor` from
/// `oneai-agent`.
pub struct DirectProviderActionExecutor {
    provider: Arc<dyn LlmProvider>,
    tools: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>>,
}

impl DirectProviderActionExecutor {
    /// Create a new direct executor with provider and tools.
    pub fn new(
        provider: Arc<dyn LlmProvider>,
        tools: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>>,
    ) -> Self {
        Self { provider, tools }
    }
}

#[async_trait::async_trait]
impl GraphActionExecutor for DirectProviderActionExecutor {
    async fn execute_llm_infer(
        &self,
        action: &NodeAction,
        state: &mut GraphState,
    ) -> Result<ActionResult> {
        // Extract LlmInfer fields
        let (system_prompt_override, _use_streaming, include_tool_definitions,
             tool_filter_override, thinking_budget, temperature, max_tokens) = match action {
            NodeAction::LlmInfer {
                system_prompt_override, use_streaming, include_tool_definitions,
                tool_filter_override, thinking_budget, temperature, max_tokens,
            } => (
                system_prompt_override.clone(),
                *use_streaming,
                *include_tool_definitions,
                tool_filter_override.clone(),
                *thinking_budget,
                *temperature,
                *max_tokens,
            ),
            _ => return Err(OneAIError::Workflow("Expected LlmInfer action".to_string())),
        };

        // Build system prompt
        let system_prompt = system_prompt_override
            .unwrap_or_else(|| "You are an intelligent agent. Respond to the task.".to_string());

        let mut conversation = state.conversation.clone();
        if !conversation.messages.iter().any(|m| m.role == Role::System) {
            conversation.add_message(Message::system(&system_prompt));
        }

        // Build tool definitions if requested
        let tool_defs = if include_tool_definitions {
            let tools_map = self.tools.read().await;
            if let Some(filter) = &tool_filter_override {
                // Filter: only include specified tools
                tools_map.values()
                    .filter(|t| filter.contains(&t.name().to_string()))
                    .map(|t| oneai_core::ToolDefinition {
                        name: t.name().to_string(),
                        description: t.description().to_string(),
                        parameters_schema: t.parameters_schema(),
                    })
                    .collect()
            } else {
                // No filter — include all tools
                tools_map.values().map(|t| oneai_core::ToolDefinition {
                    name: t.name().to_string(),
                    description: t.description().to_string(),
                    parameters_schema: t.parameters_schema(),
                }).collect()
            }
        } else {
            vec![] // No tool definitions — pure text prompt
        };

        let request = InferenceRequest {
            conversation,
            tools: tool_defs,
            max_tokens: max_tokens.or(Some(4096)),
            temperature: temperature.or(Some(0.3)),
            top_p: None,
            stop_sequences: vec![],
            constrained_output: None,
            thinking_budget,
            metadata: HashMap::new(),
        };

        let response = self.provider.infer(request).await?;
        let output = response.message.text_content();

        // Update conversation state
        state.conversation.add_message(response.message.clone());

        // Parse decision and store in state
        let _decision = self.parse_decision(&response, state).await?;

        Ok(ActionResult {
            output,
            error: None,
        })
    }

    async fn execute_tool_call(
        &self,
        tool_name: &str,
        args: &serde_json::Value,
        state: &mut GraphState,
    ) -> Result<ActionResult> {
        let tools_map = self.tools.read().await;
        let tool = tools_map.get(tool_name)
            .ok_or_else(|| OneAIError::Workflow(
                format!("Tool '{}' not found for ToolCall node", tool_name)
            ))?;

        let output = tool.execute(args.clone()).await?;

        state.conversation.add_message(Message::tool_result(
            format!("graph_tool_{}", tool_name),
            output.content.clone(),
        ));

        Ok(ActionResult {
            output: output.content,
            error: output.error,
        })
    }

    async fn execute_paradigm_switch(
        &self,
        paradigm: &str,
        state: &mut GraphState,
    ) -> Result<ActionResult> {
        state.active_paradigm = Some(paradigm.to_string());
        state.parsed_decision = None; // Clear — new inference needed

        Ok(ActionResult {
            output: format!("Paradigm switched to: {}", paradigm),
            error: None,
        })
    }

    async fn parse_decision(
        &self,
        response: &InferenceResponse,
        state: &mut GraphState,
    ) -> Result<oneai_core::GraphDecision> {
        // Simple ContentBlock-based parsing (mirrors the AgentLoop's parse_decision logic
        // but produces GraphDecision instead of AgentDecision)
        let mut tool_calls = Vec::new();
        let mut text_parts = Vec::new();

        for block in &response.message.content {
            match block {
                oneai_core::ContentBlock::ToolCall { id: _, name, args } => {
                    // Check for special internal tools (delegate, switch_paradigm)
                    if name == "delegate" {
                        // Parse delegate args
                        let args_value: serde_json::Value = serde_json::from_str(args)
                            .unwrap_or_else(|_| serde_json::json!({}));
                        let agent_kind = args_value.get("agent_type")
                            .and_then(|v| v.as_str()).unwrap_or("Explore").to_string();
                        let task = args_value.get("task")
                            .and_then(|v| v.as_str()).unwrap_or("").to_string();
                        let decision = oneai_core::GraphDecision::Delegate {
                            agent_kind,
                            task,
                        };
                        state.parsed_decision = Some(decision.clone());
                        return Ok(decision);
                    }
                    if name == "switch_paradigm" {
                        let args_value: serde_json::Value = serde_json::from_str(args)
                            .unwrap_or_else(|_| serde_json::json!({}));
                        let paradigm = args_value.get("paradigm")
                            .and_then(|v| v.as_str()).unwrap_or("react").to_string();
                        let decision = oneai_core::GraphDecision::SwitchParadigm { paradigm };
                        state.parsed_decision = Some(decision.clone());
                        return Ok(decision);
                    }
                    tool_calls.push(name.clone());
                }
                oneai_core::ContentBlock::Text { text } => {
                    text_parts.push(text.clone());
                }
                _ => {}
            }
        }

        let decision = if !tool_calls.is_empty() {
            oneai_core::GraphDecision::ToolCalls {
                count: tool_calls.len(),
            }
        } else {
            oneai_core::GraphDecision::DirectAnswer {
                text: text_parts.join("\n"),
            }
        };

        state.parsed_decision = Some(decision.clone());
        Ok(decision)
    }
}

// ─── StateGraphExecutor ──────────────────────────────────────────────────────

/// Executor for StateGraph — walks cyclic graph with conditional routing.
///
/// The executor processes a StateGraph by:
/// 1. Starting at the `entry_point` node
/// 2. Executing each node's `NodeAction` via the `GraphActionExecutor`
/// 3. Evaluating outgoing `EdgeCondition`s to select the next node
/// 4. Handling interrupt points (nodes marked with `interrupt: true`)
/// 5. Terminating when a terminal node is reached or max iterations exceeded
///
/// P2-2: The executor now uses a `GraphActionExecutor` for node action execution.
/// This enables AgentLoop integration — when an `AgentLoopGraphActionExecutor`
/// (from `oneai-agent`) is provided, LlmInfer/ToolCall nodes delegate to the
/// AgentLoop's full pipeline (hooks, permission, domain pack, tool definitions).
///
/// Template interpolation (`{{variable}}`) is still applied to `tool_name` and
/// `args_template` fields before tool execution, using `GraphState.variables`.
pub struct StateGraphExecutor {
    /// Action executor — delegates node action execution.
    /// Can be DirectProviderActionExecutor (backward compat) or
    /// AgentLoopGraphActionExecutor (full AgentLoop integration).
    action_executor: Arc<dyn GraphActionExecutor>,
    /// Delegate factory for Delegate nodes.
    delegate_factory: Arc<dyn DelegateFactory>,
    /// Approval gate for interrupt points and HumanApproval nodes.
    interaction_gate: Arc<dyn InteractionGate>,
    /// Maximum iterations through the graph (prevents infinite loops).
    /// Default: 50.
    max_iterations: usize,
}

impl StateGraphExecutor {
    /// Create a new StateGraphExecutor with a GraphActionExecutor.
    ///
    /// This is the P2-2 constructor — when an `AgentLoopGraphActionExecutor`
    /// is provided, LlmInfer/ToolCall nodes get full AgentLoop integration.
    pub fn new(
        action_executor: Arc<dyn GraphActionExecutor>,
        delegate_factory: Arc<dyn DelegateFactory>,
        interaction_gate: Arc<dyn InteractionGate>,
        max_iterations: usize,
    ) -> Self {
        Self {
            action_executor,
            delegate_factory,
            interaction_gate,
            max_iterations,
        }
    }

    /// Create with default max_iterations (50).
    pub fn with_defaults(
        action_executor: Arc<dyn GraphActionExecutor>,
        delegate_factory: Arc<dyn DelegateFactory>,
        interaction_gate: Arc<dyn InteractionGate>,
    ) -> Self {
        Self::new(action_executor, delegate_factory, interaction_gate, 50)
    }

    /// Create with direct provider + tools (backward-compatible constructor).
    ///
    /// This constructor creates a `DirectProviderActionExecutor` internally,
    /// providing the same behavior as the original StateGraphExecutor (before P2-2).
    /// Use this when you don't have an AgentLoop available (e.g., standalone
    /// StateGraph execution without AgentLoop integration).
    pub fn with_direct_provider(
        provider: Arc<dyn LlmProvider>,
        tools: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>>,
        delegate_factory: Arc<dyn DelegateFactory>,
        interaction_gate: Arc<dyn InteractionGate>,
        max_iterations: usize,
    ) -> Self {
        let action_executor = Arc::new(DirectProviderActionExecutor::new(provider, tools));
        Self::new(action_executor, delegate_factory, interaction_gate, max_iterations)
    }

    /// Create with direct provider + default max_iterations (50).
    /// Backward-compatible with the original `with_defaults()` constructor.
    pub fn with_direct_provider_defaults(
        provider: Arc<dyn LlmProvider>,
        tools: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>>,
        delegate_factory: Arc<dyn DelegateFactory>,
        interaction_gate: Arc<dyn InteractionGate>,
    ) -> Self {
        Self::with_direct_provider(provider, tools, delegate_factory, interaction_gate, 50)
    }

    /// Execute a StateGraph starting from its entry point.
    ///
    /// Walks the graph, executing each node's action and routing to the
    /// next node based on edge conditions. Returns a GraphExecutionResult
    /// with the final state, completion status, and iteration count.
    pub async fn execute(
        &self,
        graph: &StateGraph,
        initial_state: GraphState,
    ) -> Result<GraphExecutionResult> {
        let mut state = initial_state;
        let mut current_node_id = graph.entry_point.clone();
        let mut iterations = 0;
        let mut interrupt_checkpoints = Vec::new();

        while iterations < self.max_iterations {
            iterations += 1;
            state.iteration_count = iterations;

            // 1. Get the current node
            let node = graph.get_node(&current_node_id)
                .ok_or_else(|| OneAIError::Workflow(
                    format!("Node '{}' not found in graph '{}'", current_node_id, graph.name)
                ))?;

            // 2. Check if this is a terminal node
            if graph.terminal_nodes.contains(&current_node_id) {
                let action_result = self.execute_node_action(&node.action, &mut state).await?;
                state.last_result = Some(action_result.output.clone());
                state.last_error = action_result.error.clone();

                return Ok(GraphExecutionResult {
                    name: graph.name.clone(),
                    final_state: state,
                    completed: true,
                    terminal_node: Some(current_node_id),
                    iterations,
                    interrupt_checkpoints,
                });
            }

            // 3. Check interrupt point
            if node.interrupt {
                let checkpoint_id = format!("interrupt_{}_{}", graph.name, current_node_id);
                interrupt_checkpoints.push(checkpoint_id.clone());

                // Request human approval
                let approval_request = oneai_core::ApprovalRequest {
                    tool_name: "state_graph_interrupt".into(),
                    args: serde_json::json!({
                        "node": current_node_id,
                        "description": match &node.action {
                            NodeAction::HumanApproval { description } => description.clone(),
                            _ => "Interrupt point reached".to_string(),
                        },
                        "state": state.variables,
                    }),
                    risk_level: oneai_core::RiskLevel::Medium,
                    permission_level: Some(oneai_core::PermissionLevel::Standard),
                    justification: format!("StateGraph interrupt at node '{}' in graph '{}'",
                        current_node_id, graph.name),
                };

                let approval = self
                    .interaction_gate
                    .request(oneai_core::InteractionRequest::ToolApproval {
                        approval: approval_request,
                    })
                    .await?;
                match approval {
                    oneai_core::InteractionResponse::Abort { reason } => {
                        state.should_terminate = true;
                        state.last_error = Some(format!("Interrupt denied: {}", reason));
                        return Ok(GraphExecutionResult {
                            name: graph.name.clone(),
                            final_state: state,
                            completed: false,
                            terminal_node: None,
                            iterations,
                            interrupt_checkpoints,
                        });
                    }
                    oneai_core::InteractionResponse::Revise { feedback } => {
                        // Stateless graph path can't loop on feedback → deny.
                        state.should_terminate = true;
                        state.last_error = Some(format!("Interrupt denied: {}", feedback));
                        return Ok(GraphExecutionResult {
                            name: graph.name.clone(),
                            final_state: state,
                            completed: false,
                            terminal_node: None,
                            iterations,
                            interrupt_checkpoints,
                        });
                    }
                    _ => { /* Proceed / ProceedWith / Choose — continue execution */ }
                }
            }

            // 4. Execute node action
            let action_result = self.execute_node_action(&node.action, &mut state).await?;

            // 5. Update state
            state.last_result = Some(action_result.output.clone());
            state.last_error = action_result.error.clone();
            if state.should_terminate {
                break;
            }

            // 6. Evaluate outgoing edges → route to next node
            let edges = graph.get_edges_from(&current_node_id);
            let next_node = self.route_next_node(&edges, &state)?;

            if next_node.is_none() {
                // No matching condition — terminate
                tracing::warn!(
                    "No matching edge condition from node '{}' in graph '{}'. Terminating.",
                    current_node_id, graph.name
                );
                break;
            }

            current_node_id = next_node.unwrap();
        }

        // Did we exceed max_iterations or terminate without reaching a terminal node?
        let should_terminate = state.should_terminate;
        if iterations >= self.max_iterations {
            tracing::warn!(
                "StateGraph '{}' exceeded max iterations ({}). Terminating.",
                graph.name, self.max_iterations
            );
        }

        Ok(GraphExecutionResult {
            name: graph.name.clone(),
            final_state: state,
            completed: !should_terminate,
            terminal_node: None,
            iterations,
            interrupt_checkpoints,
        })
    }

    /// Execute a node's action and update the state.
    ///
    /// P2-2: LlmInfer and ToolCall nodes delegate to the GraphActionExecutor,
    /// which may be an AgentLoopGraphActionExecutor (full AgentLoop integration)
    /// or a DirectProviderActionExecutor (backward compat).
    async fn execute_node_action(
        &self,
        action: &NodeAction,
        state: &mut GraphState,
    ) -> Result<ActionResult> {
        match action {
            NodeAction::LlmInfer { .. } => {
                // Delegate to GraphActionExecutor — which may build tool definitions,
                // run hooks, use domain pack, and parse the response into GraphDecision.
                self.action_executor.execute_llm_infer(action, state).await
            }

            NodeAction::ToolCall { tool_name, args_template } => {
                // Template interpolation: {{variable}} → state.variables[key]
                let resolved_name = interpolate_graph_template(tool_name, &state.variables);
                let resolved_args = if let Some(template) = args_template {
                    let json_str = interpolate_graph_template(template, &state.variables);
                    serde_json::from_str(&json_str)
                        .unwrap_or(serde_json::json!({}))
                } else {
                    serde_json::json!({})
                };

                // Delegate to GraphActionExecutor — which may run hooks,
                // check permissions, interact with approval gate.
                self.action_executor.execute_tool_call(&resolved_name, &resolved_args, state).await
            }

            NodeAction::Delegate { agent_kind, task_template } => {
                let task = interpolate_graph_template(task_template, &state.variables);

                let result = self.delegate_factory.delegate(agent_kind, &task).await?;

                // Append delegate result to conversation
                state.conversation.add_message(Message::assistant(
                    format!("[Delegate {}]: {}", agent_kind, result)
                ));

                // Set parsed_decision to Delegate
                state.parsed_decision = Some(oneai_core::GraphDecision::Delegate {
                    agent_kind: agent_kind.clone(),
                    task,
                });

                Ok(ActionResult {
                    output: result,
                    error: None,
                })
            }

            NodeAction::HumanApproval { description } => {
                // Handled in the main loop's interrupt check.
                // Here we just return the description as output.
                Ok(ActionResult {
                    output: description.clone(),
                    error: None,
                })
            }

            NodeAction::ConditionCheck { condition } => {
                let result = self.evaluate_condition_expression(condition, state)?;
                state.variables.insert("_condition_result".to_string(), result.to_string());
                Ok(ActionResult {
                    output: result.to_string(),
                    error: None,
                })
            }

            NodeAction::SwitchParadigm { paradigm } => {
                // Delegate to GraphActionExecutor — updates state.active_paradigm
                self.action_executor.execute_paradigm_switch(paradigm, state).await
            }
        }
    }

    /// Route to the next node by evaluating outgoing edge conditions.
    ///
    /// Priority: conditional edges are evaluated in order; the first matching
    /// condition determines the next node. Unconditional edges (Always) act
    /// as fallback routing.
    fn route_next_node(
        &self,
        edges: &[&GraphEdge],
        state: &GraphState,
    ) -> Result<Option<String>> {
        for edge in edges {
            if let Some(condition) = &edge.condition {
                if self.evaluate_edge_condition(condition, state)? {
                    return Ok(Some(edge.to.clone()));
                }
            } else {
                // No condition — unconditional edge (fallback)
                return Ok(Some(edge.to.clone()));
            }
        }
        Ok(None)
    }

    /// Evaluate an edge condition against the current state.
    ///
    /// P2-2: HasToolCalls, IsFinalAnswer, and RequestsDelegation now evaluate
    /// against `state.parsed_decision` (a structured `GraphDecision`) rather
    /// than unreliable string pattern matching. This makes edge routing
    /// consistent with the AgentLoop's decision parsing.
    fn evaluate_edge_condition(
        &self,
        condition: &EdgeCondition,
        state: &GraphState,
    ) -> Result<bool> {
        match condition {
            EdgeCondition::HasToolCalls => {
                // P2-2: Use parsed_decision instead of string matching
                Ok(state.parsed_decision.as_ref()
                    .map(|d| d.has_tool_calls())
                    .unwrap_or(false))
            }

            EdgeCondition::IsFinalAnswer => {
                // P2-2: Use parsed_decision instead of !HasToolCalls
                Ok(state.parsed_decision.as_ref()
                    .map(|d| d.is_final())
                    .unwrap_or(false))
            }

            EdgeCondition::RequestsDelegation => {
                // P2-2: Use parsed_decision
                Ok(state.parsed_decision.as_ref()
                    .map(|d| d.is_delegation())
                    .unwrap_or(false))
            }

            EdgeCondition::ErrorOccurred => {
                Ok(state.last_error.is_some())
            }

            EdgeCondition::StateEquals { variable, value } => {
                Ok(state.variables.get(variable) == Some(value))
            }

            EdgeCondition::Always => Ok(true),

            EdgeCondition::Custom { name, description } => {
                tracing::warn!(
                    "Custom condition '{}' ('{}') not registered. Defaulting to false.",
                    name, description
                );
                Ok(false)
            }

            EdgeCondition::ParadigmEquals { paradigm } => {
                Ok(state.active_paradigm.as_ref() == Some(paradigm))
            }

            EdgeCondition::IterationExceeds { count } => {
                Ok(state.iteration_count > *count)
            }
        }
    }

    /// Evaluate a condition expression (for ConditionCheck nodes).
    ///
    /// Simple condition expressions:
    /// - "has_tool_calls" → checks parsed_decision for ToolCalls
    /// - "is_final_answer" → checks parsed_decision for DirectAnswer
    /// - "error_occurred" → checks if last_error is set
    /// - "variable==value" → checks state variable equality
    fn evaluate_condition_expression(&self, condition: &str, state: &GraphState) -> Result<bool> {
        if condition == "has_tool_calls" {
            return self.evaluate_edge_condition(&EdgeCondition::HasToolCalls, state);
        }
        if condition == "is_final_answer" {
            return self.evaluate_edge_condition(&EdgeCondition::IsFinalAnswer, state);
        }
        if condition == "error_occurred" {
            return self.evaluate_edge_condition(&EdgeCondition::ErrorOccurred, state);
        }
        // "variable==value" pattern
        if let Some((var, val)) = condition.split_once("==") {
            return Ok(state.variables.get(var.trim()) == Some(&val.trim().to_string()));
        }
        // Fallback: treat as a state variable lookup (truthy check)
        Ok(state.variables.get(condition).map(|v| v == "true").unwrap_or(false))
    }
}

// ─── Template Interpolation ────────────────────────────────────────────────

/// Interpolate `{{variable}}` template patterns for StateGraph execution.
///
/// Uses `GraphState.variables` as the substitution source.
/// Replaces `{{key}}` with the corresponding value from the variables map.
pub fn interpolate_graph_template(template: &str, variables: &HashMap<String, String>) -> String {
    let mut result = template.to_string();
    for (key, value) in variables {
        result = result.replace(&format!("{{{{{}}}}}", key), value);
    }
    result
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state_graph::{StateGraph, GraphNode};

    #[allow(dead_code)] // test fixture retained for future executor coverage
    fn make_simple_graph() -> StateGraph {
        // Simple linear graph: start → process → end
        let mut graph = StateGraph::new("test", "start");

        graph.add_node(GraphNode {
            id: "start".to_string(),
            action: NodeAction::ConditionCheck {
                condition: "ready==true".to_string(),
            },
            interrupt: false,
            metadata: HashMap::new(),
        });

        graph.add_node(GraphNode {
            id: "end".to_string(),
            action: NodeAction::LlmInfer {
                system_prompt_override: Some("Final answer".to_string()),
                use_streaming: false,
                include_tool_definitions: false,
                tool_filter_override: None,
                thinking_budget: None,
                temperature: None,
                max_tokens: None,
            },
            interrupt: false,
            metadata: HashMap::new(),
        });

        graph.add_edge(GraphEdge {
            from: "start".to_string(),
            to: "end".to_string(),
            condition: Some(EdgeCondition::Always),
            metadata: HashMap::new(),
        });

        graph.add_terminal("end".to_string());

        graph
    }

    #[test]
    fn test_evaluate_edge_condition_always() {
        let state = GraphState::new();
        let executor = make_test_executor();

        let result = executor.evaluate_edge_condition(&EdgeCondition::Always, &state).unwrap();
        assert!(result);
    }

    #[test]
    fn test_evaluate_edge_condition_error_occurred() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // No error → false
        assert!(!executor.evaluate_edge_condition(&EdgeCondition::ErrorOccurred, &state).unwrap());

        // With error → true
        state.last_error = Some("test error".to_string());
        assert!(executor.evaluate_edge_condition(&EdgeCondition::ErrorOccurred, &state).unwrap());
    }

    #[test]
    fn test_evaluate_edge_condition_state_equals() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // Variable not set → false
        let cond = EdgeCondition::StateEquals { variable: "mode".to_string(), value: "react".to_string() };
        assert!(!executor.evaluate_edge_condition(&cond, &state).unwrap());

        // Variable set but different value → false
        state.variables.insert("mode".to_string(), "plan".to_string());
        assert!(!executor.evaluate_edge_condition(&cond, &state).unwrap());

        // Variable matches → true
        state.variables.insert("mode".to_string(), "react".to_string());
        assert!(executor.evaluate_edge_condition(&cond, &state).unwrap());
    }

    #[test]
    fn test_evaluate_edge_condition_has_tool_calls() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // No parsed_decision → false
        assert!(!executor.evaluate_edge_condition(&EdgeCondition::HasToolCalls, &state).unwrap());

        // DirectAnswer → false
        state.parsed_decision = Some(oneai_core::GraphDecision::DirectAnswer {
            text: "Just a text answer".to_string(),
        });
        assert!(!executor.evaluate_edge_condition(&EdgeCondition::HasToolCalls, &state).unwrap());

        // ToolCalls → true
        state.parsed_decision = Some(oneai_core::GraphDecision::ToolCalls { count: 1 });
        assert!(executor.evaluate_edge_condition(&EdgeCondition::HasToolCalls, &state).unwrap());
    }

    #[test]
    fn test_evaluate_edge_condition_is_final_answer() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // No parsed_decision → false
        assert!(!executor.evaluate_edge_condition(&EdgeCondition::IsFinalAnswer, &state).unwrap());

        // DirectAnswer → true
        state.parsed_decision = Some(oneai_core::GraphDecision::DirectAnswer {
            text: "The answer is 42".to_string(),
        });
        assert!(executor.evaluate_edge_condition(&EdgeCondition::IsFinalAnswer, &state).unwrap());

        // ToolCalls → false
        state.parsed_decision = Some(oneai_core::GraphDecision::ToolCalls { count: 2 });
        assert!(!executor.evaluate_edge_condition(&EdgeCondition::IsFinalAnswer, &state).unwrap());
    }

    #[test]
    fn test_evaluate_edge_condition_requests_delegation() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // Delegate decision → true
        state.parsed_decision = Some(oneai_core::GraphDecision::Delegate {
            agent_kind: "Explore".to_string(),
            task: "Search the codebase".to_string(),
        });
        assert!(executor.evaluate_edge_condition(&EdgeCondition::RequestsDelegation, &state).unwrap());

        // ToolCalls → false
        state.parsed_decision = Some(oneai_core::GraphDecision::ToolCalls { count: 1 });
        assert!(!executor.evaluate_edge_condition(&EdgeCondition::RequestsDelegation, &state).unwrap());
    }

    #[test]
    fn test_evaluate_edge_condition_paradigm_equals() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // No paradigm → false
        let cond = EdgeCondition::ParadigmEquals { paradigm: "react".to_string() };
        assert!(!executor.evaluate_edge_condition(&cond, &state).unwrap());

        // Wrong paradigm → false
        state.active_paradigm = Some("plan".to_string());
        assert!(!executor.evaluate_edge_condition(&cond, &state).unwrap());

        // Matching paradigm → true
        state.active_paradigm = Some("react".to_string());
        assert!(executor.evaluate_edge_condition(&cond, &state).unwrap());
    }

    #[test]
    fn test_evaluate_edge_condition_iteration_exceeds() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // iteration_count = 0, threshold = 5 → false
        let cond = EdgeCondition::IterationExceeds { count: 5 };
        assert!(!executor.evaluate_edge_condition(&cond, &state).unwrap());

        // iteration_count = 10, threshold = 5 → true
        state.iteration_count = 10;
        assert!(executor.evaluate_edge_condition(&cond, &state).unwrap());
    }

    #[test]
    fn test_interpolate_graph_template() {
        let vars = HashMap::from([
            ("selected_tool".to_string(), "shell".to_string()),
            ("command".to_string(), "ls -la".to_string()),
        ]);

        let result = interpolate_graph_template("{{selected_tool}} with {{command}}", &vars);
        assert_eq!(result, "shell with ls -la");
    }

    #[test]
    fn test_evaluate_condition_expression() {
        let mut state = GraphState::new();
        let executor = make_test_executor();

        // "variable==value" pattern
        state.variables.insert("mode".to_string(), "react".to_string());
        assert!(executor.evaluate_condition_expression("mode==react", &state).unwrap());
        assert!(!executor.evaluate_condition_expression("mode==plan", &state).unwrap());

        // "error_occurred" pattern
        state.last_error = Some("error".to_string());
        assert!(executor.evaluate_condition_expression("error_occurred", &state).unwrap());
    }

    /// Create a test executor with mock dependencies (for condition testing only).
    /// Note: We can't test full execute() without a real provider,
    /// but we can test all the routing logic.
    #[allow(dead_code)] // reserved for future executor-iteration tests
    struct TestStateGraphExecutor {
        #[allow(dead_code)]
        max_iterations: usize,
    }

    impl TestStateGraphExecutor {
        fn evaluate_edge_condition(&self, condition: &EdgeCondition, state: &GraphState) -> Result<bool> {
            match condition {
                EdgeCondition::HasToolCalls => {
                    Ok(state.parsed_decision.as_ref()
                        .map(|d| d.has_tool_calls())
                        .unwrap_or(false))
                }
                EdgeCondition::IsFinalAnswer => {
                    Ok(state.parsed_decision.as_ref()
                        .map(|d| d.is_final())
                        .unwrap_or(false))
                }
                EdgeCondition::RequestsDelegation => {
                    Ok(state.parsed_decision.as_ref()
                        .map(|d| d.is_delegation())
                        .unwrap_or(false))
                }
                EdgeCondition::ErrorOccurred => Ok(state.last_error.is_some()),
                EdgeCondition::StateEquals { variable, value } => {
                    Ok(state.variables.get(variable) == Some(value))
                }
                EdgeCondition::Always => Ok(true),
                EdgeCondition::Custom { name, .. } => {
                    tracing::warn!("Custom condition '{}' not registered, defaulting to false", name);
                    Ok(false)
                }
                EdgeCondition::ParadigmEquals { paradigm } => {
                    Ok(state.active_paradigm.as_ref() == Some(paradigm))
                }
                EdgeCondition::IterationExceeds { count } => {
                    Ok(state.iteration_count > *count)
                }
            }
        }

        fn evaluate_condition_expression(&self, condition: &str, state: &GraphState) -> Result<bool> {
            if condition == "has_tool_calls" {
                return self.evaluate_edge_condition(&EdgeCondition::HasToolCalls, state);
            }
            if condition == "is_final_answer" {
                return self.evaluate_edge_condition(&EdgeCondition::IsFinalAnswer, state);
            }
            if condition == "error_occurred" {
                return self.evaluate_edge_condition(&EdgeCondition::ErrorOccurred, state);
            }
            if let Some((var, val)) = condition.split_once("==") {
                return Ok(state.variables.get(var.trim()) == Some(&val.trim().to_string()));
            }
            Ok(state.variables.get(condition).map(|v| v == "true").unwrap_or(false))
        }
    }

    fn make_test_executor() -> TestStateGraphExecutor {
        TestStateGraphExecutor { max_iterations: 50 }
    }

    #[test]
    fn test_graph_decision_enum() {
        let decision = oneai_core::GraphDecision::DirectAnswer {
            text: "42".to_string(),
        };
        assert!(decision.is_final());
        assert!(!decision.has_tool_calls());

        let tool_calls = oneai_core::GraphDecision::ToolCalls { count: 2 };
        assert!(tool_calls.has_tool_calls());
        assert!(!tool_calls.is_final());

        let delegate = oneai_core::GraphDecision::Delegate {
            agent_kind: "Explore".to_string(),
            task: "Search".to_string(),
        };
        assert!(delegate.is_delegation());
        assert!(!delegate.has_tool_calls());

        let switch = oneai_core::GraphDecision::SwitchParadigm {
            paradigm: "plan".to_string(),
        };
        assert!(!switch.is_final());
        assert!(!switch.has_tool_calls());
    }
}