agentroot-core 0.1.1

Core library for agentroot - semantic search engine with AST-aware chunking and hybrid search
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
//! Collection operations

use super::Database;
use crate::error::Result;
use chrono::Utc;
use rusqlite::params;

/// Collection info
#[derive(Debug, Clone, serde::Serialize)]
pub struct CollectionInfo {
    pub name: String,
    pub path: String,
    pub pattern: String,
    pub document_count: usize,
    pub created_at: String,
    pub updated_at: String,
    pub provider_type: String,
    pub provider_config: Option<String>,
}

impl Database {
    /// Add a new collection
    pub fn add_collection(
        &self,
        name: &str,
        path: &str,
        pattern: &str,
        provider_type: &str,
        provider_config: Option<&str>,
    ) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        self.conn.execute(
            "INSERT INTO collections (name, path, pattern, created_at, updated_at, provider_type, provider_config)
             VALUES (?1, ?2, ?3, ?4, ?4, ?5, ?6)",
            params![name, path, pattern, now, provider_type, provider_config],
        )?;
        Ok(())
    }

    /// Remove a collection and its documents
    pub fn remove_collection(&self, name: &str) -> Result<bool> {
        // Deactivate all documents
        self.conn.execute(
            "UPDATE documents SET active = 0 WHERE collection = ?1",
            params![name],
        )?;

        // Remove collection
        let rows = self
            .conn
            .execute("DELETE FROM collections WHERE name = ?1", params![name])?;

        Ok(rows > 0)
    }

    /// Rename a collection
    pub fn rename_collection(&self, old_name: &str, new_name: &str) -> Result<bool> {
        let now = Utc::now().to_rfc3339();

        // Update documents
        self.conn.execute(
            "UPDATE documents SET collection = ?2 WHERE collection = ?1",
            params![old_name, new_name],
        )?;

        // Update collection
        let rows = self.conn.execute(
            "UPDATE collections SET name = ?2, updated_at = ?3 WHERE name = ?1",
            params![old_name, new_name, now],
        )?;

        Ok(rows > 0)
    }

    /// List all collections with document counts
    pub fn list_collections(&self) -> Result<Vec<CollectionInfo>> {
        let mut stmt = self.conn.prepare(
            "SELECT c.name, c.path, c.pattern, c.created_at, c.updated_at,
                    (SELECT COUNT(*) FROM documents d WHERE d.collection = c.name AND d.active = 1),
                    c.provider_type, c.provider_config
             FROM collections c
             ORDER BY c.name",
        )?;

        let results = stmt
            .query_map([], |row| {
                Ok(CollectionInfo {
                    name: row.get(0)?,
                    path: row.get(1)?,
                    pattern: row.get(2)?,
                    created_at: row.get(3)?,
                    updated_at: row.get(4)?,
                    document_count: row.get::<_, i64>(5)? as usize,
                    provider_type: row.get(6)?,
                    provider_config: row.get(7)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(results)
    }

    /// Get collection by name
    pub fn get_collection(&self, name: &str) -> Result<Option<CollectionInfo>> {
        let result = self.conn.query_row(
            "SELECT c.name, c.path, c.pattern, c.created_at, c.updated_at,
                    (SELECT COUNT(*) FROM documents d WHERE d.collection = c.name AND d.active = 1),
                    c.provider_type, c.provider_config
             FROM collections c WHERE c.name = ?1",
            params![name],
            |row| {
                Ok(CollectionInfo {
                    name: row.get(0)?,
                    path: row.get(1)?,
                    pattern: row.get(2)?,
                    created_at: row.get(3)?,
                    updated_at: row.get(4)?,
                    document_count: row.get::<_, i64>(5)? as usize,
                    provider_type: row.get(6)?,
                    provider_config: row.get(7)?,
                })
            },
        );
        match result {
            Ok(info) => Ok(Some(info)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    /// Update collection's updated_at timestamp
    pub fn touch_collection(&self, name: &str) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        self.conn.execute(
            "UPDATE collections SET updated_at = ?2 WHERE name = ?1",
            params![name, now],
        )?;
        Ok(())
    }

    /// Reindex a collection using the provider system
    pub async fn reindex_collection(&self, name: &str) -> Result<usize> {
        let coll = self
            .get_collection(name)?
            .ok_or_else(|| crate::error::AgentRootError::CollectionNotFound(name.to_string()))?;

        let registry = crate::providers::ProviderRegistry::with_defaults();
        let provider = registry.get(&coll.provider_type).ok_or_else(|| {
            crate::error::AgentRootError::InvalidInput(format!(
                "Unknown provider type: {}",
                coll.provider_type
            ))
        })?;

        let mut config =
            crate::providers::ProviderConfig::new(coll.path.clone(), coll.pattern.clone());

        if let Some(provider_config) = &coll.provider_config {
            if let Ok(config_map) =
                serde_json::from_str::<std::collections::HashMap<String, String>>(provider_config)
            {
                for (key, value) in config_map {
                    config = config.with_option(key, value);
                }
            }
        }

        let items = provider.list_items(&config).await?;
        let mut updated = 0;

        for item in items {
            let now = Utc::now().to_rfc3339();

            if let Some(existing) = self.find_active_document(name, &item.uri)? {
                if existing.hash != item.hash {
                    self.insert_content(&item.hash, &item.content)?;
                    self.update_document(existing.id, &item.title, &item.hash, &now)?;
                    updated += 1;
                }
            } else {
                self.insert_content(&item.hash, &item.content)?;
                self.insert_document(
                    name,
                    &item.uri,
                    &item.title,
                    &item.hash,
                    &now,
                    &now,
                    &item.source_type,
                    item.metadata.get("source_uri").map(|s| s.as_str()),
                )?;
                updated += 1;
            }
        }

        self.touch_collection(name)?;
        Ok(updated)
    }

    /// Generate or fetch metadata from cache
    pub async fn generate_or_fetch_metadata(
        &self,
        content_hash: &str,
        content: &str,
        context: crate::llm::MetadataContext,
        generator: Option<&dyn crate::llm::MetadataGenerator>,
    ) -> Result<Option<crate::llm::DocumentMetadata>> {
        if generator.is_none() {
            return Ok(None);
        }

        let cache_key = format!("metadata:v1:{}", content_hash);

        if let Some(cached) = self.get_llm_cache(&cache_key)? {
            if let Ok(metadata) = serde_json::from_str::<crate::llm::DocumentMetadata>(&cached) {
                return Ok(Some(metadata));
            }
        }

        let gen = generator.unwrap();
        match gen.generate_metadata(content, &context).await {
            Ok(metadata) => {
                let cache_value = serde_json::to_string(&metadata)?;
                self.set_llm_cache(&cache_key, &cache_value, gen.model_name())?;
                Ok(Some(metadata))
            }
            Err(e) => {
                eprintln!("Metadata generation failed: {}. Skipping metadata.", e);
                Ok(None)
            }
        }
    }

    /// Get metadata from LLM cache (public API)
    pub fn get_llm_cache_public(&self, key: &str) -> Result<Option<String>> {
        self.get_llm_cache(key)
    }

    /// Get metadata from LLM cache
    fn get_llm_cache(&self, key: &str) -> Result<Option<String>> {
        let result = self.conn.query_row(
            "SELECT value FROM llm_cache WHERE key = ?1",
            params![key],
            |row| row.get(0),
        );

        match result {
            Ok(value) => Ok(Some(value)),
            Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    /// Set metadata in LLM cache
    fn set_llm_cache(&self, key: &str, value: &str, model: &str) -> Result<()> {
        let now = Utc::now().to_rfc3339();
        self.conn.execute(
            "INSERT OR REPLACE INTO llm_cache (key, value, model, created_at) VALUES (?1, ?2, ?3, ?4)",
            params![key, value, model, now],
        )?;
        Ok(())
    }

    /// Build metadata context from source item
    fn build_metadata_context(
        &self,
        item: &crate::providers::SourceItem,
        collection_name: &str,
        coll: &CollectionInfo,
    ) -> crate::llm::MetadataContext {
        let path = std::path::Path::new(&item.uri);
        let extension = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|s| s.to_string());

        crate::llm::MetadataContext::new(item.source_type.clone(), collection_name.to_string())
            .with_extension(extension.unwrap_or_default())
            .with_provider_config(coll.provider_config.clone().unwrap_or_default())
    }

    /// Insert document with metadata
    fn insert_document_with_metadata(
        &self,
        collection: &str,
        path: &str,
        title: &str,
        hash: &str,
        created_at: &str,
        modified_at: &str,
        source_type: &str,
        source_uri: Option<&str>,
        metadata: &crate::llm::DocumentMetadata,
        model_name: &str,
    ) -> Result<i64> {
        let keywords_json = serde_json::to_string(&metadata.keywords)?;
        let concepts_json = serde_json::to_string(&metadata.concepts)?;
        let queries_json = serde_json::to_string(&metadata.suggested_queries)?;
        let now = Utc::now().to_rfc3339();

        let doc = super::documents::DocumentInsert::new(
            collection,
            path,
            title,
            hash,
            created_at,
            modified_at,
        )
        .with_source_type(source_type)
        .with_source_uri(source_uri.unwrap_or(""))
        .with_llm_metadata_strings(
            &metadata.summary,
            &metadata.semantic_title,
            &keywords_json,
            &metadata.category,
            &metadata.intent,
            &concepts_json,
            &metadata.difficulty,
            &queries_json,
            model_name,
            &now,
        );

        self.insert_doc(&doc)
    }

    /// Update document with metadata
    fn update_document_with_metadata(
        &self,
        id: i64,
        title: &str,
        hash: &str,
        modified_at: &str,
        metadata: &crate::llm::DocumentMetadata,
        model_name: &str,
    ) -> Result<()> {
        let keywords_json = serde_json::to_string(&metadata.keywords)?;
        let concepts_json = serde_json::to_string(&metadata.concepts)?;
        let queries_json = serde_json::to_string(&metadata.suggested_queries)?;
        let now = Utc::now().to_rfc3339();

        self.conn.execute(
            "UPDATE documents 
             SET title = ?2, hash = ?3, modified_at = ?4,
                 llm_summary = ?5, llm_title = ?6, llm_keywords = ?7, llm_category = ?8,
                 llm_intent = ?9, llm_concepts = ?10, llm_difficulty = ?11, llm_queries = ?12,
                 llm_metadata_generated_at = ?13, llm_model = ?14
             WHERE id = ?1",
            params![
                id,
                title,
                hash,
                modified_at,
                metadata.summary,
                metadata.semantic_title,
                keywords_json,
                metadata.category,
                metadata.intent,
                concepts_json,
                metadata.difficulty,
                queries_json,
                now,
                model_name
            ],
        )?;
        Ok(())
    }

    /// Reindex all documents in a collection with optional metadata generation
    pub async fn reindex_collection_with_metadata(
        &self,
        name: &str,
        generator: Option<&dyn crate::llm::MetadataGenerator>,
    ) -> Result<usize> {
        let coll = self
            .get_collection(name)?
            .ok_or_else(|| crate::error::AgentRootError::CollectionNotFound(name.to_string()))?;

        let registry = crate::providers::ProviderRegistry::with_defaults();
        let provider = registry.get(&coll.provider_type).ok_or_else(|| {
            crate::error::AgentRootError::InvalidInput(format!(
                "Unknown provider type: {}",
                coll.provider_type
            ))
        })?;

        let mut config =
            crate::providers::ProviderConfig::new(coll.path.clone(), coll.pattern.clone());

        if let Some(provider_config) = &coll.provider_config {
            if let Ok(config_map) =
                serde_json::from_str::<std::collections::HashMap<String, String>>(provider_config)
            {
                for (key, value) in config_map {
                    config = config.with_option(key, value);
                }
            }
        }

        let items = provider.list_items(&config).await?;
        let mut updated = 0;

        for item in items {
            let now = Utc::now().to_rfc3339();

            if let Some(existing) = self.find_active_document(name, &item.uri)? {
                if existing.hash != item.hash {
                    self.insert_content(&item.hash, &item.content)?;

                    let metadata_opt = if generator.is_some() {
                        let context = self.build_metadata_context(&item, name, &coll);
                        self.generate_or_fetch_metadata(
                            &item.hash,
                            &item.content,
                            context,
                            generator,
                        )
                        .await?
                    } else {
                        None
                    };

                    if let Some(metadata) = metadata_opt {
                        self.update_document_with_metadata(
                            existing.id,
                            &item.title,
                            &item.hash,
                            &now,
                            &metadata,
                            generator.unwrap().model_name(),
                        )?;
                    } else {
                        self.update_document(existing.id, &item.title, &item.hash, &now)?;
                    }
                    updated += 1;
                }
            } else {
                self.insert_content(&item.hash, &item.content)?;

                let metadata_opt = if generator.is_some() {
                    let context = self.build_metadata_context(&item, name, &coll);
                    self.generate_or_fetch_metadata(&item.hash, &item.content, context, generator)
                        .await?
                } else {
                    None
                };

                if let Some(metadata) = metadata_opt {
                    self.insert_document_with_metadata(
                        name,
                        &item.uri,
                        &item.title,
                        &item.hash,
                        &now,
                        &now,
                        &item.source_type,
                        item.metadata.get("source_uri").map(|s| s.as_str()),
                        &metadata,
                        generator.unwrap().model_name(),
                    )?;
                } else {
                    self.insert_document(
                        name,
                        &item.uri,
                        &item.title,
                        &item.hash,
                        &now,
                        &now,
                        &item.source_type,
                        item.metadata.get("source_uri").map(|s| s.as_str()),
                    )?;
                }
                updated += 1;
            }
        }

        self.touch_collection(name)?;
        Ok(updated)
    }
}

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

    #[test]
    fn test_database_stores_provider_info_correctly() {
        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        db.add_collection(
            "test_file",
            "/tmp/test",
            "**/*.md",
            "file",
            Some(r#"{"exclude_hidden":"false"}"#),
        )
        .unwrap();

        db.add_collection(
            "test_github",
            "https://github.com/test/repo",
            "**/*.md",
            "github",
            None,
        )
        .unwrap();

        let provider_type_file: String = db
            .conn
            .query_row(
                "SELECT provider_type FROM collections WHERE name = 'test_file'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(provider_type_file, "file");

        let provider_config_file: Option<String> = db
            .conn
            .query_row(
                "SELECT provider_config FROM collections WHERE name = 'test_file'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            provider_config_file,
            Some(r#"{"exclude_hidden":"false"}"#.to_string())
        );

        let provider_type_github: String = db
            .conn
            .query_row(
                "SELECT provider_type FROM collections WHERE name = 'test_github'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(provider_type_github, "github");

        let provider_config_github: Option<String> = db
            .conn
            .query_row(
                "SELECT provider_config FROM collections WHERE name = 'test_github'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(provider_config_github, None);

        let collections = db.list_collections().unwrap();
        assert_eq!(collections.len(), 2);

        let file_coll = collections.iter().find(|c| c.name == "test_file").unwrap();
        assert_eq!(file_coll.provider_type, "file");
        assert_eq!(
            file_coll.provider_config.as_deref(),
            Some(r#"{"exclude_hidden":"false"}"#)
        );

        let github_coll = collections
            .iter()
            .find(|c| c.name == "test_github")
            .unwrap();
        assert_eq!(github_coll.provider_type, "github");
        assert_eq!(github_coll.provider_config, None);
    }

    #[test]
    fn test_documents_store_source_metadata() {
        use crate::db::hash_content;
        use chrono::Utc;

        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        db.add_collection("test", "/tmp", "**/*.md", "file", None)
            .unwrap();

        let content = "# Test Document";
        let hash = hash_content(content);
        db.insert_content(&hash, content).unwrap();

        let now = Utc::now().to_rfc3339();
        let doc_id = db
            .insert_document(
                "test",
                "doc1.md",
                "Test Document",
                &hash,
                &now,
                &now,
                "file",
                Some("/tmp/doc1.md"),
            )
            .unwrap();

        assert!(doc_id > 0);

        let source_type: String = db
            .conn
            .query_row(
                "SELECT source_type FROM documents WHERE id = ?1",
                [doc_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(source_type, "file");

        let source_uri: Option<String> = db
            .conn
            .query_row(
                "SELECT source_uri FROM documents WHERE id = ?1",
                [doc_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(source_uri, Some("/tmp/doc1.md".to_string()));

        db.insert_content(&hash, content).unwrap();
        let doc_id2 = db
            .insert_document(
                "test",
                "doc2.md",
                "Test Document 2",
                &hash,
                &now,
                &now,
                "github",
                Some("https://github.com/test/repo/doc2.md"),
            )
            .unwrap();

        let source_type2: String = db
            .conn
            .query_row(
                "SELECT source_type FROM documents WHERE id = ?1",
                [doc_id2],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(source_type2, "github");

        let source_uri2: Option<String> = db
            .conn
            .query_row(
                "SELECT source_uri FROM documents WHERE id = ?1",
                [doc_id2],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            source_uri2,
            Some("https://github.com/test/repo/doc2.md".to_string())
        );
    }

    #[tokio::test]
    async fn test_reindex_collection_uses_provider_system() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let base = temp.path();

        fs::write(base.join("doc1.md"), "# Document 1\nInitial content").unwrap();
        fs::write(base.join("doc2.md"), "# Document 2\nInitial content").unwrap();

        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        db.add_collection(
            "test",
            &base.to_string_lossy(),
            "**/*.md",
            "file",
            Some(r#"{"exclude_hidden":"false"}"#),
        )
        .unwrap();

        let updated = db.reindex_collection("test").await.unwrap();
        assert_eq!(updated, 2, "Should index 2 files on first run");

        let collections = db.list_collections().unwrap();
        assert_eq!(collections[0].document_count, 2);

        let doc_count: i64 = db
            .conn
            .query_row(
                "SELECT COUNT(*) FROM documents WHERE collection = 'test' AND active = 1",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(doc_count, 2);

        let mut stmt = db
            .conn
            .prepare(
                "SELECT path, source_type FROM documents WHERE collection = 'test' ORDER BY path",
            )
            .unwrap();
        let sources: Vec<(String, String)> = stmt
            .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
            .unwrap()
            .collect::<std::result::Result<Vec<_>, _>>()
            .unwrap();

        assert_eq!(sources.len(), 2);
        assert_eq!(sources[0].0, "doc1.md");
        assert_eq!(sources[0].1, "file");
        assert_eq!(sources[1].0, "doc2.md");
        assert_eq!(sources[1].1, "file");

        fs::write(base.join("doc1.md"), "# Document 1\nUpdated content").unwrap();

        let updated2 = db.reindex_collection("test").await.unwrap();
        assert_eq!(updated2, 1, "Should update only changed file");

        let collections2 = db.list_collections().unwrap();
        assert_eq!(
            collections2[0].document_count, 2,
            "Should still have 2 documents"
        );

        fs::write(base.join("doc3.md"), "# Document 3\nNew content").unwrap();

        let updated3 = db.reindex_collection("test").await.unwrap();
        assert_eq!(updated3, 1, "Should add new file");

        let collections3 = db.list_collections().unwrap();
        assert_eq!(
            collections3[0].document_count, 3,
            "Should now have 3 documents"
        );
    }

    #[tokio::test]
    async fn test_reindex_invalid_provider_type() {
        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        db.add_collection("test", "/tmp", "**/*.md", "nonexistent_provider", None)
            .unwrap();

        let result = db.reindex_collection("test").await;
        assert!(result.is_err(), "Should error on invalid provider type");

        match result {
            Err(crate::error::AgentRootError::InvalidInput(msg)) => {
                assert!(msg.contains("Unknown provider type"));
                assert!(msg.contains("nonexistent_provider"));
            }
            _ => panic!("Expected InvalidInput error"),
        }
    }

    #[tokio::test]
    async fn test_reindex_nonexistent_collection() {
        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        let result = db.reindex_collection("nonexistent").await;
        assert!(result.is_err(), "Should error on nonexistent collection");

        match result {
            Err(crate::error::AgentRootError::CollectionNotFound(name)) => {
                assert_eq!(name, "nonexistent");
            }
            _ => panic!("Expected CollectionNotFound error"),
        }
    }

    #[test]
    fn test_add_collection_duplicate_name() {
        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        db.add_collection("test", "/tmp1", "**/*.md", "file", None)
            .unwrap();

        let result = db.add_collection("test", "/tmp2", "**/*.md", "file", None);
        assert!(result.is_err(), "Should error on duplicate collection name");
    }

    #[tokio::test]
    async fn test_reindex_with_malformed_provider_config() {
        use std::fs;
        use tempfile::TempDir;

        let temp = TempDir::new().unwrap();
        let base = temp.path();
        fs::write(base.join("test.md"), "# Test").unwrap();

        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();

        db.add_collection(
            "test",
            &base.to_string_lossy(),
            "**/*.md",
            "file",
            Some("malformed json that won't parse"),
        )
        .unwrap();

        let result = db.reindex_collection("test").await;
        assert!(
            result.is_ok(),
            "Should succeed despite malformed JSON config (uses defaults)"
        );
    }
}