agentroot-core 0.1.0

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
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
//! Database schema and initialization

use crate::error::Result;
use rusqlite::{params, Connection};
use std::path::Path;

/// Main database handle
pub struct Database {
    pub(crate) conn: Connection,
}

const SCHEMA_VERSION: i32 = 6;

const CREATE_TABLES: &str = r#"
-- Content storage (content-addressable by SHA-256 hash)
CREATE TABLE IF NOT EXISTS content (
    hash TEXT PRIMARY KEY,
    doc TEXT NOT NULL,
    created_at TEXT NOT NULL
);

-- Document metadata
CREATE TABLE IF NOT EXISTS documents (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    collection TEXT NOT NULL,
    path TEXT NOT NULL,
    title TEXT NOT NULL,
    hash TEXT NOT NULL REFERENCES content(hash),
    created_at TEXT NOT NULL,
    modified_at TEXT NOT NULL,
    active INTEGER NOT NULL DEFAULT 1,
    source_type TEXT NOT NULL DEFAULT 'file',
    source_uri TEXT,
    llm_summary TEXT,
    llm_title TEXT,
    llm_keywords TEXT,
    llm_category TEXT,
    llm_intent TEXT,
    llm_concepts TEXT,
    llm_difficulty TEXT,
    llm_queries TEXT,
    llm_metadata_generated_at TEXT,
    llm_model TEXT,
    user_metadata TEXT,
    UNIQUE(collection, path)
);

-- Full-text search index
CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(
    filepath,
    title,
    body,
    llm_summary,
    llm_title,
    llm_keywords,
    llm_intent,
    llm_concepts,
    user_metadata,
    modified_at,
    tokenize='porter unicode61'
);

-- Vector embeddings metadata
CREATE TABLE IF NOT EXISTS content_vectors (
    hash TEXT NOT NULL,
    seq INTEGER NOT NULL,
    pos INTEGER NOT NULL,
    model TEXT NOT NULL,
    chunk_hash TEXT,
    created_at TEXT NOT NULL,
    PRIMARY KEY (hash, seq)
);

-- Model metadata for dimension validation
CREATE TABLE IF NOT EXISTS model_metadata (
    model TEXT PRIMARY KEY,
    dimensions INTEGER NOT NULL,
    created_at TEXT NOT NULL,
    last_used_at TEXT NOT NULL
);

-- Global chunk embeddings cache
CREATE TABLE IF NOT EXISTS chunk_embeddings (
    chunk_hash TEXT NOT NULL,
    model TEXT NOT NULL,
    embedding BLOB NOT NULL,
    created_at TEXT NOT NULL,
    PRIMARY KEY (chunk_hash, model)
);

-- LLM response cache
CREATE TABLE IF NOT EXISTS llm_cache (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL,
    model TEXT NOT NULL,
    created_at TEXT NOT NULL
);

-- Collections metadata
CREATE TABLE IF NOT EXISTS collections (
    name TEXT PRIMARY KEY,
    path TEXT NOT NULL,
    pattern TEXT NOT NULL DEFAULT '**/*.md',
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    provider_type TEXT NOT NULL DEFAULT 'file',
    provider_config TEXT
);

-- Context metadata (hierarchical context for paths)
CREATE TABLE IF NOT EXISTS contexts (
    path TEXT PRIMARY KEY,
    context TEXT NOT NULL,
    created_at TEXT NOT NULL
);

-- Schema version tracking
CREATE TABLE IF NOT EXISTS schema_version (
    version INTEGER PRIMARY KEY
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_documents_collection ON documents(collection);
CREATE INDEX IF NOT EXISTS idx_documents_hash ON documents(hash);
CREATE INDEX IF NOT EXISTS idx_documents_active ON documents(active);
CREATE INDEX IF NOT EXISTS idx_content_vectors_hash ON content_vectors(hash);
CREATE INDEX IF NOT EXISTS idx_content_vectors_chunk_hash ON content_vectors(chunk_hash);
CREATE INDEX IF NOT EXISTS idx_chunk_embeddings_hash ON chunk_embeddings(chunk_hash);
"#;

const CREATE_TRIGGERS: &str = r#"
-- Sync FTS on insert (only for active documents)
CREATE TRIGGER IF NOT EXISTS documents_ai
AFTER INSERT ON documents
WHEN new.active = 1
BEGIN
    INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts, user_metadata, modified_at)
    SELECT
        new.id,
        new.collection || '/' || new.path,
        new.title,
        (SELECT doc FROM content WHERE hash = new.hash),
        new.llm_summary,
        new.llm_title,
        new.llm_keywords,
        new.llm_intent,
        new.llm_concepts,
        new.user_metadata,
        new.modified_at;
END;

-- Sync FTS on update: handle activation/deactivation/content change
CREATE TRIGGER IF NOT EXISTS documents_au
AFTER UPDATE ON documents
BEGIN
    DELETE FROM documents_fts WHERE rowid = old.id;
    INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts, user_metadata, modified_at)
    SELECT
        new.id,
        new.collection || '/' || new.path,
        new.title,
        (SELECT doc FROM content WHERE hash = new.hash),
        new.llm_summary,
        new.llm_title,
        new.llm_keywords,
        new.llm_intent,
        new.llm_concepts,
        new.user_metadata,
        new.modified_at
    WHERE new.active = 1;
END;

-- Sync FTS on delete
CREATE TRIGGER IF NOT EXISTS documents_ad
AFTER DELETE ON documents
BEGIN
    DELETE FROM documents_fts WHERE rowid = old.id;
END;
"#;

impl Database {
    /// Open database at path, creating if necessary
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let conn = Connection::open(path)?;
        Ok(Self { conn })
    }

    /// Open in-memory database (for testing)
    pub fn open_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        Ok(Self { conn })
    }

    /// Initialize database schema
    pub fn initialize(&self) -> Result<()> {
        // Set PRAGMAs for performance
        self.conn.execute_batch(
            "PRAGMA journal_mode = WAL;
             PRAGMA synchronous = NORMAL;
             PRAGMA foreign_keys = ON;
             PRAGMA cache_size = -64000;
             PRAGMA busy_timeout = 5000;",
        )?;

        // Create tables
        self.conn.execute_batch(CREATE_TABLES)?;

        // Create triggers
        self.conn.execute_batch(CREATE_TRIGGERS)?;

        // Run migrations to upgrade existing databases (BEFORE setting version)
        self.migrate()?;

        // Set schema version (after migrations complete)
        self.conn.execute(
            "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
            params![SCHEMA_VERSION],
        )?;

        Ok(())
    }

    /// Get current schema version
    pub fn schema_version(&self) -> Result<Option<i32>> {
        let version = self
            .conn
            .query_row(
                "SELECT version FROM schema_version ORDER BY version DESC LIMIT 1",
                [],
                |row| row.get(0),
            )
            .ok();
        Ok(version)
    }

    /// Run migrations to upgrade schema to current version
    pub fn migrate(&self) -> Result<()> {
        let current = self.schema_version()?.unwrap_or(0);

        if current < 2 {
            self.migrate_to_v2()?;
        }

        if current < 3 {
            self.migrate_to_v3()?;
        }

        if current < 4 {
            self.migrate_to_v4()?;
        }

        if current < 5 {
            self.migrate_to_v5()?;
        }

        if current < 6 {
            self.migrate_to_v6()?;
        }

        Ok(())
    }

    fn migrate_to_v2(&self) -> Result<()> {
        // Add chunk_hash column to content_vectors if not exists
        let has_chunk_hash: bool = self.conn.query_row(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('content_vectors') WHERE name = 'chunk_hash'",
            [],
            |row| row.get(0),
        ).unwrap_or(false);

        if !has_chunk_hash {
            self.conn
                .execute("ALTER TABLE content_vectors ADD COLUMN chunk_hash TEXT", [])?;
            self.conn.execute(
                "CREATE INDEX IF NOT EXISTS idx_content_vectors_chunk_hash ON content_vectors(chunk_hash)",
                [],
            )?;
        }

        // Create model_metadata table
        self.conn.execute(
            "CREATE TABLE IF NOT EXISTS model_metadata (
                model TEXT PRIMARY KEY,
                dimensions INTEGER NOT NULL,
                created_at TEXT NOT NULL,
                last_used_at TEXT NOT NULL
            )",
            [],
        )?;

        // Create chunk_embeddings cache table
        self.conn.execute(
            "CREATE TABLE IF NOT EXISTS chunk_embeddings (
                chunk_hash TEXT NOT NULL,
                model TEXT NOT NULL,
                embedding BLOB NOT NULL,
                created_at TEXT NOT NULL,
                PRIMARY KEY (chunk_hash, model)
            )",
            [],
        )?;
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_chunk_embeddings_hash ON chunk_embeddings(chunk_hash)",
            [],
        )?;

        // Update schema version
        self.conn.execute(
            "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
            params![2],
        )?;

        Ok(())
    }

    fn migrate_to_v3(&self) -> Result<()> {
        // Add source_type column to documents if not exists
        let has_source_type: bool = self
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = 'source_type'",
                [],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if !has_source_type {
            self.conn.execute(
                "ALTER TABLE documents ADD COLUMN source_type TEXT NOT NULL DEFAULT 'file'",
                [],
            )?;
        }

        // Add source_uri column to documents if not exists
        let has_source_uri: bool = self
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = 'source_uri'",
                [],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if !has_source_uri {
            self.conn
                .execute("ALTER TABLE documents ADD COLUMN source_uri TEXT", [])?;
        }

        // Add provider_type column to collections if not exists
        let has_provider_type: bool = self
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('collections') WHERE name = 'provider_type'",
                [],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if !has_provider_type {
            self.conn.execute(
                "ALTER TABLE collections ADD COLUMN provider_type TEXT NOT NULL DEFAULT 'file'",
                [],
            )?;
        }

        // Add provider_config column to collections if not exists
        let has_provider_config: bool = self
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('collections') WHERE name = 'provider_config'",
                [],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if !has_provider_config {
            self.conn.execute(
                "ALTER TABLE collections ADD COLUMN provider_config TEXT",
                [],
            )?;
        }

        // Update schema version
        self.conn.execute(
            "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
            params![3],
        )?;

        Ok(())
    }

    fn migrate_to_v4(&self) -> Result<()> {
        // Add LLM metadata columns to documents table
        let columns_to_add = vec![
            "llm_summary",
            "llm_title",
            "llm_keywords",
            "llm_category",
            "llm_intent",
            "llm_concepts",
            "llm_difficulty",
            "llm_queries",
            "llm_metadata_generated_at",
            "llm_model",
        ];

        for column in columns_to_add {
            let has_column: bool = self
                .conn
                .query_row(
                    "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = ?1",
                    params![column],
                    |row| row.get(0),
                )
                .unwrap_or(false);

            if !has_column {
                self.conn.execute(
                    &format!("ALTER TABLE documents ADD COLUMN {} TEXT", column),
                    [],
                )?;
            }
        }

        // Rebuild FTS index to include metadata columns
        // Drop and recreate is the safest approach for FTS5
        self.conn
            .execute("DROP TABLE IF EXISTS documents_fts", [])?;
        self.conn.execute(
            "CREATE VIRTUAL TABLE documents_fts USING fts5(
                filepath,
                title,
                body,
                llm_summary,
                llm_title,
                llm_keywords,
                llm_intent,
                llm_concepts,
                tokenize='porter unicode61'
            )",
            [],
        )?;

        // Rebuild FTS data from existing documents
        self.conn.execute(
            "INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts)
             SELECT
                d.id,
                d.collection || '/' || d.path,
                d.title,
                c.doc,
                d.llm_summary,
                d.llm_title,
                d.llm_keywords,
                d.llm_intent,
                d.llm_concepts
             FROM documents d
             JOIN content c ON c.hash = d.hash
             WHERE d.active = 1",
            [],
        )?;

        // Recreate triggers with metadata support
        self.conn
            .execute("DROP TRIGGER IF EXISTS documents_ai", [])?;
        self.conn
            .execute("DROP TRIGGER IF EXISTS documents_au", [])?;
        self.conn
            .execute("DROP TRIGGER IF EXISTS documents_ad", [])?;

        self.conn.execute(
            "CREATE TRIGGER documents_ai
             AFTER INSERT ON documents
             WHEN new.active = 1
             BEGIN
                 INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts)
                 SELECT
                     new.id,
                     new.collection || '/' || new.path,
                     new.title,
                     (SELECT doc FROM content WHERE hash = new.hash),
                     new.llm_summary,
                     new.llm_title,
                     new.llm_keywords,
                     new.llm_intent,
                     new.llm_concepts;
             END",
            [],
        )?;

        self.conn.execute(
            "CREATE TRIGGER documents_au
             AFTER UPDATE ON documents
             BEGIN
                 DELETE FROM documents_fts WHERE rowid = old.id;
                 INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts)
                 SELECT
                     new.id,
                     new.collection || '/' || new.path,
                     new.title,
                     (SELECT doc FROM content WHERE hash = new.hash),
                     new.llm_summary,
                     new.llm_title,
                     new.llm_keywords,
                     new.llm_intent,
                     new.llm_concepts
                 WHERE new.active = 1;
             END",
            [],
        )?;

        self.conn.execute(
            "CREATE TRIGGER documents_ad
             AFTER DELETE ON documents
             BEGIN
                 DELETE FROM documents_fts WHERE rowid = old.id;
             END",
            [],
        )?;

        // Update schema version
        self.conn.execute(
            "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
            params![4],
        )?;

        Ok(())
    }

    fn migrate_to_v5(&self) -> Result<()> {
        // Add user_metadata column to documents table
        let has_user_metadata: bool = self
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = 'user_metadata'",
                [],
                |row| row.get(0),
            )
            .unwrap_or(false);

        if !has_user_metadata {
            self.conn
                .execute("ALTER TABLE documents ADD COLUMN user_metadata TEXT", [])?;
        }

        // Create index on user_metadata for efficient queries
        self.conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_documents_user_metadata ON documents(user_metadata)",
            [],
        )?;

        // Update schema version
        self.conn.execute(
            "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
            params![5],
        )?;

        Ok(())
    }

    fn migrate_to_v6(&self) -> Result<()> {
        // Rebuild FTS index to include user_metadata and modified_at
        // This makes user metadata and timestamps full-text searchable

        // Drop and recreate FTS table with new columns
        self.conn
            .execute("DROP TABLE IF EXISTS documents_fts", [])?;

        self.conn.execute(
            "CREATE VIRTUAL TABLE documents_fts USING fts5(
                filepath,
                title,
                body,
                llm_summary,
                llm_title,
                llm_keywords,
                llm_intent,
                llm_concepts,
                user_metadata,
                modified_at,
                tokenize='porter unicode61'
            )",
            [],
        )?;

        // Rebuild FTS data from existing documents
        self.conn.execute(
            "INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts, user_metadata, modified_at)
             SELECT
                d.id,
                d.collection || '/' || d.path,
                d.title,
                c.doc,
                d.llm_summary,
                d.llm_title,
                d.llm_keywords,
                d.llm_intent,
                d.llm_concepts,
                d.user_metadata,
                d.modified_at
             FROM documents d
             JOIN content c ON c.hash = d.hash
             WHERE d.active = 1",
            [],
        )?;

        // Recreate triggers with user_metadata and modified_at support
        self.conn
            .execute("DROP TRIGGER IF EXISTS documents_ai", [])?;
        self.conn
            .execute("DROP TRIGGER IF EXISTS documents_au", [])?;
        self.conn
            .execute("DROP TRIGGER IF EXISTS documents_ad", [])?;

        self.conn.execute(
            "CREATE TRIGGER documents_ai
             AFTER INSERT ON documents
             WHEN new.active = 1
             BEGIN
                 INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts, user_metadata, modified_at)
                 SELECT
                     new.id,
                     new.collection || '/' || new.path,
                     new.title,
                     (SELECT doc FROM content WHERE hash = new.hash),
                     new.llm_summary,
                     new.llm_title,
                     new.llm_keywords,
                     new.llm_intent,
                     new.llm_concepts,
                     new.user_metadata,
                     new.modified_at;
             END",
            [],
        )?;

        self.conn.execute(
            "CREATE TRIGGER documents_au
             AFTER UPDATE ON documents
             BEGIN
                 DELETE FROM documents_fts WHERE rowid = old.id;
                 INSERT INTO documents_fts(rowid, filepath, title, body, llm_summary, llm_title, llm_keywords, llm_intent, llm_concepts, user_metadata, modified_at)
                 SELECT
                     new.id,
                     new.collection || '/' || new.path,
                     new.title,
                     (SELECT doc FROM content WHERE hash = new.hash),
                     new.llm_summary,
                     new.llm_title,
                     new.llm_keywords,
                     new.llm_intent,
                     new.llm_concepts,
                     new.user_metadata,
                     new.modified_at
                 WHERE new.active = 1;
             END",
            [],
        )?;

        self.conn.execute(
            "CREATE TRIGGER documents_ad
             AFTER DELETE ON documents
             BEGIN
                 DELETE FROM documents_fts WHERE rowid = old.id;
             END",
            [],
        )?;

        // Update schema version
        self.conn.execute(
            "INSERT OR REPLACE INTO schema_version (version) VALUES (?1)",
            params![6],
        )?;

        Ok(())
    }
}

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

    #[test]
    fn test_open_in_memory() {
        let db = Database::open_in_memory().unwrap();
        db.initialize().unwrap();
        assert_eq!(db.schema_version().unwrap(), Some(SCHEMA_VERSION));
    }

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

        db.conn
            .execute_batch(
                "CREATE TABLE collections (
                name TEXT PRIMARY KEY,
                path TEXT NOT NULL,
                pattern TEXT NOT NULL DEFAULT '**/*.md',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL
            );
            CREATE TABLE documents (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                collection TEXT NOT NULL,
                path TEXT NOT NULL,
                title TEXT NOT NULL,
                hash TEXT NOT NULL,
                created_at TEXT NOT NULL,
                modified_at TEXT NOT NULL,
                active INTEGER NOT NULL DEFAULT 1,
                UNIQUE(collection, path)
            );
            CREATE TABLE schema_version (version INTEGER PRIMARY KEY);
            INSERT INTO schema_version VALUES (2);",
            )
            .unwrap();

        assert_eq!(db.schema_version().unwrap(), Some(2));

        db.initialize().unwrap();

        assert_eq!(db.schema_version().unwrap(), Some(6));

        let has_provider_type: bool = db.conn.query_row(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('collections') WHERE name = 'provider_type'",
            [],
            |row| row.get(0),
        ).unwrap();
        assert!(
            has_provider_type,
            "collections should have provider_type column"
        );

        let has_provider_config: bool = db.conn.query_row(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('collections') WHERE name = 'provider_config'",
            [],
            |row| row.get(0),
        ).unwrap();
        assert!(
            has_provider_config,
            "collections should have provider_config column"
        );

        let has_source_type: bool = db.conn.query_row(
            "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = 'source_type'",
            [],
            |row| row.get(0),
        ).unwrap();
        assert!(has_source_type, "documents should have source_type column");

        let has_source_uri: bool = db
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = 'source_uri'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert!(has_source_uri, "documents should have source_uri column");
    }

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

        db.conn
            .execute_batch(
                "CREATE TABLE collections (
                name TEXT PRIMARY KEY,
                path TEXT NOT NULL,
                pattern TEXT NOT NULL DEFAULT '**/*.md',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                provider_type TEXT NOT NULL DEFAULT 'file',
                provider_config TEXT
            );
            CREATE TABLE documents (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                collection TEXT NOT NULL,
                path TEXT NOT NULL,
                title TEXT NOT NULL,
                hash TEXT NOT NULL,
                created_at TEXT NOT NULL,
                modified_at TEXT NOT NULL,
                active INTEGER NOT NULL DEFAULT 1,
                source_type TEXT NOT NULL DEFAULT 'file',
                source_uri TEXT,
                UNIQUE(collection, path)
            );
            CREATE TABLE schema_version (version INTEGER PRIMARY KEY);
            INSERT INTO schema_version VALUES (3);",
            )
            .unwrap();

        assert_eq!(db.schema_version().unwrap(), Some(3));

        db.initialize().unwrap();

        assert_eq!(db.schema_version().unwrap(), Some(6));

        let metadata_columns = vec![
            "llm_summary",
            "llm_title",
            "llm_keywords",
            "llm_category",
            "llm_intent",
            "llm_concepts",
            "llm_difficulty",
            "llm_queries",
            "llm_metadata_generated_at",
            "llm_model",
        ];

        for column in metadata_columns {
            let has_column: bool = db
                .conn
                .query_row(
                    "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = ?1",
                    params![column],
                    |row| row.get(0),
                )
                .unwrap();
            assert!(has_column, "documents should have {} column", column);
        }
    }

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

        db.conn
            .execute_batch(
                "CREATE TABLE collections (
                name TEXT PRIMARY KEY,
                path TEXT NOT NULL,
                pattern TEXT NOT NULL DEFAULT '**/*.md',
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                provider_type TEXT NOT NULL DEFAULT 'file',
                provider_config TEXT
            );
            CREATE TABLE documents (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                collection TEXT NOT NULL,
                path TEXT NOT NULL,
                title TEXT NOT NULL,
                hash TEXT NOT NULL,
                created_at TEXT NOT NULL,
                modified_at TEXT NOT NULL,
                active INTEGER NOT NULL DEFAULT 1,
                source_type TEXT NOT NULL DEFAULT 'file',
                source_uri TEXT,
                llm_summary TEXT,
                llm_title TEXT,
                llm_keywords TEXT,
                llm_category TEXT,
                llm_intent TEXT,
                llm_concepts TEXT,
                llm_difficulty TEXT,
                llm_queries TEXT,
                llm_metadata_generated_at TEXT,
                llm_model TEXT,
                UNIQUE(collection, path)
            );
            CREATE TABLE content (
                hash TEXT PRIMARY KEY,
                doc TEXT NOT NULL,
                created_at TEXT NOT NULL
            );
            CREATE VIRTUAL TABLE documents_fts USING fts5(
                filepath,
                title,
                body,
                llm_summary,
                llm_title,
                llm_keywords,
                llm_intent,
                llm_concepts,
                tokenize='porter unicode61'
            );
            CREATE TABLE schema_version (version INTEGER PRIMARY KEY);
            INSERT INTO schema_version VALUES (4);",
            )
            .unwrap();

        assert_eq!(db.schema_version().unwrap(), Some(4));

        db.initialize().unwrap();

        assert_eq!(db.schema_version().unwrap(), Some(6));

        let has_user_metadata: bool = db
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM pragma_table_info('documents') WHERE name = 'user_metadata'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert!(
            has_user_metadata,
            "documents should have user_metadata column"
        );

        let has_index: bool = db
            .conn
            .query_row(
                "SELECT COUNT(*) > 0 FROM sqlite_master WHERE type = 'index' AND name = 'idx_documents_user_metadata'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert!(has_index, "user_metadata should have index");
    }
}