quorum-rs 0.7.0-rc.6

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
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
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
//! Contains a default, general-purpose implementation of the `PromptSet` trait.

use crate::agents::DeliberationPhase;

use super::PromptSet;
use crate::agents::{Proposal, UserInjection};

fn render_user_updates(injections: &[UserInjection], context: &str) -> String {
    if injections.is_empty() {
        return String::new();
    }
    let mut out = String::from("<user_updates>\n");
    if context == "evaluation" {
        out.push_str(
            "  The user provided the following clarifications during deliberation.\n  \
             Factor these into your evaluation criteria.\n",
        );
    } else {
        out.push_str(
            "  The user provided the following clarifications during deliberation.\n  \
             Integrate these into your work — later updates take priority.\n",
        );
    }
    for inj in injections {
        out.push_str(&format!(
            "  <update round=\"{}\">{}</update>\n",
            inj.injected_at_round, inj.message
        ));
    }
    out.push_str("</user_updates>\n");
    out
}

/// A default, general-purpose set of prompts for an NSED agent.
///
/// This implementation provides standard, model-agnostic prompts suitable for
/// general problem-solving tasks.
#[derive(Clone, Debug)]
pub struct DefaultPromptSet {
    pub persona: Option<String>,
    pub textual_feedback: bool,
}

impl Default for DefaultPromptSet {
    fn default() -> Self {
        Self {
            persona: None,
            textual_feedback: true,
        }
    }
}

impl DefaultPromptSet {
    /// Creates a new instance of the default prompt set.
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_persona(mut self, persona: String) -> Self {
        self.persona = Some(persona);
        self
    }

    pub fn with_textual_feedback(mut self, enabled: bool) -> Self {
        self.textual_feedback = enabled;
        self
    }
}

impl PromptSet for DefaultPromptSet {
    fn get_system_message(
        &self,
        agent_name: &str,
        current_round: usize,
        round_numbers: usize,
        phase: DeliberationPhase,
    ) -> String {
        let role_description = match phase {
            DeliberationPhase::Proposing => "Proposing",
            DeliberationPhase::Evaluating => "Evaluating",
            DeliberationPhase::ConsensusCheck => "Consensus Check",
        };

        let mut message = String::new();

        // 1. Context & Goal
        message.push_str(
            "You are a member of an elite AI council table tasked with solving complex problems through rigorous deliberation.\n\
            Your goal is to produce a **complete, finalized answer** that fully addresses the user's request. \
            The deliberation output is delivered directly to the end user — treat every proposal as a polished final draft.\n\
            If you need additional information to produce a thorough answer, use the tools provided (e.g. user-facing tools to ask clarifying questions). \
            Do not leave gaps or defer to the user when you can reason through the problem yourself.\n\n\
            <incentives>\n\
            - **Cooperative Failure**: If the group submits a wrong final answer, you ALL fail. You are punished together.\n\
            - **Competitive Success**: If the group succeeds, the agent with the winning proposal gains maximum reward. Evaluation accuracy also yields rewards.\n\
            - Therefore: Collaborate to find the truth, but compete to be the one who finds it.\n\
            </incentives>\n",
        );

        // 2. Identity & Persona
        message.push_str(&format!("\n<identity>\nYour name is {agent_name}.\n"));
        if let Some(persona) = &self.persona {
            message.push_str("Persona: ");
            message.push_str(persona);
            message.push('\n');
        }
        message.push_str("</identity>\n");

        // 3. Protocol & Rules
        message.push_str(&format!(
            "\n<protocol>\n\
            - **Structure**: The deliberation has {round_numbers} rounds. Each round has two phases: Proposing (submit solution) and Evaluating (critique peers).\n\
            - **Current Status**: Round {current_round} of {round_numbers}. Phase: {role_description}.\n\
            </protocol>\n"
        ));

        // 4. PHASE-SPECIFIC STRATEGY
        match phase {
            DeliberationPhase::Proposing => {
                message.push_str(
                    "\n<strategy phase=\"proposing\">\n\
                    1. **Plan First**: You MUST write your plan to the scratchpad before solving.\n\
                    2. **Step-by-Step**: Solve incrementally. Verify intermediate results.\n\
                    3. **Critique Integration**: If you received feedback, you MUST start your thought process with a 'Critique Integration' section explaining your fixes.\n\
                    </strategy>\n"
                );
            }
            DeliberationPhase::Evaluating => {
                message.push_str(
                    "\n<strategy phase=\"evaluating\">\n\
                    You are a Judge. Your default stance is SKEPTICISM. Do not be sycophantic.\n\
                    Use the Vector Alignment protocol:\n\
                    1. **Decompose**: Break each candidate's argument into discrete claims. Identify the 2-3 claims that most determine correctness.\n\
                    2. **Anchor**: Trust your own solution unless proven wrong.\n\
                    3. **Delta**: Identify EXACTLY where a peer diverges from you on those pivotal claims.\n\
                    4. **Verification**: Verify ONLY the divergent claims. If they are wrong, reject them ruthlessly. If they are right, accept the correction.\n\
                    5. **Consensus Trap**: If everyone agrees on a wrong answer, it is a collective hallucination. Be the one who spots the error.\n\
                    6. **Harsh Scoring**: Penalize unverified claims. Agreement without verification is worth 0.\n\
                    </strategy>\n"
                );
            }
            _ => {}
        }

        // 5. Critical Execution Rules
        message.push_str(
            "\n<rules>\n\
           1. Use `update_scratchpad` to store notes. Structure your scratchpad with XML sections:\n\
              * `<working_memory>` — Ephemeral per-round calculations (cleared after each round).\n\
              * `<key_findings>` — Persistent discoveries that matter across rounds.\n\
              * `<strategy>` — Your evolving approach.\n\
              Use sparingly; only for cross-round records or tool output notes.\n\
           2. Use `read_proposal` or `search_deliberation` to inspect peer reasoning.\n\
           3. Only call `submit` tools when finished.\n\
           4. **No meta-commentary**: Your proposal content is shown directly to the end user. Never include headers like \"FINAL RECOMMENDATION:\", \"CONCLUSION:\", \"Summary:\", or similar structural artifacts. Do not reference the deliberation process, rounds, or other agents in your output. Write as if you are the sole author delivering a polished answer.\n\
           </rules>",
        );

        message
    }

    fn get_proposer_prompt(
        &self,
        task_description: &str,
        previous_round_matrix: Option<String>,
        previous_own_proposal: Option<&Proposal>,
        previous_score: Option<f32>,
        previous_critiques: Vec<String>,
        user_injections: &[UserInjection],
        structured_feedback: Option<&crate::agents::StructuredFeedback>,
    ) -> String {
        let user_updates_section = render_user_updates(user_injections, "proposing");

        // Build structured deliberation brief when available
        let deliberation_brief = if let Some(sf) = structured_feedback {
            let mut brief = String::from("<deliberation_brief>\n");

            if !sf.contested_claims.is_empty() {
                brief.push_str(&format!(
                    "  <contested_claims count=\"{}\">\n",
                    sf.contested_claims.len()
                ));
                for cc in &sf.contested_claims {
                    brief.push_str(&format!(
                        "    <dispute id=\"{}\" evaluator=\"{}\" confidence=\"{:?}\">\n      <your_claim>{}</your_claim>\n      <counter>{}</counter>\n    </dispute>\n",
                        cc.claim_id,
                        cc.evaluator,
                        cc.confidence,
                        cc.what_you_claimed,
                        cc.counter_position
                    ));
                }
                brief.push_str("  </contested_claims>\n");
            }

            if !sf.verified_claims.is_empty() {
                brief.push_str(&format!(
                    "  <verified_claims>{}</verified_claims>\n",
                    sf.verified_claims.join(", ")
                ));
            }

            if let Some(ref cb) = sf.category_breakdown {
                brief.push_str(&format!(
                    "  <category_breakdown>correctness: {:.2} | completeness: {:.2} | novelty: {:.2} | feasibility: {:.2} | evidence_quality: {:.2}</category_breakdown>\n",
                    cb.correctness, cb.completeness, cb.novelty, cb.feasibility, cb.evidence_quality
                ));
            }

            brief.push_str("</deliberation_brief>\n\n");
            brief
        } else {
            String::new()
        };

        if let Some(matrix) = previous_round_matrix {
            let own_proposal_section = if let Some(p) = previous_own_proposal {
                let truncated_thought = if p.thought_process.chars().count() > 500 {
                    format!(
                        "{}...",
                        p.thought_process.chars().take(500).collect::<String>()
                    )
                } else {
                    p.thought_process.clone()
                };

                let score_msg = if let Some(score) = previous_score {
                    let advice = if score < 0.5 {
                        "LOW support. Provide more convincing proofs addressing critics, or fundamentally rethink your approach."
                    } else if score < 0.8 {
                        "Moderate support. Address critiques and review other proposals to improve your contribution."
                    } else {
                        "High support. Your proposal is leading. Review other proposals and iterate on it to maintain support. The group rewards verifiable truth."
                    };
                    format!(
                        "YOUR PREVIOUS SCORE: {score:.2} / 1.0\n{advice}\n\
                        Your goal is to find the objectively correct answer. Peer support is a signal of verification, but truth is the ultimate standard. If you believe you are right and others are wrong, provide stronger proof.\n"
                    )
                } else {
                    String::new()
                };

                format!(
                    "\n<previous_own_proposal>\n\
                    {}\
                    THOUGHT PROCESS (Preview): {}\n\
                    FINAL SOLUTION: {}\n\
                    (Use `read_own_proposal()` to see full details if needed.)\n\
                    </previous_own_proposal>\n\n",
                    score_msg, truncated_thought, p.content
                )
            } else {
                String::new()
            };

            let critiques_section = if !previous_critiques.is_empty() {
                let combined = previous_critiques.join("\n\n");
                format!(
                    "<peer_critiques>\n(These are the specific reasons you lost points. Address them directly.)\n{combined}\n</peer_critiques>\n\n"
                )
            } else {
                String::new()
            };

            let has_categories = structured_feedback
                .as_ref()
                .and_then(|f| f.category_breakdown.as_ref())
                .is_some();
            let structured_instructions = if structured_feedback.is_some() {
                if has_categories {
                    "\n5. For each contested claim in the deliberation brief:\n\
                       - If the counter-argument is correct: FIX your approach.\n\
                       - If your original claim is correct: STRENGTHEN your proof.\n\
                     6. Focus on your weakest category score."
                } else {
                    "\n5. For each contested claim in the deliberation brief:\n\
                       - If the counter-argument is correct: FIX your approach.\n\
                       - If your original claim is correct: STRENGTHEN your proof."
                }
            } else {
                ""
            };

            let instructions_feedback = if self.textual_feedback {
                format!(
                    "1. ANALYZE the matrix above and the critiques you received.\n\
                     2. OPTIONAL: Use `read_proposal(round, best_agent_id)` to see the full reasoning of any agent.\n\
                     3. Synthesize a NEW solution that combines the strengths of all proposals and fixes the critiques mentioned by peers.\n\
                     4. Do NOT simply repeat the previous winner. Innovate or Refine.{structured_instructions}"
                )
            } else {
                format!(
                    "1. ANALYZE the matrix above.\n\
                     2. Use `read_proposal(round, best_agent_id)` to see the full reasoning of any agent and understand why they scored differently.\n\
                     3. Synthesize a NEW solution that combines the strengths of all proposals.\n\
                     4. Do NOT simply repeat the previous winner. Innovate or Refine.{structured_instructions}"
                )
            };

            let thought_process_instruction = if self.textual_feedback {
                "Your `thought_process` MUST begin with: \"**Critique Integration:** [Explain how you used peer feedback]...\""
            } else {
                ""
            };

            format!(
                "<task>\"{task_description}\"</task>\n\n\
                <previous_round_matrix>\n\
                {matrix}\n\
                </previous_round_matrix>\n\
                {own_proposal_section}\
                {deliberation_brief}\
                {critiques_section}\
                {user_updates_section}\
                <instructions>\n\
                {instructions_feedback}\n\
                \n\
                When you are CERTAIN you have the best possible solution, call `submit_proposal` with `thought_process` and `solution_content`.\n\
                {thought_process_instruction}\n\
                Do NOT return plain text.\n\
                </instructions>"
            )
        } else {
            format!(
                "<task>\"{task_description}\"</task>\n\n\
                {user_updates_section}\
                INSTRUCTIONS:\n\
                Solve the provided task. \
                Think step-by-step. Use the `update_scratchpad` tool to break the problem down.\n\
                \n\
                When you are CERTAIN you have the best possible solution, call `submit_proposal` with `thought_process` and `solution_content`.
                Do NOT return plain text."
            )
        }
    }

    fn get_batch_evaluator_prompt(
        &self,
        task_description: &str,
        candidates: &[crate::agents::CandidateProposal],
        own_current_proposal: Option<&Proposal>,
        current_round: usize,
        user_injections: &[UserInjection],
    ) -> String {
        let valid_ids: Vec<String> = candidates.iter().map(|c| c.id.clone()).collect();
        let valid_ids_str = valid_ids.join(", ");

        let mut candidates_text = String::new();
        // Inline full thought processes to avoid wasting iterations on individual read_proposal calls.
        // Only truncate if a single candidate's thoughts exceed a generous limit.
        let thought_limit = 4000;
        for candidate in candidates {
            let thought_chars = candidate.proposal.thought_process.chars().count();
            let (thoughts_text, truncated) = if thought_chars > thought_limit {
                let truncated_text: String = candidate
                    .proposal
                    .thought_process
                    .chars()
                    .take(thought_limit)
                    .collect();
                (format!("{truncated_text}..."), true)
            } else {
                (candidate.proposal.thought_process.clone(), false)
            };

            candidates_text.push_str(&format!(
                "<candidate id=\"{}\">\nFINAL SOLUTION: {}\nTHOUGHT PROCESS: {}{}\n</candidate>\n\n",
                candidate.id,
                candidate.proposal.content,
                thoughts_text,
                if truncated {
                    format!("\n(Truncated — use `read_proposal(round={current_round}, agent_id=\"{}\")` with offset={thought_limit} to read the rest)", candidate.id)
                } else {
                    String::new()
                }
            ));
        }

        let own_proposal_section = if let Some(p) = own_current_proposal {
            let truncated_thought = if p.thought_process.chars().count() > 500 {
                format!(
                    "{}...",
                    p.thought_process.chars().take(500).collect::<String>()
                )
            } else {
                p.thought_process.clone()
            };

            format!(
                "\n<own_current_proposal>\n\
                You just proposed the following solution:\n\
                THOUGHT PROCESS (Preview): {}\n\
                CONTENT: {}\n\
                (Use this as a baseline. If a candidate disagrees with you, verify who is correct. Do not blindly accept a different answer unless you find a flaw in your own reasoning.)\n\
                </own_current_proposal>\n\n",
                truncated_thought, p.content
            )
        } else {
            String::new()
        };

        let user_updates_section = render_user_updates(user_injections, "evaluation");

        // Build evaluation focus section for round 2+ to direct dispute resolution
        let evaluation_focus_section = if current_round > 1 {
            format!(
                "<evaluation_focus>\n\
                This is round {current_round}. Prioritize dispute resolution over re-evaluation from scratch.\n\
                * Use `search_deliberation` with `rounds: [{prev_round}]` and `verdicts: [\"contested\", \"wrong\"]` to find claims that were disputed last round.\n\
                * For each candidate: check whether previously contested claims have been ADDRESSED or PERSISTED in their updated proposal.\n\
                * **Resolved claims**: If a previously contested claim is now corrected or supported with evidence, mark it as `verified` and reference its `claim_id`.\n\
                * **Still contested**: If a disputed claim persists unchanged, re-assert your disagreement with the same `claim_id` for cross-round tracking.\n\
                * **New claims**: Evaluate new arguments or changes on their own merit.\n\
                * Focus your deepest analysis on HIGH CONTROVERSY candidates (those with wide score variance in previous rounds).\n\
                </evaluation_focus>\n\n",
                prev_round = current_round - 1,
            )
        } else {
            String::new()
        };

        format!(
            "Assess the following proposals in response to the user's task.\n\n\
            {evaluation_focus_section}\
            <instructions>\n\
            1. **Inline Review**: Each candidate's full thought process is provided below. Read them carefully BEFORE evaluating.
               * Only use `read_proposal(round={current_round}, agent_id)` if a thought process was truncated and you need the rest.
               * Do NOT call `read_proposal` for every candidate — their reasoning is already inline.
            2. **Vector Alignment**: Apply the strategy defined in your System Prompt.
               * Identify the Delta. Verify the Delta. Vote accordingly.
            3. **Self-Reflection**: Use `read_own_proposal()` to review your own reasoning if needed.
               * DO NOT evaluate yourself. Only evaluate the following CANDIDATES: [{valid_ids_str}]

            4. Assign an **endorsement_weight** (-100 to +100) to each proposal. Positive = support, negative = oppose, 0 = genuinely neutral.
               * -100 to -50: Demonstrably wrong, hallucinated, or contains critical logical errors.
               * -50 to -10:  Major flaws or unverified claims that undermine the solution.
               * -10 to +10:  Uncertain / no strong opinion either way. Use 0 if genuinely neutral.
               * +10 to +50:  Solid reasoning with minor differences from your own verification.
               * +50 to +85:  Strong, well-verified logic with only trivial concerns.
               * +85 to +100: RIGOROUSLY VERIFIED correct — you traced every step and found NO flaws.
               * WARNING: Scores > +90 require absolute proof. Do not give +100 just because they agree with you.

            5. For EACH candidate, provide **structured analysis**:
               * **stance**: your overall position (strong_agree/agree/neutral/disagree/strong_disagree)
               * **claim_assessments**: The 2-3 MOST PIVOTAL claims only, each with verdict (verified/contested/unverified/wrong). Do NOT exhaustively list minor details.
               * **disagreements**: For contested/wrong claims only — what the proposal claims vs. what you believe, with your confidence (high/medium/low).
               * **category_scores**: Break your endorsement into the five axes below (each -100 to +100, same scale as endorsement_weight — negative undermines the proposal, positive supports it).
                  - **correctness**: technical claims true; cited file:line and anchors match reality.
                  - **completeness**: User intent deliverable coverage. Does it cover every section TEAM is tasked to work at (deliverables / sections / output schema)?
                  - **novelty**: findings the peer surfaced that other agents missed; cross-cutting observations score higher than restated single-subsystem claims.
                  - **feasibility**: auto-fix sketches actually compile, match in-tree precedent, don't introduce regressions.
                  - **evidence_quality**: anchors are verbatim and locatable; paraphrased / fabricated anchors drop heavily.
               * If a claim was flagged in a previous round (has a claim_id), include that claim_id so we can track resolution across rounds.

            6. Call `submit_batch_evaluation` with your evaluations.
               * CRITICAL: The `agent_id` field MUST be one of these EXACT strings: [{valid_ids_str}]
               * Do NOT use generic names like \"agent_1\" or \"candidate_1\". Use the exact candidate IDs shown in the candidate tags above.
            7. **Be efficient**: Evaluate all candidates and submit in as few steps as possible. Do not waste iterations on unnecessary tool calls.\n\
            </instructions>\n\n\
            <task>\"{task_description}\"</task>\n\
            {user_updates_section}\
            {own_proposal_section}\
            <candidates>\n\
            {candidates_text}\n\
            </candidates>"
        )
    }

    fn get_proposer_delta_prompt(
        &self,
        _task_description: &str,
        previous_round_matrix: Option<String>,
        previous_own_proposal: Option<&Proposal>,
        previous_score: Option<f32>,
        previous_critiques: Vec<String>,
        user_injections: &[UserInjection],
        structured_feedback: Option<&crate::agents::StructuredFeedback>,
    ) -> String {
        // Delta prompt: only new data. Task description and general instructions
        // are already in the persistent Claude session from round 1.
        let user_updates_section = render_user_updates(user_injections, "proposing");

        let deliberation_brief = if let Some(sf) = structured_feedback {
            let mut brief = String::from("<deliberation_brief>\n");
            if !sf.contested_claims.is_empty() {
                brief.push_str(&format!(
                    "  <contested_claims count=\"{}\">\n",
                    sf.contested_claims.len()
                ));
                for cc in &sf.contested_claims {
                    brief.push_str(&format!(
                        "    <dispute id=\"{}\" evaluator=\"{}\" confidence=\"{:?}\">\n      <your_claim>{}</your_claim>\n      <counter>{}</counter>\n    </dispute>\n",
                        cc.claim_id, cc.evaluator, cc.confidence, cc.what_you_claimed, cc.counter_position
                    ));
                }
                brief.push_str("  </contested_claims>\n");
            }
            if !sf.verified_claims.is_empty() {
                brief.push_str(&format!(
                    "  <verified_claims>{}</verified_claims>\n",
                    sf.verified_claims.join(", ")
                ));
            }
            if let Some(ref cb) = sf.category_breakdown {
                brief.push_str(&format!(
                    "  <category_breakdown>correctness: {:.2} | completeness: {:.2} | novelty: {:.2} | feasibility: {:.2} | evidence_quality: {:.2}</category_breakdown>\n",
                    cb.correctness, cb.completeness, cb.novelty, cb.feasibility, cb.evidence_quality
                ));
            }
            brief.push_str("  <guidance>\n");
            brief.push_str(
                "    For each contested claim: if the counter-argument is correct, FIX your approach; if your original claim is correct, STRENGTHEN your proof.\n",
            );
            if sf.category_breakdown.is_some() {
                brief.push_str("    Focus on your weakest category score.\n");
            }
            brief.push_str("  </guidance>\n");
            brief.push_str("</deliberation_brief>\n\n");
            brief
        } else {
            String::new()
        };

        let matrix_section = if let Some(matrix) = previous_round_matrix {
            format!("<previous_round_matrix>\n{matrix}\n</previous_round_matrix>\n\n")
        } else {
            // Round 1 — fall back to full prompt (shouldn't happen for delta)
            return self.get_proposer_prompt(
                _task_description,
                None,
                previous_own_proposal,
                previous_score,
                previous_critiques,
                user_injections,
                structured_feedback,
            );
        };

        let score_section = if let Some(score) = previous_score {
            let advice = if score < 0.5 {
                "LOW support. Strengthen proofs or rethink approach."
            } else if score < 0.8 {
                "Moderate support. Address critiques."
            } else {
                "High support. Iterate to maintain lead."
            };
            format!("YOUR PREVIOUS SCORE: {score:.2} / 1.0 — {advice}\n\n")
        } else {
            String::new()
        };

        let critiques_section = if !previous_critiques.is_empty() {
            let combined = previous_critiques.join("\n\n");
            format!("<peer_critiques>\n{combined}\n</peer_critiques>\n\n")
        } else {
            String::new()
        };

        format!(
            "Revise your proposal based on new feedback. The task and instructions are unchanged from round 1.\n\n\
            {score_section}\
            {matrix_section}\
            {deliberation_brief}\
            {critiques_section}\
            {user_updates_section}\
            Call `submit_proposal` with your revised `thought_process` and `solution_content` when ready."
        )
    }

    fn get_evaluator_delta_prompt(
        &self,
        _task_description: &str,
        candidates: &[crate::agents::CandidateProposal],
        own_current_proposal: Option<&Proposal>,
        current_round: usize,
        user_injections: &[UserInjection],
    ) -> String {
        // Delta prompt: only new candidates + evaluation focus. Scoring rubric
        // and general instructions are already in the persistent session.
        let valid_ids: Vec<String> = candidates.iter().map(|c| c.id.clone()).collect();
        let valid_ids_str = valid_ids.join(", ");

        let mut candidates_text = String::new();
        let thought_limit = 4000;
        for candidate in candidates {
            let thought_chars = candidate.proposal.thought_process.chars().count();
            let (thoughts_text, truncated) = if thought_chars > thought_limit {
                let truncated_text: String = candidate
                    .proposal
                    .thought_process
                    .chars()
                    .take(thought_limit)
                    .collect();
                (format!("{truncated_text}..."), true)
            } else {
                (candidate.proposal.thought_process.clone(), false)
            };
            candidates_text.push_str(&format!(
                "<candidate id=\"{}\">\nFINAL SOLUTION: {}\nTHOUGHT PROCESS: {}{}\n</candidate>\n\n",
                candidate.id,
                candidate.proposal.content,
                thoughts_text,
                if truncated {
                    format!("\n(Truncated — use `read_proposal(round={current_round}, agent_id=\"{}\")` with offset={thought_limit} to read the rest)", candidate.id)
                } else {
                    String::new()
                }
            ));
        }

        let own_proposal_section = if let Some(p) = own_current_proposal {
            let truncated_thought = if p.thought_process.chars().count() > 500 {
                format!(
                    "{}...",
                    p.thought_process.chars().take(500).collect::<String>()
                )
            } else {
                p.thought_process.clone()
            };
            format!(
                "<own_current_proposal>\nTHOUGHT PROCESS (Preview): {}\nCONTENT: {}\n</own_current_proposal>\n\n",
                truncated_thought, p.content
            )
        } else {
            String::new()
        };

        let user_updates_section = render_user_updates(user_injections, "evaluation");

        let evaluation_focus = if current_round > 1 {
            format!(
                "<evaluation_focus>\n\
                This is round {current_round}. Prioritize dispute resolution over re-evaluation from scratch.\n\
                * Use `search_deliberation` with `rounds: [{prev_round}]` and `verdicts: [\"contested\", \"wrong\"]` to find claims that were disputed last round.\n\
                * For each candidate: check whether previously contested claims have been ADDRESSED or PERSISTED in their updated proposal.\n\
                * **Resolved claims**: If a previously contested claim is now corrected or supported with evidence, mark it as `verified` and reference its `claim_id`.\n\
                * **Still contested**: If a disputed claim persists unchanged, re-assert your disagreement with the same `claim_id` for cross-round tracking.\n\
                * **New claims**: Evaluate new arguments or changes on their own merit.\n\
                * Focus your deepest analysis on HIGH CONTROVERSY candidates (those with wide score variance in previous rounds).\n\
                </evaluation_focus>\n\n",
                prev_round = current_round - 1,
            )
        } else {
            String::new()
        };

        format!(
            "Evaluate updated candidates. Scoring rubric and instructions are unchanged.\n\n\
            {evaluation_focus}\
            {user_updates_section}\
            {own_proposal_section}\
            CANDIDATES: [{valid_ids_str}]\n\
            <candidates>\n\
            {candidates_text}\n\
            </candidates>\n\n\
            Call `submit_batch_evaluation` when ready."
        )
    }

    fn get_summarizer_prompt(&self, task_description: &str, proposal_content: &str) -> String {
        format!(
            "Summarize the following proposal into a concise, comparative overview (approx. 3-5 sentences). \
            Focus on the architectural approach, key trade-offs, and unique features. \
            Do not include generic fluff. This summary will be used to compare against other proposals.\n\n\
            USER TASK: \"{task_description}\"\n\n\
            PROPOSAL CONTENT:\n---\n{proposal_content}"
        )
    }
}

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

    #[test]
    fn test_proposer_prompt_without_matrix() {
        let prompt_set = DefaultPromptSet::new();
        let prompt = prompt_set.get_proposer_prompt("Do task", None, None, None, vec![], &[], None);
        assert!(!prompt.contains("<previous_round_matrix>"));
        assert!(prompt.contains("<task>\"Do task\"</task>"));
    }

    #[test]
    fn test_proposer_prompt_with_matrix() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Table |".to_string();
        let prompt =
            prompt_set.get_proposer_prompt("Do task", Some(matrix), None, None, vec![], &[], None);
        assert!(prompt.contains("<previous_round_matrix>"));
        assert!(prompt.contains("| Table |"));
        assert!(prompt.contains("<instructions>"));
    }

    #[test]
    fn test_proposer_prompt_with_critiques() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Table |".to_string();
        let critiques = vec!["Critique 1".to_string(), "Critique 2".to_string()];
        let prompt = prompt_set.get_proposer_prompt(
            "Do task",
            Some(matrix),
            None,
            None,
            critiques,
            &[],
            None,
        );
        assert!(prompt.contains("<peer_critiques>"));
        assert!(prompt.contains("Critique 1"));
        assert!(prompt.contains("Critique 2"));
    }

    #[test]
    fn test_system_message_phases() {
        let prompt_set = DefaultPromptSet::new();

        let msg = prompt_set.get_system_message("agent", 1, 1, DeliberationPhase::Evaluating);
        assert!(msg.contains("Phase: Evaluating"));

        let msg = prompt_set.get_system_message("agent", 1, 1, DeliberationPhase::ConsensusCheck);
        assert!(msg.contains("Phase: Consensus Check"));
    }

    #[test]
    fn test_batch_evaluator_prompt() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();

        let candidates = vec![CandidateProposal {
            id: "agent_1".to_string(),
            proposal: Proposal {
                thought_process: "Thinking...".to_string(),
                content: "Cont1".to_string(),
                ..Default::default()
            },
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);
        assert!(prompt.contains("<candidate id=\"agent_1\">"));
        assert!(prompt.contains("Cont1"));
        assert!(prompt.contains("<task>\"Task\"</task>"));
    }

    #[test]
    fn test_batch_evaluator_prompt_rubric_contract() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "agent_1".to_string(),
            proposal: Proposal {
                thought_process: "t".to_string(),
                content: "c".to_string(),
                ..Default::default()
            },
        }];
        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);

        for axis in [
            "**correctness**",
            "**completeness**",
            "**novelty**",
            "**feasibility**",
            "**evidence_quality**",
        ] {
            assert!(
                prompt.contains(axis),
                "rubric axis {axis} missing from batch evaluator prompt"
            );
        }

        assert!(
            prompt.contains("User intent deliverable coverage"),
            "completeness must frame user intent as whole-prompt, not subsystem depth"
        );
    }

    #[test]
    fn test_summarizer_prompt() {
        let prompt_set = DefaultPromptSet::new();
        let prompt = prompt_set.get_summarizer_prompt("Task", "Content");
        assert!(prompt.contains("Summarize the following proposal"));
        assert!(prompt.contains("Content"));
    }

    #[test]
    fn test_default_prompt_set_builder() {
        let prompt_set = DefaultPromptSet::new()
            .with_persona("Expert mathematician".to_string())
            .with_textual_feedback(false);

        assert_eq!(prompt_set.persona, Some("Expert mathematician".to_string()));
        assert!(!prompt_set.textual_feedback);
    }

    #[test]
    fn test_system_message_with_persona() {
        let prompt_set = DefaultPromptSet::new()
            .with_persona("Security expert specializing in cryptography".to_string());

        let msg = prompt_set.get_system_message("agent", 1, 3, DeliberationPhase::Proposing);

        assert!(msg.contains("Security expert specializing in cryptography"));
        assert!(msg.contains("Phase: Proposing"));
        assert!(msg.contains("Round 1 of 3"));
    }

    #[test]
    fn test_system_message_proposing_phase() {
        let prompt_set = DefaultPromptSet::new();

        let msg = prompt_set.get_system_message("test_agent", 2, 5, DeliberationPhase::Proposing);

        assert!(msg.contains("test_agent"));
        assert!(msg.contains("Round 2 of 5"));
        assert!(msg.contains("strategy phase=\"proposing\""));
        assert!(msg.contains("Plan First"));
        assert!(msg.contains("Critique Integration"));
    }

    #[test]
    fn test_system_message_evaluating_phase() {
        let prompt_set = DefaultPromptSet::new();

        let msg = prompt_set.get_system_message("evaluator", 3, 5, DeliberationPhase::Evaluating);

        assert!(msg.contains("strategy phase=\"evaluating\""));
        assert!(msg.contains("Vector Alignment"));
        assert!(msg.contains("SKEPTICISM"));
        assert!(msg.contains("Harsh Scoring"));
    }

    #[test]
    fn test_proposer_prompt_with_previous_proposal_low_score() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|-------|-------|\n| A | 0.3 |".to_string();
        let prev_proposal = Proposal {
            thought_process: "My previous thinking...".to_string(),
            content: "Answer: 42".to_string(),
            ..Default::default()
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Solve the equation",
            Some(matrix),
            Some(&prev_proposal),
            Some(0.3), // Low score
            vec![],
            &[],
            None,
        );

        assert!(prompt.contains("<previous_own_proposal>"));
        assert!(prompt.contains("0.30 / 1.0"));
        assert!(prompt.contains("LOW support"));
        assert!(prompt.contains("fundamentally rethink"));
    }

    #[test]
    fn test_proposer_prompt_with_previous_proposal_moderate_score() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|-------|-------|\n| A | 0.6 |".to_string();
        let prev_proposal = Proposal {
            thought_process: "My previous thinking...".to_string(),
            content: "Answer: 42".to_string(),
            ..Default::default()
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Solve the equation",
            Some(matrix),
            Some(&prev_proposal),
            Some(0.6), // Moderate score
            vec![],
            &[],
            None,
        );

        assert!(prompt.contains("Moderate support"));
        assert!(prompt.contains("Address critiques"));
    }

    #[test]
    fn test_proposer_prompt_with_previous_proposal_high_score() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|-------|-------|\n| A | 0.9 |".to_string();
        let prev_proposal = Proposal {
            thought_process: "My previous thinking...".to_string(),
            content: "Answer: 42".to_string(),
            ..Default::default()
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Solve the equation",
            Some(matrix),
            Some(&prev_proposal),
            Some(0.9), // High score
            vec![],
            &[],
            None,
        );

        assert!(prompt.contains("High support"));
        assert!(prompt.contains("leading"));
    }

    #[test]
    fn test_proposer_prompt_with_long_thought_process_truncation() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Table |".to_string();

        // Create a proposal with thought process > 500 chars
        let long_thought = "A".repeat(600);
        let prev_proposal = Proposal {
            thought_process: long_thought.clone(),
            content: "Answer".to_string(),
            ..Default::default()
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Task",
            Some(matrix),
            Some(&prev_proposal),
            None,
            vec![],
            &[],
            None,
        );

        // Should be truncated with "..."
        assert!(prompt.contains("..."));
        // Should NOT contain the full 600 chars
        assert!(!prompt.contains(&long_thought));
    }

    #[test]
    fn test_proposer_prompt_textual_feedback_disabled() {
        let prompt_set = DefaultPromptSet::new().with_textual_feedback(false);
        let matrix = "| Table |".to_string();

        let prompt =
            prompt_set.get_proposer_prompt("Task", Some(matrix), None, None, vec![], &[], None);

        // Should not contain textual feedback instructions
        assert!(!prompt.contains("Critique Integration"));
        assert!(prompt.contains("read_proposal"));
    }

    #[test]
    fn test_batch_evaluator_prompt_with_own_proposal() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();

        let candidates = vec![CandidateProposal {
            id: "other_agent".to_string(),
            proposal: Proposal {
                thought_process: "Their thinking".to_string(),
                content: "Their answer".to_string(),
                ..Default::default()
            },
        }];

        let own_proposal = Proposal {
            thought_process: "My own thinking".to_string(),
            content: "My answer".to_string(),
            ..Default::default()
        };

        let prompt = prompt_set.get_batch_evaluator_prompt(
            "Evaluate these",
            &candidates,
            Some(&own_proposal),
            2,
            &[],
        );

        assert!(prompt.contains("<own_current_proposal>"));
        assert!(prompt.contains("My answer"));
        assert!(prompt.contains("baseline"));
        assert!(prompt.contains("round=2"));
    }

    #[test]
    fn test_batch_evaluator_prompt_truncates_long_thoughts() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();

        // Create a candidate with thought process > 4000 chars (the inline limit)
        let long_thought = "B".repeat(5000);
        let candidates = vec![CandidateProposal {
            id: "verbose_agent".to_string(),
            proposal: Proposal {
                thought_process: long_thought.clone(),
                content: "Answer".to_string(),
                ..Default::default()
            },
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);

        // Should be truncated
        assert!(prompt.contains("..."));
        // Should contain the read_proposal hint for truncated content
        assert!(prompt.contains("read_proposal"));
        // Should NOT contain the full 5000 chars
        assert!(!prompt.contains(&long_thought));
    }

    #[test]
    fn test_batch_evaluator_prompt_inlines_short_thoughts() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();

        // Thoughts under 4000 chars should be fully inlined
        let thought = "Step 1: Check X. Step 2: Verify Y.".to_string();
        let candidates = vec![CandidateProposal {
            id: "concise_agent".to_string(),
            proposal: Proposal {
                thought_process: thought.clone(),
                content: "Result".to_string(),
                ..Default::default()
            },
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);

        // Full thought should appear inline
        assert!(prompt.contains(&thought));
        // Should NOT say "Inline Review" with truncation note for this candidate
        assert!(!prompt.contains("Truncated"));
    }

    #[test]
    fn test_batch_evaluator_prompt_valid_ids() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();

        let candidates = vec![
            CandidateProposal {
                id: "agent_alpha".to_string(),
                proposal: Proposal::default(),
            },
            CandidateProposal {
                id: "agent_beta".to_string(),
                proposal: Proposal::default(),
            },
        ];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);

        // Should list valid candidate IDs
        assert!(prompt.contains("agent_alpha, agent_beta"));
    }

    #[test]
    fn test_system_message_contains_incentives() {
        let prompt_set = DefaultPromptSet::new();
        let msg = prompt_set.get_system_message("agent", 1, 1, DeliberationPhase::Proposing);

        assert!(msg.contains("<incentives>"));
        assert!(msg.contains("Cooperative Failure"));
        assert!(msg.contains("Competitive Success"));
    }

    #[test]
    fn test_system_message_contains_rules() {
        let prompt_set = DefaultPromptSet::new();
        let msg = prompt_set.get_system_message("agent", 1, 1, DeliberationPhase::Proposing);

        assert!(msg.contains("<rules>"));
        assert!(msg.contains("update_scratchpad"));
        assert!(msg.contains("read_proposal"));
    }

    // --- User Injection (Hot-Wire) Tests ---

    #[test]
    fn test_render_user_updates_empty() {
        let result = render_user_updates(&[], "proposing");
        assert!(result.is_empty());
    }

    #[test]
    fn test_render_user_updates_single() {
        use crate::agents::UserInjection;
        let injections = vec![UserInjection {
            message: "Focus on memory safety".to_string(),
            injected_at_round: 2,
            timestamp: 1000,
            ..Default::default()
        }];
        let result = render_user_updates(&injections, "proposing");
        assert!(result.contains("<user_updates>"));
        assert!(result.contains("</user_updates>"));
        assert!(result.contains("<update round=\"2\">Focus on memory safety</update>"));
        assert!(result.contains("Integrate these into your work"));
    }

    #[test]
    fn test_render_user_updates_multiple() {
        use crate::agents::UserInjection;
        let injections = vec![
            UserInjection {
                message: "First clarification".to_string(),
                injected_at_round: 1,
                timestamp: 1000,
                ..Default::default()
            },
            UserInjection {
                message: "Second clarification".to_string(),
                injected_at_round: 3,
                timestamp: 2000,
                ..Default::default()
            },
        ];
        let result = render_user_updates(&injections, "proposing");
        assert!(result.contains("<update round=\"1\">First clarification</update>"));
        assert!(result.contains("<update round=\"3\">Second clarification</update>"));
        // Verify ordering: round 1 before round 3
        let pos1 = result.find("round=\"1\"").unwrap();
        let pos3 = result.find("round=\"3\"").unwrap();
        assert!(pos1 < pos3);
    }

    #[test]
    fn test_render_user_updates_evaluation_context() {
        use crate::agents::UserInjection;
        let injections = vec![UserInjection {
            message: "Check edge cases".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];
        let result = render_user_updates(&injections, "evaluation");
        assert!(result.contains("Factor these into your evaluation criteria"));
        assert!(!result.contains("Integrate these into your work"));
    }

    #[test]
    fn test_proposer_prompt_with_user_injections() {
        use crate::agents::UserInjection;
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Table |".to_string();
        let injections = vec![UserInjection {
            message: "Focus on latency optimization".to_string(),
            injected_at_round: 2,
            timestamp: 1000,
            ..Default::default()
        }];

        let prompt = prompt_set.get_proposer_prompt(
            "Optimize the system",
            Some(matrix),
            None,
            None,
            vec![],
            &injections,
            None,
        );

        assert!(prompt.contains("<user_updates>"));
        assert!(prompt.contains("Focus on latency optimization"));
        // Verify placement: user_updates before <instructions>
        let updates_pos = prompt.find("<user_updates>").unwrap();
        let instructions_pos = prompt.find("<instructions>").unwrap();
        assert!(updates_pos < instructions_pos);
    }

    #[test]
    fn test_proposer_prompt_first_round_with_injections() {
        use crate::agents::UserInjection;
        let prompt_set = DefaultPromptSet::new();
        let injections = vec![UserInjection {
            message: "Also consider Python 3.8".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];

        let prompt = prompt_set.get_proposer_prompt(
            "Build a parser",
            None,
            None,
            None,
            vec![],
            &injections,
            None,
        );

        assert!(prompt.contains("<user_updates>"));
        assert!(prompt.contains("Also consider Python 3.8"));
        // Verify placement: after <task> but before INSTRUCTIONS
        let task_pos = prompt.find("</task>").unwrap();
        let updates_pos = prompt.find("<user_updates>").unwrap();
        let instr_pos = prompt.find("INSTRUCTIONS:").unwrap();
        assert!(task_pos < updates_pos);
        assert!(updates_pos < instr_pos);
    }

    #[test]
    fn test_evaluator_prompt_with_user_injections() {
        use crate::agents::{CandidateProposal, Proposal, UserInjection};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "agent_1".to_string(),
            proposal: Proposal {
                thought_process: "Thinking...".to_string(),
                content: "Solution".to_string(),
                ..Default::default()
            },
        }];
        let injections = vec![UserInjection {
            message: "Prioritize correctness over speed".to_string(),
            injected_at_round: 2,
            timestamp: 1000,
            ..Default::default()
        }];

        let prompt =
            prompt_set.get_batch_evaluator_prompt("Evaluate", &candidates, None, 2, &injections);

        assert!(prompt.contains("<user_updates>"));
        assert!(prompt.contains("Prioritize correctness over speed"));
        assert!(prompt.contains("Factor these into your evaluation criteria"));
        // Verify placement: after <task> and before <candidates>
        let task_pos = prompt.find("</task>").unwrap();
        let updates_pos = prompt.find("<user_updates>").unwrap();
        let candidates_pos = prompt.find("<candidates>").unwrap();
        assert!(task_pos < updates_pos);
        assert!(updates_pos < candidates_pos);
    }

    #[test]
    fn test_evaluator_prompt_evaluation_focus_round1_absent() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "agent_1".to_string(),
            proposal: Proposal {
                thought_process: "Thinking...".to_string(),
                content: "Solution".to_string(),
                ..Default::default()
            },
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);
        // Round 1 should NOT have evaluation_focus
        assert!(!prompt.contains("<evaluation_focus>"));
    }

    #[test]
    fn test_evaluator_prompt_evaluation_focus_round2_present() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "Candidate_A".to_string(),
            proposal: Proposal {
                thought_process: "Revised reasoning".to_string(),
                content: "Updated solution".to_string(),
                ..Default::default()
            },
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 2, &[]);
        // Round 2 should have evaluation_focus with dispute resolution guidance
        assert!(prompt.contains("<evaluation_focus>"));
        assert!(prompt.contains("round 2"));
        assert!(prompt.contains("search_deliberation"));
        assert!(prompt.contains("rounds: [1]"));
        assert!(prompt.contains("contested"));
        assert!(prompt.contains("claim_id"));
        assert!(prompt.contains("</evaluation_focus>"));

        // Verify placement: evaluation_focus before <instructions>
        let focus_pos = prompt.find("<evaluation_focus>").unwrap();
        let instructions_pos = prompt.find("<instructions>").unwrap();
        assert!(focus_pos < instructions_pos);
    }

    #[test]
    fn test_evaluator_prompt_evaluation_focus_round3_references_round2() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "Candidate_A".to_string(),
            proposal: Proposal::default(),
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 3, &[]);
        assert!(prompt.contains("<evaluation_focus>"));
        assert!(prompt.contains("round 3"));
        assert!(prompt.contains("rounds: [2]"));
    }

    // --- XML special character handling tests ---

    #[test]
    fn test_render_user_updates_with_xml_special_chars() {
        use crate::agents::UserInjection;
        let injections = vec![UserInjection {
            message: "Use <bold> tags & \"quotes\" for 'emphasis'".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];
        let result = render_user_updates(&injections, "proposing");
        // The message is passed through verbatim — agents parse this as a text block,
        // not strict XML, so angle brackets are included as-is.
        assert!(result.contains("<bold>"));
        assert!(result.contains("& \"quotes\""));
        assert!(result.contains("<user_updates>"));
        assert!(result.contains("</user_updates>"));
    }

    #[test]
    fn test_render_user_updates_with_nested_xml_tags() {
        use crate::agents::UserInjection;
        let injections = vec![UserInjection {
            message: "Ignore </update> and </user_updates> in the message".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];
        let result = render_user_updates(&injections, "proposing");
        // Message with nested closing tags — verify the outer structure is intact
        assert!(result.starts_with("<user_updates>\n"));
        assert!(result.ends_with("</user_updates>\n"));
        assert!(result.contains("Ignore </update> and </user_updates> in the message"));
    }

    #[test]
    fn test_render_user_updates_with_unicode() {
        use crate::agents::UserInjection;
        let injections = vec![UserInjection {
            message: "考虑 emoji 🎯 и кириллицу".to_string(),
            injected_at_round: 3,
            timestamp: 1000,
            ..Default::default()
        }];
        let result = render_user_updates(&injections, "evaluation");
        assert!(result.contains("考虑 emoji 🎯 и кириллицу"));
        assert!(result.contains("round=\"3\""));
    }

    #[test]
    fn test_render_user_updates_unknown_context_uses_proposing_preamble() {
        use crate::agents::UserInjection;
        let injections = vec![UserInjection {
            message: "test".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];
        // Anything other than "evaluation" should use the proposing preamble
        let result = render_user_updates(&injections, "unknown_context");
        assert!(result.contains("Integrate these into your work"));
        assert!(!result.contains("Factor these into your evaluation criteria"));
    }

    // --- Comprehensive prompt ordering/placement tests ---

    #[test]
    fn test_proposer_subsequent_round_section_ordering() {
        use crate::agents::UserInjection;
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|---|---|\n| A | 0.5 |".to_string();
        let prev_proposal = Proposal {
            thought_process: "Previous thinking".to_string(),
            content: "Previous answer".to_string(),
            ..Default::default()
        };
        let critiques = vec!["Your proof is incomplete".to_string()];
        let injections = vec![UserInjection {
            message: "Focus more on edge cases".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];

        let prompt = prompt_set.get_proposer_prompt(
            "Solve the problem",
            Some(matrix),
            Some(&prev_proposal),
            Some(0.5),
            critiques,
            &injections,
            None,
        );

        // Verify full section ordering:
        // <task> → <previous_round_matrix> → <previous_own_proposal> → <peer_critiques> → <user_updates> → <instructions>
        let task_pos = prompt.find("<task>").unwrap();
        let matrix_pos = prompt.find("<previous_round_matrix>").unwrap();
        let own_pos = prompt.find("<previous_own_proposal>").unwrap();
        let critiques_pos = prompt.find("<peer_critiques>").unwrap();
        let updates_pos = prompt.find("<user_updates>").unwrap();
        let instructions_pos = prompt.find("<instructions>").unwrap();

        assert!(task_pos < matrix_pos, "task before matrix");
        assert!(matrix_pos < own_pos, "matrix before own_proposal");
        assert!(own_pos < critiques_pos, "own_proposal before critiques");
        assert!(critiques_pos < updates_pos, "critiques before user_updates");
        assert!(
            updates_pos < instructions_pos,
            "user_updates before instructions"
        );
    }

    #[test]
    fn test_proposer_subsequent_round_no_injections_omits_user_updates() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Table |".to_string();
        let prompt =
            prompt_set.get_proposer_prompt("Task", Some(matrix), None, None, vec![], &[], None);

        // No injections → no <user_updates> block at all
        assert!(!prompt.contains("<user_updates>"));
        assert!(!prompt.contains("</user_updates>"));
        // But <instructions> should still be present
        assert!(prompt.contains("<instructions>"));
    }

    #[test]
    fn test_proposer_first_round_no_injections_omits_user_updates() {
        let prompt_set = DefaultPromptSet::new();
        let prompt = prompt_set.get_proposer_prompt("Task", None, None, None, vec![], &[], None);

        assert!(!prompt.contains("<user_updates>"));
        assert!(prompt.contains("INSTRUCTIONS:"));
    }

    #[test]
    fn test_evaluator_section_ordering_with_own_proposal_and_injections() {
        use crate::agents::{CandidateProposal, Proposal, UserInjection};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "agent_x".to_string(),
            proposal: Proposal {
                thought_process: "Thinking".to_string(),
                content: "Answer".to_string(),
                ..Default::default()
            },
        }];
        let own_proposal = Proposal {
            thought_process: "My thinking".to_string(),
            content: "My answer".to_string(),
            ..Default::default()
        };
        let injections = vec![UserInjection {
            message: "Consider performance".to_string(),
            injected_at_round: 2,
            timestamp: 1000,
            ..Default::default()
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt(
            "Evaluate task",
            &candidates,
            Some(&own_proposal),
            2,
            &injections,
        );

        // Full ordering: <instructions> → <task> → <user_updates> → <own_current_proposal> → <candidates>
        let instructions_pos = prompt.find("<instructions>").unwrap();
        let task_pos = prompt.find("<task>").unwrap();
        let updates_pos = prompt.find("<user_updates>").unwrap();
        let own_pos = prompt.find("<own_current_proposal>").unwrap();
        let candidates_pos = prompt.find("<candidates>").unwrap();

        assert!(instructions_pos < task_pos, "instructions before task");
        assert!(task_pos < updates_pos, "task before user_updates");
        assert!(updates_pos < own_pos, "user_updates before own_proposal");
        assert!(own_pos < candidates_pos, "own_proposal before candidates");
    }

    #[test]
    fn test_evaluator_no_injections_omits_user_updates() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "agent_1".to_string(),
            proposal: Proposal::default(),
        }];

        let prompt = prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &[]);

        assert!(!prompt.contains("<user_updates>"));
        assert!(prompt.contains("<candidates>"));
    }

    #[test]
    fn test_evaluator_no_own_proposal_omits_section() {
        use crate::agents::{CandidateProposal, Proposal, UserInjection};
        let prompt_set = DefaultPromptSet::new();
        let candidates = vec![CandidateProposal {
            id: "agent_1".to_string(),
            proposal: Proposal::default(),
        }];
        let injections = vec![UserInjection {
            message: "test".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];

        let prompt =
            prompt_set.get_batch_evaluator_prompt("Task", &candidates, None, 1, &injections);

        assert!(prompt.contains("<user_updates>"));
        assert!(!prompt.contains("<own_current_proposal>"));
        // user_updates should appear directly before candidates when no own_proposal
        let updates_end = prompt.find("</user_updates>").unwrap();
        let candidates_pos = prompt.find("<candidates>").unwrap();
        assert!(updates_end < candidates_pos);
    }

    // --- Structured Feedback Tests ---

    #[test]
    fn test_get_proposer_prompt_with_structured_feedback() {
        use crate::agents::{Confidence, ContestedClaim, StructuredFeedback};

        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|---|---|\n| A | 0.7 |".to_string();

        let feedback = StructuredFeedback {
            contested_claims: vec![ContestedClaim {
                claim_id: "claim_42".to_string(),
                what_you_claimed: "Rust is always faster than C".to_string(),
                counter_position: "C can match Rust with careful optimization".to_string(),
                evaluator: "Bob".to_string(),
                confidence: Confidence::High,
            }],
            verified_claims: vec![
                "Memory safety without GC".to_string(),
                "Zero-cost abstractions".to_string(),
            ],
            mean_stance: 0.5,
            evaluator_count: 3,
            category_breakdown: None,
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Compare Rust and C",
            Some(matrix),
            None,
            None,
            vec![],
            &[],
            Some(&feedback),
        );

        // Verify the deliberation brief section is present
        assert!(
            prompt.contains("<deliberation_brief>"),
            "should contain deliberation_brief section"
        );
        assert!(
            prompt.contains("</deliberation_brief>"),
            "should close deliberation_brief section"
        );

        // Verify contested claims appear
        assert!(
            prompt.contains("<contested_claims count=\"1\">"),
            "should have contested_claims with correct count"
        );
        assert!(prompt.contains("claim_42"), "should contain the claim_id");
        assert!(
            prompt.contains("Rust is always faster than C"),
            "should contain the original claim"
        );
        assert!(
            prompt.contains("C can match Rust with careful optimization"),
            "should contain the counter position"
        );
        assert!(prompt.contains("Bob"), "should contain the evaluator name");

        // Verify verified claims appear
        assert!(
            prompt.contains("<verified_claims>"),
            "should contain verified_claims section"
        );
        assert!(
            prompt.contains("Memory safety without GC"),
            "should contain the first verified claim"
        );
        assert!(
            prompt.contains("Zero-cost abstractions"),
            "should contain the second verified claim"
        );

        // Verify structured instructions are present when feedback is provided
        assert!(
            prompt.contains("contested claim"),
            "should contain instructions about contested claims"
        );
    }

    #[test]
    fn test_get_proposer_prompt_without_feedback() {
        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|---|---|\n| A | 0.7 |".to_string();

        let prompt = prompt_set.get_proposer_prompt(
            "Build a parser",
            Some(matrix),
            None,
            None,
            vec![],
            &[],
            None, // No structured feedback
        );

        // Should still produce a valid prompt
        assert!(prompt.contains("<task>"), "should contain task section");
        assert!(
            prompt.contains("Build a parser"),
            "should contain the task description"
        );

        // Should NOT contain structured feedback sections
        assert!(
            !prompt.contains("<deliberation_brief>"),
            "should not contain deliberation_brief when feedback is None"
        );
        assert!(
            !prompt.contains("<contested_claims"),
            "should not contain contested_claims when feedback is None"
        );
        assert!(
            !prompt.contains("<verified_claims>"),
            "should not contain verified_claims when feedback is None"
        );

        // Should still have instructions
        assert!(
            prompt.contains("<instructions>"),
            "should still have instructions section"
        );
    }

    #[test]
    fn test_prompt_reasonable_length() {
        use crate::agents::{
            CandidateProposal, Confidence, ContestedClaim, StructuredFeedback, UserInjection,
        };

        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|-------|-------|\n| A | 0.9 |".to_string();
        let prev_proposal = Proposal {
            thought_process: "X".repeat(500),
            content: "Y".repeat(300),
            ..Default::default()
        };
        let critiques = vec!["Critique A".to_string(), "Critique B".to_string()];
        let injections = vec![UserInjection {
            message: "Consider edge cases".to_string(),
            injected_at_round: 1,
            timestamp: 1000,
            ..Default::default()
        }];
        let feedback = StructuredFeedback {
            contested_claims: vec![ContestedClaim {
                claim_id: "c1".to_string(),
                what_you_claimed: "Claim text".to_string(),
                counter_position: "Counter text".to_string(),
                evaluator: "Eval".to_string(),
                confidence: Confidence::Medium,
            }],
            verified_claims: vec!["Verified claim".to_string()],
            mean_stance: 1.0,
            evaluator_count: 2,
            category_breakdown: None,
        };

        // Test proposer prompt length
        let proposer_prompt = prompt_set.get_proposer_prompt(
            "Solve a complex optimization problem with multiple constraints",
            Some(matrix),
            Some(&prev_proposal),
            Some(0.75),
            critiques,
            &injections,
            Some(&feedback),
        );

        assert!(
            proposer_prompt.chars().count() < 50000,
            "Proposer prompt should not exceed 50000 chars, got {}",
            proposer_prompt.chars().count()
        );

        // Test evaluator prompt length
        let candidates = vec![
            CandidateProposal {
                id: "agent_1".to_string(),
                proposal: Proposal {
                    thought_process: "Z".repeat(3000),
                    content: "Solution 1".to_string(),
                    ..Default::default()
                },
            },
            CandidateProposal {
                id: "agent_2".to_string(),
                proposal: Proposal {
                    thought_process: "W".repeat(3000),
                    content: "Solution 2".to_string(),
                    ..Default::default()
                },
            },
        ];

        let evaluator_prompt = prompt_set.get_batch_evaluator_prompt(
            "Evaluate the optimization proposals",
            &candidates,
            Some(&prev_proposal),
            2,
            &injections,
        );

        assert!(
            evaluator_prompt.chars().count() < 50000,
            "Evaluator prompt should not exceed 50000 chars, got {}",
            evaluator_prompt.chars().count()
        );

        // Test system message length
        let system_msg =
            prompt_set.get_system_message("test_agent", 3, 5, DeliberationPhase::Proposing);

        assert!(
            system_msg.chars().count() < 50000,
            "System message should not exceed 50000 chars, got {}",
            system_msg.chars().count()
        );
    }

    // =========================================================================
    // Structured Feedback with category_breakdown (uncovered path)
    // =========================================================================

    #[test]
    fn test_proposer_prompt_with_category_breakdown() {
        use crate::agents::{CategoryScores, Confidence, ContestedClaim, StructuredFeedback};

        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n|---|---|\n| A | 0.6 |".to_string();

        let feedback = StructuredFeedback {
            contested_claims: vec![ContestedClaim {
                claim_id: "c1".to_string(),
                what_you_claimed: "Claim A".to_string(),
                counter_position: "Counter A".to_string(),
                evaluator: "Evaluator1".to_string(),
                confidence: Confidence::High,
            }],
            verified_claims: vec!["Verified claim 1".to_string()],
            mean_stance: 0.6,
            evaluator_count: 2,
            category_breakdown: Some(CategoryScores {
                correctness: 0.85,
                completeness: 0.70,
                novelty: 0.50,
                feasibility: 0.90,
                evidence_quality: 0.65,
            }),
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Analyze the data",
            Some(matrix),
            None,
            None,
            vec![],
            &[],
            Some(&feedback),
        );

        // Verify category_breakdown section is present
        assert!(
            prompt.contains("<category_breakdown>"),
            "Should contain category_breakdown section"
        );
        assert!(
            prompt.contains("correctness: 0.85"),
            "Should contain correctness score"
        );
        assert!(
            prompt.contains("completeness: 0.70"),
            "Should contain completeness score"
        );
        assert!(
            prompt.contains("novelty: 0.50"),
            "Should contain novelty score"
        );
        assert!(
            prompt.contains("feasibility: 0.90"),
            "Should contain feasibility score"
        );
        assert!(
            prompt.contains("evidence_quality: 0.65"),
            "Should contain evidence_quality score"
        );
        assert!(
            prompt.contains("</category_breakdown>"),
            "Should close category_breakdown section"
        );

        // Verify structured instructions about weakest category
        assert!(
            prompt.contains("weakest category score"),
            "Should contain instruction about weakest category"
        );
    }

    #[test]
    fn test_proposer_prompt_structured_feedback_no_category_breakdown() {
        use crate::agents::StructuredFeedback;

        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |".to_string();

        let feedback = StructuredFeedback {
            contested_claims: vec![],
            verified_claims: vec![],
            mean_stance: 0.5,
            evaluator_count: 1,
            category_breakdown: None, // No category breakdown
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Task",
            Some(matrix),
            None,
            None,
            vec![],
            &[],
            Some(&feedback),
        );

        // Deliberation brief should still appear but without category_breakdown
        assert!(prompt.contains("<deliberation_brief>"));
        assert!(!prompt.contains("<category_breakdown>"));
    }

    #[test]
    fn test_proposer_prompt_structured_feedback_empty_contested_and_verified() {
        use crate::agents::StructuredFeedback;

        let prompt_set = DefaultPromptSet::new();
        let matrix = "| Agent | Score |".to_string();

        let feedback = StructuredFeedback {
            contested_claims: vec![],
            verified_claims: vec![],
            mean_stance: 0.0,
            evaluator_count: 0,
            category_breakdown: None,
        };

        let prompt = prompt_set.get_proposer_prompt(
            "Task",
            Some(matrix),
            None,
            None,
            vec![],
            &[],
            Some(&feedback),
        );

        // With empty contested and verified, those sub-sections should not appear
        assert!(!prompt.contains("<contested_claims"));
        assert!(!prompt.contains("<verified_claims>"));
        // But deliberation_brief wrapper should still be present
        assert!(prompt.contains("<deliberation_brief>"));
    }

    // =========================================================================
    // Batch evaluator — own proposal with long thought truncation
    // =========================================================================

    #[test]
    fn test_batch_evaluator_own_proposal_long_thought_truncation() {
        use crate::agents::{CandidateProposal, Proposal};
        let prompt_set = DefaultPromptSet::new();

        let candidates = vec![CandidateProposal {
            id: "peer_agent".to_string(),
            proposal: Proposal {
                thought_process: "Short thinking".to_string(),
                content: "Peer answer".to_string(),
                ..Default::default()
            },
        }];

        // Own proposal with thought process > 500 chars
        let long_thought = "C".repeat(700);
        let own_proposal = Proposal {
            thought_process: long_thought.clone(),
            content: "My solution".to_string(),
            ..Default::default()
        };

        let prompt = prompt_set.get_batch_evaluator_prompt(
            "Evaluate",
            &candidates,
            Some(&own_proposal),
            1,
            &[],
        );

        assert!(prompt.contains("<own_current_proposal>"));
        // Should be truncated: first 500 chars of "CCC...C" + "..."
        let expected_preview = format!("{}...", &"C".repeat(500));
        assert!(
            prompt.contains(&expected_preview),
            "Long own proposal thought should be truncated to 500 chars + '...'"
        );
        // Should NOT contain the full 700-char thought
        assert!(!prompt.contains(&long_thought));
        assert!(prompt.contains("My solution"));
    }

    // =========================================================================
    // ConsensusCheck phase in system message (the _ => {} arm)
    // =========================================================================

    #[test]
    fn test_system_message_consensus_check_no_strategy() {
        let prompt_set = DefaultPromptSet::new();
        let msg = prompt_set.get_system_message("agent", 1, 3, DeliberationPhase::ConsensusCheck);

        // ConsensusCheck should NOT have a strategy block
        assert!(!msg.contains("strategy phase="));
        // But should still have identity and protocol sections
        assert!(msg.contains("<identity>"));
        assert!(msg.contains("<protocol>"));
        assert!(msg.contains("Phase: Consensus Check"));
    }

    // ─── Delta prompt tests ────────────────────────────────────────────

    #[test]
    fn test_delta_proposer_prompt_omits_task() {
        let ps = DefaultPromptSet::new();
        let matrix = "| Agent | Score |\n| A | 0.8 |".to_string();
        let critiques = vec!["Your math is wrong".to_string()];
        let delta = ps.get_proposer_delta_prompt(
            "Build a spaceship",
            Some(matrix),
            None,
            Some(0.6),
            critiques,
            &[],
            None,
        );
        // Delta should NOT contain the task tag (already in session)
        assert!(
            !delta.contains("<task>"),
            "delta prompt should omit <task> tag"
        );
        // But should contain the matrix and critiques (new data)
        assert!(delta.contains("<previous_round_matrix>"));
        assert!(delta.contains("Your math is wrong"));
        assert!(delta.contains("0.60"));
        assert!(delta.contains("submit_proposal"));
    }

    #[test]
    fn test_delta_proposer_prompt_falls_back_for_round_1() {
        let ps = DefaultPromptSet::new();
        // No matrix = round 1 → delta falls back to full prompt
        let delta =
            ps.get_proposer_delta_prompt("Build a spaceship", None, None, None, vec![], &[], None);
        // Should contain task (full prompt fallback)
        assert!(delta.contains("<task>"));
    }

    #[test]
    fn test_delta_evaluator_prompt_omits_rubric() {
        let ps = DefaultPromptSet::new();
        let candidates = vec![crate::agents::CandidateProposal {
            id: "agent-1".to_string(),
            proposal: crate::agents::Proposal {
                thought_process: "I thought about it".to_string(),
                content: "My solution".to_string(),
                ..Default::default()
            },
        }];
        let delta = ps.get_evaluator_delta_prompt("Build a spaceship", &candidates, None, 2, &[]);
        // Delta should NOT contain the full scoring rubric
        assert!(
            !delta.contains("0-10: Demonstrably wrong"),
            "delta evaluator should omit scoring rubric"
        );
        // But should contain candidates and submit instruction
        assert!(delta.contains("<candidate id=\"agent-1\">"));
        assert!(delta.contains("submit_batch_evaluation"));
        assert!(delta.contains("<evaluation_focus>"));
    }

    #[test]
    fn test_delta_prompt_default_falls_back() {
        // The default trait impl should call the full prompt
        use crate::prompts::PromptSet;

        let ps = DefaultPromptSet::new();
        let full = ps.get_proposer_prompt("task", None, None, None, vec![], &[], None);
        let delta = ps.get_proposer_delta_prompt("task", None, None, None, vec![], &[], None);
        // For round 1 (no matrix), delta falls back to full
        assert_eq!(full, delta);
    }
}