llm-toolkit 0.63.1

A low-level, unopinionated Rust toolkit for the LLM last mile problem.
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
//! StrategyMap - Execution strategy generated from blueprint and available agents.

use serde::{Deserialize, Serialize};

/// Helper function for serde to determine if a bool value is false.
fn is_false(value: &bool) -> bool {
    !*value
}

/// A concrete execution strategy generated by the orchestrator.
///
/// The StrategyMap is created ad-hoc at runtime by analyzing:
/// - The BlueprintWorkflow (what needs to be done)
/// - Available agents (what capabilities exist)
/// - The specific task (the actual user request)
///
/// This allows the orchestrator to adapt to different agent compositions
/// without requiring pre-defined workflows.
///
/// # Backward Compatibility
///
/// This struct supports both the new `elements` format (with control flow)
/// and the legacy `steps` format (simple sequential steps). When deserializing:
/// - If `elements` is present, it's used directly
/// - If `steps` is present (legacy format), each step is wrapped in `StrategyInstruction::Step`
/// - A warning is emitted when loading legacy format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StrategyMap {
    /// The overall goal this strategy aims to achieve.
    pub goal: String,

    /// Ordered sequence of instructions to execute.
    ///
    /// This field supports control flow (loops, early termination) beyond simple steps.
    /// For backward compatibility, this field is automatically populated from `steps`
    /// if `elements` is not present in the JSON.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub elements: Vec<StrategyInstruction>,

    /// Legacy field: Ordered sequence of steps to execute.
    ///
    /// **Deprecated**: Use `elements` instead for new workflows.
    /// This field is kept for backward compatibility. When deserializing legacy JSON,
    /// `steps` will be present, and `migrate_legacy_steps()` should be called to
    /// populate `elements`.
    ///
    /// For new code, use `elements` directly.
    #[serde(default)]
    pub steps: Vec<StrategyStep>,
}

/// A single step in the execution strategy.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StrategyStep {
    /// Unique identifier for this step (for logging and debugging).
    pub step_id: String,

    /// Natural language description of what this step accomplishes.
    pub description: String,

    /// Name of the agent assigned to execute this step.
    pub assigned_agent: String,

    /// Template for the intent to pass to the agent.
    ///
    /// This template can contain placeholders like `{previous_output}`
    /// that will be filled in by the orchestrator at runtime.
    pub intent_template: String,

    /// Description of what output is expected from this step.
    pub expected_output: String,

    /// Whether this step requires validation before proceeding to the next step.
    /// Defaults to false if not specified.
    #[serde(default, skip_serializing_if = "is_false")]
    pub requires_validation: bool,

    /// Optional custom key for accessing this step's output in context.
    ///
    /// When specified, the output will be accessible as:
    /// - `step_{step_id}_output` (automatic default key)
    /// - `{output_key}` (custom alias for easier reference)
    ///
    /// This allows subsequent steps to reference outputs with meaningful names
    /// instead of auto-generated step IDs.
    ///
    /// Example:
    /// ```json
    /// {
    ///   "step_id": "step_1",
    ///   "output_key": "world_concept",
    ///   "assigned_agent": "WorldConceptAgent"
    /// }
    /// ```
    /// Next step can reference: `{{ world_concept.theme }}`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_key: Option<String>,
}

impl StrategyMap {
    /// Creates a new empty StrategyMap with a goal.
    pub fn new(goal: String) -> Self {
        Self {
            goal,
            elements: Vec::new(),
            steps: Vec::new(),
        }
    }

    /// Migrates legacy `steps` to `elements` if needed.
    ///
    /// This method should be called after deserialization to ensure
    /// backward compatibility. If `elements` is empty but `steps` is not,
    /// each step is wrapped in `StrategyInstruction::Step`.
    pub fn migrate_legacy_steps(&mut self) {
        if self.elements.is_empty() && !self.steps.is_empty() {
            tracing::warn!(
                "Loading legacy StrategyMap format with {} steps. Consider migrating to 'elements' format.",
                self.steps.len()
            );

            self.elements = self
                .steps
                .iter()
                .map(|step| StrategyInstruction::Step(step.clone()))
                .collect();
        }

        // Keep legacy `steps` vector in sync with top-level Step instructions.
        self.steps = self
            .elements
            .iter()
            .filter_map(|instruction| match instruction {
                StrategyInstruction::Step(step) => Some(step.clone()),
                _ => None,
            })
            .collect();
    }

    /// Adds a step to this strategy (wraps in StrategyInstruction::Step).
    pub fn add_step(&mut self, step: StrategyStep) {
        self.add_instruction(StrategyInstruction::Step(step));
    }

    /// Adds an instruction to this strategy.
    pub fn add_instruction(&mut self, instruction: StrategyInstruction) {
        if let StrategyInstruction::Step(step) = &instruction {
            self.steps.push(step.clone());
        }
        self.elements.push(instruction);
    }

    /// Returns the number of instructions in this strategy.
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Checks if this strategy has no instructions.
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Returns an instruction by index.
    pub fn get_instruction(&self, index: usize) -> Option<&StrategyInstruction> {
        self.elements.get(index)
    }

    /// Returns a mutable reference to an instruction by index.
    pub fn get_instruction_mut(&mut self, index: usize) -> Option<&mut StrategyInstruction> {
        self.elements.get_mut(index)
    }

    /// Returns a step by index (legacy method for backward compatibility).
    ///
    /// **Note**: This only works if the instruction at the given index is a `Step`.
    /// Returns `None` if the instruction is a `Loop` or `Terminate`.
    pub fn get_step(&self, index: usize) -> Option<&StrategyStep> {
        match self.elements.get(index) {
            Some(StrategyInstruction::Step(step)) => Some(step),
            _ => None,
        }
    }

    /// Returns a mutable reference to a step by index (legacy method).
    ///
    /// **Note**: This only works if the instruction at the given index is a `Step`.
    /// Returns `None` if the instruction is a `Loop` or `Terminate`.
    pub fn get_step_mut(&mut self, index: usize) -> Option<&mut StrategyStep> {
        match self.elements.get_mut(index) {
            Some(StrategyInstruction::Step(step)) => Some(step),
            _ => None,
        }
    }

    /// Returns all steps in this strategy (legacy method).
    ///
    /// **Note**: This only returns instructions that are `Step` variants.
    /// `Loop` and `Terminate` instructions are excluded.
    pub fn steps(&self) -> Vec<&StrategyStep> {
        self.elements
            .iter()
            .filter_map(|instruction| match instruction {
                StrategyInstruction::Step(step) => Some(step),
                _ => None,
            })
            .collect()
    }

    /// Validates the entire strategy map.
    ///
    /// This checks:
    /// - All `Loop` instructions do not contain nested loops
    ///
    /// # Errors
    ///
    /// Returns an error if any validation constraint is violated.
    pub fn validate(&self) -> Result<(), &'static str> {
        for instruction in &self.elements {
            if let StrategyInstruction::Loop(loop_block) = instruction {
                loop_block.validate()?;
            }
        }
        Ok(())
    }
}

impl StrategyStep {
    /// Creates a new StrategyStep.
    pub fn new(
        step_id: String,
        description: String,
        assigned_agent: String,
        intent_template: String,
        expected_output: String,
    ) -> Self {
        Self {
            step_id,
            description,
            assigned_agent,
            intent_template,
            expected_output,
            requires_validation: false,
            output_key: None,
        }
    }
}

/// A single instruction in the execution strategy.
///
/// This enum allows for control flow beyond simple sequential steps,
/// supporting loops and early termination while maintaining backward compatibility.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type")] // Critical for backward-compatible and extensible deserialization
pub enum StrategyInstruction {
    /// A standard execution step.
    #[serde(rename = "step")]
    Step(StrategyStep),

    /// A loop block that can iterate until a condition is met.
    #[serde(rename = "loop")]
    Loop(LoopBlock),

    /// An early termination instruction.
    #[serde(rename = "terminate")]
    Terminate(TerminateInstruction),
}

/// The type of loop to execute.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LoopType {
    /// Loop while a condition is true.
    While,

    /// Loop over each item in a collection.
    ForEach,

    /// Loop until convergence (e.g., iterative refinement).
    UntilConvergence,
}

/// Defines how to aggregate outputs from loop iterations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LoopAggregation {
    /// The aggregation mode.
    #[serde(rename = "mode")]
    pub mode: AggregationMode,

    /// The context key where the aggregated result will be stored.
    pub output_key: String,
}

/// The mode for aggregating loop iteration outputs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AggregationMode {
    /// Keep only the last successful iteration's output.
    LastSuccess,

    /// Collect all iteration outputs in an array.
    CollectAll,

    /// Keep the first successful iteration's output.
    FirstSuccess,
}

/// A loop block that can contain nested instructions.
///
/// **Important**: Nested loops are not supported. The body can only contain
/// `Step` and `Terminate` instructions, not other `Loop` instructions.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LoopBlock {
    /// Unique identifier for this loop (for namespacing context variables).
    pub loop_id: String,

    /// Human-readable description of what this loop does.
    ///
    /// Optional for hand-written JSON. LLM-generated strategies should include this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// The type of loop (semantic meaning).
    ///
    /// Optional. Defaults to `While` if not specified. This field is primarily
    /// for documentation and LLM understanding; it doesn't affect execution logic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub loop_type: Option<LoopType>,

    /// Maximum iterations (mandatory safeguard against infinite loops).
    pub max_iterations: usize,

    /// Template to evaluate for loop continuation.
    /// If it renders to "true", the loop continues.
    /// This is evaluated against the current context using MiniJinja.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition_template: Option<String>,

    /// The instructions to execute within each loop iteration.
    ///
    /// **Constraint**: Cannot contain nested `Loop` instructions.
    /// Use `validate()` to check this constraint.
    pub body: Vec<StrategyInstruction>,

    /// Optional aggregation strategy for loop outputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aggregation: Option<LoopAggregation>,
}

impl LoopBlock {
    /// Validates that the loop body does not contain nested loops.
    ///
    /// # Errors
    ///
    /// Returns an error if any instruction in the body is a `Loop`.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let loop_block = LoopBlock { /* ... */ };
    /// loop_block.validate()?;
    /// ```
    pub fn validate(&self) -> Result<(), &'static str> {
        for instruction in &self.body {
            if matches!(instruction, StrategyInstruction::Loop(_)) {
                return Err(
                    "Nested loops are not supported. Loop body cannot contain other Loop instructions.",
                );
            }
        }
        Ok(())
    }
}

/// An instruction to terminate the workflow early.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TerminateInstruction {
    /// Unique identifier for this termination point.
    pub terminate_id: String,

    /// Human-readable description of why we're terminating.
    ///
    /// Optional for hand-written JSON. LLM-generated strategies should include this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Template to evaluate for termination decision.
    /// If it renders to "true", the workflow terminates.
    /// This is evaluated against the current context using MiniJinja.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition_template: Option<String>,

    /// Optional template for the final output message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub final_output_template: Option<String>,
}

/// The type of redesign strategy to apply when a step fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RedesignStrategy {
    /// Simply retry the same step (for transient errors).
    Retry,

    /// Redesign from the failed step onwards (tactical).
    /// The actual redesigned steps will be generated and applied separately.
    TacticalRedesign,

    /// Regenerate the entire strategy from scratch.
    FullRegenerate,
}

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

    #[test]
    fn test_strategy_map_creation() {
        let mut strategy = StrategyMap::new("Complete the task".to_string());
        assert_eq!(strategy.goal, "Complete the task");
        assert!(strategy.is_empty());

        let step = StrategyStep::new(
            "step_1".to_string(),
            "Do something".to_string(),
            "AgentA".to_string(),
            "Do {task}".to_string(),
            "Result".to_string(),
        );

        strategy.add_step(step);
        assert_eq!(strategy.len(), 1);
        assert!(!strategy.is_empty());
    }

    #[test]
    fn test_add_step_retains_legacy_steps_vector() {
        let mut strategy = StrategyMap::new("Ensure steps tracked".to_string());
        strategy.add_step(StrategyStep::new(
            "step_1".to_string(),
            "Do something".to_string(),
            "AgentA".to_string(),
            "Perform task".to_string(),
            "Result".to_string(),
        ));

        assert_eq!(strategy.elements.len(), 1);
        assert_eq!(strategy.steps.len(), 1);
    }

    #[test]
    fn test_strategy_step_access() {
        let mut strategy = StrategyMap::new("Goal".to_string());

        let step = StrategyStep::new(
            "s1".to_string(),
            "Description".to_string(),
            "Agent".to_string(),
            "Intent".to_string(),
            "Output".to_string(),
        );

        strategy.add_step(step);

        assert!(strategy.get_step(0).is_some());
        assert!(strategy.get_step(1).is_none());

        if let Some(step_mut) = strategy.get_step_mut(0) {
            step_mut.description = "Modified".to_string();
        }

        assert_eq!(strategy.get_step(0).unwrap().description, "Modified");
    }

    #[test]
    fn test_strategy_step_with_output_key() {
        let mut step = StrategyStep::new(
            "step_1".to_string(),
            "Create world concept".to_string(),
            "WorldConceptAgent".to_string(),
            "Create a concept for {{ user_request }}".to_string(),
            "World concept data".to_string(),
        );

        // Initially None
        assert!(step.output_key.is_none());

        // Set output_key
        step.output_key = Some("world_concept".to_string());
        assert_eq!(step.output_key, Some("world_concept".to_string()));

        // Verify serialization includes output_key
        let json = serde_json::to_string(&step).unwrap();
        assert!(json.contains("world_concept"));
    }

    #[test]
    fn test_strategy_step_output_key_serialization() {
        // Test that output_key is properly serialized and deserialized
        let mut step = StrategyStep::new(
            "step_1".to_string(),
            "Test step".to_string(),
            "TestAgent".to_string(),
            "Do something".to_string(),
            "Result".to_string(),
        );
        step.output_key = Some("test_output".to_string());

        let json = serde_json::to_string(&step).unwrap();
        let deserialized: StrategyStep = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.output_key, Some("test_output".to_string()));
        assert_eq!(deserialized.step_id, "step_1");
    }

    #[test]
    fn test_strategy_step_without_output_key_serialization() {
        // Test that output_key is omitted from JSON when None (skip_serializing_if)
        let step = StrategyStep::new(
            "step_1".to_string(),
            "Test step".to_string(),
            "TestAgent".to_string(),
            "Do something".to_string(),
            "Result".to_string(),
        );

        let json = serde_json::to_string(&step).unwrap();
        // output_key should not appear in JSON when None
        assert!(!json.contains("output_key"));
    }

    #[test]
    fn test_strategy_instruction_step_serialization() {
        let step = StrategyStep::new(
            "step_1".to_string(),
            "Test step".to_string(),
            "TestAgent".to_string(),
            "Do something".to_string(),
            "Result".to_string(),
        );
        let instruction = StrategyInstruction::Step(step);

        // Serialize
        let json = serde_json::to_string_pretty(&instruction).unwrap();
        assert!(json.contains(r#""type": "step""#));
        assert!(json.contains("step_1"));

        // Deserialize
        let deserialized: StrategyInstruction = serde_json::from_str(&json).unwrap();
        match deserialized {
            StrategyInstruction::Step(s) => {
                assert_eq!(s.step_id, "step_1");
            }
            _ => panic!("Expected Step variant"),
        }
    }

    #[test]
    fn test_loop_block_serialization() {
        let loop_block = LoopBlock {
            loop_id: "test_loop".to_string(),
            description: Some("Test loop".to_string()),
            loop_type: Some(LoopType::UntilConvergence),
            max_iterations: 5,
            condition_template: Some("{{ approved == false }}".to_string()),
            body: vec![StrategyInstruction::Step(StrategyStep::new(
                "inner_step".to_string(),
                "Inner step".to_string(),
                "TestAgent".to_string(),
                "Do something".to_string(),
                "Result".to_string(),
            ))],
            aggregation: Some(LoopAggregation {
                mode: AggregationMode::LastSuccess,
                output_key: "final_result".to_string(),
            }),
        };

        let instruction = StrategyInstruction::Loop(loop_block);

        // Serialize
        let json = serde_json::to_string_pretty(&instruction).unwrap();
        assert!(json.contains(r#""type": "loop""#));
        assert!(json.contains("test_loop"));
        assert!(json.contains("until_convergence"));
        assert!(json.contains("approved == false"));

        // Deserialize
        let deserialized: StrategyInstruction = serde_json::from_str(&json).unwrap();
        match deserialized {
            StrategyInstruction::Loop(l) => {
                assert_eq!(l.loop_id, "test_loop");
                assert_eq!(l.max_iterations, 5);
                assert_eq!(l.body.len(), 1);
            }
            _ => panic!("Expected Loop variant"),
        }
    }

    #[test]
    fn test_terminate_instruction_serialization() {
        let terminate = TerminateInstruction {
            terminate_id: "early_exit".to_string(),
            description: Some("Exit early on approval".to_string()),
            condition_template: Some("{{ approved == true }}".to_string()),
            final_output_template: Some("Completed successfully".to_string()),
        };

        let instruction = StrategyInstruction::Terminate(terminate);

        // Serialize
        let json = serde_json::to_string_pretty(&instruction).unwrap();
        assert!(json.contains(r#""type": "terminate""#));
        assert!(json.contains("early_exit"));
        assert!(json.contains("approved == true"));

        // Deserialize
        let deserialized: StrategyInstruction = serde_json::from_str(&json).unwrap();
        match deserialized {
            StrategyInstruction::Terminate(t) => {
                assert_eq!(t.terminate_id, "early_exit");
                assert!(t.condition_template.is_some());
            }
            _ => panic!("Expected Terminate variant"),
        }
    }

    #[test]
    fn test_strategy_map_with_elements_serialization() {
        let mut strategy = StrategyMap::new("Test goal".to_string());
        strategy.add_step(StrategyStep::new(
            "step_1".to_string(),
            "First step".to_string(),
            "Agent1".to_string(),
            "Do task".to_string(),
            "Result".to_string(),
        ));

        // Serialize
        let json = serde_json::to_string_pretty(&strategy).unwrap();
        assert!(json.contains("Test goal"));
        assert!(json.contains("elements"));
        assert!(json.contains("step_1"));

        // Deserialize
        let deserialized: StrategyMap = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.goal, "Test goal");
        assert_eq!(deserialized.elements.len(), 1);
    }

    #[test]
    fn test_legacy_steps_format_deserialization() {
        // Simulate legacy JSON format with "steps" instead of "elements"
        let legacy_json = r#"{
            "goal": "Legacy workflow",
            "steps": [
                {
                    "step_id": "step_1",
                    "description": "Do something",
                    "assigned_agent": "TestAgent",
                    "intent_template": "Execute task",
                    "expected_output": "Result"
                }
            ]
        }"#;

        let mut strategy: StrategyMap = serde_json::from_str(legacy_json).unwrap();
        assert_eq!(strategy.goal, "Legacy workflow");
        assert_eq!(strategy.steps.len(), 1);
        assert_eq!(strategy.elements.len(), 0); // Not migrated yet

        // Migrate
        strategy.migrate_legacy_steps();
        assert_eq!(strategy.elements.len(), 1);
        assert_eq!(strategy.steps.len(), 1); // Legacy steps kept in sync

        match &strategy.elements[0] {
            StrategyInstruction::Step(s) => {
                assert_eq!(s.step_id, "step_1");
            }
            _ => panic!("Expected Step variant"),
        }
    }

    #[test]
    fn test_round_trip_with_mixed_instructions() {
        let mut strategy = StrategyMap::new("Complex workflow".to_string());

        // Add a regular step
        strategy.add_step(StrategyStep::new(
            "step_1".to_string(),
            "Prepare".to_string(),
            "Agent1".to_string(),
            "Setup".to_string(),
            "Config".to_string(),
        ));

        // Add a loop
        strategy.add_instruction(StrategyInstruction::Loop(LoopBlock {
            loop_id: "refine_loop".to_string(),
            description: Some("Refine output".to_string()),
            loop_type: Some(LoopType::UntilConvergence),
            max_iterations: 3,
            condition_template: Some("{{ needs_refinement }}".to_string()),
            body: vec![StrategyInstruction::Step(StrategyStep::new(
                "refine_step".to_string(),
                "Refine".to_string(),
                "Agent2".to_string(),
                "Improve".to_string(),
                "Better result".to_string(),
            ))],
            aggregation: None,
        }));

        // Add early termination
        strategy.add_instruction(StrategyInstruction::Terminate(TerminateInstruction {
            terminate_id: "success_exit".to_string(),
            description: Some("Exit on success".to_string()),
            condition_template: Some("{{ success }}".to_string()),
            final_output_template: None,
        }));

        // Round-trip: Serialize and deserialize
        let json = serde_json::to_string_pretty(&strategy).unwrap();
        let deserialized: StrategyMap = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.goal, "Complex workflow");
        assert_eq!(deserialized.elements.len(), 3);

        // Verify structure
        assert!(matches!(
            &deserialized.elements[0],
            StrategyInstruction::Step(_)
        ));
        assert!(matches!(
            &deserialized.elements[1],
            StrategyInstruction::Loop(_)
        ));
        assert!(matches!(
            &deserialized.elements[2],
            StrategyInstruction::Terminate(_)
        ));
    }

    #[test]
    fn test_loop_block_validation_success() {
        // Valid loop with only Steps and Terminate in body
        let loop_block = LoopBlock {
            loop_id: "valid_loop".to_string(),
            description: Some("Valid loop".to_string()),
            loop_type: Some(LoopType::While),
            max_iterations: 5,
            condition_template: Some("{{ continue }}".to_string()),
            body: vec![
                StrategyInstruction::Step(StrategyStep::new(
                    "step_1".to_string(),
                    "Step".to_string(),
                    "Agent".to_string(),
                    "Do work".to_string(),
                    "Result".to_string(),
                )),
                StrategyInstruction::Terminate(TerminateInstruction {
                    terminate_id: "exit".to_string(),
                    description: Some("Exit".to_string()),
                    condition_template: Some("{{ done }}".to_string()),
                    final_output_template: None,
                }),
            ],
            aggregation: None,
        };

        assert!(loop_block.validate().is_ok());
    }

    #[test]
    fn test_loop_block_validation_nested_loop_fails() {
        // Invalid loop with nested loop in body
        let nested_loop_block = LoopBlock {
            loop_id: "nested_loop".to_string(),
            description: Some("Nested loop".to_string()),
            loop_type: Some(LoopType::While),
            max_iterations: 3,
            condition_template: Some("{{ inner }}".to_string()),
            body: vec![StrategyInstruction::Step(StrategyStep::new(
                "inner_step".to_string(),
                "Inner".to_string(),
                "Agent".to_string(),
                "Work".to_string(),
                "Result".to_string(),
            ))],
            aggregation: None,
        };

        let outer_loop_block = LoopBlock {
            loop_id: "outer_loop".to_string(),
            description: Some("Outer loop".to_string()),
            loop_type: Some(LoopType::UntilConvergence),
            max_iterations: 5,
            condition_template: Some("{{ outer }}".to_string()),
            body: vec![
                StrategyInstruction::Step(StrategyStep::new(
                    "outer_step".to_string(),
                    "Outer".to_string(),
                    "Agent".to_string(),
                    "Work".to_string(),
                    "Result".to_string(),
                )),
                StrategyInstruction::Loop(nested_loop_block),
            ],
            aggregation: None,
        };

        let result = outer_loop_block.validate();
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            "Nested loops are not supported. Loop body cannot contain other Loop instructions."
        );
    }

    #[test]
    fn test_strategy_map_validation_success() {
        let mut strategy = StrategyMap::new("Valid strategy".to_string());

        strategy.add_step(StrategyStep::new(
            "step_1".to_string(),
            "Step".to_string(),
            "Agent".to_string(),
            "Work".to_string(),
            "Result".to_string(),
        ));

        strategy.add_instruction(StrategyInstruction::Loop(LoopBlock {
            loop_id: "loop_1".to_string(),
            description: Some("Loop".to_string()),
            loop_type: Some(LoopType::While),
            max_iterations: 3,
            condition_template: Some("{{ continue }}".to_string()),
            body: vec![StrategyInstruction::Step(StrategyStep::new(
                "loop_step".to_string(),
                "Loop step".to_string(),
                "Agent".to_string(),
                "Loop work".to_string(),
                "Loop result".to_string(),
            ))],
            aggregation: None,
        }));

        assert!(strategy.validate().is_ok());
    }

    #[test]
    fn test_strategy_map_validation_nested_loop_fails() {
        let mut strategy = StrategyMap::new("Invalid strategy".to_string());

        // Create a loop with nested loop
        let nested_loop = LoopBlock {
            loop_id: "nested".to_string(),
            description: Some("Nested".to_string()),
            loop_type: Some(LoopType::While),
            max_iterations: 2,
            condition_template: None,
            body: vec![StrategyInstruction::Step(StrategyStep::new(
                "inner".to_string(),
                "Inner".to_string(),
                "Agent".to_string(),
                "Work".to_string(),
                "Result".to_string(),
            ))],
            aggregation: None,
        };

        strategy.add_instruction(StrategyInstruction::Loop(LoopBlock {
            loop_id: "outer".to_string(),
            description: Some("Outer".to_string()),
            loop_type: Some(LoopType::UntilConvergence),
            max_iterations: 3,
            condition_template: None,
            body: vec![StrategyInstruction::Loop(nested_loop)],
            aggregation: None,
        }));

        let result = strategy.validate();
        assert!(result.is_err());
    }
}