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
//! Dialogue context and talk style definitions.
//!
//! This module provides a flexible context system for dialogues, allowing users
//! to customize the behavior and tone of conversations.

use crate::agent::Capability;
use crate::prompt::ToPrompt;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// The overall context for a dialogue, including talk style and additional context.
///
/// This struct is generic over:
/// - `T`: The talk style type (defaults to `TalkStyle`)
/// - `S`: The additional context item type (defaults to `String`)
///
/// Both types must implement `ToPrompt` to be converted into prompts.
///
/// # Examples
///
/// ```rust,ignore
/// // Using default types
/// let context = DialogueContext::default()
///     .with_talk_style(TalkStyle::Brainstorm)
///     .with_environment("ClaudeCode environment");
///
/// // Using custom types
/// #[derive(ToPrompt)]
/// struct ProjectInfo {
///     language: String,
///     focus: String,
/// }
///
/// let context = DialogueContext::default()
///     .with_additional_context(ProjectInfo {
///         language: "Rust".to_string(),
///         focus: "Performance".to_string(),
///     });
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DialogueContext<T = TalkStyle, S = String>
where
    T: ToPrompt + Clone,
    S: ToPrompt + Clone,
{
    /// The conversation style/mode (Brainstorm, Debate, etc.)
    pub talk_style: Option<T>,

    /// Environment information (e.g., "ClaudeCode environment", "Production system")
    pub environment: Option<String>,

    /// Additional context items (can be structured data that implements ToPrompt)
    pub additional_context: Vec<S>,

    /// Dynamic policy: maps participant name to allowed capabilities.
    ///
    /// This enables top-down, session-specific capability restrictions:
    /// - If `None`, all declared capabilities from Persona are allowed
    /// - If `Some`, only the capabilities listed here are permitted for each participant
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use llm_toolkit::agent::dialogue::DialogueContext;
    /// use llm_toolkit::agent::Capability;
    ///
    /// let context = DialogueContext::default()
    ///     .with_policy("FileAgent", vec![
    ///         Capability::new("file:read"), // Allow read
    ///         // file:write is NOT allowed in this session
    ///     ]);
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<HashMap<String, Vec<Capability>>>,
}

impl<T, S> Default for DialogueContext<T, S>
where
    T: ToPrompt + Clone,
    S: ToPrompt + Clone,
{
    fn default() -> Self {
        Self {
            talk_style: None,
            environment: None,
            additional_context: Vec::new(),
            policy: None,
        }
    }
}

impl<T, S> DialogueContext<T, S>
where
    T: ToPrompt + Clone,
    S: ToPrompt + Clone,
{
    /// Creates a new empty DialogueContext.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the talk style.
    pub fn with_talk_style(mut self, style: T) -> Self {
        self.talk_style = Some(style);
        self
    }

    /// Sets the environment information.
    pub fn with_environment(mut self, env: impl Into<String>) -> Self {
        self.environment = Some(env.into());
        self
    }

    /// Adds an additional context item.
    pub fn with_additional_context(mut self, context: S) -> Self {
        self.additional_context.push(context);
        self
    }

    /// Adds multiple additional context items.
    pub fn with_additional_contexts(mut self, contexts: Vec<S>) -> Self {
        self.additional_context.extend(contexts);
        self
    }

    /// Sets the policy (allowed capabilities) for a specific participant.
    ///
    /// This enables dynamic, session-specific restriction of what a participant
    /// can do, regardless of what capabilities their Persona declares.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use llm_toolkit::agent::dialogue::DialogueContext;
    /// use llm_toolkit::agent::Capability;
    ///
    /// let context = DialogueContext::default()
    ///     .with_policy("FileAgent", vec![Capability::new("file:read")])
    ///     .with_policy("APIAgent", vec![Capability::new("api:weather")]);
    /// ```
    pub fn with_policy(mut self, participant: impl Into<String>, allowed: Vec<Capability>) -> Self {
        self.policy
            .get_or_insert_with(HashMap::new)
            .insert(participant.into(), allowed);
        self
    }
}

impl<T, S> ToPrompt for DialogueContext<T, S>
where
    T: ToPrompt + Clone,
    S: ToPrompt + Clone,
{
    fn to_prompt(&self) -> String {
        let mut prompt = String::new();

        // Only add section if there's content
        let has_content = self.environment.is_some()
            || self.talk_style.is_some()
            || !self.additional_context.is_empty();

        if !has_content {
            return prompt;
        }

        prompt.push_str("# Dialogue Context\n\n");

        // Environment
        if let Some(env) = &self.environment {
            prompt.push_str(&format!("## Environment\n{}\n\n", env));
        }

        // Talk Style
        if let Some(style) = &self.talk_style {
            prompt.push_str(&style.to_prompt());
            prompt.push_str("\n\n");
        }

        // Additional Context
        if !self.additional_context.is_empty() {
            prompt.push_str("## Additional Context\n");
            for ctx in &self.additional_context {
                prompt.push_str(&ctx.to_prompt());
                prompt.push_str("\n\n");
            }
        }

        prompt
    }
}

/// Custom talk style template for user-defined dialogue styles.
///
/// This struct allows users to define custom talk styles by providing
/// structured data instead of implementing `ToPrompt` manually.
///
/// # Example
///
/// ```rust
/// use llm_toolkit::agent::dialogue::{TalkStyle, TalkStyleTemplate};
///
/// let custom = TalkStyleTemplate::new("Code Review")
///     .with_description("A focused code review session for Rust projects.")
///     .with_guideline("Focus on memory safety and ownership patterns")
///     .with_guideline("Check for proper error handling with Result types")
///     .with_guideline("Verify that unsafe blocks are justified and documented")
///     .with_expected_behavior("Provide specific line references")
///     .with_expected_behavior("Suggest idiomatic Rust alternatives");
///
/// let style = TalkStyle::Template(custom);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TalkStyleTemplate {
    /// The name of the talk style (e.g., "Code Review", "Architecture Discussion")
    pub name: String,

    /// A brief description of the session's purpose
    pub description: String,

    /// Guidelines for participants to follow
    pub guidelines: Vec<String>,

    /// Expected behaviors during the session
    pub expected_behaviors: Vec<String>,
}

impl TalkStyleTemplate {
    /// Creates a new TalkStyleTemplate with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: String::new(),
            guidelines: Vec::new(),
            expected_behaviors: Vec::new(),
        }
    }

    /// Sets the description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Adds a guideline.
    pub fn with_guideline(mut self, guideline: impl Into<String>) -> Self {
        self.guidelines.push(guideline.into());
        self
    }

    /// Adds multiple guidelines.
    pub fn with_guidelines(
        mut self,
        guidelines: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.guidelines
            .extend(guidelines.into_iter().map(Into::into));
        self
    }

    /// Adds an expected behavior.
    pub fn with_expected_behavior(mut self, behavior: impl Into<String>) -> Self {
        self.expected_behaviors.push(behavior.into());
        self
    }

    /// Adds multiple expected behaviors.
    pub fn with_expected_behaviors(
        mut self,
        behaviors: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.expected_behaviors
            .extend(behaviors.into_iter().map(Into::into));
        self
    }
}

impl ToPrompt for TalkStyleTemplate {
    fn to_prompt(&self) -> String {
        let mut prompt = format!("## Dialogue Style: {}\n\n", self.name);

        if !self.description.is_empty() {
            prompt.push_str(&self.description);
            prompt.push_str("\n\n");
        }

        if !self.guidelines.is_empty() {
            prompt.push_str("## Guidelines\n");
            for guideline in &self.guidelines {
                prompt.push_str(&format!("- {}\n", guideline));
            }
            prompt.push('\n');
        }

        if !self.expected_behaviors.is_empty() {
            prompt.push_str("## Expected Behavior\n");
            for behavior in &self.expected_behaviors {
                prompt.push_str(&format!("- {}\n", behavior));
            }
        }

        prompt.trim_end().to_string()
    }
}

/// Default talk styles for dialogues.
///
/// These represent common conversation modes with predefined characteristics.
/// Users can also create custom talk styles using `TalkStyle::Template` with
/// a `TalkStyleTemplate`, or by implementing `ToPrompt` on their own types.
///
/// # Example: Using a predefined style
///
/// ```rust
/// use llm_toolkit::agent::dialogue::{DialogueContext, TalkStyle};
///
/// let context: DialogueContext<TalkStyle, &str> = DialogueContext::default()
///     .with_talk_style(TalkStyle::Brainstorm);
/// ```
///
/// # Example: Using a custom template
///
/// ```rust
/// use llm_toolkit::agent::dialogue::{TalkStyle, TalkStyleTemplate};
///
/// let custom = TalkStyleTemplate::new("Security Audit")
///     .with_description("Review code for security vulnerabilities.")
///     .with_guideline("Check for injection vulnerabilities")
///     .with_guideline("Verify input validation");
///
/// let style = TalkStyle::Template(custom);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TalkStyle {
    /// Brainstorming session - creative, exploratory, building on ideas.
    Brainstorm,

    /// Casual conversation - relaxed, friendly, conversational.
    Casual,

    /// Decision-making discussion - analytical, weighing options, reaching conclusion.
    DecisionMaking,

    /// Debate - challenging ideas, diverse perspectives, constructive argument.
    Debate,

    /// Problem-solving session - systematic, solution-focused, practical.
    ProblemSolving,

    /// Review/Critique - constructive feedback, detailed analysis.
    Review,

    /// Planning session - structured, forward-thinking, action-oriented.
    Planning,

    /// Research session - fact-based, source-aware, expertise-driven investigation.
    Research,

    /// Custom template-based talk style.
    ///
    /// Use this variant when predefined styles don't fit your needs.
    /// Provide a `TalkStyleTemplate` with custom name, description,
    /// guidelines, and expected behaviors.
    Template(TalkStyleTemplate),
}

impl ToPrompt for TalkStyle {
    fn to_prompt(&self) -> String {
        match self {
            Self::Brainstorm => r#"## Dialogue Style: Brainstorming Session

This is a creative brainstorming session. Your goal is to generate and explore ideas freely.

## Guidelines
- **Encourage wild ideas**: No idea is too ambitious or unconventional
- **Build on others**: Expand and combine suggestions from other participants
- **Defer judgment**: Focus on generating ideas first, evaluating later
- **Quantity matters**: More ideas lead to better final solutions
- **Stay positive**: Use "Yes, and..." instead of "No, but..."

## Expected Behavior
- Be creative and exploratory
- Suggest multiple alternatives
- Connect ideas in novel ways
- Avoid criticizing or dismissing ideas prematurely"#
                .to_string(),

            Self::Casual => r#"## Dialogue Style: Casual Conversation

This is a relaxed, friendly conversation. Keep it natural and engaging.

## Guidelines
- **Be conversational**: Use a natural, flowing style
- **Stay friendly**: Maintain an approachable, warm tone
- **Share perspectives**: Offer your viewpoint and invite others'
- **Ask questions**: Show genuine interest in the discussion
- **Keep it light**: Balance depth with accessibility

## Expected Behavior
- Respond naturally without being overly formal
- Share relevant thoughts and experiences
- Build rapport through friendly dialogue
- Keep the conversation engaging and enjoyable"#
                .to_string(),

            Self::DecisionMaking => r#"## Dialogue Style: Decision-Making Discussion

This is a structured decision-making session. Focus on analysis and reaching clear conclusions.

## Guidelines
- **Analyze systematically**: Break down options and their implications
- **Consider trade-offs**: Weigh pros and cons of each alternative
- **Use evidence**: Base recommendations on facts and reasoning
- **Be objective**: Set aside biases to evaluate fairly
- **Aim for clarity**: Work toward a clear decision

## Expected Behavior
- Present options clearly with supporting rationale
- Highlight key considerations and constraints
- Compare alternatives objectively
- Recommend a path forward with justification
- Document the decision rationale"#
                .to_string(),

            Self::Debate => r#"## Dialogue Style: Constructive Debate

This is a respectful debate session. Challenge ideas and present diverse perspectives.

## Guidelines
- **Challenge constructively**: Question assumptions and test ideas
- **Present alternatives**: Offer different viewpoints and approaches
- **Use evidence**: Support arguments with facts and reasoning
- **Engage respectfully**: Disagree without being disagreeable
- **Seek truth**: Use dialectic to strengthen understanding

## Expected Behavior
- Present well-reasoned counterarguments
- Identify weaknesses in proposals
- Defend positions with evidence
- Acknowledge strong points from others
- Work toward robust conclusions through discussion"#
                .to_string(),

            Self::ProblemSolving => r#"## Dialogue Style: Problem-Solving Session

This is a focused problem-solving session. Be systematic and solution-oriented.

## Guidelines
- **Define clearly**: Start with a clear problem statement
- **Break it down**: Decompose complex issues into manageable parts
- **Generate solutions**: Propose practical, actionable approaches
- **Evaluate feasibility**: Consider constraints and resources
- **Focus on action**: Work toward implementable outcomes

## Expected Behavior
- Analyze the problem structure
- Suggest concrete solutions
- Assess practical implications
- Identify next steps
- Maintain focus on solving the issue"#
                .to_string(),

            Self::Review => r#"## Dialogue Style: Review & Critique

This is a constructive review session. Provide detailed, actionable feedback.

## Guidelines
- **Be specific**: Point to particular aspects and examples
- **Balance feedback**: Acknowledge strengths and identify improvements
- **Explain reasoning**: Clarify why something works or needs change
- **Suggest improvements**: Offer concrete recommendations
- **Stay constructive**: Frame feedback helpfully

## Expected Behavior
- Analyze work carefully and thoroughly
- Provide clear, specific observations
- Support feedback with rationale
- Recommend actionable improvements
- Maintain a constructive, helpful tone"#
                .to_string(),

            Self::Planning => r#"## Dialogue Style: Planning Session

This is a structured planning session. Think ahead and create actionable plans.

## Guidelines
- **Think forward**: Anticipate needs, challenges, and opportunities
- **Break down goals**: Decompose objectives into concrete steps
- **Consider resources**: Account for time, people, and dependencies
- **Identify risks**: Anticipate potential obstacles
- **Create action items**: Generate clear, assignable tasks

## Expected Behavior
- Propose structured plans with clear steps
- Consider timeline and sequencing
- Identify dependencies and constraints
- Suggest risk mitigation strategies
- Focus on practical, executable planning"#
                .to_string(),

            Self::Research => r#"## Dialogue Style: Research Session

This is a fact-based research session. Focus on gathering reliable information from trusted sources.

## Guidelines
- **Prioritize facts**: Base all claims on verifiable evidence
- **Use trusted sources**: Select sources appropriate to your expertise
- **Evaluate credibility**: Assess source reliability before citing
- **Be transparent**: Distinguish facts from interpretation
- **Acknowledge uncertainty**: State when information is incomplete

## Source Selection by Expertise
Each participant selects sources aligned with their domain:
- User perspective → Real user feedback, social media, reviews
- Technical domain → Documentation, specifications, benchmarks
- Scientific domain → Peer-reviewed papers, journals
- Business domain → Market data, industry reports

## Expected Behavior
- Gather information before forming conclusions
- Cite sources and explain their relevance
- Cross-reference multiple sources when possible
- Clearly state confidence levels in findings"#
                .to_string(),

            Self::Template(template) => template.to_prompt(),
        }
    }
}

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

    #[test]
    fn test_dialogue_context_default() {
        let context: DialogueContext = DialogueContext::default();
        assert!(context.talk_style.is_none());
        assert!(context.environment.is_none());
        assert!(context.additional_context.is_empty());
    }

    #[test]
    fn test_dialogue_context_builder() {
        let context = DialogueContext::default()
            .with_talk_style(TalkStyle::Brainstorm)
            .with_environment("Test environment")
            .with_additional_context("Additional info".to_string());

        assert_eq!(context.talk_style, Some(TalkStyle::Brainstorm));
        assert_eq!(context.environment, Some("Test environment".to_string()));
        assert_eq!(context.additional_context.len(), 1);
    }

    #[test]
    fn test_talk_style_to_prompt() {
        let prompt = TalkStyle::Brainstorm.to_prompt();
        assert!(prompt.contains("Brainstorming Session"));
        assert!(prompt.contains("creative"));
    }

    #[test]
    fn test_dialogue_context_to_prompt() {
        let context = DialogueContext::default()
            .with_talk_style(TalkStyle::Debate)
            .with_environment("Production")
            .with_additional_context("Focus on security".to_string());

        let prompt = context.to_prompt();
        assert!(prompt.contains("# Environment"));
        assert!(prompt.contains("Production"));
        assert!(prompt.contains("Debate"));
        assert!(prompt.contains("# Additional Context"));
        assert!(prompt.contains("Focus on security"));
    }

    #[test]
    fn test_dialogue_context_comprehensive_template_expansion() {
        // Test that all components (environment, talk_style, additional_context)
        // are properly expanded together in a single prompt
        let context = DialogueContext::default()
            .with_environment("ClaudeCode environment")
            .with_talk_style(TalkStyle::Brainstorm)
            .with_additional_context("We are building a Rust library".to_string())
            .with_additional_context("Focus on API design and ergonomics".to_string());

        let prompt = context.to_prompt();

        eprintln!(
            "=== Comprehensive DialogueContext Prompt ===\n{}\n=== End ===",
            prompt
        );

        // Verify structure
        assert!(
            prompt.contains("# Dialogue Context"),
            "Should have main header"
        );

        // Verify environment section
        assert!(
            prompt.contains("## Environment"),
            "Should have Environment section"
        );
        assert!(
            prompt.contains("ClaudeCode environment"),
            "Should contain environment value"
        );

        // Verify talk style section with full content
        assert!(
            prompt.contains("## Dialogue Style: Brainstorming Session"),
            "Should have Brainstorm talk style header"
        );
        assert!(
            prompt.contains("Encourage wild ideas"),
            "Should contain Brainstorm guidelines"
        );
        assert!(
            prompt.contains("creative brainstorming session"),
            "Should contain Brainstorm description"
        );

        // Verify additional context section
        assert!(
            prompt.contains("## Additional Context"),
            "Should have Additional Context section"
        );
        assert!(
            prompt.contains("We are building a Rust library"),
            "Should contain first additional context"
        );
        assert!(
            prompt.contains("Focus on API design and ergonomics"),
            "Should contain second additional context"
        );

        // Verify proper ordering (Environment -> Talk Style -> Additional Context)
        let env_pos = prompt.find("## Environment").unwrap();
        let style_pos = prompt.find("## Dialogue Style").unwrap();
        let context_pos = prompt.find("## Additional Context").unwrap();

        assert!(
            env_pos < style_pos,
            "Environment should come before Talk Style"
        );
        assert!(
            style_pos < context_pos,
            "Talk Style should come before Additional Context"
        );
    }

    #[test]
    fn test_dialogue_context_empty_renders_nothing() {
        let context: DialogueContext = DialogueContext::default();
        let prompt = context.to_prompt();
        assert_eq!(prompt, "", "Empty context should render as empty string");
    }

    #[test]
    fn test_dialogue_context_only_environment() {
        let context: DialogueContext = DialogueContext::default().with_environment("Test env");
        let prompt = context.to_prompt();

        assert!(prompt.contains("# Dialogue Context"));
        assert!(prompt.contains("## Environment"));
        assert!(prompt.contains("Test env"));
        assert!(!prompt.contains("## Dialogue Style"));
        assert!(!prompt.contains("## Additional Context"));
    }

    #[test]
    fn test_dialogue_context_all_talk_styles() {
        // Test that each TalkStyle properly expands its template
        let styles = vec![
            (TalkStyle::Brainstorm, "Brainstorming Session", "creative"),
            (TalkStyle::Casual, "Casual Conversation", "relaxed"),
            (
                TalkStyle::DecisionMaking,
                "Decision-Making Discussion",
                "systematic",
            ),
            (
                TalkStyle::Debate,
                "Constructive Debate",
                "Challenge constructively",
            ),
            (
                TalkStyle::ProblemSolving,
                "Problem-Solving Session",
                "solution-oriented",
            ),
            (
                TalkStyle::Review,
                "Review & Critique",
                "constructive review",
            ),
            (TalkStyle::Planning, "Planning Session", "Think forward"),
            (TalkStyle::Research, "Research Session", "fact-based"),
        ];

        for (style, expected_header, expected_keyword) in styles {
            let context: DialogueContext =
                DialogueContext::default().with_talk_style(style.clone());
            let prompt = context.to_prompt();

            assert!(
                prompt.contains(expected_header),
                "Style {:?} should contain header '{}'",
                style,
                expected_header
            );
            assert!(
                prompt.contains(expected_keyword),
                "Style {:?} should contain keyword '{}'",
                style,
                expected_keyword
            );
        }
    }

    #[test]
    fn test_talk_style_template_basic() {
        let template = TalkStyleTemplate::new("Code Review")
            .with_description("A focused code review session.");

        assert_eq!(template.name, "Code Review");
        assert_eq!(template.description, "A focused code review session.");
        assert!(template.guidelines.is_empty());
        assert!(template.expected_behaviors.is_empty());
    }

    #[test]
    fn test_talk_style_template_full() {
        let template = TalkStyleTemplate::new("Security Audit")
            .with_description("Review code for security vulnerabilities.")
            .with_guideline("Check for injection vulnerabilities")
            .with_guideline("Verify input validation")
            .with_expected_behavior("Provide CVE references when applicable")
            .with_expected_behavior("Suggest remediation steps");

        assert_eq!(template.name, "Security Audit");
        assert_eq!(template.guidelines.len(), 2);
        assert_eq!(template.expected_behaviors.len(), 2);
    }

    #[test]
    fn test_talk_style_template_to_prompt() {
        let template = TalkStyleTemplate::new("Architecture Review")
            .with_description("Discuss system architecture decisions.")
            .with_guideline("Consider scalability implications")
            .with_guideline("Evaluate trade-offs")
            .with_expected_behavior("Draw diagrams when helpful")
            .with_expected_behavior("Reference industry patterns");

        let prompt = template.to_prompt();

        assert!(prompt.contains("## Dialogue Style: Architecture Review"));
        assert!(prompt.contains("Discuss system architecture decisions."));
        assert!(prompt.contains("## Guidelines"));
        assert!(prompt.contains("- Consider scalability implications"));
        assert!(prompt.contains("- Evaluate trade-offs"));
        assert!(prompt.contains("## Expected Behavior"));
        assert!(prompt.contains("- Draw diagrams when helpful"));
        assert!(prompt.contains("- Reference industry patterns"));
    }

    #[test]
    fn test_talk_style_template_variant() {
        let template = TalkStyleTemplate::new("Custom Style")
            .with_description("A custom dialogue style.")
            .with_guideline("Be creative");

        let style = TalkStyle::Template(template);
        let prompt = style.to_prompt();

        assert!(prompt.contains("## Dialogue Style: Custom Style"));
        assert!(prompt.contains("A custom dialogue style."));
        assert!(prompt.contains("- Be creative"));
    }

    #[test]
    fn test_talk_style_template_in_dialogue_context() {
        let template = TalkStyleTemplate::new("Performance Review")
            .with_description("Analyze performance bottlenecks.")
            .with_guideline("Use profiling data")
            .with_expected_behavior("Provide benchmark comparisons");

        let context: DialogueContext = DialogueContext::default()
            .with_talk_style(TalkStyle::Template(template))
            .with_environment("Production analysis");

        let prompt = context.to_prompt();

        assert!(prompt.contains("# Dialogue Context"));
        assert!(prompt.contains("## Environment"));
        assert!(prompt.contains("Production analysis"));
        assert!(prompt.contains("## Dialogue Style: Performance Review"));
        assert!(prompt.contains("Analyze performance bottlenecks."));
        assert!(prompt.contains("- Use profiling data"));
        assert!(prompt.contains("- Provide benchmark comparisons"));
    }

    #[test]
    fn test_talk_style_template_with_multiple_guidelines() {
        let template = TalkStyleTemplate::new("Multi")
            .with_guidelines(["one", "two", "three"])
            .with_expected_behaviors(["a", "b"]);

        assert_eq!(template.guidelines, vec!["one", "two", "three"]);
        assert_eq!(template.expected_behaviors, vec!["a", "b"]);
    }
}