matrixcode-core 0.4.30

MatrixCode Agent Core - Pure logic, no UI
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
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
2015
2016
2017
2018
2019
//! Memory extraction: AI-based and rule-based detection.

use crate::truncate::truncate_chars;
use anyhow::Result;
use serde::Deserialize;

use super::config::*;
use super::entry::{MemoryCategory, MemoryEntry};
use super::manager::AutoMemory;
use super::conversation_pattern::{ConversationPattern, PatternType, PatternSource};
use super::unified_extraction::{UnifiedExtractionResult, ExtractedKeywords};
use crate::compress::FocusPoint;

// ============================================================================
// Memory Extractor Trait
// ============================================================================

/// Trait for memory extraction implementations.
#[async_trait::async_trait]
pub trait MemoryExtractor: Send + Sync {
    /// Extract memories and focus points from conversation text using AI.
    async fn extract(
        &self,
        text: &str,
        session_id: Option<&str>,
        project_path: Option<&str>,
    ) -> Result<ExtractionResult>;

    /// Get the model name used for extraction.
    fn model_name(&self) -> &str;
}

/// Result of memory extraction (memories + focus points + conversation patterns).
#[derive(Debug, Clone)]
pub struct ExtractionResult {
    pub memories: Vec<MemoryEntry>,
    pub focus_points: Vec<FocusPoint>,
    /// Extracted conversation patterns (reference and code patterns).
    pub conversation_patterns: Vec<ConversationPattern>,
}

/// AI-based memory extractor using a fast/cheap model.
pub struct AiMemoryExtractor {
    provider: Box<dyn crate::providers::Provider>,
    model: String,
}

impl AiMemoryExtractor {
    /// Create a new AI memory extractor.
    pub fn new(provider: Box<dyn crate::providers::Provider>, model: String) -> Self {
        Self { provider, model }
    }

    /// Create a minimal extractor (for background tasks, uses simplified prompt).
    /// This is more efficient for non-blocking background extraction.
    pub fn new_minimal(model: String) -> Self {
        // Create a minimal provider that uses the global config
        // This is for background tasks, so we use a simplified approach
        Self {
            provider: crate::create_minimal_provider(&model),
            model,
        }
    }
}

const MEMORY_EXTRACT_SYSTEM_PROMPT: &str = r#"你是记忆提取助手。从对话中提取值得长期记忆的关键信息。

# 记忆类型

<types>
<type>
    <name>decision</name>
    <description>项目或技术选型的决定</description>
    <when_to_save>用户明确做出技术决策时</when_to_save>
    <body_structure>先写决策内容,然后 **Why:** 决策原因,**Context:** 适用场景</body_structure>
</type>
<type>
    <name>preference</name>
    <description>用户习惯或偏好</description>
    <when_to_save>用户表达"我喜欢/习惯/偏好"时</when_to_save>
    <body_structure>先写偏好内容,然后 **Why:** 偏好原因(如有)</body_structure>
</type>
<type>
    <name>solution</name>
    <description>解决问题的具体方法</description>
    <when_to_save>问题成功解决且方法可复用时</when_to_save>
    <body_structure>先写解决方案,然后 **Problem:** 解决的问题,**Key:** 关键步骤</body_structure>
</type>
<type>
    <name>finding</name>
    <description>重要发现或信息</description>
    <when_to_save>发现非显而易见的信息时</when_to_save>
</type>
<type>
    <name>technical</name>
    <description>技术栈或框架信息</description>
    <when_to_save>确认项目使用的技术时</when_to_save>
</type>
<type>
    <name>structure</name>
    <description>项目结构信息</description>
    <when_to_save>发现关键入口或核心文件时</when_to_save>
</type>
</types>

# 不要保存什么到记忆中

- 代码路径、文件名、目录结构 — 可从项目实时获取
- Git 历史、最近更改 — git log/blame 是权威来源
- 临时状态:进行中的任务、当前对话上下文
- 已在 CLAUDE.md/MATRIX.md 中记录的内容
- 错误信息和调试细节 — 问题解决后无需保留

这些排除规则即使当用户要求保存时也适用。
如果他们要求保存临时信息,问:"有什么 surprising 或 non-obvious 的部分?"

# 对话模式提取

当对话文本较长时(超过500字符),还要提取对话中使用的模式:

1. **引用模式 (reference)**:用户如何引用之前的内容
   - 示例:"正如前面所说"、"接着刚才的话题"、"as mentioned"、"previously"

2. **代码模式 (code)**:对话中涉及的代码风格关键词
   - 示例:语言关键词(fn, function, class)、代码块标记(```)

模式提取规则:
- 只提取明确出现的模式,不要推测
- confidence 范围 0.0-1.0,越常见越低(常见模式置信度低)
- 只在文本 > 500 字符时提取模式

# 输出格式

严格 JSON:
{
  "memories": [
    {
      "category": "decision",
      "content": "采用 PostgreSQL 作为主数据库。**Why:** 性能要求和团队经验",
      "importance": 85,
      "keywords": ["PostgreSQL", "数据库", "database"],
      "tags": ["backend", "storage"]
    }
  ],
  "focus_points": [],
  "conversation_patterns": [
    {
      "pattern_type": "reference",
      "pattern": "正如我所说",
      "confidence": 0.8
    },
    {
      "pattern_type": "code",
      "pattern": "fn ",
      "confidence": 0.6
    }
  ]
}

关键词提取:3-5 个核心关键词(技术名词、项目名、关键概念)
标签提取:1-3 个分类标签(backend、frontend、config、auth 等)

只返回 JSON,不要其他解释。"#;

#[async_trait::async_trait]
impl MemoryExtractor for AiMemoryExtractor {
    async fn extract(
        &self,
        text: &str,
        session_id: Option<&str>,
        project_path: Option<&str>,
    ) -> Result<ExtractionResult> {
        use crate::providers::{ChatRequest, Message, MessageContent, Role};

        // Safely truncate to ~4000 chars respecting UTF-8 boundaries
        let truncated = truncate_chars(text, 4000);

        let request = ChatRequest {
            messages: vec![Message {
                role: Role::User,
                content: MessageContent::Text(format!(
                    "请从以下对话中提取值得记忆的关键信息和当前聚焦点:\n\n{}",
                    truncated
                )),
            }],
            tools: vec![],
            system: Some(MEMORY_EXTRACT_SYSTEM_PROMPT.to_string()),
            think: false,
            max_tokens: 512,
            server_tools: vec![],
            enable_caching: false,
        };

        let response = self.provider.chat(request).await?;

        let response_text = response
            .content
            .iter()
            .filter_map(|b| {
                if let crate::providers::ContentBlock::Text { text } = b {
                    Some(text.clone())
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
            .join("");

        parse_memory_response(&response_text, session_id, project_path)
    }

    fn model_name(&self) -> &str {
        &self.model
    }
}

fn parse_memory_response(
    json_text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
) -> Result<ExtractionResult> {
    let cleaned = json_text
        .trim()
        .trim_start_matches("```json")
        .trim_start_matches("```")
        .trim_end_matches("```")
        .trim();

    #[derive(Deserialize)]
    struct MemoryResponse {
        memories: Vec<MemoryItem>,
        #[serde(default)]
        focus_points: Vec<FocusPointItem>,
        #[serde(default)]
        conversation_patterns: Vec<ConversationPatternItem>,
    }

    #[derive(Deserialize)]
    struct MemoryItem {
        category: String,
        content: String,
        #[serde(default)]
        importance: f64,
        #[serde(default)]
        keywords: Vec<String>,
        #[serde(default)]
        tags: Vec<String>,
    }

    #[derive(Deserialize)]
    struct FocusPointItem {
        topic: String,
        #[serde(default)]
        keywords: Vec<String>,
        #[serde(default)]
        entities: Vec<String>,
        #[serde(default)]
        core_question: Option<String>,
        #[serde(default = "default_importance")]
        importance: f32,
        #[serde(default = "default_is_current")]
        is_current: bool,
    }

    #[derive(Deserialize)]
    struct ConversationPatternItem {
        pattern_type: String,
        pattern: String,
        #[serde(default)]
        confidence: f32,
    }

    fn default_importance() -> f32 { 0.7 }
    fn default_is_current() -> bool { true }

    let parsed: MemoryResponse = serde_json::from_str(cleaned)?;

    // Parse memories
    let entries = parsed
        .memories
        .into_iter()
        .filter_map(|item| {
            let category = match item.category.to_lowercase().as_str() {
                "decision" => MemoryCategory::Decision,
                "preference" => MemoryCategory::Preference,
                "solution" => MemoryCategory::Solution,
                "finding" => MemoryCategory::Finding,
                "technical" => MemoryCategory::Technical,
                "structure" => MemoryCategory::Structure,
                _ => return None,
            };

            if item.content.len() < MIN_MEMORY_CONTENT_LENGTH {
                return None;
            }

            let mut entry = MemoryEntry::new(
                category,
                item.content,
                session_id.map(|s| s.to_string()),
                project_path.map(|p| p.to_string()),
            );
            if item.importance > 0.0 {
                entry.importance = item.importance.clamp(0.0, 100.0);
            }
            // Add AI-extracted keywords and tags
            if !item.keywords.is_empty() {
                entry.tags.extend(item.keywords);
            }
            if !item.tags.is_empty() {
                entry.tags.extend(item.tags);
            }
            entry.tags.dedup();

            Some(entry)
        })
        .collect();

    // Parse focus points
    use chrono::Utc;
    use crate::compress::FocusStatus;

    let focus_points = parsed
        .focus_points
        .into_iter()
        .map(|item| {
            let mut focus = FocusPoint::new(
                format!("focus-{}", Utc::now().timestamp()),
                item.topic,
                item.keywords,
                item.entities,
                item.core_question,
                0,
            );
            focus.importance = item.importance.clamp(0.0, 1.0);
            if !item.is_current {
                focus.status = FocusStatus::Suspended;
            }
            focus
        })
        .collect();

    // Parse conversation patterns
    let conversation_patterns = parsed
        .conversation_patterns
        .into_iter()
        .filter_map(|item| {
            // Parse pattern type
            let pattern_type = match item.pattern_type.to_lowercase().as_str() {
                "reference" => PatternType::Reference,
                "code" => PatternType::Code,
                _ => return None, // Skip unknown pattern types
            };

            // Skip empty patterns
            if item.pattern.trim().is_empty() {
                return None;
            }

            // Create pattern with UserConversation source
            let mut pattern = ConversationPattern::new(
                pattern_type,
                item.pattern,
                PatternSource::UserConversation {
                    example: String::new(), // Will be filled when pattern is used
                },
            );

            // Set confidence (default to 0.5 if not specified or out of range)
            pattern.confidence = if item.confidence > 0.0 {
                item.confidence.clamp(0.0, 1.0)
            } else {
                0.5
            };

            Some(pattern)
        })
        .collect();

    Ok(ExtractionResult {
        memories: deduplicate_entries(entries),
        focus_points,
        conversation_patterns,
    })
}

fn deduplicate_entries(entries: Vec<MemoryEntry>) -> Vec<MemoryEntry> {
    let mut seen: Vec<String> = Vec::new();
    entries
        .into_iter()
        .filter(|e| {
            let content_lower = e.content.to_lowercase();
            if seen.iter().any(|s| {
                AutoMemory::calculate_similarity(s, &content_lower) >= SIMILARITY_THRESHOLD
            }) {
                false
            } else {
                seen.push(content_lower);
                true
            }
        })
        .take(MAX_DETECTED_ENTRIES)
        .collect()
}

// ============================================================================
// Rule-based Detection (uses KeywordsConfig)
// ============================================================================

/// Detect memories from text using hard-coded patterns.
pub fn detect_memories_fallback(
    text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
) -> Vec<MemoryEntry> {
    let mut entries = Vec::new();
    let text_lower = text.to_lowercase();

    // Hard-coded patterns for each category
    let patterns = [
        (
            MemoryCategory::Decision,
            ["决定", "选择", "采用", "定下", "decided", "chose"],
        ),
        (
            MemoryCategory::Preference,
            ["偏好", "习惯", "喜欢", "首选", "prefer", "like"],
        ),
        (
            MemoryCategory::Solution,
            ["解决", "修复", "搞定", "改成", "fixed", "solved"],
        ),
        (
            MemoryCategory::Finding,
            ["发现", "原来", "原因", "定位", "found", "reason"],
        ),
        (
            MemoryCategory::Technical,
            ["技术栈", "框架", "用的", "基于", "stack", "using"],
        ),
        (
            MemoryCategory::Structure,
            ["入口", "主文件", "目录", "位于", "entry", "main"],
        ),
    ];

    for (category, keywords) in patterns {
        for keyword in keywords {
            if text_lower.contains(&keyword.to_lowercase()) {
                let content = extract_memory_content(text, keyword);
                if !content.is_empty() && content.len() >= MIN_MEMORY_CONTENT_LENGTH {
                    entries.push(MemoryEntry::new(
                        category,
                        content,
                        session_id.map(|s| s.to_string()),
                        project_path.map(|p| p.to_string()),
                    ));
                }
            }
        }
    }

    deduplicate_entries(entries)
}

/// Detect memories from text (wrapper for fallback).
pub fn detect_memories_from_text(
    text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
) -> Vec<MemoryEntry> {
    detect_memories_fallback(text, session_id, project_path)
}

/// Smart detection: AI-first with rule-based fallback.
///
/// Priority order:
/// 1. AI extraction (if text > 200 chars and extractor available)
/// 2. Rule-based fallback (if AI fails or text too short)
pub async fn detect_memories_smart(
    text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
    extractor: Option<&AiMemoryExtractor>,
) -> ExtractionResult {
    let mode = AiDetectionMode::from_env();
    let text_len = text.len();

    // Determine if we should try AI first
    // Only use AI for text > 200 chars (avoid API overhead for short texts)
    let should_try_ai = mode != AiDetectionMode::Never && extractor.is_some() && text_len > 200;

    // Debug log: show method and model
    let model_name = extractor.map(|e| e.model_name()).unwrap_or("none");
    crate::debug::debug_log().memory_ai_detection(
        model_name,
        0, // Will update after detection
        text_len,
        should_try_ai,
    );

    if should_try_ai && let Some(ex) = extractor {
        if let Ok(result) = ex.extract(text, session_id, project_path).await {
            // AI succeeded - use AI results entirely (skip hardcoded rules)
            // Debug log: AI result
            crate::debug::debug_log().memory_ai_detection(
                ex.model_name(),
                result.memories.len(),
                text_len,
                true,
            );
            return result;
        }
        // AI failed - log and skip rule-based fallback (per user request)
        log::warn!("AI memory extraction failed, skipping detection for this turn");
        return ExtractionResult {
            memories: vec![],
            focus_points: vec![],
            conversation_patterns: vec![],
        };
    }

    // For short texts (< 200 chars), skip detection entirely (per user request)
    // No rule-based fallback
    ExtractionResult {
        memories: vec![],
        focus_points: vec![],
        conversation_patterns: vec![],
    }
}

fn extract_memory_content(text: &str, keyword: &str) -> String {
    let text_lower = text.to_lowercase();
    let keyword_lower = keyword.to_lowercase();

    let pos = match text_lower.find(&keyword_lower) {
        Some(p) => p,
        None => return String::new(),
    };

    // Find sentence containing the keyword
    let start = text[..pos]
        .rfind(['.', '', '\n'])
        .map(|i| i + 1)
        .unwrap_or(0);

    let end = text[pos..]
        .find(['.', '', '\n'])
        .map(|i| pos + i + 1)
        .unwrap_or(text.len());

    let sentence = text[start..end].trim();

    if sentence.len() > MAX_MEMORY_CONTENT_LENGTH {
        sentence[..MAX_MEMORY_CONTENT_LENGTH].to_string()
    } else {
        sentence.to_string()
    }
}

/// Infer category from content.
pub fn infer_category_from_content(content: &str) -> MemoryCategory {
    let lower = content.to_lowercase();

    if lower.contains("决定")
        || lower.contains("选择")
        || lower.contains("采用")
        || lower.contains("decided")
    {
        return MemoryCategory::Decision;
    }
    if lower.contains("喜欢")
        || lower.contains("偏好")
        || lower.contains("习惯")
        || lower.contains("prefer")
    {
        return MemoryCategory::Preference;
    }
    if lower.contains("解决")
        || lower.contains("修复")
        || lower.contains("搞定")
        || lower.contains("fixed")
    {
        return MemoryCategory::Solution;
    }
    if lower.contains("发现")
        || lower.contains("原因")
        || lower.contains("原来")
        || lower.contains("found")
    {
        return MemoryCategory::Finding;
    }
    if lower.contains("技术")
        || lower.contains("框架")
        || lower.contains("")
        || lower.contains("tech")
    {
        return MemoryCategory::Technical;
    }
    if lower.contains("文件")
        || lower.contains("目录")
        || lower.contains("入口")
        || lower.contains("file")
    {
        return MemoryCategory::Structure;
    }

    MemoryCategory::Finding // Default
}

// ============================================================================
// Unified Extraction (One AI Call for All Information)
// ============================================================================

/// Unified extraction system prompt for extracting all information in one call.
const UNIFIED_EXTRACTION_PROMPT: &str = r#"你是信息提取助手。从对话中一次性提取以下信息:

## 1. 长期记忆 (memories)
- decision: 技术决策(如"决定使用 PostgreSQL"、"采用 React 架构")
- preference: 用户偏好(如"我喜欢简洁的代码风格"、"习惯用 VS Code")
- solution: 解决方案(如"通过添加缓存解决了性能问题")
- finding: 重要发现(如"发现内存泄漏的原因")
- technical: 技术栈(如"项目使用 Rust + Tokio")
- structure: 项目结构(如"主入口是 src/main.rs")

## 2. 当前焦点 (focus_points)
- topic: 当前讨论的主题
- keywords: 相关关键词
- entities: 涉及的文件/函数/类名
- core_question: 核心问题(可选)

## 3. 对话模式 (conversation_patterns)
- reference: 引用模式(如"正如前面所说"、"as mentioned"、"previously")
- code: 代码模式(如"fn ", "function", "```", "class ")

## 4. 焦点关键词 (focus_keywords)
- transition: 话题转换词(如"换个话题", "switching", "however", "等等")
- question: 提问词(如"怎么", "how", "为什么", "why", "请问")
- task: 任务词(如"帮我", "implement", "创建", "create", "修复")
- tech: 技术词(如"rust", "数据库", "api", "性能", "优化")

## 输出格式(严格 JSON)

```json
{
  "memories": [
    {
      "category": "decision",
      "content": "采用 PostgreSQL 作为主数据库。**Why:** 性能要求",
      "importance": 85,
      "keywords": ["PostgreSQL", "数据库"],
      "tags": ["backend", "storage"]
    }
  ],
  "focus_points": [
    {
      "topic": "API 设计优化",
      "keywords": ["API", "REST", "性能"],
      "entities": ["api.rs", "handler"],
      "core_question": "如何优化 API 响应时间?",
      "importance": 0.8,
      "is_current": true
    }
  ],
  "conversation_patterns": [
    {
      "pattern_type": "reference",
      "pattern": "正如我所说",
      "confidence": 0.8
    },
    {
      "pattern_type": "code",
      "pattern": "fn ",
      "confidence": 0.6
    }
  ],
  "focus_keywords": {
    "transition": ["换个话题", "switching"],
    "question": ["怎么", "how"],
    "task": ["帮我", "implement"],
    "tech": ["rust", "性能"]
  }
}
```

## 规则
1. 只提取明确出现的信息,不要推测
2. 如果某类信息没有,返回空数组/对象
3. importance 范围:memories 0-100,focus_points 0.0-1.0
4. confidence 范围:0.0-1.0,常见模式置信度较低
5. 关键词提取 3-5 个核心关键词
6. 只返回 JSON,不要其他解释"#;

/// Unified extraction prompt with focus selection.
/// This prompt includes existing focuses and asks AI to select or create focus.
const UNIFIED_EXTRACTION_WITH_FOCUS_PROMPT: &str = r#"你是信息提取和焦点决策助手。从对话中一次性完成以下任务:

## 1. 焦点决策 (focus_decision) - 最重要!

你会收到当前已有的焦点列表。请判断:

### 选择现有焦点
如果最新对话与某个现有焦点匹配:
- selected_focus_id: 该焦点的 ID
- need_new_focus: false
- confidence: 匹配置信度 (0.0-1.0)

### 创建新焦点
如果没有任何现有焦点匹配:
- selected_focus_id: null
- need_new_focus: true
- new_focus_topic: 新焦点主题
- new_core_question: 核心问题
- confidence: 创建置信度

### 判断话题切换
- is_topic_switch: 是否从某焦点切换到另一焦点
- previous_focus_id: 切换前的焦点 ID(如果有)

### 焦点类型 (focus_type)
- problem_solving: 修复 bug、解决错误
- task_execution: 实现功能、完成任务
- knowledge_exploration: 学习、研究、探索
- decision_making: 技术选型、架构设计
- code_optimization: 性能优化、重构
- general: 一般对话

## 2. 长期记忆 (memories)
- decision: 技术决策
- preference: 用户偏好
- solution: 解决方案
- finding: 重要发现
- technical: 技术栈
- structure: 项目结构

## 3. 焦点关键词 (focus_keywords)
- transition: 话题转换词
- question: 提问词
- task: 任务词
- tech: 技术词

## 输出格式(严格 JSON)

```json
{
  "focus_decision": {
    "selected_focus_id": "focus-1",
    "need_new_focus": false,
    "new_focus_topic": null,
    "new_core_question": null,
    "confidence": 0.85,
    "focus_type": "code_optimization",
    "is_topic_switch": true,
    "previous_focus_id": "focus-2",
    "focus_keywords": ["API", "latency", "performance"],
    "related_entities": ["api.rs", "handle_request()"],
    "reasoning": "用户从数据库切换到 API 性能话题"
  },
  "memories": [...],
  "focus_keywords": {
    "transition": ["换个话题"],
    "question": ["怎么"],
    "task": ["优化"],
    "tech": ["api", "性能"]
  }
}
```

## 规则
1. focus_decision 是最重要的输出,必须仔细判断
2. 现有焦点列表会随对话文本一起提供
3. 如果现有焦点都不匹配,必须标记 need_new_focus=true
4. confidence 反映你对决策的确信程度
5. 只返回 JSON,不要其他解释"#;

/// Unified extractor that extracts all information in a single AI call.
///
/// This replaces the separate AiMemoryExtractor and FocusExtractor,
/// reducing API calls and providing consistent extraction.
pub struct UnifiedExtractor {
    provider: Box<dyn crate::providers::Provider>,
    model: String,
}

impl UnifiedExtractor {
    /// Create a new unified extractor.
    pub fn new(provider: Box<dyn crate::providers::Provider>, model: String) -> Self {
        Self { provider, model }
    }

    /// Create a minimal unified extractor for background tasks.
    pub fn new_minimal(model: String) -> Self {
        Self {
            provider: crate::create_minimal_provider(&model),
            model,
        }
    }

    /// Extract all information from conversation text in a single AI call.
    pub async fn extract_unified(
        &self,
        text: &str,
        session_id: Option<&str>,
        project_path: Option<&str>,
    ) -> Result<UnifiedExtractionResult> {
        use crate::providers::{ChatRequest, Message, MessageContent, Role};

        // Safely truncate to ~4000 chars respecting UTF-8 boundaries
        let truncated = truncate_chars(text, 4000);

        let request = ChatRequest {
            messages: vec![Message {
                role: Role::User,
                content: MessageContent::Text(format!(
                    "请从以下对话中提取所有信息:\n\n{}",
                    truncated
                )),
            }],
            tools: vec![],
            system: Some(UNIFIED_EXTRACTION_PROMPT.to_string()),
            think: false,
            max_tokens: 1024, // Larger token limit for unified extraction
            server_tools: vec![],
            enable_caching: false,
        };

        let response = self.provider.chat(request).await?;

        let response_text = response
            .content
            .iter()
            .filter_map(|b| {
                if let crate::providers::ContentBlock::Text { text } = b {
                    Some(text.clone())
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
            .join("");

        parse_unified_response(&response_text, session_id, project_path)
    }

    /// Extract all information WITH focus selection in a single AI call.
    ///
    /// This method receives existing focuses and asks AI to select the best match
    /// or create a new focus if none matches. This ensures focus continuity.
    ///
    /// # Arguments
    /// * `text` - Conversation text to analyze
    /// * `existing_foci` - Current focus points from FocusManager (id, topic, keywords)
    /// * `session_id` - Optional session ID
    /// * `project_path` - Optional project path
    ///
    /// # Returns
    /// UnifiedExtractionResult with focus_decision field populated
    pub async fn extract_unified_with_foci(
        &self,
        text: &str,
        existing_foci: &[(&str, &str, &[String])], // (id, topic, keywords)
        session_id: Option<&str>,
        project_path: Option<&str>,
    ) -> Result<UnifiedExtractionResult> {
        use crate::providers::{ChatRequest, Message, MessageContent, Role};

        // Safely truncate to ~4000 chars respecting UTF-8 boundaries
        let truncated = truncate_chars(text, 4000);

        // Format existing focuses for AI
        let foci_text = if existing_foci.is_empty() {
            "(当前没有现有焦点)".to_string()
        } else {
            let mut foci_list = Vec::new();
            for (id, topic, keywords) in existing_foci {
                foci_list.push(format!(
                    "- ID: {}\n  主题: {}\n  关键词: {}",
                    id,
                    topic,
                    keywords.join(", ")
                ));
            }
            format!("现有焦点列表:\n{}", foci_list.join("\n"))
        };

        let user_prompt = format!(
            "{}\n\n最新对话:\n{}\n\n请判断最新对话与现有焦点的匹配关系,并做出焦点决策。",
            foci_text,
            truncated
        );

        let request = ChatRequest {
            messages: vec![Message {
                role: Role::User,
                content: MessageContent::Text(user_prompt),
            }],
            tools: vec![],
            system: Some(UNIFIED_EXTRACTION_WITH_FOCUS_PROMPT.to_string()),
            think: false,
            max_tokens: 1024,
            server_tools: vec![],
            enable_caching: false,
        };

        let response = self.provider.chat(request).await?;

        let response_text = response
            .content
            .iter()
            .filter_map(|b| {
                if let crate::providers::ContentBlock::Text { text } = b {
                    Some(text.clone())
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
            .join("");

        parse_unified_response_with_focus(&response_text, session_id, project_path)
    }

    /// Get the model name used for extraction.
    pub fn model_name(&self) -> &str {
        &self.model
    }
}

/// Parse unified extraction response from AI.
fn parse_unified_response(
    json_text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
) -> Result<UnifiedExtractionResult> {
    let cleaned = json_text
        .trim()
        .trim_start_matches("```json")
        .trim_start_matches("```")
        .trim_end_matches("```")
        .trim();

    #[derive(Deserialize)]
    struct UnifiedResponse {
        #[serde(default)]
        memories: Vec<MemoryItem>,
        #[serde(default)]
        focus_points: Vec<FocusPointItem>,
        #[serde(default)]
        conversation_patterns: Vec<ConversationPatternItem>,
        #[serde(default)]
        focus_keywords: FocusKeywordsItem,
    }

    #[derive(Deserialize, Default)]
    struct FocusKeywordsItem {
        #[serde(default)]
        transition: Vec<String>,
        #[serde(default)]
        question: Vec<String>,
        #[serde(default)]
        task: Vec<String>,
        #[serde(default)]
        tech: Vec<String>,
    }

    #[derive(Deserialize)]
    struct MemoryItem {
        category: String,
        content: String,
        #[serde(default)]
        importance: f64,
        #[serde(default)]
        keywords: Vec<String>,
        #[serde(default)]
        tags: Vec<String>,
    }

    #[derive(Deserialize)]
    struct FocusPointItem {
        topic: String,
        #[serde(default)]
        keywords: Vec<String>,
        #[serde(default)]
        entities: Vec<String>,
        #[serde(default)]
        core_question: Option<String>,
        #[serde(default = "default_importance")]
        importance: f32,
        #[serde(default = "default_is_current")]
        is_current: bool,
    }

    #[derive(Deserialize)]
    struct ConversationPatternItem {
        pattern_type: String,
        pattern: String,
        #[serde(default)]
        confidence: f32,
    }

    fn default_importance() -> f32 { 0.7 }
    fn default_is_current() -> bool { true }

    let parsed: UnifiedResponse = serde_json::from_str(cleaned)?;

    // Parse memories (reuse existing logic)
    let entries = parsed
        .memories
        .into_iter()
        .filter_map(|item| {
            let category = match item.category.to_lowercase().as_str() {
                "decision" => MemoryCategory::Decision,
                "preference" => MemoryCategory::Preference,
                "solution" => MemoryCategory::Solution,
                "finding" => MemoryCategory::Finding,
                "technical" => MemoryCategory::Technical,
                "structure" => MemoryCategory::Structure,
                _ => return None,
            };

            if item.content.len() < MIN_MEMORY_CONTENT_LENGTH {
                return None;
            }

            let mut entry = MemoryEntry::new(
                category,
                item.content,
                session_id.map(|s| s.to_string()),
                project_path.map(|p| p.to_string()),
            );
            if item.importance > 0.0 {
                entry.importance = item.importance.clamp(0.0, 100.0);
            }
            if !item.keywords.is_empty() {
                entry.tags.extend(item.keywords);
            }
            if !item.tags.is_empty() {
                entry.tags.extend(item.tags);
            }
            entry.tags.dedup();

            Some(entry)
        })
        .collect();

    // Parse focus points (reuse existing logic)
    use chrono::Utc;
    use crate::compress::FocusStatus;

    let focus_points = parsed
        .focus_points
        .into_iter()
        .map(|item| {
            let mut focus = FocusPoint::new(
                format!("focus-{}", Utc::now().timestamp()),
                item.topic,
                item.keywords,
                item.entities,
                item.core_question,
                0,
            );
            focus.importance = item.importance.clamp(0.0, 1.0);
            if !item.is_current {
                focus.status = FocusStatus::Suspended;
            }
            focus
        })
        .collect();

    // Parse conversation patterns (reuse existing logic)
    let conversation_patterns = parsed
        .conversation_patterns
        .into_iter()
        .filter_map(|item| {
            let pattern_type = match item.pattern_type.to_lowercase().as_str() {
                "reference" => PatternType::Reference,
                "code" => PatternType::Code,
                _ => return None,
            };

            if item.pattern.trim().is_empty() {
                return None;
            }

            let mut pattern = ConversationPattern::new(
                pattern_type,
                item.pattern,
                PatternSource::UserConversation {
                    example: String::new(),
                },
            );

            pattern.confidence = if item.confidence > 0.0 {
                item.confidence.clamp(0.0, 1.0)
            } else {
                0.5
            };

            Some(pattern)
        })
        .collect();

    // Parse focus keywords
    let focus_keywords = ExtractedKeywords {
        transition: parsed.focus_keywords.transition,
        question: parsed.focus_keywords.question,
        task: parsed.focus_keywords.task,
        tech: parsed.focus_keywords.tech,
    };

    Ok(UnifiedExtractionResult {
        memories: deduplicate_entries(entries),
        focus_points,
        conversation_patterns,
        focus_keywords,
        focus_decision: None, // Not populated in basic extraction
    })
}

/// Parse unified extraction response with focus decision from AI.
fn parse_unified_response_with_focus(
    json_text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
) -> Result<UnifiedExtractionResult> {
    let cleaned = json_text
        .trim()
        .trim_start_matches("```json")
        .trim_start_matches("```")
        .trim_end_matches("```")
        .trim();

    #[derive(Deserialize)]
    struct UnifiedResponseWithFocus {
        #[serde(default)]
        focus_decision: Option<FocusDecisionItem>,
        #[serde(default)]
        memories: Vec<MemoryItem>,
        #[serde(default)]
        focus_keywords: FocusKeywordsItem,
    }

    #[derive(Deserialize)]
    struct FocusDecisionItem {
        #[serde(default)]
        selected_focus_id: Option<String>,
        #[serde(default)]
        need_new_focus: bool,
        #[serde(default)]
        new_focus_topic: Option<String>,
        #[serde(default)]
        new_core_question: Option<String>,
        #[serde(default)]
        confidence: f32,
        #[serde(default)]
        focus_type: String,
        #[serde(default)]
        is_topic_switch: bool,
        #[serde(default)]
        previous_focus_id: Option<String>,
        #[serde(default)]
        focus_keywords: Vec<String>,
        #[serde(default)]
        related_entities: Vec<String>,
        #[serde(default)]
        reasoning: String,
    }

    #[derive(Deserialize, Default)]
    struct FocusKeywordsItem {
        #[serde(default)]
        transition: Vec<String>,
        #[serde(default)]
        question: Vec<String>,
        #[serde(default)]
        task: Vec<String>,
        #[serde(default)]
        tech: Vec<String>,
    }

    #[derive(Deserialize)]
    struct MemoryItem {
        category: String,
        content: String,
        #[serde(default)]
        importance: f64,
        #[serde(default)]
        keywords: Vec<String>,
        #[serde(default)]
        tags: Vec<String>,
    }

    let parsed: UnifiedResponseWithFocus = serde_json::from_str(cleaned)?;

    // Parse focus decision
    let focus_decision = parsed.focus_decision.map(|item| {
        use super::unified_extraction::{FocusDecision, FocusType};

        let focus_type = match item.focus_type.to_lowercase().as_str() {
            "problem_solving" => FocusType::ProblemSolving,
            "task_execution" => FocusType::TaskExecution,
            "knowledge_exploration" => FocusType::KnowledgeExploration,
            "decision_making" => FocusType::DecisionMaking,
            "code_optimization" => FocusType::CodeOptimization,
            _ => FocusType::General,
        };

        FocusDecision {
            selected_focus_id: item.selected_focus_id,
            need_new_focus: item.need_new_focus,
            new_focus_topic: item.new_focus_topic,
            new_core_question: item.new_core_question,
            confidence: item.confidence.clamp(0.0, 1.0),
            focus_type,
            is_topic_switch: item.is_topic_switch,
            previous_focus_id: item.previous_focus_id,
            focus_keywords: item.focus_keywords,
            related_entities: item.related_entities,
            reasoning: item.reasoning,
        }
    });

    // Parse memories (reuse existing logic)
    let entries = parsed
        .memories
        .into_iter()
        .filter_map(|item| {
            let category = match item.category.to_lowercase().as_str() {
                "decision" => MemoryCategory::Decision,
                "preference" => MemoryCategory::Preference,
                "solution" => MemoryCategory::Solution,
                "finding" => MemoryCategory::Finding,
                "technical" => MemoryCategory::Technical,
                "structure" => MemoryCategory::Structure,
                _ => return None,
            };

            if item.content.len() < MIN_MEMORY_CONTENT_LENGTH {
                return None;
            }

            let mut entry = MemoryEntry::new(
                category,
                item.content,
                session_id.map(|s| s.to_string()),
                project_path.map(|p| p.to_string()),
            );
            if item.importance > 0.0 {
                entry.importance = item.importance.clamp(0.0, 100.0);
            }
            if !item.keywords.is_empty() {
                entry.tags.extend(item.keywords);
            }
            if !item.tags.is_empty() {
                entry.tags.extend(item.tags);
            }
            entry.tags.dedup();

            Some(entry)
        })
        .collect();

    // Parse focus keywords
    let focus_keywords = ExtractedKeywords {
        transition: parsed.focus_keywords.transition,
        question: parsed.focus_keywords.question,
        task: parsed.focus_keywords.task,
        tech: parsed.focus_keywords.tech,
    };

    Ok(UnifiedExtractionResult {
        memories: deduplicate_entries(entries),
        focus_points: Vec::new(), // Not used in focus selection mode
        conversation_patterns: Vec::new(), // Not used in focus selection mode
        focus_keywords,
        focus_decision,
    })
}

/// Smart unified extraction: AI-first with graceful fallback.
///
/// Uses UnifiedExtractor for single API call extraction.
pub async fn detect_unified_smart(
    text: &str,
    session_id: Option<&str>,
    project_path: Option<&str>,
    extractor: Option<&UnifiedExtractor>,
) -> UnifiedExtractionResult {
    let mode = AiDetectionMode::from_env();
    let text_len = text.len();

    // Only use AI for text > 200 chars
    let should_try_ai = mode != AiDetectionMode::Never && extractor.is_some() && text_len > 200;

    if should_try_ai && let Some(ex) = extractor {
        if let Ok(result) = ex.extract_unified(text, session_id, project_path).await {
            return result;
        }
        // AI failed - skip detection for this turn
        log::warn!("Unified extraction failed, skipping detection for this turn");
    }

    // Return empty result for short texts or failed AI
    UnifiedExtractionResult::default()
}

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

    // =========================================================================
    // Conversation Pattern Parsing Tests
    // =========================================================================

    #[test]
    fn test_parse_memory_response_with_patterns() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "正如我所说",
                    "confidence": 0.8
                },
                {
                    "pattern_type": "code",
                    "pattern": "fn ",
                    "confidence": 0.6
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        assert_eq!(result.memories.len(), 0);
        assert_eq!(result.focus_points.len(), 0);
        assert_eq!(result.conversation_patterns.len(), 2);

        // Check first pattern (reference)
        let ref_pattern = &result.conversation_patterns[0];
        assert_eq!(ref_pattern.pattern_type, PatternType::Reference);
        assert_eq!(ref_pattern.pattern, "正如我所说");
        assert_eq!(ref_pattern.confidence, 0.8);
        assert!(ref_pattern.is_active);

        // Check second pattern (code)
        let code_pattern = &result.conversation_patterns[1];
        assert_eq!(code_pattern.pattern_type, PatternType::Code);
        assert_eq!(code_pattern.pattern, "fn ");
        assert_eq!(code_pattern.confidence, 0.6);
    }

    #[test]
    fn test_parse_memory_response_patterns_default_confidence() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "as mentioned"
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        assert_eq!(result.conversation_patterns.len(), 1);

        // Default confidence should be 0.5
        let pattern = &result.conversation_patterns[0];
        assert_eq!(pattern.confidence, 0.5);
    }

    #[test]
    fn test_parse_memory_response_patterns_empty() {
        let json = r#"{
            "memories": [],
            "focus_points": []
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        assert_eq!(result.conversation_patterns.len(), 0);
    }

    #[test]
    fn test_parse_memory_response_patterns_invalid_type() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "invalid_type",
                    "pattern": "test",
                    "confidence": 0.5
                },
                {
                    "pattern_type": "reference",
                    "pattern": "valid pattern",
                    "confidence": 0.7
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        // Invalid pattern type should be skipped
        assert_eq!(result.conversation_patterns.len(), 1);
        assert_eq!(result.conversation_patterns[0].pattern, "valid pattern");
    }

    #[test]
    fn test_parse_memory_response_patterns_empty_string() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "",
                    "confidence": 0.5
                },
                {
                    "pattern_type": "code",
                    "pattern": "   ",
                    "confidence": 0.5
                },
                {
                    "pattern_type": "reference",
                    "pattern": "valid",
                    "confidence": 0.8
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        // Empty patterns should be skipped
        assert_eq!(result.conversation_patterns.len(), 1);
        assert_eq!(result.conversation_patterns[0].pattern, "valid");
    }

    #[test]
    fn test_parse_memory_response_patterns_confidence_clamped() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "test1",
                    "confidence": 1.5
                },
                {
                    "pattern_type": "code",
                    "pattern": "test2",
                    "confidence": -0.3
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        assert_eq!(result.conversation_patterns.len(), 2);

        // Confidence should be clamped to [0.0, 1.0]
        assert_eq!(result.conversation_patterns[0].confidence, 1.0);
        // Negative confidence should use default 0.5 (since <= 0.0 triggers default)
        assert_eq!(result.conversation_patterns[1].confidence, 0.5);
    }

    #[test]
    fn test_parse_memory_response_patterns_source() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "PR #123",
                    "confidence": 0.9
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        let pattern = &result.conversation_patterns[0];

        // Source should be UserConversation
        match &pattern.source {
            PatternSource::UserConversation { example } => {
                assert_eq!(example, "");
            }
            _ => panic!("Expected UserConversation source"),
        }
    }

    #[test]
    fn test_parse_memory_response_backward_compatible() {
        // Old format without conversation_patterns should still work
        let json = r#"{
            "memories": [
                {
                    "category": "decision",
                    "content": "使用 Rust 作为主要语言",
                    "importance": 80,
                    "keywords": ["Rust"],
                    "tags": ["backend"]
                }
            ],
            "focus_points": [
                {
                    "topic": "API设计",
                    "keywords": ["API", "REST"],
                    "importance": 0.8
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();
        assert_eq!(result.memories.len(), 1);
        assert_eq!(result.focus_points.len(), 1);
        assert_eq!(result.conversation_patterns.len(), 0);

        // Verify memory content
        assert_eq!(result.memories[0].category, MemoryCategory::Decision);
        assert!(result.memories[0].content.contains("Rust"));
    }

    #[test]
    fn test_parse_memory_response_with_code_block_markers() {
        // JSON wrapped in code block markers should still parse
        let json = r#"```json
{
    "memories": [],
    "focus_points": [],
    "conversation_patterns": [
        {
            "pattern_type": "code",
            "pattern": "```",
            "confidence": 0.7
        }
    ]
}
```"#;

        let result = parse_memory_response(json, None, None).unwrap();
        assert_eq!(result.conversation_patterns.len(), 1);
        assert_eq!(result.conversation_patterns[0].pattern, "```");
    }

    // =========================================================================
    // ExtractionResult Tests
    // =========================================================================

    #[test]
    fn test_extraction_result_has_patterns_field() {
        let result = ExtractionResult {
            memories: vec![],
            focus_points: vec![],
            conversation_patterns: vec![
                ConversationPattern::new(
                    PatternType::Reference,
                    "test pattern",
                    PatternSource::Manual,
                ),
            ],
        };

        assert_eq!(result.conversation_patterns.len(), 1);
    }

    #[test]
    fn test_extraction_result_clone() {
        let result = ExtractionResult {
            memories: vec![],
            focus_points: vec![],
            conversation_patterns: vec![
                ConversationPattern::new(
                    PatternType::Code,
                    "fn test()",
                    PatternSource::Manual,
                ),
            ],
        };

        let cloned = result.clone();
        assert_eq!(cloned.conversation_patterns.len(), 1);
        assert_eq!(cloned.conversation_patterns[0].pattern, "fn test()");
    }

    #[test]
    fn test_extraction_result_empty_patterns() {
        // Test ExtractionResult with empty patterns
        let result = ExtractionResult {
            memories: vec![],
            focus_points: vec![],
            conversation_patterns: vec![],
        };

        assert!(result.conversation_patterns.is_empty());
        assert!(result.memories.is_empty());
        assert!(result.focus_points.is_empty());
    }

    // =========================================================================
    // AI Prompt Validation Tests
    // =========================================================================

    #[test]
    fn test_memory_extract_prompt_contains_patterns_guidance() {
        // Verify the prompt includes conversation pattern extraction guidance
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("对话模式提取"),
            "Prompt should contain pattern extraction guidance"
        );
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("reference"),
            "Prompt should mention reference pattern type"
        );
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("code"),
            "Prompt should mention code pattern type"
        );
    }

    #[test]
    fn test_memory_extract_prompt_contains_trigger_condition() {
        // Verify the prompt mentions >500 chars trigger condition
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("500"),
            "Prompt should mention 500 chars trigger condition"
        );
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("> 500") || MEMORY_EXTRACT_SYSTEM_PROMPT.contains("超过500"),
            "Prompt should specify > 500 chars condition"
        );
    }

    #[test]
    fn test_memory_extract_prompt_contains_output_format() {
        // Verify the prompt shows correct JSON output format with patterns
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("conversation_patterns"),
            "Prompt should show conversation_patterns in output format"
        );
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("pattern_type"),
            "Prompt should show pattern_type field"
        );
        assert!(
            MEMORY_EXTRACT_SYSTEM_PROMPT.contains("confidence"),
            "Prompt should show confidence field"
        );
    }

    // =========================================================================
    // Integration Tests - Combined Extraction
    // =========================================================================

    #[test]
    fn test_parse_memory_response_full_integration() {
        // Test complete extraction with memories, focus_points, and patterns together
        let json = r#"{
            "memories": [
                {
                    "category": "decision",
                    "content": "使用 Rust 作为主要语言。**Why:** 性能要求",
                    "importance": 85,
                    "keywords": ["Rust"],
                    "tags": ["backend"]
                }
            ],
            "focus_points": [
                {
                    "topic": "API设计",
                    "keywords": ["API", "REST"],
                    "entities": ["User", "Order"],
                    "importance": 0.8
                }
            ],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "正如我所说",
                    "confidence": 0.9
                },
                {
                    "pattern_type": "code",
                    "pattern": "fn ",
                    "confidence": 0.7
                }
            ]
        }"#;

        let result = parse_memory_response(json, Some("session-123"), Some("/project/path")).unwrap();

        // Verify all three components
        assert_eq!(result.memories.len(), 1);
        assert_eq!(result.focus_points.len(), 1);
        assert_eq!(result.conversation_patterns.len(), 2);

        // Check memory
        assert_eq!(result.memories[0].category, MemoryCategory::Decision);
        assert!(result.memories[0].content.contains("Rust"));

        // Check focus point
        assert_eq!(result.focus_points[0].topic, "API设计");

        // Check patterns
        assert_eq!(result.conversation_patterns[0].pattern_type, PatternType::Reference);
        assert_eq!(result.conversation_patterns[1].pattern_type, PatternType::Code);
    }

    #[test]
    fn test_parse_memory_response_mixed_valid_invalid_patterns() {
        // Test with mix of valid and invalid patterns
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "valid pattern 1",
                    "confidence": 0.8
                },
                {
                    "pattern_type": "unknown_type",
                    "pattern": "should be skipped",
                    "confidence": 0.5
                },
                {
                    "pattern_type": "code",
                    "pattern": "fn valid",
                    "confidence": 0.6
                },
                {
                    "pattern_type": "reference",
                    "pattern": "",
                    "confidence": 0.9
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();

        // Should only have 2 valid patterns
        assert_eq!(result.conversation_patterns.len(), 2);
        assert_eq!(result.conversation_patterns[0].pattern, "valid pattern 1");
        assert_eq!(result.conversation_patterns[1].pattern, "fn valid");
    }

    #[test]
    fn test_parse_memory_response_patterns_with_session_and_project() {
        // Verify session_id and project_path are passed through correctly
        // (patterns don't use them, but the function accepts them)
        let json = r#"{
            "memories": [
                {
                    "category": "technical",
                    "content": "Using PostgreSQL database",
                    "importance": 70,
                    "keywords": ["PostgreSQL"],
                    "tags": ["database"]
                }
            ],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "as mentioned",
                    "confidence": 0.7
                }
            ]
        }"#;

        let result = parse_memory_response(json, Some("test-session"), Some("/test/project")).unwrap();

        // Memory should have source_session and project_path
        assert_eq!(result.memories[0].source_session, Some("test-session".to_string()));
        assert_eq!(result.memories[0].project_path, Some("/test/project".to_string()));

        // Pattern should be parsed correctly
        assert_eq!(result.conversation_patterns.len(), 1);
    }

    #[test]
    fn test_parse_memory_response_all_pattern_types() {
        // Test both supported pattern types
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "previously discussed",
                    "confidence": 0.8
                },
                {
                    "pattern_type": "Reference",
                    "pattern": "case insensitive",
                    "confidence": 0.7
                },
                {
                    "pattern_type": "CODE",
                    "pattern": "function ",
                    "confidence": 0.6
                },
                {
                    "pattern_type": "code",
                    "pattern": "class ",
                    "confidence": 0.5
                }
            ]
        }"#;

        let result = parse_memory_response(json, None, None).unwrap();

        // All should be parsed (case-insensitive pattern_type)
        assert_eq!(result.conversation_patterns.len(), 4);

        // Check types
        assert_eq!(result.conversation_patterns[0].pattern_type, PatternType::Reference);
        assert_eq!(result.conversation_patterns[1].pattern_type, PatternType::Reference);
        assert_eq!(result.conversation_patterns[2].pattern_type, PatternType::Code);
        assert_eq!(result.conversation_patterns[3].pattern_type, PatternType::Code);
    }

    #[test]
    fn test_extraction_result_debug_trait() {
        // Test that ExtractionResult implements Debug
        let result = ExtractionResult {
            memories: vec![],
            focus_points: vec![],
            conversation_patterns: vec![
                ConversationPattern::new(
                    PatternType::Reference,
                    "test",
                    PatternSource::Manual,
                ),
            ],
        };

        let debug_str = format!("{:?}", result);
        assert!(debug_str.contains("ExtractionResult"));
        assert!(debug_str.contains("conversation_patterns"));
    }

    // =========================================================================
    // Unified Extraction Tests
    // =========================================================================

    #[test]
    fn test_parse_unified_response_full() {
        let json = r#"{
            "memories": [
                {
                    "category": "decision",
                    "content": "使用 Rust 作为主要语言",
                    "importance": 85,
                    "keywords": ["Rust"],
                    "tags": ["backend"]
                }
            ],
            "focus_points": [
                {
                    "topic": "API设计",
                    "keywords": ["API", "REST"],
                    "entities": ["User", "Order"],
                    "core_question": "如何优化 API?",
                    "importance": 0.8,
                    "is_current": true
                }
            ],
            "conversation_patterns": [
                {
                    "pattern_type": "reference",
                    "pattern": "正如我所说",
                    "confidence": 0.8
                }
            ],
            "focus_keywords": {
                "transition": ["换个话题"],
                "question": ["怎么"],
                "task": ["帮我"],
                "tech": ["rust"]
            }
        }"#;

        let result = parse_unified_response(json, Some("session-123"), Some("/project")).unwrap();

        // Verify all components
        assert_eq!(result.memories.len(), 1);
        assert_eq!(result.memories[0].category, MemoryCategory::Decision);
        assert!(result.memories[0].content.contains("Rust"));

        assert_eq!(result.focus_points.len(), 1);
        assert_eq!(result.focus_points[0].topic, "API设计");

        assert_eq!(result.conversation_patterns.len(), 1);
        assert_eq!(result.conversation_patterns[0].pattern_type, PatternType::Reference);

        assert!(!result.focus_keywords.is_empty());
        assert_eq!(result.focus_keywords.transition.len(), 1);
        assert_eq!(result.focus_keywords.question.len(), 1);
        assert_eq!(result.focus_keywords.task.len(), 1);
        assert_eq!(result.focus_keywords.tech.len(), 1);
    }

    #[test]
    fn test_parse_unified_response_empty() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [],
            "focus_keywords": {
                "transition": [],
                "question": [],
                "task": [],
                "tech": []
            }
        }"#;

        let result = parse_unified_response(json, None, None).unwrap();

        assert!(result.memories.is_empty());
        assert!(result.focus_points.is_empty());
        assert!(result.conversation_patterns.is_empty());
        assert!(result.focus_keywords.is_empty());
    }

    #[test]
    fn test_parse_unified_response_partial() {
        // Test with only memories (no focus_keywords)
        let json = r#"{
            "memories": [
                {
                    "category": "technical",
                    "content": "使用 PostgreSQL 作为主数据库存储",
                    "importance": 70
                }
            ]
        }"#;

        let result = parse_unified_response(json, None, None).unwrap();

        assert_eq!(result.memories.len(), 1);
        assert!(result.focus_points.is_empty());
        assert!(result.conversation_patterns.is_empty());
        assert!(result.focus_keywords.is_empty());
    }

    #[test]
    fn test_parse_unified_response_with_code_block() {
        let json = r#"```json
{
    "memories": [],
    "focus_points": [],
    "conversation_patterns": [],
    "focus_keywords": {
        "transition": ["switching"],
        "question": [],
        "task": [],
        "tech": []
    }
}
```"#;

        let result = parse_unified_response(json, None, None).unwrap();

        assert_eq!(result.focus_keywords.transition.len(), 1);
        assert_eq!(result.focus_keywords.transition[0], "switching");
    }

    #[test]
    fn test_unified_extraction_result_default() {
        let result = UnifiedExtractionResult::default();
        assert!(result.memories.is_empty());
        assert!(result.focus_points.is_empty());
        assert!(result.conversation_patterns.is_empty());
        assert!(result.focus_keywords.is_empty());
    }

    #[test]
    fn test_unified_extraction_prompt_contains_all_sections() {
        // Verify the unified prompt contains all extraction sections
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("长期记忆"));
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("当前焦点"));
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("对话模式"));
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("焦点关键词"));
    }

    #[test]
    fn test_unified_extraction_prompt_contains_keyword_categories() {
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("transition"));
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("question"));
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("task"));
        assert!(UNIFIED_EXTRACTION_PROMPT.contains("tech"));
    }

    #[test]
    fn test_parse_unified_response_keywords_merged() {
        let json = r#"{
            "memories": [],
            "focus_points": [],
            "conversation_patterns": [],
            "focus_keywords": {
                "transition": ["换个话题", "switching", "however"],
                "question": ["怎么", "how", "为什么"],
                "task": ["帮我", "implement", "创建"],
                "tech": ["rust", "数据库", "api"]
            }
        }"#;

        let result = parse_unified_response(json, None, None).unwrap();

        assert_eq!(result.focus_keywords.transition.len(), 3);
        assert_eq!(result.focus_keywords.question.len(), 3);
        assert_eq!(result.focus_keywords.task.len(), 3);
        assert_eq!(result.focus_keywords.tech.len(), 3);
        assert_eq!(result.focus_keywords.total_count(), 12);
    }
}