oneai-workflow 0.1.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
//! Workflow executor — runs compiled DAG with level-based parallel execution.
//!
//! The executor runs a WorkflowDag by:
//! 1. Processing levels sequentially (level 0 → level 1 → ... → level N)
//! 2. Within each level, running all steps concurrently (since they have no mutual dependencies)
//! 3. Tracking step results and passing context between levels
//! 4. Handling timeouts, retries, and approval gates
//! 5. Supporting `{{variable}}` template interpolation in tool_args and prompt fields
//! 6. Executing LLM inference for prompt-based steps when a provider is available
//!
//! Step results are accumulated in a WorkflowContext that flows between levels.
//! Template interpolation replaces `{{step_id_output}}` and `{{step_id}}` with
//! previous step outputs, and `{{variable_name}}` with context variables.

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

use serde::{Deserialize, Serialize};

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

use crate::config::{RetryPolicy, WorkflowConfig};
use crate::dag::WorkflowDag;

/// The status of a workflow step execution.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub enum StepStatus {
    /// Not yet started.
    Pending,
    /// Currently running.
    Running,
    /// Completed successfully.
    Completed,
    /// Failed (with optional error message).
    Failed,
    /// Skipped (a dependency failed and continue_on_failure is false).
    Skipped,
}

/// The result of a single workflow step execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepResult {
    /// The step ID.
    pub step_id: String,

    /// The status of this step.
    pub status: StepStatus,

    /// The output content (if completed).
    pub output: Option<String>,

    /// Error message (if failed).
    pub error: Option<String>,

    /// How many retries were used.
    pub retries_used: usize,

    /// Execution time in milliseconds.
    pub execution_time_ms: Option<u64>,
}

/// The result of the entire workflow execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowResult {
    /// The workflow name.
    pub name: String,

    /// The results of each step.
    pub step_results: HashMap<String, StepResult>,

    /// The final context variables after all steps.
    pub variables: HashMap<String, String>,

    /// Whether the workflow completed successfully.
    pub success: bool,

    /// Total execution time in milliseconds.
    pub total_time_ms: u64,

    /// Which level was being executed when the workflow ended.
    pub completed_levels: usize,
}

impl WorkflowResult {
    /// Get a step result by ID.
    pub fn get_step_result(&self, step_id: &str) -> Option<&StepResult> {
        self.step_results.get(step_id)
    }

    /// Get all completed step IDs.
    pub fn completed_steps(&self) -> Vec<String> {
        self.step_results
            .iter()
            .filter(|(_, r)| r.status == StepStatus::Completed)
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Get all failed step IDs.
    pub fn failed_steps(&self) -> Vec<String> {
        self.step_results
            .iter()
            .filter(|(_, r)| r.status == StepStatus::Failed)
            .map(|(id, _)| id.clone())
            .collect()
    }
}

/// Workflow execution context — shared state that flows between levels.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowContext {
    /// Context variables (initially from WorkflowConfig, updated by steps).
    pub variables: HashMap<String, String>,
    /// Results from completed steps (available to subsequent steps).
    pub step_outputs: HashMap<String, String>,
}

impl WorkflowContext {
    /// Create a context from workflow config variables.
    pub fn from_config(config: &WorkflowConfig) -> Self {
        Self {
            variables: config.variables.clone(),
            step_outputs: HashMap::new(),
        }
    }

    /// Set a variable.
    pub fn set_variable(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.variables.insert(key.into(), value.into());
    }

    /// Get a variable.
    pub fn get_variable(&self, key: &str) -> Option<&String> {
        self.variables.get(key)
    }

    /// Store a step's output.
    pub fn set_step_output(&mut self, step_id: impl Into<String>, output: impl Into<String>) {
        self.step_outputs.insert(step_id.into(), output.into());
    }
}

/// Workflow executor — runs a compiled DAG.
///
/// The executor processes the DAG level by level:
/// - Level 0: all root nodes run concurrently
/// - Level 1: nodes that depend only on level 0 nodes run concurrently
/// - Level N: nodes that depend only on earlier levels run concurrently
///
/// Between levels, the WorkflowContext is updated with step results.
/// Template interpolation (`{{variable}}`) is applied to tool_args and
/// prompt fields before step execution, using context variables and
/// previous step outputs.
///
/// When a provider is available, prompt-based steps (steps with a `prompt`
/// field but no `tool`) execute actual LLM inference instead of just
/// returning the prompt text.
pub struct WorkflowExecutor {
    /// The tool registry for executing tool-based steps.
    /// Uses RwLock so tools can be registered after construction.
    tools: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>>,
    /// The approval gate for high-risk tool approval.
    interaction_gate: Arc<dyn InteractionGate>,
    /// Optional LLM provider for executing prompt-based steps.
    /// When set, steps with a `prompt` field but no `tool` will call
    /// the provider for actual inference. When None, prompt steps
    /// just return the interpolated prompt text.
    provider: Option<Arc<dyn LlmProvider>>,
    /// Optional domain permission resolver. When present, a tool step is
    /// checked against domain policy (`deny_by_default` / `require_confirmation`
    /// / `auto_approve`) BEFORE dispatch — closing the workflow-path bypass of
    /// gap-analysis P1, where tool steps previously called `tool.execute()`
    /// directly with no permission check. `None` = pre-existing behaviour.
    permission_resolver: Option<Arc<dyn PermissionResolver>>,
}

impl WorkflowExecutor {
    /// Create a new executor with tools and approval gate.
    pub fn new(
        tools: Arc<HashMap<String, Arc<dyn Tool>>>,
        interaction_gate: Arc<dyn InteractionGate>,
    ) -> Self {
        // Convert static HashMap into RwLock-backed HashMap for dynamic registration
        Self {
            tools: Arc::new(tokio::sync::RwLock::new((*tools).clone())),
            interaction_gate,
            provider: None,
            permission_resolver: None,
        }
    }

    /// Create a new executor with an empty tool registry.
    /// Tools can be registered later via `register_tool()`.
    pub fn new_empty(interaction_gate: Arc<dyn InteractionGate>) -> Self {
        Self {
            tools: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
            interaction_gate,
            provider: None,
            permission_resolver: None,
        }
    }

    /// Create a new executor with tools, approval gate, and LLM provider.
    /// With a provider, prompt-based steps will execute actual LLM inference.
    pub fn with_provider(
        tools: Arc<HashMap<String, Arc<dyn Tool>>>,
        interaction_gate: Arc<dyn InteractionGate>,
        provider: Arc<dyn LlmProvider>,
    ) -> Self {
        Self {
            tools: Arc::new(tokio::sync::RwLock::new((*tools).clone())),
            interaction_gate,
            provider: Some(provider),
            permission_resolver: None,
        }
    }

    /// Attach a domain permission resolver so tool steps honour DomainPack
    /// `deny_by_default` / `require_confirmation` policy on this path.
    pub fn with_permission_resolver(mut self, resolver: Arc<dyn PermissionResolver>) -> Self {
        self.permission_resolver = Some(resolver);
        self
    }

    /// Set the LLM provider for prompt-based steps.
    /// When set, steps with a `prompt` field but no `tool` will call
    /// the provider for actual inference instead of returning raw text.
    pub fn set_provider(&mut self, provider: Arc<dyn LlmProvider>) {
        self.provider = Some(provider);
    }

    /// Register a tool for workflow step execution.
    pub async fn register_tool(&self, tool: Arc<dyn Tool>) {
        self.tools
            .write()
            .await
            .insert(tool.name().to_string(), tool);
    }

    /// Get a handle to the internal tool registry (Arc<RwLock<HashMap>>).
    /// Used by StateGraphExecutor to share the same tool registry.
    pub fn tools_handle(&self) -> Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>> {
        self.tools.clone()
    }

    /// Execute a workflow DAG.
    ///
    /// Runs the DAG level by level, with steps at the same level
    /// executing concurrently. Returns a WorkflowResult with the
    /// status of each step.
    pub async fn execute(
        &self,
        dag: &WorkflowDag,
        config: &WorkflowConfig,
    ) -> Result<WorkflowResult> {
        let start_time = std::time::Instant::now();
        let mut step_results: HashMap<String, StepResult> = HashMap::new();
        let mut context = WorkflowContext::from_config(config);
        let mut completed_levels = 0;

        // Mark all steps as pending initially
        for id in dag.nodes.keys() {
            step_results.insert(
                id.clone(),
                StepResult {
                    step_id: id.clone(),
                    status: StepStatus::Pending,
                    output: None,
                    error: None,
                    retries_used: 0,
                    execution_time_ms: None,
                },
            );
        }

        // Execute each level
        for level_ids in &dag.levels {
            let _level_start = std::time::Instant::now();

            // Check if any dependencies failed — skip if not continue_on_failure
            let mut skip_level = false;
            if !config.continue_on_failure {
                for step_id in level_ids {
                    if let Some(node) = dag.get_node(step_id) {
                        for dep_id in &node.depends_on {
                            if let Some(dep_result) = step_results.get(dep_id) {
                                if dep_result.status == StepStatus::Failed
                                    || dep_result.status == StepStatus::Skipped
                                {
                                    skip_level = true;
                                    break;
                                }
                            }
                        }
                    }
                    if skip_level {
                        break;
                    }
                }
            }

            if skip_level {
                // Skip all steps in this level
                for step_id in level_ids {
                    if let Some(result) = step_results.get_mut(step_id) {
                        result.status = StepStatus::Skipped;
                        result.error = Some("Dependency failed — step skipped".to_string());
                    }
                }
                continue;
            }

            // Execute all steps in this level concurrently
            let mut level_futures = Vec::new();

            for step_id in level_ids {
                let node = dag.get_node(step_id).unwrap();
                let step_config = node.step.clone();
                let retry_policy = config.effective_retry_policy(step_id);
                let timeout_secs = config.effective_timeout(step_id);
                let tools = self.tools.clone();
                let interaction_gate = self.interaction_gate.clone();
                let context_snapshot = context.clone();
                let provider = self.provider.clone();
                let permission_resolver = self.permission_resolver.clone();

                level_futures.push(tokio::spawn(async move {
                    execute_step(
                        step_config,
                        retry_policy,
                        timeout_secs,
                        tools,
                        interaction_gate,
                        context_snapshot,
                        provider,
                        permission_resolver,
                    )
                    .await
                }));
            }

            // Collect results from all steps in this level
            for future in level_futures {
                let result = future
                    .await
                    .map_err(|e| OneAIError::Workflow(format!("Task join error: {}", e)))?;

                match result {
                    Ok(step_result) => {
                        step_results.insert(step_result.step_id.clone(), step_result.clone());
                        if step_result.status == StepStatus::Completed {
                            if let Some(output) = &step_result.output {
                                context.set_step_output(&step_result.step_id, output);
                            }
                        }
                    }
                    Err(e) => {
                        // Step execution error
                        tracing::error!("Step execution error: {}", e);
                    }
                }
            }

            completed_levels += 1;
        }

        let total_time_ms = start_time.elapsed().as_millis() as u64;

        let success = step_results
            .values()
            .all(|r| r.status == StepStatus::Completed || r.status == StepStatus::Skipped);

        Ok(WorkflowResult {
            name: dag.name.clone(),
            step_results,
            variables: context.variables,
            success,
            total_time_ms,
            completed_levels,
        })
    }
}

/// Execute a single workflow step with retry support and template interpolation.
///
/// Template interpolation replaces `{{step_id_output}}` and `{{step_id}}` with
/// previous step outputs, and `{{variable_name}}` with context variables.
/// This is applied to `step.tool_args` (for tool steps) and `step.prompt`
/// (for prompt-based steps) before execution.
///
/// When a provider is available, prompt-based steps (no tool, just prompt)
/// execute actual LLM inference. When no provider is set, they return
/// the interpolated prompt text.
#[allow(clippy::too_many_arguments)]
async fn execute_step(
    mut step: crate::config::StepConfig,
    retry_policy: RetryPolicy,
    timeout_secs: Option<u64>,
    tools: Arc<tokio::sync::RwLock<HashMap<String, Arc<dyn Tool>>>>,
    interaction_gate: Arc<dyn InteractionGate>,
    context: WorkflowContext,
    provider: Option<Arc<dyn LlmProvider>>,
    permission_resolver: Option<Arc<dyn PermissionResolver>>,
) -> Result<StepResult> {
    let start_time = std::time::Instant::now();
    let step_id = step.id.clone();
    let mut retries_used = 0;
    let mut last_error: Option<String> = None;

    // ─── Template interpolation ──────────────────────────────────────────
    // Interpolate {{variable}} patterns in step.tool_args and step.prompt
    // using context.step_outputs and context.variables.
    let interpolated_prompt = step
        .prompt
        .as_ref()
        .map(|p| interpolate_template(p, &context));
    let interpolated_tool_args = step.tool_args.as_ref().map(|a| {
        // Interpolate string values in the JSON
        let json_str = serde_json::to_string(a).unwrap_or_default();
        let interpolated = interpolate_template(&json_str, &context);
        serde_json::from_str(&interpolated).unwrap_or_else(|_| a.clone())
    });

    // ─── Domain permission gate (highest priority) ─────────────────────────
    // Close the workflow-path bypass of gap-analysis P1: tool steps used to
    // call `tool.execute()` directly with no permission check, so a DomainPack
    // `deny_by_default` pattern was silently ignored here. When a resolver is
    // wired, a `Deny` short-circuits before any approval/execution; other
    // outcomes fall through to the existing per-step approval flow.
    if let (Some(resolver), Some(tool_name)) = (permission_resolver.as_ref(), step.tool.as_ref()) {
        let check_args = interpolated_tool_args
            .clone()
            .or_else(|| step.tool_args.clone())
            .unwrap_or_else(|| serde_json::json!({}));
        match resolver.resolve(tool_name, &check_args) {
            oneai_core::PermissionAction::Deny { reason } => {
                tracing::warn!(
                    "Workflow step '{}' (tool '{}') denied by domain policy: {}",
                    step_id,
                    tool_name,
                    reason
                );
                return Ok(StepResult {
                    step_id,
                    status: StepStatus::Failed,
                    output: None,
                    error: Some(format!("Denied by domain policy: {}", reason)),
                    retries_used: 0,
                    execution_time_ms: Some(start_time.elapsed().as_millis() as u64),
                });
            }
            oneai_core::PermissionAction::AutoApprove => {
                // Domain has no objection — recorded for audit. The per-step
                // `requires_approval` flag is an orthogonal, author-requested
                // confirmation and is left as-is.
                tracing::info!(
                    "Workflow step '{}' (tool '{}') auto-approved by domain policy",
                    step_id,
                    tool_name
                );
            }
            oneai_core::PermissionAction::RequireConfirmation => {
                // Domain demands confirmation — force the per-step approval gate
                // on even if the step author didn't request it.
                tracing::info!(
                    "Workflow step '{}' (tool '{}') requires confirmation by domain policy",
                    step_id,
                    tool_name
                );
                step.requires_approval = true;
            }
            oneai_core::PermissionAction::UseDefaultPermission { .. } => {
                // No domain rule — fall through to existing approval flow.
            }
        }
    }

    // If this step requires approval, request it
    if step.requires_approval {
        let approval_request = oneai_core::ApprovalRequest {
            tool_name: step.id.clone(),
            args: step.tool_args.clone().unwrap_or(serde_json::json!({})),
            risk_level: oneai_core::RiskLevel::High,
            permission_level: Some(oneai_core::PermissionLevel::Full),
            justification: format!("Workflow step '{}' requires human approval", step.id),
        };

        let response = interaction_gate
            .request(oneai_core::InteractionRequest::ToolApproval {
                approval: approval_request,
            })
            .await?;
        match response {
            oneai_core::InteractionResponse::Abort { reason } => {
                return Ok(StepResult {
                    step_id,
                    status: StepStatus::Failed,
                    output: None,
                    error: Some(format!("Approval denied: {}", reason)),
                    retries_used: 0,
                    execution_time_ms: Some(start_time.elapsed().as_millis() as u64),
                });
            }
            oneai_core::InteractionResponse::Revise { feedback } => {
                // Stateless workflow path can't loop on feedback → treat as denied.
                return Ok(StepResult {
                    step_id,
                    status: StepStatus::Failed,
                    output: None,
                    error: Some(format!("Approval denied: {}", feedback)),
                    retries_used: 0,
                    execution_time_ms: Some(start_time.elapsed().as_millis() as u64),
                });
            }
            oneai_core::InteractionResponse::ProceedWith {
                modification: oneai_core::InteractionModification::ReplaceToolArgs(_args),
            } => {
                // Tool args were rewritten by the approver. (In a real
                // implementation we'd merge _args into tool_args before exec.)
            }
            oneai_core::InteractionResponse::ProceedWith { .. }
            | oneai_core::InteractionResponse::Proceed
            | oneai_core::InteractionResponse::Choose { .. } => {
                // Approved as-is (Choose is PlanDecision-only and doesn't apply).
            }
            // InteractionResponse is #[non_exhaustive]; unknown variants proceed.
            _ => {}
        }
    }

    // Execute with retry loop
    for attempt in 0..=retry_policy.max_retries {
        let exec_result: std::result::Result<oneai_core::ToolOutput, OneAIError> =
            if let Some(tool_name) = &step.tool {
                // Tool-based step — read from RwLock
                let tools_map = tools.read().await;
                let tool = tools_map.get(tool_name);
                if let Some(tool) = tool {
                    // Use interpolated args if available, otherwise use original args
                    let args = match &interpolated_tool_args {
                        Some(a) => a.clone(),
                        None => step.tool_args.clone().unwrap_or(serde_json::json!({})),
                    };
                    let timeout = timeout_secs.unwrap_or(60);

                    let timeout_result = tokio::time::timeout(
                        std::time::Duration::from_secs(timeout),
                        tool.execute(args.clone()),
                    )
                    .await;

                    match timeout_result {
                        Ok(inner_result) => inner_result, // Result<ToolOutput, OneAIError>
                        Err(_) => Err(OneAIError::Timeout(format!(
                            "Step '{}' timed out after {} seconds",
                            step_id, timeout
                        ))),
                    }
                } else {
                    Err(OneAIError::Workflow(format!(
                        "Tool '{}' not found for step '{}'",
                        tool_name, step_id
                    )))
                }
            } else if let Some(provider) = &provider {
                // Prompt-based step with LLM provider — execute actual inference
                let prompt_text = match &interpolated_prompt {
                    Some(p) => p.clone(),
                    None => step.prompt.clone().unwrap_or_default(),
                };
                if prompt_text.is_empty() {
                    Ok(oneai_core::ToolOutput {
                        success: true,
                        content: String::new(),
                        error: None,
                        ..Default::default()
                    })
                } else {
                    // Build a minimal inference request with the interpolated prompt
                    let mut conversation = Conversation::new();
                    conversation.add_message(Message::system(
                        "You are executing a step in a deterministic workflow. Respond concisely.",
                    ));
                    conversation.add_message(Message::user(prompt_text));

                    let request = InferenceRequest {
                        conversation,
                        tools: vec![], // No tools for prompt steps
                        max_tokens: Some(2048),
                        temperature: Some(0.3),
                        top_p: None,
                        stop_sequences: vec![],
                        constrained_output: None,
                        thinking_budget: None,
                        metadata: HashMap::new(),
                    };

                    let response = provider.infer(request).await;
                    match response {
                        Ok(inference_response) => Ok(oneai_core::ToolOutput {
                            success: true,
                            content: inference_response.message.text_content(),
                            error: None,
                            ..Default::default()
                        }),
                        Err(e) => Err(OneAIError::Provider(format!(
                            "LLM inference failed for step '{}': {}",
                            step_id, e
                        ))),
                    }
                }
            } else {
                // No tool defined and no provider — just return interpolated prompt
                let prompt_text = match &interpolated_prompt {
                    Some(p) => p.clone(),
                    None => step.prompt.clone().unwrap_or_default(),
                };
                Ok(oneai_core::ToolOutput {
                    success: true,
                    content: prompt_text,
                    error: None,
                    ..Default::default()
                })
            };

        match exec_result {
            Ok(output) => {
                if output.success {
                    return Ok(StepResult {
                        step_id,
                        status: StepStatus::Completed,
                        output: Some(output.content),
                        error: None,
                        retries_used,
                        execution_time_ms: Some(start_time.elapsed().as_millis() as u64),
                    });
                } else {
                    last_error = Some(
                        output
                            .error
                            .unwrap_or_else(|| "Tool execution failed".to_string()),
                    );
                }
            }
            Err(e) => {
                last_error = Some(format!("Step error: {}", e));
            }
        }

        retries_used = attempt;

        if attempt < retry_policy.max_retries {
            // Wait before retry
            tokio::time::sleep(std::time::Duration::from_secs(
                retry_policy.retry_delay_secs,
            ))
            .await;
        }
    }

    // All retries exhausted
    Ok(StepResult {
        step_id,
        status: StepStatus::Failed,
        output: None,
        error: last_error,
        retries_used,
        execution_time_ms: Some(start_time.elapsed().as_millis() as u64),
    })
}

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

/// Interpolate `{{variable}}` template patterns in a string.
///
/// Replaces `{{key}}` patterns using two sources:
/// 1. `context.step_outputs` — previous step results. Both `{{step_id}}`
///    and `{{step_id_output}}` resolve to the output of step `step_id`.
/// 2. `context.variables` — shared workflow variables.
///
/// **Order**: Longer patterns are replaced first to avoid substring conflicts.
/// `{{step_id_output}}` is replaced before `{{step_id}}`.
///
/// Example:
/// ```
/// let template = "Review {{read_diff_output}} with focus on {{focus_area}}";
/// // If read_diff has output and focus_area = "security":
/// // → "Review <output> with focus on security"
/// ```
pub fn interpolate_template(template: &str, context: &WorkflowContext) -> String {
    let mut result = template.to_string();

    // First pass: replace longer patterns (step_id_output) before shorter ones (step_id)
    // This prevents {{step1_output}} from being partially matched by {{step1}}
    for (step_id, output) in &context.step_outputs {
        // Long form: {{step_id_output}} — must be replaced first
        // Build pattern manually: "{{" + step_id + "_output}}"
        let long_pattern = "{{".to_string() + step_id + "_output}}";
        result = result.replace(&long_pattern, output);
    }
    for (step_id, output) in &context.step_outputs {
        // Short form: {{step_id}} — replaced second
        // Build pattern manually: "{{" + step_id + "}}"
        let short_pattern = "{{".to_string() + step_id + "}}";
        result = result.replace(&short_pattern, output);
    }

    // Replace variable references: {{variable_name}}
    for (key, value) in &context.variables {
        result = result.replace(&format!("{{{{{}}}}}", key), value);
    }

    result
}

#[cfg(test)]
mod interpolation_tests {
    use super::*;

    #[test]
    fn test_interpolate_step_outputs() {
        let mut context = WorkflowContext::from_config(&WorkflowConfig::new("test", vec![]));
        context.set_step_output("step1", "result of step1");
        context.set_step_output("step2", "result of step2");

        // Short form {{step_id}}
        let result = interpolate_template("{{step1}} then {{step2}}", &context);
        assert_eq!(result, "result of step1 then result of step2");

        // Long form {{step_id_output}}
        let result = interpolate_template("{{step1_output}} and {{step2_output}}", &context);
        assert_eq!(result, "result of step1 and result of step2");
    }

    #[test]
    fn test_interpolate_variables() {
        let mut context = WorkflowContext::from_config(&WorkflowConfig::new("test", vec![]));
        context.set_variable("focus_area", "security");
        context.set_variable("language", "Rust");

        let result = interpolate_template("Focus on {{focus_area}} in {{language}}", &context);
        assert_eq!(result, "Focus on security in Rust");
    }

    #[test]
    fn test_interpolate_mixed() {
        let mut context = WorkflowContext::from_config(&WorkflowConfig::new("test", vec![]));
        context.set_step_output("read_diff", "auth.rs changes");
        context.set_variable("focus", "security");

        let result = interpolate_template(
            "Review {{read_diff_output}} with focus on {{focus}}",
            &context,
        );
        assert_eq!(result, "Review auth.rs changes with focus on security");
    }

    #[test]
    fn test_interpolate_no_match() {
        let context = WorkflowContext::from_config(&WorkflowConfig::new("test", vec![]));
        let result = interpolate_template("No variables here {{unknown}}", &context);
        assert_eq!(result, "No variables here {{unknown}}");
    }
}

#[cfg(test)]
mod permission_resolver_tests {
    //! Regression tests for the gap-analysis P1 fix: workflow tool steps used
    //! to call `tool.execute()` directly, bypassing DomainPack
    //! `deny_by_default`. Now a `PermissionResolver` short-circuits a Deny
    //! before dispatch.
    use super::*;
    use crate::compiler::compile;
    use crate::config::StepConfig;
    use oneai_core::error::Result;
    use oneai_core::traits::{InteractionGate, PermissionResolver, Tool};
    use oneai_core::{
        InteractionRequest, InteractionResponse, PermissionAction, RiskLevel, ToolOutput,
    };

    /// A tool that echoes its `value` arg — stands in for any domain tool.
    struct EchoTool;
    #[async_trait::async_trait]
    impl Tool for EchoTool {
        fn name(&self) -> &str {
            "echo"
        }
        fn description(&self) -> &str {
            "echo the value"
        }
        fn parameters_schema(&self) -> serde_json::Value {
            serde_json::json!({"type": "object"})
        }
        fn risk_level(&self) -> RiskLevel {
            RiskLevel::Low
        }
        async fn execute(&self, args: serde_json::Value) -> Result<ToolOutput> {
            Ok(ToolOutput {
                success: true,
                content: args
                    .get("value")
                    .and_then(|v| v.as_str())
                    .unwrap_or("ok")
                    .to_string(),
                error: None,
                ..Default::default()
            })
        }
    }

    /// A no-op gate (Proceed) that disables every point — never reached when
    /// the resolver denies, but required to construct the executor.
    struct NoopGate;
    #[async_trait::async_trait]
    impl InteractionGate for NoopGate {
        async fn request(&self, _req: InteractionRequest) -> Result<InteractionResponse> {
            Ok(InteractionResponse::Proceed)
        }
        fn enabled(&self, _point: oneai_core::InteractionPoint) -> bool {
            false
        }
    }

    /// A resolver that denies a named tool, auto-approves everything else.
    struct DenyResolver {
        denied: String,
    }
    impl PermissionResolver for DenyResolver {
        fn resolve(&self, tool_name: &str, _args: &serde_json::Value) -> PermissionAction {
            if tool_name == self.denied {
                PermissionAction::Deny {
                    reason: "forbidden by domain policy".to_string(),
                }
            } else {
                PermissionAction::AutoApprove
            }
        }
    }

    fn step(id: &str, tool: &str) -> StepConfig {
        StepConfig {
            id: id.to_string(),
            description: String::new(),
            depends_on: vec![],
            tool: Some(tool.to_string()),
            tool_args: Some(serde_json::json!({"value": "ran"})),
            prompt: None,
            requires_approval: false,
            timeout_secs: None,
            retry_policy: None,
            metadata: HashMap::new(),
        }
    }

    #[tokio::test]
    async fn deny_by_default_short_circuits_a_tool_step() {
        // The fix: a domain-deny must stop the step BEFORE tool.execute().
        let config = WorkflowConfig::new("deny-test", vec![step("s1", "echo")]);
        let dag = compile(&config);

        let executor = WorkflowExecutor::new_empty(Arc::new(NoopGate)).with_permission_resolver(
            Arc::new(DenyResolver {
                denied: "echo".to_string(),
            }),
        );
        // Register the tool — the deny check runs before lookup, so even
        // unregistered tools are denied; we register to prove execution would
        // have run without the resolver.
        executor.register_tool(Arc::new(EchoTool)).await;

        let result = executor.execute(&dag, &config).await.unwrap();
        let step_result = result.step_results.get("s1").expect("step result present");
        assert_eq!(step_result.status, StepStatus::Failed);
        let err = step_result.error.as_ref().expect("error present");
        assert!(err.contains("Denied by domain policy"));
        assert!(err.contains("forbidden by domain policy"));
    }

    #[tokio::test]
    async fn auto_approve_allows_a_tool_step_to_run() {
        // Positive control: with the resolver not denying `echo`, the step
        // runs and produces the tool's output.
        let config = WorkflowConfig::new("allow-test", vec![step("s1", "echo")]);
        let dag = compile(&config);

        let executor = WorkflowExecutor::new_empty(Arc::new(NoopGate)).with_permission_resolver(
            Arc::new(DenyResolver {
                denied: "not_echo".to_string(),
            }),
        );
        executor.register_tool(Arc::new(EchoTool)).await;

        let result = executor.execute(&dag, &config).await.unwrap();
        let step_result = result.step_results.get("s1").expect("step result present");
        assert_eq!(step_result.status, StepStatus::Completed);
        assert_eq!(step_result.output.as_deref(), Some("ran"));
    }

    #[tokio::test]
    async fn no_resolver_preserves_legacy_behaviour() {
        // No resolver wired → the step runs exactly as before (the bypass
        // "fix" doesn't break the no-domain-pack case).
        let config = WorkflowConfig::new("legacy-test", vec![step("s1", "echo")]);
        let dag = compile(&config);

        let executor = WorkflowExecutor::new_empty(Arc::new(NoopGate));
        executor.register_tool(Arc::new(EchoTool)).await;

        let result = executor.execute(&dag, &config).await.unwrap();
        let step_result = result.step_results.get("s1").expect("step result present");
        assert_eq!(step_result.status, StepStatus::Completed);
        assert_eq!(step_result.output.as_deref(), Some("ran"));
    }
}