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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
use super::dialogue::ExecutionModel;
use super::{Agent, AgentError, Payload, RelatedParticipant, participant_relation};
use crate::ToPrompt;
use crate::agent::payload_message::format_messages_with_relation;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};

/// Visual identity for a persona, providing visual anchoring and recognition.
///
/// Visual identity helps with:
/// - **Agent Recognition**: LLMs recognize their role more strongly with visual anchors
/// - **Human Readability**: Users can quickly identify agents in conversation logs
/// - **Multi-Agent Clarity**: Essential for distinguishing agents in complex dialogues
///
/// # Research Note
///
/// Studies show that emojis and visual markers significantly improve LLM's
/// role adherence and response quality in multi-agent scenarios.
///
/// # Examples
///
/// ```rust,ignore
/// use llm_toolkit::agent::persona::VisualIdentity;
///
/// // Designer identity
/// let identity = VisualIdentity::new("🎨")
///     .with_tagline("User-Centered Design Advocate");
///
/// // Security engineer identity
/// let identity = VisualIdentity::new("🔒")
///     .with_tagline("Zero-Trust Architecture Specialist");
/// ```
#[derive(ToPrompt, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[prompt(template = "")] // Empty template as VisualIdentity is embedded in Persona
pub struct VisualIdentity {
    /// Visual icon/emoji representing this persona (e.g., "🎨", "🔧", "📊")
    pub icon: String,

    /// Optional tagline/catchphrase that captures the persona's essence
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tagline: Option<String>,

    /// Optional color code for future UI integration (e.g., "#FF5733")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
}

impl VisualIdentity {
    /// Creates a new visual identity with the given icon.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let identity = VisualIdentity::new("🎨");
    /// ```
    pub fn new(icon: impl Into<String>) -> Self {
        Self {
            icon: icon.into(),
            tagline: None,
            color: None,
        }
    }

    /// Sets the tagline for this identity.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let identity = VisualIdentity::new("🎨")
    ///     .with_tagline("Creative Problem Solver");
    /// ```
    pub fn with_tagline(mut self, tagline: impl Into<String>) -> Self {
        self.tagline = Some(tagline.into());
        self
    }

    /// Sets the color code for this identity.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let identity = VisualIdentity::new("🎨")
    ///     .with_color("#FF5733");
    /// ```
    pub fn with_color(mut self, color: impl Into<String>) -> Self {
        self.color = Some(color.into());
        self
    }
}

/// Persona definition for runtime-generated personas.
///
/// Use this for personas generated by LLMs or loaded from JSON.
/// All fields are owned `String` to support dynamic allocation.
///
/// # Visual Identity
///
/// Optionally include a `visual_identity` to enhance agent recognition
/// and improve multi-agent dialogue clarity. Visual anchoring has been
/// shown to strengthen LLM's role adherence.
#[derive(ToPrompt, Serialize, Deserialize, Clone, Debug)]
#[prompt(
    template = "{% if visual_identity %}{{ visual_identity.icon }} {% endif %}# Persona Profile
**Name**: {{ name }}
**Role**: {{ role }}
{% if visual_identity and visual_identity.tagline %}**Tagline**: {{ visual_identity.tagline }}
{% endif %}
## Background
{{ background }}

## Communication Style
{{ communication_style }}
{% if capabilities %}

## Capabilities
{% for cap in capabilities %}
- {{ cap }}
{% endfor %}
{% endif %}"
)]
pub struct Persona {
    pub name: String,
    pub role: String,
    pub background: String,
    pub communication_style: String,

    /// Optional visual identity for enhanced recognition
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visual_identity: Option<VisualIdentity>,

    /// Capabilities (tools/actions) this persona can perform
    ///
    /// Declares what concrete actions this agent can execute.
    /// This is used by Orchestrator for strategy generation and by
    /// Dialogue for participant coordination.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<super::Capability>>,
}

impl Persona {
    /// Creates a new persona with the given name and role.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use llm_toolkit::agent::persona::Persona;
    ///
    /// let persona = Persona::new("Alice", "UI/UX Designer")
    ///     .with_background("10 years of experience in user-centered design")
    ///     .with_communication_style("Visual and empathetic");
    /// ```
    pub fn new(name: impl Into<String>, role: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            role: role.into(),
            background: String::new(),
            communication_style: String::new(),
            visual_identity: None,
            capabilities: None,
        }
    }

    /// Sets the background for this persona.
    pub fn with_background(mut self, background: impl Into<String>) -> Self {
        self.background = background.into();
        self
    }

    /// Sets the communication style for this persona.
    pub fn with_communication_style(mut self, style: impl Into<String>) -> Self {
        self.communication_style = style.into();
        self
    }

    /// Sets the visual identity for this persona.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use llm_toolkit::agent::persona::{Persona, VisualIdentity};
    ///
    /// let identity = VisualIdentity::new("🎨")
    ///     .with_tagline("Creative Problem Solver");
    ///
    /// let persona = Persona::new("Alice", "Designer")
    ///     .with_visual_identity(identity);
    /// ```
    pub fn with_visual_identity(mut self, identity: VisualIdentity) -> Self {
        self.visual_identity = Some(identity);
        self
    }

    /// Sets the visual identity using just an icon.
    ///
    /// This is a convenience method for quickly adding an icon without
    /// creating a full VisualIdentity struct.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let persona = Persona::new("Alice", "Designer")
    ///     .with_icon("🎨");
    /// ```
    pub fn with_icon(mut self, icon: impl Into<String>) -> Self {
        self.visual_identity = Some(VisualIdentity::new(icon));
        self
    }

    /// Returns the icon from visual identity, if present.
    pub fn icon(&self) -> Option<&str> {
        self.visual_identity.as_ref().map(|v| v.icon.as_str())
    }

    /// Returns the tagline from visual identity, if present.
    pub fn tagline(&self) -> Option<&str> {
        self.visual_identity
            .as_ref()
            .and_then(|v| v.tagline.as_deref())
    }

    /// Sets the capabilities for this persona.
    ///
    /// Accepts any type that can be converted into a Vec<Capability>,
    /// including Vec<&str>, Vec<String>, or Vec<Capability>.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use llm_toolkit::agent::persona::Persona;
    /// use llm_toolkit::agent::Capability;
    ///
    /// // Simple string slice vector
    /// let persona = Persona::new("FileAgent", "File Manager")
    ///     .with_capabilities(vec![
    ///         Capability::new("file:read"),
    ///         Capability::new("file:write"),
    ///     ]);
    /// ```
    pub fn with_capabilities(mut self, capabilities: Vec<super::Capability>) -> Self {
        self.capabilities = Some(capabilities);
        self
    }

    /// Returns a display name with icon if available.
    ///
    /// Returns formats like:
    /// - "🎨 Alice" (with icon)
    /// - "Alice" (without icon)
    pub fn display_name(&self) -> String {
        match self.icon() {
            Some(icon) => format!("{} {}", icon, self.name),
            None => self.name.clone(),
        }
    }
}

/// A team of personas for multi-agent dialogue scenarios.
///
/// PersonaTeam can be generated from a BluePrint description or loaded from JSON.
/// It provides a serializable representation of team composition that can be
/// reused across different tasks.
///
/// # Example
///
/// ```rust,ignore
/// use llm_toolkit::agent::persona::PersonaTeam;
///
/// // Load from JSON
/// let team = PersonaTeam::load("teams/dev_team.json")?;
///
/// // Save to JSON
/// team.save("teams/dev_team_backup.json")?;
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersonaTeam {
    /// Name of this team (e.g., "HR SaaS Development Team")
    pub team_name: String,

    /// Context/scenario description
    pub context: String,

    /// List of personas in this team
    pub personas: Vec<Persona>,

    /// Optional execution strategy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_strategy: Option<ExecutionModel>,
}

/// Request for generating a PersonaTeam from a BluePrint description.
///
/// This struct uses the ToPrompt derive macro to generate a structured prompt
/// for LLM-based persona team generation.
#[derive(Serialize, ToPrompt)]
#[prompt(template = r##"
# Persona Team Generation Task

You are an expert in team composition and organizational dynamics. Your task is to generate a well-balanced team of personas for a specific scenario.

## Scenario Context
{{ context }}

{% if role_descriptions %}
## Required Roles
{{ role_descriptions }}
{% endif %}

{% if team_graph %}
### Team Structure
```mermaid
{{ team_graph }}
```
{% endif %}

---

## Your Task

Generate a PersonaTeam as a JSON object with the following structure:

```json
{
  "team_name": "A descriptive name for this team (e.g., 'HR SaaS Development Team')",
  "context": "Brief description of the scenario/context",
  "execution_strategy": "sequential" or "broadcast" (choose based on the scenario),
  "personas": [
    {
      "name": "A realistic name for this person",
      "role": "Job title/function (e.g., 'Product Owner', 'UX Designer')",
      "background": "2-3 sentences describing their relevant experience, expertise, and perspective. Be specific to make them feel real.",
      "communication_style": "1-2 sentences describing how they communicate, make decisions, and collaborate with others."
    }
  ]
}
```

**Guidelines:**

1. **Team Composition**: Analyze the scenario and create personas that cover all necessary perspectives and expertise areas
2. **Balanced Team**: Ensure diversity in perspectives, experience levels, and communication styles
3. **Realistic Personas**: Give each persona:
   - A realistic name (vary cultural backgrounds naturally)
   - Specific expertise and experience (not generic)
   - Distinct communication style (some data-driven, some user-focused, etc.)
   - Believable background (mention years of experience, past roles, specializations)

4. **Execution Strategy Selection**:
   - Use "broadcast" for brainstorming, reviews, or when all voices should be heard simultaneously
   - Use "sequential" for process-driven workflows (e.g., requirements → design → implementation → QA)

5. **Team Size**: Generally 3-6 personas is ideal. Too few lacks perspective; too many becomes unwieldy.

6. **Role Coverage**: For typical product development scenarios, consider including:
   - Decision maker (Product Owner, Tech Lead)
   - User advocate (UX Designer, Customer Success)
   - Technical experts (Engineers, Architects)
   - Quality/Risk (QA, Security, DevOps if relevant)

**Important:** Return ONLY the JSON object, no additional explanation or commentary.
"##)]
pub struct PersonaTeamGenerationRequest {
    pub context: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub role_descriptions: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub team_graph: String,
}

impl PersonaTeamGenerationRequest {
    /// Creates a new generation request.
    pub fn new(context: String) -> Self {
        Self {
            context,
            role_descriptions: String::new(),
            team_graph: String::new(),
        }
    }

    /// Sets the role descriptions.
    pub fn with_role_descriptions(mut self, descriptions: String) -> Self {
        self.role_descriptions = descriptions;
        self
    }

    /// Sets the team graph (Mermaid diagram).
    pub fn with_team_graph(mut self, graph: String) -> Self {
        self.team_graph = graph;
        self
    }
}

impl PersonaTeam {
    /// Creates a new PersonaTeam.
    pub fn new(team_name: String, context: String) -> Self {
        Self {
            team_name,
            context,
            personas: Vec::new(),
            execution_strategy: None,
        }
    }

    /// Adds a persona to this team.
    pub fn add_persona(&mut self, persona: Persona) -> &mut Self {
        self.personas.push(persona);
        self
    }

    /// Sets the execution strategy.
    pub fn with_execution_strategy(mut self, strategy: ExecutionModel) -> Self {
        self.execution_strategy = Some(strategy);
        self
    }

    /// Loads a PersonaTeam from a JSON file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed.
    pub fn load(path: impl AsRef<std::path::Path>) -> Result<Self, std::io::Error> {
        let content = std::fs::read_to_string(path)?;
        serde_json::from_str(&content)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    /// Saves this PersonaTeam to a JSON file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written.
    pub fn save(&self, path: impl AsRef<std::path::Path>) -> Result<(), std::io::Error> {
        let content = serde_json::to_string_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        std::fs::write(path, content)
    }
}

/// Formats participants information with relation interpretation.
///
/// The current agent (self) is marked as "YOU" or "ME", while other participants
/// are listed with their speaker information.
///
/// # Arguments
///
/// * `participants` - List of all participants in the dialogue
/// * `self_name` - Name of the current agent (persona)
fn relate_participants<'a>(
    participants: impl IntoIterator<Item = &'a super::dialogue::ParticipantInfo>,
    self_name: &str,
) -> Vec<RelatedParticipant> {
    participants
        .into_iter()
        .cloned()
        .map(|participant| {
            let relation = participant_relation(&participant, self_name);
            RelatedParticipant::new(participant, relation)
        })
        .collect()
}

fn format_participants_with_relation(
    participants: &[super::dialogue::ParticipantInfo],
    self_name: &str,
) -> String {
    relate_participants(participants.iter(), self_name)
        .into_iter()
        .map(|participant| participant.format_line())
        .collect::<Vec<_>>()
        .join("\n")
}

/// Structured prompt for PersonaAgent that combines persona information,
/// participants context, and current content (text or messages).
///
/// This structure allows PersonaAgent to build prompts in a type-safe way
/// and defer the actual text formatting until needed.
#[derive(ToPrompt, Serialize)]
#[prompt(template = r#"YOU ARE A PERSONA-DRIVEN AI AGENT.

{{persona}}
{% if participants_before %}
# Participants
{{participants_before}}
{% endif %}{% if context %}

# Conversation Context (History)
{{context}}{% endif %}
{% if participants_after %}

# Participants
{{participants_after}}
{% endif %}{% if current_content %}

# Current Messages
{{current_content}}
{% endif %}{% if trailing_prompt %}

{{trailing_prompt}}
{% endif %}"#)]
struct PersonaAgentPrompt {
    persona: Persona,
    #[serde(skip_serializing_if = "String::is_empty")]
    participants_before: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    context: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    participants_after: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    current_content: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    trailing_prompt: String,
}

/// Configuration for Context placement strategy in PersonaAgent.
///
/// This controls how Context (DialogueContext) is positioned
/// relative to conversation history to prevent it from being buried.
#[derive(Debug, Clone)]
pub struct ContextConfig {
    /// Threshold for considering conversation "long" (in characters)
    pub long_conversation_threshold: usize,

    /// Number of recent messages to keep after Context in long conversations
    pub recent_messages_count: usize,

    /// Place Participants section after Context instead of before Persona
    ///
    /// When true, the prompt structure becomes:
    /// Persona → Context → Participants → Messages
    ///
    /// This ensures Participants information appears closer to the actual conversation.
    pub participants_after_context: bool,

    /// Include a trailing prompt with the persona's name at the end
    ///
    /// When true, adds "YOU ({persona_name}):" at the very end of the prompt
    /// to reinforce the agent's identity and reduce confusion in long conversations.
    pub include_trailing_prompt: bool,
}

impl Default for ContextConfig {
    fn default() -> Self {
        Self {
            long_conversation_threshold: 5000,
            recent_messages_count: 10, // 5 round-trips
            participants_after_context: false,
            include_trailing_prompt: false,
        }
    }
}

pub struct PersonaAgent<T: Agent> {
    inner_agent: T,
    persona: Persona,
    context_config: ContextConfig,
}

impl<T: Agent> PersonaAgent<T> {
    pub fn new(inner_agent: T, persona: Persona) -> Self {
        Self {
            inner_agent,
            persona,
            context_config: ContextConfig::default(),
        }
    }

    /// Sets custom Context placement configuration.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use llm_toolkit::agent::persona::{PersonaAgent, ContextConfig};
    ///
    /// let config = ContextConfig {
    ///     long_conversation_threshold: 10000,
    ///     recent_messages_count: 20,
    /// };
    ///
    /// let agent = PersonaAgent::new(inner_agent, persona)
    ///     .with_context_config(config);
    /// ```
    pub fn with_context_config(mut self, config: ContextConfig) -> Self {
        self.context_config = config;
        self
    }
}

#[async_trait]
impl<T> Agent for PersonaAgent<T>
where
    T: Agent + Send + Sync,
    T::Output: Send,
{
    type Output = T::Output;
    type Expertise = String;

    fn expertise(&self) -> &String {
        &self.persona.role
    }

    fn capabilities(&self) -> Option<Vec<super::Capability>> {
        self.persona.capabilities.clone()
    }

    #[crate::tracing::instrument(
        name = "persona_agent.execute",
        skip(self, intent),
        fields(
            agent.name = %self.persona.name,
            agent.role = %self.persona.role,
            has_participants = intent.participants().is_some(),
            message_count = intent.to_messages().len(),
        )
    )]
    async fn execute(&self, intent: Payload) -> Result<Self::Output, AgentError> {
        // 1. Extract and format participants with relation interpretation (YOU/ME marking)
        let participants_text = intent
            .participants()
            .map(|participants| format_participants_with_relation(participants, &self.persona.name))
            .unwrap_or_default();

        // 2. Extract context from Payload
        let contexts = intent.contexts();
        let context_string = if !contexts.is_empty() {
            Some(contexts.join("\n\n"))
        } else {
            None
        };

        // 3. Get context text from HistoryAwareAgent (if provided)
        // Include both Text content AND System messages (excluding Context)
        let mut context_text = String::new();

        // Extract pure Text contents
        let text_content = intent.to_text();
        if !text_content.is_empty() {
            context_text.push_str(&text_content);
        }

        // Extract System messages (e.g., prepended context via prepend_system)
        let system_messages: Vec<String> = intent
            .to_messages()
            .into_iter()
            .filter_map(|msg| {
                if matches!(msg.speaker, super::dialogue::Speaker::System) {
                    Some(msg.content)
                } else {
                    None
                }
            })
            .collect();

        if !system_messages.is_empty() {
            if !context_text.is_empty() {
                context_text.push_str("\n\n");
            }
            context_text.push_str(&system_messages.join("\n\n"));
        }

        // 4. Extract and format current messages with YOU/ME marking
        let messages = intent.to_messages();
        let total_content_count = intent.total_content_count();

        // 5. Determine Context placement based on conversation length
        let (context_with_basic, current_messages_text) = if let Some(ctx_str) = context_string {
            // Calculate total message content length
            let total_message_length: usize = messages.iter().map(|m| m.content.len()).sum();

            let is_long_conversation =
                total_message_length >= self.context_config.long_conversation_threshold;

            if is_long_conversation {
                // Long conversation: Old history → Context → Recent messages
                let split_point = messages
                    .len()
                    .saturating_sub(self.context_config.recent_messages_count);
                let (old_messages, recent_messages) = messages.split_at(split_point);

                // Format old messages
                let old_messages_text = if !old_messages.is_empty() {
                    format_messages_with_relation(
                        old_messages,
                        &self.persona.name,
                        total_content_count,
                    )
                } else {
                    String::new()
                };

                // Format Context
                let basic_context_section =
                    format!("\n\n---\n\n# Basic Context\n\n{}\n\n---\n\n", ctx_str);

                // Format recent messages
                let recent_messages_text = if !recent_messages.is_empty() {
                    format_messages_with_relation(
                        recent_messages,
                        &self.persona.name,
                        total_content_count,
                    )
                } else {
                    String::new()
                };

                // Combine: old history + Context goes to context
                let mut combined_context = context_text.clone();
                if !old_messages_text.is_empty() {
                    if !combined_context.is_empty() {
                        combined_context.push_str("\n\n");
                    }
                    combined_context.push_str(&old_messages_text);
                }
                combined_context.push_str(&basic_context_section);

                (combined_context, recent_messages_text)
            } else {
                // Short conversation: Context → All history
                let basic_context_section =
                    format!("\n\n---\n\n# Basic Context\n\n{}\n\n---\n\n", ctx_str);

                let mut combined_context = context_text.clone();
                combined_context.push_str(&basic_context_section);

                let all_messages_text = format_messages_with_relation(
                    &messages,
                    &self.persona.name,
                    total_content_count,
                );

                (combined_context, all_messages_text)
            }
        } else {
            // No Context - use existing behavior
            let current_messages_text =
                format_messages_with_relation(&messages, &self.persona.name, total_content_count);
            (context_text, current_messages_text)
        };

        // 6. Build structured prompt with strategic placement
        let (participants_before, participants_after) =
            if self.context_config.participants_after_context {
                (String::new(), participants_text)
            } else {
                (participants_text, String::new())
            };

        let trailing_prompt = if self.context_config.include_trailing_prompt {
            format!("YOU ({}):", self.persona.name)
        } else {
            String::new()
        };

        let prompt_struct = PersonaAgentPrompt {
            persona: self.persona.clone(),
            participants_before,
            context: context_with_basic,
            participants_after,
            current_content: current_messages_text,
            trailing_prompt,
        };

        // 7. Convert to text
        let prompt_text = prompt_struct.to_prompt();

        // Debug log the generated prompt
        crate::tracing::debug!(
            target: "llm_toolkit::agent::persona",
            persona_name = %self.persona.name,
            prompt_length = prompt_text.len(),
            "Generated persona prompt"
        );
        crate::tracing::trace!(
            target: "llm_toolkit::agent::persona",
            "\n========== PERSONA PROMPT ==========\n{}\n====================================",
            prompt_text
        );

        // 8. Create payload with Text + Messages (preserved)
        let final_payload = intent.clone().set_text(prompt_text.clone());
        #[cfg(test)]
        eprintln!(
            "[PersonaAgent] final_payload text: '{:?}'\n prompt_text: '{}'",
            final_payload, prompt_text,
        );
        self.inner_agent.execute(final_payload).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::dialogue::Speaker;
    use crate::agent::{Agent, AgentError, Payload, PayloadMessage};
    use crate::attachment::Attachment;
    use async_trait::async_trait;
    use serde::de::DeserializeOwned;
    use std::sync::Arc;
    use tokio::sync::Mutex;

    #[derive(Clone)]
    struct RecordingAgent<T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> {
        calls: Arc<Mutex<Vec<Payload>>>,
        response: T,
    }

    impl<T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> RecordingAgent<T> {
        fn new(response: T) -> Self {
            Self {
                calls: Arc::new(Mutex::new(Vec::new())),
                response,
            }
        }

        async fn last_call(&self) -> Option<Payload> {
            self.calls.lock().await.last().cloned()
        }
    }

    #[async_trait]
    impl<T> Agent for RecordingAgent<T>
    where
        T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
    {
        type Output = T;
        type Expertise = &'static str;

        fn expertise(&self) -> &&'static str {
            const EXPERTISE: &str = "Test agent";
            &EXPERTISE
        }

        async fn execute(&self, intent: Payload) -> Result<Self::Output, AgentError> {
            self.calls.lock().await.push(intent);
            Ok(self.response.clone())
        }
    }

    #[tokio::test]
    async fn persona_agent_preserves_attachments() {
        let persona = Persona {
            name: "Tester".to_string(),
            role: "Attachment Checker".to_string(),
            background: "Validates payload handling.".to_string(),
            communication_style: "Direct and concise.".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let base_agent = RecordingAgent::new(String::from("ok"));
        let persona_agent = PersonaAgent::new(base_agent.clone(), persona);

        let attachment = Attachment::in_memory(vec![1, 2, 3]);
        let payload = Payload::text("Please inspect the data").with_attachment(attachment.clone());

        let _ = persona_agent.execute(payload).await.unwrap();

        let recorded_payload = base_agent.last_call().await.expect("call recorded");
        assert!(
            recorded_payload.has_attachments(),
            "attachments should be preserved"
        );
        let attachments = recorded_payload.attachments();
        assert_eq!(attachments.len(), 1);
        assert_eq!(attachments[0], &attachment);
    }

    #[tokio::test]
    async fn persona_agent_works() {
        let persona = Persona {
            name: "TestBot".to_string(),
            role: "Test Assistant".to_string(),
            background: "A helpful test bot for unit testing".to_string(),
            communication_style: "Direct and clear".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let base_agent = RecordingAgent::new(String::from("response"));
        let persona_agent = PersonaAgent::new(base_agent.clone(), persona);

        let result = persona_agent
            .execute(Payload::text("Initial conversation").with_message(
                Speaker::User {
                    name: "User1".to_string(),
                    role: "User".to_string(),
                },
                "additional context here".to_string(),
            ))
            .await
            .unwrap();
        assert_eq!(result, "response");

        let call = base_agent.last_call().await.expect("call recorded");
        let call_text = call.to_text();
        assert!(call_text.contains("Persona Profile"));
        assert!(call_text.contains("TestBot"));
        assert!(call_text.contains("Test Assistant"));
    }

    #[test]
    fn persona_to_prompt_template_expansion() {
        use crate::ToPrompt;

        let persona = Persona {
            name: "Alice".to_string(),
            role: "Engineer".to_string(),
            background: "Senior software engineer with 10 years of experience".to_string(),
            communication_style: "Direct and clear".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let prompt = persona.to_prompt();

        // Verify template variables are expanded (not left as {{ name }})
        assert!(
            !prompt.contains("{{ name }}"),
            "Template variables should be expanded, not left as placeholders"
        );
        assert!(
            !prompt.contains("{{ role }}"),
            "Template variables should be expanded, not left as placeholders"
        );
        assert!(
            !prompt.contains("{{ background }}"),
            "Template variables should be expanded, not left as placeholders"
        );
        assert!(
            !prompt.contains("{{ communication_style }}"),
            "Template variables should be expanded, not left as placeholders"
        );

        // Verify actual values are present
        assert!(prompt.contains("Alice"), "Name should be in prompt");
        assert!(prompt.contains("Engineer"), "Role should be in prompt");
        assert!(
            prompt.contains("Senior software engineer"),
            "Background should be in prompt"
        );
        assert!(
            prompt.contains("Direct and clear"),
            "Communication style should be in prompt"
        );

        // Verify structure
        assert!(prompt.contains("# Persona Profile"), "Should have header");
        assert!(prompt.contains("**Name**:"), "Should have Name label");
        assert!(prompt.contains("**Role**:"), "Should have Role label");
        assert!(
            prompt.contains("## Background"),
            "Should have Background section"
        );
        assert!(
            prompt.contains("## Communication Style"),
            "Should have Communication Style section"
        );

        println!("Generated prompt:\n{}", prompt);
    }

    #[test]
    fn persona_agent_prompt_nested_template_expansion() {
        use crate::ToPrompt;

        let persona = Persona {
            name: "Alice".to_string(),
            role: "Engineer".to_string(),
            background: "Senior software engineer".to_string(),
            communication_style: "Direct and clear".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let prompt_struct = PersonaAgentPrompt {
            persona: persona.clone(),
            participants_before: "- Bob (Developer)\n- Charlie (Designer)".to_string(),
            context: "additional context here".to_string(),
            participants_after: String::new(),
            current_content: "Please review the code".to_string(),
            trailing_prompt: String::new(),
        };

        let prompt = prompt_struct.to_prompt();
        eprintln!(
            "=== Generated PersonaAgentPrompt ===\n{}\n=== End ===",
            prompt
        );
        assert_eq!(
            prompt,
            r#"YOU ARE A PERSONA-DRIVEN AI AGENT.

# Persona Profile
**Name**: Alice
**Role**: Engineer

## Background
Senior software engineer

## Communication Style
Direct and clear


# Participants
- Bob (Developer)
- Charlie (Designer)


# Conversation Context (History)
additional context here


# Current Messages
Please review the code
"#
        );

        // The issue: when we use {{persona}} in template, it gets JSON serialized
        // instead of using Persona's own ToPrompt template

        // Check if it's JSON serialized (the problem we're trying to fix)
        let is_json_serialized = prompt.contains(r#""name""#) || prompt.contains(r#""role""#);

        if is_json_serialized {
            println!(
                "ISSUE CONFIRMED: Persona is being JSON serialized instead of using its ToPrompt template"
            );
            println!("Expected: Persona's formatted template with markdown");
            println!("Actual: JSON representation of Persona struct");
        }

        // What we want: Persona's template should be expanded
        assert!(
            prompt.contains("# Persona Profile"),
            "Should contain Persona's template header (not JSON)"
        );
        assert!(
            prompt.contains("**Name**: Alice"),
            "Should use Persona's template format (not JSON)"
        );
        assert!(
            !is_json_serialized,
            "Persona should use its ToPrompt template, not JSON serialization"
        );
    }

    #[test]
    fn persona_team_serialization() {
        let mut team = PersonaTeam::new("Test Team".to_string(), "Testing scenario".to_string());

        team.add_persona(Persona {
            name: "Alice".to_string(),
            role: "Developer".to_string(),
            background: "Senior engineer".to_string(),
            communication_style: "Technical".to_string(),
            visual_identity: None,
            capabilities: None,
        });

        team.add_persona(Persona {
            name: "Bob".to_string(),
            role: "Designer".to_string(),
            background: "UX specialist".to_string(),
            communication_style: "User-focused".to_string(),
            visual_identity: None,
            capabilities: None,
        });

        // Serialize
        let json = serde_json::to_string_pretty(&team).unwrap();
        assert!(json.contains("Test Team"));
        assert!(json.contains("Alice"));
        assert!(json.contains("Bob"));

        // Deserialize
        let deserialized: PersonaTeam = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.team_name, "Test Team");
        assert_eq!(deserialized.personas.len(), 2);
        assert_eq!(deserialized.personas[0].name, "Alice");
        assert_eq!(deserialized.personas[1].name, "Bob");
    }

    #[test]
    fn persona_team_load_save() {
        use tempfile::NamedTempFile;

        let mut team = PersonaTeam::new("Dev Team".to_string(), "Software development".to_string());
        team.add_persona(Persona {
            name: "Charlie".to_string(),
            role: "Tech Lead".to_string(),
            background: "10 years experience".to_string(),
            communication_style: "Strategic".to_string(),
            visual_identity: None,
            capabilities: None,
        });

        // Save to temp file
        let temp_file = NamedTempFile::new().unwrap();
        let path = temp_file.path();
        team.save(path).unwrap();

        // Load back
        let loaded = PersonaTeam::load(path).unwrap();
        assert_eq!(loaded.team_name, "Dev Team");
        assert_eq!(loaded.personas.len(), 1);
        assert_eq!(loaded.personas[0].name, "Charlie");
    }

    #[test]
    fn persona_team_generation_request_prompt() {
        use crate::ToPrompt;

        let request = PersonaTeamGenerationRequest::new(
            "Product development meeting for HR SaaS".to_string(),
        )
        .with_role_descriptions("PO, Designer, Engineer".to_string());

        let prompt = request.to_prompt();
        assert!(prompt.contains("Persona Team Generation Task"));
        assert!(prompt.contains("Product development meeting"));
        assert!(prompt.contains("PO, Designer, Engineer"));
    }

    #[tokio::test]
    async fn persona_agent_formats_participants_with_self_as_you() {
        use crate::agent::dialogue::ParticipantInfo;

        let persona = Persona {
            name: "Alice".to_string(),
            role: "PM".to_string(),
            background: "Product manager".to_string(),
            communication_style: "Strategic".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let participants = vec![
            ParticipantInfo::new(
                "Alice".to_string(),
                "PM".to_string(),
                "Product manager".to_string(),
            ),
            ParticipantInfo::new(
                "Bob".to_string(),
                "Engineer".to_string(),
                "Backend developer".to_string(),
            ),
        ];

        let base_agent = RecordingAgent::new("response".to_string());
        let persona_agent = PersonaAgent::new(base_agent.clone(), persona);

        let payload = Payload::text("Task").with_participants(participants);

        let _ = persona_agent.execute(payload).await.unwrap();

        let call = base_agent.last_call().await.unwrap();
        let call_text = call.to_text();

        // Alice should be marked as "YOU"
        assert!(call_text.contains("Alice (YOU)"));
        // Bob should not be marked as "YOU"
        assert!(call_text.contains("Bob"));
        assert!(!call_text.contains("Bob (YOU)"));
    }

    #[tokio::test]
    async fn persona_agent_formats_messages() {
        let persona = Persona {
            name: "Agent".to_string(),
            role: "Assistant".to_string(),
            background: "Helper".to_string(),
            communication_style: "Friendly".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let base_agent = RecordingAgent::new("response".to_string());
        let persona_agent = PersonaAgent::new(base_agent.clone(), persona);

        let payload = Payload::from_messages(vec![
            PayloadMessage::system("System instruction"),
            PayloadMessage::user("Alice", "PM", "User message"),
        ]);

        let _ = persona_agent.execute(payload).await.unwrap();

        let call = base_agent.last_call().await.unwrap();
        let call_text = call.to_text();

        // Messages should be formatted with speaker names
        assert!(call_text.contains("[System]: System instruction"));
        assert!(call_text.contains("[Alice]: User message"));
    }

    #[tokio::test]
    async fn persona_agent_preserves_messages_structure() {
        use crate::agent::dialogue::Speaker;

        let persona = Persona {
            name: "Agent".to_string(),
            role: "Assistant".to_string(),
            background: "Helper".to_string(),
            communication_style: "Friendly".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let base_agent = RecordingAgent::new("response".to_string());
        let persona_agent = PersonaAgent::new(base_agent.clone(), persona);

        let original_messages = vec![
            PayloadMessage::system("System msg"),
            PayloadMessage::user("Alice", "PM", "User msg"),
        ];

        let payload = Payload::from_messages(original_messages.clone());

        let _ = persona_agent.execute(payload).await.unwrap();

        let call = base_agent.last_call().await.unwrap();
        let received_messages = call.to_messages();

        // Messages should be preserved in the payload
        assert_eq!(received_messages.len(), original_messages.len());
        assert_eq!(received_messages[0].speaker, Speaker::System);
        assert_eq!(received_messages[0].content, "System msg");
        assert_eq!(received_messages[1].speaker, Speaker::user("Alice", "PM"));
        assert_eq!(received_messages[1].content, "User msg");
    }

    #[tokio::test]
    async fn persona_agent_full_integration() {
        use crate::agent::dialogue::{ParticipantInfo, Speaker};

        let persona = Persona {
            name: "Alice".to_string(),
            role: "PM".to_string(),
            background: "Product manager with 5 years experience".to_string(),
            communication_style: "Strategic and data-driven".to_string(),
            visual_identity: None,
            capabilities: None,
        };

        let participants = vec![
            ParticipantInfo::new(
                "Alice".to_string(),
                "PM".to_string(),
                "Product manager".to_string(),
            ),
            ParticipantInfo::new(
                "Bob".to_string(),
                "Engineer".to_string(),
                "Backend developer".to_string(),
            ),
        ];

        let messages = vec![
            PayloadMessage::system("Discuss feature priorities"),
            PayloadMessage::user("Bob", "Engineer", "I suggest we focus on performance"),
        ];

        let base_agent = RecordingAgent::new("Good idea".to_string());
        let persona_agent = PersonaAgent::new(base_agent.clone(), persona);

        let payload = Payload::from_messages(messages.clone()).with_participants(participants);

        let result = persona_agent.execute(payload).await.unwrap();
        assert_eq!(result, "Good idea");

        let call = base_agent.last_call().await.unwrap();
        let call_text = call.to_text();

        // Debug: print actual output
        println!("=== Actual call_text ===\n{}\n=== End ===", call_text);

        // Verify all components are present
        assert!(call_text.contains("# Persona Profile"));
        assert!(call_text.contains("**Name**: Alice"));
        assert!(call_text.contains("# Participants"));
        assert!(call_text.contains("**Alice (YOU)**"));
        assert!(call_text.contains("**Bob (ALLY)**"));
        assert!(call_text.contains("# Current Messages"));
        assert!(call_text.contains("[System]: Discuss feature priorities"));
        assert!(call_text.contains("[Bob]: I suggest we focus on performance"));

        // Verify messages are preserved (Text is excluded, only Message variants)
        let received_messages = call.to_messages();
        assert_eq!(received_messages.len(), 2);
        assert_eq!(received_messages[0].speaker, Speaker::System);
        assert_eq!(received_messages[0].content, "Discuss feature priorities");
        assert_eq!(
            received_messages[1].speaker,
            Speaker::user("Bob", "Engineer")
        );
        assert_eq!(
            received_messages[1].content,
            "I suggest we focus on performance"
        );
    }

    #[test]
    fn persona_capabilities_formatting() {
        use crate::ToPrompt;
        use crate::agent::Capability;

        let persona = Persona {
            name: "DevBot".to_string(),
            role: "Development Assistant".to_string(),
            background: "Helps with software development tasks".to_string(),
            communication_style: "Technical and precise".to_string(),
            visual_identity: None,
            capabilities: Some(vec![
                Capability::new("file:read"),
                Capability::new("file:write").with_description("Write content to a file"),
                Capability::new("api:call").with_description("Make HTTP API calls"),
            ]),
        };

        let prompt = persona.to_prompt();

        // Verify capabilities section exists
        assert!(
            prompt.contains("## Capabilities"),
            "Capabilities section should be present"
        );

        // Verify each capability is on its own line with proper formatting
        assert!(
            prompt.contains("- file:read"),
            "First capability should be properly formatted"
        );
        assert!(
            prompt.contains("- file:write: Write content to a file"),
            "Second capability with description should be properly formatted"
        );
        assert!(
            prompt.contains("- api:call: Make HTTP API calls"),
            "Third capability with description should be properly formatted"
        );

        // Verify capabilities are NOT displayed one character per line
        // (this would happen if template incorrectly iterates over string chars)
        let lines: Vec<&str> = prompt.lines().collect();
        let capability_section_start = lines
            .iter()
            .position(|line| line.contains("## Capabilities"))
            .expect("Should have Capabilities section");

        // Check that the lines after "## Capabilities" contain full capability strings
        // Skip empty lines and get actual capability lines
        let cap_lines: Vec<&str> = lines
            .iter()
            .skip(capability_section_start + 1)
            .filter(|line| !line.trim().is_empty())
            .take(3)
            .copied()
            .collect();

        // Each capability line should be more than a few characters
        assert_eq!(cap_lines.len(), 3, "Should have 3 capability lines");
        for cap_line in &cap_lines {
            assert!(
                cap_line.len() > 5,
                "Capability line should be a full line, not single characters. Got: '{}'",
                cap_line
            );
            assert!(
                cap_line.starts_with('-'),
                "Capability line should start with '-'. Got: '{}'",
                cap_line
            );
        }
    }

    // Local MockAgent for persona tests
    #[derive(Clone)]
    struct LocalMockAgent {
        responses: Vec<String>,
        call_count: std::sync::Arc<std::sync::Mutex<usize>>,
    }

    impl LocalMockAgent {
        fn new(responses: Vec<&str>) -> Self {
            Self {
                responses: responses.iter().map(|s| s.to_string()).collect(),
                call_count: std::sync::Arc::new(std::sync::Mutex::new(0)),
            }
        }
    }

    #[async_trait]
    impl Agent for LocalMockAgent {
        type Output = String;
        type Expertise = &'static str;

        fn expertise(&self) -> &&'static str {
            const EXPERTISE: &str = "Mock agent for testing";
            &EXPERTISE
        }

        async fn execute(&self, _payload: Payload) -> Result<Self::Output, AgentError> {
            let mut count = self.call_count.lock().unwrap();
            let response = self
                .responses
                .get(*count)
                .unwrap_or(&self.responses[0])
                .clone();
            *count += 1;
            Ok(response)
        }
    }

    #[tokio::test]
    async fn test_persona_agent_context_placement_short_conversation() {
        // Test that context is placed at the beginning for short conversations

        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("TestBot", "Test persona");
        let agent = PersonaAgent::new(inner_agent, persona);

        // Short conversation: just a few messages
        let payload = Payload::from_messages(vec![
            PayloadMessage::user("User1", "Role1", "Hello"),
            PayloadMessage::system("System response"),
        ])
        .with_context("Important context");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());

        // Verify the prompt structure
        // For short conversations, context should appear early in the prompt
        // (This is a simplified check - in reality we'd inspect the generated prompt)
    }

    #[tokio::test]
    async fn test_persona_agent_context_placement_long_conversation() {
        // Test that context is strategically placed in long conversations
        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("TestBot", "Test persona");

        // Configure with a low threshold to trigger long conversation behavior
        let config = ContextConfig {
            long_conversation_threshold: 50, // Very low threshold
            recent_messages_count: 2,
            participants_after_context: false,
            include_trailing_prompt: false,
        };
        let agent = PersonaAgent::new(inner_agent, persona).with_context_config(config);

        // Create a long conversation that exceeds the threshold
        let mut messages = vec![];
        for i in 0..10 {
            messages.push(PayloadMessage::user(
                "User1",
                "Role1",
                format!("Message {}", i),
            ));
            messages.push(PayloadMessage::system(format!("Response {}", i)));
        }

        let payload = Payload::from_messages(messages).with_context("Strategic context");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());

        // In long conversations, context should be placed between old and recent messages
        // (This is verified by the PersonaAgent implementation)
    }

    #[tokio::test]
    async fn test_persona_agent_multiple_contexts() {
        // Test that multiple contexts are joined correctly

        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("TestBot", "Test persona");
        let agent = PersonaAgent::new(inner_agent, persona);

        let payload = Payload::text("Question")
            .with_context("Context 1")
            .with_context("Context 2")
            .with_context("Context 3");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());

        // Multiple contexts should be joined with \n\n
        // (Verified by the PersonaAgent implementation)
    }

    #[tokio::test]
    async fn test_persona_agent_no_context() {
        // Test that PersonaAgent works correctly without context

        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("TestBot", "Test persona");
        let agent = PersonaAgent::new(inner_agent, persona);

        let payload = Payload::text("Question without context");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Response");
    }

    #[tokio::test]
    async fn test_context_config_customization() {
        // Test custom ContextConfig

        let config = ContextConfig {
            long_conversation_threshold: 10000,
            recent_messages_count: 20,
            participants_after_context: false,
            include_trailing_prompt: false,
        };

        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("TestBot", "Test persona");
        let agent = PersonaAgent::new(inner_agent, persona).with_context_config(config.clone());

        assert_eq!(agent.context_config.long_conversation_threshold, 10000);
        assert_eq!(agent.context_config.recent_messages_count, 20);
    }

    #[tokio::test]
    async fn test_participants_after_context_strategy() {
        // Test that participants can be placed after context
        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("TestBot", "Test persona");

        let config = ContextConfig {
            long_conversation_threshold: 5000,
            recent_messages_count: 10,
            participants_after_context: true,
            include_trailing_prompt: false,
        };
        let agent = PersonaAgent::new(inner_agent, persona).with_context_config(config);

        let payload = Payload::text("Test message").with_context("Important context");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());

        // The prompt structure should be: Persona → Context → Participants → Messages
        // (Verified by PersonaAgent implementation)
    }

    #[tokio::test]
    async fn test_trailing_prompt_strategy() {
        // Test that trailing prompt reinforces persona identity
        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("Alice", "Engineer");

        let config = ContextConfig {
            long_conversation_threshold: 5000,
            recent_messages_count: 10,
            participants_after_context: false,
            include_trailing_prompt: true,
        };
        let agent = PersonaAgent::new(inner_agent, persona).with_context_config(config);

        let payload = Payload::text("What should we do?");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());

        // The prompt should end with "YOU (Alice):"
        // (Verified by PersonaAgent implementation)
    }

    #[tokio::test]
    async fn test_combined_strategies() {
        // Test both strategies enabled together
        let inner_agent = LocalMockAgent::new(vec!["Response"]);
        let persona = Persona::new("Bob", "Designer");

        let config = ContextConfig {
            long_conversation_threshold: 100,
            recent_messages_count: 2,
            participants_after_context: true,
            include_trailing_prompt: true,
        };
        let agent = PersonaAgent::new(inner_agent, persona).with_context_config(config);

        // Long conversation
        let mut messages = vec![];
        for i in 0..10 {
            messages.push(PayloadMessage::user(
                "User1",
                "Role1",
                format!("Message {}", i),
            ));
        }

        let payload = Payload::from_messages(messages).with_context("Design context");

        let result = agent.execute(payload).await;
        assert!(result.is_ok());

        // Prompt structure should be:
        // Persona → Old messages → Context → Participants → Recent messages → YOU (Bob):
    }
}