ragrig 0.9.1

Trait-driven RAG framework for research and prototyping. Zero dependencies, hot-swap any agent at runtime, hybrid BM25+vector retrieval. Default build compiles with cargo build --release and nothing else.
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
use anyhow::Result;
use clap::Parser;
use ragrig::{
    ChatAgentSpec, ChunkConfig, DocumentParser, DocumentParsers, DocumentType,
    EmbedderSpec, EpubParserBackend, FsSessionStore, GenerationParams,
    HistoryStrategy, LogHistory, PaperResult, PdfParserBackend, RagAgent, RagrigError,
    ScoredChunk, SessionId, SessionStore, SummaryHistory,
    Turn, TurnRole,
    collect_documents, collect_documents_with_stats, download_and_ingest_url, embed_documents,
    search_arxiv, search_semantic_scholar,
};
use ragrig::types::{Args, ContextSizeMode, FileHashEntry, Provider};
use ragrig::documents::{HashMetadata, get_document_file_hashes, get_changed_documents, update_file_hashes};
use ragrig::vector::{get_embeddings_file_path, remove_deleted_embeddings};
use ragrig::{parsers, store};
use rustyline::DefaultEditor;
use rustyline::error::ReadlineError;
use std::fs;
use std::io::{Write, stdout};
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

// ── Session: carries all context between REPL cycles ──────────────────────

/// Persistent state shared across the REPL loop.
///
/// Holds trait-object agents for every pipeline stage — chat, memory,
/// and embeddings — plus the vector store, parser registry, and
/// conversation log.  Agents are `Box<dyn Trait>` so they can be
/// hot-swapped at runtime via `/chat`, `/memory`, and `/embed`.
///
/// # Construction
///
/// Sessions are built by [`bootstrap`], which parses CLI args, creates
/// all agents from their spec enums, indexes documents, and opens or
/// creates the vector store.
///
/// ```ignore
/// let args = Args::parse();
/// let session = bootstrap(args).await?;
/// // session enters the REPL loop
/// ```
struct Session {
    args: Args,
    agent: RagAgent,
    embeddings_file_path: PathBuf,
    last_results: Vec<ScoredChunk>,
    last_search_results: Vec<PaperResult>,
    rl: DefaultEditor,
    history_path: PathBuf,
    http_client: reqwest::Client,
    prompt_memory: Vec<Turn>,
    /// Persistent session store — saves/loads full chat sessions.
    session_store: Box<dyn SessionStore>,
    /// Current session id for auto‑save.
    session_id: SessionId,
    /// History diffusion strategy — blends past session content into the chat prompt.
    /// `None` = no diffusion.  `Some(LogHistory)` = raw transcript of last session.
    /// Set via `/memory log` or `/memory summary`.
    history_strategy: Option<Box<dyn HistoryStrategy>>,
    /// Document parser registry — dispatches `.parse()` to the right
    /// backend based on file extension.  Built once at startup.
    doc_parsers: DocumentParsers,
    /// Currently active PDF parser backend.
    pdf_parser: PdfParserBackend,
    /// EPUB parser backend (currently only one option).
    epub_parser: EpubParserBackend,
    /// Controls context-overflow behaviour: `Auto` retries with fewer chunks,
    /// `Forced` treats overflow as a fatal error.
    context_size_forced: ContextSizeMode,
}

// ── Command: parsed user input ────────────────────────────────────────────

/// Commands recognized by the REPL.  Plain text without a `/` prefix is
/// treated as a RAG query (`RagQuery`).
enum Command {
    #[allow(dead_code)]
    
    Download(String),
    GetPapers(String),
    Help,
    Scholar(String),
    SearchArxiv(String),
    ExtractRefs(String),
    Chat(String),
    Search(String),
    Embed(String),
    Memory(String),
    Hist(String),
    Parser(String),
    Prompt(String),
    RagQuery(String),
    Unknown(String),
    Exit,
}

// ── Bootstrap: build agents, index documents, enter REPL ───────────────────

/// Linear initialisation of the entire RAG session.
///
/// 1. Builds the chat agent, embedding backend, and memory agent from
///    CLI args / env vars via their `*Spec::parse().build()` factories.
/// 2. Scans the document folder, computes file hashes, and opens or
///    creates the vector store.
/// 3. Incrementally indexes new or changed documents (or builds from
///    scratch on first run).
/// 4. Constructs a [`Session`] carrying all state needed by the REPL.
///
/// This is the only place where the full pipeline is assembled —
/// downstream code just calls `session.execute(cmd).await`.
///
/// Filter the parser list to include the selected PDF backend as primary,
/// plus a panic-fallback (kreuzberg when available, otherwise sloppy-pdf).
fn filtered_parsers(pdf: &PdfParserBackend, _sloppy_pdf: bool) -> Vec<Box<dyn DocumentParser>> {
    #[allow(deprecated)]
    let selected_pdf = match pdf {
        #[cfg(feature = "kreuzberg")]
        PdfParserBackend::Kreuzberg => "kreuzberg",
        PdfParserBackend::Unpdf => "unpdf",
        PdfParserBackend::Sink => "pdfsink",
        PdfParserBackend::Extract => "pdf-extract",
        PdfParserBackend::Internal => "sloppy-pdf",
        PdfParserBackend::Vision => "vision-pdf",
    };
    let fallback = {
        #[cfg(feature = "kreuzberg")]
        { "kreuzberg" }
        #[cfg(not(feature = "kreuzberg"))]
        { "sloppy-pdf" }
    };
    let mut list = parsers::build_parsers();
    list.retain(|p| {
        if p.extensions().contains(&"pdf") {
            // Keep the selected parser plus the fallback (don't duplicate if selected == fallback).
            p.name() == selected_pdf || p.name() == fallback
        } else {
            true
        }
    });
    list
}

async fn bootstrap(args: Args) -> Result<Session> {
    // Build generation params from CLI args.
    let chat_params = GenerationParams {
        temperature: args.temperature,
        top_p: args.top_p,
        max_tokens: args.max_tokens,
        seed: args.seed,
    };
    if chat_params.temperature.is_some()
        || chat_params.top_p.is_some()
        || chat_params.max_tokens.is_some()
        || chat_params.seed.is_some()
    {
        print!("Params:");
        if let Some(t) = chat_params.temperature {
            print!(" temperature={:.2}", t);
        }
        if let Some(p) = chat_params.top_p {
            print!(" top_p={:.2}", p);
        }
        if let Some(n) = chat_params.max_tokens {
            print!(" max_tokens={}", n);
        }
        if let Some(s) = chat_params.seed {
            print!(" seed={}", s);
        }
        println!();
    }

    // Build the initial chat agent from CLI args.
    let initial_spec = match args.provider {
        Provider::Ollama => ChatAgentSpec::ollama(args.model.clone(), chat_params.clone()),
        Provider::Deepseek => ChatAgentSpec::deepseek(
            args.deepseek_model.clone(),
            args.deepseek_api_key.clone(),
            chat_params.clone(),
        ),
    };
    let chat_agent = initial_spec.build()?;
    println!(
        "Chat: {} ({})  |  chunk_size={}, chunk_overlap={}",
        chat_agent.backend_name(),
        chat_agent.model_name(),
        args.chunk_size,
        args.chunk_overlap
    );

    // Build the initial embedding backend from CLI args.
    let embedder_spec = EmbedderSpec::from_args(&args);
    let embedder = embedder_spec.build()?;
    println!(
        "Embed: {} ({})",
        embedder.backend_name(),
        embedder.model_name()
    );

    let embeddings_file_path = get_embeddings_file_path(&args.folder);

    // Build the document parser registry (needed before store setup).
    let doc_parsers = DocumentParsers::new(filtered_parsers(&args.pdf_parser, args.sloppy_pdf));
    println!(
        "Parsers: {}  |  Active PDF: {:?}  |  Chunker: markdown-structural",
        doc_parsers.names().join(", "),
        args.pdf_parser
    );

    let current_file_hashes = match get_document_file_hashes(&args.folder) {
        Ok(hashes) => {
            println!("Found {} document files with hashes.", hashes.len());
            hashes
        }
        Err(e) => {
            eprintln!("Warning: Could not compute file hashes: {}", e);
            Vec::new()
        }
    };

    // Open or create the vector store.
    let store = store::open_store(&args.folder).await?;

    // Determine whether we need to build from scratch or update incrementally.
    let chunk_cfg = ChunkConfig { size: args.chunk_size, overlap: args.chunk_overlap };
    if store.is_empty() {
        println!("No existing store found. Creating new one...");
        collect_documents(&*embedder, &doc_parsers, &args.folder, &chunk_cfg, &*store).await?;
    } else {
        println!(
            "Found existing store ({} chunks). Checking for changes...",
            store.len()
        );

        let mut stored_hashes: Vec<FileHashEntry> = Vec::new();
        if embeddings_file_path.exists() {
            match fs::read_to_string(&embeddings_file_path) {
                Ok(json) => {
                    if let Ok(metadata) = serde_json::from_str::<HashMetadata>(&json) {
                        stored_hashes = metadata.file_hashes;
                    }
                }
                Err(e) => eprintln!("Warning: Could not read hash metadata: {}", e),
            }
        }

        if stored_hashes.is_empty() {
            println!("No hash metadata found. Regenerating all embeddings...");
            for source in store.sources() {
                store.delete_by_source(&source).await?;
            }
            collect_documents(&*embedder, &doc_parsers, &args.folder, &chunk_cfg, &*store).await?;
        } else {
            let changed_files = get_changed_documents(&current_file_hashes, &stored_hashes);

            if !changed_files.is_empty() {
                println!("Found {} changed/new files.", changed_files.len());
                remove_deleted_embeddings(&*store, &current_file_hashes).await?;
                for (_doc_type, file_name) in &changed_files {
                    store.delete_by_source(file_name).await?;
                }
                let changed_with_types: Vec<(DocumentType, String)> = changed_files
                    .into_iter()
                    .map(|(doc_type, _)| {
                        let file_name = doc_type.file_name().to_string();
                        (doc_type, file_name)
                    })
                    .collect();
                embed_documents(&*embedder, &doc_parsers, &chunk_cfg, changed_with_types, &*store)
                    .await?;
                println!("Database updated.");
            } else {
                println!("No files have changed. Using existing embeddings.");
            }
        }
    }

    update_file_hashes(&current_file_hashes, &embeddings_file_path)?;

    let row_count = store.len();
    if row_count == 0 {
        return Err(anyhow::anyhow!(ragrig::RagrigError::NoDocumentsFound {
            folder: args.folder.to_string_lossy().into_owned(),
        }));
    }
    println!("Vector store initialized with {} total entries.", row_count);

    // Build the rewrite (memory) agent.
    let memory_spec = ChatAgentSpec::ollama(args.memory_model.clone(), chat_params.clone());
    let memory_agent = memory_spec.build()?;
    println!(
        "Memory: {} ({})",
        memory_agent.backend_name(),
        memory_agent.model_name()
    );

    // Build the RagAgent.
    let mut agent_builder = RagAgent::builder()
        .chat(chat_agent)
        .embed(embedder)
        .store(store)
        .rewriter(memory_agent)
        .context_tokens(args.model_ctx_tokens)
        .top_k(args.top_k)
        .similarity_threshold(args.similarity_threshold);

    // Optional prompt overrides from CLI.
    if let Some(ref path) = args.prompt_chat {
        let prompt_text = fs::read_to_string(path)?;
        agent_builder = agent_builder.system_prompt(prompt_text);
    }
    if let Some(ref path) = args.prompt_rewrite {
        let rewrite_text = fs::read_to_string(path)?;
        agent_builder = agent_builder.rewrite_prompt(rewrite_text);
    }

    let agent = agent_builder.build();

    let pdf_parser = args.pdf_parser.clone();
    let context_size_forced = args.context_size_forced;

    let mut rl = DefaultEditor::new()?;
    let history_path = args.folder.join(".ragrig_history");
    if history_path.exists()
        && let Err(e) = rl.load_history(&history_path) {
            eprintln!("Warning: Could not load history: {}", e);
        }

    println!("\nRAG System Online. Commands: /download <url> | /get <nums> | /help | exit");
    println!(
        "Ask questions based on your loaded documents (Arrow-Up for history, Ctrl+C to exit):"
    );

    // ── Session store (filesystem‑backed, one JSON file per session) ──
    let sessions_dir = args.folder.join(".ragrig").join("sessions");
    let session_store: Box<dyn SessionStore> =
        Box::new(FsSessionStore::new(sessions_dir)?);
    let session_id = SessionId(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| format!("{}", d.as_secs()))
            .unwrap_or_else(|_| "0".to_string()),
    );
    println!("Session: {}", session_id.0);

    Ok(Session {
        args,
        agent,
        embeddings_file_path,
        last_results: Vec::new(),
        last_search_results: Vec::new(),
        rl,
        history_path,
        http_client: reqwest::Client::new(),
        prompt_memory: Vec::new(),
        session_store,
        session_id,
        history_strategy: None,
        doc_parsers,
        pdf_parser,
        epub_parser: EpubParserBackend::Epub,
        context_size_forced,
    })
}

// ── Command dispatch ──────────────────────────────────────────────────────

impl From<&str> for Command {
    fn from(input: &str) -> Self {
        let input = input.trim();

        // Non‑slash input is always a RAG query.
        if !input.starts_with('/') {
            return Command::RagQuery(input.to_string());
        }

        if input == "exit" || input == "quit"
            || input == "/exit" || input == "/bye"
        {
            return Command::Exit;
        }
        if input == "/help" {
            return Command::Help;
        }

        // Helper: safe substring after a known prefix.
        let after = |prefix: &str| -> &str {
            if input.len() > prefix.len() + 1 {
                &input[prefix.len()..]
            } else {
                ""
            }
        };

        if input.starts_with("/download ") {
            let url = strip_ansi(after("/download ")).trim().to_string();
            return Command::Download(url);
        }
        if input.starts_with("/get ") {
            return Command::GetPapers(after("/get ").trim().to_string());
        }
        if input.starts_with("/scholar ") {
            return Command::Scholar(after("/scholar ").trim().to_string());
        }
        if input.eq_ignore_ascii_case("/scholar") {
            return Command::Scholar(String::new());
        }
        if input.eq_ignore_ascii_case("/search") {
            return Command::Search(String::new());
        }
        if input.starts_with("/search ") {
            return Command::Search(after("/search ").trim().to_string());
        }
        if input.starts_with("/arxiv ") {
            return Command::SearchArxiv(after("/arxiv ").trim().to_string());
        }
        if input.starts_with("/refs") {
            return Command::ExtractRefs(after("/refs").trim().to_string());
        }
        if input.starts_with("/chat") {
            return Command::Chat(after("/chat").trim().to_string());
        }
        if input.starts_with("/embed") {
            return Command::Embed(after("/embed").trim().to_string());
        }
        if input.starts_with("/memory") {
            return Command::Memory(after("/memory").trim().to_string());
        }
        if input.starts_with("/hist") {
            return Command::Hist(after("/hist").trim().to_string());
        }
        if input.starts_with("/prompt") {
            return Command::Prompt(after("/prompt").trim().to_string());
        }
        if input.starts_with("/parser") {
            return Command::Parser(after("/parser").trim().to_string());
        }

        // Any other slash‑prefixed input is an unknown command, not a query.
        Command::Unknown(input.to_string())
    }
}

impl Session {
    /// Auto‑save the current session to the store.
    async fn auto_save(&self) -> Result<()> {
        let config = ragrig::SessionConfig {
            chat_backend: self.agent.chat_agent().backend_name().to_string(),
            chat_model: self.agent.chat_agent().model_name().to_string(),
            embed_backend: self.agent.embedder().backend_name().to_string(),
            embed_model: self.agent.embedder().model_name().to_string(),
            memory_strategy: if self.agent.rewriter().is_some() {
                ragrig::MemoryStrategyKind::Rewrite
            } else {
                ragrig::MemoryStrategyKind::Off
            },
            memory_backend: String::new(),
            memory_model: String::new(),
            top_k: self.agent.top_k(),
            similarity_threshold: self.agent.similarity_threshold(),
            model_ctx_tokens: self.agent.context_tokens(),
        };
        let data = ragrig::SessionData {
            id: self.session_id.clone(),
            created: std::time::UNIX_EPOCH,
            updated: std::time::SystemTime::now(),
            config,
            turns: self.prompt_memory.clone(),
        };
        self.session_store.save(&data).await
    }

    async fn execute(&mut self, cmd: Command) -> Result<()> {
        match cmd {
            Command::Download(url) => self.cmd_download(&url).await,
            Command::GetPapers(range) => self.cmd_get_papers(&range).await,
            Command::Help => {
                self.cmd_help();
                Ok(())
            }
            Command::Scholar(q) => self.cmd_search_scholar(&q).await,
            Command::SearchArxiv(q) => self.cmd_search_arxiv(&q).await,
            Command::ExtractRefs(filter) => self.cmd_extract_refs(&filter).await,
            Command::Chat(args_str) => self.cmd_chat(&args_str).await,
            Command::Search(args) => self.cmd_search(&args).await,
            Command::Embed(args_str) => self.cmd_embed(&args_str).await,
            Command::Memory(args_str) => self.cmd_memory(&args_str).await,
            Command::Hist(args_str) => self.cmd_hist(&args_str).await,
            Command::Prompt(args_str) => self.cmd_prompt(&args_str).await,
            Command::Parser(args_str) => self.cmd_parser(&args_str).await,
            Command::RagQuery(q) => self.cmd_rag_query(&q).await,
            Command::Unknown(cmd) => {
                println!("Unknown command: '{}'", cmd);
                Ok(())
            }
            Command::Exit => Ok(()),
        }
    }

    // ── /download <url> ───────────────────────────────────────────────

    async fn cmd_download(&mut self, url: &str) -> Result<()> {
        if url.is_empty() {
            println!("Usage: /download <url>");
            return Ok(());
        }
        println!("Downloading and ingesting: {} ...", url);
        eprintln!("[DEBUG] URL bytes: {:?}", url.as_bytes());
        match download_and_ingest_url(
            &*self.agent.embedder(),
            &self.doc_parsers,
            &self.args.folder,
            &ChunkConfig { size: self.args.chunk_size, overlap: self.args.chunk_overlap },
            &self.http_client,
            self.agent.store(),
            url,
        )
        .await
        {
            Ok(summary) => {
                println!("{}", summary);
                update_file_hashes(
                    &get_document_file_hashes(&self.args.folder).unwrap_or_default(),
                    &self.embeddings_file_path,
                )?;
            }
            Err(e) => println!("Error: {}", e),
        }
        Ok(())
    }

    // ── /get <nums> ──────────────────────────────────────────────────

    async fn cmd_get_papers(&mut self, range_str: &str) -> Result<()> {
        if self.last_search_results.is_empty() {
            println!("No search results available. Run /scholar or /arxiv first.");
            return Ok(());
        }
        if range_str.is_empty() {
            println!("Usage: /get 1,2,3-4,8");
            return Ok(());
        }

        let indices = match parse_number_range(range_str) {
            Ok(ids) => ids,
            Err(e) => {
                println!("Invalid range: {}", e);
                return Ok(());
            }
        };

        let mut downloaded = 0;
        let mut failed = 0;
        for idx in &indices {
            if *idx >= self.last_search_results.len() {
                println!(
                    "  Skipping [{}]: out of range (max {})",
                    idx + 1,
                    self.last_search_results.len()
                );
                failed += 1;
                continue;
            }
            let paper = &self.last_search_results[*idx];
            let url = strip_ansi(&paper.best_pdf_url());

            if url.is_empty() {
                println!(
                    "  [{:2}] {} — no download URL available",
                    idx + 1,
                    paper.title
                );
                failed += 1;
                continue;
            }

            print!("  [{:2}] {} ... ", idx + 1, paper.title);
            stdout().flush()?;
            match download_and_ingest_url(
                &*self.agent.embedder(),
                &self.doc_parsers,
                &self.args.folder,
                &ChunkConfig { size: self.args.chunk_size, overlap: self.args.chunk_overlap },
                &self.http_client,
                self.agent.store(),
                &url,
            )
            .await
            {
                Ok(_) => {
                    println!("done");
                    downloaded += 1;
                    update_file_hashes(
                        &get_document_file_hashes(&self.args.folder).unwrap_or_default(),
                        &self.embeddings_file_path,
                    )?;
                }
                Err(e) => {
                    println!("failed: {}", e);
                    failed += 1;
                }
            }
        }

        println!(
            "Download complete: {} added, {} failed, {} skipped.",
            downloaded,
            failed,
            indices.len().saturating_sub(downloaded + failed)
        );

        Ok(())
    }

    // ── /help ────────────────────────────────────────────────────────

    fn cmd_help(&self) {
        println!("/download <url>  — download and ingest a PDF into the document pool");
        println!("/scholar <q>   — search Semantic Scholar (free API key for higher limits)");
        println!("/arxiv <q>      — search arXiv (no API key needed, no rate limits)");
        println!("/search         — show / adjust vector search parameters (topk, threshold)");
        println!("/get 1,2,3-4    — download papers by number from last search");
        println!(
            "/refs [topic]   — extract references from last query results (optionally filtered by topic)"
        );
        println!("/chat <backend> [model] [api_key] | context <N> — hot-swap chat engine or adjust context window");
        println!("/embed <backend> [model] | purge | index — hot-swap embedding backend");
        println!("/memory <backend> [model] [key] | transcript | log | summary | off | purge — hot-swap memory + history diffusion");
        println!("/hist [list | load <id> | delete <id>] — manage saved sessions");
        println!("/prompt chat|rewrite <file> | reset — load custom system prompts");
        println!(
            "/parser pdf unpdf|sink|extract|internal | epub epub — hot-swap parser per format"
        );
        println!("exit / quit     — end the session");
    }

    // ── /scholar <q> ──────────────────────────────────────────────────

    async fn cmd_search_scholar(&mut self, q: &str) -> Result<()> {
        if q.is_empty() {
            println!("Usage: /scholar <query>");
            return Ok(());
        }
        println!("Searching Semantic Scholar for: {} ...", q);
        match search_semantic_scholar(self.args.semantic_scholar_api_key.as_deref(), &self.http_client, q, 20).await {
            Ok(papers) if papers.is_empty() => {
                println!("No papers found.");
            }
            Ok(papers) => {
                println!("\nResults:");
                for (i, p) in papers.iter().enumerate() {
                    println!(
                        "  [{:2}] {}{}{}",
                        i + 1,
                        p.title,
                        p.format_authors(),
                        p.format_year()
                    );
                    let url = p.best_pdf_url();
                    if !url.is_empty() {
                        println!("       /download {}", url);
                    }
                }
                self.last_search_results = papers.clone();
                println!("\nUse /download <url> to ingest any paper.");
            }
            Err(e) => println!("Search error: {}", e),
        }
        Ok(())
    }

    // ── /arxiv <q> ───────────────────────────────────────────────────

    async fn cmd_search_arxiv(&mut self, q: &str) -> Result<()> {
        if q.is_empty() {
            println!("Usage: /arxiv <query>");
            return Ok(());
        }
        println!("Searching arXiv for: {} ...", q);
        match search_arxiv(&self.http_client, q, 20).await {
            Ok(papers) if papers.is_empty() => {
                println!("No papers found.");
            }
            Ok(papers) => {
                println!("\nResults (arXiv):");
                for (i, p) in papers.iter().enumerate() {
                    println!(
                        "  [{:2}] {}{}{}",
                        i + 1,
                        p.title,
                        p.format_authors(),
                        p.format_year()
                    );
                    let url = p.best_pdf_url();
                    if !url.is_empty() {
                        println!("       /download {}", url);
                    }
                }
                self.last_search_results = papers;
                println!("\nUse /download <url> to ingest any paper.");
            }
            Err(e) => println!("arXiv search error: {}", e),
        }
        Ok(())
    }

    // ── /search [topk|threshold] ─────────────────────────────────────

    async fn cmd_search(&mut self, args_str: &str) -> Result<()> {
        let mut parts = args_str.split_whitespace();
        let sub = parts.next().unwrap_or("");

        if sub.is_empty() {
            println!(
                "Vector search parameters:"
            );
            println!("  top-k:     {}  (change: /search topk <N>)", self.agent.top_k());
            println!("  threshold: {:.3}  (change: /search threshold <F>)", self.agent.similarity_threshold());
            return Ok(());
        }

        if sub == "topk" {
            match parts.next().and_then(|s| s.parse::<usize>().ok()) {
                Some(n) if n > 0 => {
                    self.agent.set_top_k(n);
                    println!("Top-k set to {}.", n);
                }
                _ => println!("Usage: /search topk <N>  (current: {})", self.agent.top_k()),
            }
            return Ok(());
        }

        if sub == "threshold" {
            match parts.next().and_then(|s| s.parse::<f64>().ok()) {
                Some(f) if f >= 0.0 => {
                    self.agent.set_similarity_threshold(f);
                    println!("Similarity threshold set to {:.3}.", f);
                }
                _ => println!(
                    "Usage: /search threshold <F>  (current: {:.3})",
                    self.agent.similarity_threshold()
                ),
            }
            return Ok(());
        }

        println!(
            "Unknown subcommand: '{}'. Use /search, /search topk <N>, or /search threshold <F>.",
            sub
        );
        Ok(())
    }

    // ── /refs [topic] ────────────────────────────────────────────────

    async fn cmd_extract_refs(&mut self, filter: &str) -> Result<()> {
        if self.last_results.is_empty() {
            println!("No previous query results. Ask a question first, then use /refs.");
            return Ok(());
        }

        let filter_hint = if filter.is_empty() {
            String::new()
        } else {
            format!(
                " Focus specifically on references related to: \"{}\".",
                filter
            )
        };

        let mut context = String::new();
        for (i, sc) in self.last_results.iter().take(5).enumerate() {
            context.push_str(&format!(
                "[Document {} | Source: {}]\n{}\n\n",
                i + 1,
                sc.chunk.source_file,
                sc.chunk.text
            ));
        }

        let extract_prompt = format!(
            "Extract all academic paper references (cited works with title, authors, year) from the documents below.{}\n\n\
            Return ONLY a numbered list. For each reference, include:\n\
            - Title of the cited paper\n\
            - Authors (last name of first author + et al. if multiple)\n\
            - Year\n\
            - If an arXiv ID or DOI is visible, include it as a URL.\n\n\
            Documents:\n{}",
            filter_hint, context
        );

        println!("Extracting references...\n");
        print!("Assistant > ");
        stdout().flush()?;

        let got_response = AtomicBool::new(false);
        match self
            .agent
            .chat_agent()
            .generate_stream(&extract_prompt, &|text: String| {
                print!("{}", text);
                let _ = stdout().flush();
                got_response.store(true, Ordering::Relaxed);
            })
            .await
        {
            Ok(()) => {}
            Err(e) => eprintln!("\n[ERROR] Reference extraction failed: {}", e),
        }
        if !got_response.load(Ordering::Relaxed) {
            println!("(no references found)");
        }
        println!();

        Ok(())
    }

    // ── /chat <backend> [model] [api_key] ─────────────────────────────

    /// Hot-swap the chat agent or adjust the context budget.
    ///
    /// # Agent swap
    ///
    /// Builds a new `Box<dyn Generator>` from a `ChatAgentSpec` and
    /// replaces the session's chat agent without touching the vector
    /// store, conversation memory, or document index.
    ///
    /// ```text
    /// /chat ollama gemma2:latest         # switch to local model
    /// /chat deepseek deepseek-chat sk-…  # switch to cloud
    /// ```
    ///
    /// # Context budget
    ///
    /// `context <N>` adjusts the prompt-truncation budget in tokens
    /// without changing the chat engine.
    ///
    /// ```text
    /// /chat context 4096                 # shrink for 4K-window models
    /// /chat context 131072               # expand for cloud models
    /// ```
    async fn cmd_chat(&mut self, args_str: &str) -> Result<()> {
        let mut parts = args_str.split_whitespace();
        let backend = parts.next().unwrap_or("");
        if backend == "context" {
            match parts.next().and_then(|s| s.parse::<usize>().ok()) {
                Some(n) if n > 0 => {
                    self.agent.set_context_tokens(n);
                    let ctx = self.agent.context_tokens();
                    println!(
                        "Context window set to {} tokens (prompt budget ~{} chars).",
                        ctx,
                        (ctx.saturating_sub(1024)).saturating_mul(3)
                    );
                }
                _ => println!(
                    "Usage: /chat context <tokens>  (current: {})",
                    self.agent.context_tokens()
                ),
            }
            return Ok(());
        }
        if backend == "temperature" {
            match parts.next().and_then(|s| s.parse::<f64>().ok()) {
                Some(t) if t >= 0.0 => {
                    self.rebuild_chat_with_param(|p| p.temperature = Some(t));
                }
                _ => println!(
                    "Usage: /chat temperature <F>  (0.0 = deterministic)"
                ),
            }
            return Ok(());
        }
        if backend == "top_p" {
            match parts.next().and_then(|s| s.parse::<f64>().ok()) {
                Some(p) if p >= 0.0 && p <= 1.0 => {
                    self.rebuild_chat_with_param(|gp| gp.top_p = Some(p));
                }
                _ => println!(
                    "Usage: /chat top_p <F>  (0.0–1.0)"
                ),
            }
            return Ok(());
        }
        if backend == "max_tokens" {
            match parts.next().and_then(|s| s.parse::<usize>().ok()) {
                Some(n) if n > 0 => {
                    self.rebuild_chat_with_param(|p| p.max_tokens = Some(n));
                }
                _ => println!(
                    "Usage: /chat max_tokens <N>"
                ),
            }
            return Ok(());
        }
        if backend == "seed" {
            match parts.next().and_then(|s| s.parse::<u64>().ok()) {
                Some(s) => {
                    self.rebuild_chat_with_param(|p| p.seed = Some(s));
                }
                _ => println!(
                    "Usage: /chat seed <N>"
                ),
            }
            return Ok(());
        }
        if backend.is_empty() {
            println!(
                "Chat: {} ({}) — context window: {} tokens",
                self.agent.chat_agent().backend_name(),
                self.agent.chat_agent().model_name(),
                self.agent.context_tokens(),
            );
            println!("Usage: /chat <backend> [model] [api_key]  |  context <N>  |  temperature <F>  |  top_p <F>  |  max_tokens <N>  |  seed <N>");
            println!("  backends: ollama, deepseek");
            return Ok(());
        }

        let model = parts.next();
        let api_key = parts.next();

        let spec = match ChatAgentSpec::parse(backend, model, api_key, None) {
            Ok(s) => s,
            Err(e) => {
                println!("Error: {}", e);
                return Ok(());
            }
        };

        match spec.build() {
            Ok(new_agent) => {
                let old_backend = self.agent.chat_agent().backend_name();
                let old_model = self.agent.chat_agent().model_name().to_string();
                self.agent.set_chat_agent(new_agent);
                println!(
                    "Chat agent swapped: {} ({}) → {} ({})",
                    old_backend,
                    old_model,
                    self.agent.chat_agent().backend_name(),
                    self.agent.chat_agent().model_name()
                );
            }
            Err(e) => {
                println!("Failed to build chat agent: {}", e);
            }
        }
        Ok(())
    }

    /// Rebuild the current chat agent with a modified `GenerationParams`, keeping
    /// the same backend and model.
    fn rebuild_chat_with_param(&mut self, f: impl FnOnce(&mut GenerationParams)) {
        let current = self.agent.chat_agent();
        let backend = current.backend_name();
        let model = current.model_name();

        // We need to reconstruct the spec with updated params.
        // Since we can't introspect the existing generator's params,
        // we start fresh and apply the mutation.
        let mut params = GenerationParams::default();
        f(&mut params);

        let spec = match ChatAgentSpec::parse(backend, Some(model), None, Some(params)) {
            Ok(spec) => spec,
            Err(e) => {
                println!("Cannot rebuild unknown backend: {}", e);
                return;
            }
        };

        match spec.build() {
            Ok(new_agent) => {
                self.agent.set_chat_agent(new_agent);
                let agent = self.agent.chat_agent();
                println!(
                    "Chat params updated: {} ({})",
                    agent.backend_name(),
                    agent.model_name()
                );
            }
            Err(e) => {
                println!("Failed to rebuild chat agent: {}", e);
            }
        }
    }

    // ── /embed <backend> [model] ──────────────────────────────────────

    async fn cmd_embed(&mut self, args_str: &str) -> Result<()> {
        let mut parts = args_str.split_whitespace();
        let backend = parts.next().unwrap_or("");
        if backend.is_empty() {
            println!(
                "Embed: {} ({}) — top‑k: {}, threshold: {}",
                self.agent.embedder().backend_name(),
                self.agent.embedder().model_name(),
                self.agent.top_k(),
                self.agent.similarity_threshold(),
            );
            println!(
                "Usage: /embed <backend> [model]  |  purge  |  index  |  topk <N>  |  threshold <F>"
            );
            println!(
                "  backends: {}",
                EmbedderSpec::available_backends().join(", ")
            );
            return Ok(());
        }

        if backend.eq_ignore_ascii_case("purge") {
            let store = self.agent.store();
            let count = store.len();
            let sources: Vec<_> = store.sources().into_iter().collect();
            for source in &sources {
                store.delete_by_source(source).await?;
            }
            println!(
                "Vector store purged ({} chunks across {} source files).",
                count,
                sources.len()
            );
            return Ok(());
        }

        if backend.eq_ignore_ascii_case("index") {
            println!(
                "Re-indexing all documents in {}...",
                self.args.folder.display()
            );
            let chunk_cfg = ChunkConfig { size: self.args.chunk_size, overlap: self.args.chunk_overlap };
            let stats = collect_documents_with_stats(&*self.agent.embedder(), &self.doc_parsers, &self.args.folder, &chunk_cfg, self.agent.store()).await?;
            println!(
                "Re-indexing complete. Store size: {} chunks.\n",
                self.agent.store().len()
            );
            // Print per-file result table.
            let ok_count = stats.iter().filter(|s| s.ok).count();
            let fail_count = stats.len() - ok_count;
            let total_chunks: usize = stats.iter().map(|s| s.chunks).sum();
            let total_chars: usize = stats.iter().map(|s| s.chars).sum();
            let total_kb: u64 = stats.iter().map(|s| s.file_size_kb).sum();
            println!(
                "\n{} files processed ({} ok, {} failed), {} chunks, {} chars, {} KB total.\n",
                stats.len(), ok_count, fail_count, total_chunks, total_chars, total_kb
            );
            if !stats.is_empty() {
                println!(
                    "{:<44} {:>6} {:>7} {:>8} {:>6}",
                    "File", "KB", "Chunks", "Chars", "Avg/Ch"
                );
                println!("{}", "".repeat(78));
                for s in &stats {
                    let name = if s.file_name.len() > 42 {
                        format!("{}", &s.file_name[..41])
                    } else {
                        s.file_name.clone()
                    };
                    if s.ok {
                        println!(
                            "{:<44} {:>6} {:>7} {:>8} {:>6.0}",
                            name, s.file_size_kb, s.chunks, s.chars, s.avg_chars_per_chunk()
                        );
                    } else {
                        println!(
                            "{:<44} {:>6} {:>7} {:>8} {:>6}  FAIL",
                            name, s.file_size_kb, "", "", ""
                        );
                    }
                }
            }
            return Ok(());
        }

        if backend == "topk" {
            match parts.next().and_then(|s| s.parse::<usize>().ok()) {
                Some(n) if n > 0 => {
                    self.agent.set_top_k(n);
                    println!("Top-k set to {}.", n);
                }
                _ => println!("Usage: /embed topk <N>  (current: {})", self.agent.top_k()),
            }
            return Ok(());
        }

        if backend == "threshold" {
            match parts.next().and_then(|s| s.parse::<f64>().ok()) {
                Some(f) if f >= 0.0 => {
                    self.agent.set_similarity_threshold(f);
                    println!("Similarity threshold set to {:.3}.", f);
                }
                _ => println!(
                    "Usage: /embed threshold <F>  (current: {:.3})",
                    self.agent.similarity_threshold()
                ),
            }
            return Ok(());
        }

        let model = parts.next();

        let spec = match EmbedderSpec::parse(backend, model) {
            Ok(s) => s,
            Err(e) => {
                println!("Error: {}", e);
                return Ok(());
            }
        };

        match spec.build() {
            Ok(new_embedder) => {
                let old_backend = self.agent.embedder().backend_name();
                let old_model = self.agent.embedder().model_name().to_string();
                self.agent.set_embedder(new_embedder);
                println!(
                    "Embedder swapped: {} ({}) → {} ({})",
                    old_backend,
                    old_model,
                    self.agent.embedder().backend_name(),
                    self.agent.embedder().model_name()
                );
            }
            Err(e) => {
                println!("Failed to build embedder: {}", e);
            }
        }
        Ok(())
    }

    // ── /hist [list | load <id> | delete <id>] ─────────────────────

    async fn cmd_hist(&mut self, args_str: &str) -> Result<()> {
        let arg = args_str.trim();
        if arg.is_empty() || arg == "list" {
            match self.session_store.list().await {
                Ok(manifests) if manifests.is_empty() => {
                    println!("No saved sessions.");
                }
                Ok(manifests) => {
                    println!("{} saved session(s):", manifests.len());
                    for m in &manifests {
                        println!(
                            "  {}{} turns — {:?}",
                            m.id.0, m.turn_count, m.created
                        );
                    }
                }
                Err(e) => println!("Error listing sessions: {}", e),
            }
            return Ok(());
        }
        let mut parts = arg.split_whitespace();
        let sub = parts.next().unwrap_or("");
        let id = parts.next().unwrap_or("");
        match sub {
            "load" if !id.is_empty() => {
                let sid = SessionId(id.to_string());
                match self.session_store.load(&sid).await {
                    Ok(Some(session)) => {
                        self.prompt_memory = session.turns;
                        println!(
                            "Loaded session {} ({} turns).",
                            id,
                            self.prompt_memory.len()
                        );
                    }
                    Ok(None) => println!("Session '{}' not found.", id),
                    Err(e) => println!("Error loading session: {}", e),
                }
            }
            "delete" if !id.is_empty() => {
                let sid = SessionId(id.to_string());
                match self.session_store.delete(&sid).await {
                    Ok(()) => println!("Deleted session '{}'.", id),
                    Err(e) => println!("Error deleting session: {}", e),
                }
            }
            _ => {
                println!("Usage: /hist [list | load <id> | delete <id>]");
            }
        }
        Ok(())
    }

    // ── /memory <backend> [model] [api_key] | off ───────────────────

    async fn cmd_memory(&mut self, args_str: &str) -> Result<()> {
        let arg = args_str.trim();
        if arg.is_empty() {
            // ── Current config ──────────────────────────────────────
            let mem = if self.agent.rewriter().is_some() { "rewrite" } else { "off" };
            let diff = match &self.history_strategy {
                Some(s) => s.name(),
                None => "off",
            };
            println!(
                "Memory: {}{} turns  |  history diffusion: {}",
                mem,
                self.prompt_memory.len(),
                diff,
            );
            // ── Usage ──────────────────────────────────────────────
            println!(
                "Usage: /memory <backend> [model] [api_key]  |  transcript  |  log  |  summary  |  off  |  purge"
            );
            println!("  backends: ollama, deepseek");
            println!("  modes:    transcript — raw memory, no query rewriting");
            println!("            log       — enable history diffusion (raw last session)");
            println!("            summary   — enable history diffusion (LLM summarisation)");
            return Ok(());
        }

        if arg.eq_ignore_ascii_case("purge") {
            let count = self.prompt_memory.len();
            self.prompt_memory.clear();
            if let Some(ref rewriter) = self.agent.rewriter()
                && let Err(e) = rewriter.clear_memory().await {
                    eprintln!("Warning: memory clear failed: {}", e);
                }
            println!("Conversation memory purged ({} entries removed).", count);
            return Ok(());
        }

        if arg.eq_ignore_ascii_case("off") || arg.eq_ignore_ascii_case("none") {
            let was = self.agent.rewriter().is_some();
            self.agent.set_rewriter(None);
            if was {
                println!("Memory disabled (was: rewrite)");
            } else {
                println!("Memory already off.");
            }
            return Ok(());
        }

        if arg.eq_ignore_ascii_case("log") {
            let old = self.history_strategy.replace(Box::new(LogHistory));
            match old {
                Some(o) if o.name() == "log" => {
                    println!("History diffusion unchanged: log");
                }
                Some(o) => {
                    println!("History diffusion: {} → log", o.name());
                }
                None => println!("History diffusion enabled: log"),
            }
            return Ok(());
        }

        if arg.eq_ignore_ascii_case("summary") {
            let summary_spec = ChatAgentSpec::ollama(
                self.args.memory_model.clone(),
                GenerationParams::default(),
            );
            match summary_spec.build() {
                Ok(summary_agent) => {
                    let strat: Box<dyn HistoryStrategy> =
                        Box::new(SummaryHistory::new(summary_agent));
                    let old = self.history_strategy.replace(strat);
                    match old {
                        Some(o) if o.name() == "summary" => {
                            println!("History diffusion unchanged: summary");
                        }
                        Some(o) => {
                            println!("History diffusion: {} → summary", o.name());
                        }
                        None => println!("History diffusion enabled: summary"),
                    }
                }
                Err(e) => println!("Failed to build summary agent: {}", e),
            }
            return Ok(());
        }

        if arg.eq_ignore_ascii_case("transcript") {
            let was = self.agent.rewriter().is_some();
            self.agent.set_rewriter(None);
            if was {
                println!("Memory strategy: rewrite → transcript");
            } else {
                println!("Memory unchanged: transcript");
            }
            return Ok(());
        }

        // ── LLM-backed memory (rewrite mode) ───────────────────────

        let mut parts = arg.split_whitespace();
        let backend = parts.next().unwrap_or("");
        let model = parts.next();
        let api_key = parts.next();

        let spec = match ChatAgentSpec::parse(backend, model, api_key, None) {
            Ok(s) => s,
            Err(e) => {
                println!("Error: {}", e);
                return Ok(());
            }
        };

        match spec.build() {
            Ok(new_rewriter) => {
                let new_backend = new_rewriter.backend_name();
                let new_model = new_rewriter.model_name().to_string();
                let was = self.agent.rewriter().is_some();
                self.agent.set_rewriter(Some(new_rewriter));
                if was {
                    println!("Memory agent: {} ({})", new_backend, new_model);
                } else {
                    println!("Memory enabled: rewrite — {} ({})", new_backend, new_model);
                }
            }
            Err(e) => {
                println!("Failed to build memory agent: {}", e);
            }
        }
        Ok(())
    }

    // ── /prompt [chat|rewrite|reset] [file] ──────────────────────────

    async fn cmd_prompt(&mut self, args_str: &str) -> Result<()> {
        let mut parts = args_str.split_whitespace();
        let sub = parts.next().unwrap_or("");
        if sub.is_empty() {
            println!("Current prompts:");
            println!(
                "  chat (docs):    {:.80}",
                self.agent.system_prompt().trim()
            );
            println!(
                "  chat (no docs): {:.80}",
                self.agent.chat_without_docs_prompt().trim()
            );
            println!("  rewrite:        {:.80}", self.agent.rewrite_prompt().trim());
            println!("Usage: /prompt chat|rewrite <file>  or  /prompt reset");
            return Ok(());
        }

        match sub {
            "reset" => {
                self.agent.set_system_prompt(
                    "You are a helpful document assistant. Answer the user's question \
                     explicitly using the provided Context snippets.\n\
                     \n\
                     Context:\n{context}\n".to_string()
                );
                self.agent.set_rewrite_prompt(
                    "You are a query rewriter. Given the conversation and the \
                     latest question, produce a single self-contained search query \
                     that captures all relevant context. Output ONLY the rewritten \
                     query, nothing else.\n\n\
                     Latest question: {question}".to_string()
                );
                println!("Prompts reset to defaults.");
            }
            "chat" => {
                let file = parts.next();
                let Some(file) = file else {
                    println!("Usage: /prompt chat <file>");
                    return Ok(());
                };
                match fs::read_to_string(file) {
                    Ok(text) => {
                        self.agent.set_system_prompt(text);
                        println!("Chat prompt loaded from {}", file);
                    }
                    Err(e) => println!("Failed to load prompt: {}", e),
                }
            }
            "rewrite" => {
                let file = parts.next();
                let Some(file) = file else {
                    println!("Usage: /prompt rewrite <file>");
                    return Ok(());
                };
                match fs::read_to_string(file) {
                    Ok(text) => {
                        self.agent.set_rewrite_prompt(text);
                        println!("Rewrite prompt loaded from {}", file);
                    }
                    Err(e) => println!("Failed to load prompt: {}", e),
                }
            }
            other => {
                println!(
                    "Unknown sub-command: {}. Use chat, rewrite, or reset.",
                    other
                );
            }
        }
        Ok(())
    }

    // ── /parser [pdf|epub] [sink|extract|internal|epub] ────────────

    async fn cmd_parser(&mut self, args_str: &str) -> Result<()> {
        let mut parts = args_str.split_whitespace();
        let format = parts.next().unwrap_or("");
        if format.is_empty() {
            println!("PDF:  {:?}", self.pdf_parser);
            println!("EPUB: {:?}", self.epub_parser);
            println!("Usage: /parser pdf unpdf|sink|extract|internal|vision");
            println!("       /parser epub epub");
            return Ok(());
        }

        let choice = parts.next().unwrap_or("");
        if choice.is_empty() {
            println!("Usage: /parser {} <backend>", format);
            return Ok(());
        }

        match format.to_lowercase().as_str() {
            "pdf" => {
                #[allow(deprecated)]
                let new = match choice.to_lowercase().as_str() {
                    #[cfg(feature = "kreuzberg")]
                    "kreuzberg" => PdfParserBackend::Kreuzberg,
                    "unpdf" => PdfParserBackend::Unpdf,
                    "sink" => PdfParserBackend::Sink,
                    "extract" => PdfParserBackend::Extract,
                    "internal" => PdfParserBackend::Internal,
                    "vision" => PdfParserBackend::Vision,
                    other => {
                        println!(
                            "Unknown PDF parser: {}. Use unpdf, sink, extract, internal, or vision.",
                            other
                        );
                        return Ok(());
                    }
                };
                let old = std::mem::replace(&mut self.pdf_parser, new.clone());
                println!("PDF parser: {:?}{:?}", old, new);
                // Rebuild the parser registry so the selected backend takes effect.
                self.doc_parsers =
                    DocumentParsers::new(filtered_parsers(&new, self.args.sloppy_pdf));
                println!("Active parsers: {}", self.doc_parsers.names().join(", "));
            }
            "epub" => {
                let new = match choice.to_lowercase().as_str() {
                    "epub" => EpubParserBackend::Epub,
                    other => {
                        println!("Unknown EPUB parser: {}. The only option is 'epub'.", other);
                        return Ok(());
                    }
                };
                let old = std::mem::replace(&mut self.epub_parser, new.clone());
                println!("EPUB parser: {:?}{:?}", old, new);
            }
            other => {
                println!("Unknown format: {}. Use pdf or epub.", other);
            }
        }
        Ok(())
    }

    // ── Normal RAG query ─────────────────────────────────────────────

    /// Execute a full RAG pipeline: rewrite → embed → search → prompt → generate.
    ///
    /// 1. **Rewrite** — the memory agent expands pronouns and implicit
    ///    context into a self-contained search query (skipped if `/memory off`).
    /// 2. **Embed + Search** — the embedder vectorises the rewritten query;
    ///    the vector store performs hybrid BM25 + cosine RRF retrieval.
    /// 3. **Prompt construction** — system prompt + retrieved context +
    ///    conversation Memory (when enabled) + current question, formatted
    ///    as a single string with chat-template tokens.
    /// 4. **Generate** — the chat agent streams the response token by token.
    ///
    /// Retrieved context is truncated to `(model_ctx_tokens − 1024) × 3`
    /// chars to avoid exceeding the model's context window.
    async fn cmd_rag_query(&mut self, query: &str) -> Result<()> {
        // ── History diffusion (past sessions → context preamble) ─────
        let history_context = if let Some(ref strat) = self.history_strategy {
            match strat.build_context(&*self.session_store, query).await {
                Ok(ctx) if !ctx.is_empty() => {
                    eprintln!("[DEBUG] History diffusion: {} chars", ctx.len());
                    Some(ctx)
                }
                _ => None,
            }
        } else {
            None
        };

        // Prepend history context to the query if available.
        let effective_query = if let Some(ref hc) = history_context {
            format!("{hc}\n\nCurrent question: {query}")
        } else {
            query.to_string()
        };

        // Build transcript from prompt_memory.
        let transcript: Vec<(&str, &str)> = self.prompt_memory.iter()
            .map(|t| (t.role.as_str(), t.text.as_str()))
            .collect();

        eprintln!(
            "[DEBUG] Provider: {} | Model: {}",
            self.agent.chat_agent().backend_name(),
            self.agent.chat_agent().model_name()
        );

        print!("Assistant > ");
        stdout().flush()?;

        let response_text = Arc::new(Mutex::new(String::new()));
        let mut retried = false;
        loop {
            let rt = response_text.clone();
            match self
                .agent
                .generate_with_context_streaming(&effective_query, &transcript, &move |text: String| {
                    print!("{}", text);
                    let _ = stdout().flush();
                    rt.lock().unwrap().push_str(&text);
                })
                .await
            {
                Ok(()) => {
                    let reply = {
                        let guard = response_text.lock().unwrap();
                        guard.clone()
                    };
                    if retried {
                        eprintln!(
                            "*** Budget permanently adjusted to {} tokens.  Use `/chat context` to change. ***",
                            self.agent.context_tokens()
                        );
                    }
                    // Accumulate memory.
                    if !reply.trim().is_empty() {
                        self.prompt_memory.push(Turn {
                            role: TurnRole::User,
                            text: query.to_string(),
                            perf: None,
                        });
                        self.prompt_memory.push(Turn {
                            role: TurnRole::Assistant,
                            text: reply.trim().to_string(),
                            perf: None,
                        });
                        let _ = self.auto_save().await;
                    }
                    break;
                }
                Err(e) => {
                    if let Some(ce) = e.downcast_ref::<RagrigError>() {
                        if self.context_size_forced == ContextSizeMode::Auto && !retried {
                            retried = true;
                            let max = ce.max_size();
                            self.agent.set_context_tokens(max);
                            eprintln!(
                                "\n*** Context overflow: model allows {} tokens, prompt needed {}. ***",
                                ce.max_size(),
                                ce.current_size()
                            );
                            eprintln!(
                                "*** Budget auto‑adjusted to {} tokens — retrying. ***",
                                self.agent.context_tokens()
                            );
                            eprintln!(
                                "*** Use `/chat context {}` to override, or `--context-size-forced` to disable auto‑retry. ***",
                                ce.max_size().saturating_sub(512)
                            );
                            response_text.lock().unwrap().clear();
                            continue;
                        }
                        eprintln!(
                            "\n[ERROR] Prompt exceeds model context window.  Model allows {} tokens, needed {}.  Try `/chat context {}`.",
                            ce.max_size(),
                            ce.current_size(),
                            ce.max_size().saturating_sub(512)
                        );
                    } else {
                        eprintln!("\n[ERROR] Generation failed: {}", e);
                    }
                    break;
                }
            }
        }
        println!();

        Ok(())
    }
}

// ── main: parse → bootstrap → central match loop ──────────────────────────

#[tokio::main]
async fn main() -> Result<()> {
    let args = Args::parse();
    let mut session = bootstrap(args).await?;

    loop {
        let readline = session.rl.readline("Query > ");

        let cmd = match readline {
            Ok(line) => {
                let trimmed = line.trim().to_string();
                if trimmed.is_empty() {
                    continue;
                }
                session.rl.add_history_entry(&trimmed)?;
                Command::from(trimmed.as_str())
            }
            Err(ReadlineError::Interrupted) => {
                println!("\nSession interrupted.");
                break;
            }
            Err(ReadlineError::Eof) => {
                println!("\nSession ended via Ctrl+D.");
                break;
            }
            Err(err) => {
                eprintln!("Error reading input: {}", err);
                break;
            }
        };

        match cmd {
            Command::Exit => break,
            Command::RagQuery(ref q) if q.is_empty() => continue,
            _ => {
                if let Err(e) = session.execute(cmd).await {
                    eprintln!("Error: {}", e);
                }
            }
        }
    }

    // Auto‑save the session before exiting.
    if !session.prompt_memory.is_empty()
        && let Err(e) = session.auto_save().await {
            eprintln!("Warning: failed to save session: {}", e);
        }
    session.rl.save_history(&session.history_path)?;
    Ok(())
}

// ── Utility functions ─────────────────────────────────────────────────────

/// Strip ANSI escape sequences (bracketed paste, colors, etc.) from a string.
fn strip_ansi(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' && chars.peek() == Some(&'[') {
            // Consume the escape sequence: ESC[... until a letter
            chars.next(); // skip '['
            while let Some(&nc) = chars.peek() {
                chars.next();
                if nc.is_alphabetic() || nc == '~' {
                    break;
                }
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Parse "1,2,3-4,8" into zero-based indices [0,1,2,3,7]
fn parse_number_range(input: &str) -> Result<Vec<usize>, String> {
    let mut indices = Vec::new();
    for part in input.split(',') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        if let Some((start, end)) = part.split_once('-') {
            let s: usize = start
                .trim()
                .parse()
                .map_err(|_| format!("invalid number: {}", start))?;
            let e: usize = end
                .trim()
                .parse()
                .map_err(|_| format!("invalid number: {}", end))?;
            if s == 0 || e == 0 {
                return Err("Indices start at 1".to_string());
            }
            if s > e {
                return Err(format!("invalid range: {}-{}", s, e));
            }
            for n in s..=e {
                indices.push(n - 1); // convert to zero-based
            }
        } else {
            let n: usize = part
                .parse()
                .map_err(|_| format!("invalid number: {}", part))?;
            if n == 0 {
                return Err("Indices start at 1".to_string());
            }
            indices.push(n - 1);
        }
    }
    Ok(indices)
}

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

    // ── Command::from ─────────────────────────────────────────────────

    #[test]
    fn parse_unknown_slash_command_is_not_query() {
        // Any input starting with / that doesn't match a known command
        // must be Unknown, never RagQuery.
        let cmd = Command::from("/foobar");
        assert!(matches!(cmd, Command::Unknown(_)));
    }

    #[test]
    fn parse_unknown_slash_with_args() {
        let cmd = Command::from("/bogus arg1 arg2");
        assert!(matches!(cmd, Command::Unknown(c) if c.contains("arg1")));
    }

    #[test]
    fn parse_plain_text_is_rag_query() {
        let cmd = Command::from("What is RAG?");
        assert!(matches!(cmd, Command::RagQuery(q) if q == "What is RAG?"));
    }

    #[test]
    fn parse_memory_no_args_does_not_panic() {
        // Regression: /memory with no trailing content used to panic
        // on input[8..] when input was only 7 chars.
        let cmd = Command::from("/memory");
        assert!(matches!(cmd, Command::Memory(s) if s.is_empty()));
    }

    #[test]
    fn parse_memory_with_args() {
        let cmd = Command::from("/memory transcript");
        assert!(matches!(cmd, Command::Memory(s) if s == "transcript"));
    }

    #[test]
    fn parse_hist_no_args_does_not_panic() {
        let cmd = Command::from("/hist");
        assert!(matches!(cmd, Command::Hist(s) if s.is_empty()));
    }

    #[test]
    fn parse_chat_command_recognised() {
        // Regression: /chat was broken and fell through to RagQuery.
        let cmd = Command::from("/chat ollama");
        assert!(matches!(cmd, Command::Chat(s) if s == "ollama"));
    }

    #[test]
    fn parse_embed_no_args_does_not_panic() {
        let cmd = Command::from("/embed");
        assert!(matches!(cmd, Command::Embed(s) if s.is_empty()));
    }

    #[test]
    fn parse_refs_no_args_does_not_panic() {
        let cmd = Command::from("/refs");
        assert!(matches!(cmd, Command::ExtractRefs(s) if s.is_empty()));
    }

    #[test]
    fn parse_slash_exit() {
        assert!(matches!(Command::from("/exit"), Command::Exit));
    }

    #[test]
    fn parse_slash_bye() {
        assert!(matches!(Command::from("/bye"), Command::Exit));
    }

    // ── Integration test ─────────────────────────────────────────────

    /// Full RAG integration test — requires a running Ollama server
    /// with gemma4:e4b pulled, and tests/fixtures/formats/pdf indexed.
    ///
    /// Run with: cargo test --features ollama-embed -- --ignored
    #[tokio::test]
    #[ignore = "requires Ollama with gemma4:e4b and tests/fixtures/formats/pdf"]
    async fn gemma4_rag_answer_exceeds_20_words() {
        let args = Args::parse_from([
            "test",
            "--folder",
            "tests/fixtures/formats/pdf",
            "--model",
            "gemma4:e4b",
            "--embedding-model",
            "nomic-embed-text",
        ]);
        let mut session = match bootstrap(args).await {
            Ok(s) => s,
            Err(e) => {
                eprintln!("bootstrap failed (Ollama not running?): {}", e);
                return;
            }
        };
        let question = "I have used a 7-item Likert scale in my research. What should I do?";
        match session.cmd_rag_query(question).await {
            Ok(()) => {
                let memory = &session.prompt_memory;
                let answer = memory
                    .last()
                    .filter(|t| t.role == TurnRole::Assistant)
                    .map(|t| t.text.as_str())
                    .unwrap_or("");
                let word_count = answer.split_whitespace().count();
                eprintln!("Answer ({} words): {}", word_count, answer);
                assert!(
                    word_count > 20,
                    "Expected >20 words, got {}: '{}'",
                    word_count,
                    answer
                );
            }
            Err(e) => {
                eprintln!("RAG query failed: {}", e);
                // Don't panic on API errors, but do report them.
                // The test still fails if we get here because the
                // assertion above never runs.
                panic!("cmd_rag_query returned error: {}", e);
            }
        }
    }
}